{"repo": "CalebBell/fluids", "n_pairs": 200, "version": "v2_function_scoped", "contexts": {"tests/test_units.py::376": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/units.py"], "used_names": ["TANK", "u"], "enclosing_function": "test_Tank_units_full", "extracted_code": "# Source: fluids/units.py\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 3436}, "tests/test_units.py::429": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/units.py"], "used_names": ["ATMOSPHERE_1976", "copy", "u"], "enclosing_function": "test_ATMOSPHERE_1976_units", "extracted_code": "# Source: fluids/units.py\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 3436}, "tests/test_piping.py::191": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/piping.py"], "used_names": ["schedule_lookup"], "enclosing_function": "test_piping_schedule_basics", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_piping.py::187": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/piping.py"], "used_names": ["schedule_lookup"], "enclosing_function": "test_piping_schedule_basics", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_piping.py::189": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/piping.py"], "used_names": ["schedule_lookup"], "enclosing_function": "test_piping_schedule_basics", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_safety_valve.py::128": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/numerics/__init__.py", "fluids/safety_valve.py"], "used_names": ["API520_SH", "_KSH_K_10E", "_KSH_Pa_10E", "_KSH_Pa_7E", "_KSH_tempKs_7E", "assert_close", "linspace", "pytest"], "enclosing_function": "test_API520_SH", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):\n \"\"\"Port of numpy's linspace to pure python.\n\n Does not support dtype, and returns lists of floats.\n \"\"\"\n num = int(num)\n start = start * 1.\n stop = stop * 1.\n\n if num <= 0:\n return []\n if endpoint:\n if num == 1:\n return [start]\n step = (stop-start)/float(num-1)\n if num == 1:\n step = nan\n\n y = [start]\n for _ in range(num-2):\n y.append(y[-1] + step)\n y.append(stop)\n else:\n step = (stop-start)/float(num)\n if num == 1:\n step = nan\n y = [start]\n for _ in range(num-1):\n y.append(y[-1] + step)\n\n if retstep:\n return y, step\n else:\n return y\n\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/safety_valve.py\ndef API520_SH(T1, P1, edition=TENTH_EDITION):\n r\"\"\"Calculates correction due to steam superheat for steam flow for use in\n API 520 relief valve sizing. 2D interpolation among a table with 28\n pressures and 10 temperatures is performed.\n\n\n Parameters\n ----------\n T1 : float\n Temperature of the fluid entering the valve [K]\n P1 : float\n Upstream relieving pressure; the set pressure plus the allowable\n overpressure, plus atmospheric pressure, [Pa]\n edition : str, optional\n One of '10E', '7E', [-]\n\n Returns\n -------\n KSH : float\n Correction due to steam superheat [-]\n\n Notes\n -----\n For P above 20679 kPag, use the critical flow model.\n Superheat cannot be above 649 degrees Celsius.\n If T1 is above 149 degrees Celsius, returns 1.\n\n Examples\n --------\n Custom example from table 9, 7th edition:\n\n >>> API520_SH(593+273.15, 1066.325E3, '7E')\n 0.7201800000\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n if T1 > 922.15:\n raise ValueError(\"Superheat cannot be above 649 degrees Celcius\")\n if edition == SEVENTH_EDITION:\n if P1 > 20780325.0: # 20679E3+atm\n raise ValueError(\"For P above 20679 kPag, use the gas flow model\")\n if T1 < 422.15:\n return 1. # No superheat under 15 psig\n return float(bisplev(T1, P1, API520_KSH_tck_7E))\n elif edition == TENTH_EDITION:\n if T1 < 478.15:\n # Avoid extrapolating above 1.0\n return 1.0\n if P1 > 22063223.338138755:\n raise ValueError(\"For P1 above 22.06 MPa, use the gas flow model\")\n return float(bisplev(T1, P1, API520_KSH_tck_10E))\n else:\n raise ValueError(\"Acceptable editions are '7E', '10E'\")", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 3249}, "tests/test_nrlmsise00_full.py::43": {"resolved_imports": ["fluids/atmosphere.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close1d"], "enclosing_function": "helper_test_match", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 275}, "tests/test_nrlmsise00_full.py::45": {"resolved_imports": ["fluids/atmosphere.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close1d"], "enclosing_function": "helper_test_match", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 275}, "tests/test_numerics_polynomial_evaluation.py::307": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/polynomial_evaluation.py", "fluids/numerics/polynomial_utils.py"], "used_names": ["assert_close", "exp_horner_stable_ln_tau", "exp_horner_stable_ln_tau_and_der", "exp_horner_stable_ln_tau_and_der2", "log", "polynomial_offset_scale"], "enclosing_function": "test_exp_stablepoly_fit_ln_tau", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/numerics/polynomial_evaluation.py\ndef exp_horner_stable_ln_tau(T, Tc, coeffs, offset, scale):\n if T >= Tc:\n return 0.0\n lntau = log(1.0 - T/Tc)\n return trunc_exp(horner_stable(lntau, coeffs, offset, scale))\n\ndef exp_horner_stable_ln_tau_and_der(T, Tc, coeffs, offset, scale):\n if T >= Tc:\n return 0.0, 0.0\n tau = 1.0 - T/Tc\n lntau = log(tau)\n poly_val, poly_der_val = horner_stable_and_der(lntau, coeffs, offset, scale)\n val = trunc_exp(poly_val)\n return val, -val*poly_der_val/(Tc*tau)\n\ndef exp_horner_stable_ln_tau_and_der2(T, Tc, coeffs, offset, scale):\n if T >= Tc:\n return 0.0, 0.0, 0.0\n tau = 1.0 - T/Tc\n lntau = log(tau)\n poly_val, poly_val_der, poly_val_der2 = horner_stable_and_der2(lntau, coeffs, offset, scale)\n val = trunc_exp(poly_val)\n der = -val*poly_val_der/(Tc*tau)\n der2 = (poly_val_der*poly_val_der - poly_val_der + poly_val_der2)*val/(Tc*Tc*(tau*tau))\n\n return val, der, der2\n\n\n# Source: fluids/numerics/polynomial_utils.py\ndef polynomial_offset_scale(xmin, xmax):\n range_inv = 1.0/(xmax - xmin)\n offset = (-xmax - xmin)*range_inv\n scale = 2.0*range_inv\n return offset, scale", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 1806}, "tests/test_numerics_arrays.py::1554": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/arrays.py"], "used_names": ["gelsd", "pytest"], "enclosing_function": "test_gelsd_empty_and_shapes", "extracted_code": "# Source: fluids/numerics/arrays.py\ndef gelsd(a, b, rcond=None):\n \"\"\"Solve a linear least-squares problem using SVD (Singular Value Decomposition).\n This is a simplified implementation that uses numpy's SVD internally.\n\n The function solves the equation arg min(|b - Ax|) for x, where A is\n an M x N matrix and b is a length M vector.\n\n Parameters\n ----------\n a : list[list[float]]\n Input matrix A of shape (M, N)\n b : list[float]\n Input vector b of length M\n rcond : float, optional\n Cutoff ratio for small singular values. Singular values smaller\n than rcond * largest_singular_value are considered zero.\n Default: max(M,N) * eps where eps is the machine precision\n\n Returns\n -------\n x : list[float]\n Solution vector of length N\n residuals : float\n Sum of squared residuals of the solution. Only computed for overdetermined\n systems (M > N)\n rank : int\n Effective rank of matrix A\n s : list[float]\n Singular values of A in descending order\n\n Notes\n -----\n The implementation uses numpy.linalg.svd for the core computation but\n maintains a pure Python interface for input and output.\n \"\"\"\n # Get dimensions and handle empty cases\n m = len(a)\n n = len(a[0]) if m > 0 else 0\n\n if m == 0:\n if n == 0:\n return [], 0.0, 0, [] # Empty matrix\n return [0.0] * n, 0.0, 0, [] # Empty rows\n elif n == 0:\n return [], 0.0, 0, [] # Empty columns\n\n # Check compatibility\n if len(b) != m:\n raise ValueError(f\"Incompatible dimensions: A is {m}x{n}, b has length {len(b)}\")\n\n U, s, Vt = svd(a)\n\n # Set default rcond\n if rcond is None:\n rcond = max(m, n) * 2.2e-16 # Approximate machine epsilon for float64\n\n # Determine rank using rcond\n tol = rcond * s[0]\n rank = sum(sv > tol for sv in s)\n\n # Handle zero matrix case (all singular values below threshold)\n if rank == 0:\n return [0.0] * n, sum(bi * bi for bi in b), 0, s\n\n # We only need the first rank columns of U and V\n # If U is economy sized (Mxmin(M,N)), this is fine\n # If U is full sized (MxM), we still only use first rank columns\n Ut = transpose(U)\n Utb = matrix_vector_dot(Ut[:rank], b)\n\n # Apply 1/singular values with truncation\n s_inv_Utb = [Utb[i] / s[i] for i in range(rank)]\n\n # Get the first rank rows of V (transpose of first rank columns of Vt)\n # Again, works with both economy and full-size Vt\n V = transpose(Vt[:rank])\n x = matrix_vector_dot(V, s_inv_Utb)\n\n # Compute residuals for overdetermined systems\n residuals = 0.0\n if m > n and rank == n:\n # Compute Ax\n Ax = matrix_vector_dot(a, x)\n\n # Compute residuals as |b - Ax|^2\n diff = [b[i] - Ax[i] for i in range(m)]\n residuals = dot_product(diff, diff)\n return x, residuals, rank, s", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 2905}, "tests/test_numerics_arrays.py::1861": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/arrays.py"], "used_names": ["assert_close2d", "matrix_multiply", "pytest"], "enclosing_function": "test_matrix_multiply", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close2d(a, b, rtol=1e-7, atol=0.0):\n# N = len(a)\n# if N != len(b):\n# raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n# for i in range(N):\n# assert_close1d(a[i], b[i], rtol=rtol, atol=atol)\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n if not __debug__:\n # Do not run these branches in -O, -OO mode\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n for i in range(N):\n a0, b0 = a[i], b[i]\n N0 = len(a0)\n if N0 != len(b0):\n raise ValueError(f\"Variables are not the same length: {N0}, {len(b0)}\")\n for j in range(N0):\n# assert_close(a0[j], b0[j], rtol=rtol, atol=atol)\n good = True\n a1, b1 = a0[j], b0[j]\n if a1 is b1:\n # Nice to handle None\n pass\n else:\n try:\n try:\n good = isclose(a1, b1, rel_tol=rtol, abs_tol=atol)\n except:\n good = cisclose(a1, b1, rel_tol=rtol, abs_tol=atol)\n except:\n pass\n if not good:\n from numpy.testing import assert_allclose\n return assert_allclose(a1, b1, rtol=rtol, atol=atol)\n\n\n# Source: fluids/numerics/arrays.py\ndef matrix_multiply(A, B):\n r\"\"\"Multiply two matrices using pure Python.\n\n Computes the matrix product C = A·B where A is an mxp matrix and B is a pxn matrix,\n resulting in an mxn matrix C.\n\n Parameters\n ----------\n A : list[list[float]]\n First matrix as list of lists, with shape (m, p)\n B : list[list[float]]\n Second matrix as list of lists, with shape (p, n)\n\n Returns\n -------\n list[list[float]]\n Resulting matrix C with shape (m, n)\n\n Examples\n --------\n >>> A = [[1, 2], [3, 4]]\n >>> B = [[5, 6], [7, 8]]\n >>> matrix_multiply(A, B)\n [[19.0, 22.0], [43.0, 50.0]]\n\n Notes\n -----\n Uses a straightforward three-loop implementation optimized for pure Python:\n C[i,j] = sum(A[i,k] * B[k,j] for k in range(p))\n\n The implementation avoids repeated len() calls and list accesses by caching\n frequently used values.\n\n Raises\n ------\n ValueError\n If matrices have incompatible dimensions for multiplication\n If input matrices are empty or irregular (rows of different lengths)\n TypeError\n If A or B contains non-numeric values or is not a list of lists.\n \"\"\"\n # Input validation\n if not A or not A[0] or not B or not B[0]:\n raise ValueError(\"Empty matrices cannot be multiplied\")\n\n # Get dimensions\n m = len(A) # rows in A\n p = len(A[0]) if m else 0 # cols in A = rows in B\n n = len(B[0]) if B else 0 # cols in B\n\n # Validate dimensions\n if not all(len(row) == p for row in A):\n raise ValueError(\"First matrix has irregular row lengths\")\n if len(B) != p:\n raise ValueError(f\"Incompatible dimensions: A is {m}x{p}, B is {len(B)}x{n}\")\n if not all(len(row) == n for row in B):\n raise ValueError(\"Second matrix has irregular row lengths\")\n\n # Pre-allocate result matrix with zeros\n C = [[0.0] * n for _ in range(m)]\n\n # Compute product using simple indexed loops\n for i in range(m):\n A_i = A[i] # Cache current row of A\n C_i = C[i] # Cache current row of C\n for j in range(n):\n tot = 0.0\n for k in range(p):\n tot += A_i[k] * B[k][j]\n C_i[j] = tot\n\n return C", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 3693}, "tests/test_compressible.py::155": {"resolved_imports": ["fluids/compressible.py", "fluids/constants/__init__.py", "fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["F2K", "Panhandle_A", "assert_close", "day", "foot", "inch", "psi", "pytest"], "enclosing_function": "test_Panhandle_A", "extracted_code": "# Source: fluids/compressible.py\ndef Panhandle_A(SG: float, Tavg: float, L: float | None=None, D: float | None=None, P1: float | None=None, P2: float | None=None, Q: float | None=None, Ts: float=288.7,\n Ps: float=101325., Zavg: float=1.0, E: float=0.92) -> float:\n r\"\"\"Calculation function for dealing with flow of a compressible gas in a\n pipeline with the Panhandle A formula. Can calculate any of the following,\n given all other inputs:\n\n * Flow rate\n * Upstream pressure\n * Downstream pressure\n * Diameter of pipe\n * Length of pipe\n\n A variety of different constants and expressions have been presented\n for the Panhandle A equation. Here, a new form is developed with all units\n in base SI, based on the work of [1]_.\n\n .. math::\n Q = 158.02053 E \\left(\\frac{T_s}{P_s}\\right)^{1.0788}\\left[\\frac{P_1^2\n -P_2^2}{L \\cdot {SG}^{0.8539} T_{avg}Z_{avg}}\\right]^{0.5394}D^{2.6182}\n\n Parameters\n ----------\n SG : float\n Specific gravity of fluid with respect to air at the reference\n temperature and pressure `Ts` and `Ps`, [-]\n Tavg : float\n Average temperature of the fluid in the pipeline, [K]\n L : float, optional\n Length of pipe, [m]\n D : float, optional\n Diameter of pipe, [m]\n P1 : float, optional\n Inlet pressure to pipe, [Pa]\n P2 : float, optional\n Outlet pressure from pipe, [Pa]\n Q : float, optional\n Flow rate of gas through pipe at `Ts` and `Ps`, [m^3/s]\n Ts : float, optional\n Reference temperature for the specific gravity of the gas, [K]\n Ps : float, optional\n Reference pressure for the specific gravity of the gas, [Pa]\n Zavg : float, optional\n Average compressibility factor for gas, [-]\n E : float, optional\n Pipeline efficiency, a correction factor between 0 and 1\n\n Returns\n -------\n Q, P1, P2, D, or L : float\n The missing input which was solved for [base SI]\n\n Notes\n -----\n [1]_'s original constant was 4.5965E-3, and it has units of km (length),\n kPa, mm (diameter), and flowrate in m^3/day.\n\n The form in [2]_ has the same exponents as used here, units of mm\n (diameter), kPa, km (length), and flow in m^3/hour; its leading constant is\n 1.9152E-4.\n\n The GPSA [3]_ has a leading constant of 0.191, a bracketed power of 0.5392,\n a specific gravity power of 0.853, and otherwise the same constants.\n It is in units of mm (diameter) and kPa and m^3/day; length is stated to be\n in km, but according to the errata is in m.\n\n [4]_ has a leading constant of 1.198E7, a specific gravity of power of 0.8541,\n and a power of diameter which is under the root of 4.854 and is otherwise\n the same. It has units of kPa and m^3/day, but is otherwise in base SI\n units.\n\n [5]_ has a leading constant of 99.5211, but its reference correction has no\n exponent; other exponents are the same as here. It is entirely in base SI\n units.\n\n [6]_ has pressures in psi, diameter in inches, length in miles, Q in\n ft^3/day, T in degrees Rankine, and a constant of 435.87.\n Its reference condition power is 1.07881, and it has a specific gravity\n correction outside any other term with a power of 0.4604.\n\n Examples\n --------\n >>> Panhandle_A(D=0.340, P1=90E5, P2=20E5, L=160E3, SG=0.693, Tavg=277.15)\n 42.56082051195928\n\n References\n ----------\n .. [1] Menon, E. Shashi. Gas Pipeline Hydraulics. 1st edition. Boca Raton,\n FL: CRC Press, 2005.\n .. [2] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,\n 2009.\n .. [3] GPSA. GPSA Engineering Data Book. 13th edition. Gas Processors\n Suppliers Association, Tulsa, OK, 2012.\n .. [4] Campbell, John M. Gas Conditioning and Processing, Vol. 2: The\n Equipment Modules. 7th edition. Campbell Petroleum Series, 1992.\n .. [5] Coelho, Paulo M., and Carlos Pinho. \"Considerations about Equations\n for Steady State Flow in Natural Gas Pipelines.\" Journal of the\n Brazilian Society of Mechanical Sciences and Engineering 29, no. 3\n (September 2007): 262-73. doi:10.1590/S1678-58782007000300005.\n .. [6] Ikoku, Chi U. Natural Gas Production Engineering. Malabar, Fla:\n Krieger Pub Co, 1991.\n \"\"\"\n c1 = 1.0788\n c2 = 0.8539\n c3 = 0.5394\n c4 = 2.6182\n c5 = 158.0205328706957220332831680508433862787 # 45965*10**(591/1250)/864\n if Q is None and L is not None and D is not None and P1 is not None and P2 is not None:\n return c5*E*(Ts/Ps)**c1*((P1**2 - P2**2)/(L*SG**c2*Tavg*Zavg))**c3*D**c4\n elif D is None and L is not None and Q is not None and P1 is not None and P2 is not None:\n return (Q*(Ts/Ps)**(-c1)*(SG**(-c2)*(P1**2 - P2**2)/(L*Tavg*Zavg))**(-c3)/(E*c5))**(1./c4)\n elif P1 is None and L is not None and Q is not None and D is not None and P2 is not None:\n return sqrt(L*SG**c2*Tavg*Zavg*(D**(-c4)*Q*(Ts/Ps)**(-c1)/(E*c5))**(1./c3) + P2**2)\n elif P2 is None and L is not None and Q is not None and D is not None and P1 is not None:\n return sqrt(-L*SG**c2*Tavg*Zavg*(D**(-c4)*Q*(Ts/Ps)**(-c1)/(E*c5))**(1./c3) + P1**2)\n elif L is None and P2 is not None and Q is not None and D is not None and P1 is not None:\n return SG**(-c2)*(D**(-c4)*Q*(Ts/Ps)**(-c1)/(E*c5))**(-1./c3)*(P1**2 - P2**2)/(Tavg*Zavg)\n else:\n raise ValueError(\"This function solves for either flow, upstream \\\npressure, downstream pressure, diameter, or length; all other inputs \\\nmust be provided.\")\n\n\n# Source: fluids/core.py\ndef F2K(F: float) -> float:\n \"\"\"Convert Fahrenheit to Kelvin.\n\n Parameters\n ----------\n F : float\n Fahrenheit temperature to be converted.\n\n Returns\n -------\n K : float\n Equivalent Kelvin temperature.\n\n Notes\n -----\n Computes ``K = (F - 32)/1.8 + zero_Celsius`` where `zero_Celsius` =\n 273.15, i.e., (the absolute value of) temperature \"absolute zero\" as\n measured in Celsius.\n\n Examples\n --------\n >>> F2K(-40)\n 233.14999999999998\n \"\"\"\n return (F - 32.0)/1.8 + zero_Celsius\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 6731}, "tests/test_compressible.py::158": {"resolved_imports": ["fluids/compressible.py", "fluids/constants/__init__.py", "fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["F2K", "Panhandle_A", "assert_close", "day", "foot", "inch", "psi", "pytest"], "enclosing_function": "test_Panhandle_A", "extracted_code": "# Source: fluids/compressible.py\ndef Panhandle_A(SG: float, Tavg: float, L: float | None=None, D: float | None=None, P1: float | None=None, P2: float | None=None, Q: float | None=None, Ts: float=288.7,\n Ps: float=101325., Zavg: float=1.0, E: float=0.92) -> float:\n r\"\"\"Calculation function for dealing with flow of a compressible gas in a\n pipeline with the Panhandle A formula. Can calculate any of the following,\n given all other inputs:\n\n * Flow rate\n * Upstream pressure\n * Downstream pressure\n * Diameter of pipe\n * Length of pipe\n\n A variety of different constants and expressions have been presented\n for the Panhandle A equation. Here, a new form is developed with all units\n in base SI, based on the work of [1]_.\n\n .. math::\n Q = 158.02053 E \\left(\\frac{T_s}{P_s}\\right)^{1.0788}\\left[\\frac{P_1^2\n -P_2^2}{L \\cdot {SG}^{0.8539} T_{avg}Z_{avg}}\\right]^{0.5394}D^{2.6182}\n\n Parameters\n ----------\n SG : float\n Specific gravity of fluid with respect to air at the reference\n temperature and pressure `Ts` and `Ps`, [-]\n Tavg : float\n Average temperature of the fluid in the pipeline, [K]\n L : float, optional\n Length of pipe, [m]\n D : float, optional\n Diameter of pipe, [m]\n P1 : float, optional\n Inlet pressure to pipe, [Pa]\n P2 : float, optional\n Outlet pressure from pipe, [Pa]\n Q : float, optional\n Flow rate of gas through pipe at `Ts` and `Ps`, [m^3/s]\n Ts : float, optional\n Reference temperature for the specific gravity of the gas, [K]\n Ps : float, optional\n Reference pressure for the specific gravity of the gas, [Pa]\n Zavg : float, optional\n Average compressibility factor for gas, [-]\n E : float, optional\n Pipeline efficiency, a correction factor between 0 and 1\n\n Returns\n -------\n Q, P1, P2, D, or L : float\n The missing input which was solved for [base SI]\n\n Notes\n -----\n [1]_'s original constant was 4.5965E-3, and it has units of km (length),\n kPa, mm (diameter), and flowrate in m^3/day.\n\n The form in [2]_ has the same exponents as used here, units of mm\n (diameter), kPa, km (length), and flow in m^3/hour; its leading constant is\n 1.9152E-4.\n\n The GPSA [3]_ has a leading constant of 0.191, a bracketed power of 0.5392,\n a specific gravity power of 0.853, and otherwise the same constants.\n It is in units of mm (diameter) and kPa and m^3/day; length is stated to be\n in km, but according to the errata is in m.\n\n [4]_ has a leading constant of 1.198E7, a specific gravity of power of 0.8541,\n and a power of diameter which is under the root of 4.854 and is otherwise\n the same. It has units of kPa and m^3/day, but is otherwise in base SI\n units.\n\n [5]_ has a leading constant of 99.5211, but its reference correction has no\n exponent; other exponents are the same as here. It is entirely in base SI\n units.\n\n [6]_ has pressures in psi, diameter in inches, length in miles, Q in\n ft^3/day, T in degrees Rankine, and a constant of 435.87.\n Its reference condition power is 1.07881, and it has a specific gravity\n correction outside any other term with a power of 0.4604.\n\n Examples\n --------\n >>> Panhandle_A(D=0.340, P1=90E5, P2=20E5, L=160E3, SG=0.693, Tavg=277.15)\n 42.56082051195928\n\n References\n ----------\n .. [1] Menon, E. Shashi. Gas Pipeline Hydraulics. 1st edition. Boca Raton,\n FL: CRC Press, 2005.\n .. [2] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,\n 2009.\n .. [3] GPSA. GPSA Engineering Data Book. 13th edition. Gas Processors\n Suppliers Association, Tulsa, OK, 2012.\n .. [4] Campbell, John M. Gas Conditioning and Processing, Vol. 2: The\n Equipment Modules. 7th edition. Campbell Petroleum Series, 1992.\n .. [5] Coelho, Paulo M., and Carlos Pinho. \"Considerations about Equations\n for Steady State Flow in Natural Gas Pipelines.\" Journal of the\n Brazilian Society of Mechanical Sciences and Engineering 29, no. 3\n (September 2007): 262-73. doi:10.1590/S1678-58782007000300005.\n .. [6] Ikoku, Chi U. Natural Gas Production Engineering. Malabar, Fla:\n Krieger Pub Co, 1991.\n \"\"\"\n c1 = 1.0788\n c2 = 0.8539\n c3 = 0.5394\n c4 = 2.6182\n c5 = 158.0205328706957220332831680508433862787 # 45965*10**(591/1250)/864\n if Q is None and L is not None and D is not None and P1 is not None and P2 is not None:\n return c5*E*(Ts/Ps)**c1*((P1**2 - P2**2)/(L*SG**c2*Tavg*Zavg))**c3*D**c4\n elif D is None and L is not None and Q is not None and P1 is not None and P2 is not None:\n return (Q*(Ts/Ps)**(-c1)*(SG**(-c2)*(P1**2 - P2**2)/(L*Tavg*Zavg))**(-c3)/(E*c5))**(1./c4)\n elif P1 is None and L is not None and Q is not None and D is not None and P2 is not None:\n return sqrt(L*SG**c2*Tavg*Zavg*(D**(-c4)*Q*(Ts/Ps)**(-c1)/(E*c5))**(1./c3) + P2**2)\n elif P2 is None and L is not None and Q is not None and D is not None and P1 is not None:\n return sqrt(-L*SG**c2*Tavg*Zavg*(D**(-c4)*Q*(Ts/Ps)**(-c1)/(E*c5))**(1./c3) + P1**2)\n elif L is None and P2 is not None and Q is not None and D is not None and P1 is not None:\n return SG**(-c2)*(D**(-c4)*Q*(Ts/Ps)**(-c1)/(E*c5))**(-1./c3)*(P1**2 - P2**2)/(Tavg*Zavg)\n else:\n raise ValueError(\"This function solves for either flow, upstream \\\npressure, downstream pressure, diameter, or length; all other inputs \\\nmust be provided.\")\n\n\n# Source: fluids/core.py\ndef F2K(F: float) -> float:\n \"\"\"Convert Fahrenheit to Kelvin.\n\n Parameters\n ----------\n F : float\n Fahrenheit temperature to be converted.\n\n Returns\n -------\n K : float\n Equivalent Kelvin temperature.\n\n Notes\n -----\n Computes ``K = (F - 32)/1.8 + zero_Celsius`` where `zero_Celsius` =\n 273.15, i.e., (the absolute value of) temperature \"absolute zero\" as\n measured in Celsius.\n\n Examples\n --------\n >>> F2K(-40)\n 233.14999999999998\n \"\"\"\n return (F - 32.0)/1.8 + zero_Celsius\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 6731}, "tests/test_compressible.py::159": {"resolved_imports": ["fluids/compressible.py", "fluids/constants/__init__.py", "fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["F2K", "Panhandle_A", "assert_close", "day", "foot", "inch", "psi", "pytest"], "enclosing_function": "test_Panhandle_A", "extracted_code": "# Source: fluids/compressible.py\ndef Panhandle_A(SG: float, Tavg: float, L: float | None=None, D: float | None=None, P1: float | None=None, P2: float | None=None, Q: float | None=None, Ts: float=288.7,\n Ps: float=101325., Zavg: float=1.0, E: float=0.92) -> float:\n r\"\"\"Calculation function for dealing with flow of a compressible gas in a\n pipeline with the Panhandle A formula. Can calculate any of the following,\n given all other inputs:\n\n * Flow rate\n * Upstream pressure\n * Downstream pressure\n * Diameter of pipe\n * Length of pipe\n\n A variety of different constants and expressions have been presented\n for the Panhandle A equation. Here, a new form is developed with all units\n in base SI, based on the work of [1]_.\n\n .. math::\n Q = 158.02053 E \\left(\\frac{T_s}{P_s}\\right)^{1.0788}\\left[\\frac{P_1^2\n -P_2^2}{L \\cdot {SG}^{0.8539} T_{avg}Z_{avg}}\\right]^{0.5394}D^{2.6182}\n\n Parameters\n ----------\n SG : float\n Specific gravity of fluid with respect to air at the reference\n temperature and pressure `Ts` and `Ps`, [-]\n Tavg : float\n Average temperature of the fluid in the pipeline, [K]\n L : float, optional\n Length of pipe, [m]\n D : float, optional\n Diameter of pipe, [m]\n P1 : float, optional\n Inlet pressure to pipe, [Pa]\n P2 : float, optional\n Outlet pressure from pipe, [Pa]\n Q : float, optional\n Flow rate of gas through pipe at `Ts` and `Ps`, [m^3/s]\n Ts : float, optional\n Reference temperature for the specific gravity of the gas, [K]\n Ps : float, optional\n Reference pressure for the specific gravity of the gas, [Pa]\n Zavg : float, optional\n Average compressibility factor for gas, [-]\n E : float, optional\n Pipeline efficiency, a correction factor between 0 and 1\n\n Returns\n -------\n Q, P1, P2, D, or L : float\n The missing input which was solved for [base SI]\n\n Notes\n -----\n [1]_'s original constant was 4.5965E-3, and it has units of km (length),\n kPa, mm (diameter), and flowrate in m^3/day.\n\n The form in [2]_ has the same exponents as used here, units of mm\n (diameter), kPa, km (length), and flow in m^3/hour; its leading constant is\n 1.9152E-4.\n\n The GPSA [3]_ has a leading constant of 0.191, a bracketed power of 0.5392,\n a specific gravity power of 0.853, and otherwise the same constants.\n It is in units of mm (diameter) and kPa and m^3/day; length is stated to be\n in km, but according to the errata is in m.\n\n [4]_ has a leading constant of 1.198E7, a specific gravity of power of 0.8541,\n and a power of diameter which is under the root of 4.854 and is otherwise\n the same. It has units of kPa and m^3/day, but is otherwise in base SI\n units.\n\n [5]_ has a leading constant of 99.5211, but its reference correction has no\n exponent; other exponents are the same as here. It is entirely in base SI\n units.\n\n [6]_ has pressures in psi, diameter in inches, length in miles, Q in\n ft^3/day, T in degrees Rankine, and a constant of 435.87.\n Its reference condition power is 1.07881, and it has a specific gravity\n correction outside any other term with a power of 0.4604.\n\n Examples\n --------\n >>> Panhandle_A(D=0.340, P1=90E5, P2=20E5, L=160E3, SG=0.693, Tavg=277.15)\n 42.56082051195928\n\n References\n ----------\n .. [1] Menon, E. Shashi. Gas Pipeline Hydraulics. 1st edition. Boca Raton,\n FL: CRC Press, 2005.\n .. [2] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,\n 2009.\n .. [3] GPSA. GPSA Engineering Data Book. 13th edition. Gas Processors\n Suppliers Association, Tulsa, OK, 2012.\n .. [4] Campbell, John M. Gas Conditioning and Processing, Vol. 2: The\n Equipment Modules. 7th edition. Campbell Petroleum Series, 1992.\n .. [5] Coelho, Paulo M., and Carlos Pinho. \"Considerations about Equations\n for Steady State Flow in Natural Gas Pipelines.\" Journal of the\n Brazilian Society of Mechanical Sciences and Engineering 29, no. 3\n (September 2007): 262-73. doi:10.1590/S1678-58782007000300005.\n .. [6] Ikoku, Chi U. Natural Gas Production Engineering. Malabar, Fla:\n Krieger Pub Co, 1991.\n \"\"\"\n c1 = 1.0788\n c2 = 0.8539\n c3 = 0.5394\n c4 = 2.6182\n c5 = 158.0205328706957220332831680508433862787 # 45965*10**(591/1250)/864\n if Q is None and L is not None and D is not None and P1 is not None and P2 is not None:\n return c5*E*(Ts/Ps)**c1*((P1**2 - P2**2)/(L*SG**c2*Tavg*Zavg))**c3*D**c4\n elif D is None and L is not None and Q is not None and P1 is not None and P2 is not None:\n return (Q*(Ts/Ps)**(-c1)*(SG**(-c2)*(P1**2 - P2**2)/(L*Tavg*Zavg))**(-c3)/(E*c5))**(1./c4)\n elif P1 is None and L is not None and Q is not None and D is not None and P2 is not None:\n return sqrt(L*SG**c2*Tavg*Zavg*(D**(-c4)*Q*(Ts/Ps)**(-c1)/(E*c5))**(1./c3) + P2**2)\n elif P2 is None and L is not None and Q is not None and D is not None and P1 is not None:\n return sqrt(-L*SG**c2*Tavg*Zavg*(D**(-c4)*Q*(Ts/Ps)**(-c1)/(E*c5))**(1./c3) + P1**2)\n elif L is None and P2 is not None and Q is not None and D is not None and P1 is not None:\n return SG**(-c2)*(D**(-c4)*Q*(Ts/Ps)**(-c1)/(E*c5))**(-1./c3)*(P1**2 - P2**2)/(Tavg*Zavg)\n else:\n raise ValueError(\"This function solves for either flow, upstream \\\npressure, downstream pressure, diameter, or length; all other inputs \\\nmust be provided.\")\n\n\n# Source: fluids/core.py\ndef F2K(F: float) -> float:\n \"\"\"Convert Fahrenheit to Kelvin.\n\n Parameters\n ----------\n F : float\n Fahrenheit temperature to be converted.\n\n Returns\n -------\n K : float\n Equivalent Kelvin temperature.\n\n Notes\n -----\n Computes ``K = (F - 32)/1.8 + zero_Celsius`` where `zero_Celsius` =\n 273.15, i.e., (the absolute value of) temperature \"absolute zero\" as\n measured in Celsius.\n\n Examples\n --------\n >>> F2K(-40)\n 233.14999999999998\n \"\"\"\n return (F - 32.0)/1.8 + zero_Celsius\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 6731}, "tests/test_control_valve.py::417": {"resolved_imports": ["fluids/control_valve.py", "fluids/fittings.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close1d", "frac_CV_quick", "opening_quick", "opening_quick_tck", "pytest", "splrep"], "enclosing_function": "test_opening_quick_data", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 275}, "tests/test_filters.py::64": {"resolved_imports": ["fluids/filters.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close1d", "grills_rounded_Ks", "grills_rounded_alphas", "grills_rounded_tck", "pytest", "splrep"], "enclosing_function": "test_grills_rounded", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 275}, "tests/test_fittings.py::871": {"resolved_imports": ["fluids/fittings.py", "fluids/constants/__init__.py", "fluids/core.py", "fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["K_diaphragm_valve_Crane", "assert_close", "pytest"], "enclosing_function": "test_K_diaphragm_valve_Crane", "extracted_code": "# Source: fluids/fittings.py\ndef K_diaphragm_valve_Crane(D: float | None=None, fd: float | None=None, style: int=0) -> float:\n r\"\"\"Returns the loss coefficient for a diaphragm valve of either weir\n (`style` = 0) or straight-through (`style` = 1) as shown in [1]_.\n\n .. math::\n K = K_1 = K_2 = N\\cdot f_d\n\n For style 0 (weir), N = 149; for style 1 (straight through), N = 39.\n\n Parameters\n ----------\n D : float, optional\n Diameter of the pipe section the valve in mounted in; the\n same as the line size [m]\n fd : float, optional\n Darcy friction factor calculated for the actual pipe flow in clean\n steel (roughness = 0.0018 inch) in the fully developed turbulent\n region; do not specify this to use the original Crane friction factor!,\n [-]\n style : int, optional\n Either 0 (weir type valve) or 1 (straight through weir valve) [-]\n\n Returns\n -------\n K : float\n Loss coefficient with respect to the pipe inside diameter [-]\n\n Notes\n -----\n This method is not valid in the laminar regime and the pressure drop will\n be underestimated in those conditions.\n\n Examples\n --------\n >>> K_diaphragm_valve_Crane(D=.1, style=0)\n 2.4269804835982565\n\n References\n ----------\n .. [1] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,\n 2009.\n \"\"\"\n if D is None and fd is None:\n raise ValueError(\"Either `D` or `fd` must be specified\")\n if fd is None:\n if D is None:\n raise ValueError(\"D must be specified if fd is not provided\")\n fd = ft_Crane(D)\n if style == 0:\n K = 149.0*fd\n elif style == 1:\n K = 39.0*fd\n else:\n raise ValueError(\"Accepted valve styles are 0 (weir) or 1 (straight through) only\")\n return K\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 2436}, "tests/test_fittings_fits.py::357": {"resolved_imports": ["fluids/__init__.py", "fluids/core.py", "fluids/optional/pychebfun.py", "fluids/fittings.py"], "used_names": ["Engauge_2d_parser", "UnivariateSpline", "assert_allclose", "bend_rounded_Miller_C_Re", "bend_rounded_Miller_C_Re_limit_1", "bisplev", "bisplrep", "fluids_data_dir", "log10", "newton", "os", "pytest", "tck_bend_rounded_Miller_C_Re"], "enclosing_function": "test_bend_rounded_Miller_Re_correction", "extracted_code": "# Source: fluids/__init__.py\ntry:\n fluids_dir = os.path.dirname(__file__)\n fluids_data_dir = os.path.join(fluids_dir, \"data\")\nexcept:\n pass\n\n\n# Source: fluids/core.py\ndef Engauge_2d_parser(lines, flat=False):\n \"\"\"Not exposed function to read a 2D file generated by engauge-digitizer;\n for curve fitting.\n \"\"\"\n z_values = []\n x_lists = []\n y_lists = []\n working_xs = []\n working_ys = []\n\n new_curve = True\n for line in lines:\n if line.strip() == \"\":\n new_curve = True\n elif new_curve:\n z = float(line.split(\",\")[1])\n z_values.append(z)\n if working_xs and working_ys:\n x_lists.append(working_xs)\n y_lists.append(working_ys)\n working_xs = []\n working_ys = []\n new_curve = False\n else:\n x, y = (float(i) for i in line.strip().split(\",\"))\n working_xs.append(x)\n working_ys.append(y)\n x_lists.append(working_xs)\n y_lists.append(working_ys)\n\n if flat:\n all_zs = []\n all_xs = []\n all_ys = []\n for z, xs, ys in zip(z_values, x_lists, y_lists):\n for x, y in zip(xs, ys):\n all_zs.append(z)\n all_xs.append(x)\n all_ys.append(y)\n return all_zs, all_xs, all_ys\n\n return z_values, x_lists, y_lists\n\n\n# Source: fluids/fittings.py\ntck_bend_rounded_Miller_C_Re = implementation_optimize_tck([[4.0, 4.0, 4.0, 4.0, 8.0, 8.0, 8.0, 8.0],\n [1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0],\n [2.177340320782947, 2.185952396281732, 2.185952396281732, 2.1775876405173977,\n 0.6513348082098823, 0.7944713057222101, 0.7944713057222103, 1.0526247737400114,\n 0.6030278030721317, 1.3741240162063968, 1.3741240162063992, 0.7693594604301893,\n -2.1663631289607883, -1.9474318981548622, -1.9474318981548622, 0.4196741237602154],\n 3, 3])", "n_imports_parsed": 14, "n_files_resolved": 4, "n_chars_extracted": 1961}, "tests/test_jet_pump.py::332": {"resolved_imports": ["fluids/__init__.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "vacuum_air_leakage_Ryans_Croll"], "enclosing_function": "test_vacuum_air_leakage_Ryans_Croll", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 607}, "tests/test_numerics_polynomial_roots.py::58": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/polynomial_roots.py"], "used_names": ["assert_close", "roots_quadratic"], "enclosing_function": "test_roots_quadratic", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/numerics/polynomial_roots.py\ndef roots_quadratic(a, b, c):\n if a == 0.0:\n root = -c/b\n return (root, root)\n D = b*b - 4.0*a*c\n a_inv_2 = 0.5/a\n if D < 0.0:\n D = sqrt(-D)\n x1 = (-b + D*1.0j)*a_inv_2\n x2 = (-b - D*1.0j)*a_inv_2\n else:\n D = sqrt(D)\n x1 = (D - b)*a_inv_2\n x2 = -(b + D)*a_inv_2\n return (x1, x2)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 1008}, "tests/test_numerics_polynomial_utils.py::131": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["assert_close", "horner_and_der2", "quadratic_from_f_ders"], "enclosing_function": "test_quadratic_from_f_ders", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 607}, "tests/test_separator.py::68": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/separator.py"], "used_names": ["UnivariateSpline", "assert_close1d", "pytest", "splrep", "tck_Watkins"], "enclosing_function": "test_K_separator_Watkins_fit", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 275}, "tests/test_two_phase.py::625": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/two_phase.py", "fluids/two_phase_voidage.py"], "used_names": ["Dukler_XA_tck", "Dukler_XC_tck", "Dukler_XD_tck", "assert_close1d", "log10", "pytest", "splrep"], "enclosing_function": "test_Taitel_Dukler_splines", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 275}, "tests/test_units.py::165": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/units.py"], "used_names": ["API520_A_g", "API520_round_size", "Bond", "C_Chezy_to_n_Manning", "Cv_to_K", "Geldart_Ling", "K_separator_Watkins", "K_to_Cv", "Q_weir_rectangular_SIA", "Reynolds", "Robbins", "T_critical_flow", "agitator_time_homogeneous", "assert_close", "current_ideal", "dP_packed_bed", "drag_sphere", "friction_factor", "head_from_P", "integrate_drag_sphere", "is_critical_flow", "pytest", "roughness_Farshad", "size_control_valve_g", "specific_speed", "speed_synchronous", "t_from_gauge", "u"], "enclosing_function": "test_sample_cases", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/units.py\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 4046}, "tests/test_control_valve.py::179": {"resolved_imports": ["fluids/control_valve.py", "fluids/fittings.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "pytest", "size_control_valve_g", "size_control_valve_l"], "enclosing_function": "test_control_valve_size_l", "extracted_code": "# Source: fluids/control_valve.py\ndef size_control_valve_l(rho: float, Psat: float, Pc: float, mu: float, P1: float, P2: float, Q: float, D1: float | None=None, D2: float | None=None,\n d: float | None=None, FL: float=0.9, Fd: float=1, allow_choked: bool=True,\n allow_laminar: bool=True, full_output: bool=False) -> float | dict[str, bool | float | None] | dict[str, float | bool | str | None]:\n r\"\"\"Calculates flow coefficient of a control valve passing a liquid\n according to IEC 60534. Uses a large number of inputs in SI units. Note the\n return value is not standard SI. All parameters are required.\n This sizing model does not officially apply to liquid mixtures, slurries,\n non-Newtonian fluids, or liquid-solid conveyance systems. For details\n of the calculations, consult [1]_.\n\n Parameters\n ----------\n rho : float\n Density of the liquid at the inlet [kg/m^3]\n Psat : float\n Saturation pressure of the fluid at inlet temperature [Pa]\n Pc : float\n Critical pressure of the fluid [Pa]\n mu : float\n Viscosity of the fluid [Pa*s]\n P1 : float\n Inlet pressure of the fluid before valves and reducers [Pa]\n P2 : float\n Outlet pressure of the fluid after valves and reducers [Pa]\n Q : float\n Volumetric flow rate of the fluid [m^3/s]\n D1 : float, optional\n Diameter of the pipe before the valve [m]\n D2 : float, optional\n Diameter of the pipe after the valve [m]\n d : float, optional\n Diameter of the valve [m]\n FL : float, optional\n Liquid pressure recovery factor of a control valve without attached\n fittings (normally 0.8-0.9 at full open and decreasing as opened\n further to below 0.5; use default very cautiously!) []\n Fd : float, optional\n Valve style modifier (0.1 to 1; varies tremendously depending on the\n type of valve and position; do not use the default at all!) []\n allow_choked : bool, optional\n Overrides the automatic transition into the choked regime if this is\n False and returns as if choked flow does not exist\n allow_laminar : bool, optional\n Overrides the automatic transition into the laminar regime if this is\n False and returns as if laminar flow does not exist\n full_output : bool, optional\n If True, returns intermediate calculation values as\n well as Kv in the form of a dictionary containing 'Kv', 'Rev', 'choked',\n 'FL', 'FLP', 'FR', 'FP', and 'laminar'. Some may be None if they are\n not used in the calculation.\n\n Returns\n -------\n Kv : float\n Metric Kv valve flow coefficient (flow rate of water at a pressure drop\n of 1 bar) [m^3/hr]\n\n Notes\n -----\n It is possible to use this model without any diameters specified; in that\n case, turbulent flow is assumed. Choked flow can still be modeled. This is\n not recommended. All three diameters need to be None for this to work.\n `FL` and `Fd` are not used by the models when the diameters are not\n specified.\n\n Examples\n --------\n From [1]_, matching example 1 for a globe, parabolic plug,\n flow-to-open valve.\n\n >>> size_control_valve_l(rho=965.4, Psat=70.1E3, Pc=22120E3, mu=3.1472E-4,\n ... P1=680E3, P2=220E3, Q=0.1, D1=0.15, D2=0.15, d=0.15,\n ... FL=0.9, Fd=0.46)\n 164.9954763704956\n\n From [1]_, matching example 2 for a ball, segmented ball,\n flow-to-open valve.\n\n >>> size_control_valve_l(rho=965.4, Psat=70.1E3, Pc=22120E3, mu=3.1472E-4,\n ... P1=680E3, P2=220E3, Q=0.1, D1=0.1, D2=0.1, d=0.1,\n ... FL=0.6, Fd=0.98)\n 238.05817216710483\n\n References\n ----------\n .. [1] IEC 60534-2-1 / ISA-75.01.01-2007\n \"\"\"\n if full_output:\n ans: dict[str, bool | float | None] = {\"FLP\": None, \"FP\": None, \"FR\": None}\n # Pa to kPa, according to constants in standard\n P1, P2, Psat, Pc = P1/1000., P2/1000., Psat/1000., Pc/1000.\n Q = Q*3600. # m^3/s to m^3/hr, according to constants in standard\n nu = mu/rho # kinematic viscosity used in standard\n MAX_C_POSSIBLE = 1E40 # Quit iterations if C reaches this high\n\n dP = P1 - P2\n FF = FF_critical_pressure_ratio_l(Psat=Psat, Pc=Pc)\n choked = is_choked_turbulent_l(dP=dP, P1=P1, Psat=Psat, FF=FF, FL=FL)\n if choked and allow_choked:\n # Choked flow, equation 3\n C = Q/N1/FL*sqrt(rho/rho0/(P1 - FF*Psat))\n else:\n # non-choked flow, eq 1\n C = Q/N1*sqrt(rho/rho0/dP)\n if D1 is None and D2 is None and d is None:\n # Assume turbulent if no diameters are provided, no other calculations\n Rev = 1e5\n else:\n # m to mm, according to constants in standard\n if D1 is None or D2 is None or d is None:\n raise ValueError(\"If any diameter is specified, all three (D1, D2, d) must be specified\")\n D1, D2, d = D1*1000., D2*1000., d*1000.\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=C)\n # normal calculation path\n if (Rev > 10000 or not allow_laminar) and (D1 != d or D2 != d):\n # liquid, using Fp and FLP\n FP = 1.0\n Ci = C\n MAX_ITER = 20\n def iterate_piping_turbulent_l(Ci, iterations):\n loss = loss_coefficient_piping(d, D1, D2)\n FP = 1.0/sqrt(1 + loss/N2*(Ci/d**2)**2)\n if d > D1:\n loss_upstream = 0.0\n else:\n loss_upstream = loss_coefficient_piping(d, D1)\n\n FLP = FL*1.0/sqrt(1 + FL**2/N2*loss_upstream*(Ci/d**2)**2)\n choked = is_choked_turbulent_l(dP, P1, Psat, FF, FLP=FLP, FP=FP)\n if choked:\n # Choked flow with piping, equation 4\n C = Q/N1/FLP*sqrt(rho/rho0/(P1-FF*Psat))\n else:\n # Non-Choked flow with piping, equation 5\n C = Q/N1/FP*sqrt(rho/rho0/dP)\n if Ci/C < 0.99 and iterations < MAX_ITER and Ci < MAX_C_POSSIBLE:\n C = iterate_piping_turbulent_l(C, iterations+1)\n if MAX_ITER == iterations or Ci >= MAX_C_POSSIBLE:\n ans[\"warning\"] = \"Not converged in inner loop\"\n if full_output:\n ans[\"FLP\"] = FLP\n ans[\"FP\"] = FP\n return C\n\n C = iterate_piping_turbulent_l(Ci, 0)\n elif Rev <= 10000 and allow_laminar:\n # Laminar\n def iterate_piping_laminar_l(C):\n Ci = 1.3*C\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=Ci)\n if Ci/(d*d) > 0.016*N18:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=False)\n else:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=True)\n if C/FR >= Ci:\n Ci = iterate_piping_laminar_l(Ci) # pragma: no cover\n\n if full_output:\n ans[\"Rev\"] = Rev\n ans[\"FR\"] = FR\n return Ci\n C = iterate_piping_laminar_l(C)\n if full_output:\n ans[\"FF\"] = FF\n ans[\"choked\"] = choked\n ans[\"Kv\"] = C\n ans[\"laminar\"] = Rev <= 10000\n\n # For the laminar case this is already set and needs to not be overwritten\n if \"Rev\" not in ans:\n ans[\"Rev\"] = Rev\n return ans\n else:\n# return C, choked, laminar, FF, FR, Rev, FP, FLP, warning\n return C\n\ndef size_control_valve_g(T: float, MW: float, mu: float, gamma: float, Z: float, P1: float, P2: float, Q: float, D1: float | None=None, D2: float | None=None,\n d: float | None=None, FL: float=0.9, Fd: float=1, xT: float=0.7, allow_choked: bool=True,\n allow_laminar: bool=True, full_output: bool=False) -> float | dict[str, bool | float | None] | dict[str, float | bool | str | None]:\n r\"\"\"Calculates flow coefficient of a control valve passing a gas\n according to IEC 60534. Uses a large number of inputs in SI units. Note the\n return value is not standard SI. All parameters are required. For details\n of the calculations, consult [1]_. Note the inlet gas flow conditions.\n\n Parameters\n ----------\n T : float\n Temperature of the gas at the inlet [K]\n MW : float\n Molecular weight of the gas [g/mol]\n mu : float\n Viscosity of the fluid at inlet conditions [Pa*s]\n gamma : float\n Specific heat capacity ratio [-]\n Z : float\n Compressibility factor at inlet conditions, [-]\n P1 : float\n Inlet pressure of the gas before valves and reducers [Pa]\n P2 : float\n Outlet pressure of the gas after valves and reducers [Pa]\n Q : float\n Volumetric flow rate of the gas at *273.15 K* and 1 atm specifically\n [m^3/s]\n D1 : float, optional\n Diameter of the pipe before the valve [m]\n D2 : float, optional\n Diameter of the pipe after the valve [m]\n d : float, optional\n Diameter of the valve [m]\n FL : float, optional\n Liquid pressure recovery factor of a control valve without attached\n fittings (normally 0.8-0.9 at full open and decreasing as opened\n further to below 0.5; use default very cautiously!) []\n Fd : float, optional\n Valve style modifier (0.1 to 1; varies tremendously depending on the\n type of valve and position; do not use the default at all!) []\n xT : float, optional\n Pressure difference ratio factor of a valve without fittings at choked\n flow (increasing to 0.9 or higher as the valve is closed further and\n decreasing to 0.1 or lower as the valve is opened further; use default\n very cautiously!) [-]\n allow_choked : bool, optional\n Overrides the automatic transition into the choked regime if this is\n False and returns as if choked flow does not exist\n allow_laminar : bool, optional\n Overrides the automatic transition into the laminar regime if this is\n False and returns as if laminar flow does not exist\n full_output : bool, optional\n If True, returns intermediate calculation values as\n well as Kv in the form of a dictionary containing 'Kv', 'Rev', 'choked',\n 'Y', 'FR', 'FP', 'xTP', and 'laminar'. Some may be None if they are\n not used in the calculation.\n\n Returns\n -------\n Kv : float\n Metric Kv valve flow coefficient (flow rate of water at a pressure drop\n of 1 bar) [m^3/hr]\n\n Notes\n -----\n It is possible to use this model without any diameters specified; in that\n case, turbulent flow is assumed. Choked flow can still be modeled. This is\n not recommended. All three diameters need to be None for this to work.\n `FL` and `Fd` are not used by the models when the diameters are not\n specified, but `xT` definitely is used by the model.\n\n When this model does not converge, the result is normally because of the\n specified delta P being less than that caused by the piping diameter\n changes.\n\n Examples\n --------\n From [1]_, matching example 3 for non-choked gas flow with attached\n fittings and a rotary, eccentric plug, flow-to-open control valve:\n\n >>> size_control_valve_g(T=433., MW=44.01, mu=1.4665E-4, gamma=1.30,\n ... Z=0.988, P1=680E3, P2=310E3, Q=38/36., D1=0.08, D2=0.1, d=0.05,\n ... FL=0.85, Fd=0.42, xT=0.60)\n 72.5866454539105\n\n From [1]_, roughly matching example 4 for a small flow trim sized tapered\n needle plug valve. Difference is 3% and explained by the difference in\n algorithms used.\n\n >>> size_control_valve_g(T=320., MW=39.95, mu=5.625E-5, gamma=1.67, Z=1.0,\n ... P1=2.8E5, P2=1.3E5, Q=0.46/3600., D1=0.015, D2=0.015, d=0.015, FL=0.98,\n ... Fd=0.07, xT=0.8)\n 0.016498765335995726\n\n References\n ----------\n .. [1] IEC 60534-2-1 / ISA-75.01.01-2007\n \"\"\"\n MAX_C_POSSIBLE = 1E40 # Quit iterations if C reaches this high\n # Pa to kPa, according to constants in standard\n P1, P2 = P1*1e-3, P2*1e-3\n Q = Q*3600. # m^3/s to m^3/hr, according to constants in standard\n # Convert dynamic viscosity to kinematic viscosity\n Vm = Z*R*T/(P1*1000)\n rho = MW*1e-3/Vm\n nu = mu/rho # kinematic viscosity used in standard\n\n dP = P1 - P2\n Fgamma = gamma/1.40\n x = dP/P1\n Y = max(1 - x/(3*Fgamma*xT), 2/3.)\n\n choked = is_choked_turbulent_g(x, Fgamma, xT)\n if choked and allow_choked:\n # Choked, and flow coefficient from eq 14a\n C = Q/(N9*P1*Y)*sqrt(MW*T*Z/xT/Fgamma)\n else:\n # Non-choked, and flow coefficient from eq 8a\n C = Q/(N9*P1*Y)*sqrt(MW*T*Z/x)\n\n\n if full_output: # numba: delete\n ans = {\"FP\": None, \"xTP\": None, \"FR\": None, \"choked\": choked, \"Y\": Y} # numba: delete\n\n if D1 is None and D2 is None and d is None:\n # Assume turbulent if no diameters are provided, no other calculations\n Rev = 1e5\n if full_output: # numba: delete\n ans[\"Rev\"] = None # numba: delete\n else:\n # m to mm, according to constants in standard\n if D1 is None or D2 is None or d is None:\n raise ValueError(\"If any diameter is specified, all three (D1, D2, d) must be specified\")\n D1, D2, d = D1*1000., D2*1000., d*1000. # Convert diameters to mm which is used in the standard\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=C)\n if full_output: # numba: delete\n ans[\"Rev\"] = Rev # numba: delete\n\n if (Rev > 10000 or not allow_laminar) and (D1 != d or D2 != d):\n # gas, using xTP and FLP\n FP = 1.\n MAX_ITER = 20\n\n def iterate_piping_coef_g(Ci, iterations):\n loss = loss_coefficient_piping(d, D1, D2)\n FP = 1.0/sqrt(1. + loss/N2*(Ci/d**2)**2)\n loss_upstream = loss_coefficient_piping(d, D1)\n xTP = xT/FP**2/(1 + xT*loss_upstream/N5*(Ci/d**2)**2)\n choked = is_choked_turbulent_g(x, Fgamma, xTP=xTP)\n if choked:\n # Choked flow with piping, equation 17a\n C = Q/(N9*FP*P1*Y)*sqrt(MW*T*Z/xTP/Fgamma)\n else:\n # Non-choked flow with piping, equation 11a\n C = Q/(N9*FP*P1*Y)*sqrt(MW*T*Z/x)\n if Ci/C < 0.99 and iterations < MAX_ITER and Ci < MAX_C_POSSIBLE:\n C = iterate_piping_coef_g(C, iterations+1)\n if full_output: # numba: delete\n ans[\"xTP\"] = xTP # numba: delete\n ans[\"FP\"] = FP # numba: delete\n ans[\"choked\"] = choked # numba: delete\n if MAX_ITER == iterations or Ci >= MAX_C_POSSIBLE: # numba: delete\n ans[\"warning\"] = \"Not converged in inner loop\" # numba: delete\n return C\n\n# def err_piping_coeff(Ci):\n# loss = loss_coefficient_piping(d, D1, D2)\n# FP = (1. + loss/N2*(Ci/d**2)**2)**-0.5\n# loss_upstream = loss_coefficient_piping(d, D1)\n# xTP = xT/FP**2/(1 + xT*loss_upstream/N5*(Ci/d**2)**2)\n# choked = is_choked_turbulent_g(x, Fgamma, xTP=xTP)\n# if choked:\n# # Choked flow with piping, equation 17a\n# C = Q/(N9*FP*P1*Y)*(MW*T*Z/xTP/Fgamma)**0.5\n# else:\n# # Non-choked flow with piping, equation 11a\n# C = Q/(N9*FP*P1*Y)*(MW*T*Z/x)**0.5\n# return C - Ci\n# import matplotlib.pyplot as plt\n# from fluids.numerics import linspace\n# Cs = linspace(C/50, C*50, 5000)\n# errs = [err_piping_coeff(C_test) for C_test in Cs]\n# plt.plot(Cs, errs)\n# plt.show()\n\n C = iterate_piping_coef_g(C, 0)\n elif Rev <= 10000 and allow_laminar:\n # Laminar;\n def iterate_piping_laminar_g(C):\n Ci = 1.3*C\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=Ci)\n if Ci/(d*d) > 0.016*N18:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=False)\n else:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=True)\n if C/FR >= Ci:\n Ci = iterate_piping_laminar_g(Ci)\n if full_output: # numba: delete\n ans[\"FR\"] = FR # numba: delete\n ans[\"Rev\"] = Rev # numba: delete\n return Ci\n C = iterate_piping_laminar_g(C)\n if full_output: # numba: delete\n ans[\"Kv\"] = C # numba: delete\n ans[\"laminar\"] = Rev <= 10000 # numba: delete\n ans[\"choked\"] = choked # numba: delete\n return ans # numba: delete\n return C\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 17543}, "tests/test_control_valve.py::171": {"resolved_imports": ["fluids/control_valve.py", "fluids/fittings.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "pytest", "size_control_valve_g", "size_control_valve_l"], "enclosing_function": "test_control_valve_size_l", "extracted_code": "# Source: fluids/control_valve.py\ndef size_control_valve_l(rho: float, Psat: float, Pc: float, mu: float, P1: float, P2: float, Q: float, D1: float | None=None, D2: float | None=None,\n d: float | None=None, FL: float=0.9, Fd: float=1, allow_choked: bool=True,\n allow_laminar: bool=True, full_output: bool=False) -> float | dict[str, bool | float | None] | dict[str, float | bool | str | None]:\n r\"\"\"Calculates flow coefficient of a control valve passing a liquid\n according to IEC 60534. Uses a large number of inputs in SI units. Note the\n return value is not standard SI. All parameters are required.\n This sizing model does not officially apply to liquid mixtures, slurries,\n non-Newtonian fluids, or liquid-solid conveyance systems. For details\n of the calculations, consult [1]_.\n\n Parameters\n ----------\n rho : float\n Density of the liquid at the inlet [kg/m^3]\n Psat : float\n Saturation pressure of the fluid at inlet temperature [Pa]\n Pc : float\n Critical pressure of the fluid [Pa]\n mu : float\n Viscosity of the fluid [Pa*s]\n P1 : float\n Inlet pressure of the fluid before valves and reducers [Pa]\n P2 : float\n Outlet pressure of the fluid after valves and reducers [Pa]\n Q : float\n Volumetric flow rate of the fluid [m^3/s]\n D1 : float, optional\n Diameter of the pipe before the valve [m]\n D2 : float, optional\n Diameter of the pipe after the valve [m]\n d : float, optional\n Diameter of the valve [m]\n FL : float, optional\n Liquid pressure recovery factor of a control valve without attached\n fittings (normally 0.8-0.9 at full open and decreasing as opened\n further to below 0.5; use default very cautiously!) []\n Fd : float, optional\n Valve style modifier (0.1 to 1; varies tremendously depending on the\n type of valve and position; do not use the default at all!) []\n allow_choked : bool, optional\n Overrides the automatic transition into the choked regime if this is\n False and returns as if choked flow does not exist\n allow_laminar : bool, optional\n Overrides the automatic transition into the laminar regime if this is\n False and returns as if laminar flow does not exist\n full_output : bool, optional\n If True, returns intermediate calculation values as\n well as Kv in the form of a dictionary containing 'Kv', 'Rev', 'choked',\n 'FL', 'FLP', 'FR', 'FP', and 'laminar'. Some may be None if they are\n not used in the calculation.\n\n Returns\n -------\n Kv : float\n Metric Kv valve flow coefficient (flow rate of water at a pressure drop\n of 1 bar) [m^3/hr]\n\n Notes\n -----\n It is possible to use this model without any diameters specified; in that\n case, turbulent flow is assumed. Choked flow can still be modeled. This is\n not recommended. All three diameters need to be None for this to work.\n `FL` and `Fd` are not used by the models when the diameters are not\n specified.\n\n Examples\n --------\n From [1]_, matching example 1 for a globe, parabolic plug,\n flow-to-open valve.\n\n >>> size_control_valve_l(rho=965.4, Psat=70.1E3, Pc=22120E3, mu=3.1472E-4,\n ... P1=680E3, P2=220E3, Q=0.1, D1=0.15, D2=0.15, d=0.15,\n ... FL=0.9, Fd=0.46)\n 164.9954763704956\n\n From [1]_, matching example 2 for a ball, segmented ball,\n flow-to-open valve.\n\n >>> size_control_valve_l(rho=965.4, Psat=70.1E3, Pc=22120E3, mu=3.1472E-4,\n ... P1=680E3, P2=220E3, Q=0.1, D1=0.1, D2=0.1, d=0.1,\n ... FL=0.6, Fd=0.98)\n 238.05817216710483\n\n References\n ----------\n .. [1] IEC 60534-2-1 / ISA-75.01.01-2007\n \"\"\"\n if full_output:\n ans: dict[str, bool | float | None] = {\"FLP\": None, \"FP\": None, \"FR\": None}\n # Pa to kPa, according to constants in standard\n P1, P2, Psat, Pc = P1/1000., P2/1000., Psat/1000., Pc/1000.\n Q = Q*3600. # m^3/s to m^3/hr, according to constants in standard\n nu = mu/rho # kinematic viscosity used in standard\n MAX_C_POSSIBLE = 1E40 # Quit iterations if C reaches this high\n\n dP = P1 - P2\n FF = FF_critical_pressure_ratio_l(Psat=Psat, Pc=Pc)\n choked = is_choked_turbulent_l(dP=dP, P1=P1, Psat=Psat, FF=FF, FL=FL)\n if choked and allow_choked:\n # Choked flow, equation 3\n C = Q/N1/FL*sqrt(rho/rho0/(P1 - FF*Psat))\n else:\n # non-choked flow, eq 1\n C = Q/N1*sqrt(rho/rho0/dP)\n if D1 is None and D2 is None and d is None:\n # Assume turbulent if no diameters are provided, no other calculations\n Rev = 1e5\n else:\n # m to mm, according to constants in standard\n if D1 is None or D2 is None or d is None:\n raise ValueError(\"If any diameter is specified, all three (D1, D2, d) must be specified\")\n D1, D2, d = D1*1000., D2*1000., d*1000.\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=C)\n # normal calculation path\n if (Rev > 10000 or not allow_laminar) and (D1 != d or D2 != d):\n # liquid, using Fp and FLP\n FP = 1.0\n Ci = C\n MAX_ITER = 20\n def iterate_piping_turbulent_l(Ci, iterations):\n loss = loss_coefficient_piping(d, D1, D2)\n FP = 1.0/sqrt(1 + loss/N2*(Ci/d**2)**2)\n if d > D1:\n loss_upstream = 0.0\n else:\n loss_upstream = loss_coefficient_piping(d, D1)\n\n FLP = FL*1.0/sqrt(1 + FL**2/N2*loss_upstream*(Ci/d**2)**2)\n choked = is_choked_turbulent_l(dP, P1, Psat, FF, FLP=FLP, FP=FP)\n if choked:\n # Choked flow with piping, equation 4\n C = Q/N1/FLP*sqrt(rho/rho0/(P1-FF*Psat))\n else:\n # Non-Choked flow with piping, equation 5\n C = Q/N1/FP*sqrt(rho/rho0/dP)\n if Ci/C < 0.99 and iterations < MAX_ITER and Ci < MAX_C_POSSIBLE:\n C = iterate_piping_turbulent_l(C, iterations+1)\n if MAX_ITER == iterations or Ci >= MAX_C_POSSIBLE:\n ans[\"warning\"] = \"Not converged in inner loop\"\n if full_output:\n ans[\"FLP\"] = FLP\n ans[\"FP\"] = FP\n return C\n\n C = iterate_piping_turbulent_l(Ci, 0)\n elif Rev <= 10000 and allow_laminar:\n # Laminar\n def iterate_piping_laminar_l(C):\n Ci = 1.3*C\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=Ci)\n if Ci/(d*d) > 0.016*N18:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=False)\n else:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=True)\n if C/FR >= Ci:\n Ci = iterate_piping_laminar_l(Ci) # pragma: no cover\n\n if full_output:\n ans[\"Rev\"] = Rev\n ans[\"FR\"] = FR\n return Ci\n C = iterate_piping_laminar_l(C)\n if full_output:\n ans[\"FF\"] = FF\n ans[\"choked\"] = choked\n ans[\"Kv\"] = C\n ans[\"laminar\"] = Rev <= 10000\n\n # For the laminar case this is already set and needs to not be overwritten\n if \"Rev\" not in ans:\n ans[\"Rev\"] = Rev\n return ans\n else:\n# return C, choked, laminar, FF, FR, Rev, FP, FLP, warning\n return C\n\ndef size_control_valve_g(T: float, MW: float, mu: float, gamma: float, Z: float, P1: float, P2: float, Q: float, D1: float | None=None, D2: float | None=None,\n d: float | None=None, FL: float=0.9, Fd: float=1, xT: float=0.7, allow_choked: bool=True,\n allow_laminar: bool=True, full_output: bool=False) -> float | dict[str, bool | float | None] | dict[str, float | bool | str | None]:\n r\"\"\"Calculates flow coefficient of a control valve passing a gas\n according to IEC 60534. Uses a large number of inputs in SI units. Note the\n return value is not standard SI. All parameters are required. For details\n of the calculations, consult [1]_. Note the inlet gas flow conditions.\n\n Parameters\n ----------\n T : float\n Temperature of the gas at the inlet [K]\n MW : float\n Molecular weight of the gas [g/mol]\n mu : float\n Viscosity of the fluid at inlet conditions [Pa*s]\n gamma : float\n Specific heat capacity ratio [-]\n Z : float\n Compressibility factor at inlet conditions, [-]\n P1 : float\n Inlet pressure of the gas before valves and reducers [Pa]\n P2 : float\n Outlet pressure of the gas after valves and reducers [Pa]\n Q : float\n Volumetric flow rate of the gas at *273.15 K* and 1 atm specifically\n [m^3/s]\n D1 : float, optional\n Diameter of the pipe before the valve [m]\n D2 : float, optional\n Diameter of the pipe after the valve [m]\n d : float, optional\n Diameter of the valve [m]\n FL : float, optional\n Liquid pressure recovery factor of a control valve without attached\n fittings (normally 0.8-0.9 at full open and decreasing as opened\n further to below 0.5; use default very cautiously!) []\n Fd : float, optional\n Valve style modifier (0.1 to 1; varies tremendously depending on the\n type of valve and position; do not use the default at all!) []\n xT : float, optional\n Pressure difference ratio factor of a valve without fittings at choked\n flow (increasing to 0.9 or higher as the valve is closed further and\n decreasing to 0.1 or lower as the valve is opened further; use default\n very cautiously!) [-]\n allow_choked : bool, optional\n Overrides the automatic transition into the choked regime if this is\n False and returns as if choked flow does not exist\n allow_laminar : bool, optional\n Overrides the automatic transition into the laminar regime if this is\n False and returns as if laminar flow does not exist\n full_output : bool, optional\n If True, returns intermediate calculation values as\n well as Kv in the form of a dictionary containing 'Kv', 'Rev', 'choked',\n 'Y', 'FR', 'FP', 'xTP', and 'laminar'. Some may be None if they are\n not used in the calculation.\n\n Returns\n -------\n Kv : float\n Metric Kv valve flow coefficient (flow rate of water at a pressure drop\n of 1 bar) [m^3/hr]\n\n Notes\n -----\n It is possible to use this model without any diameters specified; in that\n case, turbulent flow is assumed. Choked flow can still be modeled. This is\n not recommended. All three diameters need to be None for this to work.\n `FL` and `Fd` are not used by the models when the diameters are not\n specified, but `xT` definitely is used by the model.\n\n When this model does not converge, the result is normally because of the\n specified delta P being less than that caused by the piping diameter\n changes.\n\n Examples\n --------\n From [1]_, matching example 3 for non-choked gas flow with attached\n fittings and a rotary, eccentric plug, flow-to-open control valve:\n\n >>> size_control_valve_g(T=433., MW=44.01, mu=1.4665E-4, gamma=1.30,\n ... Z=0.988, P1=680E3, P2=310E3, Q=38/36., D1=0.08, D2=0.1, d=0.05,\n ... FL=0.85, Fd=0.42, xT=0.60)\n 72.5866454539105\n\n From [1]_, roughly matching example 4 for a small flow trim sized tapered\n needle plug valve. Difference is 3% and explained by the difference in\n algorithms used.\n\n >>> size_control_valve_g(T=320., MW=39.95, mu=5.625E-5, gamma=1.67, Z=1.0,\n ... P1=2.8E5, P2=1.3E5, Q=0.46/3600., D1=0.015, D2=0.015, d=0.015, FL=0.98,\n ... Fd=0.07, xT=0.8)\n 0.016498765335995726\n\n References\n ----------\n .. [1] IEC 60534-2-1 / ISA-75.01.01-2007\n \"\"\"\n MAX_C_POSSIBLE = 1E40 # Quit iterations if C reaches this high\n # Pa to kPa, according to constants in standard\n P1, P2 = P1*1e-3, P2*1e-3\n Q = Q*3600. # m^3/s to m^3/hr, according to constants in standard\n # Convert dynamic viscosity to kinematic viscosity\n Vm = Z*R*T/(P1*1000)\n rho = MW*1e-3/Vm\n nu = mu/rho # kinematic viscosity used in standard\n\n dP = P1 - P2\n Fgamma = gamma/1.40\n x = dP/P1\n Y = max(1 - x/(3*Fgamma*xT), 2/3.)\n\n choked = is_choked_turbulent_g(x, Fgamma, xT)\n if choked and allow_choked:\n # Choked, and flow coefficient from eq 14a\n C = Q/(N9*P1*Y)*sqrt(MW*T*Z/xT/Fgamma)\n else:\n # Non-choked, and flow coefficient from eq 8a\n C = Q/(N9*P1*Y)*sqrt(MW*T*Z/x)\n\n\n if full_output: # numba: delete\n ans = {\"FP\": None, \"xTP\": None, \"FR\": None, \"choked\": choked, \"Y\": Y} # numba: delete\n\n if D1 is None and D2 is None and d is None:\n # Assume turbulent if no diameters are provided, no other calculations\n Rev = 1e5\n if full_output: # numba: delete\n ans[\"Rev\"] = None # numba: delete\n else:\n # m to mm, according to constants in standard\n if D1 is None or D2 is None or d is None:\n raise ValueError(\"If any diameter is specified, all three (D1, D2, d) must be specified\")\n D1, D2, d = D1*1000., D2*1000., d*1000. # Convert diameters to mm which is used in the standard\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=C)\n if full_output: # numba: delete\n ans[\"Rev\"] = Rev # numba: delete\n\n if (Rev > 10000 or not allow_laminar) and (D1 != d or D2 != d):\n # gas, using xTP and FLP\n FP = 1.\n MAX_ITER = 20\n\n def iterate_piping_coef_g(Ci, iterations):\n loss = loss_coefficient_piping(d, D1, D2)\n FP = 1.0/sqrt(1. + loss/N2*(Ci/d**2)**2)\n loss_upstream = loss_coefficient_piping(d, D1)\n xTP = xT/FP**2/(1 + xT*loss_upstream/N5*(Ci/d**2)**2)\n choked = is_choked_turbulent_g(x, Fgamma, xTP=xTP)\n if choked:\n # Choked flow with piping, equation 17a\n C = Q/(N9*FP*P1*Y)*sqrt(MW*T*Z/xTP/Fgamma)\n else:\n # Non-choked flow with piping, equation 11a\n C = Q/(N9*FP*P1*Y)*sqrt(MW*T*Z/x)\n if Ci/C < 0.99 and iterations < MAX_ITER and Ci < MAX_C_POSSIBLE:\n C = iterate_piping_coef_g(C, iterations+1)\n if full_output: # numba: delete\n ans[\"xTP\"] = xTP # numba: delete\n ans[\"FP\"] = FP # numba: delete\n ans[\"choked\"] = choked # numba: delete\n if MAX_ITER == iterations or Ci >= MAX_C_POSSIBLE: # numba: delete\n ans[\"warning\"] = \"Not converged in inner loop\" # numba: delete\n return C\n\n# def err_piping_coeff(Ci):\n# loss = loss_coefficient_piping(d, D1, D2)\n# FP = (1. + loss/N2*(Ci/d**2)**2)**-0.5\n# loss_upstream = loss_coefficient_piping(d, D1)\n# xTP = xT/FP**2/(1 + xT*loss_upstream/N5*(Ci/d**2)**2)\n# choked = is_choked_turbulent_g(x, Fgamma, xTP=xTP)\n# if choked:\n# # Choked flow with piping, equation 17a\n# C = Q/(N9*FP*P1*Y)*(MW*T*Z/xTP/Fgamma)**0.5\n# else:\n# # Non-choked flow with piping, equation 11a\n# C = Q/(N9*FP*P1*Y)*(MW*T*Z/x)**0.5\n# return C - Ci\n# import matplotlib.pyplot as plt\n# from fluids.numerics import linspace\n# Cs = linspace(C/50, C*50, 5000)\n# errs = [err_piping_coeff(C_test) for C_test in Cs]\n# plt.plot(Cs, errs)\n# plt.show()\n\n C = iterate_piping_coef_g(C, 0)\n elif Rev <= 10000 and allow_laminar:\n # Laminar;\n def iterate_piping_laminar_g(C):\n Ci = 1.3*C\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=Ci)\n if Ci/(d*d) > 0.016*N18:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=False)\n else:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=True)\n if C/FR >= Ci:\n Ci = iterate_piping_laminar_g(Ci)\n if full_output: # numba: delete\n ans[\"FR\"] = FR # numba: delete\n ans[\"Rev\"] = Rev # numba: delete\n return Ci\n C = iterate_piping_laminar_g(C)\n if full_output: # numba: delete\n ans[\"Kv\"] = C # numba: delete\n ans[\"laminar\"] = Rev <= 10000 # numba: delete\n ans[\"choked\"] = choked # numba: delete\n return ans # numba: delete\n return C\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 17543}, "tests/test_fittings.py::136": {"resolved_imports": ["fluids/fittings.py", "fluids/constants/__init__.py", "fluids/core.py", "fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["Darby", "Darby3K", "Hooper", "Hooper2K", "assert_close", "assert_close1d", "change_K_basis", "contraction_beveled", "diffuser_curved", "diffuser_pipe_reducer", "entrance_beveled_orifice", "exit_normal", "helix", "pytest", "spiral"], "enclosing_function": "test_fittings", "extracted_code": "# Source: fluids/fittings.py\ndef change_K_basis(K1: float, D1: float, D2: float) -> float:\n r\"\"\"Converts a loss coefficient `K1` from the basis of one diameter `D1`\n to another diameter, `D2`. This is necessary when dealing with pipelines\n of changing diameter.\n\n .. math::\n K_2 = K_1\\frac{D_2^4}{D_1^4} = K_1 \\frac{A_2^2}{A_1^2}\n\n Parameters\n ----------\n K1 : float\n Loss coefficient with respect to diameter `D`, [-]\n D1 : float\n Diameter of pipe for which `K1` has been calculated, [m]\n D2 : float\n Diameter of pipe for which `K2` will be calculated, [m]\n\n Returns\n -------\n K2 : float\n Loss coefficient with respect to the second diameter, [-]\n\n Notes\n -----\n This expression is shown in [1]_ and can easily be derived:\n\n .. math::\n \\frac{\\rho V_{1}^{2}}{2} \\cdot K_{1} = \\frac{\\rho V_{2}^{2} }{2}\n \\cdot K_{2}\n\n Substitute velocities for flow rate divided by area:\n\n .. math::\n \\frac{8 K_{1} Q^{2} \\rho}{\\pi^{2} D_{1}^{4}} = \\frac{8 K_{2} Q^{2}\n \\rho}{\\pi^{2} D_{2}^{4}}\n\n From here, simplification and rearrangement is all that is required.\n\n Examples\n --------\n >>> change_K_basis(K1=32.68875692997804, D1=.01, D2=.02)\n 523.020110879\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n \"\"\"\n r = D2/D1\n r *= r\n return K1*r*r\n\ndef entrance_beveled_orifice(Di: float, Do: float, l: float, angle: float) -> float:\n r\"\"\"Returns loss coefficient for a beveled or chamfered orifice entrance to\n a pipe flush with the wall of a reservoir, as shown in [1]_.\n\n .. math::\n K = 0.0696\\left(1 - C_b\\frac{l}{D_o}\\right)\\lambda^2 + \\left(\\lambda\n -\\left(\\frac{D_o}{D_i}\\right)^2\\right)^2\n\n .. math::\n \\lambda = 1 + 0.622\\left[1-C_b\\left(\\frac{l}{D_o}\\right)^{\\frac{1-\n (l/D_o)^{0.25}}{2}}\\right]\n\n .. math::\n C_b = \\left(1 - \\frac{\\Psi}{90}\\right)\\left(\\frac{\\Psi}{90}\n \\right)^{\\frac{1}{1+l/D_o}}\n\n .. figure:: fittings/flush_mounted_beveled_orifice_entrance.png\n :scale: 30 %\n :alt: Beveled orifice entrance mounted straight; after [1]_\n\n Parameters\n ----------\n Di : float\n Inside diameter of pipe, [m]\n Do : float\n Inside diameter of orifice, [m]\n l : float\n Length of bevel measured parallel to the pipe length, [m]\n angle : float\n Angle of bevel with respect to the pipe length, [degrees]\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Examples\n --------\n >>> entrance_beveled_orifice(Di=0.1, Do=.07, l=0.003, angle=45)\n 1.2987552913818574\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n \"\"\"\n Cb = (1-angle/90.)*(angle/90.)**(1./(1 + l/Do ))\n lbd = 1 + 0.622*(1 - Cb*(l/Do)**((1 - sqrt(sqrt(l/Do)))/2.))\n return 0.0696*(1 - Cb*l/Do)*lbd**2 + (lbd - (Do/Di)**2)**2\n\ndef exit_normal() -> float:\n r\"\"\"Returns loss coefficient for any exit to a pipe\n as shown in [1]_ and in other sources.\n\n .. math::\n K = 1\n\n .. figure:: fittings/flush_mounted_exit.png\n :scale: 28 %\n :alt: Exit from a flush mounted wall; after [1]_\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n It has been found on occasion that K = 2.0 for laminar flow, and ranges\n from about 1.04 to 1.10 for turbulent flow.\n\n Examples\n --------\n >>> exit_normal()\n 1.0\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n \"\"\"\n return 1.0\n\ndef helix(Di: float, rs: float, pitch: float, N: int, fd: float) -> float:\n r\"\"\"Returns loss coefficient for any size constant-pitch helix\n as shown in [1]_. Has applications in immersed coils in tanks.\n\n .. math::\n K = N \\left[f\\frac{\\sqrt{(2\\pi r)^2 + p^2}}{d} + 0.20 + 4.8 f\\right]\n\n Parameters\n ----------\n Di : float\n Inside diameter of pipe, [m]\n rs : float\n Radius of spiral, [m]\n pitch : float\n Distance between two subsequent coil centers, [m]\n N : float\n Number of coils in the helix [-]\n fd : float\n Darcy friction factor [-]\n\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n Formulation based on peak secondary flow as in two 180 degree bends per\n coil. Flow separation ignored. No f, Re, geometry limitations.\n Source not compared against others.\n\n Examples\n --------\n >>> helix(Di=0.01, rs=0.1, pitch=.03, N=10, fd=.0185)\n 14.525134924495514\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n \"\"\"\n return N*(fd*sqrt((2*pi*rs)**2 + pitch**2)/Di + 0.20 + 4.8*fd)\n\ndef spiral(Di: float, rmax: float, rmin: float, pitch: float, fd: float) -> float:\n r\"\"\"Returns loss coefficient for any size constant-pitch spiral\n as shown in [1]_. Has applications in immersed coils in tanks.\n\n .. math::\n K = \\frac{r_{max} - r_{min}}{p} \\left[ f\\pi\\left(\\frac{r_{max}\n +r_{min}}{d}\\right) + 0.20 + 4.8f\\right]\n + \\frac{13.2f}{(r_{min}/d)^2}\n\n Parameters\n ----------\n Di : float\n Inside diameter of pipe, [m]\n rmax : float\n Radius of spiral at extremity, [m]\n rmin : float\n Radius of spiral at end near center, [m]\n pitch : float\n Distance between two subsequent coil centers, [m]\n fd : float\n Darcy friction factor [-]\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n Source not compared against others.\n\n Examples\n --------\n >>> spiral(Di=0.01, rmax=.1, rmin=.02, pitch=.01, fd=0.0185)\n 7.950918552775473\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n \"\"\"\n return (rmax-rmin)/pitch*(fd*pi*(rmax+rmin)/Di + 0.20 + 4.8*fd) + 13.2*fd/(rmin/Di)**2\n\ndef contraction_beveled(Di1: float, Di2: float, l: float, angle: float) -> float:\n r\"\"\"Returns loss coefficient for any sharp beveled pipe contraction\n as shown in [1]_.\n\n .. math::\n K = 0.0696[1+C_B(\\sin(\\alpha/2)-1)](1-\\beta^5)\\lambda^2 + (\\lambda-1)^2\n\n .. math::\n \\lambda = 1 + 0.622\\left[1+C_B\\left(\\left(\\frac{\\alpha}{180}\n \\right)^{0.8}-1\\right)\\right](1-0.215\\beta^2-0.785\\beta^5)\n\n .. math::\n C_B = \\frac{l}{d_2}\\frac{2\\beta\\tan(\\alpha/2)}{1-\\beta}\n\n .. math::\n \\beta = d_2/d_1\n\n .. figure:: fittings/contraction_beveled.png\n :scale: 30 %\n :alt: contraction beveled; after [1]_\n\n Parameters\n ----------\n Di1 : float\n Inside diameter of original pipe, [m]\n Di2 : float\n Inside diameter of following pipe, [m]\n l : float\n Length of the bevel along the pipe axis, [m]\n angle : float\n Angle of bevel, [degrees]\n\n Returns\n -------\n K : float\n Loss coefficient in terms of the following pipe [-]\n\n Notes\n -----\n\n Examples\n --------\n >>> contraction_beveled(Di1=0.5, Di2=0.1, l=.7*.1, angle=120)\n 0.40946469413070485\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n \"\"\"\n angle = radians(angle)\n beta = Di2/Di1\n CB = l/Di2*2.0*beta*tan(0.5*angle)/(1.0 - beta)\n beta2 = beta*beta\n beta5 = beta2*beta2*beta\n lbd = 1.0 + 0.622*(1.0 + CB*((angle/pi)**0.8 - 1.0))*(1.0 - 0.215*beta2 - 0.785*beta5)\n return 0.0696*(1.0 + CB*(sin(0.5*angle) - 1.0))*(1.0 - beta5)*lbd*lbd + (lbd-1.0)**2\n\ndef diffuser_curved(Di1: float, Di2: float, l: float) -> float:\n r\"\"\"Returns loss coefficient for any curved wall pipe expansion\n as shown in [1]_.\n\n .. math::\n K_1 = \\phi(1.43-1.3\\beta^2)(1-\\beta^2)^2\n\n .. math::\n \\phi = 1.01 - 0.624\\frac{l}{d_1} + 0.30\\left(\\frac{l}{d_1}\\right)^2\n - 0.074\\left(\\frac{l}{d_1}\\right)^3 + 0.0070\\left(\\frac{l}{d_1}\\right)^4\n\n .. figure:: fittings/curved_wall_diffuser.png\n :scale: 25 %\n :alt: diffuser curved; after [1]_\n\n Parameters\n ----------\n Di1 : float\n Inside diameter of original pipe (smaller), [m]\n Di2 : float\n Inside diameter of following pipe (larger), [m]\n l : float\n Length of the curve along the pipe axis, [m]\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n Beta^2 should be between 0.1 and 0.9.\n A small mismatch between tabulated values of this function in table 11.3\n is observed with the equation presented.\n\n Examples\n --------\n >>> diffuser_curved(Di1=.25**0.5, Di2=1., l=2.)\n 0.2299781250000002\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n \"\"\"\n beta = Di1/Di2\n phi = 1.01 - 0.624*l/Di1 + 0.30*(l/Di1)**2 - 0.074*(l/Di1)**3 + 0.0070*(l/Di1)**4\n return phi*(1.43 - 1.3*beta**2)*(1 - beta**2)**2\n\ndef diffuser_pipe_reducer(Di1: float, Di2: float, l: float, fd1: float, fd2: float | None=None) -> float:\n r\"\"\"Returns loss coefficient for any pipe reducer pipe expansion\n as shown in [1]. This is an approximate formula.\n\n .. math::\n K_f = f_1\\frac{0.20l}{d_1} + \\frac{f_1(1-\\beta)}{8\\sin(\\alpha/2)}\n + f_2\\frac{0.20l}{d_2}\\beta^4\n\n .. math::\n \\alpha = 2\\tan^{-1}\\left(\\frac{d_1-d_2}{1.20l}\\right)\n\n Parameters\n ----------\n Di1 : float\n Inside diameter of original pipe (smaller), [m]\n Di2 : float\n Inside diameter of following pipe (larger), [m]\n l : float\n Length of the pipe reducer along the pipe axis, [m]\n fd1 : float\n Darcy friction factor at inlet diameter [-]\n fd2 : float\n Darcy friction factor at outlet diameter, optional [-]\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n Industry lack of standardization prevents better formulas from being\n developed. Add 15% if the reducer is eccentric.\n Friction factor at outlet will be assumed the same as at inlet if not specified.\n\n Doubt about the validity of this equation is raised.\n\n Examples\n --------\n >>> diffuser_pipe_reducer(Di1=.5, Di2=.75, l=1.5, fd1=0.07)\n 0.06873244301714816\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n \"\"\"\n if fd2 is None:\n fd2 = fd1\n beta = Di1/Di2\n angle = -2*atan((Di1-Di2)/1.20/l)\n K = fd1*0.20*l/Di1 + fd1*(1-beta)/8./sin(angle/2) + fd2*0.20*l/Di2*beta**4\n return K\n\nDarby = {}\n\ndef Darby3K(NPS: float | None=None, Re: float | None=None, name: str | None=None, K1: float | None=None, Ki: float | None=None, Kd: float | None=None, Di: float | None=None) -> float:\n r\"\"\"Returns loss coefficient for any various fittings, depending\n on the name input. Alternatively, the Darby constants K1, Ki and Kd\n may be provided and used instead. Source of data is [1]_.\n Reviews of this model are favorable.\n\n .. math::\n K_f = \\frac{K_1}{Re} + K_i\\left(1 + \\frac{K_d}{D_{\\text{NPS}}^{0.3}}\n \\right)\n\n Note this model uses nominal pipe diameter in inches.\n\n Parameters\n ----------\n NPS : float\n Nominal diameter of the pipe, [in]\n Re : float\n Reynolds number, [-]\n name : str\n String from Darby dict representing a fitting\n K1 : float\n K1 parameter of Darby model, optional [-]\n Ki : float\n Ki parameter of Darby model, optional [-]\n Kd : float\n Kd parameter of Darby model, optional [in]\n Di : float\n If specified, the NPS will be found by interpolating linearly (with\n extrapolation) along the schedule 40 diameters and NPSs;\n this will supersede NPS if it is specified, [m]\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n Also described in Albright's Handbook and Ludwig's Applied Process Design.\n Relatively uncommon to see it used.\n\n The possibility of combining these methods with those above are attractive.\n\n Examples\n --------\n >>> Darby3K(NPS=2., Re=10000., name='Valve, Angle valve, 45°, full line size, β = 1')\n 1.1572523963562356\n >>> Darby3K(Di=.05248, Re=10000., name='Valve, Angle valve, 45°, full line size, β = 1')\n 1.1572523963562356\n >>> Darby3K(NPS=12., Re=10000., K1=950, Ki=0.25, Kd=4)\n 0.819510280626355\n\n References\n ----------\n .. [1] Silverberg, Peter, and Ron Darby. \"Correlate Pressure Drops through\n Fittings: Three Constants Accurately Calculate Flow through Elbows,\n Valves and Tees.\" Chemical Engineering 106, no. 7 (July 1999): 101.\n .. [2] Silverberg, Peter. \"Correlate Pressure Drops Through Fittings.\"\n Chemical Engineering 108, no. 4 (April 2001): 127,129-130.\n \"\"\"\n if Di is not None:\n NPS = interp(Di*1000.0, S40i, NPS40, extrapolate=True)\n if name is not None:\n K1 = None\n if name in Darby: # NUMBA: DELETE\n K1, Ki, Kd = Darby[name] # NUMBA: DELETE\n if K1 is None:\n try:\n K1, Ki, Kd = Darby_values[Darby_keys.index(name)]\n except:\n raise ValueError(\"Name of fitting is not in database\")\n elif K1 is not None and Ki is not None and Kd is not None:\n pass\n else:\n raise ValueError(\"Name of fitting or constants are required\")\n if NPS is None or Re is None or K1 is None or Ki is None or Kd is None:\n raise ValueError(\"NPS, Re, and K constants must be set\")\n return K1/Re + Ki*(1. + Kd*NPS**-0.3)\n\nHooper = {}\n\ndef Hooper2K(Di: float, Re: float, name: str | None=None, K1: float | None=None, Kinfty: float | None=None) -> float:\n r\"\"\"Returns loss coefficient for any various fittings, depending\n on the name input. Alternatively, the Hooper constants K1, Kinfty\n may be provided and used instead. Source of data is [1]_.\n Reviews of this model are less favorable than the Darby method\n but superior to the constant-K method.\n\n .. math::\n K = \\frac{K_1}{Re} + K_\\infty\\left(1 + \\frac{1\\text{ inch}}{D_{in}}\\right)\n\n **Note this model uses actual inside pipe diameter in inches.**\n\n Parameters\n ----------\n Di : float\n Actual inside diameter of the pipe, [in]\n Re : float\n Reynolds number, [-]\n name : str, optional\n String from Hooper dict representing a fitting\n K1 : float, optional\n K1 parameter of Hooper model, optional [-]\n Kinfty : float, optional\n Kinfty parameter of Hooper model, optional [-]\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n Also described in Ludwig's Applied Process Design.\n Relatively uncommon to see it used.\n No actual example found.\n\n Examples\n --------\n >>> Hooper2K(Di=2., Re=10000., name='Valve, Globe, Standard')\n 6.15\n >>> Hooper2K(Di=2., Re=10000., K1=900, Kinfty=4)\n 6.09\n\n References\n ----------\n .. [1] Hooper, W. B., \"The 2-K Method Predicts Head Losses in Pipe\n Fittings,\" Chem. Eng., p. 97, Aug. 24 (1981).\n .. [2] Hooper, William B. \"Calculate Head Loss Caused by Change in Pipe\n Size.\" Chemical Engineering 95, no. 16 (November 7, 1988): 89.\n .. [3] Kayode Coker. Ludwig's Applied Process Design for Chemical and\n Petrochemical Plants. 4E. Amsterdam ; Boston: Gulf Professional\n Publishing, 2007.\n \"\"\"\n if name is not None:\n K1 = None\n if name in Hooper: # NUMBA: DELETE\n K1, Kinfty = Hooper[name] # NUMBA: DELETE\n if K1 is None:\n try:\n K1, Kinfty = Hooper_values[Hooper_keys.index(name)]\n except:\n raise ValueError(\"Name of fitting is not in database\")\n elif K1 is not None and Kinfty is not None:\n pass\n else:\n raise ValueError(\"Name of fitting or constants are required\")\n if K1 is None or Kinfty is None:\n raise ValueError(\"K1 and Kinfty must be set\")\n return K1/Re + Kinfty*(1. + 1./Di)\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 17500}, "tests/test_flow_meter.py::134": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/flow_meter.py", "fluids/numerics/__init__.py"], "used_names": ["C_Reader_Harris_Gallagher", "assert_close", "pytest"], "enclosing_function": "test_C_Reader_Harris_Gallagher", "extracted_code": "# Source: fluids/flow_meter.py\ndef C_Reader_Harris_Gallagher(D: float, Do: float, rho: float, mu: float, m: float, taps: str=\"corner\") -> float:\n r\"\"\"Calculates the coefficient of discharge of the orifice based on the\n geometry of the plate, measured pressures of the orifice, mass flow rate\n through the orifice, and the density and viscosity of the fluid.\n\n .. math::\n C = 0.5961 + 0.0261\\beta^2 - 0.216\\beta^8 + 0.000521\\left(\\frac{\n 10^6\\beta}{Re_D}\\right)^{0.7}\\\\\n + (0.0188 + 0.0063A)\\beta^{3.5} \\left(\\frac{10^6}{Re_D}\\right)^{0.3} \\\\\n +(0.043 + 0.080\\exp(-10L_1) -0.123\\exp(-7L_1))(1-0.11A)\\frac{\\beta^4}\n {1-\\beta^4} \\\\\n - 0.031(M_2' - 0.8M_2'^{1.1})\\beta^{1.3}\n\n .. math::\n M_2' = \\frac{2L_2'}{1-\\beta}\n\n .. math::\n A = \\left(\\frac{19000\\beta}{Re_{D}}\\right)^{0.8}\n\n .. math::\n Re_D = \\frac{\\rho v D}{\\mu}\n\n\n If D < 71.12 mm (2.8 in.) (Note this is a continuous addition; there is no\n discontinuity):\n\n .. math::\n C += 0.11(0.75-\\beta)\\left(2.8-\\frac{D}{0.0254}\\right)\n\n If the orifice has corner taps:\n\n .. math::\n L_1 = L_2' = 0\n\n If the orifice has D and D/2 taps:\n\n .. math::\n L_1 = 1\n\n .. math::\n L_2' = 0.47\n\n If the orifice has Flange taps:\n\n .. math::\n L_1 = L_2' = \\frac{0.0254}{D}\n\n Parameters\n ----------\n D : float\n Upstream internal pipe diameter, [m]\n Do : float\n Diameter of orifice at flow conditions, [m]\n rho : float\n Density of fluid at `P1`, [kg/m^3]\n mu : float\n Viscosity of fluid at `P1`, [Pa*s]\n m : float\n Mass flow rate of fluid through the orifice, [kg/s]\n taps : str\n The orientation of the taps; one of 'corner', 'flange', 'D', or 'D/2',\n [-]\n\n Returns\n -------\n C : float\n Coefficient of discharge of the orifice, [-]\n\n Notes\n -----\n The following limits apply to the orifice plate standard [1]_:\n\n The measured pressure difference for the orifice plate should be under\n 250 kPa.\n\n There are roughness limits as well; the roughness should be under 6\n micrometers, although there are many more conditions to that given in [1]_.\n\n For orifice plates with D and D/2 or corner pressure taps:\n\n * Orifice bore diameter must be larger than 12.5 mm (0.5 inches)\n * Pipe diameter between 50 mm and 1 m (2 to 40 inches)\n * Beta between 0.1 and 0.75 inclusive\n * Reynolds number larger than 5000 (for :math:`0.10 \\le \\beta \\le 0.56`)\n or for :math:`\\beta \\ge 0.56, Re_D \\ge 16000\\beta^2`\n\n For orifice plates with flange pressure taps:\n\n * Orifice bore diameter must be larger than 12.5 mm (0.5 inches)\n * Pipe diameter between 50 mm and 1 m (2 to 40 inches)\n * Beta between 0.1 and 0.75 inclusive\n * Reynolds number larger than 5000 and also larger than\n :math:`170000\\beta^2 D`.\n\n This is also presented in Crane's TP410 (2009) publication, whereas the\n 1999 and 1982 editions showed only a graph for discharge coefficients.\n\n Examples\n --------\n >>> C_Reader_Harris_Gallagher(D=0.07391, Do=0.0222, rho=1.165, mu=1.85E-5,\n ... m=0.12, taps='flange')\n 0.5990326277163659\n\n References\n ----------\n .. [1] American Society of Mechanical Engineers. Mfc-3M-2004 Measurement\n Of Fluid Flow In Pipes Using Orifice, Nozzle, And Venturi. ASME, 2001.\n .. [2] ISO 5167-2:2003 - Measurement of Fluid Flow by Means of Pressure\n Differential Devices Inserted in Circular Cross-Section Conduits Running\n Full -- Part 2: Orifice Plates.\n .. [3] Reader-Harris, M. J., \"The Equation for the Expansibility Factor for\n Orifice Plates,\" Proceedings of FLOMEKO 1998, Lund, Sweden, 1998:\n 209-214.\n .. [4] Reader-Harris, Michael. Orifice Plates and Venturi Tubes. Springer,\n 2015.\n \"\"\"\n A_pipe = 0.25*pi*D*D\n v = m/(A_pipe*rho)\n Re_D = rho*v*D/mu\n Re_D_inv = 1.0/Re_D\n\n beta = Do/D\n if taps == \"corner\":\n L1, L2_prime = 0.0, 0.0\n elif taps == \"flange\":\n L1 = L2_prime = 0.0254/D\n elif taps in (\"D\", \"D/2\", ORIFICE_D_AND_D_2_TAPS):\n L1 = 1.0\n L2_prime = 0.47\n else:\n raise ValueError(\"Unsupported tap location\")\n\n beta2 = beta*beta\n beta4 = beta2*beta2\n beta8 = beta4*beta4\n\n A = 2648.5177066967326*(beta*Re_D_inv)**0.8 # 19000.0^0.8 = 2648.51....\n M2_prime = 2.0*L2_prime/(1.0 - beta)\n\n # These two exps\n expnL1 = exp(-L1)\n expnL2 = expnL1*expnL1\n expnL3 = expnL1*expnL2\n delta_C_upstream = ((0.043 + expnL3*expnL2*expnL2*(0.080*expnL3 - 0.123))\n *(1.0 - 0.11*A)*beta4/(1.0 - beta4))\n\n # The max part is not in the ISO standard\n t1 = log10(3700.*Re_D_inv)\n if t1 < 0.0:\n t1 = 0.0\n delta_C_downstream = (-0.031*(M2_prime - 0.8*M2_prime**1.1)*beta**1.3\n *(1.0 + 8.0*t1))\n\n # C_inf is discharge coefficient with corner taps for infinite Re\n # Cs, slope term, provides increase in discharge coefficient for lower\n # Reynolds numbers.\n x1 = 63.095734448019314*(Re_D_inv)**0.3 # 63.095... = (1e6)**0.3\n x2 = 22.7 - 0.0047*Re_D\n t2 = max(x2, x1)\n # max term is not in the ISO standard\n C_inf_C_s = (0.5961 + 0.0261*beta2 - 0.216*beta8\n + 0.000521*(1E6*beta*Re_D_inv)**0.7\n + (0.0188 + 0.0063*A)*beta2*beta*sqrt(beta)*(\n t2))\n\n C = (C_inf_C_s + delta_C_upstream + delta_C_downstream)\n if D < 0.07112:\n # Limit is 2.8 inches, .1 inches smaller than the internal diameter of\n # a sched. 80 pipe.\n # Suggested to be required not because of any effect of small\n # diameters themselves, but because of edge radius differences.\n # max term is given in [4]_ Reader-Harris, Michael book\n # There is a check for t3 being negative and setting it to zero if so\n # in some sources but that only occurs when t3 is exactly the limit\n # (0.07112) so it is not needed\n t3 = (2.8 - D*inch_inv)\n delta_C_diameter = 0.011*(0.75 - beta)*t3\n C += delta_C_diameter\n\n return C\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 6747}, "tests/test_numerics.py::625": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["rosen_der", "translate_bound_f_jac", "translate_bound_func", "translate_bound_jac"], "enclosing_function": "test_translate_bound_f_jac", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef translate_bound_func(func, bounds=None, low=None, high=None):\n if bounds is not None:\n low = [i[0] for i in bounds]\n high = [i[1] for i in bounds]\n\n def new_f(x, *args, **kwargs):\n \"\"\"Function for a solver to call when using the bounded variables.\"\"\"\n x = [float(i) for i in x]\n for i in range(len(x)):\n x[i] = (low[i] + (high[i] - low[i])/(1.0 + trunc_exp(-x[i])))\n # Return the actual results\n return func(x, *args, **kwargs)\n\n def translate_into(x):\n x = [float(i) for i in x]\n for i in range(len(x)):\n x[i] = -trunc_log((high[i] - x[i])/(x[i] - low[i]))\n return x\n\n def translate_outof(x):\n x = [float(i) for i in x]\n for i in range(len(x)):\n x[i] = (low[i] + (high[i] - low[i])/(1.0 + trunc_exp(-x[i])))\n return x\n return new_f, translate_into, translate_outof\n\ndef translate_bound_jac(jac, bounds=None, low=None, high=None):\n if bounds is not None:\n low = [i[0] for i in bounds]\n high = [i[1] for i in bounds]\n\n def new_j(x):\n x_base = [float(i) for i in x]\n N = len(x)\n for i in range(N):\n x_base[i] = (low[i] + (high[i] - low[i])/(1.0 + trunc_exp(-x[i])))\n jac_base = jac(x_base)\n try:\n jac_base = [i for i in jac_base]\n for i in range(N):\n v = (high[i] - low[i])*trunc_exp(-x[i])*jac_base[i]\n v *= (1.0 + trunc_exp(-x[i]))**-2\n jac_base[i] = v\n return jac_base\n except:\n raise NotImplementedError(\"Fail\")\n\n def translate_into(x):\n x = [float(i) for i in x]\n for i in range(len(x)):\n x[i] = -trunc_log((high[i] - x[i])/(x[i] - low[i]))\n return x\n\n def translate_outof(x):\n x = [float(i) for i in x]\n for i in range(len(x)):\n x[i] = (low[i] + (high[i] - low[i])/(1.0 + trunc_exp(-x[i])))\n return x\n return new_j, translate_into, translate_outof\n\ndef translate_bound_f_jac(f, jac, bounds=None, low=None, high=None,\n inplace_jac=False, as_np=False):\n if bounds is not None:\n low = [i[0] for i in bounds]\n high = [i[1] for i in bounds]\n\n exp_terms = [0.0]*len(low)\n\n def new_f_j(x, *args):\n x_base = [i for i in x]\n N = len(x)\n for i in range(N):\n exp_terms[i] = ei = trunc_exp(-x[i])\n x_base[i] = (low[i] + (high[i] - low[i])/(1.0 + ei))\n\n if jac is True:\n f_base, jac_base = f(x_base, *args)\n else:\n f_base = f(x_base, *args)\n jac_base = jac(x_base, *args)\n try:\n if type(jac_base[0]) is list or (isinstance(jac_base, np.ndarray) and len(jac_base.shape) == 2):\n if not inplace_jac:\n jac_base = [[j for j in i] for i in jac_base]\n\n for i in range(len(jac_base)):\n for j in range(len(jac_base[i])):\n # Checked numerically\n t = (1.0 + exp_terms[j])\n jac_base[i][j] = (high[j] - low[j])*exp_terms[j]*jac_base[i][j]/(t*t)\n else:\n if not inplace_jac:\n jac_base = [i for i in jac_base]\n for i in range(N):\n t = (1.0 + exp_terms[i])\n jac_base[i] = (high[i] - low[i])*exp_terms[i]*jac_base[i]/(t*t)\n if as_np:\n jac_base = np.array(jac_base)\n return f_base, jac_base\n except:\n raise NotImplementedError(\"Fail\")\n\n def translate_into(x):\n if not as_np:\n # cannot cast to float as used with mpmath tests\n x = [i for i in x]\n else:\n x = x.copy()\n for i in range(len(x)):\n x[i] = -trunc_log((high[i] - x[i])/(x[i] - low[i]))\n return x\n\n def translate_outof(x):\n if not as_np:\n # cannot cast to float as used with mpmath tests\n x = [i for i in x]\n else:\n x = x.copy()\n for i in range(len(x)):\n x[i] = (low[i] + (high[i] - low[i])/(1.0 + trunc_exp(-x[i])))\n return x\n return new_f_j, translate_into, translate_outof", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 4319}, "tests/test_numerics.py::628": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["rosen_der", "translate_bound_f_jac", "translate_bound_func", "translate_bound_jac"], "enclosing_function": "test_translate_bound_f_jac", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef translate_bound_func(func, bounds=None, low=None, high=None):\n if bounds is not None:\n low = [i[0] for i in bounds]\n high = [i[1] for i in bounds]\n\n def new_f(x, *args, **kwargs):\n \"\"\"Function for a solver to call when using the bounded variables.\"\"\"\n x = [float(i) for i in x]\n for i in range(len(x)):\n x[i] = (low[i] + (high[i] - low[i])/(1.0 + trunc_exp(-x[i])))\n # Return the actual results\n return func(x, *args, **kwargs)\n\n def translate_into(x):\n x = [float(i) for i in x]\n for i in range(len(x)):\n x[i] = -trunc_log((high[i] - x[i])/(x[i] - low[i]))\n return x\n\n def translate_outof(x):\n x = [float(i) for i in x]\n for i in range(len(x)):\n x[i] = (low[i] + (high[i] - low[i])/(1.0 + trunc_exp(-x[i])))\n return x\n return new_f, translate_into, translate_outof\n\ndef translate_bound_jac(jac, bounds=None, low=None, high=None):\n if bounds is not None:\n low = [i[0] for i in bounds]\n high = [i[1] for i in bounds]\n\n def new_j(x):\n x_base = [float(i) for i in x]\n N = len(x)\n for i in range(N):\n x_base[i] = (low[i] + (high[i] - low[i])/(1.0 + trunc_exp(-x[i])))\n jac_base = jac(x_base)\n try:\n jac_base = [i for i in jac_base]\n for i in range(N):\n v = (high[i] - low[i])*trunc_exp(-x[i])*jac_base[i]\n v *= (1.0 + trunc_exp(-x[i]))**-2\n jac_base[i] = v\n return jac_base\n except:\n raise NotImplementedError(\"Fail\")\n\n def translate_into(x):\n x = [float(i) for i in x]\n for i in range(len(x)):\n x[i] = -trunc_log((high[i] - x[i])/(x[i] - low[i]))\n return x\n\n def translate_outof(x):\n x = [float(i) for i in x]\n for i in range(len(x)):\n x[i] = (low[i] + (high[i] - low[i])/(1.0 + trunc_exp(-x[i])))\n return x\n return new_j, translate_into, translate_outof\n\ndef translate_bound_f_jac(f, jac, bounds=None, low=None, high=None,\n inplace_jac=False, as_np=False):\n if bounds is not None:\n low = [i[0] for i in bounds]\n high = [i[1] for i in bounds]\n\n exp_terms = [0.0]*len(low)\n\n def new_f_j(x, *args):\n x_base = [i for i in x]\n N = len(x)\n for i in range(N):\n exp_terms[i] = ei = trunc_exp(-x[i])\n x_base[i] = (low[i] + (high[i] - low[i])/(1.0 + ei))\n\n if jac is True:\n f_base, jac_base = f(x_base, *args)\n else:\n f_base = f(x_base, *args)\n jac_base = jac(x_base, *args)\n try:\n if type(jac_base[0]) is list or (isinstance(jac_base, np.ndarray) and len(jac_base.shape) == 2):\n if not inplace_jac:\n jac_base = [[j for j in i] for i in jac_base]\n\n for i in range(len(jac_base)):\n for j in range(len(jac_base[i])):\n # Checked numerically\n t = (1.0 + exp_terms[j])\n jac_base[i][j] = (high[j] - low[j])*exp_terms[j]*jac_base[i][j]/(t*t)\n else:\n if not inplace_jac:\n jac_base = [i for i in jac_base]\n for i in range(N):\n t = (1.0 + exp_terms[i])\n jac_base[i] = (high[i] - low[i])*exp_terms[i]*jac_base[i]/(t*t)\n if as_np:\n jac_base = np.array(jac_base)\n return f_base, jac_base\n except:\n raise NotImplementedError(\"Fail\")\n\n def translate_into(x):\n if not as_np:\n # cannot cast to float as used with mpmath tests\n x = [i for i in x]\n else:\n x = x.copy()\n for i in range(len(x)):\n x[i] = -trunc_log((high[i] - x[i])/(x[i] - low[i]))\n return x\n\n def translate_outof(x):\n if not as_np:\n # cannot cast to float as used with mpmath tests\n x = [i for i in x]\n else:\n x = x.copy()\n for i in range(len(x)):\n x[i] = (low[i] + (high[i] - low[i])/(1.0 + trunc_exp(-x[i])))\n return x\n return new_f_j, translate_into, translate_outof", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 4319}, "tests/test_numerics_polynomial_utils.py::132": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["assert_close", "horner_and_der2", "quadratic_from_f_ders"], "enclosing_function": "test_quadratic_from_f_ders", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 607}, "tests/test_numerics_polynomial_utils.py::133": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["assert_close", "horner_and_der2", "quadratic_from_f_ders"], "enclosing_function": "test_quadratic_from_f_ders", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 607}, "tests/test_packed_tower.py::71": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/packed_tower.py"], "used_names": ["assert_close", "dP_demister_wet_ElDessouky"], "enclosing_function": "test_dP_demister_wet_ElDessouky", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/packed_tower.py\ndef dP_demister_wet_ElDessouky(vs: float, voidage: float, d_wire: float, L: float=1.0) -> float:\n r\"\"\"Calculates wet pressure drop across a demister, using the\n correlation in [1]_. Uses only their own experimental data.\n\n .. math::\n \\frac{\\Delta P}{L} = 0.002357(1-\\epsilon)^{0.375798}(V)^{0.81317}\n (d_w)^{-1.56114147}\n\n Parameters\n ----------\n vs : float\n Superficial velocity of fluid, Q/A [m/s]\n voidage : float\n Voidage of bed of the demister material, normally ~0.98 []\n d_wire : float\n Diameter of mesh wire, [m]\n L : float, optional\n Length of the demister [m]\n\n Returns\n -------\n dP : float\n Pressure drop across a wet demister [Pa]\n\n Notes\n -----\n No dependency on the liquid properties is included here. Because of the\n exponential nature of the correlation, the limiting pressure drop as V\n is lowered is 0 Pa. A dry pressure drop correlation should be compared with\n results from this at low velocities, and the larger of the\n two pressure drops used.\n\n The correlation in [1]_ was presented as follows, with wire diameter in\n units of mm, density in kg/m^3, V in m/s, and dP in Pa/m.\n\n .. math::\n \\Delta P = 3.88178(\\rho_{mesh})^{0.375798}(V)^{0.81317}\n (d_w)^{-1.56114147}\n\n Here, the correlation is converted to base SI units and to use voidage;\n not all demisters are stainless steel as in [1]_. A density of 7999 kg/m^3\n was used in the conversion.\n\n In [1]_, V ranged from 0.98-7.5 m/s, rho from 80.317-208.16 kg/m^3, depth\n from 100 to 200 mm, wire diameter of 0.2mm to 0.32 mm, and particle\n diameter from 1 to 5 mm.\n\n\n Examples\n --------\n >>> dP_demister_wet_ElDessouky(6, 0.978, 0.00032)\n 688.9216420105029\n\n References\n ----------\n .. [1] El-Dessouky, Hisham T, Imad M Alatiqi, Hisham M Ettouney, and Noura\n S Al-Deffeeri. \"Performance of Wire Mesh Mist Eliminator.\" Chemical\n Engineering and Processing: Process Intensification 39, no. 2 (March\n 2000): 129-39. doi:10.1016/S0255-2701(99)00033-1.\n \"\"\"\n return L*0.002356999643727531*(1-voidage)**0.375798*vs**0.81317*d_wire**-1.56114147", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2846}, "tests/test_particle_size_distribution.py::369": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/particle_size_distribution.py"], "used_names": ["PSDLognormal", "assert_close1d"], "enclosing_function": "testPSDLognormal_meshes", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\n\n# Source: fluids/particle_size_distribution.py\nclass PSDLognormal(ParticleSizeDistributionContinuous):\n name = \"Lognormal\"\n points = False\n truncated = False\n def __init__(self, d_characteristic: float, s: float, order: int=3, d_min: float | None=None, d_max: float | None=None) -> None:\n self.s = s\n self.d_characteristic = d_characteristic\n self.order = order\n self.parameters = {\"s\": s, \"d_characteristic\": d_characteristic,\n \"d_min\": d_min, \"d_max\": d_max}\n if d_min is not None:\n self.d_min = d_min\n if d_max is not None:\n self.d_max = d_max\n # Pick an upper bound for the search algorithm of 15 orders of magnitude larger than\n # the characteristic diameter; should never be a problem, as diameters can only range\n # so much, physically.\n if d_max is not None:\n self.d_excessive = d_max\n else:\n self.d_excessive = 1E15*self.d_characteristic\n if d_min is not None:\n self.d_minimum = d_min\n else:\n self.d_minimum = 0.0\n\n if d_min is not None or d_max is not None:\n self.truncated = True\n if d_max is None:\n self.d_max = self.d_excessive\n else:\n self.d_max = d_max\n if d_min is None:\n self.d_min = 0.0\n else:\n self.d_min = d_min\n\n self._cdf_d_max = self._cdf(self.d_max)\n self._cdf_d_min = self._cdf(self.d_min)\n\n def _pdf(self, d: float) -> float:\n return pdf_lognormal(d, self.d_characteristic, self.s)\n\n def _cdf(self, d: float) -> float:\n return cdf_lognormal(d, self.d_characteristic, self.s)\n\n def _pdf_basis_integral(self, d: float, n: float) -> float:\n return pdf_lognormal_basis_integral(d, self.d_characteristic, self.s, n)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 2183}, "tests/test_safety_valve.py::56": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/numerics/__init__.py", "fluids/safety_valve.py"], "used_names": ["API520_A_g", "API520_B", "API520_C", "API520_F2", "API520_N", "API520_W", "API520_round_size", "API526_A", "API526_letters", "assert_close", "assert_close1d", "atm", "pytest"], "enclosing_function": "test_safety_valve", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\n\n# Source: fluids/safety_valve.py\nAPI526_letters = [\"D\", \"E\", \"F\", \"G\", \"H\", \"J\", \"K\", \"L\", \"M\", \"N\", \"P\", \"Q\", \"R\",\"T\"]\n\nAPI526_A = [i*inch2 for i in API526_A_sq_inch]\n\ndef API520_round_size(A: float) -> float:\n r\"\"\"Rounds up the area from an API 520 calculation to an API526 standard\n valve area. The returned area is always larger or equal to the input area.\n\n Parameters\n ----------\n A : float\n Minimum discharge area [m^2]\n\n Returns\n -------\n area : float\n Actual discharge area [m^2]\n\n Notes\n -----\n To obtain the letter designation of an input area, lookup the area with\n the following:\n\n API526_letters[API526_A.index(area)]\n\n An exception is raised if the required relief area is larger than any of\n the API 526 sizes.\n\n Examples\n --------\n From [1]_, checked with many points on Table 8.\n\n >>> API520_round_size(1E-4)\n 0.00012645136\n >>> API526_letters[API526_A.index(API520_round_size(1E-4))]\n 'E'\n\n References\n ----------\n .. [1] API Standard 526.\n \"\"\"\n for area in API526_A:\n if area >= A:\n return area\n raise ValueError(\"Required relief area is larger than can be provided with one valve\")\n\ndef API520_C(k: float) -> float:\n r\"\"\"Calculates coefficient C for use in API 520 critical flow relief valve\n sizing.\n\n .. math::\n C = 0.03948\\sqrt{k\\left(\\frac{2}{k+1}\\right)^\\frac{k+1}{k-1}}\n\n Parameters\n ----------\n k : float\n Isentropic coefficient or ideal gas heat capacity ratio [-]\n\n Returns\n -------\n C : float\n Coefficient `C` [-]\n\n Notes\n -----\n If C cannot be established, assume a coefficient of 0.0239,\n the highest value possible for C.\n\n Although not dimensional, C varies with the units used.\n\n If k is exactly equal to 1, the expression is undefined, and the formula\n must be simplified as follows from an application of L'Hopital's rule.\n\n .. math::\n C = 0.03948\\sqrt{\\frac{1}{e}}\n\n Examples\n --------\n From [1]_, checked with many points on Table 8.\n\n >>> API520_C(1.35)\n 0.02669419967057233\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n if k != 1:\n kp1 = k+1\n return 0.03948*sqrt(k*(2./kp1)**(kp1/(k-1.)))\n else:\n return 0.023945830445454768\n\ndef API520_F2(k: float, P1: float, P2: float) -> float:\n r\"\"\"Calculates coefficient F2 for subcritical flow for use in API 520\n subcritical flow relief valve sizing.\n\n .. math::\n F_2 = \\sqrt{\\left(\\frac{k}{k-1}\\right)r^\\frac{2}{k}\n \\left[\\frac{1-r^\\frac{k-1}{k}}{1-r}\\right]}\n\n .. math::\n r = \\frac{P_2}{P_1}\n\n Parameters\n ----------\n k : float\n Isentropic coefficient or ideal gas heat capacity ratio [-]\n P1 : float\n Upstream relieving pressure; the set pressure plus the allowable\n overpressure, plus atmospheric pressure, [Pa]\n P2 : float\n Built-up backpressure; the increase in pressure during flow at the\n outlet of a pressure-relief device after it opens, [Pa]\n\n Returns\n -------\n F2 : float\n Subcritical flow coefficient `F2` [-]\n\n Notes\n -----\n F2 is completely dimensionless.\n\n Examples\n --------\n From [1]_ example 2, matches.\n\n >>> API520_F2(1.8, 1E6, 7E5)\n 0.8600724121105563\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n r = P2/P1\n return sqrt(k/(k-1.0)*r**(2./k) * ((1-r**((k-1.)/k))/(1.-r)))\n\ndef API520_N(P1: float) -> float:\n r\"\"\"Calculates correction due to steam pressure for steam flow for use in\n API 520 relief valve sizing.\n\n For pressures below 10339 kPa, the correction factor is 1.\n\n .. math::\n K_N = \\frac{0.02764P_1-1000}{0.03324P_1-1061}\n\n Parameters\n ----------\n P1 : float\n Upstream relieving pressure; the set pressure plus the allowable\n overpressure, plus atmospheric pressure, [Pa]\n\n Returns\n -------\n KN : float\n Correction due to steam temperature [-]\n\n Notes\n -----\n Although not dimensional, KN varies with the units used.\n\n For temperatures above 922 K or pressures above 22057 kPa, KN is not defined.\n\n Internally, units of kPa are used to match the equation in the standard.\n\n Examples\n --------\n >>> API520_N(10500e3)\n 0.9969100255\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n P1 = P1*1e-3 # Pa to kPa\n if P1 <= 10339.0:\n KN = 1.0\n else:\n KN = (0.02764*P1 - 1000.)/(0.03324*P1 - 1061.0)\n return KN\n\ndef API520_B(Pset: float, Pback: float, overpressure: float=0.1) -> float:\n r\"\"\"Calculates capacity correction due to backpressure on balanced\n spring-loaded PRVs in vapor service. For pilot operated valves,\n this is always 1. Applicable up to 50% of the percent gauge backpressure,\n For use in API 520 relief valve sizing. 1D interpolation among a table with\n 53 backpressures is performed.\n\n Parameters\n ----------\n Pset : float\n Set pressure for relief [Pa]\n Pback : float\n Backpressure, [Pa]\n overpressure : float, optional\n The maximum fraction overpressure; one of 0.1, 0.16, or 0.21, [-]\n\n Returns\n -------\n Kb : float\n Correction due to vapor backpressure [-]\n\n Notes\n -----\n If the calculated gauge backpressure is less than 30%, 38%, or 50% for\n overpressures of 0.1, 0.16, or 0.21, a value of 1 is returned.\n\n Percent gauge backpressure must be under 50%.\n\n Examples\n --------\n Custom examples from figure 30:\n\n >>> API520_B(1E6, 5E5)\n 0.7929945420944432\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n gauge_backpressure = (Pback-atm)/(Pset-atm)*100.0 # in percent\n if overpressure not in (0.1, 0.16, 0.21):\n raise ValueError(\"Only overpressure of 10%, 16%, or 21% are permitted\")\n if (overpressure == 0.1 and gauge_backpressure < 30.0) or (\n overpressure == 0.16 and gauge_backpressure < 38.0) or (\n overpressure == 0.21 and gauge_backpressure <= 50.0):\n return 1.0\n elif gauge_backpressure > 50.0:\n raise ValueError(\"Gauge pressure must be < 50%\")\n if overpressure == 0.16:\n Kb = interp(gauge_backpressure, Kb_16_over_x, Kb_16_over_y)\n elif overpressure == 0.1:\n Kb = interp(gauge_backpressure, Kb_10_over_x, Kb_10_over_y)\n return Kb\n\ndef API520_A_g(m: float, T: float, Z: float, MW: float, k: float, P1: float, P2: float=101325, Kd: float=0.975, Kb: float=1, Kc: float=1) -> float:\n r\"\"\"Calculates required relief valve area for an API 520 valve passing\n a gas or a vapor, at either critical or sub-critical flow.\n\n For critical flow:\n\n .. math::\n A = \\frac{m}{CK_dP_1K_bK_c}\\sqrt{\\frac{TZ}{M}}\n\n For sub-critical flow:\n\n .. math::\n A = \\frac{17.9m}{F_2K_dK_c}\\sqrt{\\frac{TZ}{MP_1(P_1-P_2)}}\n\n Parameters\n ----------\n m : float\n Mass flow rate of vapor through the valve, [kg/s]\n T : float\n Temperature of vapor entering the valve, [K]\n Z : float\n Compressibility factor of the vapor, [-]\n MW : float\n Molecular weight of the vapor, [g/mol]\n k : float\n Isentropic coefficient or ideal gas heat capacity ratio [-]\n P1 : float\n Upstream relieving pressure; the set pressure plus the allowable\n overpressure, plus atmospheric pressure, [Pa]\n P2 : float, optional\n Built-up backpressure; the increase in pressure during flow at the\n outlet of a pressure-relief device after it opens, [Pa]\n Kd : float, optional\n The effective coefficient of discharge, from the manufacturer or for\n preliminary sizing, using 0.975 normally or 0.62 when used with a\n rupture disc as described in [1]_, []\n Kb : float, optional\n Correction due to vapor backpressure [-]\n Kc : float, optional\n Combination correction factor for installation with a rupture disk\n upstream of the PRV; 1.0 when a rupture disk is not installed, and\n 0.9 if a rupture disk is present and the combination has not been\n certified, []\n\n Returns\n -------\n A : float\n Minimum area for relief valve according to [1]_, [m^2]\n\n Notes\n -----\n Units are interlally kg/hr, kPa, and mm^2 to match [1]_.\n\n Examples\n --------\n Example 1 from [1]_ for critical flow, matches:\n\n >>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, Kb=1, Kc=1)\n 0.0036990460646834414\n\n Example 2 from [1]_ for sub-critical flow, matches:\n\n >>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, P2=532E3, Kd=0.975, Kb=1, Kc=1)\n 0.004248358775943481\n\n The mass flux in (kg/(s*m^2)) can be found by dividing the specified mass\n flow by the calculated area:\n\n >>> (24270/3600.)/API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, Kb=1, Kc=1)\n 1822.541960488834\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n P1, P2 = P1*1e-3, P2*1e-3 # Pa to Kpa in the standard\n m = m*3600. # kg/s to kg/hr\n if is_critical_flow(P1, P2, k):\n C = API520_C(k)\n A = m/(C*Kd*Kb*Kc*P1)*sqrt(T*Z/MW)\n else:\n F2 = API520_F2(k, P1, P2)\n A = 17.9*m/(F2*Kd*Kc)*sqrt(T*Z/(MW*P1*(P1-P2)))\n return A*1e-6\n\ndef API520_W(Pset: float, Pback: float) -> float:\n r\"\"\"Calculates capacity correction due to backpressure on balanced\n spring-loaded PRVs in liquid service. For pilot operated valves,\n this is always 1. Applicable up to 50% of the percent gauge backpressure,\n For use in API 520 relief valve sizing. 1D interpolation among a table with\n 53 backpressures is performed.\n\n Parameters\n ----------\n Pset : float\n Set pressure for relief [Pa]\n Pback : float\n Backpressure, [Pa]\n\n Returns\n -------\n KW : float\n Correction due to liquid backpressure [-]\n\n Notes\n -----\n If the calculated gauge backpressure is less than 15%, a value of 1 is\n returned.\n\n Examples\n --------\n Custom example from figure 31 in [1]_:\n\n >>> API520_W(1E6, 3E5) # 22% overpressure\n 0.95114718480085\n\n Example 5 from [2]_, set pressure 250 psig and backpressure up to 50 psig:\n\n >>> API520_W(Pset=1825014, Pback=446062)\n 0.97242133397677\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection. 7E\n .. [2] API Standard 520, Part 1 - Sizing and Selection. 10E\n \"\"\"\n gauge_backpressure = (Pback-atm)/(Pset-atm)*100.0 # in percent\n if gauge_backpressure < 15.0:\n return 1.0\n return interp(gauge_backpressure, Kw_x, Kw_y)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 11658}, "tests/test_safety_valve.py::70": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/numerics/__init__.py", "fluids/safety_valve.py"], "used_names": ["API520_A_g", "API520_B", "API520_C", "API520_F2", "API520_N", "API520_W", "API520_round_size", "API526_A", "API526_letters", "assert_close", "assert_close1d", "atm", "pytest"], "enclosing_function": "test_safety_valve", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\n\n# Source: fluids/safety_valve.py\nAPI526_letters = [\"D\", \"E\", \"F\", \"G\", \"H\", \"J\", \"K\", \"L\", \"M\", \"N\", \"P\", \"Q\", \"R\",\"T\"]\n\nAPI526_A = [i*inch2 for i in API526_A_sq_inch]\n\ndef API520_round_size(A: float) -> float:\n r\"\"\"Rounds up the area from an API 520 calculation to an API526 standard\n valve area. The returned area is always larger or equal to the input area.\n\n Parameters\n ----------\n A : float\n Minimum discharge area [m^2]\n\n Returns\n -------\n area : float\n Actual discharge area [m^2]\n\n Notes\n -----\n To obtain the letter designation of an input area, lookup the area with\n the following:\n\n API526_letters[API526_A.index(area)]\n\n An exception is raised if the required relief area is larger than any of\n the API 526 sizes.\n\n Examples\n --------\n From [1]_, checked with many points on Table 8.\n\n >>> API520_round_size(1E-4)\n 0.00012645136\n >>> API526_letters[API526_A.index(API520_round_size(1E-4))]\n 'E'\n\n References\n ----------\n .. [1] API Standard 526.\n \"\"\"\n for area in API526_A:\n if area >= A:\n return area\n raise ValueError(\"Required relief area is larger than can be provided with one valve\")\n\ndef API520_C(k: float) -> float:\n r\"\"\"Calculates coefficient C for use in API 520 critical flow relief valve\n sizing.\n\n .. math::\n C = 0.03948\\sqrt{k\\left(\\frac{2}{k+1}\\right)^\\frac{k+1}{k-1}}\n\n Parameters\n ----------\n k : float\n Isentropic coefficient or ideal gas heat capacity ratio [-]\n\n Returns\n -------\n C : float\n Coefficient `C` [-]\n\n Notes\n -----\n If C cannot be established, assume a coefficient of 0.0239,\n the highest value possible for C.\n\n Although not dimensional, C varies with the units used.\n\n If k is exactly equal to 1, the expression is undefined, and the formula\n must be simplified as follows from an application of L'Hopital's rule.\n\n .. math::\n C = 0.03948\\sqrt{\\frac{1}{e}}\n\n Examples\n --------\n From [1]_, checked with many points on Table 8.\n\n >>> API520_C(1.35)\n 0.02669419967057233\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n if k != 1:\n kp1 = k+1\n return 0.03948*sqrt(k*(2./kp1)**(kp1/(k-1.)))\n else:\n return 0.023945830445454768\n\ndef API520_F2(k: float, P1: float, P2: float) -> float:\n r\"\"\"Calculates coefficient F2 for subcritical flow for use in API 520\n subcritical flow relief valve sizing.\n\n .. math::\n F_2 = \\sqrt{\\left(\\frac{k}{k-1}\\right)r^\\frac{2}{k}\n \\left[\\frac{1-r^\\frac{k-1}{k}}{1-r}\\right]}\n\n .. math::\n r = \\frac{P_2}{P_1}\n\n Parameters\n ----------\n k : float\n Isentropic coefficient or ideal gas heat capacity ratio [-]\n P1 : float\n Upstream relieving pressure; the set pressure plus the allowable\n overpressure, plus atmospheric pressure, [Pa]\n P2 : float\n Built-up backpressure; the increase in pressure during flow at the\n outlet of a pressure-relief device after it opens, [Pa]\n\n Returns\n -------\n F2 : float\n Subcritical flow coefficient `F2` [-]\n\n Notes\n -----\n F2 is completely dimensionless.\n\n Examples\n --------\n From [1]_ example 2, matches.\n\n >>> API520_F2(1.8, 1E6, 7E5)\n 0.8600724121105563\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n r = P2/P1\n return sqrt(k/(k-1.0)*r**(2./k) * ((1-r**((k-1.)/k))/(1.-r)))\n\ndef API520_N(P1: float) -> float:\n r\"\"\"Calculates correction due to steam pressure for steam flow for use in\n API 520 relief valve sizing.\n\n For pressures below 10339 kPa, the correction factor is 1.\n\n .. math::\n K_N = \\frac{0.02764P_1-1000}{0.03324P_1-1061}\n\n Parameters\n ----------\n P1 : float\n Upstream relieving pressure; the set pressure plus the allowable\n overpressure, plus atmospheric pressure, [Pa]\n\n Returns\n -------\n KN : float\n Correction due to steam temperature [-]\n\n Notes\n -----\n Although not dimensional, KN varies with the units used.\n\n For temperatures above 922 K or pressures above 22057 kPa, KN is not defined.\n\n Internally, units of kPa are used to match the equation in the standard.\n\n Examples\n --------\n >>> API520_N(10500e3)\n 0.9969100255\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n P1 = P1*1e-3 # Pa to kPa\n if P1 <= 10339.0:\n KN = 1.0\n else:\n KN = (0.02764*P1 - 1000.)/(0.03324*P1 - 1061.0)\n return KN\n\ndef API520_B(Pset: float, Pback: float, overpressure: float=0.1) -> float:\n r\"\"\"Calculates capacity correction due to backpressure on balanced\n spring-loaded PRVs in vapor service. For pilot operated valves,\n this is always 1. Applicable up to 50% of the percent gauge backpressure,\n For use in API 520 relief valve sizing. 1D interpolation among a table with\n 53 backpressures is performed.\n\n Parameters\n ----------\n Pset : float\n Set pressure for relief [Pa]\n Pback : float\n Backpressure, [Pa]\n overpressure : float, optional\n The maximum fraction overpressure; one of 0.1, 0.16, or 0.21, [-]\n\n Returns\n -------\n Kb : float\n Correction due to vapor backpressure [-]\n\n Notes\n -----\n If the calculated gauge backpressure is less than 30%, 38%, or 50% for\n overpressures of 0.1, 0.16, or 0.21, a value of 1 is returned.\n\n Percent gauge backpressure must be under 50%.\n\n Examples\n --------\n Custom examples from figure 30:\n\n >>> API520_B(1E6, 5E5)\n 0.7929945420944432\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n gauge_backpressure = (Pback-atm)/(Pset-atm)*100.0 # in percent\n if overpressure not in (0.1, 0.16, 0.21):\n raise ValueError(\"Only overpressure of 10%, 16%, or 21% are permitted\")\n if (overpressure == 0.1 and gauge_backpressure < 30.0) or (\n overpressure == 0.16 and gauge_backpressure < 38.0) or (\n overpressure == 0.21 and gauge_backpressure <= 50.0):\n return 1.0\n elif gauge_backpressure > 50.0:\n raise ValueError(\"Gauge pressure must be < 50%\")\n if overpressure == 0.16:\n Kb = interp(gauge_backpressure, Kb_16_over_x, Kb_16_over_y)\n elif overpressure == 0.1:\n Kb = interp(gauge_backpressure, Kb_10_over_x, Kb_10_over_y)\n return Kb\n\ndef API520_A_g(m: float, T: float, Z: float, MW: float, k: float, P1: float, P2: float=101325, Kd: float=0.975, Kb: float=1, Kc: float=1) -> float:\n r\"\"\"Calculates required relief valve area for an API 520 valve passing\n a gas or a vapor, at either critical or sub-critical flow.\n\n For critical flow:\n\n .. math::\n A = \\frac{m}{CK_dP_1K_bK_c}\\sqrt{\\frac{TZ}{M}}\n\n For sub-critical flow:\n\n .. math::\n A = \\frac{17.9m}{F_2K_dK_c}\\sqrt{\\frac{TZ}{MP_1(P_1-P_2)}}\n\n Parameters\n ----------\n m : float\n Mass flow rate of vapor through the valve, [kg/s]\n T : float\n Temperature of vapor entering the valve, [K]\n Z : float\n Compressibility factor of the vapor, [-]\n MW : float\n Molecular weight of the vapor, [g/mol]\n k : float\n Isentropic coefficient or ideal gas heat capacity ratio [-]\n P1 : float\n Upstream relieving pressure; the set pressure plus the allowable\n overpressure, plus atmospheric pressure, [Pa]\n P2 : float, optional\n Built-up backpressure; the increase in pressure during flow at the\n outlet of a pressure-relief device after it opens, [Pa]\n Kd : float, optional\n The effective coefficient of discharge, from the manufacturer or for\n preliminary sizing, using 0.975 normally or 0.62 when used with a\n rupture disc as described in [1]_, []\n Kb : float, optional\n Correction due to vapor backpressure [-]\n Kc : float, optional\n Combination correction factor for installation with a rupture disk\n upstream of the PRV; 1.0 when a rupture disk is not installed, and\n 0.9 if a rupture disk is present and the combination has not been\n certified, []\n\n Returns\n -------\n A : float\n Minimum area for relief valve according to [1]_, [m^2]\n\n Notes\n -----\n Units are interlally kg/hr, kPa, and mm^2 to match [1]_.\n\n Examples\n --------\n Example 1 from [1]_ for critical flow, matches:\n\n >>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, Kb=1, Kc=1)\n 0.0036990460646834414\n\n Example 2 from [1]_ for sub-critical flow, matches:\n\n >>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, P2=532E3, Kd=0.975, Kb=1, Kc=1)\n 0.004248358775943481\n\n The mass flux in (kg/(s*m^2)) can be found by dividing the specified mass\n flow by the calculated area:\n\n >>> (24270/3600.)/API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, Kb=1, Kc=1)\n 1822.541960488834\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n P1, P2 = P1*1e-3, P2*1e-3 # Pa to Kpa in the standard\n m = m*3600. # kg/s to kg/hr\n if is_critical_flow(P1, P2, k):\n C = API520_C(k)\n A = m/(C*Kd*Kb*Kc*P1)*sqrt(T*Z/MW)\n else:\n F2 = API520_F2(k, P1, P2)\n A = 17.9*m/(F2*Kd*Kc)*sqrt(T*Z/(MW*P1*(P1-P2)))\n return A*1e-6\n\ndef API520_W(Pset: float, Pback: float) -> float:\n r\"\"\"Calculates capacity correction due to backpressure on balanced\n spring-loaded PRVs in liquid service. For pilot operated valves,\n this is always 1. Applicable up to 50% of the percent gauge backpressure,\n For use in API 520 relief valve sizing. 1D interpolation among a table with\n 53 backpressures is performed.\n\n Parameters\n ----------\n Pset : float\n Set pressure for relief [Pa]\n Pback : float\n Backpressure, [Pa]\n\n Returns\n -------\n KW : float\n Correction due to liquid backpressure [-]\n\n Notes\n -----\n If the calculated gauge backpressure is less than 15%, a value of 1 is\n returned.\n\n Examples\n --------\n Custom example from figure 31 in [1]_:\n\n >>> API520_W(1E6, 3E5) # 22% overpressure\n 0.95114718480085\n\n Example 5 from [2]_, set pressure 250 psig and backpressure up to 50 psig:\n\n >>> API520_W(Pset=1825014, Pback=446062)\n 0.97242133397677\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection. 7E\n .. [2] API Standard 520, Part 1 - Sizing and Selection. 10E\n \"\"\"\n gauge_backpressure = (Pback-atm)/(Pset-atm)*100.0 # in percent\n if gauge_backpressure < 15.0:\n return 1.0\n return interp(gauge_backpressure, Kw_x, Kw_y)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 11658}, "tests/test_safety_valve.py::85": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/numerics/__init__.py", "fluids/safety_valve.py"], "used_names": ["API520_A_g", "API520_B", "API520_C", "API520_F2", "API520_N", "API520_W", "API520_round_size", "API526_A", "API526_letters", "assert_close", "assert_close1d", "atm", "pytest"], "enclosing_function": "test_safety_valve", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\n\n# Source: fluids/safety_valve.py\nAPI526_letters = [\"D\", \"E\", \"F\", \"G\", \"H\", \"J\", \"K\", \"L\", \"M\", \"N\", \"P\", \"Q\", \"R\",\"T\"]\n\nAPI526_A = [i*inch2 for i in API526_A_sq_inch]\n\ndef API520_round_size(A: float) -> float:\n r\"\"\"Rounds up the area from an API 520 calculation to an API526 standard\n valve area. The returned area is always larger or equal to the input area.\n\n Parameters\n ----------\n A : float\n Minimum discharge area [m^2]\n\n Returns\n -------\n area : float\n Actual discharge area [m^2]\n\n Notes\n -----\n To obtain the letter designation of an input area, lookup the area with\n the following:\n\n API526_letters[API526_A.index(area)]\n\n An exception is raised if the required relief area is larger than any of\n the API 526 sizes.\n\n Examples\n --------\n From [1]_, checked with many points on Table 8.\n\n >>> API520_round_size(1E-4)\n 0.00012645136\n >>> API526_letters[API526_A.index(API520_round_size(1E-4))]\n 'E'\n\n References\n ----------\n .. [1] API Standard 526.\n \"\"\"\n for area in API526_A:\n if area >= A:\n return area\n raise ValueError(\"Required relief area is larger than can be provided with one valve\")\n\ndef API520_C(k: float) -> float:\n r\"\"\"Calculates coefficient C for use in API 520 critical flow relief valve\n sizing.\n\n .. math::\n C = 0.03948\\sqrt{k\\left(\\frac{2}{k+1}\\right)^\\frac{k+1}{k-1}}\n\n Parameters\n ----------\n k : float\n Isentropic coefficient or ideal gas heat capacity ratio [-]\n\n Returns\n -------\n C : float\n Coefficient `C` [-]\n\n Notes\n -----\n If C cannot be established, assume a coefficient of 0.0239,\n the highest value possible for C.\n\n Although not dimensional, C varies with the units used.\n\n If k is exactly equal to 1, the expression is undefined, and the formula\n must be simplified as follows from an application of L'Hopital's rule.\n\n .. math::\n C = 0.03948\\sqrt{\\frac{1}{e}}\n\n Examples\n --------\n From [1]_, checked with many points on Table 8.\n\n >>> API520_C(1.35)\n 0.02669419967057233\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n if k != 1:\n kp1 = k+1\n return 0.03948*sqrt(k*(2./kp1)**(kp1/(k-1.)))\n else:\n return 0.023945830445454768\n\ndef API520_F2(k: float, P1: float, P2: float) -> float:\n r\"\"\"Calculates coefficient F2 for subcritical flow for use in API 520\n subcritical flow relief valve sizing.\n\n .. math::\n F_2 = \\sqrt{\\left(\\frac{k}{k-1}\\right)r^\\frac{2}{k}\n \\left[\\frac{1-r^\\frac{k-1}{k}}{1-r}\\right]}\n\n .. math::\n r = \\frac{P_2}{P_1}\n\n Parameters\n ----------\n k : float\n Isentropic coefficient or ideal gas heat capacity ratio [-]\n P1 : float\n Upstream relieving pressure; the set pressure plus the allowable\n overpressure, plus atmospheric pressure, [Pa]\n P2 : float\n Built-up backpressure; the increase in pressure during flow at the\n outlet of a pressure-relief device after it opens, [Pa]\n\n Returns\n -------\n F2 : float\n Subcritical flow coefficient `F2` [-]\n\n Notes\n -----\n F2 is completely dimensionless.\n\n Examples\n --------\n From [1]_ example 2, matches.\n\n >>> API520_F2(1.8, 1E6, 7E5)\n 0.8600724121105563\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n r = P2/P1\n return sqrt(k/(k-1.0)*r**(2./k) * ((1-r**((k-1.)/k))/(1.-r)))\n\ndef API520_N(P1: float) -> float:\n r\"\"\"Calculates correction due to steam pressure for steam flow for use in\n API 520 relief valve sizing.\n\n For pressures below 10339 kPa, the correction factor is 1.\n\n .. math::\n K_N = \\frac{0.02764P_1-1000}{0.03324P_1-1061}\n\n Parameters\n ----------\n P1 : float\n Upstream relieving pressure; the set pressure plus the allowable\n overpressure, plus atmospheric pressure, [Pa]\n\n Returns\n -------\n KN : float\n Correction due to steam temperature [-]\n\n Notes\n -----\n Although not dimensional, KN varies with the units used.\n\n For temperatures above 922 K or pressures above 22057 kPa, KN is not defined.\n\n Internally, units of kPa are used to match the equation in the standard.\n\n Examples\n --------\n >>> API520_N(10500e3)\n 0.9969100255\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n P1 = P1*1e-3 # Pa to kPa\n if P1 <= 10339.0:\n KN = 1.0\n else:\n KN = (0.02764*P1 - 1000.)/(0.03324*P1 - 1061.0)\n return KN\n\ndef API520_B(Pset: float, Pback: float, overpressure: float=0.1) -> float:\n r\"\"\"Calculates capacity correction due to backpressure on balanced\n spring-loaded PRVs in vapor service. For pilot operated valves,\n this is always 1. Applicable up to 50% of the percent gauge backpressure,\n For use in API 520 relief valve sizing. 1D interpolation among a table with\n 53 backpressures is performed.\n\n Parameters\n ----------\n Pset : float\n Set pressure for relief [Pa]\n Pback : float\n Backpressure, [Pa]\n overpressure : float, optional\n The maximum fraction overpressure; one of 0.1, 0.16, or 0.21, [-]\n\n Returns\n -------\n Kb : float\n Correction due to vapor backpressure [-]\n\n Notes\n -----\n If the calculated gauge backpressure is less than 30%, 38%, or 50% for\n overpressures of 0.1, 0.16, or 0.21, a value of 1 is returned.\n\n Percent gauge backpressure must be under 50%.\n\n Examples\n --------\n Custom examples from figure 30:\n\n >>> API520_B(1E6, 5E5)\n 0.7929945420944432\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n gauge_backpressure = (Pback-atm)/(Pset-atm)*100.0 # in percent\n if overpressure not in (0.1, 0.16, 0.21):\n raise ValueError(\"Only overpressure of 10%, 16%, or 21% are permitted\")\n if (overpressure == 0.1 and gauge_backpressure < 30.0) or (\n overpressure == 0.16 and gauge_backpressure < 38.0) or (\n overpressure == 0.21 and gauge_backpressure <= 50.0):\n return 1.0\n elif gauge_backpressure > 50.0:\n raise ValueError(\"Gauge pressure must be < 50%\")\n if overpressure == 0.16:\n Kb = interp(gauge_backpressure, Kb_16_over_x, Kb_16_over_y)\n elif overpressure == 0.1:\n Kb = interp(gauge_backpressure, Kb_10_over_x, Kb_10_over_y)\n return Kb\n\ndef API520_A_g(m: float, T: float, Z: float, MW: float, k: float, P1: float, P2: float=101325, Kd: float=0.975, Kb: float=1, Kc: float=1) -> float:\n r\"\"\"Calculates required relief valve area for an API 520 valve passing\n a gas or a vapor, at either critical or sub-critical flow.\n\n For critical flow:\n\n .. math::\n A = \\frac{m}{CK_dP_1K_bK_c}\\sqrt{\\frac{TZ}{M}}\n\n For sub-critical flow:\n\n .. math::\n A = \\frac{17.9m}{F_2K_dK_c}\\sqrt{\\frac{TZ}{MP_1(P_1-P_2)}}\n\n Parameters\n ----------\n m : float\n Mass flow rate of vapor through the valve, [kg/s]\n T : float\n Temperature of vapor entering the valve, [K]\n Z : float\n Compressibility factor of the vapor, [-]\n MW : float\n Molecular weight of the vapor, [g/mol]\n k : float\n Isentropic coefficient or ideal gas heat capacity ratio [-]\n P1 : float\n Upstream relieving pressure; the set pressure plus the allowable\n overpressure, plus atmospheric pressure, [Pa]\n P2 : float, optional\n Built-up backpressure; the increase in pressure during flow at the\n outlet of a pressure-relief device after it opens, [Pa]\n Kd : float, optional\n The effective coefficient of discharge, from the manufacturer or for\n preliminary sizing, using 0.975 normally or 0.62 when used with a\n rupture disc as described in [1]_, []\n Kb : float, optional\n Correction due to vapor backpressure [-]\n Kc : float, optional\n Combination correction factor for installation with a rupture disk\n upstream of the PRV; 1.0 when a rupture disk is not installed, and\n 0.9 if a rupture disk is present and the combination has not been\n certified, []\n\n Returns\n -------\n A : float\n Minimum area for relief valve according to [1]_, [m^2]\n\n Notes\n -----\n Units are interlally kg/hr, kPa, and mm^2 to match [1]_.\n\n Examples\n --------\n Example 1 from [1]_ for critical flow, matches:\n\n >>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, Kb=1, Kc=1)\n 0.0036990460646834414\n\n Example 2 from [1]_ for sub-critical flow, matches:\n\n >>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, P2=532E3, Kd=0.975, Kb=1, Kc=1)\n 0.004248358775943481\n\n The mass flux in (kg/(s*m^2)) can be found by dividing the specified mass\n flow by the calculated area:\n\n >>> (24270/3600.)/API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, Kb=1, Kc=1)\n 1822.541960488834\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n P1, P2 = P1*1e-3, P2*1e-3 # Pa to Kpa in the standard\n m = m*3600. # kg/s to kg/hr\n if is_critical_flow(P1, P2, k):\n C = API520_C(k)\n A = m/(C*Kd*Kb*Kc*P1)*sqrt(T*Z/MW)\n else:\n F2 = API520_F2(k, P1, P2)\n A = 17.9*m/(F2*Kd*Kc)*sqrt(T*Z/(MW*P1*(P1-P2)))\n return A*1e-6\n\ndef API520_W(Pset: float, Pback: float) -> float:\n r\"\"\"Calculates capacity correction due to backpressure on balanced\n spring-loaded PRVs in liquid service. For pilot operated valves,\n this is always 1. Applicable up to 50% of the percent gauge backpressure,\n For use in API 520 relief valve sizing. 1D interpolation among a table with\n 53 backpressures is performed.\n\n Parameters\n ----------\n Pset : float\n Set pressure for relief [Pa]\n Pback : float\n Backpressure, [Pa]\n\n Returns\n -------\n KW : float\n Correction due to liquid backpressure [-]\n\n Notes\n -----\n If the calculated gauge backpressure is less than 15%, a value of 1 is\n returned.\n\n Examples\n --------\n Custom example from figure 31 in [1]_:\n\n >>> API520_W(1E6, 3E5) # 22% overpressure\n 0.95114718480085\n\n Example 5 from [2]_, set pressure 250 psig and backpressure up to 50 psig:\n\n >>> API520_W(Pset=1825014, Pback=446062)\n 0.97242133397677\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection. 7E\n .. [2] API Standard 520, Part 1 - Sizing and Selection. 10E\n \"\"\"\n gauge_backpressure = (Pback-atm)/(Pset-atm)*100.0 # in percent\n if gauge_backpressure < 15.0:\n return 1.0\n return interp(gauge_backpressure, Kw_x, Kw_y)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 11658}, "tests/test_two_phase_voidage.py::324": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/two_phase_voidage.py"], "used_names": ["assert_close", "gas_liquid_viscosity", "gas_liquid_viscosity_methods", "pytest"], "enclosing_function": "test_gas_liquid_viscosity", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/two_phase_voidage.py\ndef gas_liquid_viscosity_methods(rhol: float | None=None, rhog: float | None=None, check_ranges: bool=False) -> list[str]:\n r\"\"\"This function returns a list of methods which can be used for calculating\n two-phase liquid-gas viscosity.\n Six calculation methods are available; three of them require only `x`,\n `mul`, and `mug`; the other three require `rhol` and `rhog` as well.\n\n Parameters\n ----------\n rhol : float, optional\n Liquid density, [kg/m^3]\n rhog : float, optional\n Gas density, [kg/m^3]\n check_ranges : bool, optional\n Added for compatibility only, never used\n\n Returns\n -------\n methods : list\n List of methods which can be used to calculate two-phase liquid-gas\n viscosity with the given inputs.\n\n Examples\n --------\n >>> gas_liquid_viscosity_methods()\n ['McAdams', 'Cicchitti', 'Lin Kwok']\n >>> gas_liquid_viscosity_methods(rhol=1000, rhog=2)\n ['Beattie Whalley', 'Fourar Bories', 'Duckler', 'McAdams', 'Cicchitti', 'Lin Kwok']\n \"\"\"\n methods = [\"McAdams\", \"Cicchitti\", \"Lin Kwok\"]\n if rhol is not None and rhog is not None:\n methods = liquid_gas_viscosity_correlations_list\n return methods\n\ndef gas_liquid_viscosity(x: float, mul: float, mug: float, rhol: float | None=None, rhog: float | None=None, Method: str | None=None) -> float:\n r\"\"\"This function handles the calculation of two-phase liquid-gas viscosity.\n Six calculation methods are available; three of them require only `x`,\n `mul`, and `mug`; the other three require `rhol` and `rhog` as well.\n\n The 'McAdams' method will be used if no method is specified.\n The full list of correlation can be obtained with the `AvailableMethods`\n flag.\n\n **ALL OF THESE METHODS ARE ONLY SUGGESTED DEFINITIONS, POTENTIALLY\n USEFUL FOR EMPIRICAL WORK ONLY!**\n\n Parameters\n ----------\n x : float\n Quality of fluid, [-]\n mul : float\n Viscosity of liquid, [Pa*s]\n mug : float\n Viscosity of gas, [Pa*s]\n rhol : float, optional\n Liquid density, [kg/m^3]\n rhog : float, optional\n Gas density, [kg/m^3]\n\n Returns\n -------\n mu_lg : float\n Liquid-gas viscosity (**a suggested definition, potentially useful\n for empirical work only!**) [Pa*s]\n\n Other Parameters\n ----------------\n Method : string, optional\n A string of the function name to use, as in the dictionary\n liquid_gas_viscosity_correlations.\n\n Notes\n -----\n All of these models converge to the liquid or gas viscosity as the quality\n approaches either limits. Other definitions have been proposed, such as\n using only liquid viscosity.\n\n These values cannot just be plugged into single phase correlations!\n\n Examples\n --------\n >>> gas_liquid_viscosity(x=0.4, mul=1E-3, mug=1E-5, rhol=850, rhog=1.2, Method='Duckler')\n 1.2092040385066917e-05\n >>> gas_liquid_viscosity(x=0.4, mul=1E-3, mug=1E-5)\n 2.4630541871921184e-05\n \"\"\"\n if Method is None:\n Method = \"McAdams\"\n\n # Type narrowing: validate required parameters based on selected method\n # Initialize to dummy values for numba (will be overwritten before use)\n rhol2 = 0.0\n rhog2 = 0.0\n\n if Method in gas_liquid_viscosity_methods_needing_rhol:\n if rhol is None:\n raise TypeError(f\"{Method} requires rhol\")\n rhol2 = rhol\n if Method in gas_liquid_viscosity_methods_needing_rhog:\n if rhog is None:\n raise TypeError(f\"{Method} requires rhog\")\n rhog2 = rhog\n\n if Method == \"Beattie Whalley\":\n return Beattie_Whalley(x, mul, mug, rhol=rhol2, rhog=rhog2)\n elif Method == \"Fourar Bories\":\n return Fourar_Bories(x, mul, mug, rhol=rhol2, rhog=rhog2)\n elif Method == \"Duckler\":\n return Duckler(x, mul, mug, rhol=rhol2, rhog=rhog2)\n elif Method == \"McAdams\":\n return McAdams(x, mul, mug)\n elif Method == \"Cicchitti\":\n return Cicchitti(x, mul, mug)\n elif Method == \"Lin Kwok\":\n return Lin_Kwok(x, mul, mug)\n else:\n raise ValueError(_gas_liquid_viscosity_method_unknown)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 4787}, "tests/test_atmosphere.py::57": {"resolved_imports": ["fluids/atmosphere.py", "fluids/numerics/__init__.py"], "used_names": ["ATMOSPHERE_1976", "assert_close", "assert_close1d"], "enclosing_function": "test_ATMOSPHERE_1976", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 846}, "tests/test_atmosphere.py::59": {"resolved_imports": ["fluids/atmosphere.py", "fluids/numerics/__init__.py"], "used_names": ["ATMOSPHERE_1976", "assert_close", "assert_close1d"], "enclosing_function": "test_ATMOSPHERE_1976", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 846}, "tests/test_atmosphere.py::63": {"resolved_imports": ["fluids/atmosphere.py", "fluids/numerics/__init__.py"], "used_names": ["ATMOSPHERE_1976", "assert_close", "assert_close1d"], "enclosing_function": "test_ATMOSPHERE_1976", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 846}, "tests/test_control_valve.py::352": {"resolved_imports": ["fluids/control_valve.py", "fluids/fittings.py", "fluids/numerics/__init__.py"], "used_names": ["Cv_to_Kv", "assert_close", "control_valve_noise_g_2011", "pytest"], "enclosing_function": "test_control_valve_noise_g_2011", "extracted_code": "# Source: fluids/control_valve.py\ndef control_valve_noise_g_2011(m: float, P1: float, P2: float, T1: float, rho: float, gamma: float, MW: float, Kv: float,\n d: float, Di: float, t_pipe: float, Fd: float, FL: float | None, FLP: float | None=None, FP: float | None=None,\n rho_pipe: float=7800.0, c_pipe: float=5000.0,\n P_air: float=101325.0, rho_air: float=1.2, c_air: float=343.0,\n An: float=-3.8, Stp: float=0.2, T2: float | None=None, beta: float=0.93) -> float:\n r\"\"\"Calculates the sound made by a gas flowing through a control valve\n according to the standard IEC 60534-8-3 (2011) [1]_.\n\n Parameters\n ----------\n m : float\n Mass flow rate of gas through the control valve, [kg/s]\n P1 : float\n Inlet pressure of the gas before valves and reducers [Pa]\n P2 : float\n Outlet pressure of the gas after valves and reducers [Pa]\n T1 : float\n Inlet gas temperature, [K]\n rho : float\n Density of the gas at the inlet [kg/m^3]\n gamma : float\n Specific heat capacity ratio [-]\n MW : float\n Molecular weight of the gas [g/mol]\n Kv : float\n Metric Kv valve flow coefficient (flow rate of water at a pressure drop\n of 1 bar) [m^3/hr]\n d : float\n Diameter of the valve [m]\n Di : float\n Internal diameter of the pipe before and after the valve [m]\n t_pipe : float\n Wall thickness of the pipe after the valve, [m]\n Fd : float\n Valve style modifier (0.1 to 1; varies tremendously depending on the\n type of valve and position; do not use the default at all!) [-]\n FL : float\n Liquid pressure recovery factor of a control valve without attached\n fittings (normally 0.8-0.9 at full open and decreasing as opened\n further to below 0.5; use default very cautiously!) [-]\n FLP : float, optional\n Combined liquid pressure recovery factor with piping geometry factor,\n for a control valve with attached fittings [-]\n FP : float, optional\n Piping geometry factor [-]\n rho_pipe : float, optional\n Density of the pipe wall material at flowing conditions, [kg/m^3]\n c_pipe : float, optional\n Speed of sound of the pipe wall material at flowing conditions, [m/s]\n P_air : float, optional\n Pressure of the air surrounding the valve and pipe wall, [Pa]\n rho_air : float, optional\n Density of the air surrounding the valve and pipe wall, [kg/m^3]\n c_air : float, optional\n Speed of sound of the air surrounding the valve and pipe wall, [m/s]\n An : float, optional\n Valve correction factor for acoustic efficiency, [-]\n Stp : float, optional\n Strouhal number at the peak `fp`; between 0.1 and 0.3 typically, [-]\n T2 : float, optional\n Outlet gas temperature; assumed `T1` if not provided (a PH flash\n should be used to obtain this if possible), [K]\n beta : float, optional\n Valve outlet / expander inlet contraction coefficient, [-]\n\n Returns\n -------\n LpAe1m : float\n A-weighted sound pressure level 1 m from the pipe wall, 1 m distance\n dowstream of the valve (at reference sound pressure level 2E-5), [dB]\n\n Notes\n -----\n For formulas see [1]_. This takes on the order of 100 us to compute.\n For values of `An`, see [1]_.\n\n This model was checked against six examples in [1]_; they match to all\n given decimals.\n\n Several additional formulas are given for multihole trim valves,\n control valves with two or more fixed area stages, and multipath,\n multistage trim valves.\n\n Examples\n --------\n >>> control_valve_noise_g_2011(m=2.22, P1=1E6, P2=7.2E5, T1=450, rho=5.3,\n ... gamma=1.22, MW=19.8, Kv=77.85, d=0.1, Di=0.2031, FL=None, FLP=0.792,\n ... FP=0.98, Fd=0.296, t_pipe=0.008, rho_pipe=8000.0, c_pipe=5000.0,\n ... rho_air=1.293, c_air=343.0, An=-3.8, Stp=0.2)\n 91.67702674629604\n\n References\n ----------\n .. [1] IEC 60534-8-3 : Industrial-Process Control Valves - Part 8-3: Noise\n Considerations - Control Valve Aerodynamic Noise Prediction Method.\"\n \"\"\"\n k = gamma # alias\n C = Kv_to_Cv(Kv)\n N14 = 4.6E-3\n # N16 = 4.89E4\n # fs = 1.0 # structural loss factor reference frequency, Hz\n P_air_std = 101325.0\n if T2 is None:\n T2 = T1\n x = (P1 - P2)/P1\n\n # FLP/FP when fittings attached\n if FP is not None and FLP is not None:\n FL_term = FLP/FP\n elif FL is not None:\n FL_term = FL\n else:\n raise ValueError(\"Either FL must be specified, or both FLP and FP must be specified\")\n\n # P_vc = P1*(1.0 - x/FL_term**2)\n\n x_vcc = 1.0 - (2.0/(k + 1.0))**(k/(k - 1.0)) # mostly matches\n xc = FL_term**2*x_vcc\n alpha = (1.0 - x_vcc)/(1.0 - xc)\n xB = 1.0 - 1.0/alpha*(1.0/k)**(k/(k - 1.0))\n xCE = 1.0 - 1.0/(22.0*alpha)\n\n # Regime determination check - should be ordered or won't work\n# assert xc < x_vcc\n# assert x_vcc < xB\n# assert xB < xCE\n if x <= xc:\n regime = 1\n elif xc < x <= x_vcc:\n regime = 2\n elif x_vcc < x <= xB:\n regime = 3\n elif xB < x <= xCE:\n regime = 4\n else:\n regime = 5\n# print('regime', regime)\n\n Dj = N14*Fd*sqrt(C*(FL_term))\n\n Mj5 = sqrt(2.0/(k - 1.0)*( 22.0**((k-1.0)/k) - 1.0 ))\n if regime == 1:\n Mvc = sqrt((2.0/(k-1.0)) *((1.0 - x/FL_term**2)**((1.0 - k)/k) - 1.0)) # Not match\n elif regime in (2, 3, 4):\n Mj = sqrt((2.0/(k-1.0))*((1.0/(alpha*(1.0-x)))**((k - 1.0)/k) - 1.0)) # Not match\n Mj = min(Mj, Mj5)\n# elif regime == 5:\n# pass\n\n if regime == 1:\n # Tvc = T1*(1.0 - x/(FL_term)**2)**((k - 1.0)/k)\n cvc = sqrt(k*P1/rho*(1 - x/(FL_term)**2)**((k-1.0)/k))\n Wm = 0.5*m*(Mvc*cvc)**2\n else:\n # Tvcc = 2.0*T1/(k + 1.0)\n cvcc = sqrt(2.0*k*P1/(k+1.0)/rho)\n Wm = 0.5*m*cvcc*cvcc\n# print('Wm', Wm)\n\n if regime == 1:\n fp = Stp*Mvc*cvc/Dj\n elif regime in (2, 3):\n fp = Stp*Mj*cvcc/Dj\n elif regime == 4:\n fp = 1.4*Stp*cvcc/Dj/sqrt(Mj*Mj - 1.0)\n elif regime == 5:\n fp = 1.4*Stp*cvcc/Dj/sqrt(Mj5*Mj5 - 1.0)\n fp_inv = 1.0/fp\n# print('fp', fp)\n\n if regime == 1:\n eta = 10.0**An*FL_term**2*(Mvc)**3\n elif regime == 2:\n eta = 10.0**An*x/x_vcc*Mj**(6.6*FL_term*FL_term)\n elif regime == 3:\n eta = 10.0**An*Mj**(6.6*FL_term*FL_term)\n elif regime == 4:\n eta = 0.5*10.0**An*Mj*Mj*(sqrt(2.0))**(6.6*FL_term*FL_term)\n elif regime == 5:\n eta = 0.5*10.0**An*Mj5*Mj5*(sqrt(2.0))**(6.6*FL_term*FL_term)\n# print('eta', eta)\n\n Wa = eta*Wm\n\n rho2 = rho*(P2/P1)\n # Speed of sound\n c2 = sqrt(k*R*T2/(MW/1000.))\n\n # Mo = 4.0*m/(pi*d*d*rho2*c2)\n\n M2 = 4.0*m/(pi*Di*Di*rho2*c2)\n# print('M2', M2)\n\n Lg = 16.0*log10(1.0/(1.0 - min(M2, 0.3))) # dB\n\n if M2 > 0.3:\n Up = 4.0*m/(pi*rho2*Di*Di)\n UR = Up*Di*Di/(beta*d*d)\n WmR = 0.5*m*UR*UR*( (1.0 - d*d/(Di*Di))**2 + 0.2)\n fpR = Stp*UR/d\n MR = UR/c2\n # Value listed in appendix here is wrong, \"based on another\n # earlier standard. Calculation thereon is wrong\". Assumed\n # correct, matches spreadsheet to three decimals.\n eta_R = 10**An*MR**3\n WaR = eta_R*WmR\n L_piR = 10.0*log10((3.2E9)*WaR*rho2*c2/(Di*Di)) + Lg\n# print('Up', Up)\n# print('UR', UR)\n# print('WmR', WmR)\n# print('fpR', fpR)\n# print('MR', MR)\n# print('eta_R', eta_R, eta_R/8.8E-4)\n# print('WaR', WaR)\n# print('L_piR', L_piR)\n\n L_pi = 10.0*log10((3.2E9)*Wa*rho2*c2/(Di*Di)) + Lg\n# print('L_pi', L_pi)\n\n fr = c_pipe/(pi*Di)\n fo = 0.25*fr*(c2/c_air)\n fg = sqrt(3)*c_air**2/(pi*t_pipe*c_pipe)\n\n if d > 0.15:\n dTL = 0.0\n elif 0.05 <= d <= 0.15:\n dTL = -16660.0*d**3 + 6370.0*d**2 - 813.0*d + 35.8\n else:\n dTL = 9.0\n# print(dTL, 'dTL')\n\n P_air_ratio = P_air/P_air_std\n\n LpAe1m_sum = 0.0\n# LPis = []\n# LPIRs = []\n# L_pe1m_fis = []\n for fi, A_weight in zip(fis_l_2015, A_weights_l_2015):\n # This gets adjusted when Ma > 0.3\n fi_turb_ratio = fi*fp_inv\n\n t1 = 1.0 + (0.5*fi_turb_ratio)**2.5\n t2 = 1.0 + (0.5/fi_turb_ratio)**1.7\n\n # Formula forgot to use log10, but log10 is needed for the numbers\n Lpif = L_pi - 8.0 - 10.0*log10(t1*t2)\n# print(Lpif, 'Lpif')\n# LPis.append(Lpif)\n\n if M2 > 0.3:\n fiR_turb_ratio = fi/fpR\n t1 = 1.0 + (0.5*fiR_turb_ratio)**2.5\n t2 = 1.0 + (0.5/fiR_turb_ratio)**1.7\n # Again, log10 is missing\n LpiRf = L_piR - 8.0 - 10.0*log10(t1*t2)\n# LPIRs.append(LpiRf)\n\n LpiSf = 10.0*log10( 10**(0.1*Lpif) + 10.0**(0.1*LpiRf) )\n\n if fi < fo:\n Gx = (fo/fr)**(2.0/3.0)*(fi/fo)**4.0\n if fo < fg:\n Gy = (fo/fg)\n else:\n Gy = 1.0\n else:\n if fi < fr:\n Gx = sqrt(fi/fr)\n else:\n Gx = 1.0\n if fi < fg:\n Gy = fi/fg\n else:\n Gy = 1.0\n\n eta_s = sqrt(0.01/fi)\n# print('eta_s', eta_s)\n # up to eta_s is good\n\n den = (rho2*c2 + 2.0*pi*t_pipe*fi*rho_pipe*eta_s)/(415.0*Gy) + 1.0\n TL_fi = 10.0*log10(8.25E-7*(c2/(t_pipe*fi))**2*Gx/den*P_air_ratio) - dTL\n\n # Formula forgot to use log10, but log10 is needed for the numbers\n if M2 > 0.3:\n term = LpiSf\n else:\n term = Lpif\n\n L_pe1m_fi = term + TL_fi - 10.0*log10((Di + 2.0*t_pipe + 2.0)/(Di + 2.0*t_pipe))\n# L_pe1m_fis.append(L_pe1m_fi)\n# print(L_pe1m_fi)\n\n LpAe1m_sum += 10.0**(0.1*(L_pe1m_fi + A_weight))\n LpAe1m = 10.0*log10(LpAe1m_sum)\n return LpAe1m\n\n\n# Source: fluids/fittings.py\ndef Cv_to_Kv(Cv: float) -> float:\n r\"\"\"Convert valve flow coefficient from imperial to common metric units.\n\n .. math::\n K_v = C_v/1.156\n\n Parameters\n ----------\n Cv : float\n Imperial Cv valve flow coefficient (flow rate of water at a pressure\n drop of 1 psi) [gallons/minute]\n\n Returns\n -------\n Kv : float\n Metric Kv valve flow coefficient (flow rate of water at a pressure drop\n of 1 bar) [m^3/hr]\n\n Notes\n -----\n Kv = 0.865 Cv is in the IEC standard 60534-2-1.\n It has also been said that Cv = 1.17Kv; this is wrong by current standards.\n\n The conversion factor does not depend on the density of the fluid or the\n diameter of the valve. It is calculated with the definition of a US gallon\n as 231 cubic inches, and a psi as a pound-force per square inch.\n\n The exact conversion coefficient between Kv to Cv is 1.1560992283536566;\n it is rounded in the formula above.\n\n Examples\n --------\n >>> Cv_to_Kv(2.312)\n 1.9998283393826013\n\n References\n ----------\n .. [1] ISA-75.01.01-2007 (60534-2-1 Mod) Draft\n \"\"\"\n return Cv/1.1560992283536566\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 11763}, "tests/test_numba.py::668": {"resolved_imports": ["fluids/__init__.py", "fluids/vectorized.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close1d", "fluids"], "enclosing_function": "test_numerics_solve_direct", "extracted_code": "# Source: fluids/__init__.py\n def __getattr__(name):\n if name == \"vectorized\":\n import fluids.vectorized\n globals()[name] = fluids.vectorized\n return fluids.vectorized\n if name == \"numba\":\n import fluids.numba\n globals()[name] = fluids.numba\n return fluids.numba\n if name == \"units\":\n import fluids.units\n globals()[name] = fluids.units\n\n if name == \"vectorized\":\n import fluids.vectorized\n globals()[name] = fluids.vectorized\n return fluids.vectorized\n if name == \"numba\":\n import fluids.numba\n globals()[name] = fluids.numba\n return fluids.numba\n if name == \"units\":\n import fluids.units\n globals()[name] = fluids.units\n return fluids.units\n\n import fluids.vectorized\n globals()[name] = fluids.vectorized\n return fluids.vectorized\n if name == \"numba\":\n import fluids.numba\n globals()[name] = fluids.numba\n return fluids.numba\n if name == \"units\":\n import fluids.units\n globals()[name] = fluids.units\n return fluids.units\n if name == \"numba_vectorized\":\n\n return fluids.vectorized\n if name == \"numba\":\n import fluids.numba\n globals()[name] = fluids.numba\n return fluids.numba\n if name == \"units\":\n import fluids.units\n globals()[name] = fluids.units\n return fluids.units\n if name == \"numba_vectorized\":\n import fluids.numba_vectorized\n globals()[name] = fluids.numba_vectorized\n\n if name == \"numba\":\n import fluids.numba\n globals()[name] = fluids.numba\n return fluids.numba\n if name == \"units\":\n import fluids.units\n globals()[name] = fluids.units\n return fluids.units\n if name == \"numba_vectorized\":\n import fluids.numba_vectorized\n globals()[name] = fluids.numba_vectorized\n return fluids.numba_vectorized\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 2478}, "tests/test_numerics_special.py::203": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/special.py"], "used_names": ["comb", "py_comb"], "enclosing_function": "test_py_comb", "extracted_code": "# Source: fluids/numerics/__init__.py\n stable_poly_to_unstable,\n)\nfrom fluids.numerics.special import cbrt, comb, factorial, py_cacos, py_catan, py_catanh, py_hypot, trunc_exp, trunc_log\n\n__all__ = [\n \"IS_PYPY\",\n \"NoSolutionError\",\n \"NotBoundedError\",\n \"OscillationError\",\n \"SamePointError\",\n \"SolverInterface\",\n \"UnconvergedError\",\n\n \"chebval_ln_tau_and_der3\",\n \"clog\",\n \"comb\",\n \"csqrt\",\n \"cube_dd\",\n \"cumsum\",\n \"cumulative_trapezoid\",\n \"curve_fit\",\n \"damping_maintain_sign\",\n \"deflate_cubic_real_roots\",\n \"derivative\",\n \"detect_outlier_normal\",", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 607}, "tests/test_packed_tower.py::89": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/packed_tower.py"], "used_names": ["assert_close", "separation_demister_ElDessouky"], "enclosing_function": "test_separation_demister_ElDessouky", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/packed_tower.py\ndef separation_demister_ElDessouky(vs: float, voidage: float, d_wire: float, d_drop: float) -> float:\n r\"\"\"Calculates droplet removal by a demister as a fraction from 0 to 1,\n using the correlation in [1]_. Uses only their own experimental data.\n\n .. math::\n \\eta = 0.85835(d_w)^{-0.28264}(1-\\epsilon)^{0.099625}(V)^{0.106878}\n (d_p)^{0.383197}\n\n Parameters\n ----------\n vs : float\n Superficial velocity of fluid, Q/A [m/s]\n voidage : float\n Voidage of bed of the demister material, normally ~0.98 []\n d_wire : float\n Diameter of mesh wire, [m]\n d_drop : float\n Drop diameter, [m]\n\n Returns\n -------\n eta : float\n Fraction droplets removed by mass [-]\n\n Notes\n -----\n No dependency on the liquid properties is included here. Because of the\n exponential nature of the correlation, for smaller diameters separation\n quickly lowers. This correlation can predict a separation larger than 1\n for higher velocities, lower voidages, lower wire diameters, and large\n droplet sizes. This function truncates these larger values to 1.\n\n The correlation in [1]_ was presented as follows, with wire diameter in\n units of mm, density in kg/m^3, V in m/s, separation in %, and particle\n diameter in mm.\n\n .. math::\n \\eta = 17.5047(d_w)^{-0.28264}(\\rho_{mesh})^{0.099625}(V)^{0.106878}\n (d_p)^{0.383197}\n\n Here, the correlation is converted to base SI units and to use voidage;\n not all demisters are stainless steel as in [1]_. A density of 7999 kg/m^3\n was used in the conversion.\n\n In [1]_, V ranged from 0.98-7.5 m/s, rho from 80.317-208.16 kg/m^3, depth\n from 100 to 200 mm, wire diameter of 0.2 mm to 0.32 mm, and particle\n diameter from 1 to 5 mm.\n\n Examples\n --------\n >>> separation_demister_ElDessouky(1.35, 0.974, 0.0002, 0.005)\n 0.8982892997640582\n\n References\n ----------\n .. [1] El-Dessouky, Hisham T, Imad M Alatiqi, Hisham M Ettouney, and Noura\n S Al-Deffeeri. \"Performance of Wire Mesh Mist Eliminator.\" Chemical\n Engineering and Processing: Process Intensification 39, no. 2 (March\n 2000): 129-39. doi:10.1016/S0255-2701(99)00033-1.\n \"\"\"\n eta = 0.858352355761947*d_wire**-0.28264*(1-voidage)**0.099625*vs**0.106878*d_drop**0.383197\n return min(eta, 1.0)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2996}, "tests/test_particle_size_distribution.py::85": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/particle_size_distribution.py"], "used_names": ["Sieve"], "enclosing_function": "test_sieve_repr_includes_set_fields", "extracted_code": "# Source: fluids/particle_size_distribution.py\nclass Sieve:\n r\"\"\"Class for storing data on sieves. If a property is not available, it is\n set to None.\n\n Attributes\n ----------\n designation : str\n The standard name of the sieve - its opening's length in units of\n millimeters\n opening : float\n The opening length of the sieve holes, [m]\n old_designation : str\n The older, imperial-esque name of the sieve; in Numbers, or inches for\n large sieves\n opening_inch : float\n The opening length of the sieve holes in the rounded inches as stated\n in common tables (not exactly equal to the `opening`), [inch]\n Y_variation_avg : float\n The allowable average variation in the Y direction of the sieve\n openings, [m]\n X_variation_max : float\n The allowable maximum variation in the X direction of the sieve\n openings, [m]\n max_opening : float\n The maximum allowable opening of the sieve, [m]\n calibration_samples : float\n The number of opening sample inspections required for `calibration`-\n type sieve openings (per 100 ft^2 of sieve material), [1/(ft^2)]\n compliance_sd : float\n The maximum standard deviation of `compliance`-type sieve openings,\n [-]\n inspection_samples : float\n The number of opening sample inspections required for `inspection`-\n type sieve openings (based on an 8-inch sieve), [-]\n inspection_sd : float\n The maximum standard deviation of `inspection`-type sieve openings,\n [-]\n calibration_samples : float\n The number of opening sample inspections required for `calibration`-\n type sieve openings (based on an 8-inch sieve), [-]\n calibration_sd : float\n The maximum standard deviation of `calibration`-type sieve openings,\n [-]\n d_wire : float\n Typical wire diameter of the specified sieve size, [m]\n d_wire_min : float\n Permissible minimum wire diameter of specified sieve size, [m]\n d_wire_max : float\n Permissible maximum wire diameter of specified sieve size, [m]\n\n \"\"\"\n\n __slots__ = (\n \"X_variation_max\",\n \"Y_variation_avg\",\n \"calibration_samples\",\n \"calibration_sd\",\n \"compliance_samples\",\n \"compliance_sd\",\n \"d_wire\",\n \"d_wire_max\",\n \"d_wire_min\",\n \"designation\",\n \"inspection_samples\",\n \"inspection_sd\",\n \"max_opening\",\n \"old_designation\",\n \"opening\",\n \"opening_inch\",\n )\n\n def __repr__(self):\n fields = []\n for attr in self.__slots__:\n value = getattr(self, attr)\n if value is None:\n continue\n if isinstance(value, float):\n rendered = f\"{value:g}\"\n else:\n rendered = repr(value)\n fields.append(f\"{attr}={rendered}\")\n params = \", \".join(fields)\n return f\"Sieve({params})\"\n\n def __str__(self):\n return f\"\"\n\n def __init__(self, designation: str, opening: float, old_designation: str | None=None,\n opening_inch: float | None=None, Y_variation_avg: float | None=None, X_variation_max: float | None=None,\n max_opening: float | None=None, compliance_samples: float | None=None, compliance_sd: float | None=None,\n inspection_samples: float | None=None, inspection_sd: float | None=None, calibration_samples: float | None=None,\n calibration_sd: float | None=None, d_wire: float | None=None, d_wire_min: float | None=None, d_wire_max: float | None=None) -> None:\n self.designation = designation\n self.old_designation = old_designation\n self.opening_inch = opening_inch\n self.opening = opening\n\n self.Y_variation_avg = Y_variation_avg\n self.X_variation_max = X_variation_max\n self.max_opening = max_opening\n\n self.compliance_samples = compliance_samples\n self.compliance_sd = compliance_sd\n\n self.inspection_samples = inspection_samples\n self.inspection_sd = inspection_sd\n\n self.calibration_samples = calibration_samples\n self.calibration_sd = calibration_sd\n\n self.d_wire = d_wire\n self.d_wire_min = d_wire_min\n self.d_wire_max = d_wire_max", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 4413}, "tests/test_particle_size_distribution.py::198": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/particle_size_distribution.py"], "used_names": ["assert_close", "pdf_lognormal", "stats"], "enclosing_function": "test_pdf_lognormal", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/particle_size_distribution.py\ndef pdf_lognormal(d: float, d_characteristic: float, s: float) -> float:\n r\"\"\"Calculates the probability density function of a lognormal particle\n distribution given a particle diameter `d`, characteristic particle\n diameter `d_characteristic`, and distribution standard deviation `s`.\n\n .. math::\n q(d) = \\frac{1}{ds\\sqrt{2\\pi}} \\exp\\left[-0.5\\left(\\frac{\n \\ln(d/d_{characteristic})}{s}\\right)^2\\right]\n\n Parameters\n ----------\n d : float\n Specified particle diameter, [m]\n d_characteristic : float\n Characteristic particle diameter; often D[3, 3] is used for this\n purpose but not always, [m]\n s : float\n Distribution standard deviation, [-]\n\n Returns\n -------\n pdf : float\n Lognormal probability density function, [-]\n\n Notes\n -----\n The characteristic diameter can be in terns of number density (denoted\n :math:`q_0(d)`), length density (:math:`q_1(d)`), surface area density\n (:math:`q_2(d)`), or volume density (:math:`q_3(d)`). Volume density is\n most often used. Interconversions among the distributions is possible but\n tricky.\n\n The standard distribution (i.e. the one used in Scipy) can perform the same\n computation with `d_characteristic` as the value of `scale`.\n\n >>> import scipy.stats\n >>> float(scipy.stats.lognorm.pdf(x=1E-4, s=1.1, scale=1E-5))\n 405.5420921\n\n Scipy's calculation is over 300 times slower however, and this expression\n is numerically integrated so speed is required.\n\n Examples\n --------\n >>> pdf_lognormal(1E-4, 1E-5, 1.1)\n 405.5420921\n\n References\n ----------\n .. [1] ISO 9276-2:2014 - Representation of Results of Particle Size\n Analysis - Part 2: Calculation of Average Particle Sizes/Diameters and\n Moments from Particle Size Distributions.\n \"\"\"\n try:\n log_term = log(d/d_characteristic)/s\n except ValueError:\n return 0.0\n return 1./(d*s*ROOT_TWO_PI)*exp(-0.5*log_term*log_term)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 2663}, "tests/test_safety_valve.py::90": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/numerics/__init__.py", "fluids/safety_valve.py"], "used_names": ["API520_Kv", "assert_close", "assert_close1d", "pytest"], "enclosing_function": "test_API520_Kv", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\n\n# Source: fluids/safety_valve.py\ndef API520_Kv(Re, edition=TENTH_EDITION):\n r\"\"\"Calculates correction due to viscosity for liquid flow for use in\n API 520 relief valve sizing.\n\n From the 7th to 9th editions, the formula for this calculation is as\n follows:\n\n .. math::\n K_v = \\left(0.9935 + \\frac{2.878}{Re^{0.5}} + \\frac{342.75}\n {Re^{1.5}}\\right)^{-1}\n\n Startign in the 10th edition, the formula is\n\n .. math::\n K_v = \\left(1 + \\frac{170}{Re}\\right)^{-0.5}\n\n In the 10th edition, the formula is applicable for Re > 80. It is also\n recommended there that if the viscosity is < 0.1 Pa*s, this correction\n should be set to 1.\n\n Parameters\n ----------\n Re : float\n Reynolds number for flow out the valve [-]\n edition : str, optional\n One of '10E', '7E', [-]\n\n Returns\n -------\n Kv : float\n Correction due to viscosity [-]\n\n Notes\n -----\n Reynolds number in the standard is defined as follows, with Q in L/min, G1\n as specific gravity, mu in centipoise, and area in mm^2:\n\n .. math::\n Re = \\frac{Q(18800G_1)}{\\mu \\sqrt{A}}\n\n The constant 18800 is derived as follows, combining multiple unit\n conversions and the formula from diameter from area together. The precise\n value is shown below.\n\n >>> from scipy.constants import *\n >>> liter/minute*1000./(0.001*(milli**2)**0.5)*sqrt(4/pi)\n 18806.319451591\n\n Note that 4 formulas are provided in API 520 part 1; two metric and two\n imperial. One pair of formulas uses viscosity in conventional units; the\n other uses it in Saybolt Universal Seconds. A conversion is essentially\n embedded in the the Saybolt Universal Seconds formula. A more precise\n conversion can be obtained from\n :obj:`chemicals.viscosity.viscosity_converter`.\n\n In both editions, if the formula is used below the recommended Re range\n and into the very low Re region this correction tends towards 0.\n\n In the 10th edition, the formula tends to 1 exactly as Re increases. In the\n 7th edition, the formula can actually produce corrections above 1; this is\n handled by truncating the factor to 1.\n\n Examples\n --------\n From [1]_ 7E, checked with example 5.\n\n >>> API520_Kv(100, edition='7E')\n 0.615744589\n\n From [2]_ 10E, checked with example 5:\n\n >>> API520_Kv(4525, edition='10E')\n 0.9817287137013179\n\n Example in [3]_, using the 7th edition formula:\n\n >>> API520_Kv(2110, edition='7E')\n 0.943671807\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection, 7E\n .. [2] API Standard 520, Part 1 - Sizing and Selection, 10E\n .. [3] CCPS. Guidelines for Pressure Relief and Effluent Handling Systems.\n 2nd edition. New York, NY: Wiley-AIChE, 2017.\n \"\"\"\n if edition == SEVENTH_EDITION:\n factor = 1.0/(0.9935 + 2.878/sqrt(Re) + 342.75/(Re*sqrt(Re)))\n if factor > 1.0:\n factor = 1.0\n return factor\n elif edition == TENTH_EDITION:\n return 1.0/sqrt(170.0/Re + 1.0)\n else:\n raise ValueError(\"Acceptable editions are '7E', '10E'\")", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 3982}, "tests/test_atmosphere.py::65": {"resolved_imports": ["fluids/atmosphere.py", "fluids/numerics/__init__.py"], "used_names": ["ATMOSPHERE_1976", "assert_close", "assert_close1d"], "enclosing_function": "test_ATMOSPHERE_1976", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 846}, "tests/test_flow_meter.py::222": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/flow_meter.py", "fluids/numerics/__init__.py"], "used_names": ["C_Miller_1996", "C_Reader_Harris_Gallagher", "MILLER_CONICAL_ORIFICE", "MILLER_ECCENTRIC_ORIFICE", "MILLER_ORIFICE", "MILLER_QUARTER_CIRCLE_ORIFICE", "MILLER_SEGMENTAL_ORIFICE", "ORIFICE_CORNER_TAPS", "ORIFICE_D_AND_D_2_TAPS", "ORIFICE_FLANGE_TAPS", "ORIFICE_PIPE_TAPS", "ORIFICE_VENA_CONTRACTA_TAPS", "TAPS_OPPOSITE", "TAPS_SIDE", "assert_close", "pytest"], "enclosing_function": "test_C_Miller_1996", "extracted_code": "# Source: fluids/flow_meter.py\nORIFICE_CORNER_TAPS = \"corner\"\n\nORIFICE_FLANGE_TAPS = \"flange\"\n\nORIFICE_D_AND_D_2_TAPS = \"D and D/2\"\n\nORIFICE_PIPE_TAPS = \"pipe\"\n\nORIFICE_VENA_CONTRACTA_TAPS = \"vena contracta\"\n\nTAPS_OPPOSITE = \"180 degree\"\n\nTAPS_SIDE = \"90 degree\"\n\nMILLER_ORIFICE = \"Miller orifice\"\n\nMILLER_ECCENTRIC_ORIFICE = \"Miller eccentric orifice\"\n\nMILLER_SEGMENTAL_ORIFICE = \"Miller segmental orifice\"\n\nMILLER_CONICAL_ORIFICE = \"Miller conical orifice\"\n\nMILLER_QUARTER_CIRCLE_ORIFICE = \"Miller quarter circle orifice\"\n\ndef C_Reader_Harris_Gallagher(D: float, Do: float, rho: float, mu: float, m: float, taps: str=\"corner\") -> float:\n r\"\"\"Calculates the coefficient of discharge of the orifice based on the\n geometry of the plate, measured pressures of the orifice, mass flow rate\n through the orifice, and the density and viscosity of the fluid.\n\n .. math::\n C = 0.5961 + 0.0261\\beta^2 - 0.216\\beta^8 + 0.000521\\left(\\frac{\n 10^6\\beta}{Re_D}\\right)^{0.7}\\\\\n + (0.0188 + 0.0063A)\\beta^{3.5} \\left(\\frac{10^6}{Re_D}\\right)^{0.3} \\\\\n +(0.043 + 0.080\\exp(-10L_1) -0.123\\exp(-7L_1))(1-0.11A)\\frac{\\beta^4}\n {1-\\beta^4} \\\\\n - 0.031(M_2' - 0.8M_2'^{1.1})\\beta^{1.3}\n\n .. math::\n M_2' = \\frac{2L_2'}{1-\\beta}\n\n .. math::\n A = \\left(\\frac{19000\\beta}{Re_{D}}\\right)^{0.8}\n\n .. math::\n Re_D = \\frac{\\rho v D}{\\mu}\n\n\n If D < 71.12 mm (2.8 in.) (Note this is a continuous addition; there is no\n discontinuity):\n\n .. math::\n C += 0.11(0.75-\\beta)\\left(2.8-\\frac{D}{0.0254}\\right)\n\n If the orifice has corner taps:\n\n .. math::\n L_1 = L_2' = 0\n\n If the orifice has D and D/2 taps:\n\n .. math::\n L_1 = 1\n\n .. math::\n L_2' = 0.47\n\n If the orifice has Flange taps:\n\n .. math::\n L_1 = L_2' = \\frac{0.0254}{D}\n\n Parameters\n ----------\n D : float\n Upstream internal pipe diameter, [m]\n Do : float\n Diameter of orifice at flow conditions, [m]\n rho : float\n Density of fluid at `P1`, [kg/m^3]\n mu : float\n Viscosity of fluid at `P1`, [Pa*s]\n m : float\n Mass flow rate of fluid through the orifice, [kg/s]\n taps : str\n The orientation of the taps; one of 'corner', 'flange', 'D', or 'D/2',\n [-]\n\n Returns\n -------\n C : float\n Coefficient of discharge of the orifice, [-]\n\n Notes\n -----\n The following limits apply to the orifice plate standard [1]_:\n\n The measured pressure difference for the orifice plate should be under\n 250 kPa.\n\n There are roughness limits as well; the roughness should be under 6\n micrometers, although there are many more conditions to that given in [1]_.\n\n For orifice plates with D and D/2 or corner pressure taps:\n\n * Orifice bore diameter must be larger than 12.5 mm (0.5 inches)\n * Pipe diameter between 50 mm and 1 m (2 to 40 inches)\n * Beta between 0.1 and 0.75 inclusive\n * Reynolds number larger than 5000 (for :math:`0.10 \\le \\beta \\le 0.56`)\n or for :math:`\\beta \\ge 0.56, Re_D \\ge 16000\\beta^2`\n\n For orifice plates with flange pressure taps:\n\n * Orifice bore diameter must be larger than 12.5 mm (0.5 inches)\n * Pipe diameter between 50 mm and 1 m (2 to 40 inches)\n * Beta between 0.1 and 0.75 inclusive\n * Reynolds number larger than 5000 and also larger than\n :math:`170000\\beta^2 D`.\n\n This is also presented in Crane's TP410 (2009) publication, whereas the\n 1999 and 1982 editions showed only a graph for discharge coefficients.\n\n Examples\n --------\n >>> C_Reader_Harris_Gallagher(D=0.07391, Do=0.0222, rho=1.165, mu=1.85E-5,\n ... m=0.12, taps='flange')\n 0.5990326277163659\n\n References\n ----------\n .. [1] American Society of Mechanical Engineers. Mfc-3M-2004 Measurement\n Of Fluid Flow In Pipes Using Orifice, Nozzle, And Venturi. ASME, 2001.\n .. [2] ISO 5167-2:2003 - Measurement of Fluid Flow by Means of Pressure\n Differential Devices Inserted in Circular Cross-Section Conduits Running\n Full -- Part 2: Orifice Plates.\n .. [3] Reader-Harris, M. J., \"The Equation for the Expansibility Factor for\n Orifice Plates,\" Proceedings of FLOMEKO 1998, Lund, Sweden, 1998:\n 209-214.\n .. [4] Reader-Harris, Michael. Orifice Plates and Venturi Tubes. Springer,\n 2015.\n \"\"\"\n A_pipe = 0.25*pi*D*D\n v = m/(A_pipe*rho)\n Re_D = rho*v*D/mu\n Re_D_inv = 1.0/Re_D\n\n beta = Do/D\n if taps == \"corner\":\n L1, L2_prime = 0.0, 0.0\n elif taps == \"flange\":\n L1 = L2_prime = 0.0254/D\n elif taps in (\"D\", \"D/2\", ORIFICE_D_AND_D_2_TAPS):\n L1 = 1.0\n L2_prime = 0.47\n else:\n raise ValueError(\"Unsupported tap location\")\n\n beta2 = beta*beta\n beta4 = beta2*beta2\n beta8 = beta4*beta4\n\n A = 2648.5177066967326*(beta*Re_D_inv)**0.8 # 19000.0^0.8 = 2648.51....\n M2_prime = 2.0*L2_prime/(1.0 - beta)\n\n # These two exps\n expnL1 = exp(-L1)\n expnL2 = expnL1*expnL1\n expnL3 = expnL1*expnL2\n delta_C_upstream = ((0.043 + expnL3*expnL2*expnL2*(0.080*expnL3 - 0.123))\n *(1.0 - 0.11*A)*beta4/(1.0 - beta4))\n\n # The max part is not in the ISO standard\n t1 = log10(3700.*Re_D_inv)\n if t1 < 0.0:\n t1 = 0.0\n delta_C_downstream = (-0.031*(M2_prime - 0.8*M2_prime**1.1)*beta**1.3\n *(1.0 + 8.0*t1))\n\n # C_inf is discharge coefficient with corner taps for infinite Re\n # Cs, slope term, provides increase in discharge coefficient for lower\n # Reynolds numbers.\n x1 = 63.095734448019314*(Re_D_inv)**0.3 # 63.095... = (1e6)**0.3\n x2 = 22.7 - 0.0047*Re_D\n t2 = max(x2, x1)\n # max term is not in the ISO standard\n C_inf_C_s = (0.5961 + 0.0261*beta2 - 0.216*beta8\n + 0.000521*(1E6*beta*Re_D_inv)**0.7\n + (0.0188 + 0.0063*A)*beta2*beta*sqrt(beta)*(\n t2))\n\n C = (C_inf_C_s + delta_C_upstream + delta_C_downstream)\n if D < 0.07112:\n # Limit is 2.8 inches, .1 inches smaller than the internal diameter of\n # a sched. 80 pipe.\n # Suggested to be required not because of any effect of small\n # diameters themselves, but because of edge radius differences.\n # max term is given in [4]_ Reader-Harris, Michael book\n # There is a check for t3 being negative and setting it to zero if so\n # in some sources but that only occurs when t3 is exactly the limit\n # (0.07112) so it is not needed\n t3 = (2.8 - D*inch_inv)\n delta_C_diameter = 0.011*(0.75 - beta)*t3\n C += delta_C_diameter\n\n return C\n\ndef C_Miller_1996(D: float, Do: float, rho: float, mu: float, m: float, subtype: str=\"orifice\",\n taps: str | None=ORIFICE_CORNER_TAPS, tap_position: str | None=TAPS_OPPOSITE) -> float:\n r\"\"\"Calculates the coefficient of discharge of any of the orifice types\n supported by the Miller (1996) [1]_ correlation set. These correlations\n cover a wide range of industrial applications and sizes. Most of them are\n functions of `beta` ratio and Reynolds number. Unlike the ISO standards,\n these correlations do not come with well defined ranges of validity, so\n caution should be applied using these correlations.\n\n The base equation is as follows, and each orifice type and range has\n different values or correlations for :math:`C_{\\infty}`, `b`, and `n`.\n\n .. math::\n C = C_{\\infty} + \\frac{b}{{Re}_D^n}\n\n Parameters\n ----------\n D : float\n Upstream internal pipe diameter, [m]\n Do : float\n Diameter of orifice at flow conditions, [m]\n rho : float\n Density of fluid at `P1`, [kg/m^3]\n mu : float\n Viscosity of fluid at `P1`, [Pa*s]\n m : float\n Mass flow rate of fluid through the orifice, [kg/s]\n subtype : str, optional\n One of 'orifice', 'eccentric orifice', 'segmental orifice',\n 'conical orifice', or 'quarter circle orifice', [-]\n taps : str, optional\n The orientation of the taps; one of 'corner', 'flange',\n 'D and D/2', 'pipe', or 'vena contracta'; not all orifice subtypes\n support all tap types [-]\n tap_position : str, optional\n The rotation of the taps, used **only for the eccentric orifice case**\n where the pressure profiles are not symmetric; '180 degree' for the\n normal case where the taps are opposite the orifice bore, and\n '90 degree' for the case where, normally for operational reasons, the\n taps are near the bore [-]\n\n Returns\n -------\n C : float\n Coefficient of discharge of the orifice, [-]\n\n Notes\n -----\n Many of the correlations transition at a pipe diameter of 100 mm to\n different equations, which will lead to discontinuous behavior.\n\n It should also be noted the author of these correlations developed a\n commercial flow meter rating software package, at [2]_.\n He passed away in 2014, but contributed massively to the field of flow\n measurement.\n\n The numerous equations for the different cases are as follows:\n\n For all **regular (concentric) orifices**, the `b` equation is as follows\n and n = 0.75:\n\n .. math::\n b = 91.706\\beta^{2.5}\n\n Regular (concentric) orifice, corner taps:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.0312\\beta^2.1 - 0.184\\beta^8\n\n Regular (concentric) orifice, flange taps, D > 58.4 mm:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.0312\\beta^{2.1} - 0.184\\beta^8\n + \\frac{2.286\\beta^4}{(D_{mm}(1.0 - \\beta^4))}\n - \\frac{0.856\\beta^3}{D_{mm}}\n\n Regular (concentric) orifice, flange taps, D < 58.4 mm:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.0312\\beta^{2.1} - 0.184\\beta^8\n + \\frac{0.039\\beta^4}{(1.0 - \\beta^4)} - \\frac{0.856\\beta^3}{D_{mm}}\n\n Regular (concentric) orifice, 'D and D/2' taps:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.0312\\beta^{2.1} - 0.184\\beta^8\n + \\frac{0.039\\beta^4}{(1.0 - \\beta^4)} - 0.01584\n\n Regular (concentric) orifice, 'pipe' taps:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.461\\beta^{2.1} + 0.48\\beta^8\n + \\frac{0.039\\beta^4}{(1.0 - \\beta^4)}\n\n For the case of a **conical orifice**, there is no tap dependence\n and one equation (`b` = 0, `n` = 0):\n\n .. math::\n C_{\\infty} = 0.734 \\text{ if } 250\\beta \\le Re \\le 500\\beta \\text{ else } 0.730\n\n For the case of a **quarter circle orifice**, corner and flange taps have\n the same dependence (`b` = 0, `n` = 0):\n\n .. math::\n C_{\\infty} = (0.7746 - 0.1334\\beta^{2.1} + 1.4098\\beta^8\n + \\frac{0.0675\\beta^4}{(1 - \\beta^4)} + 0.3865\\beta^3)\n\n For all **segmental orifice** types, `b` = 0 and `n` = 0\n\n Segmental orifice, 'flange' taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.6284 + 0.1462\\beta^{2.1} - 0.8464\\beta^8\n + \\frac{0.2603\\beta^4}{(1-\\beta^4)} - 0.2886\\beta^3\n\n Segmental orifice, 'flange' taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.6276 + 0.0828\\beta^{2.1} + 0.2739\\beta^8\n - \\frac{0.0934\\beta^4}{(1-\\beta^4)} - 0.1132\\beta^3\n\n Segmental orifice, 'vena contracta' taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.6261 + 0.1851\\beta^{2.1} - 0.2879\\beta^8\n + \\frac{0.1170\\beta^4}{(1-\\beta^4)} - 0.2845\\beta^3\n\n Segmental orifice, 'vena contracta' taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.6276 + 0.0828\\beta^{2.1} + 0.2739\\beta^8\n - \\frac{0.0934\\beta^4}{(1-\\beta^4)} - 0.1132\\beta^3\n\n For all **eccentric orifice** types, `n` = 0.75 and `b` is fit to a\n polynomial of `beta`.\n\n Eccentric orifice, 'flange' taps, 180 degree opposite taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.5917 + 0.3061\\beta^{2.1} + .3406\\beta^8 -\\frac{.1019\\beta^4}{(1-\\beta^4)} - 0.2715\\beta^3\n\n .. math::\n b = 7.3 - 15.7\\beta + 170.8\\beta^2 - 399.7\\beta^3 + 332.2\\beta^4\n\n Eccentric orifice, 'flange' taps, 180 degree opposite taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.6016 + 0.3312\\beta^{2.1} -1.5581\\beta^8 + \\frac{0.6510\\beta^4}{(1-\\beta^4)} - 0.7308\\beta^3\n\n .. math::\n b = -139.7 + 1328.8\\beta - 4228.2\\beta^2 + 5691.9\\beta^3 - 2710.4\\beta^4\n\n Eccentric orifice, 'flange' taps, 90 degree side taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.5866 + 0.3917\\beta^{2.1} + .7586\\beta^8 - \\frac{.2273\\beta^4}{(1-\\beta^4)} - .3343\\beta^3\n\n .. math::\n b = 69.1 - 469.4\\beta + 1245.6\\beta^2 -1287.5\\beta^3 + 486.2\\beta^4\n\n Eccentric orifice, 'flange' taps, 90 degree side taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.6037 + 0.1598\\beta^{2.1} -.2918\\beta^8 + \\frac{0.0244\\beta^4}{(1-\\beta^4)} - 0.0790\\beta^3\n\n .. math::\n b = -103.2 + 898.3\\beta - 2557.3\\beta^2 + 2977.0\\beta^3 - 1131.3\\beta^4\n\n Eccentric orifice, 'vena contracta' taps, 180 degree opposite taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.5925 + 0.3380\\beta^{2.1} + 0.4016\\beta^8 - \\frac{.1046\\beta^4}{(1-\\beta^4)} - 0.3212\\beta^3\n\n .. math::\n b = 23.3 -207.0\\beta + 821.5\\beta^2 -1388.6\\beta^3 + 900.3\\beta^4\n\n Eccentric orifice, 'vena contracta' taps, 180 degree opposite taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.5922 + 0.3932\\beta^{2.1} + .3412\\beta^8 - \\frac{.0569\\beta^4}{(1-\\beta^4)} - 0.4628\\beta^3\n\n .. math::\n b = 55.7 - 471.4\\beta + 1721.8\\beta^2 - 2722.6\\beta^3 + 1569.4\\beta^4\n\n Eccentric orifice, 'vena contracta' taps, 90 degree side taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.5875 + 0.3813\\beta^{2.1} + 0.6898\\beta^8 - \\frac{0.1963\\beta^4}{(1-\\beta^4)} - 0.3366\\beta^3\n\n .. math::\n b = -69.3 + 556.9\\beta - 1332.2\\beta^2 + 1303.7\\beta^3 - 394.8\\beta^4\n\n Eccentric orifice, 'vena contracta' taps, 90 degree side taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.5949 + 0.4078\\beta^{2.1} + 0.0547\\beta^8 + \\frac{0.0955\\beta^4}{(1-\\beta^4)} - 0.5608\\beta^3\n\n .. math::\n b = 52.8 - 434.2\\beta + 1571.2\\beta^2 - 2460.9\\beta^3 + 1420.2\\beta^4\n\n\n Examples\n --------\n >>> C_Miller_1996(D=0.07391, Do=0.0222, rho=1.165, mu=1.85E-5, m=0.12, taps='flange', subtype='orifice')\n 0.599065557156788\n\n References\n ----------\n .. [1] Miller, Richard W. Flow Measurement Engineering Handbook.\n McGraw-Hill Education, 1996.\n .. [2] \"RW Miller & Associates.\" Accessed April 13, 2020.\n http://rwmillerassociates.com/.\n \"\"\"\n A_pipe = 0.25*pi*D*D\n v = m/(A_pipe*rho)\n Re = rho*v*D/mu\n D_mm = D*1000.0\n\n beta = Do/D\n beta2 = beta*beta\n beta3 = beta2*beta\n beta4 = beta*beta3\n beta8 = beta4*beta4\n beta21 = beta**2.1\n\n if subtype in (MILLER_ORIFICE, CONCENTRIC_ORIFICE):\n b = 91.706*beta2*sqrt(beta)\n n = 0.75\n if taps == ORIFICE_CORNER_TAPS:\n C_inf = 0.5959 + 0.0312*beta21 - 0.184*beta8\n elif taps == ORIFICE_FLANGE_TAPS:\n if D_mm >= 58.4:\n C_inf = 0.5959 + 0.0312*beta21 - 0.184*beta8 + 2.286*beta4/(D_mm*(1.0 - beta4)) - 0.856*beta3/D_mm\n else:\n C_inf = 0.5959 + 0.0312*beta21 - 0.184*beta8 + 0.039*beta4/(1.0 - beta4) - 0.856*beta3/D_mm\n elif taps == ORIFICE_D_AND_D_2_TAPS:\n C_inf = 0.5959 + 0.0312*beta21 - 0.184*beta8 + 0.039*beta4/(1.0 - beta4) - 0.01584\n elif taps == ORIFICE_PIPE_TAPS:\n C_inf = 0.5959 + 0.461*beta21 + 0.48*beta8 + 0.039*beta4/(1.0 - beta4)\n else:\n raise ValueError(_Miller_1996_unsupported_tap_concentric)\n elif subtype in (MILLER_ECCENTRIC_ORIFICE, ECCENTRIC_ORIFICE):\n if tap_position not in (TAPS_OPPOSITE, TAPS_SIDE):\n raise ValueError(_Miller_1996_unsupported_tap_pos_eccentric)\n n = 0.75\n if taps == ORIFICE_FLANGE_TAPS:\n if tap_position == TAPS_OPPOSITE:\n if D < 0.1:\n b = 7.3 - 15.7*beta + 170.8*beta2 - 399.7*beta3 + 332.2*beta4\n C_inf = 0.5917 + 0.3061*beta21 + 0.3406*beta8 - 0.1019*beta4/(1.0-beta4) - 0.2715*beta3\n else:\n b = -139.7 + 1328.8*beta - 4228.2*beta2 + 5691.9*beta3 - 2710.4*beta4\n C_inf = 0.6016 + 0.3312*beta21 - 1.5581*beta8 + 0.6510*beta4/(1.0-beta4) - 0.7308*beta3\n elif tap_position == TAPS_SIDE:\n if D < 0.1:\n b = 69.1 - 469.4*beta + 1245.6*beta2 -1287.5*beta3 + 486.2*beta4\n C_inf = 0.5866 + 0.3917*beta21 + 0.7586*beta8 - 0.2273*beta4/(1.0-beta4) - 0.3343*beta3\n else:\n b = -103.2 + 898.3*beta - 2557.3*beta2 + 2977.0*beta3 - 1131.3*beta4\n C_inf = 0.6037 + 0.1598*beta21 - 0.2918*beta8 + 0.0244*beta4/(1.0-beta4) - 0.0790*beta3\n elif taps == ORIFICE_VENA_CONTRACTA_TAPS:\n if tap_position == TAPS_OPPOSITE:\n if D < 0.1:\n b = 23.3 -207.0*beta + 821.5*beta2 -1388.6*beta3 + 900.3*beta4\n C_inf = 0.5925 + 0.3380*beta21 + 0.4016*beta8 - 0.1046*beta4/(1.0-beta4) - 0.3212*beta3\n else:\n b = 55.7 - 471.4*beta + 1721.8*beta2 - 2722.6*beta3 + 1569.4*beta4\n C_inf = 0.5922 + 0.3932*beta21 + 0.3412*beta8 - 0.0569*beta4/(1.0-beta4) - 0.4628*beta3\n elif tap_position == TAPS_SIDE:\n if D < 0.1:\n b = -69.3 + 556.9*beta - 1332.2*beta2 + 1303.7*beta3 - 394.8*beta4\n C_inf = 0.5875 + 0.3813*beta21 + 0.6898*beta8 - 0.1963*beta4/(1.0-beta4) - 0.3366*beta3\n else:\n b = 52.8 - 434.2*beta + 1571.2*beta2 - 2460.9*beta3 + 1420.2*beta4\n C_inf = 0.5949 + 0.4078*beta21 + 0.0547*beta8 + 0.0955*beta4/(1.0-beta4) - 0.5608*beta3\n else:\n raise ValueError(_Miller_1996_unsupported_tap_eccentric)\n elif subtype in (MILLER_SEGMENTAL_ORIFICE, SEGMENTAL_ORIFICE):\n n = b = 0.0\n if taps == ORIFICE_FLANGE_TAPS:\n if D < 0.1:\n C_inf = 0.6284 + 0.1462*beta21 - 0.8464*beta8 + 0.2603*beta4/(1.0-beta4) - 0.2886*beta3\n else:\n C_inf = 0.6276 + 0.0828*beta21 + 0.2739*beta8 - 0.0934*beta4/(1.0-beta4) - 0.1132*beta3\n elif taps == ORIFICE_VENA_CONTRACTA_TAPS:\n if D < 0.1:\n C_inf = 0.6261 + 0.1851*beta21 - 0.2879*beta8 + 0.1170*beta4/(1.0-beta4) - 0.2845*beta3\n else:\n # Yes these are supposed to be the same as the flange, large set\n C_inf = 0.6276 + 0.0828*beta21 + 0.2739*beta8 - 0.0934*beta4/(1.0-beta4) - 0.1132*beta3\n else:\n raise ValueError(_Miller_1996_unsupported_tap_segmental)\n elif subtype in (MILLER_CONICAL_ORIFICE, CONICAL_ORIFICE):\n n = b = 0.0\n if 250.0*beta <= Re <= 500.0*beta:\n C_inf = 0.734\n else:\n C_inf = 0.730\n elif subtype in (MILLER_QUARTER_CIRCLE_ORIFICE, QUARTER_CIRCLE_ORIFICE):\n n = b = 0.0\n C_inf = (0.7746 - 0.1334*beta21 + 1.4098*beta8\n + 0.0675*beta4/(1.0 - beta4) + 0.3865*beta3)\n else:\n raise ValueError(_Miller_1996_unsupported_type)\n C = C_inf + b*Re**-n\n return C\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 19793}, "tests/test_flow_meter.py::894": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/flow_meter.py", "fluids/numerics/__init__.py"], "used_names": ["CONCENTRIC_ORIFICE", "HOLLINGSHEAD_CONE", "HOLLINGSHEAD_ORIFICE", "HOLLINGSHEAD_VENTURI_SHARP", "HOLLINGSHEAD_VENTURI_SMOOTH", "HOLLINGSHEAD_WEDGE", "ISO_15377_CONICAL_ORIFICE", "ISO_15377_ECCENTRIC_ORIFICE", "ISO_15377_QUARTER_CIRCLE_ORIFICE", "MILLER_CONICAL_ORIFICE", "MILLER_ORIFICE", "assert_close", "differential_pressure_meter_C_epsilon", "pytest"], "enclosing_function": "test_differential_pressure_meter_C_epsilon", "extracted_code": "# Source: fluids/flow_meter.py\nCONCENTRIC_ORIFICE = \"orifice\"\n\nISO_15377_ECCENTRIC_ORIFICE = \"ISO 15377 eccentric orifice\"\n\nISO_15377_QUARTER_CIRCLE_ORIFICE = \"ISO 15377 quarter-circle orifice\"\n\nISO_15377_CONICAL_ORIFICE = \"ISO 15377 conical orifice\"\n\nMILLER_ORIFICE = \"Miller orifice\"\n\nMILLER_CONICAL_ORIFICE = \"Miller conical orifice\"\n\nHOLLINGSHEAD_ORIFICE = \"Hollingshead orifice\"\n\nHOLLINGSHEAD_VENTURI_SMOOTH = \"Hollingshead venturi smooth\"\n\nHOLLINGSHEAD_VENTURI_SHARP = \"Hollingshead venturi sharp\"\n\nHOLLINGSHEAD_CONE = \"Hollingshead v cone\"\n\nHOLLINGSHEAD_WEDGE = \"Hollingshead wedge\"\n\ndef differential_pressure_meter_C_epsilon(D: float, D2: float, m: float, P1: float, P2: float, rho: float, mu: float, k: float,\n meter_type: str, taps: str | None=None,\n tap_position: str | None=None, C_specified: float | None=None,\n epsilon_specified: int | None=None) -> tuple[float, float] | tuple[float, int]:\n r\"\"\"Calculates the discharge coefficient and expansibility of a flow\n meter given the mass flow rate, the upstream pressure, the second\n pressure value, and the orifice diameter for a differential\n pressure flow meter based on the geometry of the meter, measured pressures\n of the meter, and the density, viscosity, and isentropic exponent of the\n fluid.\n\n Parameters\n ----------\n D : float\n Upstream internal pipe diameter, [m]\n D2 : float\n Diameter of orifice, or venturi meter orifice, or flow tube orifice,\n or cone meter end diameter, or wedge meter fluid flow height, [m]\n m : float\n Mass flow rate of fluid through the flow meter, [kg/s]\n P1 : float\n Static pressure of fluid upstream of differential pressure meter at the\n cross-section of the pressure tap, [Pa]\n P2 : float\n Static pressure of fluid downstream of differential pressure meter or\n at the prescribed location (varies by type of meter) [Pa]\n rho : float\n Density of fluid at `P1`, [kg/m^3]\n mu : float\n Viscosity of fluid at `P1`, [Pa*s]\n k : float\n Isentropic exponent of fluid, [-]\n meter_type : str\n One of {'conical orifice', 'orifice', 'machined convergent venturi tube',\n 'ISO 5167 orifice', 'Miller quarter circle orifice', 'Hollingshead venturi sharp',\n 'segmental orifice', 'Miller conical orifice', 'Miller segmental orifice',\n 'quarter circle orifice', 'Hollingshead v cone', 'wedge meter', 'eccentric orifice',\n 'venturi nozzle', 'rough welded convergent venturi tube', 'ISA 1932 nozzle',\n 'ISO 15377 quarter-circle orifice', 'Hollingshead venturi smooth',\n 'Hollingshead orifice', 'cone meter', 'Hollingshead wedge', 'Miller orifice',\n 'long radius nozzle', 'ISO 15377 conical orifice', 'unspecified meter',\n 'as cast convergent venturi tube', 'Miller eccentric orifice',\n 'ISO 15377 eccentric orifice'}, [-]\n taps : str, optional\n The orientation of the taps; one of 'corner', 'flange', 'D', or 'D/2';\n applies for orifice meters only, [-]\n tap_position : str, optional\n The rotation of the taps, used **only for the eccentric orifice case**\n where the pressure profiles are not symmetric; '180 degree' for the\n normal case where the taps are opposite the orifice bore, and\n '90 degree' for the case where, normally for operational reasons, the\n taps are near the bore [-]\n C_specified : float, optional\n If specified, the correlation for the meter type is not used - this\n value is returned for `C`\n epsilon_specified : float, optional\n If specified, the correlation for the fluid expansibility is not used -\n this value is returned for :math:`\\epsilon`, [-]\n\n Returns\n -------\n C : float\n Coefficient of discharge of the specified flow meter type at the\n specified conditions, [-]\n expansibility : float\n Expansibility factor (1 for incompressible fluids, less than 1 for\n real fluids), [-]\n\n Notes\n -----\n This function should be called by an outer loop when solving for a\n variable.\n\n The latest ISO formulations for `expansibility` are used with the Miller\n correlations.\n\n Examples\n --------\n >>> differential_pressure_meter_C_epsilon(D=0.07366, D2=0.05, P1=200000.0,\n ... P2=183000.0, rho=999.1, mu=0.0011, k=1.33, m=7.702338035732168,\n ... meter_type='ISO 5167 orifice', taps='D')\n (0.6151252900244296, 0.9711026966676307)\n \"\"\"\n # Translate default meter type to implementation specific correlation\n if meter_type == CONCENTRIC_ORIFICE:\n meter_type = ISO_5167_ORIFICE\n elif meter_type == ECCENTRIC_ORIFICE:\n meter_type = ISO_15377_ECCENTRIC_ORIFICE\n elif meter_type == CONICAL_ORIFICE:\n meter_type = ISO_15377_CONICAL_ORIFICE\n elif meter_type == QUARTER_CIRCLE_ORIFICE:\n meter_type = ISO_15377_QUARTER_CIRCLE_ORIFICE\n elif meter_type == SEGMENTAL_ORIFICE:\n meter_type = MILLER_SEGMENTAL_ORIFICE\n\n if meter_type == ISO_5167_ORIFICE:\n taps_val = taps if taps is not None else \"corner\"\n C = C_Reader_Harris_Gallagher(D, D2, rho, mu, m, taps_val)\n epsilon = orifice_expansibility(D, D2, P1, P2, k)\n elif meter_type == ISO_15377_ECCENTRIC_ORIFICE:\n C = C_eccentric_orifice_ISO_15377_1998(D, D2)\n epsilon = orifice_expansibility(D, D2, P1, P2, k)\n elif meter_type == ISO_15377_QUARTER_CIRCLE_ORIFICE:\n C = C_quarter_circle_orifice_ISO_15377_1998(D, D2)\n epsilon = orifice_expansibility(D, D2, P1, P2, k)\n elif meter_type == ISO_15377_CONICAL_ORIFICE:\n C = ISO_15377_CONICAL_ORIFICE_C\n # Average of concentric square edge orifice and ISA 1932 nozzles\n epsilon = 0.5*(orifice_expansibility(D, D2, P1, P2, k)\n + nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k))\n\n elif meter_type in (MILLER_ORIFICE, MILLER_ECCENTRIC_ORIFICE,\n MILLER_SEGMENTAL_ORIFICE, MILLER_QUARTER_CIRCLE_ORIFICE):\n C = C_Miller_1996(D, D2, rho, mu, m, subtype=meter_type, taps=taps,\n tap_position=tap_position)\n epsilon = orifice_expansibility(D, D2, P1, P2, k)\n elif meter_type == MILLER_CONICAL_ORIFICE:\n C = C_Miller_1996(D, D2, rho, mu, m, subtype=meter_type, taps=taps,\n tap_position=tap_position)\n epsilon = 0.5*(orifice_expansibility(D, D2, P1, P2, k)\n + nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k))\n elif meter_type == LONG_RADIUS_NOZZLE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = C_long_radius_nozzle(D=D, Do=D2, rho=rho, mu=mu, m=m)\n elif meter_type == ISA_1932_NOZZLE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = C_ISA_1932_nozzle(D=D, Do=D2, rho=rho, mu=mu, m=m)\n elif meter_type == VENTURI_NOZZLE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = C_venturi_nozzle(D=D, Do=D2)\n\n elif meter_type == AS_CAST_VENTURI_TUBE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = AS_CAST_VENTURI_TUBE_C\n elif meter_type == MACHINED_CONVERGENT_VENTURI_TUBE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = MACHINED_CONVERGENT_VENTURI_TUBE_C\n elif meter_type == ROUGH_WELDED_CONVERGENT_VENTURI_TUBE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = ROUGH_WELDED_CONVERGENT_VENTURI_TUBE_C\n\n elif meter_type == CONE_METER:\n epsilon = cone_meter_expansibility_Stewart(D=D, Dc=D2, P1=P1, P2=P2, k=k)\n C = CONE_METER_C\n elif meter_type == WEDGE_METER:\n beta = diameter_ratio_wedge_meter(D=D, H=D2)\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k, beta=beta)\n C = C_wedge_meter_ISO_5167_6_2017(D=D, H=D2)\n elif meter_type == HOLLINGSHEAD_ORIFICE:\n v = m/((0.25*pi*D*D)*rho)\n Re_D = rho*v*D/mu\n C = float(bisplev(D2/D, log(Re_D), orifice_std_Hollingshead_tck))\n epsilon = orifice_expansibility(D, D2, P1, P2, k)\n elif meter_type == HOLLINGSHEAD_VENTURI_SMOOTH:\n v = m/((0.25*pi*D*D)*rho)\n Re_D = rho*v*D/mu\n C = interp(log(Re_D), venturi_logRes_Hollingshead, venturi_smooth_Cs_Hollingshead, extrapolate=True)\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n elif meter_type == HOLLINGSHEAD_VENTURI_SHARP:\n v = m/((0.25*pi*D*D)*rho)\n Re_D = rho*v*D/mu\n C = interp(log(Re_D), venturi_logRes_Hollingshead, venturi_sharp_Cs_Hollingshead, extrapolate=True)\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n elif meter_type == HOLLINGSHEAD_CONE:\n v = m/((0.25*pi*D*D)*rho)\n Re_D = rho*v*D/mu\n beta = diameter_ratio_cone_meter(D, D2)\n C = float(bisplev(beta, log(Re_D), cone_Hollingshead_tck))\n epsilon = cone_meter_expansibility_Stewart(D=D, Dc=D2, P1=P1, P2=P2, k=k)\n elif meter_type == HOLLINGSHEAD_WEDGE:\n v = m/((0.25*pi*D*D)*rho)\n Re_D = rho*v*D/mu\n beta = diameter_ratio_wedge_meter(D=D, H=D2)\n C = float(bisplev(beta, log(Re_D), wedge_Hollingshead_tck))\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k, beta=beta)\n elif meter_type == UNSPECIFIED_METER:\n epsilon = orifice_expansibility(D, D2, P1, P2, k) # Default to orifice type expansibility\n if C_specified is None:\n raise ValueError(\"For unspecified meter type, C_specified is required\")\n else:\n raise ValueError(_unsupported_meter_msg)\n if C_specified is not None:\n C = C_specified\n if epsilon_specified is not None:\n epsilon = epsilon_specified\n return C, epsilon\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 10525}, "tests/test_numerics_polynomial_evaluation.py::302": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/polynomial_evaluation.py", "fluids/numerics/polynomial_utils.py"], "used_names": ["assert_close", "exp_horner_stable_ln_tau", "exp_horner_stable_ln_tau_and_der", "exp_horner_stable_ln_tau_and_der2", "log", "polynomial_offset_scale"], "enclosing_function": "test_exp_stablepoly_fit_ln_tau", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/numerics/polynomial_evaluation.py\ndef exp_horner_stable_ln_tau(T, Tc, coeffs, offset, scale):\n if T >= Tc:\n return 0.0\n lntau = log(1.0 - T/Tc)\n return trunc_exp(horner_stable(lntau, coeffs, offset, scale))\n\ndef exp_horner_stable_ln_tau_and_der(T, Tc, coeffs, offset, scale):\n if T >= Tc:\n return 0.0, 0.0\n tau = 1.0 - T/Tc\n lntau = log(tau)\n poly_val, poly_der_val = horner_stable_and_der(lntau, coeffs, offset, scale)\n val = trunc_exp(poly_val)\n return val, -val*poly_der_val/(Tc*tau)\n\ndef exp_horner_stable_ln_tau_and_der2(T, Tc, coeffs, offset, scale):\n if T >= Tc:\n return 0.0, 0.0, 0.0\n tau = 1.0 - T/Tc\n lntau = log(tau)\n poly_val, poly_val_der, poly_val_der2 = horner_stable_and_der2(lntau, coeffs, offset, scale)\n val = trunc_exp(poly_val)\n der = -val*poly_val_der/(Tc*tau)\n der2 = (poly_val_der*poly_val_der - poly_val_der + poly_val_der2)*val/(Tc*Tc*(tau*tau))\n\n return val, der, der2\n\n\n# Source: fluids/numerics/polynomial_utils.py\ndef polynomial_offset_scale(xmin, xmax):\n range_inv = 1.0/(xmax - xmin)\n offset = (-xmax - xmin)*range_inv\n scale = 2.0*range_inv\n return offset, scale", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 1806}, "tests/test_pump.py::163": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/numerics/__init__.py", "fluids/pump.py"], "used_names": ["CountryPower"], "enclosing_function": "test_CountryPower", "extracted_code": "# Source: fluids/pump.py\nclass CountryPower:\n \"\"\"Class to hold information on the residential or electrical data of a\n country. Data from Wikipedia, obtained in 2017.\n\n Parameters\n ----------\n plugs : tuple(str)\n Tuple of residential plug letter codes in use in the country, [-]\n voltage : float or tuple(float)\n Voltage or voltages in common use of the country (residential data\n has one voltage; industrial data has multiple often), [V]\n freq : float\n The electrical frequency in use in the country, [Hz]\n country : str\n The name of the country, [-]\n \"\"\"\n\n __slots__ = (\"country\", \"freq\", \"plugs\", \"voltage\")\n\n def __repr__(self):\n return (\n f'CountryPower(country=\"{self.country}\", voltage={self.voltage}, '\n f'freq={self.freq}, plugs={self.plugs})'\n )\n def __init__(self, country: str, voltage: Any, freq: float, plugs: Any | None=None) -> None:\n self.plugs = plugs\n self.voltage = voltage\n self.freq = freq\n self.country = country", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 1070}, "tests/test_vectorized.py::36": {"resolved_imports": ["fluids/vectorized.py", "fluids/__init__.py"], "used_names": ["assert_allclose", "vectorized"], "enclosing_function": "test_a_complicated_function", "extracted_code": "# Source: fluids/vectorized.py\nwill be imported from here.\n\n>>> from fluids.vectorized import *\n\nInputs do not need to be numpy arrays; they can be any iterable:\n\n>>> fluids.vectorized.friction_factor(Re=[100, 1000, 10000], eD=0)\narray([ 0.64 , 0.064 , 0.03088295])\n\nNote that because this needs to import fluids itself, fluids.vectorized\nneeds to be imported separately; the following will cause an error:\n\n\nInputs do not need to be numpy arrays; they can be any iterable:\n\n>>> fluids.vectorized.friction_factor(Re=[100, 1000, 10000], eD=0)\narray([ 0.64 , 0.064 , 0.03088295])\n\nNote that because this needs to import fluids itself, fluids.vectorized\nneeds to be imported separately; the following will cause an error:\n\n>>> import fluids\n>>> fluids.vectorized # Won't work, has not been imported yet\n\nThe correct syntax is as follows:\n\narray([ 0.64 , 0.064 , 0.03088295])\n\nNote that because this needs to import fluids itself, fluids.vectorized\nneeds to be imported separately; the following will cause an error:\n\n>>> import fluids\n>>> fluids.vectorized # Won't work, has not been imported yet\n\nThe correct syntax is as follows:\n\n>>> import fluids.vectorized # Necessary\n>>> from fluids.vectorized import * # May be used without first importing fluids\n\n\n>>> import fluids\n>>> fluids.vectorized # Won't work, has not been imported yet\n\nThe correct syntax is as follows:\n\n>>> import fluids.vectorized # Necessary\n>>> from fluids.vectorized import * # May be used without first importing fluids\n\n\nThis module is lightweight! It takes approximately 3 ms to load, and increases\nram usage by only 250 KB.\n\nThe correct syntax is as follows:\n\n>>> import fluids.vectorized # Necessary\n>>> from fluids.vectorized import * # May be used without first importing fluids\n\n\nThis module is lightweight! It takes approximately 3 ms to load, and increases\nram usage by only 250 KB.\n\"\"\"\n\n__all__ = []\n", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1915}, "tests/test_atmosphere.py::61": {"resolved_imports": ["fluids/atmosphere.py", "fluids/numerics/__init__.py"], "used_names": ["ATMOSPHERE_1976", "assert_close", "assert_close1d"], "enclosing_function": "test_ATMOSPHERE_1976", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 846}, "tests/test_design_climate.py::82": {"resolved_imports": ["fluids/design_climate.py", "fluids/numerics/__init__.py"], "used_names": ["IntegratedSurfaceDatabaseStation"], "enclosing_function": "test_IntegratedSurfaceDatabaseStation", "extracted_code": "# Source: fluids/design_climate.py\nclass IntegratedSurfaceDatabaseStation:\n \"\"\"Class to hold data on a weather station in the Integrated Surface\n Database.\n\n License information for the database can be found at the following link:\n https://data.noaa.gov/dataset/global-surface-summary-of-the-day-gsod\n\n Note: Of the 28000 + stations in the database, approximately 3000 have WBAN\n identifiers; 26000 have unique names; 24000 have USAF identifiers; and\n there are only 25800 unique lat/lon pairs.\n\n To uniquely represent a weather station, a combination of identifiers\n must be used. (Name, USAF, WBAN) makes a good choice.\n\n Parameters\n ----------\n USAF : str or None if unassigned\n Air Force station ID. May contain a letter in the first position.\n WBAN : str or None if unassigned\n NCDC WBAN number\n NAME : str\n Name of the station; ex. 'CENTRAL COLORADO REGIONAL AP'\n CTRY : str or None if unspecified\n FIPS country ID\n ST : str or None if not in the US\n State for US stations\n ICAO : str or None if not an airport\n ICAO airport code\n LAT : float\n Latitude with a precision of one thousandths of a decimal degree,\n [degrees]\n LON : float\n Longitude with a precision of one thousandths of a decimal degree,\n [degrees]\n ELEV : float\n Elevation of weather station, [m]\n BEGIN : float\n Beginning Period Of Record (YYYYMMDD). There may be reporting gaps\n within the P.O.R.\n END : Ending Period Of Record (YYYYMMDD). There may be reporting gaps\n within the P.O.R.\n \"\"\"\n\n __slots__ = [\n \"BEGIN\",\n \"CTRY\",\n \"ELEV\",\n \"END\",\n \"ICAO\",\n \"LAT\",\n \"LON\",\n \"NAME\",\n \"ST\",\n \"USAF\",\n \"WBAN\",\n ]\n\n def __repr__(self):\n s = (\"\" )\n return s%(self.NAME, self.CTRY, self.USAF, self.WBAN, self.LAT, self.LON, str(self.BEGIN)[0:4], str(self.END)[0:4])\n\n def __init__(self, USAF, WBAN, NAME, CTRY, ST, ICAO, LAT, LON, ELEV, BEGIN,\n END):\n try:\n self.USAF = int(USAF)\n except:\n self.USAF = USAF # Nones\n self.WBAN = WBAN\n self.NAME = NAME\n self.CTRY = CTRY\n self.ST = ST\n self.ICAO = ICAO\n self.LAT = LAT\n self.LON = LON\n self.ELEV = ELEV\n self.BEGIN = int(BEGIN)\n self.END = int(END)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 2627}, "tests/test_jet_pump.py::56": {"resolved_imports": ["fluids/__init__.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "liquid_jet_pump_ancillary"], "enclosing_function": "test_liquid_jet_pump_ancillary", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 607}, "tests/test_numerics_polynomial_utils.py::172": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["assert_close1d", "stable_poly_to_unstable"], "enclosing_function": "test_stable_poly_to_unstable", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 275}, "tests/test_flow_meter.py::227": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/flow_meter.py", "fluids/numerics/__init__.py"], "used_names": ["C_Miller_1996", "C_Reader_Harris_Gallagher", "MILLER_CONICAL_ORIFICE", "MILLER_ECCENTRIC_ORIFICE", "MILLER_ORIFICE", "MILLER_QUARTER_CIRCLE_ORIFICE", "MILLER_SEGMENTAL_ORIFICE", "ORIFICE_CORNER_TAPS", "ORIFICE_D_AND_D_2_TAPS", "ORIFICE_FLANGE_TAPS", "ORIFICE_PIPE_TAPS", "ORIFICE_VENA_CONTRACTA_TAPS", "TAPS_OPPOSITE", "TAPS_SIDE", "assert_close", "pytest"], "enclosing_function": "test_C_Miller_1996", "extracted_code": "# Source: fluids/flow_meter.py\nORIFICE_CORNER_TAPS = \"corner\"\n\nORIFICE_FLANGE_TAPS = \"flange\"\n\nORIFICE_D_AND_D_2_TAPS = \"D and D/2\"\n\nORIFICE_PIPE_TAPS = \"pipe\"\n\nORIFICE_VENA_CONTRACTA_TAPS = \"vena contracta\"\n\nTAPS_OPPOSITE = \"180 degree\"\n\nTAPS_SIDE = \"90 degree\"\n\nMILLER_ORIFICE = \"Miller orifice\"\n\nMILLER_ECCENTRIC_ORIFICE = \"Miller eccentric orifice\"\n\nMILLER_SEGMENTAL_ORIFICE = \"Miller segmental orifice\"\n\nMILLER_CONICAL_ORIFICE = \"Miller conical orifice\"\n\nMILLER_QUARTER_CIRCLE_ORIFICE = \"Miller quarter circle orifice\"\n\ndef C_Reader_Harris_Gallagher(D: float, Do: float, rho: float, mu: float, m: float, taps: str=\"corner\") -> float:\n r\"\"\"Calculates the coefficient of discharge of the orifice based on the\n geometry of the plate, measured pressures of the orifice, mass flow rate\n through the orifice, and the density and viscosity of the fluid.\n\n .. math::\n C = 0.5961 + 0.0261\\beta^2 - 0.216\\beta^8 + 0.000521\\left(\\frac{\n 10^6\\beta}{Re_D}\\right)^{0.7}\\\\\n + (0.0188 + 0.0063A)\\beta^{3.5} \\left(\\frac{10^6}{Re_D}\\right)^{0.3} \\\\\n +(0.043 + 0.080\\exp(-10L_1) -0.123\\exp(-7L_1))(1-0.11A)\\frac{\\beta^4}\n {1-\\beta^4} \\\\\n - 0.031(M_2' - 0.8M_2'^{1.1})\\beta^{1.3}\n\n .. math::\n M_2' = \\frac{2L_2'}{1-\\beta}\n\n .. math::\n A = \\left(\\frac{19000\\beta}{Re_{D}}\\right)^{0.8}\n\n .. math::\n Re_D = \\frac{\\rho v D}{\\mu}\n\n\n If D < 71.12 mm (2.8 in.) (Note this is a continuous addition; there is no\n discontinuity):\n\n .. math::\n C += 0.11(0.75-\\beta)\\left(2.8-\\frac{D}{0.0254}\\right)\n\n If the orifice has corner taps:\n\n .. math::\n L_1 = L_2' = 0\n\n If the orifice has D and D/2 taps:\n\n .. math::\n L_1 = 1\n\n .. math::\n L_2' = 0.47\n\n If the orifice has Flange taps:\n\n .. math::\n L_1 = L_2' = \\frac{0.0254}{D}\n\n Parameters\n ----------\n D : float\n Upstream internal pipe diameter, [m]\n Do : float\n Diameter of orifice at flow conditions, [m]\n rho : float\n Density of fluid at `P1`, [kg/m^3]\n mu : float\n Viscosity of fluid at `P1`, [Pa*s]\n m : float\n Mass flow rate of fluid through the orifice, [kg/s]\n taps : str\n The orientation of the taps; one of 'corner', 'flange', 'D', or 'D/2',\n [-]\n\n Returns\n -------\n C : float\n Coefficient of discharge of the orifice, [-]\n\n Notes\n -----\n The following limits apply to the orifice plate standard [1]_:\n\n The measured pressure difference for the orifice plate should be under\n 250 kPa.\n\n There are roughness limits as well; the roughness should be under 6\n micrometers, although there are many more conditions to that given in [1]_.\n\n For orifice plates with D and D/2 or corner pressure taps:\n\n * Orifice bore diameter must be larger than 12.5 mm (0.5 inches)\n * Pipe diameter between 50 mm and 1 m (2 to 40 inches)\n * Beta between 0.1 and 0.75 inclusive\n * Reynolds number larger than 5000 (for :math:`0.10 \\le \\beta \\le 0.56`)\n or for :math:`\\beta \\ge 0.56, Re_D \\ge 16000\\beta^2`\n\n For orifice plates with flange pressure taps:\n\n * Orifice bore diameter must be larger than 12.5 mm (0.5 inches)\n * Pipe diameter between 50 mm and 1 m (2 to 40 inches)\n * Beta between 0.1 and 0.75 inclusive\n * Reynolds number larger than 5000 and also larger than\n :math:`170000\\beta^2 D`.\n\n This is also presented in Crane's TP410 (2009) publication, whereas the\n 1999 and 1982 editions showed only a graph for discharge coefficients.\n\n Examples\n --------\n >>> C_Reader_Harris_Gallagher(D=0.07391, Do=0.0222, rho=1.165, mu=1.85E-5,\n ... m=0.12, taps='flange')\n 0.5990326277163659\n\n References\n ----------\n .. [1] American Society of Mechanical Engineers. Mfc-3M-2004 Measurement\n Of Fluid Flow In Pipes Using Orifice, Nozzle, And Venturi. ASME, 2001.\n .. [2] ISO 5167-2:2003 - Measurement of Fluid Flow by Means of Pressure\n Differential Devices Inserted in Circular Cross-Section Conduits Running\n Full -- Part 2: Orifice Plates.\n .. [3] Reader-Harris, M. J., \"The Equation for the Expansibility Factor for\n Orifice Plates,\" Proceedings of FLOMEKO 1998, Lund, Sweden, 1998:\n 209-214.\n .. [4] Reader-Harris, Michael. Orifice Plates and Venturi Tubes. Springer,\n 2015.\n \"\"\"\n A_pipe = 0.25*pi*D*D\n v = m/(A_pipe*rho)\n Re_D = rho*v*D/mu\n Re_D_inv = 1.0/Re_D\n\n beta = Do/D\n if taps == \"corner\":\n L1, L2_prime = 0.0, 0.0\n elif taps == \"flange\":\n L1 = L2_prime = 0.0254/D\n elif taps in (\"D\", \"D/2\", ORIFICE_D_AND_D_2_TAPS):\n L1 = 1.0\n L2_prime = 0.47\n else:\n raise ValueError(\"Unsupported tap location\")\n\n beta2 = beta*beta\n beta4 = beta2*beta2\n beta8 = beta4*beta4\n\n A = 2648.5177066967326*(beta*Re_D_inv)**0.8 # 19000.0^0.8 = 2648.51....\n M2_prime = 2.0*L2_prime/(1.0 - beta)\n\n # These two exps\n expnL1 = exp(-L1)\n expnL2 = expnL1*expnL1\n expnL3 = expnL1*expnL2\n delta_C_upstream = ((0.043 + expnL3*expnL2*expnL2*(0.080*expnL3 - 0.123))\n *(1.0 - 0.11*A)*beta4/(1.0 - beta4))\n\n # The max part is not in the ISO standard\n t1 = log10(3700.*Re_D_inv)\n if t1 < 0.0:\n t1 = 0.0\n delta_C_downstream = (-0.031*(M2_prime - 0.8*M2_prime**1.1)*beta**1.3\n *(1.0 + 8.0*t1))\n\n # C_inf is discharge coefficient with corner taps for infinite Re\n # Cs, slope term, provides increase in discharge coefficient for lower\n # Reynolds numbers.\n x1 = 63.095734448019314*(Re_D_inv)**0.3 # 63.095... = (1e6)**0.3\n x2 = 22.7 - 0.0047*Re_D\n t2 = max(x2, x1)\n # max term is not in the ISO standard\n C_inf_C_s = (0.5961 + 0.0261*beta2 - 0.216*beta8\n + 0.000521*(1E6*beta*Re_D_inv)**0.7\n + (0.0188 + 0.0063*A)*beta2*beta*sqrt(beta)*(\n t2))\n\n C = (C_inf_C_s + delta_C_upstream + delta_C_downstream)\n if D < 0.07112:\n # Limit is 2.8 inches, .1 inches smaller than the internal diameter of\n # a sched. 80 pipe.\n # Suggested to be required not because of any effect of small\n # diameters themselves, but because of edge radius differences.\n # max term is given in [4]_ Reader-Harris, Michael book\n # There is a check for t3 being negative and setting it to zero if so\n # in some sources but that only occurs when t3 is exactly the limit\n # (0.07112) so it is not needed\n t3 = (2.8 - D*inch_inv)\n delta_C_diameter = 0.011*(0.75 - beta)*t3\n C += delta_C_diameter\n\n return C\n\ndef C_Miller_1996(D: float, Do: float, rho: float, mu: float, m: float, subtype: str=\"orifice\",\n taps: str | None=ORIFICE_CORNER_TAPS, tap_position: str | None=TAPS_OPPOSITE) -> float:\n r\"\"\"Calculates the coefficient of discharge of any of the orifice types\n supported by the Miller (1996) [1]_ correlation set. These correlations\n cover a wide range of industrial applications and sizes. Most of them are\n functions of `beta` ratio and Reynolds number. Unlike the ISO standards,\n these correlations do not come with well defined ranges of validity, so\n caution should be applied using these correlations.\n\n The base equation is as follows, and each orifice type and range has\n different values or correlations for :math:`C_{\\infty}`, `b`, and `n`.\n\n .. math::\n C = C_{\\infty} + \\frac{b}{{Re}_D^n}\n\n Parameters\n ----------\n D : float\n Upstream internal pipe diameter, [m]\n Do : float\n Diameter of orifice at flow conditions, [m]\n rho : float\n Density of fluid at `P1`, [kg/m^3]\n mu : float\n Viscosity of fluid at `P1`, [Pa*s]\n m : float\n Mass flow rate of fluid through the orifice, [kg/s]\n subtype : str, optional\n One of 'orifice', 'eccentric orifice', 'segmental orifice',\n 'conical orifice', or 'quarter circle orifice', [-]\n taps : str, optional\n The orientation of the taps; one of 'corner', 'flange',\n 'D and D/2', 'pipe', or 'vena contracta'; not all orifice subtypes\n support all tap types [-]\n tap_position : str, optional\n The rotation of the taps, used **only for the eccentric orifice case**\n where the pressure profiles are not symmetric; '180 degree' for the\n normal case where the taps are opposite the orifice bore, and\n '90 degree' for the case where, normally for operational reasons, the\n taps are near the bore [-]\n\n Returns\n -------\n C : float\n Coefficient of discharge of the orifice, [-]\n\n Notes\n -----\n Many of the correlations transition at a pipe diameter of 100 mm to\n different equations, which will lead to discontinuous behavior.\n\n It should also be noted the author of these correlations developed a\n commercial flow meter rating software package, at [2]_.\n He passed away in 2014, but contributed massively to the field of flow\n measurement.\n\n The numerous equations for the different cases are as follows:\n\n For all **regular (concentric) orifices**, the `b` equation is as follows\n and n = 0.75:\n\n .. math::\n b = 91.706\\beta^{2.5}\n\n Regular (concentric) orifice, corner taps:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.0312\\beta^2.1 - 0.184\\beta^8\n\n Regular (concentric) orifice, flange taps, D > 58.4 mm:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.0312\\beta^{2.1} - 0.184\\beta^8\n + \\frac{2.286\\beta^4}{(D_{mm}(1.0 - \\beta^4))}\n - \\frac{0.856\\beta^3}{D_{mm}}\n\n Regular (concentric) orifice, flange taps, D < 58.4 mm:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.0312\\beta^{2.1} - 0.184\\beta^8\n + \\frac{0.039\\beta^4}{(1.0 - \\beta^4)} - \\frac{0.856\\beta^3}{D_{mm}}\n\n Regular (concentric) orifice, 'D and D/2' taps:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.0312\\beta^{2.1} - 0.184\\beta^8\n + \\frac{0.039\\beta^4}{(1.0 - \\beta^4)} - 0.01584\n\n Regular (concentric) orifice, 'pipe' taps:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.461\\beta^{2.1} + 0.48\\beta^8\n + \\frac{0.039\\beta^4}{(1.0 - \\beta^4)}\n\n For the case of a **conical orifice**, there is no tap dependence\n and one equation (`b` = 0, `n` = 0):\n\n .. math::\n C_{\\infty} = 0.734 \\text{ if } 250\\beta \\le Re \\le 500\\beta \\text{ else } 0.730\n\n For the case of a **quarter circle orifice**, corner and flange taps have\n the same dependence (`b` = 0, `n` = 0):\n\n .. math::\n C_{\\infty} = (0.7746 - 0.1334\\beta^{2.1} + 1.4098\\beta^8\n + \\frac{0.0675\\beta^4}{(1 - \\beta^4)} + 0.3865\\beta^3)\n\n For all **segmental orifice** types, `b` = 0 and `n` = 0\n\n Segmental orifice, 'flange' taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.6284 + 0.1462\\beta^{2.1} - 0.8464\\beta^8\n + \\frac{0.2603\\beta^4}{(1-\\beta^4)} - 0.2886\\beta^3\n\n Segmental orifice, 'flange' taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.6276 + 0.0828\\beta^{2.1} + 0.2739\\beta^8\n - \\frac{0.0934\\beta^4}{(1-\\beta^4)} - 0.1132\\beta^3\n\n Segmental orifice, 'vena contracta' taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.6261 + 0.1851\\beta^{2.1} - 0.2879\\beta^8\n + \\frac{0.1170\\beta^4}{(1-\\beta^4)} - 0.2845\\beta^3\n\n Segmental orifice, 'vena contracta' taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.6276 + 0.0828\\beta^{2.1} + 0.2739\\beta^8\n - \\frac{0.0934\\beta^4}{(1-\\beta^4)} - 0.1132\\beta^3\n\n For all **eccentric orifice** types, `n` = 0.75 and `b` is fit to a\n polynomial of `beta`.\n\n Eccentric orifice, 'flange' taps, 180 degree opposite taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.5917 + 0.3061\\beta^{2.1} + .3406\\beta^8 -\\frac{.1019\\beta^4}{(1-\\beta^4)} - 0.2715\\beta^3\n\n .. math::\n b = 7.3 - 15.7\\beta + 170.8\\beta^2 - 399.7\\beta^3 + 332.2\\beta^4\n\n Eccentric orifice, 'flange' taps, 180 degree opposite taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.6016 + 0.3312\\beta^{2.1} -1.5581\\beta^8 + \\frac{0.6510\\beta^4}{(1-\\beta^4)} - 0.7308\\beta^3\n\n .. math::\n b = -139.7 + 1328.8\\beta - 4228.2\\beta^2 + 5691.9\\beta^3 - 2710.4\\beta^4\n\n Eccentric orifice, 'flange' taps, 90 degree side taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.5866 + 0.3917\\beta^{2.1} + .7586\\beta^8 - \\frac{.2273\\beta^4}{(1-\\beta^4)} - .3343\\beta^3\n\n .. math::\n b = 69.1 - 469.4\\beta + 1245.6\\beta^2 -1287.5\\beta^3 + 486.2\\beta^4\n\n Eccentric orifice, 'flange' taps, 90 degree side taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.6037 + 0.1598\\beta^{2.1} -.2918\\beta^8 + \\frac{0.0244\\beta^4}{(1-\\beta^4)} - 0.0790\\beta^3\n\n .. math::\n b = -103.2 + 898.3\\beta - 2557.3\\beta^2 + 2977.0\\beta^3 - 1131.3\\beta^4\n\n Eccentric orifice, 'vena contracta' taps, 180 degree opposite taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.5925 + 0.3380\\beta^{2.1} + 0.4016\\beta^8 - \\frac{.1046\\beta^4}{(1-\\beta^4)} - 0.3212\\beta^3\n\n .. math::\n b = 23.3 -207.0\\beta + 821.5\\beta^2 -1388.6\\beta^3 + 900.3\\beta^4\n\n Eccentric orifice, 'vena contracta' taps, 180 degree opposite taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.5922 + 0.3932\\beta^{2.1} + .3412\\beta^8 - \\frac{.0569\\beta^4}{(1-\\beta^4)} - 0.4628\\beta^3\n\n .. math::\n b = 55.7 - 471.4\\beta + 1721.8\\beta^2 - 2722.6\\beta^3 + 1569.4\\beta^4\n\n Eccentric orifice, 'vena contracta' taps, 90 degree side taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.5875 + 0.3813\\beta^{2.1} + 0.6898\\beta^8 - \\frac{0.1963\\beta^4}{(1-\\beta^4)} - 0.3366\\beta^3\n\n .. math::\n b = -69.3 + 556.9\\beta - 1332.2\\beta^2 + 1303.7\\beta^3 - 394.8\\beta^4\n\n Eccentric orifice, 'vena contracta' taps, 90 degree side taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.5949 + 0.4078\\beta^{2.1} + 0.0547\\beta^8 + \\frac{0.0955\\beta^4}{(1-\\beta^4)} - 0.5608\\beta^3\n\n .. math::\n b = 52.8 - 434.2\\beta + 1571.2\\beta^2 - 2460.9\\beta^3 + 1420.2\\beta^4\n\n\n Examples\n --------\n >>> C_Miller_1996(D=0.07391, Do=0.0222, rho=1.165, mu=1.85E-5, m=0.12, taps='flange', subtype='orifice')\n 0.599065557156788\n\n References\n ----------\n .. [1] Miller, Richard W. Flow Measurement Engineering Handbook.\n McGraw-Hill Education, 1996.\n .. [2] \"RW Miller & Associates.\" Accessed April 13, 2020.\n http://rwmillerassociates.com/.\n \"\"\"\n A_pipe = 0.25*pi*D*D\n v = m/(A_pipe*rho)\n Re = rho*v*D/mu\n D_mm = D*1000.0\n\n beta = Do/D\n beta2 = beta*beta\n beta3 = beta2*beta\n beta4 = beta*beta3\n beta8 = beta4*beta4\n beta21 = beta**2.1\n\n if subtype in (MILLER_ORIFICE, CONCENTRIC_ORIFICE):\n b = 91.706*beta2*sqrt(beta)\n n = 0.75\n if taps == ORIFICE_CORNER_TAPS:\n C_inf = 0.5959 + 0.0312*beta21 - 0.184*beta8\n elif taps == ORIFICE_FLANGE_TAPS:\n if D_mm >= 58.4:\n C_inf = 0.5959 + 0.0312*beta21 - 0.184*beta8 + 2.286*beta4/(D_mm*(1.0 - beta4)) - 0.856*beta3/D_mm\n else:\n C_inf = 0.5959 + 0.0312*beta21 - 0.184*beta8 + 0.039*beta4/(1.0 - beta4) - 0.856*beta3/D_mm\n elif taps == ORIFICE_D_AND_D_2_TAPS:\n C_inf = 0.5959 + 0.0312*beta21 - 0.184*beta8 + 0.039*beta4/(1.0 - beta4) - 0.01584\n elif taps == ORIFICE_PIPE_TAPS:\n C_inf = 0.5959 + 0.461*beta21 + 0.48*beta8 + 0.039*beta4/(1.0 - beta4)\n else:\n raise ValueError(_Miller_1996_unsupported_tap_concentric)\n elif subtype in (MILLER_ECCENTRIC_ORIFICE, ECCENTRIC_ORIFICE):\n if tap_position not in (TAPS_OPPOSITE, TAPS_SIDE):\n raise ValueError(_Miller_1996_unsupported_tap_pos_eccentric)\n n = 0.75\n if taps == ORIFICE_FLANGE_TAPS:\n if tap_position == TAPS_OPPOSITE:\n if D < 0.1:\n b = 7.3 - 15.7*beta + 170.8*beta2 - 399.7*beta3 + 332.2*beta4\n C_inf = 0.5917 + 0.3061*beta21 + 0.3406*beta8 - 0.1019*beta4/(1.0-beta4) - 0.2715*beta3\n else:\n b = -139.7 + 1328.8*beta - 4228.2*beta2 + 5691.9*beta3 - 2710.4*beta4\n C_inf = 0.6016 + 0.3312*beta21 - 1.5581*beta8 + 0.6510*beta4/(1.0-beta4) - 0.7308*beta3\n elif tap_position == TAPS_SIDE:\n if D < 0.1:\n b = 69.1 - 469.4*beta + 1245.6*beta2 -1287.5*beta3 + 486.2*beta4\n C_inf = 0.5866 + 0.3917*beta21 + 0.7586*beta8 - 0.2273*beta4/(1.0-beta4) - 0.3343*beta3\n else:\n b = -103.2 + 898.3*beta - 2557.3*beta2 + 2977.0*beta3 - 1131.3*beta4\n C_inf = 0.6037 + 0.1598*beta21 - 0.2918*beta8 + 0.0244*beta4/(1.0-beta4) - 0.0790*beta3\n elif taps == ORIFICE_VENA_CONTRACTA_TAPS:\n if tap_position == TAPS_OPPOSITE:\n if D < 0.1:\n b = 23.3 -207.0*beta + 821.5*beta2 -1388.6*beta3 + 900.3*beta4\n C_inf = 0.5925 + 0.3380*beta21 + 0.4016*beta8 - 0.1046*beta4/(1.0-beta4) - 0.3212*beta3\n else:\n b = 55.7 - 471.4*beta + 1721.8*beta2 - 2722.6*beta3 + 1569.4*beta4\n C_inf = 0.5922 + 0.3932*beta21 + 0.3412*beta8 - 0.0569*beta4/(1.0-beta4) - 0.4628*beta3\n elif tap_position == TAPS_SIDE:\n if D < 0.1:\n b = -69.3 + 556.9*beta - 1332.2*beta2 + 1303.7*beta3 - 394.8*beta4\n C_inf = 0.5875 + 0.3813*beta21 + 0.6898*beta8 - 0.1963*beta4/(1.0-beta4) - 0.3366*beta3\n else:\n b = 52.8 - 434.2*beta + 1571.2*beta2 - 2460.9*beta3 + 1420.2*beta4\n C_inf = 0.5949 + 0.4078*beta21 + 0.0547*beta8 + 0.0955*beta4/(1.0-beta4) - 0.5608*beta3\n else:\n raise ValueError(_Miller_1996_unsupported_tap_eccentric)\n elif subtype in (MILLER_SEGMENTAL_ORIFICE, SEGMENTAL_ORIFICE):\n n = b = 0.0\n if taps == ORIFICE_FLANGE_TAPS:\n if D < 0.1:\n C_inf = 0.6284 + 0.1462*beta21 - 0.8464*beta8 + 0.2603*beta4/(1.0-beta4) - 0.2886*beta3\n else:\n C_inf = 0.6276 + 0.0828*beta21 + 0.2739*beta8 - 0.0934*beta4/(1.0-beta4) - 0.1132*beta3\n elif taps == ORIFICE_VENA_CONTRACTA_TAPS:\n if D < 0.1:\n C_inf = 0.6261 + 0.1851*beta21 - 0.2879*beta8 + 0.1170*beta4/(1.0-beta4) - 0.2845*beta3\n else:\n # Yes these are supposed to be the same as the flange, large set\n C_inf = 0.6276 + 0.0828*beta21 + 0.2739*beta8 - 0.0934*beta4/(1.0-beta4) - 0.1132*beta3\n else:\n raise ValueError(_Miller_1996_unsupported_tap_segmental)\n elif subtype in (MILLER_CONICAL_ORIFICE, CONICAL_ORIFICE):\n n = b = 0.0\n if 250.0*beta <= Re <= 500.0*beta:\n C_inf = 0.734\n else:\n C_inf = 0.730\n elif subtype in (MILLER_QUARTER_CIRCLE_ORIFICE, QUARTER_CIRCLE_ORIFICE):\n n = b = 0.0\n C_inf = (0.7746 - 0.1334*beta21 + 1.4098*beta8\n + 0.0675*beta4/(1.0 - beta4) + 0.3865*beta3)\n else:\n raise ValueError(_Miller_1996_unsupported_type)\n C = C_inf + b*Re**-n\n return C\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 19793}, "tests/test_flow_meter.py::895": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/flow_meter.py", "fluids/numerics/__init__.py"], "used_names": ["CONCENTRIC_ORIFICE", "HOLLINGSHEAD_CONE", "HOLLINGSHEAD_ORIFICE", "HOLLINGSHEAD_VENTURI_SHARP", "HOLLINGSHEAD_VENTURI_SMOOTH", "HOLLINGSHEAD_WEDGE", "ISO_15377_CONICAL_ORIFICE", "ISO_15377_ECCENTRIC_ORIFICE", "ISO_15377_QUARTER_CIRCLE_ORIFICE", "MILLER_CONICAL_ORIFICE", "MILLER_ORIFICE", "assert_close", "differential_pressure_meter_C_epsilon", "pytest"], "enclosing_function": "test_differential_pressure_meter_C_epsilon", "extracted_code": "# Source: fluids/flow_meter.py\nCONCENTRIC_ORIFICE = \"orifice\"\n\nISO_15377_ECCENTRIC_ORIFICE = \"ISO 15377 eccentric orifice\"\n\nISO_15377_QUARTER_CIRCLE_ORIFICE = \"ISO 15377 quarter-circle orifice\"\n\nISO_15377_CONICAL_ORIFICE = \"ISO 15377 conical orifice\"\n\nMILLER_ORIFICE = \"Miller orifice\"\n\nMILLER_CONICAL_ORIFICE = \"Miller conical orifice\"\n\nHOLLINGSHEAD_ORIFICE = \"Hollingshead orifice\"\n\nHOLLINGSHEAD_VENTURI_SMOOTH = \"Hollingshead venturi smooth\"\n\nHOLLINGSHEAD_VENTURI_SHARP = \"Hollingshead venturi sharp\"\n\nHOLLINGSHEAD_CONE = \"Hollingshead v cone\"\n\nHOLLINGSHEAD_WEDGE = \"Hollingshead wedge\"\n\ndef differential_pressure_meter_C_epsilon(D: float, D2: float, m: float, P1: float, P2: float, rho: float, mu: float, k: float,\n meter_type: str, taps: str | None=None,\n tap_position: str | None=None, C_specified: float | None=None,\n epsilon_specified: int | None=None) -> tuple[float, float] | tuple[float, int]:\n r\"\"\"Calculates the discharge coefficient and expansibility of a flow\n meter given the mass flow rate, the upstream pressure, the second\n pressure value, and the orifice diameter for a differential\n pressure flow meter based on the geometry of the meter, measured pressures\n of the meter, and the density, viscosity, and isentropic exponent of the\n fluid.\n\n Parameters\n ----------\n D : float\n Upstream internal pipe diameter, [m]\n D2 : float\n Diameter of orifice, or venturi meter orifice, or flow tube orifice,\n or cone meter end diameter, or wedge meter fluid flow height, [m]\n m : float\n Mass flow rate of fluid through the flow meter, [kg/s]\n P1 : float\n Static pressure of fluid upstream of differential pressure meter at the\n cross-section of the pressure tap, [Pa]\n P2 : float\n Static pressure of fluid downstream of differential pressure meter or\n at the prescribed location (varies by type of meter) [Pa]\n rho : float\n Density of fluid at `P1`, [kg/m^3]\n mu : float\n Viscosity of fluid at `P1`, [Pa*s]\n k : float\n Isentropic exponent of fluid, [-]\n meter_type : str\n One of {'conical orifice', 'orifice', 'machined convergent venturi tube',\n 'ISO 5167 orifice', 'Miller quarter circle orifice', 'Hollingshead venturi sharp',\n 'segmental orifice', 'Miller conical orifice', 'Miller segmental orifice',\n 'quarter circle orifice', 'Hollingshead v cone', 'wedge meter', 'eccentric orifice',\n 'venturi nozzle', 'rough welded convergent venturi tube', 'ISA 1932 nozzle',\n 'ISO 15377 quarter-circle orifice', 'Hollingshead venturi smooth',\n 'Hollingshead orifice', 'cone meter', 'Hollingshead wedge', 'Miller orifice',\n 'long radius nozzle', 'ISO 15377 conical orifice', 'unspecified meter',\n 'as cast convergent venturi tube', 'Miller eccentric orifice',\n 'ISO 15377 eccentric orifice'}, [-]\n taps : str, optional\n The orientation of the taps; one of 'corner', 'flange', 'D', or 'D/2';\n applies for orifice meters only, [-]\n tap_position : str, optional\n The rotation of the taps, used **only for the eccentric orifice case**\n where the pressure profiles are not symmetric; '180 degree' for the\n normal case where the taps are opposite the orifice bore, and\n '90 degree' for the case where, normally for operational reasons, the\n taps are near the bore [-]\n C_specified : float, optional\n If specified, the correlation for the meter type is not used - this\n value is returned for `C`\n epsilon_specified : float, optional\n If specified, the correlation for the fluid expansibility is not used -\n this value is returned for :math:`\\epsilon`, [-]\n\n Returns\n -------\n C : float\n Coefficient of discharge of the specified flow meter type at the\n specified conditions, [-]\n expansibility : float\n Expansibility factor (1 for incompressible fluids, less than 1 for\n real fluids), [-]\n\n Notes\n -----\n This function should be called by an outer loop when solving for a\n variable.\n\n The latest ISO formulations for `expansibility` are used with the Miller\n correlations.\n\n Examples\n --------\n >>> differential_pressure_meter_C_epsilon(D=0.07366, D2=0.05, P1=200000.0,\n ... P2=183000.0, rho=999.1, mu=0.0011, k=1.33, m=7.702338035732168,\n ... meter_type='ISO 5167 orifice', taps='D')\n (0.6151252900244296, 0.9711026966676307)\n \"\"\"\n # Translate default meter type to implementation specific correlation\n if meter_type == CONCENTRIC_ORIFICE:\n meter_type = ISO_5167_ORIFICE\n elif meter_type == ECCENTRIC_ORIFICE:\n meter_type = ISO_15377_ECCENTRIC_ORIFICE\n elif meter_type == CONICAL_ORIFICE:\n meter_type = ISO_15377_CONICAL_ORIFICE\n elif meter_type == QUARTER_CIRCLE_ORIFICE:\n meter_type = ISO_15377_QUARTER_CIRCLE_ORIFICE\n elif meter_type == SEGMENTAL_ORIFICE:\n meter_type = MILLER_SEGMENTAL_ORIFICE\n\n if meter_type == ISO_5167_ORIFICE:\n taps_val = taps if taps is not None else \"corner\"\n C = C_Reader_Harris_Gallagher(D, D2, rho, mu, m, taps_val)\n epsilon = orifice_expansibility(D, D2, P1, P2, k)\n elif meter_type == ISO_15377_ECCENTRIC_ORIFICE:\n C = C_eccentric_orifice_ISO_15377_1998(D, D2)\n epsilon = orifice_expansibility(D, D2, P1, P2, k)\n elif meter_type == ISO_15377_QUARTER_CIRCLE_ORIFICE:\n C = C_quarter_circle_orifice_ISO_15377_1998(D, D2)\n epsilon = orifice_expansibility(D, D2, P1, P2, k)\n elif meter_type == ISO_15377_CONICAL_ORIFICE:\n C = ISO_15377_CONICAL_ORIFICE_C\n # Average of concentric square edge orifice and ISA 1932 nozzles\n epsilon = 0.5*(orifice_expansibility(D, D2, P1, P2, k)\n + nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k))\n\n elif meter_type in (MILLER_ORIFICE, MILLER_ECCENTRIC_ORIFICE,\n MILLER_SEGMENTAL_ORIFICE, MILLER_QUARTER_CIRCLE_ORIFICE):\n C = C_Miller_1996(D, D2, rho, mu, m, subtype=meter_type, taps=taps,\n tap_position=tap_position)\n epsilon = orifice_expansibility(D, D2, P1, P2, k)\n elif meter_type == MILLER_CONICAL_ORIFICE:\n C = C_Miller_1996(D, D2, rho, mu, m, subtype=meter_type, taps=taps,\n tap_position=tap_position)\n epsilon = 0.5*(orifice_expansibility(D, D2, P1, P2, k)\n + nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k))\n elif meter_type == LONG_RADIUS_NOZZLE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = C_long_radius_nozzle(D=D, Do=D2, rho=rho, mu=mu, m=m)\n elif meter_type == ISA_1932_NOZZLE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = C_ISA_1932_nozzle(D=D, Do=D2, rho=rho, mu=mu, m=m)\n elif meter_type == VENTURI_NOZZLE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = C_venturi_nozzle(D=D, Do=D2)\n\n elif meter_type == AS_CAST_VENTURI_TUBE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = AS_CAST_VENTURI_TUBE_C\n elif meter_type == MACHINED_CONVERGENT_VENTURI_TUBE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = MACHINED_CONVERGENT_VENTURI_TUBE_C\n elif meter_type == ROUGH_WELDED_CONVERGENT_VENTURI_TUBE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = ROUGH_WELDED_CONVERGENT_VENTURI_TUBE_C\n\n elif meter_type == CONE_METER:\n epsilon = cone_meter_expansibility_Stewart(D=D, Dc=D2, P1=P1, P2=P2, k=k)\n C = CONE_METER_C\n elif meter_type == WEDGE_METER:\n beta = diameter_ratio_wedge_meter(D=D, H=D2)\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k, beta=beta)\n C = C_wedge_meter_ISO_5167_6_2017(D=D, H=D2)\n elif meter_type == HOLLINGSHEAD_ORIFICE:\n v = m/((0.25*pi*D*D)*rho)\n Re_D = rho*v*D/mu\n C = float(bisplev(D2/D, log(Re_D), orifice_std_Hollingshead_tck))\n epsilon = orifice_expansibility(D, D2, P1, P2, k)\n elif meter_type == HOLLINGSHEAD_VENTURI_SMOOTH:\n v = m/((0.25*pi*D*D)*rho)\n Re_D = rho*v*D/mu\n C = interp(log(Re_D), venturi_logRes_Hollingshead, venturi_smooth_Cs_Hollingshead, extrapolate=True)\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n elif meter_type == HOLLINGSHEAD_VENTURI_SHARP:\n v = m/((0.25*pi*D*D)*rho)\n Re_D = rho*v*D/mu\n C = interp(log(Re_D), venturi_logRes_Hollingshead, venturi_sharp_Cs_Hollingshead, extrapolate=True)\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n elif meter_type == HOLLINGSHEAD_CONE:\n v = m/((0.25*pi*D*D)*rho)\n Re_D = rho*v*D/mu\n beta = diameter_ratio_cone_meter(D, D2)\n C = float(bisplev(beta, log(Re_D), cone_Hollingshead_tck))\n epsilon = cone_meter_expansibility_Stewart(D=D, Dc=D2, P1=P1, P2=P2, k=k)\n elif meter_type == HOLLINGSHEAD_WEDGE:\n v = m/((0.25*pi*D*D)*rho)\n Re_D = rho*v*D/mu\n beta = diameter_ratio_wedge_meter(D=D, H=D2)\n C = float(bisplev(beta, log(Re_D), wedge_Hollingshead_tck))\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k, beta=beta)\n elif meter_type == UNSPECIFIED_METER:\n epsilon = orifice_expansibility(D, D2, P1, P2, k) # Default to orifice type expansibility\n if C_specified is None:\n raise ValueError(\"For unspecified meter type, C_specified is required\")\n else:\n raise ValueError(_unsupported_meter_msg)\n if C_specified is not None:\n C = C_specified\n if epsilon_specified is not None:\n epsilon = epsilon_specified\n return C, epsilon\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 10525}, "tests/test_friction.py::185": {"resolved_imports": ["fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["Clamond", "_roughness", "assert_close", "friction_factor", "friction_factor_methods", "ft_Crane", "pytest", "roughness_Farshad"], "enclosing_function": "test_friction", "extracted_code": "# Source: fluids/friction.py\ndef Clamond(Re: float, eD: float, fast: bool=False) -> float:\n r\"\"\"Calculates Darcy friction factor using a solution accurate to almost\n machine precision. Recommended very strongly. For details of the algorithm,\n see [1]_.\n\n Parameters\n ----------\n Re : float\n Reynolds number, [-]\n eD : float\n Relative roughness, [-]\n fast : bool, optional\n If true, performs only one iteration, which gives roughly half the\n number of decimals of accuracy, [-]\n\n Returns\n -------\n fd : float\n Darcy friction factor [-]\n\n Notes\n -----\n This is a highly optimized function, 4 times faster than the solution using\n the LambertW function, and faster than many other approximations which are\n much less accurate.\n\n The code used here is only slightly modified from that in [1]_, for further\n performance improvements.\n\n For 10 < Re < 1E12, and 0 < eD < 0.01, this equation has been confirmed\n numerically to provide a solution to the Colebrook equation accurate to an\n rtol of 1E-9 or better - the same level of accuracy as the analytical\n solution to the Colebrook equation due to floating point precision.\n\n Comparing this to the numerical solution of the Colebrook equation,\n identical values are given accurate to an rtol of 1E-9 for 10 < Re < 1E100,\n and 0 < eD < 1 and beyond.\n\n However, for values of Re under 10, different answers from the `Colebrook`\n equation appear and then quickly a ValueError is raised.\n\n Examples\n --------\n >>> Clamond(1E5, 1E-4)\n 0.01851386607747165\n\n References\n ----------\n .. [1] Clamond, Didier. \"Efficient Resolution of the Colebrook Equation.\"\n Industrial & Engineering Chemistry Research 48, no. 7 (April 1, 2009):\n 3665-71. doi:10.1021/ie801626g.\n http://math.unice.fr/%7Edidierc/DidPublis/ICR_2009.pdf\n \"\"\"\n X1 = eD*Re*0.1239681863354175460160858261654858382699 # (log(10)/18.574).evalf(40)\n X2 = log(Re) - 0.7793974884556819406441139701653776731705 # log(log(10)/5.02).evalf(40)\n F = X2 - 0.2\n X1F = X1 + F\n X1F1 = 1. + X1F\n\n E = (log(X1F) - 0.2)/(X1F1)\n F = F - (X1F1 + 0.5*E)*E*(X1F)/(X1F1 + E*(1. + (1.0/3.0)*E))\n\n if not fast:\n X1F = X1 + F\n X1F1 = 1. + X1F\n E = (log(X1F) + F - X2)/(X1F1)\n\n b = (X1F1 + E*(1. + 1.0/3.0*E))\n F = b/(b*F - ((X1F1 + 0.5*E)*E*(X1F)))\n return 1.325474527619599502640416597148504422899*(F*F) # ((0.5*log(10))**2).evalf(40)\n\n return 1.325474527619599502640416597148504422899/(F*F)\n\ndef ft_Crane(D: float) -> float:\n r\"\"\"Calculates the Crane fully turbulent Darcy friction factor for flow in\n commercial pipe, as used in the Crane formulas for loss coefficients in\n various fittings. Note that this is **not generally applicable to loss\n due to friction in pipes**, as it does not take into account the roughness\n of various pipe materials. But for fittings in any type of pipe, this is\n the friction factor to use in the Crane [1]_ method to get their loss\n coefficients.\n\n Parameters\n ----------\n D : float\n Pipe inner diameter, [m]\n\n Returns\n -------\n fd : float\n Darcy Crane friction factor for fully turbulent flow, [-]\n\n Notes\n -----\n There is confusion and uncertainty regarding the friction factor table\n given in Crane TP 410M [1]_. This function does not help: it implements a\n new way to obtain Crane friction factors, so that it can better be based in\n theory and give more precision (not accuracy) and trend better with\n diameters not tabulated in [1]_.\n\n The data in [1]_ was digitized, and nominal pipe diameters were converted\n to actual pipe diameters. An objective function was sought which would\n produce the exact same values as in [1]_ when rounded to the same decimal\n place. One was found fairly easily by using the standard `Colebrook`\n friction factor formula, and using the diameter-dependent roughness values\n calculated with the `roughness_Farshad` method for bare Carbon steel. A\n diameter-dependent Reynolds number was required to match the values;\n the :math:`\\rho V/\\mu` term is set to 7.5E6.\n\n The formula given in [1]_ is:\n\n .. math::\n f_T = \\frac{0.25}{\\left[\\log_{10}\\left(\\frac{\\epsilon/D}{3.7}\\right)\n \\right]^2}\n\n However, this function does not match the rounded values in [1]_ well and\n it is not very clear which roughness to use. Using both the value for new\n commercial steel (.05 mm) or a diameter-dependent value\n (`roughness_Farshad`), values were found to be too high and too low\n respectively. That function is based in theory - the limit of the\n `Colebrook` equation when `Re` goes to infinity - but in the end real pipe\n flow is not infinity, and so a large error occurs from that use.\n\n The following plot shows all these options, and that the method implemented\n here matches perfectly the rounded values in [1]_.\n\n .. plot:: plots/ft_Crane_plot.py\n\n Examples\n --------\n >>> ft_Crane(.1)\n 0.01628845962146481\n\n Explicitly spelling out the function (note the exact same answer is not\n returned; it is accurate to 5-8 decimals however, for increased speed):\n\n >>> Di = 0.1\n >>> Colebrook(7.5E6*Di, eD=roughness_Farshad(ID='Carbon steel, bare', D=Di)/Di)\n 0.0162884254312\n\n References\n ----------\n .. [1] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,\n 2009.\n \"\"\"\n fast = True\n if D < 1E-2:\n fast = False\n return Clamond(7.5E6*D, 3.4126825352925e-5*D**-1.0112, fast)\n\ndef friction_factor_methods(Re: float, eD: float=0.0, check_ranges: bool=True) -> list[str]:\n r\"\"\"Returns a list of correlation names for calculating friction factor\n for internal pipe flow.\n\n Examples\n --------\n >>> len(friction_factor_methods(Re=1E5, eD=1E-4))\n 30\n\n Parameters\n ----------\n Re : float\n Reynolds number, [-]\n eD : float, optional\n Relative roughness of the wall, [-]\n check_ranges : bool, optional\n Whether to filter the list for correlations which claim to be valid for\n the given values, [-]\n\n Returns\n -------\n methods : list\n List of methods which claim to be valid for the range of `Re` and `eD`\n given, [-]\n \"\"\"\n if check_ranges:\n if Re < LAMINAR_TRANSITION_PIPE:\n return [\"laminar\"]\n methods = []\n for n, (Re_min, Re_max, eD_min, eD_max) in fmethods.items():\n if Re_min is not None and Re < Re_min:\n continue\n if Re_max is not None and Re > Re_max:\n continue\n if eD_min is not None and eD < eD_min:\n continue\n if eD_max is not None and eD > eD_max:\n continue\n methods.append(n)\n return methods\n else:\n return list(fmethods.keys()) + [\"laminar\"]\n\ndef friction_factor(Re: float, eD: float=0.0, Method: str | None=\"Clamond\", Darcy: bool=True) -> float:\n r\"\"\"Calculates friction factor. Uses a specified method, or automatically\n picks one from the dictionary of available methods. 29 approximations are\n available as well as the direct solution, described in the table below.\n The default is to use the exact solution.\n\n For Re < 2040, [1]_ the laminar solution is always returned, regardless of\n selected method.\n\n Examples\n --------\n >>> friction_factor(Re=1E5, eD=1E-4)\n 0.01851386607747165\n >>> friction_factor(Re=2.9E5, eD=1E-5, Method='Serghides_2')\n 0.0146199041093456\n\n Parameters\n ----------\n Re : float\n Reynolds number, [-]\n eD : float, optional\n Relative roughness of the wall, [-]\n\n Returns\n -------\n f : float\n Friction factor, [-]\n\n Other Parameters\n ----------------\n Method : string, optional\n A string of the function name to use\n Darcy : bool, optional\n If False, will return fanning friction factor, 1/4 of the Darcy value\n\n See Also\n --------\n Colebrook\n Clamond\n\n Notes\n -----\n A table of the supposed limits of each correlation is as follows. Note that\n the spaces in the method names are replaced by underscores in the actual\n function names and when provided as the `Method` argument. The default\n method is likely to be sufficient.\n\n\n +-------------------+------+------+----------------------+----------------------+\n |Nice name |Re min|Re max|:math:`\\epsilon/D` Min|:math:`\\epsilon/D` Max|\n +===================+======+======+======================+======================+\n |Clamond |0 |None |0 |None |\n +-------------------+------+------+----------------------+----------------------+\n |Rao Kumar 2007 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Eck 1973 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Jain 1976 |5000 |1.0E+7|4.0E-5 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Avci Karagoz 2009 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Swamee Jain 1976 |5000 |1.0E+8|1.0E-6 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Churchill 1977 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Brkic 2011 1 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Chen 1979 |4000 |4.0E+8|1.0E-7 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Round 1980 |4000 |4.0E+8|0 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Papaevangelo 2010 |10000 |1.0E+7|1.0E-5 |0.001 |\n +-------------------+------+------+----------------------+----------------------+\n |Fang 2011 |3000 |1.0E+8|0 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Shacham 1980 |4000 |4.0E+8|None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Barr 1981 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Churchill 1973 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Moody |4000 |1.0E+8|0 |1 |\n +-------------------+------+------+----------------------+----------------------+\n |Zigrang Sylvester 1|4000 |1.0E+8|4.0E-5 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Zigrang Sylvester 2|4000 |1.0E+8|4.0E-5 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Buzzelli 2008 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Haaland |4000 |1.0E+8|1.0E-6 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Serghides 1 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Serghides 2 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Tsal 1989 |4000 |1.0E+8|0 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Alshul 1952 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Wood 1966 |4000 |5.0E+7|1.0E-5 |0.04 |\n +-------------------+------+------+----------------------+----------------------+\n |Manadilli 1997 |5245 |1.0E+8|0 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Brkic 2011 2 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Romeo 2002 |3000 |1.5E+8|0 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Sonnad Goudar 2006 |4000 |1.0E+8|1.0E-6 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n\n References\n ----------\n .. [1] Avila, Kerstin, David Moxey, Alberto de Lozar, Marc Avila, Dwight\n Barkley, and Björn Hof. \"The Onset of Turbulence in Pipe Flow.\" Science\n 333, no. 6039 (July 8, 2011): 192-96. doi:10.1126/science.1203223.\n \"\"\"\n if Method is None:\n Method = \"Clamond\"\n\n if Re < LAMINAR_TRANSITION_PIPE or Method == \"laminar\":\n f = friction_laminar(Re)\n elif Method == \"Clamond\":\n f = Clamond(Re, eD, False)\n elif Method == \"Colebrook\":\n f = Colebrook(Re, eD)\n elif Method == \"Moody\":\n f = Moody(Re, eD)\n elif Method == \"Alshul_1952\":\n f = Alshul_1952(Re, eD)\n elif Method == \"Wood_1966\":\n f = Wood_1966(Re, eD)\n elif Method == \"Churchill_1973\":\n f = Churchill_1973(Re, eD)\n elif Method == \"Eck_1973\":\n f = Eck_1973(Re, eD)\n elif Method == \"Jain_1976\":\n f = Jain_1976(Re, eD)\n elif Method == \"Swamee_Jain_1976\":\n f = Swamee_Jain_1976(Re, eD)\n elif Method == \"Churchill_1977\":\n f = Churchill_1977(Re, eD)\n elif Method == \"Chen_1979\":\n f = Chen_1979(Re, eD)\n elif Method == \"Round_1980\":\n f = Round_1980(Re, eD)\n elif Method == \"Shacham_1980\":\n f = Shacham_1980(Re, eD)\n elif Method == \"Barr_1981\":\n f = Barr_1981(Re, eD)\n elif Method == \"Zigrang_Sylvester_1\":\n f = Zigrang_Sylvester_1(Re, eD)\n elif Method == \"Zigrang_Sylvester_2\":\n f = Zigrang_Sylvester_2(Re, eD)\n elif Method == \"Haaland\":\n f = Haaland(Re, eD)\n elif Method == \"Serghides_1\":\n f = Serghides_1(Re, eD)\n elif Method == \"Serghides_2\":\n f = Serghides_2(Re, eD)\n elif Method == \"Tsal_1989\":\n f = Tsal_1989(Re, eD)\n elif Method == \"Manadilli_1997\":\n f = Manadilli_1997(Re, eD)\n elif Method == \"Romeo_2002\":\n f = Romeo_2002(Re, eD)\n elif Method == \"Sonnad_Goudar_2006\":\n f = Sonnad_Goudar_2006(Re, eD)\n elif Method == \"Rao_Kumar_2007\":\n f = Rao_Kumar_2007(Re, eD)\n elif Method == \"Buzzelli_2008\":\n f = Buzzelli_2008(Re, eD)\n elif Method == \"Avci_Karagoz_2009\":\n f = Avci_Karagoz_2009(Re, eD)\n elif Method == \"Papaevangelo_2010\":\n f = Papaevangelo_2010(Re, eD)\n elif Method == \"Brkic_2011_1\":\n f = Brkic_2011_1(Re, eD)\n elif Method == \"Brkic_2011_2\":\n f = Brkic_2011_2(Re, eD)\n elif Method == \"Fang_2011\":\n f = Fang_2011(Re, eD)\n else:\n raise ValueError(\"Method not recognized\")\n if not Darcy:\n f *= 0.25\n return f\n\n_roughness = {\"Brass\": .00000152, \"Lead\": .00000152, \"Glass\": .00000152,\n\"Steel\": .00000152, \"Asphalted cast iron\": .000122, \"Galvanized iron\": .000152,\n\"Cast iron\": .000259, \"Wood stave\": .000183, \"Rough wood stave\": .000914,\n\"Concrete\": .000305, \"Rough concrete\": .00305, \"Riveted steel\": .000914,\n\"Rough riveted steel\": .00914}\n\ndef roughness_Farshad(ID: str | None=None, D: float | None=None, coeffs: tuple[float, float] | None=None) -> float:\n r\"\"\"Calculates or retrieves the roughness of a pipe based on the work of\n [1]_. This function will return an average value for pipes of a given\n material, or if diameter is provided, will calculate one specifically for\n the pipe inner diameter according to the following expression with\n constants `A` and `B`:\n\n .. math::\n \\epsilon = A\\cdot D^{B+1}\n\n Please note that `A` has units of inches, and `B` requires `D` to be in\n inches as well.\n\n The list of supported materials is as follows:\n\n * 'Plastic coated'\n * 'Carbon steel, honed bare'\n * 'Cr13, electropolished bare'\n * 'Cement lining'\n * 'Carbon steel, bare'\n * 'Fiberglass lining'\n * 'Cr13, bare'\n\n If `coeffs` and `D` are given, the custom coefficients for the equation as\n given by the user will be used and `ID` is not required.\n\n Parameters\n ----------\n ID : str, optional\n Name of pipe material from above list\n D : float, optional\n Actual inner diameter of pipe, [m]\n coeffs : tuple, optional\n (A, B) Coefficients to use directly, instead of looking them up;\n they are actually dimensional, in the forms (inch^-B, -) but only\n coefficients with those dimensions are available [-]\n\n Returns\n -------\n epsilon : float\n Roughness of pipe [m]\n\n Notes\n -----\n The diameter-dependent form provides lower roughness values for larger\n diameters.\n\n The measurements were based on DIN 4768/1 (1987), using both a\n \"Dektak ST Surface Profiler\" and a \"Hommel Tester T1000\". Both instruments\n were found to be in agreement. A series of flow tests, in which pressure\n drop directly measured, were performed as well, with nitrogen gas as an\n operating fluid. The accuracy of the data from these tests is claimed to be\n within 1%.\n\n Using those results, the authors back-calculated what relative roughness\n values would be necessary to produce the observed pressure drops. The\n average difference between this back-calculated roughness and the measured\n roughness was 6.75%.\n\n For microchannels, this model will predict roughness much larger than the\n actual channel diameter.\n\n Examples\n --------\n >>> roughness_Farshad('Cr13, bare', 0.05)\n 5.3141677781137006e-05\n\n References\n ----------\n .. [1] Farshad, Fred F., and Herman H. Rieke. \"Surface Roughness Design\n Values for Modern Pipes.\" SPE Drilling & Completion 21, no. 3 (September\n 1, 2006): 212-215. doi:10.2118/89040-PA.\n \"\"\"\n # Case 1, coeffs given; only run if ID is not given.\n if ID is None and coeffs is not None:\n if D is None:\n raise ValueError(\"D is required when using coeffs\")\n A, B = coeffs\n return A*(D/inch)**(B + 1.0)*inch\n # Case 2, lookup parameters\n if ID in _Farshad_roughness: # numba: delete\n dat = _Farshad_roughness[ID] # numba: delete\n# try: # numba: uncomment\n# dat = _Farshad_roughness_values[_Farshad_roughness_keys.index(ID)] # numba: uncomment\n# except: # numba: uncomment\n# raise KeyError('ID was not in _Farshad_roughness.') # numba: uncomment\n if D is None:\n return dat[0]\n else:\n A, B = dat[1], dat[2]\n return A*(D/inch)**(B+1)*inch\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 20600}, "tests/test_control_valve.py::197": {"resolved_imports": ["fluids/control_valve.py", "fluids/fittings.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "pytest", "size_control_valve_g", "size_control_valve_l"], "enclosing_function": "test_control_valve_size_l", "extracted_code": "# Source: fluids/control_valve.py\ndef size_control_valve_l(rho: float, Psat: float, Pc: float, mu: float, P1: float, P2: float, Q: float, D1: float | None=None, D2: float | None=None,\n d: float | None=None, FL: float=0.9, Fd: float=1, allow_choked: bool=True,\n allow_laminar: bool=True, full_output: bool=False) -> float | dict[str, bool | float | None] | dict[str, float | bool | str | None]:\n r\"\"\"Calculates flow coefficient of a control valve passing a liquid\n according to IEC 60534. Uses a large number of inputs in SI units. Note the\n return value is not standard SI. All parameters are required.\n This sizing model does not officially apply to liquid mixtures, slurries,\n non-Newtonian fluids, or liquid-solid conveyance systems. For details\n of the calculations, consult [1]_.\n\n Parameters\n ----------\n rho : float\n Density of the liquid at the inlet [kg/m^3]\n Psat : float\n Saturation pressure of the fluid at inlet temperature [Pa]\n Pc : float\n Critical pressure of the fluid [Pa]\n mu : float\n Viscosity of the fluid [Pa*s]\n P1 : float\n Inlet pressure of the fluid before valves and reducers [Pa]\n P2 : float\n Outlet pressure of the fluid after valves and reducers [Pa]\n Q : float\n Volumetric flow rate of the fluid [m^3/s]\n D1 : float, optional\n Diameter of the pipe before the valve [m]\n D2 : float, optional\n Diameter of the pipe after the valve [m]\n d : float, optional\n Diameter of the valve [m]\n FL : float, optional\n Liquid pressure recovery factor of a control valve without attached\n fittings (normally 0.8-0.9 at full open and decreasing as opened\n further to below 0.5; use default very cautiously!) []\n Fd : float, optional\n Valve style modifier (0.1 to 1; varies tremendously depending on the\n type of valve and position; do not use the default at all!) []\n allow_choked : bool, optional\n Overrides the automatic transition into the choked regime if this is\n False and returns as if choked flow does not exist\n allow_laminar : bool, optional\n Overrides the automatic transition into the laminar regime if this is\n False and returns as if laminar flow does not exist\n full_output : bool, optional\n If True, returns intermediate calculation values as\n well as Kv in the form of a dictionary containing 'Kv', 'Rev', 'choked',\n 'FL', 'FLP', 'FR', 'FP', and 'laminar'. Some may be None if they are\n not used in the calculation.\n\n Returns\n -------\n Kv : float\n Metric Kv valve flow coefficient (flow rate of water at a pressure drop\n of 1 bar) [m^3/hr]\n\n Notes\n -----\n It is possible to use this model without any diameters specified; in that\n case, turbulent flow is assumed. Choked flow can still be modeled. This is\n not recommended. All three diameters need to be None for this to work.\n `FL` and `Fd` are not used by the models when the diameters are not\n specified.\n\n Examples\n --------\n From [1]_, matching example 1 for a globe, parabolic plug,\n flow-to-open valve.\n\n >>> size_control_valve_l(rho=965.4, Psat=70.1E3, Pc=22120E3, mu=3.1472E-4,\n ... P1=680E3, P2=220E3, Q=0.1, D1=0.15, D2=0.15, d=0.15,\n ... FL=0.9, Fd=0.46)\n 164.9954763704956\n\n From [1]_, matching example 2 for a ball, segmented ball,\n flow-to-open valve.\n\n >>> size_control_valve_l(rho=965.4, Psat=70.1E3, Pc=22120E3, mu=3.1472E-4,\n ... P1=680E3, P2=220E3, Q=0.1, D1=0.1, D2=0.1, d=0.1,\n ... FL=0.6, Fd=0.98)\n 238.05817216710483\n\n References\n ----------\n .. [1] IEC 60534-2-1 / ISA-75.01.01-2007\n \"\"\"\n if full_output:\n ans: dict[str, bool | float | None] = {\"FLP\": None, \"FP\": None, \"FR\": None}\n # Pa to kPa, according to constants in standard\n P1, P2, Psat, Pc = P1/1000., P2/1000., Psat/1000., Pc/1000.\n Q = Q*3600. # m^3/s to m^3/hr, according to constants in standard\n nu = mu/rho # kinematic viscosity used in standard\n MAX_C_POSSIBLE = 1E40 # Quit iterations if C reaches this high\n\n dP = P1 - P2\n FF = FF_critical_pressure_ratio_l(Psat=Psat, Pc=Pc)\n choked = is_choked_turbulent_l(dP=dP, P1=P1, Psat=Psat, FF=FF, FL=FL)\n if choked and allow_choked:\n # Choked flow, equation 3\n C = Q/N1/FL*sqrt(rho/rho0/(P1 - FF*Psat))\n else:\n # non-choked flow, eq 1\n C = Q/N1*sqrt(rho/rho0/dP)\n if D1 is None and D2 is None and d is None:\n # Assume turbulent if no diameters are provided, no other calculations\n Rev = 1e5\n else:\n # m to mm, according to constants in standard\n if D1 is None or D2 is None or d is None:\n raise ValueError(\"If any diameter is specified, all three (D1, D2, d) must be specified\")\n D1, D2, d = D1*1000., D2*1000., d*1000.\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=C)\n # normal calculation path\n if (Rev > 10000 or not allow_laminar) and (D1 != d or D2 != d):\n # liquid, using Fp and FLP\n FP = 1.0\n Ci = C\n MAX_ITER = 20\n def iterate_piping_turbulent_l(Ci, iterations):\n loss = loss_coefficient_piping(d, D1, D2)\n FP = 1.0/sqrt(1 + loss/N2*(Ci/d**2)**2)\n if d > D1:\n loss_upstream = 0.0\n else:\n loss_upstream = loss_coefficient_piping(d, D1)\n\n FLP = FL*1.0/sqrt(1 + FL**2/N2*loss_upstream*(Ci/d**2)**2)\n choked = is_choked_turbulent_l(dP, P1, Psat, FF, FLP=FLP, FP=FP)\n if choked:\n # Choked flow with piping, equation 4\n C = Q/N1/FLP*sqrt(rho/rho0/(P1-FF*Psat))\n else:\n # Non-Choked flow with piping, equation 5\n C = Q/N1/FP*sqrt(rho/rho0/dP)\n if Ci/C < 0.99 and iterations < MAX_ITER and Ci < MAX_C_POSSIBLE:\n C = iterate_piping_turbulent_l(C, iterations+1)\n if MAX_ITER == iterations or Ci >= MAX_C_POSSIBLE:\n ans[\"warning\"] = \"Not converged in inner loop\"\n if full_output:\n ans[\"FLP\"] = FLP\n ans[\"FP\"] = FP\n return C\n\n C = iterate_piping_turbulent_l(Ci, 0)\n elif Rev <= 10000 and allow_laminar:\n # Laminar\n def iterate_piping_laminar_l(C):\n Ci = 1.3*C\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=Ci)\n if Ci/(d*d) > 0.016*N18:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=False)\n else:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=True)\n if C/FR >= Ci:\n Ci = iterate_piping_laminar_l(Ci) # pragma: no cover\n\n if full_output:\n ans[\"Rev\"] = Rev\n ans[\"FR\"] = FR\n return Ci\n C = iterate_piping_laminar_l(C)\n if full_output:\n ans[\"FF\"] = FF\n ans[\"choked\"] = choked\n ans[\"Kv\"] = C\n ans[\"laminar\"] = Rev <= 10000\n\n # For the laminar case this is already set and needs to not be overwritten\n if \"Rev\" not in ans:\n ans[\"Rev\"] = Rev\n return ans\n else:\n# return C, choked, laminar, FF, FR, Rev, FP, FLP, warning\n return C\n\ndef size_control_valve_g(T: float, MW: float, mu: float, gamma: float, Z: float, P1: float, P2: float, Q: float, D1: float | None=None, D2: float | None=None,\n d: float | None=None, FL: float=0.9, Fd: float=1, xT: float=0.7, allow_choked: bool=True,\n allow_laminar: bool=True, full_output: bool=False) -> float | dict[str, bool | float | None] | dict[str, float | bool | str | None]:\n r\"\"\"Calculates flow coefficient of a control valve passing a gas\n according to IEC 60534. Uses a large number of inputs in SI units. Note the\n return value is not standard SI. All parameters are required. For details\n of the calculations, consult [1]_. Note the inlet gas flow conditions.\n\n Parameters\n ----------\n T : float\n Temperature of the gas at the inlet [K]\n MW : float\n Molecular weight of the gas [g/mol]\n mu : float\n Viscosity of the fluid at inlet conditions [Pa*s]\n gamma : float\n Specific heat capacity ratio [-]\n Z : float\n Compressibility factor at inlet conditions, [-]\n P1 : float\n Inlet pressure of the gas before valves and reducers [Pa]\n P2 : float\n Outlet pressure of the gas after valves and reducers [Pa]\n Q : float\n Volumetric flow rate of the gas at *273.15 K* and 1 atm specifically\n [m^3/s]\n D1 : float, optional\n Diameter of the pipe before the valve [m]\n D2 : float, optional\n Diameter of the pipe after the valve [m]\n d : float, optional\n Diameter of the valve [m]\n FL : float, optional\n Liquid pressure recovery factor of a control valve without attached\n fittings (normally 0.8-0.9 at full open and decreasing as opened\n further to below 0.5; use default very cautiously!) []\n Fd : float, optional\n Valve style modifier (0.1 to 1; varies tremendously depending on the\n type of valve and position; do not use the default at all!) []\n xT : float, optional\n Pressure difference ratio factor of a valve without fittings at choked\n flow (increasing to 0.9 or higher as the valve is closed further and\n decreasing to 0.1 or lower as the valve is opened further; use default\n very cautiously!) [-]\n allow_choked : bool, optional\n Overrides the automatic transition into the choked regime if this is\n False and returns as if choked flow does not exist\n allow_laminar : bool, optional\n Overrides the automatic transition into the laminar regime if this is\n False and returns as if laminar flow does not exist\n full_output : bool, optional\n If True, returns intermediate calculation values as\n well as Kv in the form of a dictionary containing 'Kv', 'Rev', 'choked',\n 'Y', 'FR', 'FP', 'xTP', and 'laminar'. Some may be None if they are\n not used in the calculation.\n\n Returns\n -------\n Kv : float\n Metric Kv valve flow coefficient (flow rate of water at a pressure drop\n of 1 bar) [m^3/hr]\n\n Notes\n -----\n It is possible to use this model without any diameters specified; in that\n case, turbulent flow is assumed. Choked flow can still be modeled. This is\n not recommended. All three diameters need to be None for this to work.\n `FL` and `Fd` are not used by the models when the diameters are not\n specified, but `xT` definitely is used by the model.\n\n When this model does not converge, the result is normally because of the\n specified delta P being less than that caused by the piping diameter\n changes.\n\n Examples\n --------\n From [1]_, matching example 3 for non-choked gas flow with attached\n fittings and a rotary, eccentric plug, flow-to-open control valve:\n\n >>> size_control_valve_g(T=433., MW=44.01, mu=1.4665E-4, gamma=1.30,\n ... Z=0.988, P1=680E3, P2=310E3, Q=38/36., D1=0.08, D2=0.1, d=0.05,\n ... FL=0.85, Fd=0.42, xT=0.60)\n 72.5866454539105\n\n From [1]_, roughly matching example 4 for a small flow trim sized tapered\n needle plug valve. Difference is 3% and explained by the difference in\n algorithms used.\n\n >>> size_control_valve_g(T=320., MW=39.95, mu=5.625E-5, gamma=1.67, Z=1.0,\n ... P1=2.8E5, P2=1.3E5, Q=0.46/3600., D1=0.015, D2=0.015, d=0.015, FL=0.98,\n ... Fd=0.07, xT=0.8)\n 0.016498765335995726\n\n References\n ----------\n .. [1] IEC 60534-2-1 / ISA-75.01.01-2007\n \"\"\"\n MAX_C_POSSIBLE = 1E40 # Quit iterations if C reaches this high\n # Pa to kPa, according to constants in standard\n P1, P2 = P1*1e-3, P2*1e-3\n Q = Q*3600. # m^3/s to m^3/hr, according to constants in standard\n # Convert dynamic viscosity to kinematic viscosity\n Vm = Z*R*T/(P1*1000)\n rho = MW*1e-3/Vm\n nu = mu/rho # kinematic viscosity used in standard\n\n dP = P1 - P2\n Fgamma = gamma/1.40\n x = dP/P1\n Y = max(1 - x/(3*Fgamma*xT), 2/3.)\n\n choked = is_choked_turbulent_g(x, Fgamma, xT)\n if choked and allow_choked:\n # Choked, and flow coefficient from eq 14a\n C = Q/(N9*P1*Y)*sqrt(MW*T*Z/xT/Fgamma)\n else:\n # Non-choked, and flow coefficient from eq 8a\n C = Q/(N9*P1*Y)*sqrt(MW*T*Z/x)\n\n\n if full_output: # numba: delete\n ans = {\"FP\": None, \"xTP\": None, \"FR\": None, \"choked\": choked, \"Y\": Y} # numba: delete\n\n if D1 is None and D2 is None and d is None:\n # Assume turbulent if no diameters are provided, no other calculations\n Rev = 1e5\n if full_output: # numba: delete\n ans[\"Rev\"] = None # numba: delete\n else:\n # m to mm, according to constants in standard\n if D1 is None or D2 is None or d is None:\n raise ValueError(\"If any diameter is specified, all three (D1, D2, d) must be specified\")\n D1, D2, d = D1*1000., D2*1000., d*1000. # Convert diameters to mm which is used in the standard\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=C)\n if full_output: # numba: delete\n ans[\"Rev\"] = Rev # numba: delete\n\n if (Rev > 10000 or not allow_laminar) and (D1 != d or D2 != d):\n # gas, using xTP and FLP\n FP = 1.\n MAX_ITER = 20\n\n def iterate_piping_coef_g(Ci, iterations):\n loss = loss_coefficient_piping(d, D1, D2)\n FP = 1.0/sqrt(1. + loss/N2*(Ci/d**2)**2)\n loss_upstream = loss_coefficient_piping(d, D1)\n xTP = xT/FP**2/(1 + xT*loss_upstream/N5*(Ci/d**2)**2)\n choked = is_choked_turbulent_g(x, Fgamma, xTP=xTP)\n if choked:\n # Choked flow with piping, equation 17a\n C = Q/(N9*FP*P1*Y)*sqrt(MW*T*Z/xTP/Fgamma)\n else:\n # Non-choked flow with piping, equation 11a\n C = Q/(N9*FP*P1*Y)*sqrt(MW*T*Z/x)\n if Ci/C < 0.99 and iterations < MAX_ITER and Ci < MAX_C_POSSIBLE:\n C = iterate_piping_coef_g(C, iterations+1)\n if full_output: # numba: delete\n ans[\"xTP\"] = xTP # numba: delete\n ans[\"FP\"] = FP # numba: delete\n ans[\"choked\"] = choked # numba: delete\n if MAX_ITER == iterations or Ci >= MAX_C_POSSIBLE: # numba: delete\n ans[\"warning\"] = \"Not converged in inner loop\" # numba: delete\n return C\n\n# def err_piping_coeff(Ci):\n# loss = loss_coefficient_piping(d, D1, D2)\n# FP = (1. + loss/N2*(Ci/d**2)**2)**-0.5\n# loss_upstream = loss_coefficient_piping(d, D1)\n# xTP = xT/FP**2/(1 + xT*loss_upstream/N5*(Ci/d**2)**2)\n# choked = is_choked_turbulent_g(x, Fgamma, xTP=xTP)\n# if choked:\n# # Choked flow with piping, equation 17a\n# C = Q/(N9*FP*P1*Y)*(MW*T*Z/xTP/Fgamma)**0.5\n# else:\n# # Non-choked flow with piping, equation 11a\n# C = Q/(N9*FP*P1*Y)*(MW*T*Z/x)**0.5\n# return C - Ci\n# import matplotlib.pyplot as plt\n# from fluids.numerics import linspace\n# Cs = linspace(C/50, C*50, 5000)\n# errs = [err_piping_coeff(C_test) for C_test in Cs]\n# plt.plot(Cs, errs)\n# plt.show()\n\n C = iterate_piping_coef_g(C, 0)\n elif Rev <= 10000 and allow_laminar:\n # Laminar;\n def iterate_piping_laminar_g(C):\n Ci = 1.3*C\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=Ci)\n if Ci/(d*d) > 0.016*N18:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=False)\n else:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=True)\n if C/FR >= Ci:\n Ci = iterate_piping_laminar_g(Ci)\n if full_output: # numba: delete\n ans[\"FR\"] = FR # numba: delete\n ans[\"Rev\"] = Rev # numba: delete\n return Ci\n C = iterate_piping_laminar_g(C)\n if full_output: # numba: delete\n ans[\"Kv\"] = C # numba: delete\n ans[\"laminar\"] = Rev <= 10000 # numba: delete\n ans[\"choked\"] = choked # numba: delete\n return ans # numba: delete\n return C\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 17543}, "tests/test_design_climate.py::71": {"resolved_imports": ["fluids/design_climate.py", "fluids/numerics/__init__.py"], "used_names": ["StationDataGSOD", "assert_close1d", "get_closest_station", "pytest"], "enclosing_function": "test_month_average_temperature", "extracted_code": "# Source: fluids/design_climate.py\nclass StationDataGSOD:\n # Holds data, caches and retrieves data\n def __init__(self, station, data_dir_override=None):\n self.data_dir_override = data_dir_override\n self.station = station\n\n self.begin = datetime.datetime.strptime(str(self.station.BEGIN), \"%Y%m%d\")\n self.end = datetime.datetime.strptime(str(self.station.END), \"%Y%m%d\")\n\n self.year_range = range(self.begin.year, self.end.year + 1)\n\n# Would be nice to create these later, when using a download_data method\n self.raw_text = {}\n self.raw_data = {}\n self.parsed_data = {}\n self.load_empty_vectors()\n self.download_data()\n self.parse_data()\n\n def load_empty_vectors(self):\n for year in self.year_range:\n days_in_year = 366 if isleap(year) else 365\n self.raw_data[year] = [None]*days_in_year\n self.parsed_data[year] = [None]*days_in_year\n self.raw_text[year] = None\n# days = [None]*days_in_year(y)\n\n def download_data(self):\n for year in self.year_range:\n if self.raw_text[year] is None:\n try:\n year_data = get_station_year_text(self.station.USAF, self.station.WBAN, year, data_dir_override=self.data_dir_override)\n self.raw_text[year] = year_data\n except:\n pass\n\n def parse_data(self):\n for year, data in self.raw_text.items():\n if data is not None:\n days = self.parsed_data[year]\n for line in data.split(\"\\n\")[1:-1]:\n parsed = gsod_day_parser(line)\n doy = parsed.DATE.timetuple().tm_yday-1\n days[doy] = parsed\n\n def coldest_month(self, older_year=None, newer_year=None, minimum_days=23):\n # Tested\n month_data = self.month_average_temperature(older_year=older_year,\n newer_year=newer_year,\n minimum_days=minimum_days)\n return month_data.index(min(month_data))\n\n def warmest_month(self, older_year=None, newer_year=None, minimum_days=23):\n # Tested\n month_data = self.month_average_temperature(older_year=older_year,\n newer_year=newer_year,\n minimum_days=minimum_days)\n return month_data.index(max(month_data))\n\n def month_average_temperature(self, older_year=None, newer_year=None,\n include_yearly=False, minimum_days=23):\n \"\"\"\n >> station = get_closest_station(38.8572, -77.0369)\n >> station_data = StationDataGSOD(station)\n >> station_data.month_average_temperature(1990, 2000, include_yearly=False)\n [276.1599380905833, 277.5375516246206, 281.1881231671554, 286.7367003367004, 291.8689638318671, 296.79545454545456, 299.51868686868687, 298.2097914630174, 294.4116161616162, 288.25883023786247, 282.3188552188553, 277.8282339524275]\n \"\"\"\n # Take years, make them inclusive; add minimum valid days.\n year_month_averages = {}\n year_month_counts = {}\n\n for year, data in self.parsed_data.items():\n if not (older_year <= year <= newer_year):\n continue # Ignore out-of-range years easily\n year_month_averages[year] = [0.0]*12\n year_month_counts[year] = [0]*12\n\n for i, day in enumerate(data):\n if day is None:\n continue\n # Don't do these comparisons to make it fast\n if day.DATE.year < older_year or day.DATE.year > newer_year:\n continue # Ignore out-of-range days as possible\n\n T = day.TEMP\n if T is None:\n continue\n # Cache these lookups\n year_month_averages[year][day.DATE.month-1] += T\n year_month_counts[year][day.DATE.month-1] += 1\n\n for month in range(12):\n count = year_month_counts[year][month]\n if count < minimum_days:\n ans = None\n else:\n ans = year_month_averages[year][month]/count\n year_month_averages[year][month] = ans\n\n # Compute the average of the month\n actual_averages = [0.0]*12\n actual_averages_counts = [0]*12\n for year, average in year_month_averages.items():\n for month in range(12):\n if average is not None and average[month] is not None:\n count = actual_averages_counts[month]\n if count is None:\n count = 1\n else:\n count += 1\n actual_averages_counts[month] = count\n month_average_sum = actual_averages[month]\n if month_average_sum is None:\n month_average_sum = average[month]\n else:\n month_average_sum += average[month]\n actual_averages[month] = month_average_sum\n\n for month in range(12):\n actual_averages[month] = actual_averages[month]/actual_averages_counts[month]\n\n # Don't set anything as properties - too many variables used in calculating thems\n # Speed is not that important.\n if include_yearly:\n return actual_averages, year_month_averages\n else:\n return actual_averages\n\n # Copy and paste\n def month_average_windspeed(self, older_year=None, newer_year=None,\n include_yearly=False, minimum_days=23):\n # Take years, make them inclusive; add minimum valid days.\n year_month_averages = {}\n year_month_counts = {}\n\n for year, data in self.parsed_data.items():\n if not (older_year <= year <= newer_year):\n continue # Ignore out-of-range years easily\n year_month_averages[year] = [0.0]*12\n year_month_counts[year] = [0]*12\n\n for i, day in enumerate(data):\n if day is None:\n continue\n # Don't do these comparisons to make it fast\n if day.DATE.year < older_year or day.DATE.year > newer_year:\n continue # Ignore out-of-range days as possible\n\n wind_speed = day.WDSP\n if wind_speed is None:\n continue\n # Cache these lookups\n year_month_averages[year][day.DATE.month-1] += wind_speed\n year_month_counts[year][day.DATE.month-1] += 1\n\n for month in range(12):\n count = year_month_counts[year][month]\n if count < minimum_days:\n ans = None\n else:\n ans = year_month_averages[year][month]/count\n year_month_averages[year][month] = ans\n\n # Compute the average of the month\n actual_averages = [0.0]*12\n actual_averages_counts = [0]*12\n for year, average in year_month_averages.items():\n for month in range(12):\n if average is not None and average[month] is not None:\n count = actual_averages_counts[month]\n if count is None:\n count = 1\n else:\n count += 1\n actual_averages_counts[month] = count\n month_average_sum = actual_averages[month]\n if month_average_sum is None:\n month_average_sum = average[month]\n else:\n month_average_sum += average[month]\n actual_averages[month] = month_average_sum\n\n for month in range(12):\n actual_averages[month] = actual_averages[month]/actual_averages_counts[month]\n\n # Don't set anything as properties - too many variables used in calculating thems\n # Speed is not that important.\n if include_yearly:\n return actual_averages, year_month_averages\n else:\n return actual_averages\n\n def percentile_extreme_condition(self, older_year=None, newer_year=None,\n include_yearly=False, minimum_days=23, attr=\"WDSP\"):\n # Really need to normalize data with interpolation etc here.\n # Need to get the data, and process it and score interpolation regimes.\n # Or could just randomly drop data and try to fill it in.\n accepted_values = []\n for year in self.parsed_data.keys():\n if not (older_year <= year <= newer_year):\n continue\n\ndef get_closest_station(latitude, longitude, minumum_recent_data=20140000,\n match_max=100):\n \"\"\"Query function to find the nearest weather station to a particular set of\n coordinates. Optionally allows for a recent date by which the station is\n required to be still active at.\n\n Parameters\n ----------\n latitude : float\n Latitude to search for nearby weather stations at, [degrees]\n longitude : float\n Longitude to search for nearby weather stations at, [degrees]\n minumum_recent_data : int, optional\n Date that the weather station is required to have more recent\n weather data than; format YYYYMMDD; set this to 0 to not restrict data\n by date.\n match_max : int, optional\n The maximum number of results in the KDTree to search for before\n applying the filtering criteria; an internal parameter which is\n increased automatically if the default value is insufficient [-]\n\n Returns\n -------\n station : IntegratedSurfaceDatabaseStation\n Instance of IntegratedSurfaceDatabaseStation which was nearest\n to the requested coordinates and with sufficiently recent data\n available [-]\n\n Notes\n -----\n Searching for 100 stations is a reasonable choice as it takes, ~70\n microseconds vs 50 microsecond to find only 1 station. The search does get\n slower as more points are requested. Bad data is returned from a KDTree\n search if more points are requested than are available.\n\n Examples\n --------\n >>> get_closest_station(51.02532675, -114.049868485806, 20150000)\n \n \"\"\"\n # Both station strings may be important\n # Searching for 100 stations is fine, 70 microseconds vs 50 microsecond for 1\n # but there's little point for more points, it gets slower.\n # bad data is returned if k > station_count\n station_count = get_station_count()\n stations = get_stations()\n distances, indexes = get_kd_tree().query([latitude, longitude], k=min(match_max, station_count))\n for i in indexes:\n latlon = _latlongs[i]\n enddate = stations[i].END\n # Iterate for all indexes until one is found whose date is current\n if enddate > minumum_recent_data:\n return stations[i]\n if match_max < station_count:\n return get_closest_station(latitude, longitude, minumum_recent_data=minumum_recent_data, match_max=match_max*10)\n raise ValueError(\"Could not find a station with more recent data than \"\n \"specified near the specified coordinates.\")\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 11893}, "tests/test_design_climate.py::72": {"resolved_imports": ["fluids/design_climate.py", "fluids/numerics/__init__.py"], "used_names": ["StationDataGSOD", "assert_close1d", "get_closest_station", "pytest"], "enclosing_function": "test_month_average_temperature", "extracted_code": "# Source: fluids/design_climate.py\nclass StationDataGSOD:\n # Holds data, caches and retrieves data\n def __init__(self, station, data_dir_override=None):\n self.data_dir_override = data_dir_override\n self.station = station\n\n self.begin = datetime.datetime.strptime(str(self.station.BEGIN), \"%Y%m%d\")\n self.end = datetime.datetime.strptime(str(self.station.END), \"%Y%m%d\")\n\n self.year_range = range(self.begin.year, self.end.year + 1)\n\n# Would be nice to create these later, when using a download_data method\n self.raw_text = {}\n self.raw_data = {}\n self.parsed_data = {}\n self.load_empty_vectors()\n self.download_data()\n self.parse_data()\n\n def load_empty_vectors(self):\n for year in self.year_range:\n days_in_year = 366 if isleap(year) else 365\n self.raw_data[year] = [None]*days_in_year\n self.parsed_data[year] = [None]*days_in_year\n self.raw_text[year] = None\n# days = [None]*days_in_year(y)\n\n def download_data(self):\n for year in self.year_range:\n if self.raw_text[year] is None:\n try:\n year_data = get_station_year_text(self.station.USAF, self.station.WBAN, year, data_dir_override=self.data_dir_override)\n self.raw_text[year] = year_data\n except:\n pass\n\n def parse_data(self):\n for year, data in self.raw_text.items():\n if data is not None:\n days = self.parsed_data[year]\n for line in data.split(\"\\n\")[1:-1]:\n parsed = gsod_day_parser(line)\n doy = parsed.DATE.timetuple().tm_yday-1\n days[doy] = parsed\n\n def coldest_month(self, older_year=None, newer_year=None, minimum_days=23):\n # Tested\n month_data = self.month_average_temperature(older_year=older_year,\n newer_year=newer_year,\n minimum_days=minimum_days)\n return month_data.index(min(month_data))\n\n def warmest_month(self, older_year=None, newer_year=None, minimum_days=23):\n # Tested\n month_data = self.month_average_temperature(older_year=older_year,\n newer_year=newer_year,\n minimum_days=minimum_days)\n return month_data.index(max(month_data))\n\n def month_average_temperature(self, older_year=None, newer_year=None,\n include_yearly=False, minimum_days=23):\n \"\"\"\n >> station = get_closest_station(38.8572, -77.0369)\n >> station_data = StationDataGSOD(station)\n >> station_data.month_average_temperature(1990, 2000, include_yearly=False)\n [276.1599380905833, 277.5375516246206, 281.1881231671554, 286.7367003367004, 291.8689638318671, 296.79545454545456, 299.51868686868687, 298.2097914630174, 294.4116161616162, 288.25883023786247, 282.3188552188553, 277.8282339524275]\n \"\"\"\n # Take years, make them inclusive; add minimum valid days.\n year_month_averages = {}\n year_month_counts = {}\n\n for year, data in self.parsed_data.items():\n if not (older_year <= year <= newer_year):\n continue # Ignore out-of-range years easily\n year_month_averages[year] = [0.0]*12\n year_month_counts[year] = [0]*12\n\n for i, day in enumerate(data):\n if day is None:\n continue\n # Don't do these comparisons to make it fast\n if day.DATE.year < older_year or day.DATE.year > newer_year:\n continue # Ignore out-of-range days as possible\n\n T = day.TEMP\n if T is None:\n continue\n # Cache these lookups\n year_month_averages[year][day.DATE.month-1] += T\n year_month_counts[year][day.DATE.month-1] += 1\n\n for month in range(12):\n count = year_month_counts[year][month]\n if count < minimum_days:\n ans = None\n else:\n ans = year_month_averages[year][month]/count\n year_month_averages[year][month] = ans\n\n # Compute the average of the month\n actual_averages = [0.0]*12\n actual_averages_counts = [0]*12\n for year, average in year_month_averages.items():\n for month in range(12):\n if average is not None and average[month] is not None:\n count = actual_averages_counts[month]\n if count is None:\n count = 1\n else:\n count += 1\n actual_averages_counts[month] = count\n month_average_sum = actual_averages[month]\n if month_average_sum is None:\n month_average_sum = average[month]\n else:\n month_average_sum += average[month]\n actual_averages[month] = month_average_sum\n\n for month in range(12):\n actual_averages[month] = actual_averages[month]/actual_averages_counts[month]\n\n # Don't set anything as properties - too many variables used in calculating thems\n # Speed is not that important.\n if include_yearly:\n return actual_averages, year_month_averages\n else:\n return actual_averages\n\n # Copy and paste\n def month_average_windspeed(self, older_year=None, newer_year=None,\n include_yearly=False, minimum_days=23):\n # Take years, make them inclusive; add minimum valid days.\n year_month_averages = {}\n year_month_counts = {}\n\n for year, data in self.parsed_data.items():\n if not (older_year <= year <= newer_year):\n continue # Ignore out-of-range years easily\n year_month_averages[year] = [0.0]*12\n year_month_counts[year] = [0]*12\n\n for i, day in enumerate(data):\n if day is None:\n continue\n # Don't do these comparisons to make it fast\n if day.DATE.year < older_year or day.DATE.year > newer_year:\n continue # Ignore out-of-range days as possible\n\n wind_speed = day.WDSP\n if wind_speed is None:\n continue\n # Cache these lookups\n year_month_averages[year][day.DATE.month-1] += wind_speed\n year_month_counts[year][day.DATE.month-1] += 1\n\n for month in range(12):\n count = year_month_counts[year][month]\n if count < minimum_days:\n ans = None\n else:\n ans = year_month_averages[year][month]/count\n year_month_averages[year][month] = ans\n\n # Compute the average of the month\n actual_averages = [0.0]*12\n actual_averages_counts = [0]*12\n for year, average in year_month_averages.items():\n for month in range(12):\n if average is not None and average[month] is not None:\n count = actual_averages_counts[month]\n if count is None:\n count = 1\n else:\n count += 1\n actual_averages_counts[month] = count\n month_average_sum = actual_averages[month]\n if month_average_sum is None:\n month_average_sum = average[month]\n else:\n month_average_sum += average[month]\n actual_averages[month] = month_average_sum\n\n for month in range(12):\n actual_averages[month] = actual_averages[month]/actual_averages_counts[month]\n\n # Don't set anything as properties - too many variables used in calculating thems\n # Speed is not that important.\n if include_yearly:\n return actual_averages, year_month_averages\n else:\n return actual_averages\n\n def percentile_extreme_condition(self, older_year=None, newer_year=None,\n include_yearly=False, minimum_days=23, attr=\"WDSP\"):\n # Really need to normalize data with interpolation etc here.\n # Need to get the data, and process it and score interpolation regimes.\n # Or could just randomly drop data and try to fill it in.\n accepted_values = []\n for year in self.parsed_data.keys():\n if not (older_year <= year <= newer_year):\n continue\n\ndef get_closest_station(latitude, longitude, minumum_recent_data=20140000,\n match_max=100):\n \"\"\"Query function to find the nearest weather station to a particular set of\n coordinates. Optionally allows for a recent date by which the station is\n required to be still active at.\n\n Parameters\n ----------\n latitude : float\n Latitude to search for nearby weather stations at, [degrees]\n longitude : float\n Longitude to search for nearby weather stations at, [degrees]\n minumum_recent_data : int, optional\n Date that the weather station is required to have more recent\n weather data than; format YYYYMMDD; set this to 0 to not restrict data\n by date.\n match_max : int, optional\n The maximum number of results in the KDTree to search for before\n applying the filtering criteria; an internal parameter which is\n increased automatically if the default value is insufficient [-]\n\n Returns\n -------\n station : IntegratedSurfaceDatabaseStation\n Instance of IntegratedSurfaceDatabaseStation which was nearest\n to the requested coordinates and with sufficiently recent data\n available [-]\n\n Notes\n -----\n Searching for 100 stations is a reasonable choice as it takes, ~70\n microseconds vs 50 microsecond to find only 1 station. The search does get\n slower as more points are requested. Bad data is returned from a KDTree\n search if more points are requested than are available.\n\n Examples\n --------\n >>> get_closest_station(51.02532675, -114.049868485806, 20150000)\n \n \"\"\"\n # Both station strings may be important\n # Searching for 100 stations is fine, 70 microseconds vs 50 microsecond for 1\n # but there's little point for more points, it gets slower.\n # bad data is returned if k > station_count\n station_count = get_station_count()\n stations = get_stations()\n distances, indexes = get_kd_tree().query([latitude, longitude], k=min(match_max, station_count))\n for i in indexes:\n latlon = _latlongs[i]\n enddate = stations[i].END\n # Iterate for all indexes until one is found whose date is current\n if enddate > minumum_recent_data:\n return stations[i]\n if match_max < station_count:\n return get_closest_station(latitude, longitude, minumum_recent_data=minumum_recent_data, match_max=match_max*10)\n raise ValueError(\"Could not find a station with more recent data than \"\n \"specified near the specified coordinates.\")\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 11893}, "tests/test_fittings.py::388": {"resolved_imports": ["fluids/fittings.py", "fluids/constants/__init__.py", "fluids/core.py", "fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["bend_rounded_Miller", "isinf", "isnan", "pytest"], "enclosing_function": "test_bend_rounded_Miller_fuzz", "extracted_code": "# Source: fluids/fittings.py\ndef bend_rounded_Miller(Di: float, angle: float, Re: float, rc: float | None=None, bend_diameters: float | None=None,\n roughness: float=0.0, L_unimpeded: float | None=None) -> float:\n r\"\"\"Calculates the loss coefficient for a rounded pipe bend according to\n Miller [1]_. This is a sophisticated model which uses corrections for\n pipe roughness, the length of the pipe downstream before another\n interruption, and a correction for Reynolds number. It interpolates several\n times using several corrections graphs in [1]_.\n\n Parameters\n ----------\n Di : float\n Inside diameter of pipe, [m]\n angle : float\n Angle of bend, [degrees]\n Re : float\n Reynolds number of the pipe (no specification if inlet or outlet\n properties should be used), [m]\n rc : float, optional\n Radius of curvature of the entrance, [m]\n bend_diameters : float, optional\n Number of diameters of pipe making up the bend radius (used if rc not\n provided; defaults to 5), [-]\n roughness : float, optional\n Roughness of bend wall, [m]\n L_unimpeded : float, optional\n The length of unimpeded pipe without any fittings, instrumentation,\n or flow disturbances downstream (assumed 20 diameters if not\n specified), [m]\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n When inputting bend diameters, note that manufacturers often specify\n this as a multiplier of nominal diameter, which is different than actual\n diameter. Those require that rc be specified.\n\n `rc` is limited to 0.5 or above; which represents a sharp, square, inner\n edge - and an outer bend radius of 1.0. Losses are at a minimum when this\n value is large.\n\n This was developed for bend angles between 10 and 180 degrees; and r/D\n ratios between 0.5 and 10. Both smooth and rough data was used in its\n development from several sources.\n\n Note the loss coefficient includes the surface friction of the pipe as if\n it was straight.\n\n Examples\n --------\n >>> bend_rounded_Miller(Di=.6, bend_diameters=2, angle=90, Re=2e6,\n ... roughness=2E-5, L_unimpeded=30*.6)\n 0.15261820705145895\n\n References\n ----------\n .. [1] Miller, Donald S. Internal Flow Systems: Design and Performance\n Prediction. Gulf Publishing Company, 1990.\n \"\"\"\n if rc is None:\n if bend_diameters is None:\n bend_diameters = 5.0\n rc = Di*bend_diameters\n\n radius_ratio = rc/Di\n\n if L_unimpeded is None:\n # Assumption - smooth outlet\n L_unimpeded = 20.0*Di\n\n # Graph is defined for angles 10 to 180 degrees, ratios 0.5 to 10\n if radius_ratio < 0.5:\n radius_ratio = 0.5\n if radius_ratio > 10.0:\n radius_ratio = 10.0\n if angle < 10.0:\n angle = 10.0\n\n # Curve fit in terms of degrees\n # Caching could work here - angle, radius ratio does not change often\n Kb = bend_rounded_Miller_Kb(radius_ratio, angle)\n\n C_roughness = Miller_bend_roughness_correction(Re=Re, Di=Di,\n roughness=roughness)\n \"\"\"Section 9.2.2 - Reynolds Number Correction\n Allow some extrapolation up to 1E8 (1E7 max in graph but the trend looks good)\n \"\"\"\n Re_C_Re = min(max(Re, 1E4), 1E8)\n if radius_ratio >= 2.0:\n if Re_C_Re == 1E8:\n C_Re = 0.4196741237602154 # bend_rounded_Miller_C_Re(1e8, 2.0)\n elif Re_C_Re == 1E4:\n C_Re = 2.1775876405173977 # bend_rounded_Miller_C_Re(1e4, 2.0)\n else:\n C_Re = bend_rounded_Miller_C_Re(Re_C_Re, 2.0)\n elif radius_ratio <= 1.0:\n # newton(lambda x: bend_rounded_Miller_C_Re(x, 1.0)-1, 2e5) to get the boundary value\n C_Re_1 = bend_rounded_Miller_C_Re(Re_C_Re, 1.0) if Re_C_Re < 207956.58904584477 else 1.0\n if radius_ratio > 0.7 or Kb < 0.4:\n C_Re = C_Re_1\n else:\n C_Re = Kb/(Kb - 0.2*C_Re_1 + 0.2)\n if C_Re > 2.2 or C_Re < 0:\n C_Re = 2.2\n else:\n # regardless of ratio - 1\n if Re_C_Re > 1048884.4656835075:\n C_Re = 1.0\n elif Re_C_Re > horner(bend_rounded_Miller_C_Re_limit_1, radius_ratio):\n C_Re = 1.0\n# ps = np.linspace(1, 2)\n# qs = [secant(lambda x: bend_rounded_Miller_C_Re(x, i)-1, 2e5) for i in ps]\n# np.polyfit(ps, qs, 4).tolist()\n # Line of C_Re=1 as a function of r_d between 0 and 1\n else:\n C_Re = bend_rounded_Miller_C_Re(Re_C_Re, radius_ratio)\n C_o = Miller_bend_unimpeded_correction(Kb=Kb, Di=Di, L_unimpeded=L_unimpeded)\n\n# print('Kb=%g, C Re=%g, C rough =%g, Co=%g' %(Kb, C_Re, C_roughness, C_o))\n return Kb*C_Re*C_roughness*C_o", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 4818}, "tests/test_geometry.py::553": {"resolved_imports": ["fluids/__init__.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": ["TANK"], "enclosing_function": "test_TANK_hash_behavior", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_geometry.py::992": {"resolved_imports": ["fluids/__init__.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": ["SA_from_h", "SA_partial_vertical_torispherical_head", "TANK", "assert_close", "foot", "inch"], "enclosing_function": "test_SA_partial_vertical_torispherical_head", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 607}, "tests/test_jet_pump.py::174": {"resolved_imports": ["fluids/__init__.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "liquid_jet_pump"], "enclosing_function": "validate_liquid_jet_pump", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 607}, "tests/test_numba.py::659": {"resolved_imports": ["fluids/__init__.py", "fluids/vectorized.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": ["assert_allclose", "fluids"], "enclosing_function": "tets_newton_system", "extracted_code": "# Source: fluids/__init__.py\n def __getattr__(name):\n if name == \"vectorized\":\n import fluids.vectorized\n globals()[name] = fluids.vectorized\n return fluids.vectorized\n if name == \"numba\":\n import fluids.numba\n globals()[name] = fluids.numba\n return fluids.numba\n if name == \"units\":\n import fluids.units\n globals()[name] = fluids.units\n\n if name == \"vectorized\":\n import fluids.vectorized\n globals()[name] = fluids.vectorized\n return fluids.vectorized\n if name == \"numba\":\n import fluids.numba\n globals()[name] = fluids.numba\n return fluids.numba\n if name == \"units\":\n import fluids.units\n globals()[name] = fluids.units\n return fluids.units\n\n import fluids.vectorized\n globals()[name] = fluids.vectorized\n return fluids.vectorized\n if name == \"numba\":\n import fluids.numba\n globals()[name] = fluids.numba\n return fluids.numba\n if name == \"units\":\n import fluids.units\n globals()[name] = fluids.units\n return fluids.units\n if name == \"numba_vectorized\":\n\n return fluids.vectorized\n if name == \"numba\":\n import fluids.numba\n globals()[name] = fluids.numba\n return fluids.numba\n if name == \"units\":\n import fluids.units\n globals()[name] = fluids.units\n return fluids.units\n if name == \"numba_vectorized\":\n import fluids.numba_vectorized\n globals()[name] = fluids.numba_vectorized\n\n if name == \"numba\":\n import fluids.numba\n globals()[name] = fluids.numba\n return fluids.numba\n if name == \"units\":\n import fluids.units\n globals()[name] = fluids.units\n return fluids.units\n if name == \"numba_vectorized\":\n import fluids.numba_vectorized\n globals()[name] = fluids.numba_vectorized\n return fluids.numba_vectorized", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 2200}, "tests/test_numerics.py::1824": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["UnconvergedError", "pytest", "secant"], "enclosing_function": "test_secant_cases_nan_inf", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef secant(func, x0, args=(), maxiter=100, low=None, high=None, damping=1.0,\n xtol=1.48e-8, ytol=None, x1=None, require_eval=False,\n f0=None, f1=None, bisection=False, same_tol=1.0, kwargs={},\n require_xtol=True, additional_guesses=False, additional_guess_scale=1.0):\n p0 = 1.0*x0\n # Logic to take a small step to calculate the approximate derivative\n if x1 is not None:\n p1 = x1\n else:\n if x0 >= 0.0:\n p1 = x0*1.0001 + 1e-4\n else:\n p1 = x0*1.0001 - 1e-4\n # May need to truncate p1\n if low is not None and p1 < low:\n p1 = low\n if high is not None and p1 > high:\n p1 = high\n\n # Are we already converged on either point? Do not consider checking xtol\n # if so.\n if f0 is None:\n q0 = func(p0, *args, **kwargs)\n else:\n q0 = f0\n if isnan(q0) or isinf(q0):\n raise UnconvergedError(\"Bad function evaluation on first starting point\", iterations=0, point=p0, err=q0)\n if (ytol is not None and abs(q0) < ytol and not require_xtol) or q0 == 0.0:\n return p0\n\n if f1 is None:\n q1 = func(p1, *args, **kwargs)\n else:\n q1 = f1\n if isnan(q1) or isinf(q1):\n raise UnconvergedError(\"Bad function evaluation on second starting point\", iterations=0, point=p1, err=q1)\n\n if q1 == q0 and additional_guesses:\n # we cannot proceed when the guessed point has the same value; need to increase the search space\n # try to guess again with a larger change, up to 16 orders of magnitude larger\n for guess_factor in secant_bisection_factors:\n # print('Slope was zero with initial guess, expanding search...')\n p1 = x0*guess_factor if x0 != 0.0 else guess_factor\n if low is not None and p1 < low:\n p1 = low\n if high is not None and p1 > high:\n p1 = high\n q1 = func(p1, *args, **kwargs)\n # For the check, we will require a significant difference in result magnitude\n if not (isnan(q1) or isinf(q1)) and abs(q1/q0-1.0) > 1e-10:\n break\n\n did_additional_guesses = False\n\n if (ytol is not None and abs(q1) < ytol and not require_xtol) or q1 == 0.0:\n return p1\n if bisection:\n a, b = None, None\n if q1 < 0.0:\n a = p1\n else:\n b = p1\n if q0 < 0.0:\n a = p0\n else:\n b = p0\n\n for i in range(maxiter):\n # Calculate new point, and truncate if necessary\n\n if q1 != q0:\n p = p1 - q1*(p1 - p0)/(q1 - q0)*damping\n else:\n p = p1\n\n if low is not None and p < low:\n p = low\n if high is not None and p > high:\n p = high\n\n # After computing new point\n if bisection and a is not None and b is not None:\n if not (a < p < b) or (b < p < a):\n # print('Bisecting')\n p = 0.5*(a + b)\n # Check the exit conditions\n if ytol is not None and xtol is not None:\n # Meet both tolerance - new value is under ytol, and old value\n if abs(q1) < ytol and (not require_xtol or abs(p0 - p1) <= abs(xtol*p0)):\n# if abs(p0 - p1) <= abs(xtol*p0) and abs(q1) < ytol:\n if require_eval:\n return p1\n return p\n elif xtol is not None:\n if abs(p0 - p1) <= abs(xtol*p0) and not (p0 == p1 and (p0 == low or p0 == high)):\n if require_eval:\n return p1\n return p\n elif ytol is not None:\n if abs(q1) < ytol:\n if require_eval:\n return p1\n return p\n\n # Check to quit after convergence check - may meet criteria\n if q1 == q0:\n # Are we close enough? Run the checks again\n if xtol is not None:\n xtol *= same_tol\n if ytol is not None:\n ytol *= same_tol\n\n if ytol is not None and xtol is not None:\n # Meet both tolerance - new value is under ytol, and old value\n if abs(p0 - p1) <= abs(xtol * p0) and abs(q1) < ytol:\n return p\n elif xtol is not None:\n if abs(p0 - p1) <= abs(xtol * p0) and not (p0 == p1 and (p0 == low or p0 == high)):\n return p\n elif ytol is not None:\n if abs(q1) < ytol:\n return p\n if bisection and a is not None and b is not None:\n p = 0.5*(a + b)\n else:\n # Search increasingly away from the initial guess for something with a different sign\n if additional_guesses and not did_additional_guesses:\n # print('Converged to points with a slope of zero, attempting to bisect the problem...')\n for guess_factor in secant_bisection_factors:\n p = x0*guess_factor*additional_guess_scale\n if (low is not None and p < low) or (high is not None and p > high):\n continue\n temp_q = func(p, *args, **kwargs)\n # print(f'Did not bisect the problem at x={p}')\n if not (isnan(q1) or isinf(q1)) and temp_q*q0 < 0.0:\n # print('Bisected the problem, restarting with new point')\n break\n\n did_additional_guesses = True\n else:\n # Cannot proceed, raise an error\n raise SamePointError(\"Convergence failed - previous points are the same\", q1=q1, p1=p1, q0=q0, p0=p0)\n\n\n # Swap the points around\n p0 = p1\n q0 = q1\n p1 = p\n q1 = func(p1, *args, **kwargs)\n if (isnan(q1) or isinf(q1)):\n raise UnconvergedError(\"Bad function evaluation\", iterations=i, point=p1, err=q1)\n if q1 == 0.0:\n return p1\n if bisection:\n if q1 < 0.0:\n a = p1\n else:\n b = p1\n # print(f\"f({p1}) = {q1}, high={a}, low={b}\")\n\n raise UnconvergedError(\"Failed to converge\", iterations=i, point=p, err=q1)", "n_imports_parsed": 6, "n_files_resolved": 1, "n_chars_extracted": 6352}, "tests/test_numerics.py::1920": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["assert_close1d", "exp", "jacobian", "newton_system"], "enclosing_function": "test_basic_newton_system", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef jacobian(f, x0, scalar=True, perturbation=1e-9, zero_offset=1e-7, args=(), base=None,\n **kwargs):\n \"\"\"def test_fun(x):\n\n # test case - 2 inputs, 3 outputs - should work fine\n x2 = x[0]*x[0]\n return np.array([x2*exp(x[1]), x2*sin(x[1]), x2*cos(x[1])])\n\n def easy_fun(x):\n x = x[0]\n return 5*x*x - 3*x - 100\n \"\"\"\n # For scalar - returns list, size of input variables\n # For vector - returns list of list - size of input variables * output variables\n # Could add backwards/complex, multiple evaluations, detection of poor condition\n # types and limits\n if base is None:\n base = f(x0, *args, **kwargs)\n if not scalar:\n base = list(base) # copy the base point\n x = list(x0)\n nx = len(x0)\n\n gradient = []\n for i in range(nx):\n delta = x0[i]*(perturbation)\n if delta == 0:\n delta = zero_offset\n\n x[i] += delta\n\n point = f(x, *args, **kwargs)\n if scalar:\n dy = (point - base)/delta\n gradient.append(dy)\n else:\n delta_inv = 1.0/delta\n dys = [delta_inv*(p - b) for p, b in zip(point, base)]\n gradient.append(dys)\n\n x[i] -= delta\n if not scalar:\n # Transpose to be in standard form\n return list(map(list, zip(*gradient)))\n return gradient\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\ndef newton_system(f, x0, jac, xtol=None, ytol=None, maxiter=100, damping=1.0,\n args=(), damping_func=None, line_search=False,\n require_progress=False, check_numbers=False,\n Armijo=False, Armijo_c1=1e-4,\n solve_func=py_solve, with_point=False, jac_error_allowed=False): # numba: delete\n# solve_func=np.linalg.solve): # numba: uncomment\n jac_also = True if jac == True else False # noqa: E712, SIM210\n\n\n if jac_also:\n fcur, j = f(x0, *args)\n else: # numba: delete\n fcur = f(x0, *args) # numba: delete\n N = len(fcur)\n\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n\n if xtol is None and (ytol is not None and err0 < ytol):\n return x0, 0\n\n\n x = x0\n if not jac_also: # numba: delete\n j = jac(x, *args) # numba: delete\n if check_numbers:# numba: delete\n j = check_jacobian(x=x0, j=j, func=f, jac_error_allowed=jac_error_allowed)# numba: delete\n factors = newton_line_search_factors if line_search else newton_line_search_factors_disabled\n jac_updated = True # numba: delete\n iteration = 1\n while iteration < maxiter:\n try:# numba: delete\n dx = solve_func(j, [-v for v in fcur]) # numba: delete\n except Exception as e:# numba: delete\n if jac_error_allowed:# numba: delete\n j = jacobian(f, x, scalar=False) # numba: delete\n dx = solve_func(j, [-v for v in fcur]) # numba: delete\n else:# numba: delete\n raise e# numba: delete\n# dx = solve_func(j, -fcur) # numba: uncomment\n for factor in factors:\n # print(factor)\n mult = factor*damping\n if damping_func is None:\n# xnew = x + dx*mult # numba: uncomment\n xnew = [xi + dxi*mult for xi, dxi in zip(x, dx)] # numba: delete\n else:\n xnew = damping_func(x, dx, damping*factor, *args)\n try: # numba: delete\n if jac_also: # numba: delete\n fnew, jnew = f(xnew, *args) # numba: delete\n jac_updated = True # numba: delete\n else: # numba: delete\n fnew = f(xnew, *args) # numba: delete\n # print(xnew, 'xnew')\n # print(fnew, 'fnew')\n do_next = False # numba: delete\n if check_numbers: # numba: delete\n for v in fnew: # numba: delete\n if isinf(v) or isnan(v): # numba: delete\n do_next = True # numba: delete\n if do_next and factor != factors[-1]:# numba: delete\n # print('math error, trying next point')\n continue# numba: delete\n except: # numba: delete\n # print(f'Line search calculation with point failed') # numba: delete\n continue # numba: delete\n# fnew, jnew = f(xnew, *args) # numba: uncomment\n err_new = 0.0\n for v in fnew:\n err_new += abs(v)\n if check_numbers:\n for v in fnew:\n if isinf(v) or isnan(v):\n raise ValueError(\"Cannot continue - math error in function value\")\n # print(f'Line search with error={err_new}, factor {mult}' )\n if err_new < err0:\n if Armijo:\n phi = 0.0\n for v in fnew:\n phi += v*v\n Armijo_lhs = phi\n\n phi0 = 0.0\n for v in fcur:\n phi0 += v*v\n\n derphi0 = 0.0\n for i in range(N):\n temp = 0.0\n for jidx in range(N):\n temp += fcur[jidx]*j[jidx][i]\n # Armijo_grad[i] = 2.0*temp\n derphi0 += 4.0*temp*temp\n\n # derphi0 = float(np.dot(Armijo_grad, Armijo_grad))\n Armijo_rhs = Armijo_c1*factor*derphi0 + phi0\n if Armijo_lhs <= Armijo_rhs:\n if not jac_also: # numba: delete\n jac_updated = False # numba: delete\n break\n # else:\n # print('lhs and rhs not same', Armijo_lhs, Armijo_rhs)\n else:\n if not jac_also: # numba: delete\n jac_updated = False # numba: delete\n break\n\n if (line_search and err_new > err0) and require_progress:\n raise ValueError(\"Completed line search without reducing the objective function error, cannot proceed\")\n\n fcur = fnew\n if err_new >= err0:\n # edge case, didn't make any progress but keep going\n if require_progress:\n raise ValueError(\"Completed line search without reducing the objective function error, cannot proceed\")\n else:# numba: delete\n if not jac_also: # numba: delete\n jnew = jac(xnew, *args) # numba: delete\n jac_updated = True # numba: delete\n # print(xnew)\n err0 = err_new\n x = xnew\n iteration += 1\n\n if xtol is not None:\n if (norm2(fcur) < xtol) and (ytol is None or err0 < ytol):\n break\n elif ytol is not None:\n if err0 < ytol:\n break\n if not jac_updated: # numba: delete\n jnew = jac(x, *args) # numba: delete\n if check_numbers:# numba: delete\n jnew = check_jacobian(x=xnew, j=jnew, func=f, jac_error_allowed=jac_error_allowed) # numba: delete\n # print('jnew', jnew)\n j = jnew\n jac_updated = False\n\n # if not jac_also: # numba: delete\n # j = jac(x, *args) # numba: delete\n\n if xtol is not None and norm2(fcur) > xtol:\n raise UnconvergedError(\"Failed to converge\")\n# raise UnconvergedError(\"Failed to converge; maxiter (%d) reached, value=%s\" %(maxiter, x))\n if ytol is not None:\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if err0 > ytol:\n# raise UnconvergedError(\"Failed to converge; maxiter (%d) reached, value=%s\" %(maxiter, x))\n raise UnconvergedError(\"Failed to converge\")\n if with_point: # numba: delete\n return x, iteration, fcur, j # numba: delete\n\n return x, iteration\n\nclass SolverInterface:\n __slots__ = (\n \"damping\",\n \"fval_iter\",\n \"hess_fval_count\",\n \"hess_iter\",\n \"hessian_method\",\n \"hessian_numpy\",\n \"jac_fval_count\",\n \"jac_iter\",\n \"jacobian_method\",\n \"jacobian_numpy\",\n \"jacobian_order\",\n \"jacobian_perturbation\",\n \"jacobian_zero_offset\",\n \"matrix_solver\",\n \"maxiter\",\n \"method\",\n \"minimizing\",\n \"objf\",\n \"objf_numpy\",\n \"objf_original\",\n \"original_jac\",\n \"scalar_objective\",\n \"solver_analytical_jac\",\n \"solver_numpy\",\n \"xtol\",\n \"ytol\",\n )\n\n def objf_counting(self, *args):\n self.fval_iter += 1\n return self.objf_original(*args)\n\n def objf_python_return_numpy(self, x, *args):\n # function only knows python, solver knows numpy\n self.fval_iter += 1\n return np.array(self.objf_original(x if type(x) is list else x.tolist(),\n *args))\n\n def objf_numpy_return_python(self, x, *args):\n # function only knows numpy, solver knows python\n self.fval_iter += 1\n return self.objf_original(np.array(x), *args).tolist()\n\n def objf_numpy_minimizing(self, x, *args):\n self.fval_iter += 1\n errs = self.objf_original(np.array(x), *args)\n tot = 0.0\n for v in errs:\n tot += v*v\n return float(tot)\n\n def objf_python_minimizing(self, x, *args):\n self.fval_iter += 1\n errs = self.objf_original(x if type(x) is list else x.tolist(), *args)\n tot = 0.0\n for v in errs:\n tot += v*v\n return tot\n\n def jac_minimizing(self, x, *args):\n fval = self.objf_original(x, *args)\n jval = self.original_jac(x, *args)\n N = len(fval)\n small_jac = [0.0]*N\n for i in range(N):\n temp = 0.0\n for j in range(N):\n temp += fval[j]*jval[j][i]\n small_jac[i] = 2.0*temp\n return small_jac\n\n def jac_minimizing_numpy(self, x, *args):\n fval = self.objf_original(x, *args)\n jval = self.original_jac(x, *args)\n return 2.0*np.dot(fval, jval)\n\n def objf_python_return_numpy_scalar(self, x, *args):\n self.fval_iter += 1\n return float(self.objf_original(x if type(x) is list else x.tolist(), *args))\n\n def objf_numpy_return_python_scalar(self, x, *args):\n self.fval_iter += 1\n return float(self.objf_original(np.array(x), *args))\n\n def __init__(self, method, objf, jac=None, xtol=1e-8, ytol=None, maxiter=100, damping=1.0,\n jacobian_method=\"python\", jacobian_perturbation=1e-9, jacobian_zero_offset=1e-7,\n hessian_method=\"python\",\n jacobian_order=1, objf_numpy=False, matrix_solver=py_solve, scalar_objective=False):\n self.method, self.objf_original, self.original_jac = method, objf, jac\n self.xtol, self.ytol, self.maxiter, self.damping = xtol, ytol, maxiter, damping\n\n (self.jacobian_perturbation, self.jacobian_zero_offset, self.jacobian_method,\n self.jacobian_order, self.hessian_method) = (jacobian_perturbation,\n jacobian_zero_offset,\n jacobian_method,\n jacobian_order,\n hessian_method)\n self.objf_numpy, self.matrix_solver = objf_numpy, matrix_solver\n\n\n if jacobian_method == \"analytical\":\n self.jacobian_numpy = objf_numpy\n else:\n self.jacobian_numpy = jacobian_method not in python_jacobians_set\n if hessian_method == \"analytical\":\n self.hessian_numpy = objf_numpy\n else:\n self.hessian_numpy = hessian_method not in python_hessians_set\n # whether or not the solver uses numpy\n self.solver_numpy = solver_numpy = method not in python_solvers_set\n\n self.minimizing = False\n self.fval_iter = self.jac_iter = self.jac_fval_count = self.hess_iter = self.hess_fval_count = 0\n self.scalar_objective = scalar_objective\n # whether or not the objf uses numpy\n # if jac is provided it is assumed it is in the same basis\n\n if self.scalar_objective:\n # Direct scalar minimization\n if solver_numpy:\n if not objf_numpy:\n self.objf = self.objf_python_return_numpy_scalar\n else:\n self.objf = self.objf_counting\n else:\n if objf_numpy:\n self.objf = self.objf_numpy_return_python_scalar\n else:\n self.objf = self.objf_counting\n else:\n\n if method in scipy_minimize_options_set:\n self.minimizing = True\n if jacobian_method == \"scipy\" and method in scipy_requires_jacobian_options_set:\n self.jacobian_method = \"python\"\n self.objf = self.objf_numpy_minimizing if objf_numpy else self.objf_python_minimizing\n elif solver_numpy:\n if not objf_numpy:\n self.objf = self.objf_python_return_numpy\n else:\n self.objf = self.objf_counting\n else:\n if objf_numpy:\n self.objf = self.objf_numpy_return_python\n else:\n self.objf = self.objf_counting\n\n if self.minimizing:\n if objf_numpy:\n self.solver_analytical_jac = self.jac_minimizing_numpy\n else:\n self.solver_analytical_jac = self.jac_minimizing\n else:\n self.solver_analytical_jac = self.original_jac\n\n\n\n\n\n def hessian(self, x, base=None, args=()):\n self.hess_iter += 1\n fval_iter, hessian_method, objf_numpy, hessian_numpy = self.fval_iter, self.hessian_method, self.objf_numpy, self.hessian_numpy\n return_numpy = type(x) is not list\n\n if self.scalar_objective:\n # For scalar objectives, always use the efficient scalar calculator\n if not self.hessian_numpy:\n x = x if type(x) is list else x.tolist()\n else:\n x = np.array(x)\n # Use the correct objf based on numpy/python preferences\n if self.objf_numpy:\n objf = self.objf_counting\n else:\n objf = self.objf_python_return_numpy if self.hessian_numpy else self.objf_counting\n\n h = hessian(objf, x, scalar=True,\n perturbation=self.jacobian_perturbation,\n zero_offset=self.jacobian_zero_offset,\n args=args)\n else:\n if hessian_method == \"analytical\":\n if objf_numpy and not return_numpy:\n x = np.array(x)\n elif return_numpy and not objf_numpy:\n x = x.tolist()\n raise NotImplementedError\n h = self.solver_analytical_hess(x, *args)\n else:\n # if the hessian method doesn't speak numpy, convert x to a list\n if not hessian_numpy:\n x = x if type(x) is list else x.tolist()\n else:\n x = np.array(x)\n # If the objf doesn't speak numpy but the hessian does, use the converter\n if self.minimizing:\n if objf_numpy:\n objf = self.objf_numpy_minimizing\n else:\n objf = self.objf_python_minimizing\n else:\n if not hessian_numpy:\n if objf_numpy:\n objf = self.objf_numpy_return_python\n else:\n objf = self.objf_counting\n else:\n if objf_numpy:\n objf = self.objf_counting\n else:\n objf = self.objf_python_return_numpy\n\n if hessian_method.startswith(\"numdifftools\"):\n import numdifftools as nd\n if hessian_method == \"python\":\n h = hessian(objf, x, scalar=self.minimizing, perturbation=1e-4,\n zero_offset=self.jacobian_zero_offset, args=args)\n\n elif hessian_method == \"numdifftools_forward\":\n h = nd.Hessian(objf, method=\"forward\")(x)\n elif hessian_method == \"numdifftools_reverse\":\n h = nd.Hessian(objf, method=\"reverse\")(x)\n elif hessian_method == \"numdifftools_central\":\n h = nd.Hessian(objf, method=\"central\")(x)\n\n # Up the hessian fval count, set the fval back\n self.hess_fval_count += self.fval_iter - fval_iter\n self.fval_iter = fval_iter\n\n if return_numpy:\n return np.array(h) if type(h) is list else h\n else:\n return h if type(h) is list else h.tolist()\n\n def jacobian(self, x, *args):\n \"\"\"\n jacobi - doesn't support jacobian_perturbation, jacobian_zero_offset, jacobian_order\n python - doesn't support jacobian_order\n \"\"\"\n self.jac_iter += 1\n fval_iter, jacobian_method, objf_numpy, jacobian_numpy = self.fval_iter, self.jacobian_method, self.objf_numpy, self.jacobian_numpy\n return_numpy = type(x) is not list\n if self.scalar_objective:\n # For scalar objectives, always use the efficient scalar calculator\n if not self.jacobian_numpy:\n x = x if type(x) is list else x.tolist()\n else:\n x = np.array(x)\n\n # Use the correct objf based on numpy/python preferences\n if self.objf_numpy:\n objf = self.objf_counting\n else:\n objf = self.objf_python_return_numpy if self.jacobian_numpy else self.objf_counting\n\n j = jacobian(objf, x, scalar=True,\n perturbation=self.jacobian_perturbation,\n zero_offset=self.jacobian_zero_offset,\n args=args)\n else:\n if jacobian_method == \"analytical\":\n if objf_numpy and not return_numpy:\n x = np.array(x)\n elif return_numpy and not objf_numpy:\n x = x.tolist()\n j = self.solver_analytical_jac(x, *args)\n else:\n # if the jacobian method doesn't speak numpy, convert x to a list\n if not jacobian_numpy:\n x = x if type(x) is list else x.tolist()\n else:\n x = np.array(x)\n # If the objf doesn't speak numpy but the jacobian does, use the converter\n if self.minimizing:\n if objf_numpy:\n objf = self.objf_numpy_minimizing\n else:\n objf = self.objf_python_minimizing\n else:\n if not jacobian_numpy:\n if objf_numpy:\n objf = self.objf_numpy_return_python\n else:\n objf = self.objf_counting\n else:\n if objf_numpy:\n objf = self.objf_counting\n else:\n objf = self.objf_python_return_numpy\n\n if jacobian_method.startswith(\"numdifftools\"):\n import numdifftools as nd\n numdifftools_func = nd.Gradient if self.minimizing else nd.Jacobian\n step = self.jacobian_perturbation*x\n step[np.where(step==0)] = self.jacobian_zero_offset\n elif jacobian_method.startswith(\"jacobi\"):\n from jacobi import jacobi\n if jacobian_method == \"python\":\n j = jacobian(objf, x, scalar=self.minimizing, perturbation=self.jacobian_perturbation,\n zero_offset=self.jacobian_zero_offset, args=args)\n\n elif jacobian_method == \"numdifftools_forward\":\n j = numdifftools_func(objf, method=\"forward\", order=self.jacobian_order, step=step)(x)\n elif jacobian_method == \"numdifftools_reverse\":\n j = numdifftools_func(objf, method=\"reverse\", order=self.jacobian_order, step=step)(x)\n elif jacobian_method == \"numdifftools_central\":\n j = numdifftools_func(objf, method=\"central\", order=self.jacobian_order, step=step)(x)\n\n elif jacobian_method == \"jacobi_forward\":\n j = jacobi(objf, x, method=1)[0]\n elif jacobian_method == \"jacobi_central\":\n j = jacobi(objf, x, method=0)[0]\n elif jacobian_method == \"jacobi_backward\":\n j = jacobi(objf, x, method=1)[0]\n\n # Up the jacobian fval count, set the fval back\n self.jac_fval_count += self.fval_iter - fval_iter\n self.fval_iter = fval_iter\n # Handle the return value - doesn't matter what type the method returns\n # if (not (jacobian_numpy ^ return_numpy)) or (return_numpy and jacobian_numpy):\n # return j\n # elif return_numpy and not jacobian_numpy:\n # return np.array(j)\n # elif jacobian_numpy and not return_numpy:\n # return j.tolist()\n\n if return_numpy:\n return np.array(j) if type(j) is list else j\n else:\n return j if type(j) is list else j.tolist()\n\n def solve(self, x0, args=()):\n self.fval_iter = self.jac_iter = self.jac_fval_count = self.hess_iter = self.hess_fval_count = 0\n return_numpy = type(x0) is not list\n if self.solver_numpy:\n x0 = np.array(x0)\n elif return_numpy:\n x0 = x0.tolist()\n\n process_root = False\n method = self.method\n if method == \"newton_system\":\n sln, niter = newton_system(self.objf, x0, jac=self.jacobian, xtol=self.xtol, args=args,\n ytol=self.ytol, maxiter=self.maxiter, damping=self.damping,\n solve_func=self.matrix_solver)\n elif method == \"newton_system_line_search\":\n sln, niter = newton_system(self.objf, x0, jac=self.jacobian, xtol=self.xtol, args=args,\n ytol=self.ytol, maxiter=self.maxiter, damping=self.damping,\n line_search=True, solve_func=self.matrix_solver, require_progress=False,\n check_numbers=True, Armijo=True)\n elif method == \"newton_system_line_search_progress\":\n sln, niter = newton_system(self.objf, x0, jac=self.jacobian, xtol=self.xtol, args=args,\n ytol=self.ytol, maxiter=self.maxiter, damping=self.damping,\n line_search=True, solve_func=self.matrix_solver, require_progress=True,\n check_numbers=True, Armijo=True)\n elif method == \"homotopy_solver\":\n sln, niter = homotopy_solver(self.objf, x0, jac=self.jacobian, xtol=self.xtol, args=args,\n ytol=self.ytol, maxiter=self.maxiter, damping=self.damping,\n line_search=True, solve_func=self.matrix_solver)\n elif method == \"broyden2_python\":\n sln, niter = broyden2(x0, self.objf, self.jacobian, xtol=self.xtol, maxiter=self.maxiter,\n args=args)\n elif method == \"fixed_point\":\n sln, niter = fixed_point(residual_to_fixed_point(self.objf), x0, xtol=self.xtol, args=args, ytol=self.ytol, maxiter=self.maxiter, damping=self.damping)\n elif method == \"fixed_point_aitken\":\n sln, niter = fixed_point_aitken(residual_to_fixed_point(self.objf), x0, xtol=self.xtol, args=args, ytol=self.ytol, maxiter=self.maxiter, damping=self.damping)\n elif method == \"fixed_point_gdem\":\n sln, niter = fixed_point_gdem(residual_to_fixed_point(self.objf), x0, xtol=self.xtol, args=args, ytol=self.ytol, maxiter=self.maxiter, damping=self.damping)\n elif method == \"fixed_point_anderson\":\n sln, niter = fixed_point_anderson_residual(residual_to_fixed_point(self.objf), x0, xtol=self.xtol, args=args, ytol=self.ytol, maxiter=self.maxiter, window_size=5, reg=1e-8, initial_iterations=5, acc_damping=0.3, damping=1.0)\n elif method in scipy_root_options_set:\n process_root = True\n jacobian_method = self.jacobian_method\n jac = self.jacobian if jacobian_method != \"scipy\" else None\n result = root(self.objf, x0, args=args, method=method, jac=jac, tol=self.xtol)\n elif method in scipy_minimize_options_set:\n process_root = True\n jacobian_method = self.jacobian_method\n jac = self.jacobian if jacobian_method != \"scipy\" else None\n hess = self.hessian if method in scipy_requires_hessian_options_set else None\n result = minimize(self.objf, x0, args=args, method=method, jac=jac, tol=self.xtol, hess=hess)\n elif method == \"newton_minimize\":\n sln, niter = newton_minimize(\n self.objf, x0, jac=self.jacobian, hess=self.hessian,\n xtol=self.xtol, ytol=self.ytol,\n maxiter=self.maxiter, damping=self.damping,\n args=args)\n if process_root:\n sln = result.x\n\n if not return_numpy:\n sln = sln.tolist()\n elif return_numpy:\n sln = np.array(sln)\n\n return sln", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 26228}, "tests/test_numerics_arrays.py::1354": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/arrays.py"], "used_names": ["gelsd"], "enclosing_function": "test_gelsd_basic", "extracted_code": "# Source: fluids/numerics/arrays.py\ndef gelsd(a, b, rcond=None):\n \"\"\"Solve a linear least-squares problem using SVD (Singular Value Decomposition).\n This is a simplified implementation that uses numpy's SVD internally.\n\n The function solves the equation arg min(|b - Ax|) for x, where A is\n an M x N matrix and b is a length M vector.\n\n Parameters\n ----------\n a : list[list[float]]\n Input matrix A of shape (M, N)\n b : list[float]\n Input vector b of length M\n rcond : float, optional\n Cutoff ratio for small singular values. Singular values smaller\n than rcond * largest_singular_value are considered zero.\n Default: max(M,N) * eps where eps is the machine precision\n\n Returns\n -------\n x : list[float]\n Solution vector of length N\n residuals : float\n Sum of squared residuals of the solution. Only computed for overdetermined\n systems (M > N)\n rank : int\n Effective rank of matrix A\n s : list[float]\n Singular values of A in descending order\n\n Notes\n -----\n The implementation uses numpy.linalg.svd for the core computation but\n maintains a pure Python interface for input and output.\n \"\"\"\n # Get dimensions and handle empty cases\n m = len(a)\n n = len(a[0]) if m > 0 else 0\n\n if m == 0:\n if n == 0:\n return [], 0.0, 0, [] # Empty matrix\n return [0.0] * n, 0.0, 0, [] # Empty rows\n elif n == 0:\n return [], 0.0, 0, [] # Empty columns\n\n # Check compatibility\n if len(b) != m:\n raise ValueError(f\"Incompatible dimensions: A is {m}x{n}, b has length {len(b)}\")\n\n U, s, Vt = svd(a)\n\n # Set default rcond\n if rcond is None:\n rcond = max(m, n) * 2.2e-16 # Approximate machine epsilon for float64\n\n # Determine rank using rcond\n tol = rcond * s[0]\n rank = sum(sv > tol for sv in s)\n\n # Handle zero matrix case (all singular values below threshold)\n if rank == 0:\n return [0.0] * n, sum(bi * bi for bi in b), 0, s\n\n # We only need the first rank columns of U and V\n # If U is economy sized (Mxmin(M,N)), this is fine\n # If U is full sized (MxM), we still only use first rank columns\n Ut = transpose(U)\n Utb = matrix_vector_dot(Ut[:rank], b)\n\n # Apply 1/singular values with truncation\n s_inv_Utb = [Utb[i] / s[i] for i in range(rank)]\n\n # Get the first rank rows of V (transpose of first rank columns of Vt)\n # Again, works with both economy and full-size Vt\n V = transpose(Vt[:rank])\n x = matrix_vector_dot(V, s_inv_Utb)\n\n # Compute residuals for overdetermined systems\n residuals = 0.0\n if m > n and rank == n:\n # Compute Ax\n Ax = matrix_vector_dot(a, x)\n\n # Compute residuals as |b - Ax|^2\n diff = [b[i] - Ax[i] for i in range(m)]\n residuals = dot_product(diff, diff)\n return x, residuals, rank, s", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 2905}, "tests/test_numerics_arrays.py::1372": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/arrays.py"], "used_names": ["gelsd"], "enclosing_function": "test_gelsd_overdetermined", "extracted_code": "# Source: fluids/numerics/arrays.py\ndef gelsd(a, b, rcond=None):\n \"\"\"Solve a linear least-squares problem using SVD (Singular Value Decomposition).\n This is a simplified implementation that uses numpy's SVD internally.\n\n The function solves the equation arg min(|b - Ax|) for x, where A is\n an M x N matrix and b is a length M vector.\n\n Parameters\n ----------\n a : list[list[float]]\n Input matrix A of shape (M, N)\n b : list[float]\n Input vector b of length M\n rcond : float, optional\n Cutoff ratio for small singular values. Singular values smaller\n than rcond * largest_singular_value are considered zero.\n Default: max(M,N) * eps where eps is the machine precision\n\n Returns\n -------\n x : list[float]\n Solution vector of length N\n residuals : float\n Sum of squared residuals of the solution. Only computed for overdetermined\n systems (M > N)\n rank : int\n Effective rank of matrix A\n s : list[float]\n Singular values of A in descending order\n\n Notes\n -----\n The implementation uses numpy.linalg.svd for the core computation but\n maintains a pure Python interface for input and output.\n \"\"\"\n # Get dimensions and handle empty cases\n m = len(a)\n n = len(a[0]) if m > 0 else 0\n\n if m == 0:\n if n == 0:\n return [], 0.0, 0, [] # Empty matrix\n return [0.0] * n, 0.0, 0, [] # Empty rows\n elif n == 0:\n return [], 0.0, 0, [] # Empty columns\n\n # Check compatibility\n if len(b) != m:\n raise ValueError(f\"Incompatible dimensions: A is {m}x{n}, b has length {len(b)}\")\n\n U, s, Vt = svd(a)\n\n # Set default rcond\n if rcond is None:\n rcond = max(m, n) * 2.2e-16 # Approximate machine epsilon for float64\n\n # Determine rank using rcond\n tol = rcond * s[0]\n rank = sum(sv > tol for sv in s)\n\n # Handle zero matrix case (all singular values below threshold)\n if rank == 0:\n return [0.0] * n, sum(bi * bi for bi in b), 0, s\n\n # We only need the first rank columns of U and V\n # If U is economy sized (Mxmin(M,N)), this is fine\n # If U is full sized (MxM), we still only use first rank columns\n Ut = transpose(U)\n Utb = matrix_vector_dot(Ut[:rank], b)\n\n # Apply 1/singular values with truncation\n s_inv_Utb = [Utb[i] / s[i] for i in range(rank)]\n\n # Get the first rank rows of V (transpose of first rank columns of Vt)\n # Again, works with both economy and full-size Vt\n V = transpose(Vt[:rank])\n x = matrix_vector_dot(V, s_inv_Utb)\n\n # Compute residuals for overdetermined systems\n residuals = 0.0\n if m > n and rank == n:\n # Compute Ax\n Ax = matrix_vector_dot(a, x)\n\n # Compute residuals as |b - Ax|^2\n diff = [b[i] - Ax[i] for i in range(m)]\n residuals = dot_product(diff, diff)\n return x, residuals, rank, s", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 2905}, "tests/test_numerics_arrays.py::1382": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/arrays.py"], "used_names": ["gelsd"], "enclosing_function": "test_gelsd_underdetermined", "extracted_code": "# Source: fluids/numerics/arrays.py\ndef gelsd(a, b, rcond=None):\n \"\"\"Solve a linear least-squares problem using SVD (Singular Value Decomposition).\n This is a simplified implementation that uses numpy's SVD internally.\n\n The function solves the equation arg min(|b - Ax|) for x, where A is\n an M x N matrix and b is a length M vector.\n\n Parameters\n ----------\n a : list[list[float]]\n Input matrix A of shape (M, N)\n b : list[float]\n Input vector b of length M\n rcond : float, optional\n Cutoff ratio for small singular values. Singular values smaller\n than rcond * largest_singular_value are considered zero.\n Default: max(M,N) * eps where eps is the machine precision\n\n Returns\n -------\n x : list[float]\n Solution vector of length N\n residuals : float\n Sum of squared residuals of the solution. Only computed for overdetermined\n systems (M > N)\n rank : int\n Effective rank of matrix A\n s : list[float]\n Singular values of A in descending order\n\n Notes\n -----\n The implementation uses numpy.linalg.svd for the core computation but\n maintains a pure Python interface for input and output.\n \"\"\"\n # Get dimensions and handle empty cases\n m = len(a)\n n = len(a[0]) if m > 0 else 0\n\n if m == 0:\n if n == 0:\n return [], 0.0, 0, [] # Empty matrix\n return [0.0] * n, 0.0, 0, [] # Empty rows\n elif n == 0:\n return [], 0.0, 0, [] # Empty columns\n\n # Check compatibility\n if len(b) != m:\n raise ValueError(f\"Incompatible dimensions: A is {m}x{n}, b has length {len(b)}\")\n\n U, s, Vt = svd(a)\n\n # Set default rcond\n if rcond is None:\n rcond = max(m, n) * 2.2e-16 # Approximate machine epsilon for float64\n\n # Determine rank using rcond\n tol = rcond * s[0]\n rank = sum(sv > tol for sv in s)\n\n # Handle zero matrix case (all singular values below threshold)\n if rank == 0:\n return [0.0] * n, sum(bi * bi for bi in b), 0, s\n\n # We only need the first rank columns of U and V\n # If U is economy sized (Mxmin(M,N)), this is fine\n # If U is full sized (MxM), we still only use first rank columns\n Ut = transpose(U)\n Utb = matrix_vector_dot(Ut[:rank], b)\n\n # Apply 1/singular values with truncation\n s_inv_Utb = [Utb[i] / s[i] for i in range(rank)]\n\n # Get the first rank rows of V (transpose of first rank columns of Vt)\n # Again, works with both economy and full-size Vt\n V = transpose(Vt[:rank])\n x = matrix_vector_dot(V, s_inv_Utb)\n\n # Compute residuals for overdetermined systems\n residuals = 0.0\n if m > n and rank == n:\n # Compute Ax\n Ax = matrix_vector_dot(a, x)\n\n # Compute residuals as |b - Ax|^2\n diff = [b[i] - Ax[i] for i in range(m)]\n residuals = dot_product(diff, diff)\n return x, residuals, rank, s", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 2905}, "tests/test_numerics_arrays.py::1395": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/arrays.py"], "used_names": ["gelsd"], "enclosing_function": "test_gelsd_ill_conditioned", "extracted_code": "# Source: fluids/numerics/arrays.py\ndef gelsd(a, b, rcond=None):\n \"\"\"Solve a linear least-squares problem using SVD (Singular Value Decomposition).\n This is a simplified implementation that uses numpy's SVD internally.\n\n The function solves the equation arg min(|b - Ax|) for x, where A is\n an M x N matrix and b is a length M vector.\n\n Parameters\n ----------\n a : list[list[float]]\n Input matrix A of shape (M, N)\n b : list[float]\n Input vector b of length M\n rcond : float, optional\n Cutoff ratio for small singular values. Singular values smaller\n than rcond * largest_singular_value are considered zero.\n Default: max(M,N) * eps where eps is the machine precision\n\n Returns\n -------\n x : list[float]\n Solution vector of length N\n residuals : float\n Sum of squared residuals of the solution. Only computed for overdetermined\n systems (M > N)\n rank : int\n Effective rank of matrix A\n s : list[float]\n Singular values of A in descending order\n\n Notes\n -----\n The implementation uses numpy.linalg.svd for the core computation but\n maintains a pure Python interface for input and output.\n \"\"\"\n # Get dimensions and handle empty cases\n m = len(a)\n n = len(a[0]) if m > 0 else 0\n\n if m == 0:\n if n == 0:\n return [], 0.0, 0, [] # Empty matrix\n return [0.0] * n, 0.0, 0, [] # Empty rows\n elif n == 0:\n return [], 0.0, 0, [] # Empty columns\n\n # Check compatibility\n if len(b) != m:\n raise ValueError(f\"Incompatible dimensions: A is {m}x{n}, b has length {len(b)}\")\n\n U, s, Vt = svd(a)\n\n # Set default rcond\n if rcond is None:\n rcond = max(m, n) * 2.2e-16 # Approximate machine epsilon for float64\n\n # Determine rank using rcond\n tol = rcond * s[0]\n rank = sum(sv > tol for sv in s)\n\n # Handle zero matrix case (all singular values below threshold)\n if rank == 0:\n return [0.0] * n, sum(bi * bi for bi in b), 0, s\n\n # We only need the first rank columns of U and V\n # If U is economy sized (Mxmin(M,N)), this is fine\n # If U is full sized (MxM), we still only use first rank columns\n Ut = transpose(U)\n Utb = matrix_vector_dot(Ut[:rank], b)\n\n # Apply 1/singular values with truncation\n s_inv_Utb = [Utb[i] / s[i] for i in range(rank)]\n\n # Get the first rank rows of V (transpose of first rank columns of Vt)\n # Again, works with both economy and full-size Vt\n V = transpose(Vt[:rank])\n x = matrix_vector_dot(V, s_inv_Utb)\n\n # Compute residuals for overdetermined systems\n residuals = 0.0\n if m > n and rank == n:\n # Compute Ax\n Ax = matrix_vector_dot(a, x)\n\n # Compute residuals as |b - Ax|^2\n diff = [b[i] - Ax[i] for i in range(m)]\n residuals = dot_product(diff, diff)\n return x, residuals, rank, s", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 2905}, "tests/test_numerics_arrays.py::1526": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/arrays.py"], "used_names": ["gelsd"], "enclosing_function": "test_gelsd_rcond", "extracted_code": "# Source: fluids/numerics/arrays.py\ndef gelsd(a, b, rcond=None):\n \"\"\"Solve a linear least-squares problem using SVD (Singular Value Decomposition).\n This is a simplified implementation that uses numpy's SVD internally.\n\n The function solves the equation arg min(|b - Ax|) for x, where A is\n an M x N matrix and b is a length M vector.\n\n Parameters\n ----------\n a : list[list[float]]\n Input matrix A of shape (M, N)\n b : list[float]\n Input vector b of length M\n rcond : float, optional\n Cutoff ratio for small singular values. Singular values smaller\n than rcond * largest_singular_value are considered zero.\n Default: max(M,N) * eps where eps is the machine precision\n\n Returns\n -------\n x : list[float]\n Solution vector of length N\n residuals : float\n Sum of squared residuals of the solution. Only computed for overdetermined\n systems (M > N)\n rank : int\n Effective rank of matrix A\n s : list[float]\n Singular values of A in descending order\n\n Notes\n -----\n The implementation uses numpy.linalg.svd for the core computation but\n maintains a pure Python interface for input and output.\n \"\"\"\n # Get dimensions and handle empty cases\n m = len(a)\n n = len(a[0]) if m > 0 else 0\n\n if m == 0:\n if n == 0:\n return [], 0.0, 0, [] # Empty matrix\n return [0.0] * n, 0.0, 0, [] # Empty rows\n elif n == 0:\n return [], 0.0, 0, [] # Empty columns\n\n # Check compatibility\n if len(b) != m:\n raise ValueError(f\"Incompatible dimensions: A is {m}x{n}, b has length {len(b)}\")\n\n U, s, Vt = svd(a)\n\n # Set default rcond\n if rcond is None:\n rcond = max(m, n) * 2.2e-16 # Approximate machine epsilon for float64\n\n # Determine rank using rcond\n tol = rcond * s[0]\n rank = sum(sv > tol for sv in s)\n\n # Handle zero matrix case (all singular values below threshold)\n if rank == 0:\n return [0.0] * n, sum(bi * bi for bi in b), 0, s\n\n # We only need the first rank columns of U and V\n # If U is economy sized (Mxmin(M,N)), this is fine\n # If U is full sized (MxM), we still only use first rank columns\n Ut = transpose(U)\n Utb = matrix_vector_dot(Ut[:rank], b)\n\n # Apply 1/singular values with truncation\n s_inv_Utb = [Utb[i] / s[i] for i in range(rank)]\n\n # Get the first rank rows of V (transpose of first rank columns of Vt)\n # Again, works with both economy and full-size Vt\n V = transpose(Vt[:rank])\n x = matrix_vector_dot(V, s_inv_Utb)\n\n # Compute residuals for overdetermined systems\n residuals = 0.0\n if m > n and rank == n:\n # Compute Ax\n Ax = matrix_vector_dot(a, x)\n\n # Compute residuals as |b - Ax|^2\n diff = [b[i] - Ax[i] for i in range(m)]\n residuals = dot_product(diff, diff)\n return x, residuals, rank, s", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 2905}, "tests/test_numerics_doubledouble.py::292": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/doubledouble.py"], "used_names": ["assert_close", "exp_dd"], "enclosing_function": "test_exp_dd", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/numerics/doubledouble.py\ndef exp_dd(r, e):\n n = round(r)\n xr, xe = add_dd(r, e, -n, 0)\n ur, ue = add_dd(xr, xe, dd_exp_coeffs[0], 0)\n\n for i in range(1, 12):\n ur, ue = mul_dd(xr, xe, ur, ue)\n ur, ue = add_dd(ur, ue, dd_exp_coeffs[i], 0)\n\n vr, ve = add_dd(xr, xe, -dd_exp_coeffs[0], 0)\n f = 1.0\n for i in range(1, 12):\n vr, ve = mul_dd(xr, xe, vr, ve)\n vr, ve = add_dd(vr, ve, f*dd_exp_coeffs[i], 0)\n f *= -1.0\n\n outr, oute = intpow_dd(2.718281828459045, 1.4456468917292502e-16, n)\n outr, oute = mul_dd(outr, oute, ur, ue)\n outr, oute = div_dd(outr, oute, vr, ve)\n return outr, oute", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1276}, "tests/test_particle_size_distribution.py::610": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/particle_size_distribution.py"], "used_names": ["PSDLognormal", "assert_close", "assert_close1d"], "enclosing_function": "test_PSD_lognormal_truncated", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\n\n# Source: fluids/particle_size_distribution.py\nclass PSDLognormal(ParticleSizeDistributionContinuous):\n name = \"Lognormal\"\n points = False\n truncated = False\n def __init__(self, d_characteristic: float, s: float, order: int=3, d_min: float | None=None, d_max: float | None=None) -> None:\n self.s = s\n self.d_characteristic = d_characteristic\n self.order = order\n self.parameters = {\"s\": s, \"d_characteristic\": d_characteristic,\n \"d_min\": d_min, \"d_max\": d_max}\n if d_min is not None:\n self.d_min = d_min\n if d_max is not None:\n self.d_max = d_max\n # Pick an upper bound for the search algorithm of 15 orders of magnitude larger than\n # the characteristic diameter; should never be a problem, as diameters can only range\n # so much, physically.\n if d_max is not None:\n self.d_excessive = d_max\n else:\n self.d_excessive = 1E15*self.d_characteristic\n if d_min is not None:\n self.d_minimum = d_min\n else:\n self.d_minimum = 0.0\n\n if d_min is not None or d_max is not None:\n self.truncated = True\n if d_max is None:\n self.d_max = self.d_excessive\n else:\n self.d_max = d_max\n if d_min is None:\n self.d_min = 0.0\n else:\n self.d_min = d_min\n\n self._cdf_d_max = self._cdf(self.d_max)\n self._cdf_d_min = self._cdf(self.d_min)\n\n def _pdf(self, d: float) -> float:\n return pdf_lognormal(d, self.d_characteristic, self.s)\n\n def _cdf(self, d: float) -> float:\n return cdf_lognormal(d, self.d_characteristic, self.s)\n\n def _pdf_basis_integral(self, d: float, n: float) -> float:\n return pdf_lognormal_basis_integral(d, self.d_characteristic, self.s, n)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 2754}, "tests/test_piping.py::123": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/piping.py"], "used_names": ["NPS120_D1785", "assert_close", "assert_close1d", "nearest_pipe", "pipe_too_large_msg", "pytest"], "enclosing_function": "test_nearest_pipe_error_paths", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\n\n# Source: fluids/piping.py\npipe_too_large_msg = \"Pipe input is larger than max of selected schedule\"\n\ndef nearest_pipe(Do: float | None=None, Di: float | None=None, NPS: int | None=None, schedule: str | float=\"40\") -> tuple[float, float, float, float]:\n r\"\"\"Searches for and finds the nearest standard pipe size to a given\n specification. Acceptable inputs are:\n\n - Nominal pipe size\n - Nominal pipe size and schedule\n - Outer diameter `Do`\n - Outer diameter `Do` and schedule\n - Inner diameter `Di`\n - Inner diameter `Di` and schedule\n\n Acceptable schedules are: '5', '10', '20', '30', '40', '60', '80', '100',\n '120', '140', '160', 'STD', 'XS', 'XXS', '5S', '10S', '40S', '80S',\n '40D1527', '80D1527',\n 'ABSD2680', 'PVCD2680',\n 'DR25C900', 'DR18C900', 'DR14C900',\n 'CIDR51C905', 'CIDR41C905', 'CIDR325C905', 'CIDR25C905', 'CIDR21C905', 'CIDR18C905', 'CIDR14C905',\n 'IPSDR21', 'IPSDR26', 'IPSDR325', 'IPSDR41',\n 'PS115F679', 'PS75F679', 'PS46F679',\n 'PVCD2665',\n '40D1785', '80D1785', '120D1785',\n 'DR135D2241', 'DR17D2241', 'DR21D2241', 'DR26D2241', 'DR325D2241', 'DR41D2241', 'DR64D2241',\n 'DR21D2241CTS', 'DR17D2241CTS', 'DR135D2241CTS', 'DR11D2241CTS',\n 'DR21D2241PIP', 'DR26D2241PIP', 'DR325D2241PIP', 'DR35D2241PIP', 'DR41D2241PIP', 'DR51D2241PIP', 'DR81D2241PIP',\n 'S40F441IPS', 'S80F441IPS', 'S40F441SI', 'S80F441SI'\n 'DR325F2619SI', 'DR26F2619SI', 'DR21F2619SI', 'DR17F2619SI', 'DR135F2619SI', 'DR11F2619SI', 'DR9F2619SI', 'DR73F2619SI', 'DR7F2619SI',\n 'DR325F2619IPS', 'DR26F2619IPS', 'DR21F2619IPS', 'DR17F2619IPS', 'DR135F2619IPS', 'DR11F2619IPS', 'DR9F2619IPS', 'DR73F2619IPS', 'DR7F2619IPS',\n 'BS1387LIGHT', 'BS1387MEDIUM', 'BS1387HEAVY'\n\n Parameters\n ----------\n Do : float, optional\n Pipe outer diameter, [m]\n Di : float, optional\n Pipe inner diameter, [m]\n NPS : float, optional\n Nominal pipe size, [-]\n schedule : str, optional\n String representing schedule size\n\n Returns\n -------\n NPS : float\n Nominal pipe size, [-]\n Di : float\n Pipe inner diameter, [m]\n Do : float\n Pipe outer diameter, [m]\n t : float\n Pipe wall thickness, [m]\n\n Notes\n -----\n Internal units within this function are mm.\n The imperial schedules are not quite identical to these value, but\n all rounding differences happen in the sub-0.1 mm level.\n\n Examples\n --------\n >>> nearest_pipe(Di=0.021)\n (1.0, 0.02664, 0.0334, 0.00338)\n >>> nearest_pipe(Do=.273, schedule='5S')\n (10.0, 0.2663, 0.2731, 0.0034)\n\n References\n ----------\n .. [1] American National Standards Institute, and American Society of\n Mechanical Engineers. B36.10M-2004: Welded and Seamless Wrought Steel\n Pipe. New York: American Society of Mechanical Engineers, 2004.\n .. [2] American National Standards Institute, and American Society of\n Mechanical Engineers. B36-19M-2004: Stainless Steel Pipe.\n New York, N.Y.: American Society of Mechanical Engineers, 2004.\n .. [3] F17 Committee. \"Specification for Acrylonitrile-Butadiene-Styrene\n (ABS) Plastic Pipe, Schedules 40 and 80.\" ASTM International.\n https://doi.org/10.1520/D1527-99R05.\n .. [4] F17 Committee. \"Specification for Acrylonitrile-Butadiene-Styrene\n (ABS) and Poly(Vinyl Chloride) (PVC) Composite Sewer Piping.\" ASTM\n International. https://doi.org/10.1520/D2680-01R14.\n .. [5] AWWA-American Water Works Association. \"AWWA C900-07 Polyvinyl\n Chloride (PVC) Pressure Pipe and Fabricated Fittings, 4 In. Through 12\n In. (100 Mm Through 300 Mm), for Water Transmission and Distribution.\"\n .. [6] AWWA-American Water Works Association. \"AWWA C905-97 Polyvinyl\n Chloride (PVC) Pressure Pipe and Fabricated Fittings, 14 in. Through\n 48 in. (350 Mm through 1,200 Mm), for Water Transmission and\n Distribution.\"\n .. [7] F17 Committee. \"Specification for Poly(Vinyl Chloride) (PVC)\n Large-Diameter Plastic Gravity Sewer Pipe and Fittings.\" ASTM\n International. https://doi.org/10.1520/F0679-16.\n .. [8] F17 Committee. \"Specification for Poly(Vinyl Chloride) (PVC) Plastic\n Drain, Waste, and Vent Pipe and Fittings.\" ASTM International.\n https://doi.org/10.1520/D2665-14.\n .. [9] F17 Committee. \"Specification for Poly(Vinyl Chloride) (PVC) Plastic\n Pipe, Schedules 40, 80, and 120.\" ASTM International.\n https://doi.org/10.1520/D1785-15E01.\n .. [10] F17 Committee. \"Specification for Chlorinated Poly(Vinyl Chloride)\n (CPVC) Plastic Pipe, Schedules 40 and 80.\" ASTM International.\n https://doi.org/10.1520/F0441_F0441M-15.\n .. [11] F17 Committee. \"Specification for High-Density Polyethylene (PE)\n Line Pipe.\" ASTM International. https://doi.org/10.1520/F2619_F2619M-20.\n \"\"\"\n if Di is not None:\n Di *= 1E3\n if Do is not None:\n Do *= 1E3\n\n # If accidentally given an numerical schedule, convert it to a string\n if isinstance(schedule, (int, float)):\n search_schedule = str(int(schedule))\n else:\n search_schedule = schedule\n\n if search_schedule not in schedule_lookup:\n raise ValueError(\"Schedule not recognized\")\n else:\n NPSes, Dis, Dos, ts = schedule_lookup[search_schedule]\n\n # Handle the three cases of different inputs\n if Di is not None:\n nums = Di_lookup(Di, NPSes, Dis, Dos, ts)\n elif Do is not None:\n nums = Do_lookup(Do, NPSes, Dis, Dos, ts)\n elif NPS is not None:\n nums = NPS_lookup(float(NPS), NPSes, Dis, Dos, ts)\n\n _nps, _di, _do, _t = nums\n return _nps, _di*1e-3, _do*1e-3, _t*1e-3", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 6531}, "tests/test_pump.py::138": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/numerics/__init__.py", "fluids/pump.py"], "used_names": ["electrical_plug_types", "industrial_power", "residential_power", "residential_power_frequencies", "voltages_1_phase_residential", "voltages_3_phase"], "enclosing_function": "test_power_sources", "extracted_code": "# Source: fluids/pump.py\nresidential_power = {\n \"at\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Austria\"),\n \"bj\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Benin\"),\n \"gh\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Ghana\"),\n \"sc\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Seychelles\"),\n \"bg\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Bulgaria\"),\n \"me\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Montenegro\"),\n \"fo\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"K\"), voltage=230, freq=50, country=\"Faroe Islands\"),\n \"ne\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"), voltage=220, freq=50, country=\"Niger\"),\n \"za\": CountryPower(plugs=(\"C\", \"F\", \"M\", \"N\"), voltage=230, freq=50, country=\"South Africa\"),\n \"az\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Azerbaijan\"),\n \"so\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Somalia\"),\n \"sn\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"K\"), voltage=230, freq=50, country=\"Senegal\"),\n \"np\": CountryPower(plugs=(\"C\", \"D\", \"M\"), voltage=230, freq=50, country=\"Nepal\"),\n \"sl\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Sierra Leone\"),\n \"be\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Belgium\"),\n \"vg\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"British Virgin Islands\"),\n \"bz\": CountryPower(plugs=(\"A\", \"B\", \"G\"), voltage=110, freq=60, country=\"Belize\"),\n \"tw\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Taiwan\"),\n \"bf\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Burkina Faso\"),\n \"ao\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Angola\"),\n \"gi\": CountryPower(plugs=(\"C\", \"G\"), voltage=240, freq=50, country=\"Gibraltar\"),\n \"ee\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Estonia\"),\n \"bs\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Bahamas\"),\n \"ir\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Iran\"),\n \"sv\": CountryPower(plugs=(\"A\", \"B\"), voltage=115, freq=60, country=\"El Salvador\"),\n \"am\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Armenia\"),\n \"is\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Iceland\"),\n \"uy\": CountryPower(plugs=(\"C\", \"F\", \"I\", \"L\"), voltage=230, freq=50, country=\"Uruguay\"),\n \"mc\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"F\"), voltage=230, freq=50, country=\"Monaco\"),\n \"jm\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=50, country=\"Jamaica\"),\n \"im\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Isle of Man\"),\n \"dm\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Dominica\"),\n \"mu\": CountryPower(plugs=(\"C\", \"G\"), voltage=230, freq=50, country=\"Mauritius\"),\n \"cz\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Czech Republic\"),\n \"kh\": CountryPower(plugs=(\"A\", \"C\", \"G\"), voltage=230, freq=50, country=\"Cambodia\"),\n \"cf\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Central African Republic\"),\n \"se\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Sweden\"),\n \"uz\": CountryPower(plugs=(\"C\", \"I\"), voltage=220, freq=50, country=\"Uzbekistan\"),\n \"sk\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Slovakia\"),\n \"ky\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Cayman Islands\"),\n \"tn\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Tunisia\"),\n \"do\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Dominican Republic\"),\n \"hu\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Hungary\"),\n \"af\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Afghanistan\"),\n \"et\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"L\"), voltage=220, freq=50, country=\"Ethiopia\"),\n \"tv\": CountryPower(plugs=(\"I\",), voltage=220, freq=50, country=\"Tuvalu\"),\n \"ad\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Andorra\"),\n \"hn\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Honduras\"),\n \"ls\": CountryPower(plugs=(\"M\",), voltage=220, freq=50, country=\"Lesotho\"),\n \"na\": CountryPower(plugs=(\"D\", \"M\"), voltage=220, freq=50, country=\"Namibia\"),\n \"jo\": CountryPower(plugs=(\"B\", \"C\", \"D\", \"F\", \"G\", \"J\"), voltage=230, freq=50, country=\"Jordan\"),\n \"pl\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Poland\"),\n \"bt\": CountryPower(plugs=(\"C\", \"D\", \"F\", \"G\", \"M\"), voltage=230, freq=50, country=\"Bhutan\"),\n \"fm\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Micronesia\"),\n \"no\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Norway\"),\n \"fk\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Falkland Islands\"),\n \"je\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Jersey\"),\n \"ye\": CountryPower(plugs=(\"A\", \"D\", \"G\"), voltage=230, freq=50, country=\"Yemen\"),\n \"cm\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Cameroon\"),\n \"md\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Moldova\"),\n \"cn\": CountryPower(plugs=(\"A\", \"I\", \"C\"), voltage=220, freq=50, country=\"China\"),\n \"gm\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Gambia\"),\n \"sg\": CountryPower(plugs=(\"C\", \"G\", \"M\"), voltage=230, freq=50, country=\"Singapore\"),\n \"tj\": CountryPower(plugs=(\"C\", \"F\", \"I\"), voltage=220, freq=50, country=\"Tajikistan\"),\n \"gt\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Guatemala\"),\n \"ma\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Morocco\"),\n \"mv\": CountryPower(plugs=(\"D\", \"G\", \"J\", \"K\", \"L\"), voltage=230, freq=50, country=\"Maldives\"),\n \"ga\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Gabon\"),\n \"bo\": CountryPower(plugs=(\"A\", \"C\"), voltage=115, freq=50, country=\"Bolivia\"),\n \"ly\": CountryPower(plugs=(\"C\", \"D\", \"F\", \"L\"), voltage=127, freq=50, country=\"Libya\"),\n \"rw\": CountryPower(plugs=(\"C\", \"J\"), voltage=230, freq=50, country=\"Rwanda\"),\n \"cg\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Congo, Republic of the\"),\n \"kz\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Kazakhstan\"),\n \"jp\": CountryPower(plugs=(\"A\", \"B\"), voltage=100, freq=50, country=\"Japan\"),\n \"co\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Colombia\"),\n \"sm\": CountryPower(plugs=(\"C\", \"F\", \"L\"), voltage=230, freq=50, country=\"San Marino\"),\n \"rs\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Serbia\"),\n \"gw\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Guinea-Bissau\"),\n \"kr\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=60, country=\"South Korea\"),\n \"py\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Paraguay\"),\n \"lt\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Lithuania\"),\n \"tr\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Turkey\"),\n \"pa\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Panama\"),\n \"ba\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Bosnia and Herzegovina\"),\n \"vn\": CountryPower(plugs=(\"A\", \"C\", \"G\"), voltage=220, freq=50, country=\"Vietnam\"),\n \"iq\": CountryPower(plugs=(\"C\", \"D\", \"G\"), voltage=230, freq=50, country=\"Iraq\"),\n \"pk\": CountryPower(plugs=(\"C\", \"D\", \"G\", \"M\"), voltage=230, freq=50, country=\"Pakistan\"),\n \"li\": CountryPower(plugs=(\"C\", \"J\"), voltage=230, freq=50, country=\"Liechtenstein\"),\n \"mz\": CountryPower(plugs=(\"C\", \"F\", \"M\"), voltage=220, freq=50, country=\"Mozambique\"),\n \"au\": CountryPower(plugs=(\"I\",), voltage=230, freq=50, country=\"Australia\"),\n \"ws\": CountryPower(plugs=(\"I\",), voltage=230, freq=50, country=\"Samoa\"),\n \"sr\": CountryPower(plugs=(\"C\", \"F\"), voltage=127, freq=60, country=\"Suriname\"),\n \"mn\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Mongolia\"),\n \"bw\": CountryPower(plugs=(\"D\", \"G\", \"M\"), voltage=230, freq=50, country=\"Botswana\"),\n \"gb\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"United Kingdom\"),\n \"pg\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Papua New Guinea\"),\n \"dj\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Djibouti\"),\n \"th\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"F\"), voltage=220, freq=50, country=\"Thailand\"),\n \"us\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"United States\"),\n \"gr\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Greece\"),\n \"kn\": CountryPower(plugs=(\"A\", \"B\", \"D\", \"G\"), voltage=110, freq=60, country=\"St. Kitts and Nevis\"),\n \"ug\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Uganda\"),\n \"ie\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Ireland\"),\n \"tg\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Togo\"),\n \"td\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"F\"), voltage=220, freq=50, country=\"Chad\"),\n \"la\": CountryPower(plugs=(\"C\", \"E\", \"F\"), voltage=230, freq=50, country=\"Laos\"),\n \"sy\": CountryPower(plugs=(\"C\", \"E\", \"L\"), voltage=220, freq=50, country=\"Syria\"),\n \"bm\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Bermuda\"),\n \"il\": CountryPower(plugs=(\"C\", \"H\", \"M\"), voltage=230, freq=50, country=\"Israel\"),\n \"nz\": CountryPower(plugs=(\"I\",), voltage=230, freq=50, country=\"New Zealand\"),\n \"mg\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"J\", \"K\"), voltage=220, freq=50, country=\"Madagascar\"),\n \"ve\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Venezuela\"),\n \"dk\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"K\"), voltage=230, freq=50, country=\"Denmark\"),\n \"lb\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"D\", \"G\"), voltage=220, freq=50, country=\"Lebanon\"),\n \"kp\": CountryPower(plugs=(\"A\", \"C\", \"F\"), voltage=110, freq=60, country=\"North Korea\"),\n \"vu\": CountryPower(plugs=(\"C\", \"G\", \"I\"), voltage=220, freq=50, country=\"Vanuatu\"),\n \"cu\": CountryPower(plugs=(\"A\", \"B\", \"C\"), voltage=110, freq=60, country=\"Cuba\"),\n \"pt\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Portugal\"),\n \"kw\": CountryPower(plugs=(\"C\", \"G\"), voltage=240, freq=50, country=\"Kuwait\"),\n \"cd\": CountryPower(plugs=(\"C\", \"D\", \"E\"), voltage=220, freq=50, country=\"Congo, Democratic Republic of the\"),\n \"nr\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Nauru\"),\n \"si\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Slovenia\"),\n \"bd\": CountryPower(plugs=(\"C\", \"D\", \"G\", \"K\"), voltage=220, freq=50, country=\"Bangladesh\"),\n \"al\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Albania\"),\n \"ec\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Ecuador\"),\n \"gy\": CountryPower(plugs=(\"A\", \"B\", \"D\", \"G\"), voltage=110, freq=60, country=\"Guyana\"),\n \"bb\": CountryPower(plugs=(\"A\", \"B\"), voltage=115, freq=50, country=\"Barbados\"),\n \"ke\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Kenya\"),\n \"mx\": CountryPower(plugs=(\"A\", \"B\"), voltage=127, freq=60, country=\"Mexico\"),\n \"gq\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Equatorial Guinea\"),\n \"gn\": CountryPower(plugs=(\"C\", \"F\", \"K\"), voltage=220, freq=50, country=\"Guinea\"),\n \"bi\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Burundi\"),\n \"lv\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Latvia\"),\n \"fj\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Fiji\"),\n \"ci\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Côte d'Ivoire\"),\n \"ai\": CountryPower(plugs=(\"A\",), voltage=110, freq=60, country=\"Anguilla\"),\n \"gu\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Guam\"),\n \"lr\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"E\", \"F\"), voltage=120, freq=60, country=\"Liberia\"),\n \"br\": CountryPower(plugs=(\"C\", \"N\"), voltage=220, freq=60, country=\"Brazil\"),\n \"cv\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Cape Verde\"),\n \"cl\": CountryPower(plugs=(\"L\",), voltage=220, freq=50, country=\"Chile\"),\n \"in\": CountryPower(plugs=(\"C\", \"D\", \"M\"), voltage=230, freq=50, country=\"India\"),\n \"gg\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Guernsey\"),\n \"tt\": CountryPower(plugs=(\"A\", \"B\"), voltage=115, freq=60, country=\"Trinidad & Tobago\"),\n \"de\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Germany\"),\n \"qa\": CountryPower(plugs=(\"D\", \"G\"), voltage=240, freq=50, country=\"Qatar\"),\n \"ph\": CountryPower(plugs=(\"A\", \"B\"), voltage=220, freq=60, country=\"Philippines\"),\n \"sd\": CountryPower(plugs=(\"C\", \"D\"), voltage=230, freq=50, country=\"Sudan\"),\n \"mm\": CountryPower(plugs=(\"C\", \"D\", \"F\", \"G\"), voltage=230, freq=50, country=\"Myanmar\"),\n \"gd\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Grenada\"),\n \"st\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"São Tomé and Príncipe\"),\n \"sz\": CountryPower(plugs=(\"M\",), voltage=230, freq=50, country=\"Swaziland\"),\n \"ro\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Romania\"),\n \"xk\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Kosovo\"),\n \"cy\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Cyprus\"),\n \"dz\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Algeria\"),\n \"zm\": CountryPower(plugs=(\"C\", \"D\", \"G\"), voltage=230, freq=50, country=\"Zambia\"),\n \"by\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Belarus\"),\n \"hr\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Croatia\"),\n \"lu\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Luxembourg\"),\n \"fi\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Finland\"),\n \"zw\": CountryPower(plugs=(\"D\", \"G\"), voltage=220, freq=50, country=\"Zimbabwe\"),\n \"km\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Comoros\"),\n \"tl\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"I\"), voltage=220, freq=50, country=\"Timor-Leste \"),\n \"tz\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Tanzania\"),\n \"ht\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Haiti\"),\n \"vc\": CountryPower(plugs=(\"C\", \"E\", \"G\", \"I\", \"K\"), voltage=230, freq=50, country=\"St. Vincent and the Grenadines\"),\n \"es\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Spain\"),\n \"my\": CountryPower(plugs=(\"C\", \"G\", \"M\"), voltage=230, freq=50, country=\"Malaysia\"),\n \"lc\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"St. Lucia\"),\n \"tm\": CountryPower(plugs=(\"B\", \"C\", \"F\"), voltage=220, freq=50, country=\"Turkmenistan\"),\n \"pe\": CountryPower(plugs=(\"A\", \"B\", \"C\"), voltage=220, freq=60, country=\"Peru\"),\n \"ua\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Ukraine\"),\n \"eg\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Egypt\"),\n \"sb\": CountryPower(plugs=(\"I\", \"G\"), voltage=220, freq=50, country=\"Solomon Islands\"),\n \"to\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Tonga\"),\n \"fr\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"France\"),\n \"ng\": CountryPower(plugs=(\"D\", \"G\"), voltage=240, freq=50, country=\"Nigeria\"),\n \"sh\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Saint Helena, Ascension and Tristan da Cunha\"),\n \"mw\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Malawi\"),\n \"ms\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Montserrat\"),\n \"ae\": CountryPower(plugs=(\"C\", \"D\", \"G\"), voltage=220, freq=50, country=\"United Arab Emirates\"),\n \"nl\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Netherlands\"),\n \"id\": CountryPower(plugs=(\"C\", \"F\", \"G\"), voltage=230, freq=50, country=\"Indonesia\"),\n \"ru\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Russia\"),\n \"ar\": CountryPower(plugs=(\"C\", \"I\"), voltage=220, freq=50, country=\"Argentina\"),\n \"bn\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Brunei\"),\n \"pw\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Palau\"),\n \"kg\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Kyrgyzstan\"),\n \"bh\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Bahrain\"),\n \"ml\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Mali\"),\n \"it\": CountryPower(plugs=(\"C\", \"F\", \"L\"), voltage=230, freq=50, country=\"Italy\"),\n \"sa\": CountryPower(plugs=(\"A\", \"B\", \"G\"), voltage=220, freq=60, country=\"Saudi Arabia\"),\n \"ag\": CountryPower(plugs=(\"A\", \"B\"), voltage=230, freq=60, country=\"Antigua and Barbuda\"),\n \"mr\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Mauritania\"),\n \"om\": CountryPower(plugs=(\"C\", \"G\"), voltage=240, freq=50, country=\"Oman\"),\n \"lk\": CountryPower(plugs=(\"D\", \"G\", \"M\"), voltage=230, freq=50, country=\"Sri Lanka\"),\n \"er\": CountryPower(plugs=(\"C\", \"L\"), voltage=230, freq=50, country=\"Eritrea\"),\n \"mk\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Macedonia\"),\n \"ni\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Nicaragua\"),\n \"ch\": CountryPower(plugs=(\"C\", \"J\"), voltage=230, freq=50, country=\"Switzerland\"),\n \"ca\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Canada\"),\n \"cr\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Costa Rica\")\n}\n\nindustrial_power = {\n \"at\": CountryPower(voltage=TUP_400, freq=50, country=\"Austria\"),\n \"bj\": CountryPower(voltage=TUP_380, freq=50, country=\"Benin\"),\n \"gh\": CountryPower(voltage=TUP_400, freq=50, country=\"Ghana\"),\n \"sc\": CountryPower(voltage=TUP_240, freq=50, country=\"Seychelles\"),\n \"bg\": CountryPower(voltage=TUP_400, freq=50, country=\"Bulgaria\"),\n \"me\": CountryPower(voltage=TUP_400, freq=50, country=\"Montenegro\"),\n \"fo\": CountryPower(voltage=TUP_400, freq=50, country=\"Faeroe Islands\"),\n \"iq\": CountryPower(voltage=TUP_400, freq=50, country=\"Iraq\"),\n \"ne\": CountryPower(voltage=TUP_380, freq=50, country=\"Niger\"),\n \"za\": CountryPower(voltage=TUP_400, freq=50, country=\"South Africa\"),\n \"az\": CountryPower(voltage=TUP_380, freq=50, country=\"Azerbaijan\"),\n \"so\": CountryPower(voltage=TUP_380, freq=50, country=\"Somalia\"),\n \"sn\": CountryPower(voltage=TUP_400, freq=50, country=\"Senegal\"),\n \"np\": CountryPower(voltage=TUP_400, freq=50, country=\"Nepal\"),\n \"sl\": CountryPower(voltage=TUP_400, freq=50, country=\"Sierra Leone\"),\n \"be\": CountryPower(voltage=TUP_400, freq=50, country=\"Belgium\"),\n \"vg\": CountryPower(voltage=TUP_190, freq=60, country=\"British Virgin Islands\"),\n \"bz\": CountryPower(voltage=(190, CONST_380), freq=60, country=\"Belize\"),\n \"tw\": CountryPower(voltage=(220,), freq=60, country=\"Taiwan\"),\n \"bf\": CountryPower(voltage=TUP_380, freq=50, country=\"Burkina Faso\"),\n \"ao\": CountryPower(voltage=TUP_380, freq=50, country=\"Angola\"),\n \"ee\": CountryPower(voltage=TUP_400, freq=50, country=\"Estonia\"),\n \"bs\": CountryPower(voltage=TUP_208, freq=60, country=\"Bahamas\"),\n \"ir\": CountryPower(voltage=TUP_400, freq=50, country=\"Iran\"),\n \"sv\": CountryPower(voltage=(200,), freq=60, country=\"El Salvador\"),\n \"am\": CountryPower(voltage=TUP_400, freq=50, country=\"Armenia\"),\n \"is\": CountryPower(voltage=TUP_400, freq=50, country=\"Iceland\"),\n \"uy\": CountryPower(voltage=TUP_380, freq=50, country=\"Uruguay\"),\n \"mc\": CountryPower(voltage=TUP_400, freq=50, country=\"Monaco\"),\n \"jm\": CountryPower(voltage=TUP_190, freq=50, country=\"Jamaica\"),\n \"im\": CountryPower(voltage=TUP_415, freq=50, country=\"Isle of Man\"),\n \"dm\": CountryPower(voltage=TUP_400, freq=50, country=\"Dominica\"),\n \"mu\": CountryPower(voltage=TUP_400, freq=50, country=\"Mauritius\"),\n \"cz\": CountryPower(voltage=TUP_400, freq=50, country=\"Czech Republic\"),\n \"kh\": CountryPower(voltage=TUP_400, freq=50, country=\"Cambodia\"),\n \"cf\": CountryPower(voltage=TUP_380, freq=50, country=\"Central African Republic\"),\n \"se\": CountryPower(voltage=TUP_400, freq=50, country=\"Sweden\"),\n \"uz\": CountryPower(voltage=TUP_380, freq=50, country=\"Uzbekistan\"),\n \"sk\": CountryPower(voltage=TUP_400, freq=50, country=\"Slovakia\"),\n \"ky\": CountryPower(voltage=TUP_240, freq=60, country=\"Cayman Islands\"),\n \"tn\": CountryPower(voltage=TUP_400, freq=50, country=\"Tunisia\"),\n \"hu\": CountryPower(voltage=TUP_400, freq=50, country=\"Hungary\"),\n \"af\": CountryPower(voltage=TUP_380, freq=50, country=\"Afghanistan\"),\n \"tc\": CountryPower(voltage=TUP_240, freq=60, country=\"Turks and Caicos Islands\"),\n \"et\": CountryPower(voltage=TUP_380, freq=50, country=\"Ethiopia\"),\n \"sd\": CountryPower(voltage=TUP_400, freq=50, country=\"Sudan\"),\n \"ad\": CountryPower(voltage=TUP_400, freq=50, country=\"Andorra\"),\n \"hn\": CountryPower(voltage=(208, 230, 240, 460, CONST_480), freq=60, country=\"Honduras\"),\n \"ls\": CountryPower(voltage=TUP_380, freq=50, country=\"Lesotho\"),\n \"na\": CountryPower(voltage=TUP_380, freq=50, country=\"Namibia\"),\n \"pl\": CountryPower(voltage=TUP_400, freq=50, country=\"Poland\"),\n \"bt\": CountryPower(voltage=TUP_400, freq=50, country=\"Bhutan\"),\n \"sa\": CountryPower(voltage=TUP_400, freq=60, country=\"Saudi Arabia\"),\n \"no\": CountryPower(voltage=(230, 400), freq=50, country=\"Norway\"),\n \"fk\": CountryPower(voltage=TUP_415, freq=50, country=\"Falkland Islands\"),\n \"ye\": CountryPower(voltage=TUP_400, freq=50, country=\"Yemen\"),\n \"gi\": CountryPower(voltage=TUP_400, freq=50, country=\"Gibraltar\"),\n \"md\": CountryPower(voltage=TUP_400, freq=50, country=\"Moldova\"),\n \"cn\": CountryPower(voltage=TUP_380, freq=50, country=\"China\"),\n \"gm\": CountryPower(voltage=TUP_400, freq=50, country=\"Gambia\"),\n \"sg\": CountryPower(voltage=TUP_400, freq=50, country=\"Singapore\"),\n \"tj\": CountryPower(voltage=TUP_380, freq=50, country=\"Tajikistan\"),\n \"gt\": CountryPower(voltage=TUP_208, freq=60, country=\"Guatemala\"),\n \"ma\": CountryPower(voltage=TUP_380, freq=50, country=\"Morocco\"),\n \"mv\": CountryPower(voltage=TUP_400, freq=50, country=\"Maldives\"),\n \"ga\": CountryPower(voltage=TUP_380, freq=50, country=\"Gabon\"),\n \"bo\": CountryPower(voltage=TUP_400, freq=50, country=\"Bolivia\"),\n \"ly\": CountryPower(voltage=TUP_400, freq=50, country=\"Libya\"),\n \"rw\": CountryPower(voltage=TUP_400, freq=50, country=\"Rwanda\"),\n \"cg\": CountryPower(voltage=TUP_400, freq=50, country=\"People's Republic of Congo\"),\n \"kz\": CountryPower(voltage=TUP_380, freq=50, country=\"Kazakhstan\"),\n \"jp\": CountryPower(voltage=(200,), freq=50, country=\"Japan\"),\n \"co\": CountryPower(voltage=(220, 440), freq=60, country=\"Colombia\"),\n \"sm\": CountryPower(voltage=TUP_400, freq=50, country=\"San Marino\"),\n \"rs\": CountryPower(voltage=TUP_400, freq=50, country=\"Serbia\"),\n \"gw\": CountryPower(voltage=TUP_380, freq=50, country=\"Guinea-Bissau\"),\n \"kr\": CountryPower(voltage=TUP_380, freq=60, country=\"South Korea\"),\n \"py\": CountryPower(voltage=TUP_380, freq=50, country=\"Paraguay\"),\n \"lt\": CountryPower(voltage=TUP_400, freq=50, country=\"Lithuania\"),\n \"tr\": CountryPower(voltage=TUP_400, freq=50, country=\"Turkey\"),\n \"ss\": CountryPower(voltage=TUP_400, freq=50, country=\"South Sudan\"),\n \"ba\": CountryPower(voltage=TUP_400, freq=50, country=\"Bosnia & Herzegovina\"),\n \"vn\": CountryPower(voltage=TUP_380, freq=50, country=\"Vietnam\"),\n \"do\": CountryPower(voltage=(120, 208, 277, 480), freq=60, country=\"Dominican Republic\"),\n \"pk\": CountryPower(voltage=TUP_400, freq=50, country=\"Pakistan\"),\n \"li\": CountryPower(voltage=TUP_400, freq=50, country=\"Liechtenstein\"),\n \"mz\": CountryPower(voltage=TUP_380, freq=50, country=\"Mozambique\"),\n \"au\": CountryPower(voltage=TUP_400, freq=50, country=\"Australia\"),\n \"ws\": CountryPower(voltage=TUP_400, freq=50, country=\"Samoa\"),\n \"sr\": CountryPower(voltage=(220, 400,), freq=60, country=\"Suriname\"),\n \"mn\": CountryPower(voltage=TUP_400, freq=50, country=\"Mongolia\"),\n \"bw\": CountryPower(voltage=TUP_400, freq=50, country=\"Botswana\"),\n \"gb\": CountryPower(voltage=TUP_415, freq=50, country=\"United Kingdom\"),\n \"pg\": CountryPower(voltage=TUP_415, freq=50, country=\"Papua New Guinea\"),\n \"dj\": CountryPower(voltage=TUP_380, freq=50, country=\"Djibouti\"),\n \"th\": CountryPower(voltage=TUP_400, freq=50, country=\"Thailand\"),\n \"us\": CountryPower(voltage=(120, 208, 277, 480, 120, 240, 240, CONST_480), freq=60, country=\"United States of America\"),\n \"gr\": CountryPower(voltage=TUP_400, freq=50, country=\"Greece\"),\n \"ug\": CountryPower(voltage=TUP_415, freq=50, country=\"Uganda\"),\n \"ie\": CountryPower(voltage=TUP_415, freq=50, country=\"Ireland\"),\n \"tg\": CountryPower(voltage=TUP_380, freq=50, country=\"Togo\"),\n \"td\": CountryPower(voltage=TUP_380, freq=50, country=\"Chad\"),\n \"la\": CountryPower(voltage=TUP_400, freq=50, country=\"Laos\"),\n \"sy\": CountryPower(voltage=TUP_380, freq=50, country=\"Syria\"),\n \"bm\": CountryPower(voltage=TUP_208, freq=60, country=\"Bermuda\"),\n \"il\": CountryPower(voltage=TUP_400, freq=50, country=\"Israel\"),\n \"nz\": CountryPower(voltage=TUP_400, freq=50, country=\"New Zealand\"),\n \"mg\": CountryPower(voltage=TUP_380, freq=50, country=\"Madagascar\"),\n \"ve\": CountryPower(voltage=(120,), freq=60, country=\"Venezuela\"),\n \"dk\": CountryPower(voltage=TUP_400, freq=50, country=\"Denmark\"),\n \"lb\": CountryPower(voltage=TUP_400, freq=50, country=\"Lebanon\"),\n \"kp\": CountryPower(voltage=TUP_380, freq=50, country=\"North Korea\"),\n \"vu\": CountryPower(voltage=TUP_400, freq=50, country=\"Vanuatu\"),\n \"cu\": CountryPower(voltage=(190, 440), freq=60, country=\"Cuba\"),\n \"kw\": CountryPower(voltage=TUP_415, freq=50, country=\"Kuwait\"),\n \"cd\": CountryPower(voltage=TUP_380, freq=50, country=\"Democratic Republic of Congo\"),\n \"nr\": CountryPower(voltage=TUP_415, freq=50, country=\"Nauru\"),\n \"si\": CountryPower(voltage=TUP_400, freq=50, country=\"Slovenia\"),\n \"mt\": CountryPower(voltage=TUP_400, freq=50, country=\"Malta\"),\n \"bd\": CountryPower(voltage=TUP_380, freq=50, country=\"Bangladesh\"),\n \"al\": CountryPower(voltage=TUP_400, freq=50, country=\"Albania\"),\n \"ec\": CountryPower(voltage=TUP_208, freq=60, country=\"Ecuador\"),\n \"gy\": CountryPower(voltage=TUP_190, freq=60, country=\"Guyana\"),\n \"bb\": CountryPower(voltage=(200,), freq=50, country=\"Barbados\"),\n \"ke\": CountryPower(voltage=TUP_415, freq=50, country=\"Kenya\"),\n \"mx\": CountryPower(voltage=(220, CONST_480), freq=60, country=\"Mexico\"),\n \"gn\": CountryPower(voltage=TUP_380, freq=50, country=\"Guinea\"),\n \"bi\": CountryPower(voltage=TUP_380, freq=50, country=\"Burundi\"),\n \"lv\": CountryPower(voltage=TUP_400, freq=50, country=\"Latvia\"),\n \"fj\": CountryPower(voltage=TUP_415, freq=50, country=\"Fiji\"),\n \"ci\": CountryPower(voltage=TUP_380, freq=50, country=\"Côte d’Ivoire\"),\n \"ai\": CountryPower(voltage=(120, 208, 127, 220, 240, 415), freq=60, country=\"Anguilla\"),\n \"gu\": CountryPower(voltage=TUP_190, freq=60, country=\"Guam\"),\n \"lr\": CountryPower(voltage=TUP_208, freq=60, country=\"Liberia\"),\n \"br\": CountryPower(voltage=(220, 380), freq=60, country=\"Brazil\"),\n \"cv\": CountryPower(voltage=TUP_400, freq=50, country=\"Cape Verde\"),\n \"cl\": CountryPower(voltage=TUP_380, freq=50, country=\"Chile\"),\n \"in\": CountryPower(voltage=TUP_400, freq=50, country=\"India\"),\n \"tt\": CountryPower(voltage=(115, 230, 230, 400), freq=60, country=\"Trinidad & Tobago\"),\n \"de\": CountryPower(voltage=TUP_400, freq=50, country=\"Germany\"),\n \"pa\": CountryPower(voltage=TUP_240, freq=60, country=\"Panama\"),\n \"qa\": CountryPower(voltage=TUP_415, freq=50, country=\"Qatar\"),\n \"ph\": CountryPower(voltage=TUP_380, freq=60, country=\"Philippines\"),\n \"jo\": CountryPower(voltage=TUP_400, freq=50, country=\"Jordan\"),\n \"mm\": CountryPower(voltage=TUP_400, freq=50, country=\"Myanmar\"),\n \"gd\": CountryPower(voltage=TUP_400, freq=50, country=\"Grenada\"),\n \"st\": CountryPower(voltage=TUP_400, freq=50, country=\"São Tomé and Príncipe\"),\n \"sz\": CountryPower(voltage=TUP_400, freq=50, country=\"Swaziland\"),\n \"ro\": CountryPower(voltage=TUP_400, freq=50, country=\"Romania\"),\n \"xk\": CountryPower(voltage=(230, 400), freq=50, country=\"Kosovo\"),\n \"cy\": CountryPower(voltage=TUP_400, freq=50, country=\"Cyprus\"),\n \"dz\": CountryPower(voltage=TUP_400, freq=50, country=\"Algeria\"),\n \"zm\": CountryPower(voltage=TUP_400, freq=50, country=\"Zambia\"),\n \"by\": CountryPower(voltage=TUP_380, freq=50, country=\"Belarus\"),\n \"hr\": CountryPower(voltage=TUP_400, freq=50, country=\"Croatia\"),\n \"lu\": CountryPower(voltage=TUP_400, freq=50, country=\"Luxembourg\"),\n \"fi\": CountryPower(voltage=TUP_400, freq=50, country=\"Finland\"),\n \"zw\": CountryPower(voltage=TUP_415, freq=50, country=\"Zimbabwe\"),\n \"km\": CountryPower(voltage=TUP_380, freq=50, country=\"Comoros\"),\n \"tl\": CountryPower(voltage=TUP_380, freq=50, country=\"East Timor\"),\n \"tz\": CountryPower(voltage=TUP_415, freq=50, country=\"Tanzania\"),\n \"ht\": CountryPower(voltage=TUP_190, freq=60, country=\"Haiti\"),\n \"vc\": CountryPower(voltage=TUP_400, freq=50, country=\"Saint Vincent and the Grenadines\"),\n \"es\": CountryPower(voltage=TUP_400, freq=50, country=\"Spain\"),\n \"my\": CountryPower(voltage=TUP_415, freq=50, country=\"Malaysia\"),\n \"lc\": CountryPower(voltage=TUP_400, freq=50, country=\"Saint Lucia\"),\n \"tm\": CountryPower(voltage=TUP_380, freq=50, country=\"Turkmenistan\"),\n \"pe\": CountryPower(voltage=(220,), freq=60, country=\"Peru\"),\n \"ua\": CountryPower(voltage=TUP_400, freq=50, country=\"Ukraine\"),\n \"eg\": CountryPower(voltage=TUP_380, freq=50, country=\"Egypt\"),\n \"to\": CountryPower(voltage=TUP_415, freq=50, country=\"Tonga\"),\n \"fr\": CountryPower(voltage=TUP_400, freq=50, country=\"France\"),\n \"ng\": CountryPower(voltage=TUP_415, freq=50, country=\"Nigeria\"),\n \"mw\": CountryPower(voltage=TUP_400, freq=50, country=\"Malawi\"),\n \"ms\": CountryPower(voltage=TUP_400, freq=60, country=\"Montserrat\"),\n \"ae\": CountryPower(voltage=TUP_400, freq=50, country=\"United Arab Emirates\"),\n \"nl\": CountryPower(voltage=TUP_400, freq=50, country=\"Netherlands\"),\n \"id\": CountryPower(voltage=TUP_400, freq=50, country=\"Indonesia\"),\n \"ru\": CountryPower(voltage=TUP_380, freq=50, country=\"Russia\"),\n \"ar\": CountryPower(voltage=TUP_380, freq=50, country=\"Argentina\"),\n \"bn\": CountryPower(voltage=TUP_415, freq=50, country=\"Brunei\"),\n \"pw\": CountryPower(voltage=TUP_208, freq=60, country=\"Palau\"),\n \"kg\": CountryPower(voltage=TUP_380, freq=50, country=\"Kyrgyzstan\"),\n \"bh\": CountryPower(voltage=TUP_400, freq=50, country=\"Bahrain\"),\n \"ml\": CountryPower(voltage=TUP_380, freq=50, country=\"Mali\"),\n \"it\": CountryPower(voltage=TUP_400, freq=50, country=\"Italy\"),\n \"cm\": CountryPower(voltage=TUP_380, freq=50, country=\"Cameroon\"),\n \"ag\": CountryPower(voltage=TUP_400, freq=60, country=\"Antigua and Barbuda\"),\n \"mr\": CountryPower(voltage=(220,), freq=50, country=\"Mauritania\"),\n \"om\": CountryPower(voltage=TUP_415, freq=50, country=\"Oman\"),\n \"lk\": CountryPower(voltage=TUP_400, freq=50, country=\"Sri Lanka\"),\n \"er\": CountryPower(voltage=TUP_400, freq=50, country=\"Eritrea\"),\n \"mk\": CountryPower(voltage=TUP_400, freq=50, country=\"Macedonia, Republic of\"),\n \"ni\": CountryPower(voltage=TUP_208, freq=60, country=\"Nicaragua\"),\n \"ch\": CountryPower(voltage=TUP_400, freq=50, country=\"Switzerland\"),\n \"ca\": CountryPower(voltage=(120, 208, 240, CONST_480, 347, 600), freq=60, country=\"Canada\"),\n \"cr\": CountryPower(voltage=TUP_240, freq=60, country=\"Costa Rica\")\n}\n\nelectrical_plug_types = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\"]\n\nvoltages_1_phase_residential = [100, 110, 115, 120, 127, 220, 230, 240]\n\nvoltages_3_phase = [120, 190, 200, 208, 220, 230, 240, 277, 380, 400, 415, 440, 480]\n\nresidential_power_frequencies = [50, 60]", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 31977}, "tests/test_safety_valve.py::92": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/numerics/__init__.py", "fluids/safety_valve.py"], "used_names": ["API520_Kv", "assert_close", "assert_close1d", "pytest"], "enclosing_function": "test_API520_Kv", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\n\n# Source: fluids/safety_valve.py\ndef API520_Kv(Re, edition=TENTH_EDITION):\n r\"\"\"Calculates correction due to viscosity for liquid flow for use in\n API 520 relief valve sizing.\n\n From the 7th to 9th editions, the formula for this calculation is as\n follows:\n\n .. math::\n K_v = \\left(0.9935 + \\frac{2.878}{Re^{0.5}} + \\frac{342.75}\n {Re^{1.5}}\\right)^{-1}\n\n Startign in the 10th edition, the formula is\n\n .. math::\n K_v = \\left(1 + \\frac{170}{Re}\\right)^{-0.5}\n\n In the 10th edition, the formula is applicable for Re > 80. It is also\n recommended there that if the viscosity is < 0.1 Pa*s, this correction\n should be set to 1.\n\n Parameters\n ----------\n Re : float\n Reynolds number for flow out the valve [-]\n edition : str, optional\n One of '10E', '7E', [-]\n\n Returns\n -------\n Kv : float\n Correction due to viscosity [-]\n\n Notes\n -----\n Reynolds number in the standard is defined as follows, with Q in L/min, G1\n as specific gravity, mu in centipoise, and area in mm^2:\n\n .. math::\n Re = \\frac{Q(18800G_1)}{\\mu \\sqrt{A}}\n\n The constant 18800 is derived as follows, combining multiple unit\n conversions and the formula from diameter from area together. The precise\n value is shown below.\n\n >>> from scipy.constants import *\n >>> liter/minute*1000./(0.001*(milli**2)**0.5)*sqrt(4/pi)\n 18806.319451591\n\n Note that 4 formulas are provided in API 520 part 1; two metric and two\n imperial. One pair of formulas uses viscosity in conventional units; the\n other uses it in Saybolt Universal Seconds. A conversion is essentially\n embedded in the the Saybolt Universal Seconds formula. A more precise\n conversion can be obtained from\n :obj:`chemicals.viscosity.viscosity_converter`.\n\n In both editions, if the formula is used below the recommended Re range\n and into the very low Re region this correction tends towards 0.\n\n In the 10th edition, the formula tends to 1 exactly as Re increases. In the\n 7th edition, the formula can actually produce corrections above 1; this is\n handled by truncating the factor to 1.\n\n Examples\n --------\n From [1]_ 7E, checked with example 5.\n\n >>> API520_Kv(100, edition='7E')\n 0.615744589\n\n From [2]_ 10E, checked with example 5:\n\n >>> API520_Kv(4525, edition='10E')\n 0.9817287137013179\n\n Example in [3]_, using the 7th edition formula:\n\n >>> API520_Kv(2110, edition='7E')\n 0.943671807\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection, 7E\n .. [2] API Standard 520, Part 1 - Sizing and Selection, 10E\n .. [3] CCPS. Guidelines for Pressure Relief and Effluent Handling Systems.\n 2nd edition. New York, NY: Wiley-AIChE, 2017.\n \"\"\"\n if edition == SEVENTH_EDITION:\n factor = 1.0/(0.9935 + 2.878/sqrt(Re) + 342.75/(Re*sqrt(Re)))\n if factor > 1.0:\n factor = 1.0\n return factor\n elif edition == TENTH_EDITION:\n return 1.0/sqrt(170.0/Re + 1.0)\n else:\n raise ValueError(\"Acceptable editions are '7E', '10E'\")", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 3982}, "tests/test_units.py::129": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/units.py"], "used_names": ["convert_input", "pytest", "u"], "enclosing_function": "test_convert_input", "extracted_code": "# Source: fluids/units.py\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 3436}, "tests/test_core.py::327": {"resolved_imports": ["fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["F2C", "assert_close", "assert_close1d"], "enclosing_function": "test_fahrenheit_to_celcius", "extracted_code": "# Source: fluids/core.py\ndef F2C(F: float) -> float:\n \"\"\"Convert Fahrenheit to Celsius.\n\n Parameters\n ----------\n F : float\n Fahrenheit temperature to be converted.\n\n Returns\n -------\n C : float\n Equivalent Celsius temperature.\n\n Notes\n -----\n Computes ``C = (F - 32) / 1.8``.\n\n Examples\n --------\n >>> F2C(-40.0)\n -40.0\n \"\"\"\n return (F - 32.0) / 1.8\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1261}, "tests/test_design_climate.py::87": {"resolved_imports": ["fluids/design_climate.py", "fluids/numerics/__init__.py"], "used_names": ["get_latlongs", "get_stations"], "enclosing_function": "test_data", "extracted_code": "# Source: fluids/design_climate.py\ndef get_stations():\n \"\"\"Get the list of weather stations.\"\"\"\n if _stations is None:\n _load_station_data()\n return _stations\n\ndef get_latlongs():\n \"\"\"Get the array of station coordinates.\"\"\"\n if _latlongs is None:\n _load_station_data()\n return _latlongs", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 319}, "tests/test_flow_meter.py::511": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/flow_meter.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "nozzle_expansibility"], "enclosing_function": "test_nozzle_expansibility", "extracted_code": "# Source: fluids/flow_meter.py\ndef nozzle_expansibility(D: float, Do: float, P1: float, P2: float, k: float, beta: float | None=None) -> float:\n r\"\"\"Calculates the expansibility factor for a nozzle or venturi nozzle,\n based on the geometry of the plate, measured pressures of the orifice, and\n the isentropic exponent of the fluid.\n\n .. math::\n \\epsilon = \\left\\{\\left(\\frac{\\kappa \\tau^{2/\\kappa}}{\\kappa-1}\\right)\n \\left(\\frac{1 - \\beta^4}{1 - \\beta^4 \\tau^{2/\\kappa}}\\right)\n \\left[\\frac{1 - \\tau^{(\\kappa-1)/\\kappa}}{1 - \\tau}\n \\right] \\right\\}^{0.5}\n\n Parameters\n ----------\n D : float\n Upstream internal pipe diameter, [m]\n Do : float\n Diameter of orifice of the venturi or nozzle, [m]\n P1 : float\n Static pressure of fluid upstream of orifice at the cross-section of\n the pressure tap, [Pa]\n P2 : float\n Static pressure of fluid downstream of orifice at the cross-section of\n the pressure tap, [Pa]\n k : float\n Isentropic exponent of fluid, [-]\n beta : float, optional\n Optional `beta` ratio, which is useful to specify for wedge meters or\n flow meters which have a different beta ratio calculation, [-]\n\n Returns\n -------\n expansibility : float\n Expansibility factor (1 for incompressible fluids, less than 1 for\n real fluids), [-]\n\n Notes\n -----\n This formula was determined for the range of P2/P1 >= 0.75.\n\n Mathematically the equation cannot be evaluated at `k` = 1, but if the\n limit of the equation is taken the following equation is obtained and is\n implemented:\n\n\n .. math::\n \\epsilon = \\sqrt{\\frac{- D^{4} P_{1} P_{2}^{2} \\log{\\left(\\frac{P_{2}}\n {P_{1}} \\right)} + Do^{4} P_{1} P_{2}^{2} \\log{\\left(\\frac{P_{2}}{P_{1}}\n \\right)}}{D^{4} P_{1}^{3} - D^{4} P_{1}^{2} P_{2} - Do^{4} P_{1}\n P_{2}^{2} + Do^{4} P_{2}^{3}}}\n\n Note also there is a small amount of floating-point error around the range\n of `k` ~1+1e-5 to ~1-1e-5, starting with 1e-7 and increasing to the point\n of giving values larger than 1 or zero in the `k` ~1+1e-12 to ~1-1e-12\n range.\n\n Examples\n --------\n >>> nozzle_expansibility(D=0.0739, Do=0.0222, P1=1E5, P2=9.9E4, k=1.4)\n 0.994570234456\n\n References\n ----------\n .. [1] American Society of Mechanical Engineers. Mfc-3M-2004 Measurement\n Of Fluid Flow In Pipes Using Orifice, Nozzle, And Venturi. ASME, 2001.\n .. [2] ISO 5167-3:2003 - Measurement of Fluid Flow by Means of Pressure\n Differential Devices Inserted in Circular Cross-Section Conduits Running\n Full -- Part 3: Nozzles and Venturi Nozzles.\n \"\"\"\n if beta is None:\n beta = Do/D\n beta2 = beta*beta\n beta4 = beta2*beta2\n tau = P2/P1\n if k == 1.0:\n \"\"\"Avoid a zero division error:\n from sympy import *\n D, Do, P1, P2, k = symbols('D, Do, P1, P2, k')\n beta = Do/D\n tau = P2/P1\n term1 = k*tau**(2/k )/(k - 1)\n term2 = (1 - beta**4)/(1 - beta**4*tau**(2/k))\n term3 = (1 - tau**((k - 1)/k))/(1 - tau)\n val= sqrt(term1*term2*term3)\n print(simplify(limit((term1*term2*term3), k, 1)))\n \"\"\"\n limit_val = (P1*P2**2*(-D**4 + Do**4)*log(P2/P1)/(D**4*P1**3\n - D**4*P1**2*P2 - Do**4*P1*P2**2 + Do**4*P2**3))\n return sqrt(limit_val)\n\n term1 = k*tau**(2.0/k)/(k - 1.0)\n term2 = (1.0 - beta4)/(1.0 - beta4*tau**(2.0/k))\n if tau == 1.0:\n \"\"\"Avoid a zero division error.\n Obtained with:\n from sympy import *\n tau, k = symbols('tau, k')\n expr = (1 - tau**((k - 1)/k))/(1 - tau)\n limit(expr, tau, 1)\n \"\"\"\n term3 = (k - 1.0)/k\n else:\n # This form of the equation is mathematically equivalent but\n # does not have issues where k = 1.\n term3 = (P1 - P2*(tau)**(-1.0/k))/(P1 - P2)\n # term3 = (1.0 - tau**((k - 1.0)/k))/(1.0 - tau)\n return sqrt(term1*term2*term3)\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 4646}, "tests/test_geometry.py::634": {"resolved_imports": ["fluids/__init__.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": ["A_partial_circle", "SA_partial_cylindrical_body", "V_tank", "assert_close", "pi", "pytest"], "enclosing_function": "test_V_tank_branch_coverage", "extracted_code": "# Source: fluids/constants/__init__.py\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 1945}, "tests/test_geometry.py::1175": {"resolved_imports": ["fluids/__init__.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": ["AirCooledExchanger", "assert_close", "inch"], "enclosing_function": "test_AirCooledExchangerFull", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 607}, "tests/test_geometry.py::1496": {"resolved_imports": ["fluids/__init__.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": ["PlateExchanger", "assert_close", "plate_enlargement_factor"], "enclosing_function": "test_PlateExchanger", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 607}, "tests/test_geometry.py::1513": {"resolved_imports": ["fluids/__init__.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": ["PlateExchanger", "assert_close", "plate_enlargement_factor"], "enclosing_function": "test_PlateExchanger", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 607}, "tests/test_geometry.py::1514": {"resolved_imports": ["fluids/__init__.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": ["PlateExchanger", "assert_close", "plate_enlargement_factor"], "enclosing_function": "test_PlateExchanger", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 607}, "tests/test_geometry.py::1594": {"resolved_imports": ["fluids/__init__.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": ["RectangularOffsetStripFinExchanger", "assert_close"], "enclosing_function": "test_RectangularOffsetStripFinExchanger", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 607}, "tests/test_geometry.py::1445": {"resolved_imports": ["fluids/__init__.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": ["HelicalCoil", "assert_close", "pytest"], "enclosing_function": "test_HelicalCoil", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 607}, "tests/test_jet_pump.py::249": {"resolved_imports": ["fluids/__init__.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": [], "enclosing_function": "test_liquid_jet_pump_examples_round_robin_Ex3", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_jet_pump.py::277": {"resolved_imports": ["fluids/__init__.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": [], "enclosing_function": "test_liquid_jet_pump_examples_round_robin_Ex3", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_numerics.py::1921": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["assert_close1d", "exp", "jacobian", "newton_system"], "enclosing_function": "test_basic_newton_system", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef jacobian(f, x0, scalar=True, perturbation=1e-9, zero_offset=1e-7, args=(), base=None,\n **kwargs):\n \"\"\"def test_fun(x):\n\n # test case - 2 inputs, 3 outputs - should work fine\n x2 = x[0]*x[0]\n return np.array([x2*exp(x[1]), x2*sin(x[1]), x2*cos(x[1])])\n\n def easy_fun(x):\n x = x[0]\n return 5*x*x - 3*x - 100\n \"\"\"\n # For scalar - returns list, size of input variables\n # For vector - returns list of list - size of input variables * output variables\n # Could add backwards/complex, multiple evaluations, detection of poor condition\n # types and limits\n if base is None:\n base = f(x0, *args, **kwargs)\n if not scalar:\n base = list(base) # copy the base point\n x = list(x0)\n nx = len(x0)\n\n gradient = []\n for i in range(nx):\n delta = x0[i]*(perturbation)\n if delta == 0:\n delta = zero_offset\n\n x[i] += delta\n\n point = f(x, *args, **kwargs)\n if scalar:\n dy = (point - base)/delta\n gradient.append(dy)\n else:\n delta_inv = 1.0/delta\n dys = [delta_inv*(p - b) for p, b in zip(point, base)]\n gradient.append(dys)\n\n x[i] -= delta\n if not scalar:\n # Transpose to be in standard form\n return list(map(list, zip(*gradient)))\n return gradient\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\ndef newton_system(f, x0, jac, xtol=None, ytol=None, maxiter=100, damping=1.0,\n args=(), damping_func=None, line_search=False,\n require_progress=False, check_numbers=False,\n Armijo=False, Armijo_c1=1e-4,\n solve_func=py_solve, with_point=False, jac_error_allowed=False): # numba: delete\n# solve_func=np.linalg.solve): # numba: uncomment\n jac_also = True if jac == True else False # noqa: E712, SIM210\n\n\n if jac_also:\n fcur, j = f(x0, *args)\n else: # numba: delete\n fcur = f(x0, *args) # numba: delete\n N = len(fcur)\n\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n\n if xtol is None and (ytol is not None and err0 < ytol):\n return x0, 0\n\n\n x = x0\n if not jac_also: # numba: delete\n j = jac(x, *args) # numba: delete\n if check_numbers:# numba: delete\n j = check_jacobian(x=x0, j=j, func=f, jac_error_allowed=jac_error_allowed)# numba: delete\n factors = newton_line_search_factors if line_search else newton_line_search_factors_disabled\n jac_updated = True # numba: delete\n iteration = 1\n while iteration < maxiter:\n try:# numba: delete\n dx = solve_func(j, [-v for v in fcur]) # numba: delete\n except Exception as e:# numba: delete\n if jac_error_allowed:# numba: delete\n j = jacobian(f, x, scalar=False) # numba: delete\n dx = solve_func(j, [-v for v in fcur]) # numba: delete\n else:# numba: delete\n raise e# numba: delete\n# dx = solve_func(j, -fcur) # numba: uncomment\n for factor in factors:\n # print(factor)\n mult = factor*damping\n if damping_func is None:\n# xnew = x + dx*mult # numba: uncomment\n xnew = [xi + dxi*mult for xi, dxi in zip(x, dx)] # numba: delete\n else:\n xnew = damping_func(x, dx, damping*factor, *args)\n try: # numba: delete\n if jac_also: # numba: delete\n fnew, jnew = f(xnew, *args) # numba: delete\n jac_updated = True # numba: delete\n else: # numba: delete\n fnew = f(xnew, *args) # numba: delete\n # print(xnew, 'xnew')\n # print(fnew, 'fnew')\n do_next = False # numba: delete\n if check_numbers: # numba: delete\n for v in fnew: # numba: delete\n if isinf(v) or isnan(v): # numba: delete\n do_next = True # numba: delete\n if do_next and factor != factors[-1]:# numba: delete\n # print('math error, trying next point')\n continue# numba: delete\n except: # numba: delete\n # print(f'Line search calculation with point failed') # numba: delete\n continue # numba: delete\n# fnew, jnew = f(xnew, *args) # numba: uncomment\n err_new = 0.0\n for v in fnew:\n err_new += abs(v)\n if check_numbers:\n for v in fnew:\n if isinf(v) or isnan(v):\n raise ValueError(\"Cannot continue - math error in function value\")\n # print(f'Line search with error={err_new}, factor {mult}' )\n if err_new < err0:\n if Armijo:\n phi = 0.0\n for v in fnew:\n phi += v*v\n Armijo_lhs = phi\n\n phi0 = 0.0\n for v in fcur:\n phi0 += v*v\n\n derphi0 = 0.0\n for i in range(N):\n temp = 0.0\n for jidx in range(N):\n temp += fcur[jidx]*j[jidx][i]\n # Armijo_grad[i] = 2.0*temp\n derphi0 += 4.0*temp*temp\n\n # derphi0 = float(np.dot(Armijo_grad, Armijo_grad))\n Armijo_rhs = Armijo_c1*factor*derphi0 + phi0\n if Armijo_lhs <= Armijo_rhs:\n if not jac_also: # numba: delete\n jac_updated = False # numba: delete\n break\n # else:\n # print('lhs and rhs not same', Armijo_lhs, Armijo_rhs)\n else:\n if not jac_also: # numba: delete\n jac_updated = False # numba: delete\n break\n\n if (line_search and err_new > err0) and require_progress:\n raise ValueError(\"Completed line search without reducing the objective function error, cannot proceed\")\n\n fcur = fnew\n if err_new >= err0:\n # edge case, didn't make any progress but keep going\n if require_progress:\n raise ValueError(\"Completed line search without reducing the objective function error, cannot proceed\")\n else:# numba: delete\n if not jac_also: # numba: delete\n jnew = jac(xnew, *args) # numba: delete\n jac_updated = True # numba: delete\n # print(xnew)\n err0 = err_new\n x = xnew\n iteration += 1\n\n if xtol is not None:\n if (norm2(fcur) < xtol) and (ytol is None or err0 < ytol):\n break\n elif ytol is not None:\n if err0 < ytol:\n break\n if not jac_updated: # numba: delete\n jnew = jac(x, *args) # numba: delete\n if check_numbers:# numba: delete\n jnew = check_jacobian(x=xnew, j=jnew, func=f, jac_error_allowed=jac_error_allowed) # numba: delete\n # print('jnew', jnew)\n j = jnew\n jac_updated = False\n\n # if not jac_also: # numba: delete\n # j = jac(x, *args) # numba: delete\n\n if xtol is not None and norm2(fcur) > xtol:\n raise UnconvergedError(\"Failed to converge\")\n# raise UnconvergedError(\"Failed to converge; maxiter (%d) reached, value=%s\" %(maxiter, x))\n if ytol is not None:\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if err0 > ytol:\n# raise UnconvergedError(\"Failed to converge; maxiter (%d) reached, value=%s\" %(maxiter, x))\n raise UnconvergedError(\"Failed to converge\")\n if with_point: # numba: delete\n return x, iteration, fcur, j # numba: delete\n\n return x, iteration\n\nclass SolverInterface:\n __slots__ = (\n \"damping\",\n \"fval_iter\",\n \"hess_fval_count\",\n \"hess_iter\",\n \"hessian_method\",\n \"hessian_numpy\",\n \"jac_fval_count\",\n \"jac_iter\",\n \"jacobian_method\",\n \"jacobian_numpy\",\n \"jacobian_order\",\n \"jacobian_perturbation\",\n \"jacobian_zero_offset\",\n \"matrix_solver\",\n \"maxiter\",\n \"method\",\n \"minimizing\",\n \"objf\",\n \"objf_numpy\",\n \"objf_original\",\n \"original_jac\",\n \"scalar_objective\",\n \"solver_analytical_jac\",\n \"solver_numpy\",\n \"xtol\",\n \"ytol\",\n )\n\n def objf_counting(self, *args):\n self.fval_iter += 1\n return self.objf_original(*args)\n\n def objf_python_return_numpy(self, x, *args):\n # function only knows python, solver knows numpy\n self.fval_iter += 1\n return np.array(self.objf_original(x if type(x) is list else x.tolist(),\n *args))\n\n def objf_numpy_return_python(self, x, *args):\n # function only knows numpy, solver knows python\n self.fval_iter += 1\n return self.objf_original(np.array(x), *args).tolist()\n\n def objf_numpy_minimizing(self, x, *args):\n self.fval_iter += 1\n errs = self.objf_original(np.array(x), *args)\n tot = 0.0\n for v in errs:\n tot += v*v\n return float(tot)\n\n def objf_python_minimizing(self, x, *args):\n self.fval_iter += 1\n errs = self.objf_original(x if type(x) is list else x.tolist(), *args)\n tot = 0.0\n for v in errs:\n tot += v*v\n return tot\n\n def jac_minimizing(self, x, *args):\n fval = self.objf_original(x, *args)\n jval = self.original_jac(x, *args)\n N = len(fval)\n small_jac = [0.0]*N\n for i in range(N):\n temp = 0.0\n for j in range(N):\n temp += fval[j]*jval[j][i]\n small_jac[i] = 2.0*temp\n return small_jac\n\n def jac_minimizing_numpy(self, x, *args):\n fval = self.objf_original(x, *args)\n jval = self.original_jac(x, *args)\n return 2.0*np.dot(fval, jval)\n\n def objf_python_return_numpy_scalar(self, x, *args):\n self.fval_iter += 1\n return float(self.objf_original(x if type(x) is list else x.tolist(), *args))\n\n def objf_numpy_return_python_scalar(self, x, *args):\n self.fval_iter += 1\n return float(self.objf_original(np.array(x), *args))\n\n def __init__(self, method, objf, jac=None, xtol=1e-8, ytol=None, maxiter=100, damping=1.0,\n jacobian_method=\"python\", jacobian_perturbation=1e-9, jacobian_zero_offset=1e-7,\n hessian_method=\"python\",\n jacobian_order=1, objf_numpy=False, matrix_solver=py_solve, scalar_objective=False):\n self.method, self.objf_original, self.original_jac = method, objf, jac\n self.xtol, self.ytol, self.maxiter, self.damping = xtol, ytol, maxiter, damping\n\n (self.jacobian_perturbation, self.jacobian_zero_offset, self.jacobian_method,\n self.jacobian_order, self.hessian_method) = (jacobian_perturbation,\n jacobian_zero_offset,\n jacobian_method,\n jacobian_order,\n hessian_method)\n self.objf_numpy, self.matrix_solver = objf_numpy, matrix_solver\n\n\n if jacobian_method == \"analytical\":\n self.jacobian_numpy = objf_numpy\n else:\n self.jacobian_numpy = jacobian_method not in python_jacobians_set\n if hessian_method == \"analytical\":\n self.hessian_numpy = objf_numpy\n else:\n self.hessian_numpy = hessian_method not in python_hessians_set\n # whether or not the solver uses numpy\n self.solver_numpy = solver_numpy = method not in python_solvers_set\n\n self.minimizing = False\n self.fval_iter = self.jac_iter = self.jac_fval_count = self.hess_iter = self.hess_fval_count = 0\n self.scalar_objective = scalar_objective\n # whether or not the objf uses numpy\n # if jac is provided it is assumed it is in the same basis\n\n if self.scalar_objective:\n # Direct scalar minimization\n if solver_numpy:\n if not objf_numpy:\n self.objf = self.objf_python_return_numpy_scalar\n else:\n self.objf = self.objf_counting\n else:\n if objf_numpy:\n self.objf = self.objf_numpy_return_python_scalar\n else:\n self.objf = self.objf_counting\n else:\n\n if method in scipy_minimize_options_set:\n self.minimizing = True\n if jacobian_method == \"scipy\" and method in scipy_requires_jacobian_options_set:\n self.jacobian_method = \"python\"\n self.objf = self.objf_numpy_minimizing if objf_numpy else self.objf_python_minimizing\n elif solver_numpy:\n if not objf_numpy:\n self.objf = self.objf_python_return_numpy\n else:\n self.objf = self.objf_counting\n else:\n if objf_numpy:\n self.objf = self.objf_numpy_return_python\n else:\n self.objf = self.objf_counting\n\n if self.minimizing:\n if objf_numpy:\n self.solver_analytical_jac = self.jac_minimizing_numpy\n else:\n self.solver_analytical_jac = self.jac_minimizing\n else:\n self.solver_analytical_jac = self.original_jac\n\n\n\n\n\n def hessian(self, x, base=None, args=()):\n self.hess_iter += 1\n fval_iter, hessian_method, objf_numpy, hessian_numpy = self.fval_iter, self.hessian_method, self.objf_numpy, self.hessian_numpy\n return_numpy = type(x) is not list\n\n if self.scalar_objective:\n # For scalar objectives, always use the efficient scalar calculator\n if not self.hessian_numpy:\n x = x if type(x) is list else x.tolist()\n else:\n x = np.array(x)\n # Use the correct objf based on numpy/python preferences\n if self.objf_numpy:\n objf = self.objf_counting\n else:\n objf = self.objf_python_return_numpy if self.hessian_numpy else self.objf_counting\n\n h = hessian(objf, x, scalar=True,\n perturbation=self.jacobian_perturbation,\n zero_offset=self.jacobian_zero_offset,\n args=args)\n else:\n if hessian_method == \"analytical\":\n if objf_numpy and not return_numpy:\n x = np.array(x)\n elif return_numpy and not objf_numpy:\n x = x.tolist()\n raise NotImplementedError\n h = self.solver_analytical_hess(x, *args)\n else:\n # if the hessian method doesn't speak numpy, convert x to a list\n if not hessian_numpy:\n x = x if type(x) is list else x.tolist()\n else:\n x = np.array(x)\n # If the objf doesn't speak numpy but the hessian does, use the converter\n if self.minimizing:\n if objf_numpy:\n objf = self.objf_numpy_minimizing\n else:\n objf = self.objf_python_minimizing\n else:\n if not hessian_numpy:\n if objf_numpy:\n objf = self.objf_numpy_return_python\n else:\n objf = self.objf_counting\n else:\n if objf_numpy:\n objf = self.objf_counting\n else:\n objf = self.objf_python_return_numpy\n\n if hessian_method.startswith(\"numdifftools\"):\n import numdifftools as nd\n if hessian_method == \"python\":\n h = hessian(objf, x, scalar=self.minimizing, perturbation=1e-4,\n zero_offset=self.jacobian_zero_offset, args=args)\n\n elif hessian_method == \"numdifftools_forward\":\n h = nd.Hessian(objf, method=\"forward\")(x)\n elif hessian_method == \"numdifftools_reverse\":\n h = nd.Hessian(objf, method=\"reverse\")(x)\n elif hessian_method == \"numdifftools_central\":\n h = nd.Hessian(objf, method=\"central\")(x)\n\n # Up the hessian fval count, set the fval back\n self.hess_fval_count += self.fval_iter - fval_iter\n self.fval_iter = fval_iter\n\n if return_numpy:\n return np.array(h) if type(h) is list else h\n else:\n return h if type(h) is list else h.tolist()\n\n def jacobian(self, x, *args):\n \"\"\"\n jacobi - doesn't support jacobian_perturbation, jacobian_zero_offset, jacobian_order\n python - doesn't support jacobian_order\n \"\"\"\n self.jac_iter += 1\n fval_iter, jacobian_method, objf_numpy, jacobian_numpy = self.fval_iter, self.jacobian_method, self.objf_numpy, self.jacobian_numpy\n return_numpy = type(x) is not list\n if self.scalar_objective:\n # For scalar objectives, always use the efficient scalar calculator\n if not self.jacobian_numpy:\n x = x if type(x) is list else x.tolist()\n else:\n x = np.array(x)\n\n # Use the correct objf based on numpy/python preferences\n if self.objf_numpy:\n objf = self.objf_counting\n else:\n objf = self.objf_python_return_numpy if self.jacobian_numpy else self.objf_counting\n\n j = jacobian(objf, x, scalar=True,\n perturbation=self.jacobian_perturbation,\n zero_offset=self.jacobian_zero_offset,\n args=args)\n else:\n if jacobian_method == \"analytical\":\n if objf_numpy and not return_numpy:\n x = np.array(x)\n elif return_numpy and not objf_numpy:\n x = x.tolist()\n j = self.solver_analytical_jac(x, *args)\n else:\n # if the jacobian method doesn't speak numpy, convert x to a list\n if not jacobian_numpy:\n x = x if type(x) is list else x.tolist()\n else:\n x = np.array(x)\n # If the objf doesn't speak numpy but the jacobian does, use the converter\n if self.minimizing:\n if objf_numpy:\n objf = self.objf_numpy_minimizing\n else:\n objf = self.objf_python_minimizing\n else:\n if not jacobian_numpy:\n if objf_numpy:\n objf = self.objf_numpy_return_python\n else:\n objf = self.objf_counting\n else:\n if objf_numpy:\n objf = self.objf_counting\n else:\n objf = self.objf_python_return_numpy\n\n if jacobian_method.startswith(\"numdifftools\"):\n import numdifftools as nd\n numdifftools_func = nd.Gradient if self.minimizing else nd.Jacobian\n step = self.jacobian_perturbation*x\n step[np.where(step==0)] = self.jacobian_zero_offset\n elif jacobian_method.startswith(\"jacobi\"):\n from jacobi import jacobi\n if jacobian_method == \"python\":\n j = jacobian(objf, x, scalar=self.minimizing, perturbation=self.jacobian_perturbation,\n zero_offset=self.jacobian_zero_offset, args=args)\n\n elif jacobian_method == \"numdifftools_forward\":\n j = numdifftools_func(objf, method=\"forward\", order=self.jacobian_order, step=step)(x)\n elif jacobian_method == \"numdifftools_reverse\":\n j = numdifftools_func(objf, method=\"reverse\", order=self.jacobian_order, step=step)(x)\n elif jacobian_method == \"numdifftools_central\":\n j = numdifftools_func(objf, method=\"central\", order=self.jacobian_order, step=step)(x)\n\n elif jacobian_method == \"jacobi_forward\":\n j = jacobi(objf, x, method=1)[0]\n elif jacobian_method == \"jacobi_central\":\n j = jacobi(objf, x, method=0)[0]\n elif jacobian_method == \"jacobi_backward\":\n j = jacobi(objf, x, method=1)[0]\n\n # Up the jacobian fval count, set the fval back\n self.jac_fval_count += self.fval_iter - fval_iter\n self.fval_iter = fval_iter\n # Handle the return value - doesn't matter what type the method returns\n # if (not (jacobian_numpy ^ return_numpy)) or (return_numpy and jacobian_numpy):\n # return j\n # elif return_numpy and not jacobian_numpy:\n # return np.array(j)\n # elif jacobian_numpy and not return_numpy:\n # return j.tolist()\n\n if return_numpy:\n return np.array(j) if type(j) is list else j\n else:\n return j if type(j) is list else j.tolist()\n\n def solve(self, x0, args=()):\n self.fval_iter = self.jac_iter = self.jac_fval_count = self.hess_iter = self.hess_fval_count = 0\n return_numpy = type(x0) is not list\n if self.solver_numpy:\n x0 = np.array(x0)\n elif return_numpy:\n x0 = x0.tolist()\n\n process_root = False\n method = self.method\n if method == \"newton_system\":\n sln, niter = newton_system(self.objf, x0, jac=self.jacobian, xtol=self.xtol, args=args,\n ytol=self.ytol, maxiter=self.maxiter, damping=self.damping,\n solve_func=self.matrix_solver)\n elif method == \"newton_system_line_search\":\n sln, niter = newton_system(self.objf, x0, jac=self.jacobian, xtol=self.xtol, args=args,\n ytol=self.ytol, maxiter=self.maxiter, damping=self.damping,\n line_search=True, solve_func=self.matrix_solver, require_progress=False,\n check_numbers=True, Armijo=True)\n elif method == \"newton_system_line_search_progress\":\n sln, niter = newton_system(self.objf, x0, jac=self.jacobian, xtol=self.xtol, args=args,\n ytol=self.ytol, maxiter=self.maxiter, damping=self.damping,\n line_search=True, solve_func=self.matrix_solver, require_progress=True,\n check_numbers=True, Armijo=True)\n elif method == \"homotopy_solver\":\n sln, niter = homotopy_solver(self.objf, x0, jac=self.jacobian, xtol=self.xtol, args=args,\n ytol=self.ytol, maxiter=self.maxiter, damping=self.damping,\n line_search=True, solve_func=self.matrix_solver)\n elif method == \"broyden2_python\":\n sln, niter = broyden2(x0, self.objf, self.jacobian, xtol=self.xtol, maxiter=self.maxiter,\n args=args)\n elif method == \"fixed_point\":\n sln, niter = fixed_point(residual_to_fixed_point(self.objf), x0, xtol=self.xtol, args=args, ytol=self.ytol, maxiter=self.maxiter, damping=self.damping)\n elif method == \"fixed_point_aitken\":\n sln, niter = fixed_point_aitken(residual_to_fixed_point(self.objf), x0, xtol=self.xtol, args=args, ytol=self.ytol, maxiter=self.maxiter, damping=self.damping)\n elif method == \"fixed_point_gdem\":\n sln, niter = fixed_point_gdem(residual_to_fixed_point(self.objf), x0, xtol=self.xtol, args=args, ytol=self.ytol, maxiter=self.maxiter, damping=self.damping)\n elif method == \"fixed_point_anderson\":\n sln, niter = fixed_point_anderson_residual(residual_to_fixed_point(self.objf), x0, xtol=self.xtol, args=args, ytol=self.ytol, maxiter=self.maxiter, window_size=5, reg=1e-8, initial_iterations=5, acc_damping=0.3, damping=1.0)\n elif method in scipy_root_options_set:\n process_root = True\n jacobian_method = self.jacobian_method\n jac = self.jacobian if jacobian_method != \"scipy\" else None\n result = root(self.objf, x0, args=args, method=method, jac=jac, tol=self.xtol)\n elif method in scipy_minimize_options_set:\n process_root = True\n jacobian_method = self.jacobian_method\n jac = self.jacobian if jacobian_method != \"scipy\" else None\n hess = self.hessian if method in scipy_requires_hessian_options_set else None\n result = minimize(self.objf, x0, args=args, method=method, jac=jac, tol=self.xtol, hess=hess)\n elif method == \"newton_minimize\":\n sln, niter = newton_minimize(\n self.objf, x0, jac=self.jacobian, hess=self.hessian,\n xtol=self.xtol, ytol=self.ytol,\n maxiter=self.maxiter, damping=self.damping,\n args=args)\n if process_root:\n sln = result.x\n\n if not return_numpy:\n sln = sln.tolist()\n elif return_numpy:\n sln = np.array(sln)\n\n return sln", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 26228}, "tests/test_numerics.py::2205": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["assert_close1d", "broyden2", "exp", "fixed_point", "fixed_point_aitken", "fixed_point_anderson", "fixed_point_gdem", "fixed_point_to_residual", "residual_to_fixed_point"], "enclosing_function": "test_fixed_point_process", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\ndef broyden2(xs, fun, jac, xtol=1e-7, maxiter=100, jac_has_fun=False,\n skip_J=False, args=()):\n iter = 0\n if skip_J:\n fcur = fun(xs, *args)\n N = len(fcur)\n J = eye(N)\n elif jac_has_fun:\n fcur, J = jac(xs, *args)\n J = inv(J)\n else:\n fcur = fun(xs, *args)\n J = inv(jac(xs, *args))\n\n N = len(fcur)\n eqns = range(N)\n\n err = 0.0\n for fi in fcur:\n err += abs(fi)\n\n while err > xtol and iter < maxiter:\n s = matrix_vector_dot(J, fcur)\n\n xs = [xs[i] - s[i] for i in eqns]\n\n fnew = fun(xs, *args)\n z = [fnew[i] - fcur[i] for i in eqns]\n\n u = matrix_vector_dot(J, z)\n\n d = [-i for i in s]\n\n\n dmu = [d[i]-u[i] for i in eqns]\n dmu_d = dot_product(dmu, d)\n den_inv = 1.0/dot_product(d, u)\n factor = den_inv*dmu_d\n J_delta = [[factor*j for j in row] for row in J]\n for i in eqns:\n for j in eqns:\n J[i][j] += J_delta[i][j]\n\n fcur = fnew\n iter += 1\n err = 0.0\n for fi in fcur:\n err += abs(fi)\n\n return xs, iter\n\ndef fixed_point(f, x0, xtol=None, ytol=None, maxiter=100, damping=1.0,\n args=(), require_progress=False, check_numbers=False):\n fcur = f(x0, *args)\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if xtol is None and (ytol is not None and err0 < ytol):\n return x0, 0.0\n x = [xi - fi for xi, fi in zip(x0, fcur)]\n iteration = 1\n while iteration < maxiter:\n fcur = f(x, *args)\n if check_numbers:\n for v in fcur:\n if isinf(v) or isnan(v):\n raise ValueError(\"Cannot continue - math error in function value\")\n x = [xi - fi*damping for xi, fi in zip(x, fcur)]\n err1 = 0.0\n for v in fcur:\n err1 += abs(v)\n iteration += 1\n if xtol is not None:\n if (norm2(fcur) < xtol) and (ytol is None or err1 < ytol):\n break\n elif ytol is not None:\n if err1 < ytol:\n break\n if err1 >= err0 and require_progress:\n raise ValueError(\"Fixed point is not making progress, cannot proceed\")\n err0 = err1\n\n\n\n if xtol is not None and norm2(fcur) > xtol:\n raise UnconvergedError(\"Failed to converge\")\n if ytol is not None:\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if err0 > ytol:\n raise UnconvergedError(\"Failed to converge\")\n return x, iteration\n\ndef fixed_point_aitken(f, x0, xtol=None, ytol=None, maxiter=100, damping=1.0,\n args=(), require_progress=False, check_numbers=False, acc_frequency=4,\n acc_damping=1.0, acc_max_change_ratio=1.0):\n all_guesses = [x0]\n fcur = f(x0, *args)\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if xtol is None and (ytol is not None and err0 < ytol):\n return x0, 0.0\n\n x = [xi - fi for xi, fi in zip(x0, fcur)]\n iteration = 1\n while iteration < maxiter:\n all_guesses.append(x)\n fcur = f(x, *args)\n if check_numbers:\n for v in fcur:\n if isinf(v) or isnan(v):\n raise ValueError(\"Cannot continue - math error in function value\")\n if (iteration % acc_frequency) == 0:\n x1, x2 = all_guesses[-2], all_guesses[-3]\n dx = aitken_delta_squared_accelerate(x, x1, x2, acc_max_change_ratio)\n x = [xi + dxi*acc_damping for xi, dxi in zip(x, dx)]\n else:\n x = [xi - fi*damping for xi, fi in zip(x, fcur)]\n err1 = 0.0\n for v in fcur:\n err1 += abs(v)\n iteration += 1\n if xtol is not None:\n if (norm2(fcur) < xtol) and (ytol is None or err1 < ytol):\n break\n elif ytol is not None:\n if err1 < ytol:\n break\n if err1 >= err0 and require_progress:\n raise ValueError(\"Fixed point is not making progress, cannot proceed\")\n err0 = err1\n\n if xtol is not None and norm2(fcur) > xtol:\n raise UnconvergedError(\"Failed to converge\")\n if ytol is not None:\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if err0 > ytol:\n raise UnconvergedError(\"Failed to converge\")\n return x, iteration\n\ndef fixed_point_gdem(f, x0, xtol=None, ytol=None, maxiter=100, damping=1.0,\n args=(), require_progress=False, check_numbers=False, acc_frequency=5,\n acc_damping=1.0, acc_max_change_ratio=1.0):\n all_guesses = [x0]\n fcur = f(x0, *args)\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if xtol is None and (ytol is not None and err0 < ytol):\n return x0, 0.0\n\n x = [xi - fi for xi, fi in zip(x0, fcur)]\n iteration = 1\n while iteration < maxiter:\n all_guesses.append(x)\n fcur = f(x, *args)\n if check_numbers:\n for v in fcur:\n if isinf(v) or isnan(v):\n raise ValueError(\"Cannot continue - math error in function value\")\n if (iteration % acc_frequency) == 0:\n x1, x2, x3 = all_guesses[-2], all_guesses[-3], all_guesses[-4]\n dx = gdem(x, x1, x2, x3, acc_max_change_ratio)\n # print(np.array([xi - fi*acc_damping for xi, fi in zip(x, fcur)])/[xi + dxi*acc_damping for xi, dxi in zip(x, dx)])\n x = [xi + dxi*acc_damping for xi, dxi in zip(x, dx)]\n else:\n x = [xi - fi*damping for xi, fi in zip(x, fcur)]\n err1 = 0.0\n for v in fcur:\n err1 += abs(v)\n iteration += 1\n if xtol is not None:\n if (norm2(fcur) < xtol) and (ytol is None or err1 < ytol):\n break\n elif ytol is not None:\n if err1 < ytol:\n break\n if err1 >= err0 and require_progress:\n raise ValueError(\"Fixed point is not making progress, cannot proceed\")\n err0 = err1\n\n if xtol is not None and norm2(fcur) > xtol:\n raise UnconvergedError(\"Failed to converge\")\n if ytol is not None:\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if err0 > ytol:\n raise UnconvergedError(\"Failed to converge\")\n return x, iteration\n\ndef fixed_point_anderson(\n f,\n x0,\n xtol: float = 1e-7,\n ytol: float | None = None,\n maxiter: int = 100,\n args: tuple = (),\n require_progress: bool = False,\n check_numbers: bool = False,\n window_size: int = 5,\n reg: float = 1e-8,\n mixing_param: float = 1.0,\n initial_iterations: int = 4,\n damping: float = 0.9,\n acc_damping: float = 1, # Damping for acceleration phase\n max_step_size: float = 10000, # Maximum allowed relative step size\n phase_in_steps: int = 3 # Number of steps to phase in acceleration\n):\n # Initialize state\n x_hist = []\n gx_hist = []\n residuals_hist = []\n x = x0\n # f = residual_to_fixed_point(f) # this commented out means the first lines should be uncommented; second lines commented\n fcur = f(x, *args)\n\n # Truncate window size based on the dimensionality of the problem\n # sometimes being 1 larger can be OK, for now not allowing it\n if len(fcur) < window_size:\n window_size = len(fcur)\n\n # Check initial convergence for ytol\n err0 = sum(abs(v) for v in fcur) if ytol is not None else 0.0\n if ytol is not None and xtol is None and err0 < ytol:\n return x0, 0\n\n # Main iteration loop\n for iteration in range(maxiter):\n x_new = f(x, *args)\n\n # Check for inf/nan\n if check_numbers and any(isnan(v) or isinf(v) for v in x_new):\n raise ValueError(\"Cannot continue - math error in function value\")\n\n if iteration < initial_iterations:\n # Damped fixed-point iteration\n x_acc = [\n (1 - damping) * x[i] + damping * x_new[i]\n for i in range(len(x))\n ]\n # Collect history for later use\n if iteration > 0:\n residual = [xi - xp for xi, xp in zip(x_new, x)]\n residuals_hist.append(residual)\n gx_hist.append(x_new)\n x_hist.append(x_acc)\n\n # Maintain window size\n if len(residuals_hist) > window_size:\n residuals_hist = residuals_hist[1:]\n gx_hist = gx_hist[1:]\n x_hist = x_hist[1:]\n else:\n # Apply Anderson acceleration with safeguards\n x_acc_raw, x_hist, gx_hist, residuals_hist = anderson_step(\n x_hist, gx_hist, residuals_hist, x_new,\n window_size, reg, mixing_param\n )\n\n # Calculate phase-in factor (gradually increase from 0 to 1)\n phase = min(1.0, (iteration - initial_iterations + 1) / phase_in_steps)\n\n # Compute damped acceleration step\n x_acc_damped = []\n for i in range(len(x)):\n # Regular damped fixed-point step\n fp_step = (1 - damping) * x[i] + damping * x_new[i]\n\n # Anderson acceleration step with its own damping\n acc_step = (1 - acc_damping) * x[i] + acc_damping * x_acc_raw[i]\n\n # Blend between fixed-point and acceleration based on phase\n x_acc_i = (1 - phase) * fp_step + phase * acc_step\n\n # Limit maximum step size relative to current position\n max_change = abs(x[i] * (1.0-max_step_size))\n change = x_acc_i - x[i]\n if abs(change) > max_change:\n # Clamp the change to the maximum allowed\n x_acc_i = x[i] + max_change * (1 if change > 0 else -1)\n\n x_acc_damped.append(x_acc_i)\n\n x_acc = x_acc_damped\n x_hist[-1] = x_acc\n\n # Calculate errors\n err1 = sum(abs(v) for v in fcur) if ytol is not None else 0.0\n\n # Check progress\n if require_progress and ytol is not None and err1 >= err0:\n raise ValueError(\"Fixed point is not making progress\")\n\n # Update error\n err0 = err1 if ytol is not None else 0.0\n\n # Check convergence\n if xtol is not None:\n x_err = max(abs((a - b) / abs(b)) for a, b in zip(x_acc, x))\n if x_err < xtol and (ytol is None or err1 < ytol):\n return x_acc, iteration\n elif ytol is not None and err1 < ytol:\n return x_acc, iteration\n\n x = x_acc\n\n # Check final convergence\n x_err = max(abs((a - b) / abs(b)) for a, b in zip(x_acc, x))\n if xtol is not None and x_err > xtol:\n raise ValueError(f\"Failed to converge after {maxiter} iterations. Error: {x_err}\")\n if ytol is not None and err1 > ytol:\n raise ValueError(f\"Failed to converge after {maxiter} iterations. Error: {err1}\")\n\n return x, iteration\n\ndef fixed_point_to_residual(f_fixed_point):\n \"\"\"\n Transforms a fixed-point iteration function to a residual-based function.\n\n Parameters\n ----------\n - f_fixed_point: Function that takes x and returns the difference x - thing\n\n Returns\n -------\n - A function that outputs residuals: thing - x\n \"\"\"\n def residual_function(x, *args):\n # Get the original fixed-point differences (x - thing)\n fp_diff = f_fixed_point(x, *args)\n # Calculate the residuals as (thing - x)\n return [-diff for diff in fp_diff]\n\n return residual_function\n\ndef residual_to_fixed_point(f_residual):\n \"\"\"\n Transforms a residual-based function to a fixed-point iteration function.\n\n Parameters\n ----------\n - f_residual: Function that takes x and returns residuals (thing - x)\n\n Returns\n -------\n - A function that outputs differences for fixed-point: x - thing\n \"\"\"\n def fixed_point_function(x, *args):\n # Get the residuals (thing - x)\n res = f_residual(x, *args)\n # Calculate the fixed-point differences as (x - thing)\n return [-r for r in res]\n\n return fixed_point_function", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 12387}, "tests/test_numerics.py::2222": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["assert_close1d", "broyden2", "exp", "fixed_point", "fixed_point_aitken", "fixed_point_anderson", "fixed_point_gdem", "fixed_point_to_residual", "residual_to_fixed_point"], "enclosing_function": "test_fixed_point_process", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\ndef broyden2(xs, fun, jac, xtol=1e-7, maxiter=100, jac_has_fun=False,\n skip_J=False, args=()):\n iter = 0\n if skip_J:\n fcur = fun(xs, *args)\n N = len(fcur)\n J = eye(N)\n elif jac_has_fun:\n fcur, J = jac(xs, *args)\n J = inv(J)\n else:\n fcur = fun(xs, *args)\n J = inv(jac(xs, *args))\n\n N = len(fcur)\n eqns = range(N)\n\n err = 0.0\n for fi in fcur:\n err += abs(fi)\n\n while err > xtol and iter < maxiter:\n s = matrix_vector_dot(J, fcur)\n\n xs = [xs[i] - s[i] for i in eqns]\n\n fnew = fun(xs, *args)\n z = [fnew[i] - fcur[i] for i in eqns]\n\n u = matrix_vector_dot(J, z)\n\n d = [-i for i in s]\n\n\n dmu = [d[i]-u[i] for i in eqns]\n dmu_d = dot_product(dmu, d)\n den_inv = 1.0/dot_product(d, u)\n factor = den_inv*dmu_d\n J_delta = [[factor*j for j in row] for row in J]\n for i in eqns:\n for j in eqns:\n J[i][j] += J_delta[i][j]\n\n fcur = fnew\n iter += 1\n err = 0.0\n for fi in fcur:\n err += abs(fi)\n\n return xs, iter\n\ndef fixed_point(f, x0, xtol=None, ytol=None, maxiter=100, damping=1.0,\n args=(), require_progress=False, check_numbers=False):\n fcur = f(x0, *args)\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if xtol is None and (ytol is not None and err0 < ytol):\n return x0, 0.0\n x = [xi - fi for xi, fi in zip(x0, fcur)]\n iteration = 1\n while iteration < maxiter:\n fcur = f(x, *args)\n if check_numbers:\n for v in fcur:\n if isinf(v) or isnan(v):\n raise ValueError(\"Cannot continue - math error in function value\")\n x = [xi - fi*damping for xi, fi in zip(x, fcur)]\n err1 = 0.0\n for v in fcur:\n err1 += abs(v)\n iteration += 1\n if xtol is not None:\n if (norm2(fcur) < xtol) and (ytol is None or err1 < ytol):\n break\n elif ytol is not None:\n if err1 < ytol:\n break\n if err1 >= err0 and require_progress:\n raise ValueError(\"Fixed point is not making progress, cannot proceed\")\n err0 = err1\n\n\n\n if xtol is not None and norm2(fcur) > xtol:\n raise UnconvergedError(\"Failed to converge\")\n if ytol is not None:\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if err0 > ytol:\n raise UnconvergedError(\"Failed to converge\")\n return x, iteration\n\ndef fixed_point_aitken(f, x0, xtol=None, ytol=None, maxiter=100, damping=1.0,\n args=(), require_progress=False, check_numbers=False, acc_frequency=4,\n acc_damping=1.0, acc_max_change_ratio=1.0):\n all_guesses = [x0]\n fcur = f(x0, *args)\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if xtol is None and (ytol is not None and err0 < ytol):\n return x0, 0.0\n\n x = [xi - fi for xi, fi in zip(x0, fcur)]\n iteration = 1\n while iteration < maxiter:\n all_guesses.append(x)\n fcur = f(x, *args)\n if check_numbers:\n for v in fcur:\n if isinf(v) or isnan(v):\n raise ValueError(\"Cannot continue - math error in function value\")\n if (iteration % acc_frequency) == 0:\n x1, x2 = all_guesses[-2], all_guesses[-3]\n dx = aitken_delta_squared_accelerate(x, x1, x2, acc_max_change_ratio)\n x = [xi + dxi*acc_damping for xi, dxi in zip(x, dx)]\n else:\n x = [xi - fi*damping for xi, fi in zip(x, fcur)]\n err1 = 0.0\n for v in fcur:\n err1 += abs(v)\n iteration += 1\n if xtol is not None:\n if (norm2(fcur) < xtol) and (ytol is None or err1 < ytol):\n break\n elif ytol is not None:\n if err1 < ytol:\n break\n if err1 >= err0 and require_progress:\n raise ValueError(\"Fixed point is not making progress, cannot proceed\")\n err0 = err1\n\n if xtol is not None and norm2(fcur) > xtol:\n raise UnconvergedError(\"Failed to converge\")\n if ytol is not None:\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if err0 > ytol:\n raise UnconvergedError(\"Failed to converge\")\n return x, iteration\n\ndef fixed_point_gdem(f, x0, xtol=None, ytol=None, maxiter=100, damping=1.0,\n args=(), require_progress=False, check_numbers=False, acc_frequency=5,\n acc_damping=1.0, acc_max_change_ratio=1.0):\n all_guesses = [x0]\n fcur = f(x0, *args)\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if xtol is None and (ytol is not None and err0 < ytol):\n return x0, 0.0\n\n x = [xi - fi for xi, fi in zip(x0, fcur)]\n iteration = 1\n while iteration < maxiter:\n all_guesses.append(x)\n fcur = f(x, *args)\n if check_numbers:\n for v in fcur:\n if isinf(v) or isnan(v):\n raise ValueError(\"Cannot continue - math error in function value\")\n if (iteration % acc_frequency) == 0:\n x1, x2, x3 = all_guesses[-2], all_guesses[-3], all_guesses[-4]\n dx = gdem(x, x1, x2, x3, acc_max_change_ratio)\n # print(np.array([xi - fi*acc_damping for xi, fi in zip(x, fcur)])/[xi + dxi*acc_damping for xi, dxi in zip(x, dx)])\n x = [xi + dxi*acc_damping for xi, dxi in zip(x, dx)]\n else:\n x = [xi - fi*damping for xi, fi in zip(x, fcur)]\n err1 = 0.0\n for v in fcur:\n err1 += abs(v)\n iteration += 1\n if xtol is not None:\n if (norm2(fcur) < xtol) and (ytol is None or err1 < ytol):\n break\n elif ytol is not None:\n if err1 < ytol:\n break\n if err1 >= err0 and require_progress:\n raise ValueError(\"Fixed point is not making progress, cannot proceed\")\n err0 = err1\n\n if xtol is not None and norm2(fcur) > xtol:\n raise UnconvergedError(\"Failed to converge\")\n if ytol is not None:\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if err0 > ytol:\n raise UnconvergedError(\"Failed to converge\")\n return x, iteration\n\ndef fixed_point_anderson(\n f,\n x0,\n xtol: float = 1e-7,\n ytol: float | None = None,\n maxiter: int = 100,\n args: tuple = (),\n require_progress: bool = False,\n check_numbers: bool = False,\n window_size: int = 5,\n reg: float = 1e-8,\n mixing_param: float = 1.0,\n initial_iterations: int = 4,\n damping: float = 0.9,\n acc_damping: float = 1, # Damping for acceleration phase\n max_step_size: float = 10000, # Maximum allowed relative step size\n phase_in_steps: int = 3 # Number of steps to phase in acceleration\n):\n # Initialize state\n x_hist = []\n gx_hist = []\n residuals_hist = []\n x = x0\n # f = residual_to_fixed_point(f) # this commented out means the first lines should be uncommented; second lines commented\n fcur = f(x, *args)\n\n # Truncate window size based on the dimensionality of the problem\n # sometimes being 1 larger can be OK, for now not allowing it\n if len(fcur) < window_size:\n window_size = len(fcur)\n\n # Check initial convergence for ytol\n err0 = sum(abs(v) for v in fcur) if ytol is not None else 0.0\n if ytol is not None and xtol is None and err0 < ytol:\n return x0, 0\n\n # Main iteration loop\n for iteration in range(maxiter):\n x_new = f(x, *args)\n\n # Check for inf/nan\n if check_numbers and any(isnan(v) or isinf(v) for v in x_new):\n raise ValueError(\"Cannot continue - math error in function value\")\n\n if iteration < initial_iterations:\n # Damped fixed-point iteration\n x_acc = [\n (1 - damping) * x[i] + damping * x_new[i]\n for i in range(len(x))\n ]\n # Collect history for later use\n if iteration > 0:\n residual = [xi - xp for xi, xp in zip(x_new, x)]\n residuals_hist.append(residual)\n gx_hist.append(x_new)\n x_hist.append(x_acc)\n\n # Maintain window size\n if len(residuals_hist) > window_size:\n residuals_hist = residuals_hist[1:]\n gx_hist = gx_hist[1:]\n x_hist = x_hist[1:]\n else:\n # Apply Anderson acceleration with safeguards\n x_acc_raw, x_hist, gx_hist, residuals_hist = anderson_step(\n x_hist, gx_hist, residuals_hist, x_new,\n window_size, reg, mixing_param\n )\n\n # Calculate phase-in factor (gradually increase from 0 to 1)\n phase = min(1.0, (iteration - initial_iterations + 1) / phase_in_steps)\n\n # Compute damped acceleration step\n x_acc_damped = []\n for i in range(len(x)):\n # Regular damped fixed-point step\n fp_step = (1 - damping) * x[i] + damping * x_new[i]\n\n # Anderson acceleration step with its own damping\n acc_step = (1 - acc_damping) * x[i] + acc_damping * x_acc_raw[i]\n\n # Blend between fixed-point and acceleration based on phase\n x_acc_i = (1 - phase) * fp_step + phase * acc_step\n\n # Limit maximum step size relative to current position\n max_change = abs(x[i] * (1.0-max_step_size))\n change = x_acc_i - x[i]\n if abs(change) > max_change:\n # Clamp the change to the maximum allowed\n x_acc_i = x[i] + max_change * (1 if change > 0 else -1)\n\n x_acc_damped.append(x_acc_i)\n\n x_acc = x_acc_damped\n x_hist[-1] = x_acc\n\n # Calculate errors\n err1 = sum(abs(v) for v in fcur) if ytol is not None else 0.0\n\n # Check progress\n if require_progress and ytol is not None and err1 >= err0:\n raise ValueError(\"Fixed point is not making progress\")\n\n # Update error\n err0 = err1 if ytol is not None else 0.0\n\n # Check convergence\n if xtol is not None:\n x_err = max(abs((a - b) / abs(b)) for a, b in zip(x_acc, x))\n if x_err < xtol and (ytol is None or err1 < ytol):\n return x_acc, iteration\n elif ytol is not None and err1 < ytol:\n return x_acc, iteration\n\n x = x_acc\n\n # Check final convergence\n x_err = max(abs((a - b) / abs(b)) for a, b in zip(x_acc, x))\n if xtol is not None and x_err > xtol:\n raise ValueError(f\"Failed to converge after {maxiter} iterations. Error: {x_err}\")\n if ytol is not None and err1 > ytol:\n raise ValueError(f\"Failed to converge after {maxiter} iterations. Error: {err1}\")\n\n return x, iteration\n\ndef fixed_point_to_residual(f_fixed_point):\n \"\"\"\n Transforms a fixed-point iteration function to a residual-based function.\n\n Parameters\n ----------\n - f_fixed_point: Function that takes x and returns the difference x - thing\n\n Returns\n -------\n - A function that outputs residuals: thing - x\n \"\"\"\n def residual_function(x, *args):\n # Get the original fixed-point differences (x - thing)\n fp_diff = f_fixed_point(x, *args)\n # Calculate the residuals as (thing - x)\n return [-diff for diff in fp_diff]\n\n return residual_function\n\ndef residual_to_fixed_point(f_residual):\n \"\"\"\n Transforms a residual-based function to a fixed-point iteration function.\n\n Parameters\n ----------\n - f_residual: Function that takes x and returns residuals (thing - x)\n\n Returns\n -------\n - A function that outputs differences for fixed-point: x - thing\n \"\"\"\n def fixed_point_function(x, *args):\n # Get the residuals (thing - x)\n res = f_residual(x, *args)\n # Calculate the fixed-point differences as (x - thing)\n return [-r for r in res]\n\n return fixed_point_function", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 12387}, "tests/test_numerics.py::2259": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["assert_close1d", "broyden2", "exp", "fixed_point", "fixed_point_aitken", "fixed_point_anderson", "fixed_point_gdem", "fixed_point_to_residual", "residual_to_fixed_point"], "enclosing_function": "test_fixed_point_process", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\ndef broyden2(xs, fun, jac, xtol=1e-7, maxiter=100, jac_has_fun=False,\n skip_J=False, args=()):\n iter = 0\n if skip_J:\n fcur = fun(xs, *args)\n N = len(fcur)\n J = eye(N)\n elif jac_has_fun:\n fcur, J = jac(xs, *args)\n J = inv(J)\n else:\n fcur = fun(xs, *args)\n J = inv(jac(xs, *args))\n\n N = len(fcur)\n eqns = range(N)\n\n err = 0.0\n for fi in fcur:\n err += abs(fi)\n\n while err > xtol and iter < maxiter:\n s = matrix_vector_dot(J, fcur)\n\n xs = [xs[i] - s[i] for i in eqns]\n\n fnew = fun(xs, *args)\n z = [fnew[i] - fcur[i] for i in eqns]\n\n u = matrix_vector_dot(J, z)\n\n d = [-i for i in s]\n\n\n dmu = [d[i]-u[i] for i in eqns]\n dmu_d = dot_product(dmu, d)\n den_inv = 1.0/dot_product(d, u)\n factor = den_inv*dmu_d\n J_delta = [[factor*j for j in row] for row in J]\n for i in eqns:\n for j in eqns:\n J[i][j] += J_delta[i][j]\n\n fcur = fnew\n iter += 1\n err = 0.0\n for fi in fcur:\n err += abs(fi)\n\n return xs, iter\n\ndef fixed_point(f, x0, xtol=None, ytol=None, maxiter=100, damping=1.0,\n args=(), require_progress=False, check_numbers=False):\n fcur = f(x0, *args)\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if xtol is None and (ytol is not None and err0 < ytol):\n return x0, 0.0\n x = [xi - fi for xi, fi in zip(x0, fcur)]\n iteration = 1\n while iteration < maxiter:\n fcur = f(x, *args)\n if check_numbers:\n for v in fcur:\n if isinf(v) or isnan(v):\n raise ValueError(\"Cannot continue - math error in function value\")\n x = [xi - fi*damping for xi, fi in zip(x, fcur)]\n err1 = 0.0\n for v in fcur:\n err1 += abs(v)\n iteration += 1\n if xtol is not None:\n if (norm2(fcur) < xtol) and (ytol is None or err1 < ytol):\n break\n elif ytol is not None:\n if err1 < ytol:\n break\n if err1 >= err0 and require_progress:\n raise ValueError(\"Fixed point is not making progress, cannot proceed\")\n err0 = err1\n\n\n\n if xtol is not None and norm2(fcur) > xtol:\n raise UnconvergedError(\"Failed to converge\")\n if ytol is not None:\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if err0 > ytol:\n raise UnconvergedError(\"Failed to converge\")\n return x, iteration\n\ndef fixed_point_aitken(f, x0, xtol=None, ytol=None, maxiter=100, damping=1.0,\n args=(), require_progress=False, check_numbers=False, acc_frequency=4,\n acc_damping=1.0, acc_max_change_ratio=1.0):\n all_guesses = [x0]\n fcur = f(x0, *args)\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if xtol is None and (ytol is not None and err0 < ytol):\n return x0, 0.0\n\n x = [xi - fi for xi, fi in zip(x0, fcur)]\n iteration = 1\n while iteration < maxiter:\n all_guesses.append(x)\n fcur = f(x, *args)\n if check_numbers:\n for v in fcur:\n if isinf(v) or isnan(v):\n raise ValueError(\"Cannot continue - math error in function value\")\n if (iteration % acc_frequency) == 0:\n x1, x2 = all_guesses[-2], all_guesses[-3]\n dx = aitken_delta_squared_accelerate(x, x1, x2, acc_max_change_ratio)\n x = [xi + dxi*acc_damping for xi, dxi in zip(x, dx)]\n else:\n x = [xi - fi*damping for xi, fi in zip(x, fcur)]\n err1 = 0.0\n for v in fcur:\n err1 += abs(v)\n iteration += 1\n if xtol is not None:\n if (norm2(fcur) < xtol) and (ytol is None or err1 < ytol):\n break\n elif ytol is not None:\n if err1 < ytol:\n break\n if err1 >= err0 and require_progress:\n raise ValueError(\"Fixed point is not making progress, cannot proceed\")\n err0 = err1\n\n if xtol is not None and norm2(fcur) > xtol:\n raise UnconvergedError(\"Failed to converge\")\n if ytol is not None:\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if err0 > ytol:\n raise UnconvergedError(\"Failed to converge\")\n return x, iteration\n\ndef fixed_point_gdem(f, x0, xtol=None, ytol=None, maxiter=100, damping=1.0,\n args=(), require_progress=False, check_numbers=False, acc_frequency=5,\n acc_damping=1.0, acc_max_change_ratio=1.0):\n all_guesses = [x0]\n fcur = f(x0, *args)\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if xtol is None and (ytol is not None and err0 < ytol):\n return x0, 0.0\n\n x = [xi - fi for xi, fi in zip(x0, fcur)]\n iteration = 1\n while iteration < maxiter:\n all_guesses.append(x)\n fcur = f(x, *args)\n if check_numbers:\n for v in fcur:\n if isinf(v) or isnan(v):\n raise ValueError(\"Cannot continue - math error in function value\")\n if (iteration % acc_frequency) == 0:\n x1, x2, x3 = all_guesses[-2], all_guesses[-3], all_guesses[-4]\n dx = gdem(x, x1, x2, x3, acc_max_change_ratio)\n # print(np.array([xi - fi*acc_damping for xi, fi in zip(x, fcur)])/[xi + dxi*acc_damping for xi, dxi in zip(x, dx)])\n x = [xi + dxi*acc_damping for xi, dxi in zip(x, dx)]\n else:\n x = [xi - fi*damping for xi, fi in zip(x, fcur)]\n err1 = 0.0\n for v in fcur:\n err1 += abs(v)\n iteration += 1\n if xtol is not None:\n if (norm2(fcur) < xtol) and (ytol is None or err1 < ytol):\n break\n elif ytol is not None:\n if err1 < ytol:\n break\n if err1 >= err0 and require_progress:\n raise ValueError(\"Fixed point is not making progress, cannot proceed\")\n err0 = err1\n\n if xtol is not None and norm2(fcur) > xtol:\n raise UnconvergedError(\"Failed to converge\")\n if ytol is not None:\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if err0 > ytol:\n raise UnconvergedError(\"Failed to converge\")\n return x, iteration\n\ndef fixed_point_anderson(\n f,\n x0,\n xtol: float = 1e-7,\n ytol: float | None = None,\n maxiter: int = 100,\n args: tuple = (),\n require_progress: bool = False,\n check_numbers: bool = False,\n window_size: int = 5,\n reg: float = 1e-8,\n mixing_param: float = 1.0,\n initial_iterations: int = 4,\n damping: float = 0.9,\n acc_damping: float = 1, # Damping for acceleration phase\n max_step_size: float = 10000, # Maximum allowed relative step size\n phase_in_steps: int = 3 # Number of steps to phase in acceleration\n):\n # Initialize state\n x_hist = []\n gx_hist = []\n residuals_hist = []\n x = x0\n # f = residual_to_fixed_point(f) # this commented out means the first lines should be uncommented; second lines commented\n fcur = f(x, *args)\n\n # Truncate window size based on the dimensionality of the problem\n # sometimes being 1 larger can be OK, for now not allowing it\n if len(fcur) < window_size:\n window_size = len(fcur)\n\n # Check initial convergence for ytol\n err0 = sum(abs(v) for v in fcur) if ytol is not None else 0.0\n if ytol is not None and xtol is None and err0 < ytol:\n return x0, 0\n\n # Main iteration loop\n for iteration in range(maxiter):\n x_new = f(x, *args)\n\n # Check for inf/nan\n if check_numbers and any(isnan(v) or isinf(v) for v in x_new):\n raise ValueError(\"Cannot continue - math error in function value\")\n\n if iteration < initial_iterations:\n # Damped fixed-point iteration\n x_acc = [\n (1 - damping) * x[i] + damping * x_new[i]\n for i in range(len(x))\n ]\n # Collect history for later use\n if iteration > 0:\n residual = [xi - xp for xi, xp in zip(x_new, x)]\n residuals_hist.append(residual)\n gx_hist.append(x_new)\n x_hist.append(x_acc)\n\n # Maintain window size\n if len(residuals_hist) > window_size:\n residuals_hist = residuals_hist[1:]\n gx_hist = gx_hist[1:]\n x_hist = x_hist[1:]\n else:\n # Apply Anderson acceleration with safeguards\n x_acc_raw, x_hist, gx_hist, residuals_hist = anderson_step(\n x_hist, gx_hist, residuals_hist, x_new,\n window_size, reg, mixing_param\n )\n\n # Calculate phase-in factor (gradually increase from 0 to 1)\n phase = min(1.0, (iteration - initial_iterations + 1) / phase_in_steps)\n\n # Compute damped acceleration step\n x_acc_damped = []\n for i in range(len(x)):\n # Regular damped fixed-point step\n fp_step = (1 - damping) * x[i] + damping * x_new[i]\n\n # Anderson acceleration step with its own damping\n acc_step = (1 - acc_damping) * x[i] + acc_damping * x_acc_raw[i]\n\n # Blend between fixed-point and acceleration based on phase\n x_acc_i = (1 - phase) * fp_step + phase * acc_step\n\n # Limit maximum step size relative to current position\n max_change = abs(x[i] * (1.0-max_step_size))\n change = x_acc_i - x[i]\n if abs(change) > max_change:\n # Clamp the change to the maximum allowed\n x_acc_i = x[i] + max_change * (1 if change > 0 else -1)\n\n x_acc_damped.append(x_acc_i)\n\n x_acc = x_acc_damped\n x_hist[-1] = x_acc\n\n # Calculate errors\n err1 = sum(abs(v) for v in fcur) if ytol is not None else 0.0\n\n # Check progress\n if require_progress and ytol is not None and err1 >= err0:\n raise ValueError(\"Fixed point is not making progress\")\n\n # Update error\n err0 = err1 if ytol is not None else 0.0\n\n # Check convergence\n if xtol is not None:\n x_err = max(abs((a - b) / abs(b)) for a, b in zip(x_acc, x))\n if x_err < xtol and (ytol is None or err1 < ytol):\n return x_acc, iteration\n elif ytol is not None and err1 < ytol:\n return x_acc, iteration\n\n x = x_acc\n\n # Check final convergence\n x_err = max(abs((a - b) / abs(b)) for a, b in zip(x_acc, x))\n if xtol is not None and x_err > xtol:\n raise ValueError(f\"Failed to converge after {maxiter} iterations. Error: {x_err}\")\n if ytol is not None and err1 > ytol:\n raise ValueError(f\"Failed to converge after {maxiter} iterations. Error: {err1}\")\n\n return x, iteration\n\ndef fixed_point_to_residual(f_fixed_point):\n \"\"\"\n Transforms a fixed-point iteration function to a residual-based function.\n\n Parameters\n ----------\n - f_fixed_point: Function that takes x and returns the difference x - thing\n\n Returns\n -------\n - A function that outputs residuals: thing - x\n \"\"\"\n def residual_function(x, *args):\n # Get the original fixed-point differences (x - thing)\n fp_diff = f_fixed_point(x, *args)\n # Calculate the residuals as (thing - x)\n return [-diff for diff in fp_diff]\n\n return residual_function\n\ndef residual_to_fixed_point(f_residual):\n \"\"\"\n Transforms a residual-based function to a fixed-point iteration function.\n\n Parameters\n ----------\n - f_residual: Function that takes x and returns residuals (thing - x)\n\n Returns\n -------\n - A function that outputs differences for fixed-point: x - thing\n \"\"\"\n def fixed_point_function(x, *args):\n # Get the residuals (thing - x)\n res = f_residual(x, *args)\n # Calculate the fixed-point differences as (x - thing)\n return [-r for r in res]\n\n return fixed_point_function", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 12387}, "tests/test_numerics.py::2295": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["SolverInterface", "assert_close1d", "fixed_point_to_residual"], "enclosing_function": "test_SolverInterface_fixed_point", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\ndef fixed_point_to_residual(f_fixed_point):\n \"\"\"\n Transforms a fixed-point iteration function to a residual-based function.\n\n Parameters\n ----------\n - f_fixed_point: Function that takes x and returns the difference x - thing\n\n Returns\n -------\n - A function that outputs residuals: thing - x\n \"\"\"\n def residual_function(x, *args):\n # Get the original fixed-point differences (x - thing)\n fp_diff = f_fixed_point(x, *args)\n # Calculate the residuals as (thing - x)\n return [-diff for diff in fp_diff]\n\n return residual_function\n\nclass SolverInterface:\n __slots__ = (\n \"damping\",\n \"fval_iter\",\n \"hess_fval_count\",\n \"hess_iter\",\n \"hessian_method\",\n \"hessian_numpy\",\n \"jac_fval_count\",\n \"jac_iter\",\n \"jacobian_method\",\n \"jacobian_numpy\",\n \"jacobian_order\",\n \"jacobian_perturbation\",\n \"jacobian_zero_offset\",\n \"matrix_solver\",\n \"maxiter\",\n \"method\",\n \"minimizing\",\n \"objf\",\n \"objf_numpy\",\n \"objf_original\",\n \"original_jac\",\n \"scalar_objective\",\n \"solver_analytical_jac\",\n \"solver_numpy\",\n \"xtol\",\n \"ytol\",\n )\n\n def objf_counting(self, *args):\n self.fval_iter += 1\n return self.objf_original(*args)\n\n def objf_python_return_numpy(self, x, *args):\n # function only knows python, solver knows numpy\n self.fval_iter += 1\n return np.array(self.objf_original(x if type(x) is list else x.tolist(),\n *args))\n\n def objf_numpy_return_python(self, x, *args):\n # function only knows numpy, solver knows python\n self.fval_iter += 1\n return self.objf_original(np.array(x), *args).tolist()\n\n def objf_numpy_minimizing(self, x, *args):\n self.fval_iter += 1\n errs = self.objf_original(np.array(x), *args)\n tot = 0.0\n for v in errs:\n tot += v*v\n return float(tot)\n\n def objf_python_minimizing(self, x, *args):\n self.fval_iter += 1\n errs = self.objf_original(x if type(x) is list else x.tolist(), *args)\n tot = 0.0\n for v in errs:\n tot += v*v\n return tot\n\n def jac_minimizing(self, x, *args):\n fval = self.objf_original(x, *args)\n jval = self.original_jac(x, *args)\n N = len(fval)\n small_jac = [0.0]*N\n for i in range(N):\n temp = 0.0\n for j in range(N):\n temp += fval[j]*jval[j][i]\n small_jac[i] = 2.0*temp\n return small_jac\n\n def jac_minimizing_numpy(self, x, *args):\n fval = self.objf_original(x, *args)\n jval = self.original_jac(x, *args)\n return 2.0*np.dot(fval, jval)\n\n def objf_python_return_numpy_scalar(self, x, *args):\n self.fval_iter += 1\n return float(self.objf_original(x if type(x) is list else x.tolist(), *args))\n\n def objf_numpy_return_python_scalar(self, x, *args):\n self.fval_iter += 1\n return float(self.objf_original(np.array(x), *args))\n\n def __init__(self, method, objf, jac=None, xtol=1e-8, ytol=None, maxiter=100, damping=1.0,\n jacobian_method=\"python\", jacobian_perturbation=1e-9, jacobian_zero_offset=1e-7,\n hessian_method=\"python\",\n jacobian_order=1, objf_numpy=False, matrix_solver=py_solve, scalar_objective=False):\n self.method, self.objf_original, self.original_jac = method, objf, jac\n self.xtol, self.ytol, self.maxiter, self.damping = xtol, ytol, maxiter, damping\n\n (self.jacobian_perturbation, self.jacobian_zero_offset, self.jacobian_method,\n self.jacobian_order, self.hessian_method) = (jacobian_perturbation,\n jacobian_zero_offset,\n jacobian_method,\n jacobian_order,\n hessian_method)\n self.objf_numpy, self.matrix_solver = objf_numpy, matrix_solver\n\n\n if jacobian_method == \"analytical\":\n self.jacobian_numpy = objf_numpy\n else:\n self.jacobian_numpy = jacobian_method not in python_jacobians_set\n if hessian_method == \"analytical\":\n self.hessian_numpy = objf_numpy\n else:\n self.hessian_numpy = hessian_method not in python_hessians_set\n # whether or not the solver uses numpy\n self.solver_numpy = solver_numpy = method not in python_solvers_set\n\n self.minimizing = False\n self.fval_iter = self.jac_iter = self.jac_fval_count = self.hess_iter = self.hess_fval_count = 0\n self.scalar_objective = scalar_objective\n # whether or not the objf uses numpy\n # if jac is provided it is assumed it is in the same basis\n\n if self.scalar_objective:\n # Direct scalar minimization\n if solver_numpy:\n if not objf_numpy:\n self.objf = self.objf_python_return_numpy_scalar\n else:\n self.objf = self.objf_counting\n else:\n if objf_numpy:\n self.objf = self.objf_numpy_return_python_scalar\n else:\n self.objf = self.objf_counting\n else:\n\n if method in scipy_minimize_options_set:\n self.minimizing = True\n if jacobian_method == \"scipy\" and method in scipy_requires_jacobian_options_set:\n self.jacobian_method = \"python\"\n self.objf = self.objf_numpy_minimizing if objf_numpy else self.objf_python_minimizing\n elif solver_numpy:\n if not objf_numpy:\n self.objf = self.objf_python_return_numpy\n else:\n self.objf = self.objf_counting\n else:\n if objf_numpy:\n self.objf = self.objf_numpy_return_python\n else:\n self.objf = self.objf_counting\n\n if self.minimizing:\n if objf_numpy:\n self.solver_analytical_jac = self.jac_minimizing_numpy\n else:\n self.solver_analytical_jac = self.jac_minimizing\n else:\n self.solver_analytical_jac = self.original_jac\n\n\n\n\n\n def hessian(self, x, base=None, args=()):\n self.hess_iter += 1\n fval_iter, hessian_method, objf_numpy, hessian_numpy = self.fval_iter, self.hessian_method, self.objf_numpy, self.hessian_numpy\n return_numpy = type(x) is not list\n\n if self.scalar_objective:\n # For scalar objectives, always use the efficient scalar calculator\n if not self.hessian_numpy:\n x = x if type(x) is list else x.tolist()\n else:\n x = np.array(x)\n # Use the correct objf based on numpy/python preferences\n if self.objf_numpy:\n objf = self.objf_counting\n else:\n objf = self.objf_python_return_numpy if self.hessian_numpy else self.objf_counting\n\n h = hessian(objf, x, scalar=True,\n perturbation=self.jacobian_perturbation,\n zero_offset=self.jacobian_zero_offset,\n args=args)\n else:\n if hessian_method == \"analytical\":\n if objf_numpy and not return_numpy:\n x = np.array(x)\n elif return_numpy and not objf_numpy:\n x = x.tolist()\n raise NotImplementedError\n h = self.solver_analytical_hess(x, *args)\n else:\n # if the hessian method doesn't speak numpy, convert x to a list\n if not hessian_numpy:\n x = x if type(x) is list else x.tolist()\n else:\n x = np.array(x)\n # If the objf doesn't speak numpy but the hessian does, use the converter\n if self.minimizing:\n if objf_numpy:\n objf = self.objf_numpy_minimizing\n else:\n objf = self.objf_python_minimizing\n else:\n if not hessian_numpy:\n if objf_numpy:\n objf = self.objf_numpy_return_python\n else:\n objf = self.objf_counting\n else:\n if objf_numpy:\n objf = self.objf_counting\n else:\n objf = self.objf_python_return_numpy\n\n if hessian_method.startswith(\"numdifftools\"):\n import numdifftools as nd\n if hessian_method == \"python\":\n h = hessian(objf, x, scalar=self.minimizing, perturbation=1e-4,\n zero_offset=self.jacobian_zero_offset, args=args)\n\n elif hessian_method == \"numdifftools_forward\":\n h = nd.Hessian(objf, method=\"forward\")(x)\n elif hessian_method == \"numdifftools_reverse\":\n h = nd.Hessian(objf, method=\"reverse\")(x)\n elif hessian_method == \"numdifftools_central\":\n h = nd.Hessian(objf, method=\"central\")(x)\n\n # Up the hessian fval count, set the fval back\n self.hess_fval_count += self.fval_iter - fval_iter\n self.fval_iter = fval_iter\n\n if return_numpy:\n return np.array(h) if type(h) is list else h\n else:\n return h if type(h) is list else h.tolist()\n\n def jacobian(self, x, *args):\n \"\"\"\n jacobi - doesn't support jacobian_perturbation, jacobian_zero_offset, jacobian_order\n python - doesn't support jacobian_order\n \"\"\"\n self.jac_iter += 1\n fval_iter, jacobian_method, objf_numpy, jacobian_numpy = self.fval_iter, self.jacobian_method, self.objf_numpy, self.jacobian_numpy\n return_numpy = type(x) is not list\n if self.scalar_objective:\n # For scalar objectives, always use the efficient scalar calculator\n if not self.jacobian_numpy:\n x = x if type(x) is list else x.tolist()\n else:\n x = np.array(x)\n\n # Use the correct objf based on numpy/python preferences\n if self.objf_numpy:\n objf = self.objf_counting\n else:\n objf = self.objf_python_return_numpy if self.jacobian_numpy else self.objf_counting\n\n j = jacobian(objf, x, scalar=True,\n perturbation=self.jacobian_perturbation,\n zero_offset=self.jacobian_zero_offset,\n args=args)\n else:\n if jacobian_method == \"analytical\":\n if objf_numpy and not return_numpy:\n x = np.array(x)\n elif return_numpy and not objf_numpy:\n x = x.tolist()\n j = self.solver_analytical_jac(x, *args)\n else:\n # if the jacobian method doesn't speak numpy, convert x to a list\n if not jacobian_numpy:\n x = x if type(x) is list else x.tolist()\n else:\n x = np.array(x)\n # If the objf doesn't speak numpy but the jacobian does, use the converter\n if self.minimizing:\n if objf_numpy:\n objf = self.objf_numpy_minimizing\n else:\n objf = self.objf_python_minimizing\n else:\n if not jacobian_numpy:\n if objf_numpy:\n objf = self.objf_numpy_return_python\n else:\n objf = self.objf_counting\n else:\n if objf_numpy:\n objf = self.objf_counting\n else:\n objf = self.objf_python_return_numpy\n\n if jacobian_method.startswith(\"numdifftools\"):\n import numdifftools as nd\n numdifftools_func = nd.Gradient if self.minimizing else nd.Jacobian\n step = self.jacobian_perturbation*x\n step[np.where(step==0)] = self.jacobian_zero_offset\n elif jacobian_method.startswith(\"jacobi\"):\n from jacobi import jacobi\n if jacobian_method == \"python\":\n j = jacobian(objf, x, scalar=self.minimizing, perturbation=self.jacobian_perturbation,\n zero_offset=self.jacobian_zero_offset, args=args)\n\n elif jacobian_method == \"numdifftools_forward\":\n j = numdifftools_func(objf, method=\"forward\", order=self.jacobian_order, step=step)(x)\n elif jacobian_method == \"numdifftools_reverse\":\n j = numdifftools_func(objf, method=\"reverse\", order=self.jacobian_order, step=step)(x)\n elif jacobian_method == \"numdifftools_central\":\n j = numdifftools_func(objf, method=\"central\", order=self.jacobian_order, step=step)(x)\n\n elif jacobian_method == \"jacobi_forward\":\n j = jacobi(objf, x, method=1)[0]\n elif jacobian_method == \"jacobi_central\":\n j = jacobi(objf, x, method=0)[0]\n elif jacobian_method == \"jacobi_backward\":\n j = jacobi(objf, x, method=1)[0]\n\n # Up the jacobian fval count, set the fval back\n self.jac_fval_count += self.fval_iter - fval_iter\n self.fval_iter = fval_iter\n # Handle the return value - doesn't matter what type the method returns\n # if (not (jacobian_numpy ^ return_numpy)) or (return_numpy and jacobian_numpy):\n # return j\n # elif return_numpy and not jacobian_numpy:\n # return np.array(j)\n # elif jacobian_numpy and not return_numpy:\n # return j.tolist()\n\n if return_numpy:\n return np.array(j) if type(j) is list else j\n else:\n return j if type(j) is list else j.tolist()\n\n def solve(self, x0, args=()):\n self.fval_iter = self.jac_iter = self.jac_fval_count = self.hess_iter = self.hess_fval_count = 0\n return_numpy = type(x0) is not list\n if self.solver_numpy:\n x0 = np.array(x0)\n elif return_numpy:\n x0 = x0.tolist()\n\n process_root = False\n method = self.method\n if method == \"newton_system\":\n sln, niter = newton_system(self.objf, x0, jac=self.jacobian, xtol=self.xtol, args=args,\n ytol=self.ytol, maxiter=self.maxiter, damping=self.damping,\n solve_func=self.matrix_solver)\n elif method == \"newton_system_line_search\":\n sln, niter = newton_system(self.objf, x0, jac=self.jacobian, xtol=self.xtol, args=args,\n ytol=self.ytol, maxiter=self.maxiter, damping=self.damping,\n line_search=True, solve_func=self.matrix_solver, require_progress=False,\n check_numbers=True, Armijo=True)\n elif method == \"newton_system_line_search_progress\":\n sln, niter = newton_system(self.objf, x0, jac=self.jacobian, xtol=self.xtol, args=args,\n ytol=self.ytol, maxiter=self.maxiter, damping=self.damping,\n line_search=True, solve_func=self.matrix_solver, require_progress=True,\n check_numbers=True, Armijo=True)\n elif method == \"homotopy_solver\":\n sln, niter = homotopy_solver(self.objf, x0, jac=self.jacobian, xtol=self.xtol, args=args,\n ytol=self.ytol, maxiter=self.maxiter, damping=self.damping,\n line_search=True, solve_func=self.matrix_solver)\n elif method == \"broyden2_python\":\n sln, niter = broyden2(x0, self.objf, self.jacobian, xtol=self.xtol, maxiter=self.maxiter,\n args=args)\n elif method == \"fixed_point\":\n sln, niter = fixed_point(residual_to_fixed_point(self.objf), x0, xtol=self.xtol, args=args, ytol=self.ytol, maxiter=self.maxiter, damping=self.damping)\n elif method == \"fixed_point_aitken\":\n sln, niter = fixed_point_aitken(residual_to_fixed_point(self.objf), x0, xtol=self.xtol, args=args, ytol=self.ytol, maxiter=self.maxiter, damping=self.damping)\n elif method == \"fixed_point_gdem\":\n sln, niter = fixed_point_gdem(residual_to_fixed_point(self.objf), x0, xtol=self.xtol, args=args, ytol=self.ytol, maxiter=self.maxiter, damping=self.damping)\n elif method == \"fixed_point_anderson\":\n sln, niter = fixed_point_anderson_residual(residual_to_fixed_point(self.objf), x0, xtol=self.xtol, args=args, ytol=self.ytol, maxiter=self.maxiter, window_size=5, reg=1e-8, initial_iterations=5, acc_damping=0.3, damping=1.0)\n elif method in scipy_root_options_set:\n process_root = True\n jacobian_method = self.jacobian_method\n jac = self.jacobian if jacobian_method != \"scipy\" else None\n result = root(self.objf, x0, args=args, method=method, jac=jac, tol=self.xtol)\n elif method in scipy_minimize_options_set:\n process_root = True\n jacobian_method = self.jacobian_method\n jac = self.jacobian if jacobian_method != \"scipy\" else None\n hess = self.hessian if method in scipy_requires_hessian_options_set else None\n result = minimize(self.objf, x0, args=args, method=method, jac=jac, tol=self.xtol, hess=hess)\n elif method == \"newton_minimize\":\n sln, niter = newton_minimize(\n self.objf, x0, jac=self.jacobian, hess=self.hessian,\n xtol=self.xtol, ytol=self.ytol,\n maxiter=self.maxiter, damping=self.damping,\n args=args)\n if process_root:\n sln = result.x\n\n if not return_numpy:\n sln = sln.tolist()\n elif return_numpy:\n sln = np.array(sln)\n\n return sln", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 18910}, "tests/test_numerics.py::2300": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["SolverInterface", "assert_close1d", "fixed_point_to_residual"], "enclosing_function": "test_SolverInterface_fixed_point", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\ndef fixed_point_to_residual(f_fixed_point):\n \"\"\"\n Transforms a fixed-point iteration function to a residual-based function.\n\n Parameters\n ----------\n - f_fixed_point: Function that takes x and returns the difference x - thing\n\n Returns\n -------\n - A function that outputs residuals: thing - x\n \"\"\"\n def residual_function(x, *args):\n # Get the original fixed-point differences (x - thing)\n fp_diff = f_fixed_point(x, *args)\n # Calculate the residuals as (thing - x)\n return [-diff for diff in fp_diff]\n\n return residual_function\n\nclass SolverInterface:\n __slots__ = (\n \"damping\",\n \"fval_iter\",\n \"hess_fval_count\",\n \"hess_iter\",\n \"hessian_method\",\n \"hessian_numpy\",\n \"jac_fval_count\",\n \"jac_iter\",\n \"jacobian_method\",\n \"jacobian_numpy\",\n \"jacobian_order\",\n \"jacobian_perturbation\",\n \"jacobian_zero_offset\",\n \"matrix_solver\",\n \"maxiter\",\n \"method\",\n \"minimizing\",\n \"objf\",\n \"objf_numpy\",\n \"objf_original\",\n \"original_jac\",\n \"scalar_objective\",\n \"solver_analytical_jac\",\n \"solver_numpy\",\n \"xtol\",\n \"ytol\",\n )\n\n def objf_counting(self, *args):\n self.fval_iter += 1\n return self.objf_original(*args)\n\n def objf_python_return_numpy(self, x, *args):\n # function only knows python, solver knows numpy\n self.fval_iter += 1\n return np.array(self.objf_original(x if type(x) is list else x.tolist(),\n *args))\n\n def objf_numpy_return_python(self, x, *args):\n # function only knows numpy, solver knows python\n self.fval_iter += 1\n return self.objf_original(np.array(x), *args).tolist()\n\n def objf_numpy_minimizing(self, x, *args):\n self.fval_iter += 1\n errs = self.objf_original(np.array(x), *args)\n tot = 0.0\n for v in errs:\n tot += v*v\n return float(tot)\n\n def objf_python_minimizing(self, x, *args):\n self.fval_iter += 1\n errs = self.objf_original(x if type(x) is list else x.tolist(), *args)\n tot = 0.0\n for v in errs:\n tot += v*v\n return tot\n\n def jac_minimizing(self, x, *args):\n fval = self.objf_original(x, *args)\n jval = self.original_jac(x, *args)\n N = len(fval)\n small_jac = [0.0]*N\n for i in range(N):\n temp = 0.0\n for j in range(N):\n temp += fval[j]*jval[j][i]\n small_jac[i] = 2.0*temp\n return small_jac\n\n def jac_minimizing_numpy(self, x, *args):\n fval = self.objf_original(x, *args)\n jval = self.original_jac(x, *args)\n return 2.0*np.dot(fval, jval)\n\n def objf_python_return_numpy_scalar(self, x, *args):\n self.fval_iter += 1\n return float(self.objf_original(x if type(x) is list else x.tolist(), *args))\n\n def objf_numpy_return_python_scalar(self, x, *args):\n self.fval_iter += 1\n return float(self.objf_original(np.array(x), *args))\n\n def __init__(self, method, objf, jac=None, xtol=1e-8, ytol=None, maxiter=100, damping=1.0,\n jacobian_method=\"python\", jacobian_perturbation=1e-9, jacobian_zero_offset=1e-7,\n hessian_method=\"python\",\n jacobian_order=1, objf_numpy=False, matrix_solver=py_solve, scalar_objective=False):\n self.method, self.objf_original, self.original_jac = method, objf, jac\n self.xtol, self.ytol, self.maxiter, self.damping = xtol, ytol, maxiter, damping\n\n (self.jacobian_perturbation, self.jacobian_zero_offset, self.jacobian_method,\n self.jacobian_order, self.hessian_method) = (jacobian_perturbation,\n jacobian_zero_offset,\n jacobian_method,\n jacobian_order,\n hessian_method)\n self.objf_numpy, self.matrix_solver = objf_numpy, matrix_solver\n\n\n if jacobian_method == \"analytical\":\n self.jacobian_numpy = objf_numpy\n else:\n self.jacobian_numpy = jacobian_method not in python_jacobians_set\n if hessian_method == \"analytical\":\n self.hessian_numpy = objf_numpy\n else:\n self.hessian_numpy = hessian_method not in python_hessians_set\n # whether or not the solver uses numpy\n self.solver_numpy = solver_numpy = method not in python_solvers_set\n\n self.minimizing = False\n self.fval_iter = self.jac_iter = self.jac_fval_count = self.hess_iter = self.hess_fval_count = 0\n self.scalar_objective = scalar_objective\n # whether or not the objf uses numpy\n # if jac is provided it is assumed it is in the same basis\n\n if self.scalar_objective:\n # Direct scalar minimization\n if solver_numpy:\n if not objf_numpy:\n self.objf = self.objf_python_return_numpy_scalar\n else:\n self.objf = self.objf_counting\n else:\n if objf_numpy:\n self.objf = self.objf_numpy_return_python_scalar\n else:\n self.objf = self.objf_counting\n else:\n\n if method in scipy_minimize_options_set:\n self.minimizing = True\n if jacobian_method == \"scipy\" and method in scipy_requires_jacobian_options_set:\n self.jacobian_method = \"python\"\n self.objf = self.objf_numpy_minimizing if objf_numpy else self.objf_python_minimizing\n elif solver_numpy:\n if not objf_numpy:\n self.objf = self.objf_python_return_numpy\n else:\n self.objf = self.objf_counting\n else:\n if objf_numpy:\n self.objf = self.objf_numpy_return_python\n else:\n self.objf = self.objf_counting\n\n if self.minimizing:\n if objf_numpy:\n self.solver_analytical_jac = self.jac_minimizing_numpy\n else:\n self.solver_analytical_jac = self.jac_minimizing\n else:\n self.solver_analytical_jac = self.original_jac\n\n\n\n\n\n def hessian(self, x, base=None, args=()):\n self.hess_iter += 1\n fval_iter, hessian_method, objf_numpy, hessian_numpy = self.fval_iter, self.hessian_method, self.objf_numpy, self.hessian_numpy\n return_numpy = type(x) is not list\n\n if self.scalar_objective:\n # For scalar objectives, always use the efficient scalar calculator\n if not self.hessian_numpy:\n x = x if type(x) is list else x.tolist()\n else:\n x = np.array(x)\n # Use the correct objf based on numpy/python preferences\n if self.objf_numpy:\n objf = self.objf_counting\n else:\n objf = self.objf_python_return_numpy if self.hessian_numpy else self.objf_counting\n\n h = hessian(objf, x, scalar=True,\n perturbation=self.jacobian_perturbation,\n zero_offset=self.jacobian_zero_offset,\n args=args)\n else:\n if hessian_method == \"analytical\":\n if objf_numpy and not return_numpy:\n x = np.array(x)\n elif return_numpy and not objf_numpy:\n x = x.tolist()\n raise NotImplementedError\n h = self.solver_analytical_hess(x, *args)\n else:\n # if the hessian method doesn't speak numpy, convert x to a list\n if not hessian_numpy:\n x = x if type(x) is list else x.tolist()\n else:\n x = np.array(x)\n # If the objf doesn't speak numpy but the hessian does, use the converter\n if self.minimizing:\n if objf_numpy:\n objf = self.objf_numpy_minimizing\n else:\n objf = self.objf_python_minimizing\n else:\n if not hessian_numpy:\n if objf_numpy:\n objf = self.objf_numpy_return_python\n else:\n objf = self.objf_counting\n else:\n if objf_numpy:\n objf = self.objf_counting\n else:\n objf = self.objf_python_return_numpy\n\n if hessian_method.startswith(\"numdifftools\"):\n import numdifftools as nd\n if hessian_method == \"python\":\n h = hessian(objf, x, scalar=self.minimizing, perturbation=1e-4,\n zero_offset=self.jacobian_zero_offset, args=args)\n\n elif hessian_method == \"numdifftools_forward\":\n h = nd.Hessian(objf, method=\"forward\")(x)\n elif hessian_method == \"numdifftools_reverse\":\n h = nd.Hessian(objf, method=\"reverse\")(x)\n elif hessian_method == \"numdifftools_central\":\n h = nd.Hessian(objf, method=\"central\")(x)\n\n # Up the hessian fval count, set the fval back\n self.hess_fval_count += self.fval_iter - fval_iter\n self.fval_iter = fval_iter\n\n if return_numpy:\n return np.array(h) if type(h) is list else h\n else:\n return h if type(h) is list else h.tolist()\n\n def jacobian(self, x, *args):\n \"\"\"\n jacobi - doesn't support jacobian_perturbation, jacobian_zero_offset, jacobian_order\n python - doesn't support jacobian_order\n \"\"\"\n self.jac_iter += 1\n fval_iter, jacobian_method, objf_numpy, jacobian_numpy = self.fval_iter, self.jacobian_method, self.objf_numpy, self.jacobian_numpy\n return_numpy = type(x) is not list\n if self.scalar_objective:\n # For scalar objectives, always use the efficient scalar calculator\n if not self.jacobian_numpy:\n x = x if type(x) is list else x.tolist()\n else:\n x = np.array(x)\n\n # Use the correct objf based on numpy/python preferences\n if self.objf_numpy:\n objf = self.objf_counting\n else:\n objf = self.objf_python_return_numpy if self.jacobian_numpy else self.objf_counting\n\n j = jacobian(objf, x, scalar=True,\n perturbation=self.jacobian_perturbation,\n zero_offset=self.jacobian_zero_offset,\n args=args)\n else:\n if jacobian_method == \"analytical\":\n if objf_numpy and not return_numpy:\n x = np.array(x)\n elif return_numpy and not objf_numpy:\n x = x.tolist()\n j = self.solver_analytical_jac(x, *args)\n else:\n # if the jacobian method doesn't speak numpy, convert x to a list\n if not jacobian_numpy:\n x = x if type(x) is list else x.tolist()\n else:\n x = np.array(x)\n # If the objf doesn't speak numpy but the jacobian does, use the converter\n if self.minimizing:\n if objf_numpy:\n objf = self.objf_numpy_minimizing\n else:\n objf = self.objf_python_minimizing\n else:\n if not jacobian_numpy:\n if objf_numpy:\n objf = self.objf_numpy_return_python\n else:\n objf = self.objf_counting\n else:\n if objf_numpy:\n objf = self.objf_counting\n else:\n objf = self.objf_python_return_numpy\n\n if jacobian_method.startswith(\"numdifftools\"):\n import numdifftools as nd\n numdifftools_func = nd.Gradient if self.minimizing else nd.Jacobian\n step = self.jacobian_perturbation*x\n step[np.where(step==0)] = self.jacobian_zero_offset\n elif jacobian_method.startswith(\"jacobi\"):\n from jacobi import jacobi\n if jacobian_method == \"python\":\n j = jacobian(objf, x, scalar=self.minimizing, perturbation=self.jacobian_perturbation,\n zero_offset=self.jacobian_zero_offset, args=args)\n\n elif jacobian_method == \"numdifftools_forward\":\n j = numdifftools_func(objf, method=\"forward\", order=self.jacobian_order, step=step)(x)\n elif jacobian_method == \"numdifftools_reverse\":\n j = numdifftools_func(objf, method=\"reverse\", order=self.jacobian_order, step=step)(x)\n elif jacobian_method == \"numdifftools_central\":\n j = numdifftools_func(objf, method=\"central\", order=self.jacobian_order, step=step)(x)\n\n elif jacobian_method == \"jacobi_forward\":\n j = jacobi(objf, x, method=1)[0]\n elif jacobian_method == \"jacobi_central\":\n j = jacobi(objf, x, method=0)[0]\n elif jacobian_method == \"jacobi_backward\":\n j = jacobi(objf, x, method=1)[0]\n\n # Up the jacobian fval count, set the fval back\n self.jac_fval_count += self.fval_iter - fval_iter\n self.fval_iter = fval_iter\n # Handle the return value - doesn't matter what type the method returns\n # if (not (jacobian_numpy ^ return_numpy)) or (return_numpy and jacobian_numpy):\n # return j\n # elif return_numpy and not jacobian_numpy:\n # return np.array(j)\n # elif jacobian_numpy and not return_numpy:\n # return j.tolist()\n\n if return_numpy:\n return np.array(j) if type(j) is list else j\n else:\n return j if type(j) is list else j.tolist()\n\n def solve(self, x0, args=()):\n self.fval_iter = self.jac_iter = self.jac_fval_count = self.hess_iter = self.hess_fval_count = 0\n return_numpy = type(x0) is not list\n if self.solver_numpy:\n x0 = np.array(x0)\n elif return_numpy:\n x0 = x0.tolist()\n\n process_root = False\n method = self.method\n if method == \"newton_system\":\n sln, niter = newton_system(self.objf, x0, jac=self.jacobian, xtol=self.xtol, args=args,\n ytol=self.ytol, maxiter=self.maxiter, damping=self.damping,\n solve_func=self.matrix_solver)\n elif method == \"newton_system_line_search\":\n sln, niter = newton_system(self.objf, x0, jac=self.jacobian, xtol=self.xtol, args=args,\n ytol=self.ytol, maxiter=self.maxiter, damping=self.damping,\n line_search=True, solve_func=self.matrix_solver, require_progress=False,\n check_numbers=True, Armijo=True)\n elif method == \"newton_system_line_search_progress\":\n sln, niter = newton_system(self.objf, x0, jac=self.jacobian, xtol=self.xtol, args=args,\n ytol=self.ytol, maxiter=self.maxiter, damping=self.damping,\n line_search=True, solve_func=self.matrix_solver, require_progress=True,\n check_numbers=True, Armijo=True)\n elif method == \"homotopy_solver\":\n sln, niter = homotopy_solver(self.objf, x0, jac=self.jacobian, xtol=self.xtol, args=args,\n ytol=self.ytol, maxiter=self.maxiter, damping=self.damping,\n line_search=True, solve_func=self.matrix_solver)\n elif method == \"broyden2_python\":\n sln, niter = broyden2(x0, self.objf, self.jacobian, xtol=self.xtol, maxiter=self.maxiter,\n args=args)\n elif method == \"fixed_point\":\n sln, niter = fixed_point(residual_to_fixed_point(self.objf), x0, xtol=self.xtol, args=args, ytol=self.ytol, maxiter=self.maxiter, damping=self.damping)\n elif method == \"fixed_point_aitken\":\n sln, niter = fixed_point_aitken(residual_to_fixed_point(self.objf), x0, xtol=self.xtol, args=args, ytol=self.ytol, maxiter=self.maxiter, damping=self.damping)\n elif method == \"fixed_point_gdem\":\n sln, niter = fixed_point_gdem(residual_to_fixed_point(self.objf), x0, xtol=self.xtol, args=args, ytol=self.ytol, maxiter=self.maxiter, damping=self.damping)\n elif method == \"fixed_point_anderson\":\n sln, niter = fixed_point_anderson_residual(residual_to_fixed_point(self.objf), x0, xtol=self.xtol, args=args, ytol=self.ytol, maxiter=self.maxiter, window_size=5, reg=1e-8, initial_iterations=5, acc_damping=0.3, damping=1.0)\n elif method in scipy_root_options_set:\n process_root = True\n jacobian_method = self.jacobian_method\n jac = self.jacobian if jacobian_method != \"scipy\" else None\n result = root(self.objf, x0, args=args, method=method, jac=jac, tol=self.xtol)\n elif method in scipy_minimize_options_set:\n process_root = True\n jacobian_method = self.jacobian_method\n jac = self.jacobian if jacobian_method != \"scipy\" else None\n hess = self.hessian if method in scipy_requires_hessian_options_set else None\n result = minimize(self.objf, x0, args=args, method=method, jac=jac, tol=self.xtol, hess=hess)\n elif method == \"newton_minimize\":\n sln, niter = newton_minimize(\n self.objf, x0, jac=self.jacobian, hess=self.hessian,\n xtol=self.xtol, ytol=self.ytol,\n maxiter=self.maxiter, damping=self.damping,\n args=args)\n if process_root:\n sln = result.x\n\n if not return_numpy:\n sln = sln.tolist()\n elif return_numpy:\n sln = np.array(sln)\n\n return sln", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 18910}, "tests/test_numerics.py::190": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["assert_close", "interp", "linspace"], "enclosing_function": "test_interp", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):\n \"\"\"Port of numpy's linspace to pure python.\n\n Does not support dtype, and returns lists of floats.\n \"\"\"\n num = int(num)\n start = start * 1.\n stop = stop * 1.\n\n if num <= 0:\n return []\n if endpoint:\n if num == 1:\n return [start]\n step = (stop-start)/float(num-1)\n if num == 1:\n step = nan\n\n y = [start]\n for _ in range(num-2):\n y.append(y[-1] + step)\n y.append(stop)\n else:\n step = (stop-start)/float(num)\n if num == 1:\n step = nan\n y = [start]\n for _ in range(num-1):\n y.append(y[-1] + step)\n\n if retstep:\n return y, step\n else:\n return y\n\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 1404}, "tests/test_numerics.py::193": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["assert_close", "interp", "linspace"], "enclosing_function": "test_interp", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):\n \"\"\"Port of numpy's linspace to pure python.\n\n Does not support dtype, and returns lists of floats.\n \"\"\"\n num = int(num)\n start = start * 1.\n stop = stop * 1.\n\n if num <= 0:\n return []\n if endpoint:\n if num == 1:\n return [start]\n step = (stop-start)/float(num-1)\n if num == 1:\n step = nan\n\n y = [start]\n for _ in range(num-2):\n y.append(y[-1] + step)\n y.append(stop)\n else:\n step = (stop-start)/float(num)\n if num == 1:\n step = nan\n y = [start]\n for _ in range(num-1):\n y.append(y[-1] + step)\n\n if retstep:\n return y, step\n else:\n return y\n\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 1404}, "tests/test_numerics_arrays.py::1867": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/arrays.py"], "used_names": ["assert_close2d", "matrix_multiply", "pytest"], "enclosing_function": "test_matrix_multiply", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close2d(a, b, rtol=1e-7, atol=0.0):\n# N = len(a)\n# if N != len(b):\n# raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n# for i in range(N):\n# assert_close1d(a[i], b[i], rtol=rtol, atol=atol)\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n if not __debug__:\n # Do not run these branches in -O, -OO mode\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n for i in range(N):\n a0, b0 = a[i], b[i]\n N0 = len(a0)\n if N0 != len(b0):\n raise ValueError(f\"Variables are not the same length: {N0}, {len(b0)}\")\n for j in range(N0):\n# assert_close(a0[j], b0[j], rtol=rtol, atol=atol)\n good = True\n a1, b1 = a0[j], b0[j]\n if a1 is b1:\n # Nice to handle None\n pass\n else:\n try:\n try:\n good = isclose(a1, b1, rel_tol=rtol, abs_tol=atol)\n except:\n good = cisclose(a1, b1, rel_tol=rtol, abs_tol=atol)\n except:\n pass\n if not good:\n from numpy.testing import assert_allclose\n return assert_allclose(a1, b1, rtol=rtol, atol=atol)\n\n\n# Source: fluids/numerics/arrays.py\ndef matrix_multiply(A, B):\n r\"\"\"Multiply two matrices using pure Python.\n\n Computes the matrix product C = A·B where A is an mxp matrix and B is a pxn matrix,\n resulting in an mxn matrix C.\n\n Parameters\n ----------\n A : list[list[float]]\n First matrix as list of lists, with shape (m, p)\n B : list[list[float]]\n Second matrix as list of lists, with shape (p, n)\n\n Returns\n -------\n list[list[float]]\n Resulting matrix C with shape (m, n)\n\n Examples\n --------\n >>> A = [[1, 2], [3, 4]]\n >>> B = [[5, 6], [7, 8]]\n >>> matrix_multiply(A, B)\n [[19.0, 22.0], [43.0, 50.0]]\n\n Notes\n -----\n Uses a straightforward three-loop implementation optimized for pure Python:\n C[i,j] = sum(A[i,k] * B[k,j] for k in range(p))\n\n The implementation avoids repeated len() calls and list accesses by caching\n frequently used values.\n\n Raises\n ------\n ValueError\n If matrices have incompatible dimensions for multiplication\n If input matrices are empty or irregular (rows of different lengths)\n TypeError\n If A or B contains non-numeric values or is not a list of lists.\n \"\"\"\n # Input validation\n if not A or not A[0] or not B or not B[0]:\n raise ValueError(\"Empty matrices cannot be multiplied\")\n\n # Get dimensions\n m = len(A) # rows in A\n p = len(A[0]) if m else 0 # cols in A = rows in B\n n = len(B[0]) if B else 0 # cols in B\n\n # Validate dimensions\n if not all(len(row) == p for row in A):\n raise ValueError(\"First matrix has irregular row lengths\")\n if len(B) != p:\n raise ValueError(f\"Incompatible dimensions: A is {m}x{p}, B is {len(B)}x{n}\")\n if not all(len(row) == n for row in B):\n raise ValueError(\"Second matrix has irregular row lengths\")\n\n # Pre-allocate result matrix with zeros\n C = [[0.0] * n for _ in range(m)]\n\n # Compute product using simple indexed loops\n for i in range(m):\n A_i = A[i] # Cache current row of A\n C_i = C[i] # Cache current row of C\n for j in range(n):\n tot = 0.0\n for k in range(p):\n tot += A_i[k] * B[k][j]\n C_i[j] = tot\n\n return C", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 3693}, "tests/test_numerics_doubledouble.py::293": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/doubledouble.py"], "used_names": ["assert_close", "exp_dd"], "enclosing_function": "test_exp_dd", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/numerics/doubledouble.py\ndef exp_dd(r, e):\n n = round(r)\n xr, xe = add_dd(r, e, -n, 0)\n ur, ue = add_dd(xr, xe, dd_exp_coeffs[0], 0)\n\n for i in range(1, 12):\n ur, ue = mul_dd(xr, xe, ur, ue)\n ur, ue = add_dd(ur, ue, dd_exp_coeffs[i], 0)\n\n vr, ve = add_dd(xr, xe, -dd_exp_coeffs[0], 0)\n f = 1.0\n for i in range(1, 12):\n vr, ve = mul_dd(xr, xe, vr, ve)\n vr, ve = add_dd(vr, ve, f*dd_exp_coeffs[i], 0)\n f *= -1.0\n\n outr, oute = intpow_dd(2.718281828459045, 1.4456468917292502e-16, n)\n outr, oute = mul_dd(outr, oute, ur, ue)\n outr, oute = div_dd(outr, oute, vr, ve)\n return outr, oute", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1276}, "tests/test_numerics_polynomial_roots.py::98": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/polynomial_roots.py"], "used_names": ["assert_close", "roots_cubic_a2"], "enclosing_function": "test_roots_cubic_a2", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/numerics/polynomial_roots.py\ndef roots_cubic_a2(a, b, c, d):\n # Output from maple\n t2 = a*a\n t3 = d*d\n t10 = c*c\n t14 = b*b\n t15 = t14*b\n t20 = csqrt(-18.0*a*b*c*d + 4.0*a*t10*c + 4.0*t15*d - t14*t10 + 27.0*t2*t3)\n t31 = (36.0*c*b*a + 12.0*root_three*t20*a - 108.0*d*t2 - 8.0*t15)**third\n t32 = 1.0/a\n root1 = t31*t32*sixth - two_thirds*(3.0*a*c - t14)*t32/t31 - b*t32*third\n t33 = t31*t32\n t40 = (3.0*a*c - t14)*t32/t31\n\n t50 = -t33*twelfth + t40*third - b*t32*third\n t51 = 0.5j*root_three *(t33*sixth + two_thirds*t40)\n root2 = t50 + t51\n root3 = t50 - t51\n return (root1, root2, root3)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 1266}, "tests/test_numerics_polynomial_utils.py::81": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["assert_close", "assert_close1d", "polyint_over_x"], "enclosing_function": "test_polyint_over_x", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 846}, "tests/test_particle_size_distribution.py::67": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/particle_size_distribution.py"], "used_names": ["ASTM_E11_sieves", "assert_close"], "enclosing_function": "test_ASTM_E11_sieves", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/particle_size_distribution.py\nASTM_E11_sieves = {\"0.02\": Sieve(calibration_samples=300.0, d_wire_min=2e-08, d_wire=2e-08, inspection_sd=4.51, calibration_sd=4.75, old_designation=\"No. 635\", opening=2e-05, compliance_samples=1000.0, opening_inch=8e-07, inspection_samples=100.0, designation=\"0.02\", d_wire_max=2e-08, max_opening=0.035, X_variation_max=1.5e-05, Y_variation_avg=2.3e-06, compliance_sd=5.33),\n \"0.025\": Sieve(calibration_samples=300.0, d_wire_min=2e-08, d_wire=3e-08, inspection_sd=4.82, calibration_sd=5.06, old_designation=\"No. 500\", opening=2.5e-05, compliance_samples=1000.0, opening_inch=1e-06, inspection_samples=100.0, designation=\"0.025\", d_wire_max=3e-08, max_opening=0.041, X_variation_max=1.6e-05, Y_variation_avg=2.5e-06, compliance_sd=5.71),\n \"0.032\": Sieve(calibration_samples=300.0, d_wire_min=2e-08, d_wire=3e-08, inspection_sd=5.42, calibration_sd=5.71, old_designation=\"No. 450\", opening=3.2e-05, compliance_samples=1000.0, opening_inch=1.2e-06, inspection_samples=100.0, designation=\"0.032\", d_wire_max=3e-08, max_opening=0.05, X_variation_max=1.8e-05, Y_variation_avg=2.7e-06, compliance_sd=6.42),\n \"0.038\": Sieve(calibration_samples=300.0, d_wire_min=2e-08, d_wire=3e-08, inspection_sd=5.99, calibration_sd=6.31, old_designation=\"No. 400\", opening=3.8e-05, compliance_samples=1000.0, opening_inch=1.5e-06, inspection_samples=100.0, designation=\"0.038\", d_wire_max=3e-08, max_opening=0.058, X_variation_max=2e-05, Y_variation_avg=2.9e-06, compliance_sd=7.09),\n \"0.045\": Sieve(calibration_samples=250.0, d_wire_min=3e-08, d_wire=3e-08, inspection_sd=6.56, calibration_sd=6.84, old_designation=\"No. 325\", opening=4.5e-05, compliance_samples=1000.0, opening_inch=1.7e-06, inspection_samples=100.0, designation=\"0.045\", d_wire_max=4e-08, max_opening=0.067, X_variation_max=2.2e-05, Y_variation_avg=3.1e-06, compliance_sd=7.76),\n \"0.053\": Sieve(calibration_samples=250.0, d_wire_min=3e-08, d_wire=4e-08, inspection_sd=7.13, calibration_sd=7.44, old_designation=\"No. 270\", opening=5.3e-05, compliance_samples=1000.0, opening_inch=2.1e-06, inspection_samples=100.0, designation=\"0.053\", d_wire_max=4e-08, max_opening=0.077, X_variation_max=2.4e-05, Y_variation_avg=3.4e-06, compliance_sd=8.44),\n \"0.063\": Sieve(calibration_samples=250.0, d_wire_min=4e-08, d_wire=5e-08, inspection_sd=7.76, calibration_sd=8.09, old_designation=\"No. 230\", opening=6.3e-05, compliance_samples=1000.0, opening_inch=2.5e-06, inspection_samples=100.0, designation=\"0.063\", d_wire_max=5e-08, max_opening=0.089, X_variation_max=2.6e-05, Y_variation_avg=3.7e-06, compliance_sd=9.18),\n \"0.075\": Sieve(calibration_samples=250.0, d_wire_min=4e-08, d_wire=5e-08, inspection_sd=8.64, calibration_sd=9.02, old_designation=\"No. 200\", opening=7.5e-05, compliance_samples=1000.0, opening_inch=2.9e-06, inspection_samples=100.0, designation=\"0.075\", d_wire_max=6e-08, max_opening=0.104, X_variation_max=2.9e-05, Y_variation_avg=4.1e-06, compliance_sd=10.23),\n \"0.09\": Sieve(calibration_samples=200.0, d_wire_min=5e-08, d_wire=6e-08, inspection_sd=9.53, calibration_sd=9.8, old_designation=\"No. 170\", opening=9e-05, compliance_samples=1000.0, opening_inch=3.5e-06, inspection_samples=100.0, designation=\"0.09\", d_wire_max=7e-08, max_opening=0.122, X_variation_max=3.2e-05, Y_variation_avg=4.6e-06, compliance_sd=11.27),\n \"0.106\": Sieve(calibration_samples=200.0, d_wire_min=6e-08, d_wire=7e-08, inspection_sd=10.47, calibration_sd=10.77, old_designation=\"No. 140\", opening=0.000106, compliance_samples=1000.0, opening_inch=4.1e-06, inspection_samples=100.0, designation=\"0.106\", d_wire_max=8e-08, max_opening=0.141, X_variation_max=3.5e-05, Y_variation_avg=5.2e-06, compliance_sd=12.39),\n \"0.125\": Sieve(calibration_samples=200.0, d_wire_min=8e-08, d_wire=9e-08, inspection_sd=11.41, calibration_sd=11.74, old_designation=\"No. 120\", opening=0.000125, compliance_samples=1000.0, opening_inch=4.9e-06, inspection_samples=100.0, designation=\"0.125\", d_wire_max=1e-07, max_opening=0.163, X_variation_max=3.8e-05, Y_variation_avg=5.8e-06, compliance_sd=13.51),\n \"0.15\": Sieve(calibration_samples=200.0, d_wire_min=9e-08, d_wire=1e-07, inspection_sd=12.93, calibration_sd=13.3, old_designation=\"No. 100\", opening=0.00015, compliance_samples=1000.0, opening_inch=5.9e-06, inspection_samples=100.0, designation=\"0.15\", d_wire_max=1.2e-07, max_opening=0.193, X_variation_max=4.3e-05, Y_variation_avg=6.6e-06, compliance_sd=15.3),\n \"0.18\": Sieve(calibration_samples=200.0, d_wire_min=1.1e-07, d_wire=1.2e-07, inspection_sd=14.24, calibration_sd=14.65, old_designation=\"No. 80\", opening=0.00018, compliance_samples=1000.0, opening_inch=7e-06, inspection_samples=100.0, designation=\"0.18\", d_wire_max=1.5e-07, max_opening=0.227, X_variation_max=4.7e-05, Y_variation_avg=7.6e-06, compliance_sd=16.85),\n \"0.212\": Sieve(calibration_samples=160.0, d_wire_min=1.2e-07, d_wire=1.4e-07, inspection_sd=15.59, calibration_sd=16.08, old_designation=\"No. 70\", opening=0.000212, compliance_samples=800.0, opening_inch=8.3e-06, inspection_samples=80.0, designation=\"0.212\", d_wire_max=1.7e-07, max_opening=0.264, X_variation_max=5.2e-05, Y_variation_avg=8.7e-06, compliance_sd=18.79),\n \"0.25\": Sieve(calibration_samples=160.0, d_wire_min=1.3e-07, d_wire=1.6e-07, inspection_sd=17.44, calibration_sd=17.99, old_designation=\"No. 60\", opening=0.00025, compliance_samples=800.0, opening_inch=9.8e-06, inspection_samples=80.0, designation=\"0.25\", d_wire_max=1.9e-07, max_opening=0.308, X_variation_max=5.8e-05, Y_variation_avg=9.9e-06, compliance_sd=21.02),\n \"0.3\": Sieve(calibration_samples=160.0, d_wire_min=1.7e-07, d_wire=2e-07, inspection_sd=19.66, calibration_sd=20.29, old_designation=\"No. 50\", opening=0.0003, compliance_samples=800.0, opening_inch=1.17e-05, inspection_samples=80.0, designation=\"0.3\", d_wire_max=2.3e-07, max_opening=0.365, X_variation_max=6.5e-05, Y_variation_avg=1.15e-05, compliance_sd=23.7),\n \"0.355\": Sieve(calibration_samples=160.0, d_wire_min=1.9e-07, d_wire=2.2e-07, inspection_sd=21.95, calibration_sd=22.64, old_designation=\"No. 45\", opening=0.000355, compliance_samples=800.0, opening_inch=1.39e-05, inspection_samples=80.0, designation=\"0.355\", d_wire_max=2.6e-07, max_opening=0.427, X_variation_max=7.2e-05, Y_variation_avg=1.33e-05, compliance_sd=26.45),\n \"0.425\": Sieve(calibration_samples=120.0, d_wire_min=2.4e-07, d_wire=2.8e-07, inspection_sd=24.2, calibration_sd=25.08, old_designation=\"No. 40\", opening=0.000425, compliance_samples=600.0, opening_inch=1.65e-05, inspection_samples=60.0, designation=\"0.425\", d_wire_max=3.2e-07, max_opening=0.506, X_variation_max=8.1e-05, Y_variation_avg=1.55e-05, compliance_sd=29.95),\n \"0.5\": Sieve(calibration_samples=120.0, d_wire_min=2.7e-07, d_wire=3.2e-07, inspection_sd=26.85, calibration_sd=27.82, old_designation=\"No. 35\", opening=0.0005, compliance_samples=600.0, opening_inch=1.97e-05, inspection_samples=60.0, designation=\"0.5\", d_wire_max=3.6e-07, max_opening=0.589, X_variation_max=8.9e-05, Y_variation_avg=1.8e-05, compliance_sd=33.23),\n \"0.6\": Sieve(calibration_samples=100.0, d_wire_min=3.4e-07, d_wire=4e-07, inspection_sd=30.14, calibration_sd=31.32, old_designation=\"No. 30\", opening=0.0006, compliance_samples=500.0, opening_inch=2.34e-05, inspection_samples=50.0, designation=\"0.6\", d_wire_max=4.6e-07, max_opening=0.701, X_variation_max=0.000101, Y_variation_avg=2.12e-05, compliance_sd=38.0),\n \"0.71\": Sieve(calibration_samples=100.0, d_wire_min=3.8e-07, d_wire=4.5e-07, inspection_sd=33.82, calibration_sd=35.14, old_designation=\"No. 25\", opening=0.00071, compliance_samples=500.0, opening_inch=2.78e-05, inspection_samples=50.0, designation=\"0.71\", d_wire_max=5.2e-07, max_opening=0.822, X_variation_max=0.000112, Y_variation_avg=2.47e-05, compliance_sd=42.63),\n \"0.85\": Sieve(calibration_samples=80.0, d_wire_min=4.3e-07, d_wire=5e-07, inspection_sd=37.73, calibration_sd=39.36, old_designation=\"No. 20\", opening=0.00085, compliance_samples=400.0, opening_inch=3.31e-05, inspection_samples=40.0, designation=\"0.85\", d_wire_max=5.8e-07, max_opening=0.977, X_variation_max=0.000127, Y_variation_avg=2.91e-05, compliance_sd=48.76),\n \"1\": Sieve(calibration_samples=80.0, d_wire_min=0.00048, d_wire=0.00056, inspection_sd=0.042, calibration_sd=0.044, old_designation=\"No. 18\", opening=0.001, compliance_samples=400.0, opening_inch=3.94e-05, inspection_samples=40.0, designation=\"1\", d_wire_max=0.00064, max_opening=1.14, X_variation_max=0.00014, Y_variation_avg=3.4e-05, compliance_sd=0.055),\n \"1.18\": Sieve(calibration_samples=80.0, d_wire_min=0.00054, d_wire=0.00063, inspection_sd=0.049, calibration_sd=0.051, old_designation=\"No. 16\", opening=0.00118, compliance_samples=400.0, opening_inch=4.69e-05, inspection_samples=40.0, designation=\"1.18\", d_wire_max=0.00072, max_opening=1.34, X_variation_max=0.00016, Y_variation_avg=4e-05, compliance_sd=0.063),\n \"1.4\": Sieve(calibration_samples=80.0, d_wire_min=0.0006, d_wire=0.00071, inspection_sd=0.055, calibration_sd=0.057, old_designation=\"No. 14\", opening=0.0014, compliance_samples=400.0, opening_inch=5.55e-05, inspection_samples=40.0, designation=\"1.4\", d_wire_max=0.00082, max_opening=1.58, X_variation_max=0.00018, Y_variation_avg=4.6e-05, compliance_sd=0.071),\n \"1.7\": Sieve(calibration_samples=50.0, d_wire_min=0.00068, d_wire=0.0008, inspection_sd=0.059, calibration_sd=0.062, old_designation=\"No. 12\", opening=0.0017, compliance_samples=250.0, opening_inch=6.61e-05, inspection_samples=25.0, designation=\"1.7\", d_wire_max=0.00092, max_opening=1.9, X_variation_max=0.0002, Y_variation_avg=5.6e-05, compliance_sd=0.081),\n \"100\": Sieve(d_wire_min=0.0054, d_wire=0.0063, old_designation=\"4 in.\", opening=0.1, compliance_samples=20.0, opening_inch=0.004, designation=\"100\", d_wire_max=0.0072, max_opening=103.82, X_variation_max=0.00382, Y_variation_avg=0.00294),\n \"106\": Sieve(d_wire_min=0.0054, d_wire=0.0063, old_designation=\"4.24 in.\", opening=0.106, compliance_samples=20.0, opening_inch=0.00424, designation=\"106\", d_wire_max=0.0072, max_opening=109.99, X_variation_max=0.00399, Y_variation_avg=0.00312),\n \"11.2\": Sieve(calibration_samples=30.0, d_wire_min=0.0021, d_wire=0.0025, inspection_sd=0.256, calibration_sd=0.274, old_designation=\"7/16 in.\", opening=0.0112, compliance_samples=150.0, opening_inch=0.000438, inspection_samples=15.0, designation=\"11.2\", d_wire_max=0.0029, max_opening=11.97, X_variation_max=0.00077, Y_variation_avg=0.000346, compliance_sd=0.382),\n \"12.5\": Sieve(calibration_samples=30.0, d_wire_min=0.0021, d_wire=0.0025, inspection_sd=0.283, calibration_sd=0.302, old_designation=\"1/2 in.\", opening=0.0125, compliance_samples=150.0, opening_inch=0.0005, inspection_samples=15.0, designation=\"12.5\", d_wire_max=0.0029, max_opening=13.33, X_variation_max=0.00083, Y_variation_avg=0.000385, compliance_sd=0.421),\n \"125\": Sieve(d_wire_min=0.0068, d_wire=0.008, old_designation=\"5 in.\", opening=0.125, compliance_samples=20.0, opening_inch=0.005, designation=\"125\", d_wire_max=0.0092, max_opening=129.51, X_variation_max=0.00451, Y_variation_avg=0.00366),\n \"13.2\": Sieve(calibration_samples=30.0, d_wire_min=0.0024, d_wire=0.0028, inspection_sd=0.296, calibration_sd=0.316, old_designation=\"0.530 in.\", opening=0.0132, compliance_samples=150.0, opening_inch=0.00053, inspection_samples=15.0, designation=\"13.2\", d_wire_max=0.0032, max_opening=14.06, X_variation_max=0.00086, Y_variation_avg=0.000406, compliance_sd=0.441),\n \"16\": Sieve(calibration_samples=30.0, d_wire_min=0.0027, d_wire=0.00315, inspection_sd=0.354, calibration_sd=0.378, old_designation=\"5/8 in.\", opening=0.016, compliance_samples=150.0, opening_inch=0.000625, inspection_samples=15.0, designation=\"16\", d_wire_max=0.0036, max_opening=16.99, X_variation_max=0.00099, Y_variation_avg=0.00049, compliance_sd=0.527),\n \"19\": Sieve(calibration_samples=30.0, d_wire_min=0.0027, d_wire=0.00315, inspection_sd=0.418, calibration_sd=0.446, old_designation=\"3/4 in.\", opening=0.019, compliance_samples=150.0, opening_inch=0.00075, inspection_samples=15.0, designation=\"19\", d_wire_max=0.0035, max_opening=20.13, X_variation_max=0.00113, Y_variation_avg=0.000579, compliance_sd=0.622),\n \"2\": Sieve(calibration_samples=50.0, d_wire_min=0.00077, d_wire=0.0009, inspection_sd=0.068, calibration_sd=0.072, old_designation=\"No. 10\", opening=0.002, compliance_samples=250.0, opening_inch=7.87e-05, inspection_samples=25.0, designation=\"2\", d_wire_max=0.00104, max_opening=2.23, X_variation_max=0.00023, Y_variation_avg=6.5e-05, compliance_sd=0.094),\n \"2.36\": Sieve(calibration_samples=40.0, d_wire_min=0.00085, d_wire=0.001, inspection_sd=0.073, calibration_sd=0.077, old_designation=\"No. 8\", opening=0.00236, compliance_samples=200.0, opening_inch=9.37e-05, inspection_samples=20.0, designation=\"2.36\", d_wire_max=0.00115, max_opening=2.61, X_variation_max=0.00025, Y_variation_avg=7.6e-05, compliance_sd=0.104),\n \"2.8\": Sieve(calibration_samples=40.0, d_wire_min=0.00095, d_wire=0.00112, inspection_sd=0.085, calibration_sd=0.09, old_designation=\"No. 7\", opening=0.0028, compliance_samples=200.0, opening_inch=0.00011, inspection_samples=20.0, designation=\"2.8\", d_wire_max=0.0013, max_opening=3.09, X_variation_max=0.00029, Y_variation_avg=9e-05, compliance_sd=0.121),\n \"22.4\": Sieve(d_wire_min=0.003, d_wire=0.00355, inspection_sd=0.493, old_designation=\"7/8 in.\", opening=0.0224, compliance_samples=150.0, opening_inch=0.000875, inspection_samples=15.0, designation=\"22.4\", d_wire_max=0.0041, max_opening=23.67, X_variation_max=0.00127, Y_variation_avg=0.000681, compliance_sd=0.734),\n \"25\": Sieve(d_wire_min=0.003, d_wire=0.00355, inspection_sd=0.553, old_designation=\"1.00 in.\", opening=0.025, compliance_samples=20.0, opening_inch=0.001, inspection_samples=15.0, designation=\"25\", d_wire_max=0.0041, max_opening=26.38, X_variation_max=0.00138, Y_variation_avg=0.000758, compliance_sd=0.823),\n \"26.5\": Sieve(d_wire_min=0.003, d_wire=0.00355, inspection_sd=0.584, old_designation=\"1.06 in.\", opening=0.0265, compliance_samples=20.0, opening_inch=0.00106, inspection_samples=15.0, designation=\"26.5\", d_wire_max=0.0041, max_opening=27.94, X_variation_max=0.00144, Y_variation_avg=0.000802, compliance_sd=0.869),\n \"3.35\": Sieve(calibration_samples=40.0, d_wire_min=0.00106, d_wire=0.00125, inspection_sd=0.097, calibration_sd=0.103, old_designation=\"No. 6\", opening=0.00335, compliance_samples=200.0, opening_inch=0.000132, inspection_samples=20.0, designation=\"3.35\", d_wire_max=0.0015, max_opening=3.67, X_variation_max=0.00032, Y_variation_avg=0.000107, compliance_sd=0.138),\n \"31.5\": Sieve(d_wire_min=0.0034, d_wire=0.004, old_designation=\"1 1/4 in.\", opening=0.0315, compliance_samples=20.0, opening_inch=0.00125, designation=\"31.5\", d_wire_max=0.0046, max_opening=33.13, X_variation_max=0.00163, Y_variation_avg=0.00095, compliance_sd=1.066),\n \"37.5\": Sieve(d_wire_min=0.0038, d_wire=0.0045, old_designation=\"1 1/2 in.\", opening=0.0375, compliance_samples=20.0, opening_inch=0.0015, designation=\"37.5\", d_wire_max=0.0052, max_opening=39.35, X_variation_max=0.00185, Y_variation_avg=0.00113, compliance_sd=1.374),\n \"4\": Sieve(calibration_samples=30.0, d_wire_min=0.0012, d_wire=0.0014, inspection_sd=0.108, calibration_sd=0.115, old_designation=\"No. 5\", opening=0.004, compliance_samples=150.0, opening_inch=0.000157, inspection_samples=15.0, designation=\"4\", d_wire_max=0.0017, max_opening=4.37, X_variation_max=0.00037, Y_variation_avg=0.000127, compliance_sd=0.161),\n \"4.75\": Sieve(calibration_samples=30.0, d_wire_min=0.0013, d_wire=0.0016, inspection_sd=0.123, calibration_sd=0.131, old_designation=\"No. 4\", opening=0.00475, compliance_samples=150.0, opening_inch=0.000187, inspection_samples=15.0, designation=\"4.75\", d_wire_max=0.0019, max_opening=5.16, X_variation_max=0.00041, Y_variation_avg=0.00015, compliance_sd=0.182),\n \"45\": Sieve(d_wire_min=0.0038, d_wire=0.0045, old_designation=\"1 3/4 in.\", opening=0.045, compliance_samples=20.0, opening_inch=0.00175, designation=\"45\", d_wire_max=0.0052, max_opening=47.12, X_variation_max=0.00212, Y_variation_avg=0.00135),\n \"5.6\": Sieve(calibration_samples=30.0, d_wire_min=0.0013, d_wire=0.0016, inspection_sd=0.142, calibration_sd=0.151, old_designation=\"No. 3 1/2\", opening=0.0056, compliance_samples=150.0, opening_inch=0.000223, inspection_samples=15.0, designation=\"5.6\", d_wire_max=0.0019, max_opening=6.07, X_variation_max=0.00047, Y_variation_avg=0.000176, compliance_sd=0.211),\n \"50\": Sieve(d_wire_min=0.0043, d_wire=0.005, old_designation=\"2 in.\", opening=0.05, compliance_samples=20.0, opening_inch=0.002, designation=\"50\", d_wire_max=0.0058, max_opening=52.29, X_variation_max=0.00229, Y_variation_avg=0.00149),\n \"53\": Sieve(d_wire_min=0.0043, d_wire=0.005, old_designation=\"2.12 in.\", opening=0.053, compliance_samples=20.0, opening_inch=0.00212, designation=\"53\", d_wire_max=0.0058, max_opening=55.39, X_variation_max=0.00239, Y_variation_avg=0.00158),\n \"6.3\": Sieve(calibration_samples=30.0, d_wire_min=0.0015, d_wire=0.0018, inspection_sd=0.157, calibration_sd=0.167, old_designation=\"1/4 in.\", opening=0.0063, compliance_samples=150.0, opening_inch=0.00025, inspection_samples=15.0, designation=\"6.3\", d_wire_max=0.0021, max_opening=6.81, X_variation_max=0.00051, Y_variation_avg=0.000197, compliance_sd=0.233),\n \"6.7\": Sieve(calibration_samples=30.0, d_wire_min=0.0015, d_wire=0.0018, inspection_sd=0.164, calibration_sd=0.175, old_designation=\"0.265 in.\", opening=0.0067, compliance_samples=150.0, opening_inch=0.000265, inspection_samples=15.0, designation=\"6.7\", d_wire_max=0.0021, max_opening=7.23, X_variation_max=0.00053, Y_variation_avg=0.00021, compliance_sd=0.245),\n \"63\": Sieve(d_wire_min=0.0048, d_wire=0.0056, old_designation=\"2 1/2 in.\", opening=0.063, compliance_samples=20.0, opening_inch=0.0025, designation=\"63\", d_wire_max=0.0064, max_opening=65.71, X_variation_max=0.00271, Y_variation_avg=0.00187),\n \"75\": Sieve(d_wire_min=0.0054, d_wire=0.0063, old_designation=\"3 in.\", opening=0.075, compliance_samples=20.0, opening_inch=0.003, designation=\"75\", d_wire_max=0.0072, max_opening=78.09, X_variation_max=0.00309, Y_variation_avg=0.00222),\n \"8\": Sieve(calibration_samples=30.0, d_wire_min=0.0017, d_wire=0.002, inspection_sd=0.191, calibration_sd=0.204, old_designation=\"5/16 in.\", opening=0.008, compliance_samples=150.0, opening_inch=0.000312, inspection_samples=15.0, designation=\"8\", d_wire_max=0.0023, max_opening=8.6, X_variation_max=0.0006, Y_variation_avg=0.000249, compliance_sd=0.284),\n \"9.5\": Sieve(calibration_samples=30.0, d_wire_min=0.0019, d_wire=0.00224, inspection_sd=0.222, calibration_sd=0.237, old_designation=\"3/8 in.\", opening=0.0095, compliance_samples=150.0, opening_inch=0.000375, inspection_samples=15.0, designation=\"9.5\", d_wire_max=0.0026, max_opening=10.18, X_variation_max=0.00068, Y_variation_avg=0.000295, compliance_sd=0.33),\n \"90\": Sieve(d_wire_min=0.0054, d_wire=0.0063, old_designation=\"3 1/2 in.\", opening=0.09, compliance_samples=20.0, opening_inch=0.0035, designation=\"90\", d_wire_max=0.0072, max_opening=93.53, X_variation_max=0.00353, Y_variation_avg=0.00265)\n }", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 19633}, "tests/test_particle_size_distribution.py::99": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/particle_size_distribution.py"], "used_names": ["ISO_3310_1_R10", "ISO_3310_1_R20", "ISO_3310_1_R20_3", "ISO_3310_1_R40_3", "ISO_3310_1_sieves", "assert_close"], "enclosing_function": "test_ISO_3310_2_sieves", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/particle_size_distribution.py\nISO_3310_1_sieves = {\n \"0.02\": Sieve(designation=\"0.02\", d_wire_max=2.3e-05, compliance_sd=4.7e-06, X_variation_max=1.3e-05, d_wire=2e-05, Y_variation_avg=2.1e-06, d_wire_min=2.3e-05, opening=2e-05),\n \"0.025\": Sieve(designation=\"0.025\", d_wire_max=2.9e-05, compliance_sd=5.2e-06, X_variation_max=1.5e-05, d_wire=2.5e-05, Y_variation_avg=2.2e-06, d_wire_min=2.9e-05, opening=2.5e-05),\n \"0.032\": Sieve(designation=\"0.032\", d_wire_max=3.3e-05, compliance_sd=5.9e-06, X_variation_max=1.7e-05, d_wire=2.8e-05, Y_variation_avg=2.4e-06, d_wire_min=3.3e-05, opening=3.2e-05),\n \"0.036\": Sieve(designation=\"0.036\", d_wire_max=3.5e-05, compliance_sd=6.3e-06, X_variation_max=1.8e-05, d_wire=3e-05, Y_variation_avg=2.6e-06, d_wire_min=3.5e-05, opening=3.6e-05),\n \"0.038\": Sieve(designation=\"0.038\", d_wire_max=3.5e-05, compliance_sd=6.4e-06, X_variation_max=1.8e-05, d_wire=3e-05, Y_variation_avg=2.6e-06, d_wire_min=3.5e-05, opening=3.8e-05),\n \"0.04\": Sieve(designation=\"0.04\", d_wire_max=3.7e-05, compliance_sd=6.5e-06, X_variation_max=1.9e-05, d_wire=3.2e-05, Y_variation_avg=2.7e-06, d_wire_min=3.7e-05, opening=4e-05),\n \"0.045\": Sieve(designation=\"0.045\", d_wire_max=3.7e-05, compliance_sd=6.9e-06, X_variation_max=2e-05, d_wire=3.2e-05, Y_variation_avg=2.8e-06, d_wire_min=3.7e-05, opening=4.5e-05),\n \"0.05\": Sieve(designation=\"0.05\", d_wire_max=4.1e-05, compliance_sd=7.3e-06, X_variation_max=2.1e-05, d_wire=3.6e-05, Y_variation_avg=3e-06, d_wire_min=4.1e-05, opening=5e-05),\n \"0.053\": Sieve(designation=\"0.053\", d_wire_max=4.1e-05, compliance_sd=7.6e-06, X_variation_max=2.1e-05, d_wire=3.6e-05, Y_variation_avg=3.1e-06, d_wire_min=4.1e-05, opening=5.3e-05),\n \"0.056\": Sieve(designation=\"0.056\", d_wire_max=4.6e-05, compliance_sd=7.8e-06, X_variation_max=2.2e-05, d_wire=4e-05, Y_variation_avg=3.2e-06, d_wire_min=4.6e-05, opening=5.6e-05),\n \"0.063\": Sieve(designation=\"0.063\", d_wire_max=5.2e-05, compliance_sd=8.3e-06, X_variation_max=2.4e-05, d_wire=4.5e-05, Y_variation_avg=3.4e-06, d_wire_min=5.2e-05, opening=6.3e-05),\n \"0.071\": Sieve(designation=\"0.071\", d_wire_max=5.8e-05, compliance_sd=8.9e-06, X_variation_max=2.5e-05, d_wire=5e-05, Y_variation_avg=3.6e-06, d_wire_min=4.3e-05, opening=7.1e-05),\n \"0.075\": Sieve(designation=\"0.075\", d_wire_max=5.8e-05, compliance_sd=9.1e-06, X_variation_max=2.6e-05, d_wire=5e-05, Y_variation_avg=3.7e-06, d_wire_min=4.3e-05, opening=7.5e-05),\n \"0.08\": Sieve(designation=\"0.08\", d_wire_max=6.4e-05, compliance_sd=9.4e-06, X_variation_max=2.7e-05, d_wire=5.6e-05, Y_variation_avg=3.9e-06, d_wire_min=4.8e-05, opening=8e-05),\n \"0.09\": Sieve(designation=\"0.09\", d_wire_max=7.2e-05, compliance_sd=1.01e-05, X_variation_max=2.9e-05, d_wire=6.3e-05, Y_variation_avg=4.2e-06, d_wire_min=5.4e-05, opening=9e-05),\n \"0.1\": Sieve(designation=\"0.1\", d_wire_max=8.2e-05, compliance_sd=1.08e-05, X_variation_max=3e-05, d_wire=7.1e-05, Y_variation_avg=4.5e-06, d_wire_min=6e-05, opening=0.0001),\n \"0.106\": Sieve(designation=\"0.106\", d_wire_max=8.2e-05, compliance_sd=1.11e-05, X_variation_max=3.1e-05, d_wire=7.1e-05, Y_variation_avg=4.7e-06, d_wire_min=6e-05, opening=0.000106),\n \"0.112\": Sieve(designation=\"0.112\", d_wire_max=9.2e-05, compliance_sd=1.15e-05, X_variation_max=3.2e-05, d_wire=8e-05, Y_variation_avg=4.8e-06, d_wire_min=6.8e-05, opening=0.000112),\n \"0.125\": Sieve(designation=\"0.125\", d_wire_max=0.000104, compliance_sd=1.22e-05, X_variation_max=3.4e-05, d_wire=9e-05, Y_variation_avg=5.2e-06, d_wire_min=7.7e-05, opening=0.000125),\n \"0.14\": Sieve(designation=\"0.14\", d_wire_max=0.000115, compliance_sd=1.31e-05, X_variation_max=3.7e-05, d_wire=0.0001, Y_variation_avg=5.7e-06, d_wire_min=8.5e-05, opening=0.00014),\n \"0.15\": Sieve(designation=\"0.15\", d_wire_max=0.000115, compliance_sd=1.37e-05, X_variation_max=3.8e-05, d_wire=0.0001, Y_variation_avg=6e-06, d_wire_min=8.5e-05, opening=0.00015),\n \"0.16\": Sieve(designation=\"0.16\", d_wire_max=0.00013, compliance_sd=1.42e-05, X_variation_max=4e-05, d_wire=0.000112, Y_variation_avg=6.3e-06, d_wire_min=9.5e-05, opening=0.00016),\n \"0.18\": Sieve(designation=\"0.18\", d_wire_max=0.00015, compliance_sd=1.53e-05, X_variation_max=4.3e-05, d_wire=0.000125, Y_variation_avg=6.8e-06, d_wire_min=0.000106, opening=0.00018),\n \"0.2\": Sieve(designation=\"0.2\", d_wire_max=0.00017, compliance_sd=1.63e-05, X_variation_max=4.5e-05, d_wire=0.00014, Y_variation_avg=7.4e-06, d_wire_min=0.00012, opening=0.0002),\n \"0.212\": Sieve(designation=\"0.212\", d_wire_max=0.00017, compliance_sd=1.69e-05, X_variation_max=4.7e-05, d_wire=0.00014, Y_variation_avg=7.8e-06, d_wire_min=0.00012, opening=0.000212),\n \"0.224\": Sieve(designation=\"0.224\", d_wire_max=0.00019, compliance_sd=1.75e-05, X_variation_max=4.9e-05, d_wire=0.00016, Y_variation_avg=8.1e-06, d_wire_min=0.00013, opening=0.000224),\n \"0.25\": Sieve(designation=\"0.25\", d_wire_max=0.00019, compliance_sd=1.88e-05, X_variation_max=5.2e-05, d_wire=0.00016, Y_variation_avg=8.9e-06, d_wire_min=0.00013, opening=0.00025),\n \"0.28\": Sieve(designation=\"0.28\", d_wire_max=0.00021, compliance_sd=2.03e-05, X_variation_max=5.6e-05, d_wire=0.00018, Y_variation_avg=1e-05, d_wire_min=0.00015, opening=0.00028),\n \"0.3\": Sieve(designation=\"0.3\", d_wire_max=0.00023, compliance_sd=2.12e-05, X_variation_max=5.8e-05, d_wire=0.0002, Y_variation_avg=1e-05, d_wire_min=0.00017, opening=0.0003),\n \"0.315\": Sieve(designation=\"0.315\", d_wire_max=0.00023, compliance_sd=2.19e-05, X_variation_max=6e-05, d_wire=0.0002, Y_variation_avg=1.1e-05, d_wire_min=0.00017, opening=0.000315),\n \"0.355\": Sieve(designation=\"0.355\", d_wire_max=0.00026, compliance_sd=2.37e-05, X_variation_max=6.5e-05, d_wire=0.000224, Y_variation_avg=1.2e-05, d_wire_min=0.00019, opening=0.000355),\n \"0.4\": Sieve(designation=\"0.4\", d_wire_max=0.00029, compliance_sd=2.57e-05, X_variation_max=7e-05, d_wire=0.00025, Y_variation_avg=1.3e-05, d_wire_min=0.00021, opening=0.0004),\n \"0.425\": Sieve(designation=\"0.425\", d_wire_max=0.00032, compliance_sd=2.68e-05, X_variation_max=7.3e-05, d_wire=0.00028, Y_variation_avg=1.4e-05, d_wire_min=0.00024, opening=0.000425),\n \"0.45\": Sieve(designation=\"0.45\", d_wire_max=0.00032, compliance_sd=2.79e-05, X_variation_max=7.5e-05, d_wire=0.00028, Y_variation_avg=1.5e-05, d_wire_min=0.00024, opening=0.00045),\n \"0.5\": Sieve(designation=\"0.5\", d_wire_max=0.00036, compliance_sd=3e-05, X_variation_max=8e-05, d_wire=0.000315, Y_variation_avg=1.6e-05, d_wire_min=0.00027, opening=0.0005),\n \"0.56\": Sieve(designation=\"0.56\", d_wire_max=0.00041, compliance_sd=3.24e-05, X_variation_max=8.7e-05, d_wire=0.000355, Y_variation_avg=1.8e-05, d_wire_min=0.0003, opening=0.00056),\n \"0.6\": Sieve(designation=\"0.6\", d_wire_max=0.00046, compliance_sd=3.4e-05, X_variation_max=9.1e-05, d_wire=0.0004, Y_variation_avg=1.9e-05, d_wire_min=0.00034, opening=0.0006),\n \"0.63\": Sieve(designation=\"0.63\", d_wire_max=0.00046, compliance_sd=3.52e-05, X_variation_max=9.3e-05, d_wire=0.0004, Y_variation_avg=2e-05, d_wire_min=0.00034, opening=0.00063),\n \"0.71\": Sieve(designation=\"0.71\", d_wire_max=0.00052, compliance_sd=3.84e-05, X_variation_max=0.000101, d_wire=0.00045, Y_variation_avg=2.2e-05, d_wire_min=0.00038, opening=0.00071),\n \"0.8\": Sieve(designation=\"0.8\", d_wire_max=0.00052, compliance_sd=4.18e-05, X_variation_max=0.000109, d_wire=0.00045, Y_variation_avg=2.5e-05, d_wire_min=0.00038, opening=0.0008),\n \"0.85\": Sieve(designation=\"0.85\", d_wire_max=0.00058, compliance_sd=4.36e-05, X_variation_max=0.000114, d_wire=0.0005, Y_variation_avg=2.6e-05, d_wire_min=0.00043, opening=0.00085),\n \"0.9\": Sieve(designation=\"0.9\", d_wire_max=0.00058, compliance_sd=4.55e-05, X_variation_max=0.000118, d_wire=0.0005, Y_variation_avg=2.8e-05, d_wire_min=0.00043, opening=0.0009),\n \"1\": Sieve(designation=\"1\", d_wire_max=0.00064, compliance_sd=4.9e-05, X_variation_max=0.00013, d_wire=0.00056, Y_variation_avg=3e-05, d_wire_min=0.00048, opening=0.001),\n \"1.12\": Sieve(designation=\"1.12\", d_wire_max=0.00064, compliance_sd=5.3e-05, X_variation_max=0.00014, d_wire=0.00056, Y_variation_avg=3e-05, d_wire_min=0.00048, opening=0.00112),\n \"1.18\": Sieve(designation=\"1.18\", d_wire_max=0.00072, compliance_sd=5.6e-05, X_variation_max=0.00014, d_wire=0.00063, Y_variation_avg=4e-05, d_wire_min=0.00054, opening=0.00118),\n \"1.25\": Sieve(designation=\"1.25\", d_wire_max=0.00072, compliance_sd=5.8e-05, X_variation_max=0.00015, d_wire=0.00063, Y_variation_avg=4e-05, d_wire_min=0.00054, opening=0.00125),\n \"1.4\": Sieve(designation=\"1.4\", d_wire_max=0.00082, compliance_sd=6.3e-05, X_variation_max=0.00016, d_wire=0.00071, Y_variation_avg=4e-05, d_wire_min=0.0006, opening=0.0014),\n \"1.6\": Sieve(designation=\"1.6\", d_wire_max=0.00092, compliance_sd=7e-05, X_variation_max=0.00017, d_wire=0.0008, Y_variation_avg=5e-05, d_wire_min=0.00068, opening=0.0016),\n \"1.7\": Sieve(designation=\"1.7\", d_wire_max=0.00092, compliance_sd=7.3e-05, X_variation_max=0.00018, d_wire=0.0008, Y_variation_avg=5e-05, d_wire_min=0.00068, opening=0.0017),\n \"1.8\": Sieve(designation=\"1.8\", d_wire_max=0.00092, compliance_sd=7.6e-05, X_variation_max=0.00019, d_wire=0.0008, Y_variation_avg=5e-05, d_wire_min=0.00068, opening=0.0018),\n \"10\": Sieve(designation=\"10\", d_wire_max=0.0029, compliance_sd=0.000307, X_variation_max=0.00064, d_wire=0.0025, Y_variation_avg=0.00028, d_wire_min=0.0021, opening=0.01),\n \"100\": Sieve(designation=\"100\", d_wire_max=0.0072, X_variation_max=0.00344, d_wire=0.0063, Y_variation_avg=0.00265, d_wire_min=0.0054, opening=0.1),\n \"106\": Sieve(designation=\"106\", d_wire_max=0.0072, X_variation_max=0.00359, d_wire=0.0063, Y_variation_avg=0.0028, d_wire_min=0.0054, opening=0.106),\n \"11.2\": Sieve(designation=\"11.2\", d_wire_max=0.0029, compliance_sd=0.000339, X_variation_max=0.00069, d_wire=0.0025, Y_variation_avg=0.00031, d_wire_min=0.0021, opening=0.0112),\n \"112\": Sieve(designation=\"112\", d_wire_max=0.0092, X_variation_max=0.00374, d_wire=0.008, Y_variation_avg=0.00296, d_wire_min=0.0068, opening=0.112),\n \"12.5\": Sieve(designation=\"12.5\", d_wire_max=0.0029, compliance_sd=0.000374, X_variation_max=0.00075, d_wire=0.0025, Y_variation_avg=0.00035, d_wire_min=0.0021, opening=0.0125),\n \"125\": Sieve(designation=\"125\", d_wire_max=0.0092, X_variation_max=0.00406, d_wire=0.008, Y_variation_avg=0.0033, d_wire_min=0.0068, opening=0.125),\n \"13.2\": Sieve(designation=\"13.2\", d_wire_max=0.0032, compliance_sd=0.000392, X_variation_max=0.00078, d_wire=0.0028, Y_variation_avg=0.00037, d_wire_min=0.0024, opening=0.0132),\n \"14\": Sieve(designation=\"14\", d_wire_max=0.0032, compliance_sd=0.000413, X_variation_max=0.00081, d_wire=0.0028, Y_variation_avg=0.00039, d_wire_min=0.0024, opening=0.014),\n \"16\": Sieve(designation=\"16\", d_wire_max=0.0036, compliance_sd=0.000467, X_variation_max=0.00089, d_wire=0.00315, Y_variation_avg=0.00044, d_wire_min=0.0027, opening=0.016),\n \"18\": Sieve(designation=\"18\", d_wire_max=0.0036, compliance_sd=0.00052, X_variation_max=0.00097, d_wire=0.00315, Y_variation_avg=0.00049, d_wire_min=0.0027, opening=0.018),\n \"19\": Sieve(designation=\"19\", d_wire_max=0.0036, compliance_sd=0.000548, X_variation_max=0.00101, d_wire=0.00315, Y_variation_avg=0.00052, d_wire_min=0.0027, opening=0.019),\n \"2\": Sieve(designation=\"2\", d_wire_max=0.00104, compliance_sd=8.3e-05, X_variation_max=0.0002, d_wire=0.0009, Y_variation_avg=6e-05, d_wire_min=0.00077, opening=0.002),\n \"2.24\": Sieve(designation=\"2.24\", d_wire_max=0.00104, compliance_sd=9e-05, X_variation_max=0.00022, d_wire=0.0009, Y_variation_avg=7e-05, d_wire_min=0.00077, opening=0.00224),\n \"2.36\": Sieve(designation=\"2.36\", d_wire_max=0.00115, compliance_sd=9.4e-05, X_variation_max=0.00023, d_wire=0.001, Y_variation_avg=7e-05, d_wire_min=0.00085, opening=0.00236),\n \"2.5\": Sieve(designation=\"2.5\", d_wire_max=0.00115, compliance_sd=9.8e-05, X_variation_max=0.00024, d_wire=0.001, Y_variation_avg=7e-05, d_wire_min=0.00085, opening=0.0025),\n \"2.8\": Sieve(designation=\"2.8\", d_wire_max=0.0013, compliance_sd=0.000108, X_variation_max=0.00026, d_wire=0.00112, Y_variation_avg=8e-05, d_wire_min=0.00095, opening=0.0028),\n \"20\": Sieve(designation=\"20\", d_wire_max=0.0036, compliance_sd=0.000575, X_variation_max=0.00105, d_wire=0.00315, Y_variation_avg=0.00055, d_wire_min=0.0027, opening=0.02),\n \"22.4\": Sieve(designation=\"22.4\", d_wire_max=0.0041, compliance_sd=0.000641, X_variation_max=0.00114, d_wire=0.00355, Y_variation_avg=0.00061, d_wire_min=0.003, opening=0.0224),\n \"25\": Sieve(designation=\"25\", d_wire_max=0.0041, compliance_sd=0.000713, X_variation_max=0.00124, d_wire=0.00355, Y_variation_avg=0.00068, d_wire_min=0.003, opening=0.025),\n \"26.5\": Sieve(designation=\"26.5\", d_wire_max=0.0041, compliance_sd=0.000757, X_variation_max=0.00129, d_wire=0.00355, Y_variation_avg=0.00072, d_wire_min=0.003, opening=0.0265),\n \"28\": Sieve(designation=\"28\", d_wire_max=0.0041, compliance_sd=0.000801, X_variation_max=0.00135, d_wire=0.00355, Y_variation_avg=0.00076, d_wire_min=0.003, opening=0.028),\n \"3.15\": Sieve(designation=\"3.15\", d_wire_max=0.0015, compliance_sd=0.000118, X_variation_max=0.00028, d_wire=0.00125, Y_variation_avg=9e-05, d_wire_min=0.00106, opening=0.00315),\n \"3.35\": Sieve(designation=\"3.35\", d_wire_max=0.0015, compliance_sd=0.000124, X_variation_max=0.00029, d_wire=0.00125, Y_variation_avg=0.0001, d_wire_min=0.00106, opening=0.00335),\n \"3.55\": Sieve(designation=\"3.55\", d_wire_max=0.0015, compliance_sd=0.00013, X_variation_max=0.0003, d_wire=0.00125, Y_variation_avg=0.0001, d_wire_min=0.00106, opening=0.00355),\n \"31.5\": Sieve(designation=\"31.5\", d_wire_max=0.0046, compliance_sd=0.000905, X_variation_max=0.00147, d_wire=0.004, Y_variation_avg=0.00085, d_wire_min=0.0034, opening=0.0315),\n \"35.5\": Sieve(designation=\"35.5\", d_wire_max=0.0046, compliance_sd=0.001, X_variation_max=0.0016, d_wire=0.004, Y_variation_avg=0.00096, d_wire_min=0.0034, opening=0.0355),\n \"37.5\": Sieve(designation=\"37.5\", d_wire_max=0.0052, compliance_sd=0.001, X_variation_max=0.00167, d_wire=0.0045, Y_variation_avg=0.00101, d_wire_min=0.0038, opening=0.0375),\n \"4\": Sieve(designation=\"4\", d_wire_max=0.0017, compliance_sd=0.000143, X_variation_max=0.00033, d_wire=0.0014, Y_variation_avg=0.00011, d_wire_min=0.0012, opening=0.004),\n \"4.5\": Sieve(designation=\"4.5\", d_wire_max=0.0017, compliance_sd=0.000157, X_variation_max=0.00036, d_wire=0.0014, Y_variation_avg=0.00013, d_wire_min=0.0012, opening=0.0045),\n \"4.75\": Sieve(designation=\"4.75\", d_wire_max=0.0019, compliance_sd=0.000164, X_variation_max=0.00037, d_wire=0.0016, Y_variation_avg=0.00014, d_wire_min=0.0013, opening=0.00475),\n \"40\": Sieve(designation=\"40\", d_wire_max=0.0052, compliance_sd=0.001, X_variation_max=0.00175, d_wire=0.0045, Y_variation_avg=0.00108, d_wire_min=0.0038, opening=0.04),\n \"45\": Sieve(designation=\"45\", d_wire_max=0.0052, compliance_sd=0.001, X_variation_max=0.00191, d_wire=0.0045, Y_variation_avg=0.00121, d_wire_min=0.0038, opening=0.045),\n \"5\": Sieve(designation=\"5\", d_wire_max=0.0019, compliance_sd=0.000171, X_variation_max=0.00039, d_wire=0.0016, Y_variation_avg=0.00014, d_wire_min=0.0013, opening=0.005),\n \"5.6\": Sieve(designation=\"5.6\", d_wire_max=0.0019, compliance_sd=0.000188, X_variation_max=0.00042, d_wire=0.0016, Y_variation_avg=0.00016, d_wire_min=0.0013, opening=0.0056),\n \"50\": Sieve(designation=\"50\", d_wire_max=0.0058, X_variation_max=0.00206, d_wire=0.005, Y_variation_avg=0.00134, d_wire_min=0.0043, opening=0.05),\n \"53\": Sieve(designation=\"53\", d_wire_max=0.0058, X_variation_max=0.00215, d_wire=0.005, Y_variation_avg=0.00142, d_wire_min=0.0043, opening=0.053),\n \"56\": Sieve(designation=\"56\", d_wire_max=0.0058, X_variation_max=0.00224, d_wire=0.005, Y_variation_avg=0.0015, d_wire_min=0.0043, opening=0.056),\n \"6.3\": Sieve(designation=\"6.3\", d_wire_max=0.0021, compliance_sd=0.000207, X_variation_max=0.00046, d_wire=0.0018, Y_variation_avg=0.00018, d_wire_min=0.0015, opening=0.0063),\n \"6.7\": Sieve(designation=\"6.7\", d_wire_max=0.0021, compliance_sd=0.000218, X_variation_max=0.00048, d_wire=0.0018, Y_variation_avg=0.00019, d_wire_min=0.0015, opening=0.0067),\n \"63\": Sieve(designation=\"63\", d_wire_max=0.0064, X_variation_max=0.00244, d_wire=0.0056, Y_variation_avg=0.00169, d_wire_min=0.0048, opening=0.063),\n \"7.1\": Sieve(designation=\"7.1\", d_wire_max=0.0021, compliance_sd=0.000229, X_variation_max=0.0005, d_wire=0.0018, Y_variation_avg=0.0002, d_wire_min=0.0015, opening=0.0071),\n \"71\": Sieve(designation=\"71\", d_wire_max=0.0064, X_variation_max=0.00267, d_wire=0.0056, Y_variation_avg=0.00189, d_wire_min=0.0048, opening=0.071),\n \"75\": Sieve(designation=\"75\", d_wire_max=0.0072, X_variation_max=0.00278, d_wire=0.0063, Y_variation_avg=0.002, d_wire_min=0.0054, opening=0.075),\n \"8\": Sieve(designation=\"8\", d_wire_max=0.0023, compliance_sd=0.000254, X_variation_max=0.00054, d_wire=0.002, Y_variation_avg=0.00022, d_wire_min=0.0017, opening=0.008),\n \"80\": Sieve(designation=\"80\", d_wire_max=0.0072, X_variation_max=0.00291, d_wire=0.0063, Y_variation_avg=0.00213, d_wire_min=0.0054, opening=0.08),\n \"9\": Sieve(designation=\"9\", d_wire_max=0.0026, compliance_sd=0.000281, X_variation_max=0.00059, d_wire=0.00224, Y_variation_avg=0.00025, d_wire_min=0.0019, opening=0.009),\n \"9.5\": Sieve(designation=\"9.5\", d_wire_max=0.0026, compliance_sd=0.000294, X_variation_max=0.00061, d_wire=0.00224, Y_variation_avg=0.00027, d_wire_min=0.0019, opening=0.0095),\n \"90\": Sieve(designation=\"90\", d_wire_max=0.0072, X_variation_max=0.00318, d_wire=0.0063, Y_variation_avg=0.00239, d_wire_min=0.0054, opening=0.09)\n}\n\nISO_3310_1_R20_3 = [ISO_3310_1_sieves[i] for i in (\"125\", \"90\", \"63\", \"45\", \"31.5\", \"22.4\", \"16\", \"11.2\", \"8\", \"5.6\", \"4\", \"2.8\", \"2\", \"1.4\", \"1\", \"0.71\", \"0.5\", \"0.355\", \"0.25\", \"0.18\", \"0.125\", \"0.09\", \"0.063\", \"0.045\")]\n\nISO_3310_1_R20 = [ISO_3310_1_sieves[i] for i in ISO_3310_1_R20_keys]\n\nISO_3310_1_R40_3 = [ISO_3310_1_sieves[i] for i in ISO_3310_1_R40_3_keys]\n\nISO_3310_1_R10 = [ISO_3310_1_sieves[i] for i in ISO_3310_1_R10_keys]", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 18467}, "tests/test_particle_size_distribution.py::687": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/particle_size_distribution.py"], "used_names": ["PSDInterpolated", "ParticleSizeDistribution", "assert_close", "assert_close1d"], "enclosing_function": "test_PSDInterpolated_pchip", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\n\n# Source: fluids/particle_size_distribution.py\nclass ParticleSizeDistribution(ParticleSizeDistributionContinuous):\n r\"\"\"Class representing a discrete particle size distribution specified by a\n series of diameter bins, and the quantity of particles in each bin. The\n quantities may be specified as either the fraction of particles in each\n bin, or as cumulative distributions. The input fractions can be\n specified to be in a mass basis (`order=3`), number basis (`order=0`),\n or the orders in between for length basis or area basis. If the\n fractions do not sum to 1, and `cdf` is False, then the fractions are\n normalized. This allows flow rates or counts of size bins to be given as\n well.\n\n Parameters\n ----------\n ds : list[float]\n Diameter bins; length of the specified quantities, optionally +1 that\n length to specify a cutoff diameter for the smallest diameter bin, [m]\n fractions : list[float], optional\n The mass/mole/volume/length/area/count fractions or cumulative\n distributions or counts of each particle size in\n each diameter bin (the type is specified by `order`), [-]\n order : int, optional\n 0 for a number distribution as input; 1 for length distribution;\n 2 for area distribution; 3 for mass, mole, or volume distribution, [-]\n cdf : bool, optional\n If the distribution is given as increasing fractions with 1 as the last\n result, `cdf` must be set to True, [-]\n monotonic : bool, optional\n If True, for interpolated quanties, monotonic splines will be used\n instead of the standard splines, [-]\n\n Attributes\n ----------\n fractions : list[float]\n The mass/mole/volume basis fractions of particles in each bin, [-]\n area_fractions : list[float]\n The area fractions of particles in each bin, [-]\n length_fractions : list[float]\n The length fractions of particles in each bin, [-]\n number_fractions : list[float]\n The number fractions of particles in each bin, [-]\n fraction_cdf : list[float]\n The cumulative mass/mole/volume basis fractions of particles in each\n bin, [-]\n area_cdf : list[float]\n The cumulative area fractions of particles in each bin, [-]\n length_cdf : list[float]\n The cumulative length fractions of particles in each bin, [-]\n number_cdf : list[float]\n The cumulative number fractions of particles in each bin, [-]\n size_classes : bool\n Whether or not the diameter bins were set as size classes (as length\n of fractions + 1), [-]\n N : int\n The number of provided points, [-]\n\n Notes\n -----\n Although the stated units of input are in meters, this class is actually\n independent of the units provided; all results will be consistent with the\n provided unit.\n\n Examples\n --------\n Example problem from [1]_, calculating several diameters and the cumulative\n distribution.\n\n >>> import numpy as np\n >>> ds = 1E-6*np.array([240, 360, 450, 562.5, 703, 878, 1097, 1371, 1713, 2141, 2676, 3345, 4181, 5226, 6532])\n >>> numbers = [65, 119, 232, 410, 629, 849, 990, 981, 825, 579, 297, 111, 21, 1]\n >>> psd = ParticleSizeDistribution(ds=ds, fractions=numbers, order=0)\n >>> psd\n \n\n References\n ----------\n .. [1] ASTM E799 - 03(2015) - Standard Practice for Determining Data\n Criteria and Processing for Liquid Drop Size Analysis.\n .. [2] ISO 9276-2:2014 - Representation of Results of Particle Size\n Analysis - Part 2: Calculation of Average Particle Sizes/Diameters and\n Moments from Particle Size Distributions.\n \"\"\"\n\n def __repr__(self):\n txt = \"\"\n return txt %(self.N, self.mean_size(p=3, q=3))\n\n size_classes = False\n _interpolated = None\n points = True\n truncated = False\n name = \"Discrete\"\n def __init__(self, ds: list[float] | np.ndarray, fractions: list[float], cdf: bool=False, order: int=3, monotonic: bool=True) -> None:\n self.monotonic = monotonic\n self.ds = ds\n self.order = order\n\n if ds is not None and (len(ds) == len(fractions) + 1):\n self.size_classes = True\n else:\n self.size_classes = False\n\n if cdf:\n # Convert a cdf to fraction set\n if len(fractions)+1 == len(ds):\n fractions = [fractions[0]] + diff(fractions)\n else:\n fractions_diff = diff(fractions)\n fractions = [0.0] + fractions_diff\n elif sum(fractions) != 1.0:\n # Normalize flow inputs\n tot_inv = 1.0/sum(fractions)\n fractions = [i*tot_inv if i != 0.0 else 0.0 for i in fractions]\n\n self.N = len(fractions)\n\n # This will always be in base-3 basis\n if self.order != 3:\n power = 3 - self.order\n d3s = [self.di_power(i, power=power)*fractions[i] for i in range(self.N)]\n tot_d3 = sum(d3s)\n self.fractions = [i/tot_d3 for i in d3s]\n else:\n self.fractions = fractions\n # Set the number fractions\n D3s = [self.di_power(i, power=3) for i in range(self.N)]\n numbers = [Vi/Vp for Vi, Vp in zip(self.fractions, D3s)]\n number_sum = sum(numbers)\n self.number_fractions = [i/number_sum for i in numbers]\n\n # Set the length fractions\n D3s = [self.di_power(i, power=2) for i in range(self.N)]\n numbers = [Vi/Vp for Vi, Vp in zip(self.fractions, D3s)]\n number_sum = sum(numbers)\n self.length_fractions = [i/number_sum for i in numbers]\n\n # Set the surface area fractions\n D3s = [self.di_power(i, power=1) for i in range(self.N)]\n numbers = [Vi/Vp for Vi, Vp in zip(self.fractions, D3s)]\n number_sum = sum(numbers)\n self.area_fractions = [i/number_sum for i in numbers]\n\n\n # Things for interoperability with the Continuous distribution\n self.d_excessive = float(self.ds[-1])\n self.d_minimum = 0.0\n self.parameters: dict[str, float | None] = {}\n self.order = 3\n self.fraction_cdf = self.volume_cdf = cumsum(self.fractions)\n self.area_cdf = cumsum(self.area_fractions)\n self.length_cdf = cumsum(self.length_fractions)\n self.number_cdf = cumsum(self.number_fractions)\n\n @property\n def interpolated(self) -> PSDInterpolated:\n if not self._interpolated:\n self._interpolated = PSDInterpolated(ds=self.ds,\n fractions=self.fractions,\n order=3,\n monotonic=self.monotonic)\n return self._interpolated\n\n def _pdf(self, d: float) -> float:\n return self.interpolated._pdf(d)\n\n def _cdf(self, d: float) -> float:\n return self.interpolated._cdf(d)\n\n def _pdf_basis_integral(self, d: float, n: float) -> float:\n return self.interpolated._pdf_basis_integral(d, n)\n\n def _fit_obj_function(self, vals, distribution, n):\n err = 0.0\n dist = distribution(*list(vals))\n l = len(self.fractions) if self.size_classes else len(self.fractions) - 1\n for i in range(l):\n delta_cdf = dist.delta_cdf(d_min=self.ds[i], d_max=self.ds[i+1])\n err += abs(delta_cdf - self.fractions[i])\n return err\n\n def fit(self, x0=None, distribution=\"lognormal\", n=None, **kwargs):\n \"\"\"Incomplete method to fit experimental values to a curve.\n\n It is very hard to get good initial guesses, which are really required\n for this. Differential evolution is promising. This API is likely to\n change in the future.\n \"\"\"\n dist = {\"lognormal\": PSDLognormal,\n \"GGS\": PSDGatesGaudinSchuhman,\n \"RR\": PSDRosinRammler}[distribution]\n\n if distribution == \"lognormal\":\n if x0 is None:\n d_characteristic = sum([fi*di for fi, di in zip(self.fractions, self.Dis)])\n s = 0.4\n x0 = [d_characteristic, s]\n elif distribution == \"GGS\":\n if x0 is None:\n d_characteristic = sum([fi*di for fi, di in zip(self.fractions, self.Dis)])\n m = 1.5\n x0 = [d_characteristic, m]\n elif distribution == \"RR\" and x0 is None:\n x0 = [5E-6, 1e-2]\n # from fluids.numerics import SolverInterface\n # solver = SolverInterface('newton_minimize', self._fit_obj_function, xtol=1e-10, jacobian_perturbation=1e-5, scalar_objective=True, **kwargs)\n # return solver.solve(x0, args=(dist, n))\n from scipy.optimize import minimize\n return minimize(self._fit_obj_function, x0, args=(dist, n), **kwargs)\n\n @property\n def Dis(self) -> list[float]:\n \"\"\"Representative diameters of each bin.\"\"\"\n return [self.di_power(i, power=1) for i in range(self.N)]\n\n def di_power(self, i: int, power: float=1) -> float:\n r\"\"\"Method to calculate a power of a particle class/bin in a generic\n way so as to support when there are as many `ds` as `fractions`,\n or one more diameter spec than `fractions`.\n\n When each bin has a lower and upper bound, the formula is as follows\n [1]_.\n\n .. math::\n D_i^r = \\frac{D_{i, ub}^{(r+1)} - D_{i, lb}^{(r+1)}}\n {(D_{i, ub} - D_{i, lb})(r+1)}\n\n Where `ub` represents the upper bound, and `lb` represents the lower\n bound. Otherwise, the standard definition is used:\n\n .. math::\n D_i^r = D_i^r\n\n Parameters\n ----------\n i : int\n The index of the diameter for the calculation, [-]\n power : int\n The exponent, [-]\n\n Returns\n -------\n di_power : float\n The representative bin diameter raised to `power`, [m^power]\n\n References\n ----------\n .. [1] ASTM E799 - 03(2015) - Standard Practice for Determining Data\n Criteria and Processing for Liquid Drop Size Analysis.\n \"\"\"\n if self.size_classes:\n rt = power + 1\n return ((self.ds[i+1]**rt - self.ds[i]**rt)/((self.ds[i+1] - self.ds[i])*rt))\n else:\n return self.ds[i]**power\n\n def mean_size(self, p: float, q: float) -> float:\n \"\"\"\n >>> import numpy as np\n >>> ds = 1E-6*np.array([240, 360, 450, 562.5, 703, 878, 1097, 1371, 1713, 2141, 2676, 3345, 4181, 5226, 6532])\n >>> numbers = [65, 119, 232, 410, 629, 849, 990, 981, 825, 579, 297, 111, 21, 1]\n >>> psd = ParticleSizeDistribution(ds=ds, fractions=numbers, order=0)\n >>> psd.mean_size(3, 2)\n 0.002269321031745045\n \"\"\"\n if p != q:\n # Note: D(p, q) = D(q, p); in ISO and proven experimentally\n numerator = sum(self.di_power(i=i, power=p)*self.number_fractions[i] for i in range(self.N))\n denominator = sum(self.di_power(i=i, power=q)*self.number_fractions[i] for i in range(self.N))\n return float((numerator/denominator)**(1.0/(p-q)))\n else:\n numerator = sum(log(self.di_power(i=i, power=1))*self.di_power(i=i, power=p)*self.number_fractions[i] for i in range(self.N))\n denominator = sum(self.di_power(i=i, power=q)*self.number_fractions[i] for i in range(self.N))\n return exp(numerator/denominator)\n\n def mean_size_ISO(self, k, r):\n r\"\"\"\n >>> import numpy as np\n >>> ds = 1E-6*np.array([240, 360, 450, 562.5, 703, 878, 1097, 1371, 1713, 2141, 2676, 3345, 4181, 5226, 6532])\n >>> numbers = [65, 119, 232, 410, 629, 849, 990, 981, 825, 579, 297, 111, 21, 1]\n >>> psd = ParticleSizeDistribution(ds=ds, fractions=numbers, order=0)\n >>> psd.mean_size_ISO(1, 2)\n 0.002269321031745045\n \"\"\"\n p = k + r\n q = r\n return self.mean_size(p=p, q=q)\n\n @property\n def vssa(self) -> float:\n r\"\"\"The volume-specific surface area of a particle size distribution.\n Note this uses the diameters provided by the method `Dis`.\n\n .. math::\n \\text{VSSA} = \\sum_i \\text{fraction}_i \\frac{SA_i}{V_i}\n\n Returns\n -------\n VSSA : float\n The volume-specific surface area of the distribution, [m^2/m^3]\n\n References\n ----------\n .. [1] ISO 9276-2:2014 - Representation of Results of Particle Size\n Analysis - Part 2: Calculation of Average Particle Sizes/Diameters\n and Moments from Particle Size Distributions.\n \"\"\"\n ds = self.Dis\n Vs = [pi/6*di**3 for di in ds]\n SAs = [pi*di**2 for di in ds]\n SASs = [SA/V for SA, V in zip(SAs, Vs)]\n VSSA = sum([fi*SASi for fi, SASi in zip(self.fractions, SASs)])\n return VSSA\n\nclass PSDInterpolated(ParticleSizeDistributionContinuous):\n name = \"Interpolated\"\n points = True\n truncated = False\n def __init__(self, ds: list[float] | np.ndarray, fractions: list[float] | np.ndarray, order: int=3, monotonic: bool=True) -> None:\n self.order = order\n self.monotonic = monotonic # always true now\n self.parameters: dict[str, float | None] = {}\n\n ds = list(ds)\n fractions = list(fractions)\n\n if len(ds) == len(fractions)+1:\n # size classes, the last point will be zero\n fractions.insert(0, 0.0)\n self.d_minimum = min(ds)\n elif ds[0] != 0:\n ds = [0.0] + ds\n if len(ds) != len(fractions):\n fractions = [0.0] + fractions\n self.d_minimum = 0.0\n\n self.ds = ds\n self.fractions = fractions\n\n self.d_excessive = max(ds)\n\n\n self.fraction_cdf = cumsum(fractions)\n if self.monotonic:\n from scipy.interpolate import PchipInterpolator\n self.cdf_spline = PchipInterpolator(ds, self.fraction_cdf, extrapolate=True)\n self.pdf_spline = PchipInterpolator(ds, self.fraction_cdf, extrapolate=True).derivative(1)\n\n self.basis_integrals: dict[int, Callable[[float], float]] = {}\n\n\n def _pdf(self, d: float) -> float:\n return max(0.0, float(self.pdf_spline(d)))\n\n def _cdf(self, d: float) -> float:\n if d > self.d_excessive:\n # Handle spline values past 1 that decrease to zero\n return 1.0\n return max(0.0, float(self.cdf_spline(d)))\n\n def _pdf_basis_integral(self, d: float, n: float) -> float:\n # there are slight errors with this approach - but they are OK to\n # ignore.\n # DO NOT evaluate the first point as it leads to inf values; just set\n # it to zero\n if n not in self.basis_integrals:\n ds = np.array(self.ds[1:])\n pdf_vals = self.pdf_spline(ds)\n # n may be an integer, numpy says \"Integers to negative integer powers are not allowed\" if we don't make it a float\n basis_integral = ds**float(n)*pdf_vals\n if self.monotonic:\n from scipy.interpolate import PchipInterpolator\n self.basis_integrals[int(n)] = PchipInterpolator(ds, basis_integral, extrapolate=True).antiderivative(1)\n return max(float(self.basis_integrals[int(n)](d)), 0.0)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 16261}, "tests/test_particle_size_distribution.py::267": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/particle_size_distribution.py"], "used_names": ["assert_close", "cdf_Gates_Gaudin_Schuhman"], "enclosing_function": "test_cdf_Gates_Gaudin_Schuhman", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/particle_size_distribution.py\ndef cdf_Gates_Gaudin_Schuhman(d: float, d_characteristic: float, m: float) -> float:\n r\"\"\"Calculates the cumulative distribution function of a particle\n distribution following the Gates, Gaudin and Schuhman (GGS) model given a\n particle diameter `d`, characteristic (maximum) particle\n diameter `d_characteristic`, and exponent `m`.\n\n .. math::\n Q(d) = \\left(\\frac{d}{d_{characteristic}}\\right)^m \\text{ if }\n d < d_{characteristic} \\text{ else } 1\n\n Parameters\n ----------\n d : float\n Specified particle diameter, [m]\n d_characteristic : float\n Characteristic particle diameter; in this model, it is the largest\n particle size diameter in the distribution, [m]\n m : float\n Particle size distribution exponent, [-]\n\n Returns\n -------\n cdf : float\n GGS cumulative density function, [-]\n\n Notes\n -----\n The characteristic diameter can be in terns of number density (denoted\n :math:`q_0(d)`), length density (:math:`q_1(d)`), surface area density\n (:math:`q_2(d)`), or volume density (:math:`q_3(d)`). Volume density is\n most often used. Interconversions among the distributions is possible but\n tricky.\n\n Examples\n --------\n >>> cdf_Gates_Gaudin_Schuhman(d=2E-4, d_characteristic=1E-3, m=2.3)\n 0.024681354508800397\n\n References\n ----------\n .. [1] Schuhmann, R., 1940. Principles of Comminution, I-Size Distribution\n and Surface Calculations. American Institute of Mining, Metallurgical\n and Petroleum Engineers Technical Publication 1189. Mining Technology,\n volume 4, p. 1-11.\n .. [2] Bayat, Hossein, Mostafa Rastgo, Moharram Mansouri Zadeh, and Harry\n Vereecken. \"Particle Size Distribution Models, Their Characteristics and\n Fitting Capability.\" Journal of Hydrology 529 (October 1, 2015): 872-89.\n \"\"\"\n if d <= d_characteristic:\n return (d/d_characteristic)**m\n else:\n return 1.0", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 2625}, "tests/test_particle_size_distribution.py::275": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/particle_size_distribution.py"], "used_names": ["assert_close", "pdf_Gates_Gaudin_Schuhman"], "enclosing_function": "test_pdf_Gates_Gaudin_Schuhman", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/particle_size_distribution.py\ndef pdf_Gates_Gaudin_Schuhman(d: float, d_characteristic: float, m: float) -> float:\n r\"\"\"Calculates the probability density of a particle\n distribution following the Gates, Gaudin and Schuhman (GGS) model given a\n particle diameter `d`, characteristic (maximum) particle\n diameter `d_characteristic`, and exponent `m`.\n\n .. math::\n q(d) = \\frac{n}{d}\\left(\\frac{d}{d_{characteristic}}\\right)^m\n \\text{ if } d < d_{characteristic} \\text{ else } 0\n\n Parameters\n ----------\n d : float\n Specified particle diameter, [m]\n d_characteristic : float\n Characteristic particle diameter; in this model, it is the largest\n particle size diameter in the distribution, [m]\n m : float\n Particle size distribution exponent, [-]\n\n Returns\n -------\n pdf : float\n GGS probability density function, [-]\n\n Notes\n -----\n The characteristic diameter can be in terns of number density (denoted\n :math:`q_0(d)`), length density (:math:`q_1(d)`), surface area density\n (:math:`q_2(d)`), or volume density (:math:`q_3(d)`). Volume density is\n most often used. Interconversions among the distributions is possible but\n tricky.\n\n Examples\n --------\n >>> pdf_Gates_Gaudin_Schuhman(d=2E-4, d_characteristic=1E-3, m=2.3)\n 283.8355768512045\n\n References\n ----------\n .. [1] Schuhmann, R., 1940. Principles of Comminution, I-Size Distribution\n and Surface Calculations. American Institute of Mining, Metallurgical\n and Petroleum Engineers Technical Publication 1189. Mining Technology,\n volume 4, p. 1-11.\n .. [2] Bayat, Hossein, Mostafa Rastgo, Moharram Mansouri Zadeh, and Harry\n Vereecken. \"Particle Size Distribution Models, Their Characteristics and\n Fitting Capability.\" Journal of Hydrology 529 (October 1, 2015): 872-89.\n \"\"\"\n if d <= d_characteristic:\n return m/d*(d/d_characteristic)**m\n else:\n return 0.0", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 2625}, "tests/test_piping.py::117": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/piping.py"], "used_names": ["NPS120_D1785", "assert_close", "assert_close1d", "nearest_pipe", "pipe_too_large_msg", "pytest"], "enclosing_function": "test_nearest_pipe_error_paths", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\n\n# Source: fluids/piping.py\npipe_too_large_msg = \"Pipe input is larger than max of selected schedule\"\n\ndef nearest_pipe(Do: float | None=None, Di: float | None=None, NPS: int | None=None, schedule: str | float=\"40\") -> tuple[float, float, float, float]:\n r\"\"\"Searches for and finds the nearest standard pipe size to a given\n specification. Acceptable inputs are:\n\n - Nominal pipe size\n - Nominal pipe size and schedule\n - Outer diameter `Do`\n - Outer diameter `Do` and schedule\n - Inner diameter `Di`\n - Inner diameter `Di` and schedule\n\n Acceptable schedules are: '5', '10', '20', '30', '40', '60', '80', '100',\n '120', '140', '160', 'STD', 'XS', 'XXS', '5S', '10S', '40S', '80S',\n '40D1527', '80D1527',\n 'ABSD2680', 'PVCD2680',\n 'DR25C900', 'DR18C900', 'DR14C900',\n 'CIDR51C905', 'CIDR41C905', 'CIDR325C905', 'CIDR25C905', 'CIDR21C905', 'CIDR18C905', 'CIDR14C905',\n 'IPSDR21', 'IPSDR26', 'IPSDR325', 'IPSDR41',\n 'PS115F679', 'PS75F679', 'PS46F679',\n 'PVCD2665',\n '40D1785', '80D1785', '120D1785',\n 'DR135D2241', 'DR17D2241', 'DR21D2241', 'DR26D2241', 'DR325D2241', 'DR41D2241', 'DR64D2241',\n 'DR21D2241CTS', 'DR17D2241CTS', 'DR135D2241CTS', 'DR11D2241CTS',\n 'DR21D2241PIP', 'DR26D2241PIP', 'DR325D2241PIP', 'DR35D2241PIP', 'DR41D2241PIP', 'DR51D2241PIP', 'DR81D2241PIP',\n 'S40F441IPS', 'S80F441IPS', 'S40F441SI', 'S80F441SI'\n 'DR325F2619SI', 'DR26F2619SI', 'DR21F2619SI', 'DR17F2619SI', 'DR135F2619SI', 'DR11F2619SI', 'DR9F2619SI', 'DR73F2619SI', 'DR7F2619SI',\n 'DR325F2619IPS', 'DR26F2619IPS', 'DR21F2619IPS', 'DR17F2619IPS', 'DR135F2619IPS', 'DR11F2619IPS', 'DR9F2619IPS', 'DR73F2619IPS', 'DR7F2619IPS',\n 'BS1387LIGHT', 'BS1387MEDIUM', 'BS1387HEAVY'\n\n Parameters\n ----------\n Do : float, optional\n Pipe outer diameter, [m]\n Di : float, optional\n Pipe inner diameter, [m]\n NPS : float, optional\n Nominal pipe size, [-]\n schedule : str, optional\n String representing schedule size\n\n Returns\n -------\n NPS : float\n Nominal pipe size, [-]\n Di : float\n Pipe inner diameter, [m]\n Do : float\n Pipe outer diameter, [m]\n t : float\n Pipe wall thickness, [m]\n\n Notes\n -----\n Internal units within this function are mm.\n The imperial schedules are not quite identical to these value, but\n all rounding differences happen in the sub-0.1 mm level.\n\n Examples\n --------\n >>> nearest_pipe(Di=0.021)\n (1.0, 0.02664, 0.0334, 0.00338)\n >>> nearest_pipe(Do=.273, schedule='5S')\n (10.0, 0.2663, 0.2731, 0.0034)\n\n References\n ----------\n .. [1] American National Standards Institute, and American Society of\n Mechanical Engineers. B36.10M-2004: Welded and Seamless Wrought Steel\n Pipe. New York: American Society of Mechanical Engineers, 2004.\n .. [2] American National Standards Institute, and American Society of\n Mechanical Engineers. B36-19M-2004: Stainless Steel Pipe.\n New York, N.Y.: American Society of Mechanical Engineers, 2004.\n .. [3] F17 Committee. \"Specification for Acrylonitrile-Butadiene-Styrene\n (ABS) Plastic Pipe, Schedules 40 and 80.\" ASTM International.\n https://doi.org/10.1520/D1527-99R05.\n .. [4] F17 Committee. \"Specification for Acrylonitrile-Butadiene-Styrene\n (ABS) and Poly(Vinyl Chloride) (PVC) Composite Sewer Piping.\" ASTM\n International. https://doi.org/10.1520/D2680-01R14.\n .. [5] AWWA-American Water Works Association. \"AWWA C900-07 Polyvinyl\n Chloride (PVC) Pressure Pipe and Fabricated Fittings, 4 In. Through 12\n In. (100 Mm Through 300 Mm), for Water Transmission and Distribution.\"\n .. [6] AWWA-American Water Works Association. \"AWWA C905-97 Polyvinyl\n Chloride (PVC) Pressure Pipe and Fabricated Fittings, 14 in. Through\n 48 in. (350 Mm through 1,200 Mm), for Water Transmission and\n Distribution.\"\n .. [7] F17 Committee. \"Specification for Poly(Vinyl Chloride) (PVC)\n Large-Diameter Plastic Gravity Sewer Pipe and Fittings.\" ASTM\n International. https://doi.org/10.1520/F0679-16.\n .. [8] F17 Committee. \"Specification for Poly(Vinyl Chloride) (PVC) Plastic\n Drain, Waste, and Vent Pipe and Fittings.\" ASTM International.\n https://doi.org/10.1520/D2665-14.\n .. [9] F17 Committee. \"Specification for Poly(Vinyl Chloride) (PVC) Plastic\n Pipe, Schedules 40, 80, and 120.\" ASTM International.\n https://doi.org/10.1520/D1785-15E01.\n .. [10] F17 Committee. \"Specification for Chlorinated Poly(Vinyl Chloride)\n (CPVC) Plastic Pipe, Schedules 40 and 80.\" ASTM International.\n https://doi.org/10.1520/F0441_F0441M-15.\n .. [11] F17 Committee. \"Specification for High-Density Polyethylene (PE)\n Line Pipe.\" ASTM International. https://doi.org/10.1520/F2619_F2619M-20.\n \"\"\"\n if Di is not None:\n Di *= 1E3\n if Do is not None:\n Do *= 1E3\n\n # If accidentally given an numerical schedule, convert it to a string\n if isinstance(schedule, (int, float)):\n search_schedule = str(int(schedule))\n else:\n search_schedule = schedule\n\n if search_schedule not in schedule_lookup:\n raise ValueError(\"Schedule not recognized\")\n else:\n NPSes, Dis, Dos, ts = schedule_lookup[search_schedule]\n\n # Handle the three cases of different inputs\n if Di is not None:\n nums = Di_lookup(Di, NPSes, Dis, Dos, ts)\n elif Do is not None:\n nums = Do_lookup(Do, NPSes, Dis, Dos, ts)\n elif NPS is not None:\n nums = NPS_lookup(float(NPS), NPSes, Dis, Dos, ts)\n\n _nps, _di, _do, _t = nums\n return _nps, _di*1e-3, _do*1e-3, _t*1e-3", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 6531}, "tests/test_piping.py::130": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/piping.py"], "used_names": ["NPS120_D1785", "assert_close", "assert_close1d", "nearest_pipe", "pipe_too_large_msg", "pytest"], "enclosing_function": "test_nearest_pipe_error_paths", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\n\n# Source: fluids/piping.py\npipe_too_large_msg = \"Pipe input is larger than max of selected schedule\"\n\ndef nearest_pipe(Do: float | None=None, Di: float | None=None, NPS: int | None=None, schedule: str | float=\"40\") -> tuple[float, float, float, float]:\n r\"\"\"Searches for and finds the nearest standard pipe size to a given\n specification. Acceptable inputs are:\n\n - Nominal pipe size\n - Nominal pipe size and schedule\n - Outer diameter `Do`\n - Outer diameter `Do` and schedule\n - Inner diameter `Di`\n - Inner diameter `Di` and schedule\n\n Acceptable schedules are: '5', '10', '20', '30', '40', '60', '80', '100',\n '120', '140', '160', 'STD', 'XS', 'XXS', '5S', '10S', '40S', '80S',\n '40D1527', '80D1527',\n 'ABSD2680', 'PVCD2680',\n 'DR25C900', 'DR18C900', 'DR14C900',\n 'CIDR51C905', 'CIDR41C905', 'CIDR325C905', 'CIDR25C905', 'CIDR21C905', 'CIDR18C905', 'CIDR14C905',\n 'IPSDR21', 'IPSDR26', 'IPSDR325', 'IPSDR41',\n 'PS115F679', 'PS75F679', 'PS46F679',\n 'PVCD2665',\n '40D1785', '80D1785', '120D1785',\n 'DR135D2241', 'DR17D2241', 'DR21D2241', 'DR26D2241', 'DR325D2241', 'DR41D2241', 'DR64D2241',\n 'DR21D2241CTS', 'DR17D2241CTS', 'DR135D2241CTS', 'DR11D2241CTS',\n 'DR21D2241PIP', 'DR26D2241PIP', 'DR325D2241PIP', 'DR35D2241PIP', 'DR41D2241PIP', 'DR51D2241PIP', 'DR81D2241PIP',\n 'S40F441IPS', 'S80F441IPS', 'S40F441SI', 'S80F441SI'\n 'DR325F2619SI', 'DR26F2619SI', 'DR21F2619SI', 'DR17F2619SI', 'DR135F2619SI', 'DR11F2619SI', 'DR9F2619SI', 'DR73F2619SI', 'DR7F2619SI',\n 'DR325F2619IPS', 'DR26F2619IPS', 'DR21F2619IPS', 'DR17F2619IPS', 'DR135F2619IPS', 'DR11F2619IPS', 'DR9F2619IPS', 'DR73F2619IPS', 'DR7F2619IPS',\n 'BS1387LIGHT', 'BS1387MEDIUM', 'BS1387HEAVY'\n\n Parameters\n ----------\n Do : float, optional\n Pipe outer diameter, [m]\n Di : float, optional\n Pipe inner diameter, [m]\n NPS : float, optional\n Nominal pipe size, [-]\n schedule : str, optional\n String representing schedule size\n\n Returns\n -------\n NPS : float\n Nominal pipe size, [-]\n Di : float\n Pipe inner diameter, [m]\n Do : float\n Pipe outer diameter, [m]\n t : float\n Pipe wall thickness, [m]\n\n Notes\n -----\n Internal units within this function are mm.\n The imperial schedules are not quite identical to these value, but\n all rounding differences happen in the sub-0.1 mm level.\n\n Examples\n --------\n >>> nearest_pipe(Di=0.021)\n (1.0, 0.02664, 0.0334, 0.00338)\n >>> nearest_pipe(Do=.273, schedule='5S')\n (10.0, 0.2663, 0.2731, 0.0034)\n\n References\n ----------\n .. [1] American National Standards Institute, and American Society of\n Mechanical Engineers. B36.10M-2004: Welded and Seamless Wrought Steel\n Pipe. New York: American Society of Mechanical Engineers, 2004.\n .. [2] American National Standards Institute, and American Society of\n Mechanical Engineers. B36-19M-2004: Stainless Steel Pipe.\n New York, N.Y.: American Society of Mechanical Engineers, 2004.\n .. [3] F17 Committee. \"Specification for Acrylonitrile-Butadiene-Styrene\n (ABS) Plastic Pipe, Schedules 40 and 80.\" ASTM International.\n https://doi.org/10.1520/D1527-99R05.\n .. [4] F17 Committee. \"Specification for Acrylonitrile-Butadiene-Styrene\n (ABS) and Poly(Vinyl Chloride) (PVC) Composite Sewer Piping.\" ASTM\n International. https://doi.org/10.1520/D2680-01R14.\n .. [5] AWWA-American Water Works Association. \"AWWA C900-07 Polyvinyl\n Chloride (PVC) Pressure Pipe and Fabricated Fittings, 4 In. Through 12\n In. (100 Mm Through 300 Mm), for Water Transmission and Distribution.\"\n .. [6] AWWA-American Water Works Association. \"AWWA C905-97 Polyvinyl\n Chloride (PVC) Pressure Pipe and Fabricated Fittings, 14 in. Through\n 48 in. (350 Mm through 1,200 Mm), for Water Transmission and\n Distribution.\"\n .. [7] F17 Committee. \"Specification for Poly(Vinyl Chloride) (PVC)\n Large-Diameter Plastic Gravity Sewer Pipe and Fittings.\" ASTM\n International. https://doi.org/10.1520/F0679-16.\n .. [8] F17 Committee. \"Specification for Poly(Vinyl Chloride) (PVC) Plastic\n Drain, Waste, and Vent Pipe and Fittings.\" ASTM International.\n https://doi.org/10.1520/D2665-14.\n .. [9] F17 Committee. \"Specification for Poly(Vinyl Chloride) (PVC) Plastic\n Pipe, Schedules 40, 80, and 120.\" ASTM International.\n https://doi.org/10.1520/D1785-15E01.\n .. [10] F17 Committee. \"Specification for Chlorinated Poly(Vinyl Chloride)\n (CPVC) Plastic Pipe, Schedules 40 and 80.\" ASTM International.\n https://doi.org/10.1520/F0441_F0441M-15.\n .. [11] F17 Committee. \"Specification for High-Density Polyethylene (PE)\n Line Pipe.\" ASTM International. https://doi.org/10.1520/F2619_F2619M-20.\n \"\"\"\n if Di is not None:\n Di *= 1E3\n if Do is not None:\n Do *= 1E3\n\n # If accidentally given an numerical schedule, convert it to a string\n if isinstance(schedule, (int, float)):\n search_schedule = str(int(schedule))\n else:\n search_schedule = schedule\n\n if search_schedule not in schedule_lookup:\n raise ValueError(\"Schedule not recognized\")\n else:\n NPSes, Dis, Dos, ts = schedule_lookup[search_schedule]\n\n # Handle the three cases of different inputs\n if Di is not None:\n nums = Di_lookup(Di, NPSes, Dis, Dos, ts)\n elif Do is not None:\n nums = Do_lookup(Do, NPSes, Dis, Dos, ts)\n elif NPS is not None:\n nums = NPS_lookup(float(NPS), NPSes, Dis, Dos, ts)\n\n _nps, _di, _do, _t = nums\n return _nps, _di*1e-3, _do*1e-3, _t*1e-3", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 6531}, "tests/test_pump.py::135": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/numerics/__init__.py", "fluids/pump.py"], "used_names": ["electrical_plug_types", "industrial_power", "residential_power", "residential_power_frequencies", "voltages_1_phase_residential", "voltages_3_phase"], "enclosing_function": "test_power_sources", "extracted_code": "# Source: fluids/pump.py\nresidential_power = {\n \"at\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Austria\"),\n \"bj\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Benin\"),\n \"gh\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Ghana\"),\n \"sc\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Seychelles\"),\n \"bg\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Bulgaria\"),\n \"me\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Montenegro\"),\n \"fo\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"K\"), voltage=230, freq=50, country=\"Faroe Islands\"),\n \"ne\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"), voltage=220, freq=50, country=\"Niger\"),\n \"za\": CountryPower(plugs=(\"C\", \"F\", \"M\", \"N\"), voltage=230, freq=50, country=\"South Africa\"),\n \"az\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Azerbaijan\"),\n \"so\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Somalia\"),\n \"sn\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"K\"), voltage=230, freq=50, country=\"Senegal\"),\n \"np\": CountryPower(plugs=(\"C\", \"D\", \"M\"), voltage=230, freq=50, country=\"Nepal\"),\n \"sl\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Sierra Leone\"),\n \"be\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Belgium\"),\n \"vg\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"British Virgin Islands\"),\n \"bz\": CountryPower(plugs=(\"A\", \"B\", \"G\"), voltage=110, freq=60, country=\"Belize\"),\n \"tw\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Taiwan\"),\n \"bf\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Burkina Faso\"),\n \"ao\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Angola\"),\n \"gi\": CountryPower(plugs=(\"C\", \"G\"), voltage=240, freq=50, country=\"Gibraltar\"),\n \"ee\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Estonia\"),\n \"bs\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Bahamas\"),\n \"ir\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Iran\"),\n \"sv\": CountryPower(plugs=(\"A\", \"B\"), voltage=115, freq=60, country=\"El Salvador\"),\n \"am\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Armenia\"),\n \"is\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Iceland\"),\n \"uy\": CountryPower(plugs=(\"C\", \"F\", \"I\", \"L\"), voltage=230, freq=50, country=\"Uruguay\"),\n \"mc\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"F\"), voltage=230, freq=50, country=\"Monaco\"),\n \"jm\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=50, country=\"Jamaica\"),\n \"im\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Isle of Man\"),\n \"dm\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Dominica\"),\n \"mu\": CountryPower(plugs=(\"C\", \"G\"), voltage=230, freq=50, country=\"Mauritius\"),\n \"cz\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Czech Republic\"),\n \"kh\": CountryPower(plugs=(\"A\", \"C\", \"G\"), voltage=230, freq=50, country=\"Cambodia\"),\n \"cf\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Central African Republic\"),\n \"se\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Sweden\"),\n \"uz\": CountryPower(plugs=(\"C\", \"I\"), voltage=220, freq=50, country=\"Uzbekistan\"),\n \"sk\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Slovakia\"),\n \"ky\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Cayman Islands\"),\n \"tn\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Tunisia\"),\n \"do\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Dominican Republic\"),\n \"hu\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Hungary\"),\n \"af\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Afghanistan\"),\n \"et\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"L\"), voltage=220, freq=50, country=\"Ethiopia\"),\n \"tv\": CountryPower(plugs=(\"I\",), voltage=220, freq=50, country=\"Tuvalu\"),\n \"ad\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Andorra\"),\n \"hn\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Honduras\"),\n \"ls\": CountryPower(plugs=(\"M\",), voltage=220, freq=50, country=\"Lesotho\"),\n \"na\": CountryPower(plugs=(\"D\", \"M\"), voltage=220, freq=50, country=\"Namibia\"),\n \"jo\": CountryPower(plugs=(\"B\", \"C\", \"D\", \"F\", \"G\", \"J\"), voltage=230, freq=50, country=\"Jordan\"),\n \"pl\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Poland\"),\n \"bt\": CountryPower(plugs=(\"C\", \"D\", \"F\", \"G\", \"M\"), voltage=230, freq=50, country=\"Bhutan\"),\n \"fm\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Micronesia\"),\n \"no\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Norway\"),\n \"fk\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Falkland Islands\"),\n \"je\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Jersey\"),\n \"ye\": CountryPower(plugs=(\"A\", \"D\", \"G\"), voltage=230, freq=50, country=\"Yemen\"),\n \"cm\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Cameroon\"),\n \"md\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Moldova\"),\n \"cn\": CountryPower(plugs=(\"A\", \"I\", \"C\"), voltage=220, freq=50, country=\"China\"),\n \"gm\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Gambia\"),\n \"sg\": CountryPower(plugs=(\"C\", \"G\", \"M\"), voltage=230, freq=50, country=\"Singapore\"),\n \"tj\": CountryPower(plugs=(\"C\", \"F\", \"I\"), voltage=220, freq=50, country=\"Tajikistan\"),\n \"gt\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Guatemala\"),\n \"ma\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Morocco\"),\n \"mv\": CountryPower(plugs=(\"D\", \"G\", \"J\", \"K\", \"L\"), voltage=230, freq=50, country=\"Maldives\"),\n \"ga\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Gabon\"),\n \"bo\": CountryPower(plugs=(\"A\", \"C\"), voltage=115, freq=50, country=\"Bolivia\"),\n \"ly\": CountryPower(plugs=(\"C\", \"D\", \"F\", \"L\"), voltage=127, freq=50, country=\"Libya\"),\n \"rw\": CountryPower(plugs=(\"C\", \"J\"), voltage=230, freq=50, country=\"Rwanda\"),\n \"cg\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Congo, Republic of the\"),\n \"kz\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Kazakhstan\"),\n \"jp\": CountryPower(plugs=(\"A\", \"B\"), voltage=100, freq=50, country=\"Japan\"),\n \"co\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Colombia\"),\n \"sm\": CountryPower(plugs=(\"C\", \"F\", \"L\"), voltage=230, freq=50, country=\"San Marino\"),\n \"rs\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Serbia\"),\n \"gw\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Guinea-Bissau\"),\n \"kr\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=60, country=\"South Korea\"),\n \"py\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Paraguay\"),\n \"lt\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Lithuania\"),\n \"tr\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Turkey\"),\n \"pa\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Panama\"),\n \"ba\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Bosnia and Herzegovina\"),\n \"vn\": CountryPower(plugs=(\"A\", \"C\", \"G\"), voltage=220, freq=50, country=\"Vietnam\"),\n \"iq\": CountryPower(plugs=(\"C\", \"D\", \"G\"), voltage=230, freq=50, country=\"Iraq\"),\n \"pk\": CountryPower(plugs=(\"C\", \"D\", \"G\", \"M\"), voltage=230, freq=50, country=\"Pakistan\"),\n \"li\": CountryPower(plugs=(\"C\", \"J\"), voltage=230, freq=50, country=\"Liechtenstein\"),\n \"mz\": CountryPower(plugs=(\"C\", \"F\", \"M\"), voltage=220, freq=50, country=\"Mozambique\"),\n \"au\": CountryPower(plugs=(\"I\",), voltage=230, freq=50, country=\"Australia\"),\n \"ws\": CountryPower(plugs=(\"I\",), voltage=230, freq=50, country=\"Samoa\"),\n \"sr\": CountryPower(plugs=(\"C\", \"F\"), voltage=127, freq=60, country=\"Suriname\"),\n \"mn\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Mongolia\"),\n \"bw\": CountryPower(plugs=(\"D\", \"G\", \"M\"), voltage=230, freq=50, country=\"Botswana\"),\n \"gb\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"United Kingdom\"),\n \"pg\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Papua New Guinea\"),\n \"dj\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Djibouti\"),\n \"th\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"F\"), voltage=220, freq=50, country=\"Thailand\"),\n \"us\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"United States\"),\n \"gr\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Greece\"),\n \"kn\": CountryPower(plugs=(\"A\", \"B\", \"D\", \"G\"), voltage=110, freq=60, country=\"St. Kitts and Nevis\"),\n \"ug\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Uganda\"),\n \"ie\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Ireland\"),\n \"tg\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Togo\"),\n \"td\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"F\"), voltage=220, freq=50, country=\"Chad\"),\n \"la\": CountryPower(plugs=(\"C\", \"E\", \"F\"), voltage=230, freq=50, country=\"Laos\"),\n \"sy\": CountryPower(plugs=(\"C\", \"E\", \"L\"), voltage=220, freq=50, country=\"Syria\"),\n \"bm\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Bermuda\"),\n \"il\": CountryPower(plugs=(\"C\", \"H\", \"M\"), voltage=230, freq=50, country=\"Israel\"),\n \"nz\": CountryPower(plugs=(\"I\",), voltage=230, freq=50, country=\"New Zealand\"),\n \"mg\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"J\", \"K\"), voltage=220, freq=50, country=\"Madagascar\"),\n \"ve\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Venezuela\"),\n \"dk\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"K\"), voltage=230, freq=50, country=\"Denmark\"),\n \"lb\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"D\", \"G\"), voltage=220, freq=50, country=\"Lebanon\"),\n \"kp\": CountryPower(plugs=(\"A\", \"C\", \"F\"), voltage=110, freq=60, country=\"North Korea\"),\n \"vu\": CountryPower(plugs=(\"C\", \"G\", \"I\"), voltage=220, freq=50, country=\"Vanuatu\"),\n \"cu\": CountryPower(plugs=(\"A\", \"B\", \"C\"), voltage=110, freq=60, country=\"Cuba\"),\n \"pt\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Portugal\"),\n \"kw\": CountryPower(plugs=(\"C\", \"G\"), voltage=240, freq=50, country=\"Kuwait\"),\n \"cd\": CountryPower(plugs=(\"C\", \"D\", \"E\"), voltage=220, freq=50, country=\"Congo, Democratic Republic of the\"),\n \"nr\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Nauru\"),\n \"si\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Slovenia\"),\n \"bd\": CountryPower(plugs=(\"C\", \"D\", \"G\", \"K\"), voltage=220, freq=50, country=\"Bangladesh\"),\n \"al\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Albania\"),\n \"ec\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Ecuador\"),\n \"gy\": CountryPower(plugs=(\"A\", \"B\", \"D\", \"G\"), voltage=110, freq=60, country=\"Guyana\"),\n \"bb\": CountryPower(plugs=(\"A\", \"B\"), voltage=115, freq=50, country=\"Barbados\"),\n \"ke\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Kenya\"),\n \"mx\": CountryPower(plugs=(\"A\", \"B\"), voltage=127, freq=60, country=\"Mexico\"),\n \"gq\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Equatorial Guinea\"),\n \"gn\": CountryPower(plugs=(\"C\", \"F\", \"K\"), voltage=220, freq=50, country=\"Guinea\"),\n \"bi\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Burundi\"),\n \"lv\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Latvia\"),\n \"fj\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Fiji\"),\n \"ci\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Côte d'Ivoire\"),\n \"ai\": CountryPower(plugs=(\"A\",), voltage=110, freq=60, country=\"Anguilla\"),\n \"gu\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Guam\"),\n \"lr\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"E\", \"F\"), voltage=120, freq=60, country=\"Liberia\"),\n \"br\": CountryPower(plugs=(\"C\", \"N\"), voltage=220, freq=60, country=\"Brazil\"),\n \"cv\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Cape Verde\"),\n \"cl\": CountryPower(plugs=(\"L\",), voltage=220, freq=50, country=\"Chile\"),\n \"in\": CountryPower(plugs=(\"C\", \"D\", \"M\"), voltage=230, freq=50, country=\"India\"),\n \"gg\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Guernsey\"),\n \"tt\": CountryPower(plugs=(\"A\", \"B\"), voltage=115, freq=60, country=\"Trinidad & Tobago\"),\n \"de\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Germany\"),\n \"qa\": CountryPower(plugs=(\"D\", \"G\"), voltage=240, freq=50, country=\"Qatar\"),\n \"ph\": CountryPower(plugs=(\"A\", \"B\"), voltage=220, freq=60, country=\"Philippines\"),\n \"sd\": CountryPower(plugs=(\"C\", \"D\"), voltage=230, freq=50, country=\"Sudan\"),\n \"mm\": CountryPower(plugs=(\"C\", \"D\", \"F\", \"G\"), voltage=230, freq=50, country=\"Myanmar\"),\n \"gd\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Grenada\"),\n \"st\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"São Tomé and Príncipe\"),\n \"sz\": CountryPower(plugs=(\"M\",), voltage=230, freq=50, country=\"Swaziland\"),\n \"ro\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Romania\"),\n \"xk\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Kosovo\"),\n \"cy\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Cyprus\"),\n \"dz\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Algeria\"),\n \"zm\": CountryPower(plugs=(\"C\", \"D\", \"G\"), voltage=230, freq=50, country=\"Zambia\"),\n \"by\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Belarus\"),\n \"hr\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Croatia\"),\n \"lu\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Luxembourg\"),\n \"fi\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Finland\"),\n \"zw\": CountryPower(plugs=(\"D\", \"G\"), voltage=220, freq=50, country=\"Zimbabwe\"),\n \"km\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Comoros\"),\n \"tl\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"I\"), voltage=220, freq=50, country=\"Timor-Leste \"),\n \"tz\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Tanzania\"),\n \"ht\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Haiti\"),\n \"vc\": CountryPower(plugs=(\"C\", \"E\", \"G\", \"I\", \"K\"), voltage=230, freq=50, country=\"St. Vincent and the Grenadines\"),\n \"es\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Spain\"),\n \"my\": CountryPower(plugs=(\"C\", \"G\", \"M\"), voltage=230, freq=50, country=\"Malaysia\"),\n \"lc\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"St. Lucia\"),\n \"tm\": CountryPower(plugs=(\"B\", \"C\", \"F\"), voltage=220, freq=50, country=\"Turkmenistan\"),\n \"pe\": CountryPower(plugs=(\"A\", \"B\", \"C\"), voltage=220, freq=60, country=\"Peru\"),\n \"ua\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Ukraine\"),\n \"eg\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Egypt\"),\n \"sb\": CountryPower(plugs=(\"I\", \"G\"), voltage=220, freq=50, country=\"Solomon Islands\"),\n \"to\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Tonga\"),\n \"fr\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"France\"),\n \"ng\": CountryPower(plugs=(\"D\", \"G\"), voltage=240, freq=50, country=\"Nigeria\"),\n \"sh\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Saint Helena, Ascension and Tristan da Cunha\"),\n \"mw\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Malawi\"),\n \"ms\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Montserrat\"),\n \"ae\": CountryPower(plugs=(\"C\", \"D\", \"G\"), voltage=220, freq=50, country=\"United Arab Emirates\"),\n \"nl\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Netherlands\"),\n \"id\": CountryPower(plugs=(\"C\", \"F\", \"G\"), voltage=230, freq=50, country=\"Indonesia\"),\n \"ru\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Russia\"),\n \"ar\": CountryPower(plugs=(\"C\", \"I\"), voltage=220, freq=50, country=\"Argentina\"),\n \"bn\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Brunei\"),\n \"pw\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Palau\"),\n \"kg\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Kyrgyzstan\"),\n \"bh\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Bahrain\"),\n \"ml\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Mali\"),\n \"it\": CountryPower(plugs=(\"C\", \"F\", \"L\"), voltage=230, freq=50, country=\"Italy\"),\n \"sa\": CountryPower(plugs=(\"A\", \"B\", \"G\"), voltage=220, freq=60, country=\"Saudi Arabia\"),\n \"ag\": CountryPower(plugs=(\"A\", \"B\"), voltage=230, freq=60, country=\"Antigua and Barbuda\"),\n \"mr\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Mauritania\"),\n \"om\": CountryPower(plugs=(\"C\", \"G\"), voltage=240, freq=50, country=\"Oman\"),\n \"lk\": CountryPower(plugs=(\"D\", \"G\", \"M\"), voltage=230, freq=50, country=\"Sri Lanka\"),\n \"er\": CountryPower(plugs=(\"C\", \"L\"), voltage=230, freq=50, country=\"Eritrea\"),\n \"mk\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Macedonia\"),\n \"ni\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Nicaragua\"),\n \"ch\": CountryPower(plugs=(\"C\", \"J\"), voltage=230, freq=50, country=\"Switzerland\"),\n \"ca\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Canada\"),\n \"cr\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Costa Rica\")\n}\n\nindustrial_power = {\n \"at\": CountryPower(voltage=TUP_400, freq=50, country=\"Austria\"),\n \"bj\": CountryPower(voltage=TUP_380, freq=50, country=\"Benin\"),\n \"gh\": CountryPower(voltage=TUP_400, freq=50, country=\"Ghana\"),\n \"sc\": CountryPower(voltage=TUP_240, freq=50, country=\"Seychelles\"),\n \"bg\": CountryPower(voltage=TUP_400, freq=50, country=\"Bulgaria\"),\n \"me\": CountryPower(voltage=TUP_400, freq=50, country=\"Montenegro\"),\n \"fo\": CountryPower(voltage=TUP_400, freq=50, country=\"Faeroe Islands\"),\n \"iq\": CountryPower(voltage=TUP_400, freq=50, country=\"Iraq\"),\n \"ne\": CountryPower(voltage=TUP_380, freq=50, country=\"Niger\"),\n \"za\": CountryPower(voltage=TUP_400, freq=50, country=\"South Africa\"),\n \"az\": CountryPower(voltage=TUP_380, freq=50, country=\"Azerbaijan\"),\n \"so\": CountryPower(voltage=TUP_380, freq=50, country=\"Somalia\"),\n \"sn\": CountryPower(voltage=TUP_400, freq=50, country=\"Senegal\"),\n \"np\": CountryPower(voltage=TUP_400, freq=50, country=\"Nepal\"),\n \"sl\": CountryPower(voltage=TUP_400, freq=50, country=\"Sierra Leone\"),\n \"be\": CountryPower(voltage=TUP_400, freq=50, country=\"Belgium\"),\n \"vg\": CountryPower(voltage=TUP_190, freq=60, country=\"British Virgin Islands\"),\n \"bz\": CountryPower(voltage=(190, CONST_380), freq=60, country=\"Belize\"),\n \"tw\": CountryPower(voltage=(220,), freq=60, country=\"Taiwan\"),\n \"bf\": CountryPower(voltage=TUP_380, freq=50, country=\"Burkina Faso\"),\n \"ao\": CountryPower(voltage=TUP_380, freq=50, country=\"Angola\"),\n \"ee\": CountryPower(voltage=TUP_400, freq=50, country=\"Estonia\"),\n \"bs\": CountryPower(voltage=TUP_208, freq=60, country=\"Bahamas\"),\n \"ir\": CountryPower(voltage=TUP_400, freq=50, country=\"Iran\"),\n \"sv\": CountryPower(voltage=(200,), freq=60, country=\"El Salvador\"),\n \"am\": CountryPower(voltage=TUP_400, freq=50, country=\"Armenia\"),\n \"is\": CountryPower(voltage=TUP_400, freq=50, country=\"Iceland\"),\n \"uy\": CountryPower(voltage=TUP_380, freq=50, country=\"Uruguay\"),\n \"mc\": CountryPower(voltage=TUP_400, freq=50, country=\"Monaco\"),\n \"jm\": CountryPower(voltage=TUP_190, freq=50, country=\"Jamaica\"),\n \"im\": CountryPower(voltage=TUP_415, freq=50, country=\"Isle of Man\"),\n \"dm\": CountryPower(voltage=TUP_400, freq=50, country=\"Dominica\"),\n \"mu\": CountryPower(voltage=TUP_400, freq=50, country=\"Mauritius\"),\n \"cz\": CountryPower(voltage=TUP_400, freq=50, country=\"Czech Republic\"),\n \"kh\": CountryPower(voltage=TUP_400, freq=50, country=\"Cambodia\"),\n \"cf\": CountryPower(voltage=TUP_380, freq=50, country=\"Central African Republic\"),\n \"se\": CountryPower(voltage=TUP_400, freq=50, country=\"Sweden\"),\n \"uz\": CountryPower(voltage=TUP_380, freq=50, country=\"Uzbekistan\"),\n \"sk\": CountryPower(voltage=TUP_400, freq=50, country=\"Slovakia\"),\n \"ky\": CountryPower(voltage=TUP_240, freq=60, country=\"Cayman Islands\"),\n \"tn\": CountryPower(voltage=TUP_400, freq=50, country=\"Tunisia\"),\n \"hu\": CountryPower(voltage=TUP_400, freq=50, country=\"Hungary\"),\n \"af\": CountryPower(voltage=TUP_380, freq=50, country=\"Afghanistan\"),\n \"tc\": CountryPower(voltage=TUP_240, freq=60, country=\"Turks and Caicos Islands\"),\n \"et\": CountryPower(voltage=TUP_380, freq=50, country=\"Ethiopia\"),\n \"sd\": CountryPower(voltage=TUP_400, freq=50, country=\"Sudan\"),\n \"ad\": CountryPower(voltage=TUP_400, freq=50, country=\"Andorra\"),\n \"hn\": CountryPower(voltage=(208, 230, 240, 460, CONST_480), freq=60, country=\"Honduras\"),\n \"ls\": CountryPower(voltage=TUP_380, freq=50, country=\"Lesotho\"),\n \"na\": CountryPower(voltage=TUP_380, freq=50, country=\"Namibia\"),\n \"pl\": CountryPower(voltage=TUP_400, freq=50, country=\"Poland\"),\n \"bt\": CountryPower(voltage=TUP_400, freq=50, country=\"Bhutan\"),\n \"sa\": CountryPower(voltage=TUP_400, freq=60, country=\"Saudi Arabia\"),\n \"no\": CountryPower(voltage=(230, 400), freq=50, country=\"Norway\"),\n \"fk\": CountryPower(voltage=TUP_415, freq=50, country=\"Falkland Islands\"),\n \"ye\": CountryPower(voltage=TUP_400, freq=50, country=\"Yemen\"),\n \"gi\": CountryPower(voltage=TUP_400, freq=50, country=\"Gibraltar\"),\n \"md\": CountryPower(voltage=TUP_400, freq=50, country=\"Moldova\"),\n \"cn\": CountryPower(voltage=TUP_380, freq=50, country=\"China\"),\n \"gm\": CountryPower(voltage=TUP_400, freq=50, country=\"Gambia\"),\n \"sg\": CountryPower(voltage=TUP_400, freq=50, country=\"Singapore\"),\n \"tj\": CountryPower(voltage=TUP_380, freq=50, country=\"Tajikistan\"),\n \"gt\": CountryPower(voltage=TUP_208, freq=60, country=\"Guatemala\"),\n \"ma\": CountryPower(voltage=TUP_380, freq=50, country=\"Morocco\"),\n \"mv\": CountryPower(voltage=TUP_400, freq=50, country=\"Maldives\"),\n \"ga\": CountryPower(voltage=TUP_380, freq=50, country=\"Gabon\"),\n \"bo\": CountryPower(voltage=TUP_400, freq=50, country=\"Bolivia\"),\n \"ly\": CountryPower(voltage=TUP_400, freq=50, country=\"Libya\"),\n \"rw\": CountryPower(voltage=TUP_400, freq=50, country=\"Rwanda\"),\n \"cg\": CountryPower(voltage=TUP_400, freq=50, country=\"People's Republic of Congo\"),\n \"kz\": CountryPower(voltage=TUP_380, freq=50, country=\"Kazakhstan\"),\n \"jp\": CountryPower(voltage=(200,), freq=50, country=\"Japan\"),\n \"co\": CountryPower(voltage=(220, 440), freq=60, country=\"Colombia\"),\n \"sm\": CountryPower(voltage=TUP_400, freq=50, country=\"San Marino\"),\n \"rs\": CountryPower(voltage=TUP_400, freq=50, country=\"Serbia\"),\n \"gw\": CountryPower(voltage=TUP_380, freq=50, country=\"Guinea-Bissau\"),\n \"kr\": CountryPower(voltage=TUP_380, freq=60, country=\"South Korea\"),\n \"py\": CountryPower(voltage=TUP_380, freq=50, country=\"Paraguay\"),\n \"lt\": CountryPower(voltage=TUP_400, freq=50, country=\"Lithuania\"),\n \"tr\": CountryPower(voltage=TUP_400, freq=50, country=\"Turkey\"),\n \"ss\": CountryPower(voltage=TUP_400, freq=50, country=\"South Sudan\"),\n \"ba\": CountryPower(voltage=TUP_400, freq=50, country=\"Bosnia & Herzegovina\"),\n \"vn\": CountryPower(voltage=TUP_380, freq=50, country=\"Vietnam\"),\n \"do\": CountryPower(voltage=(120, 208, 277, 480), freq=60, country=\"Dominican Republic\"),\n \"pk\": CountryPower(voltage=TUP_400, freq=50, country=\"Pakistan\"),\n \"li\": CountryPower(voltage=TUP_400, freq=50, country=\"Liechtenstein\"),\n \"mz\": CountryPower(voltage=TUP_380, freq=50, country=\"Mozambique\"),\n \"au\": CountryPower(voltage=TUP_400, freq=50, country=\"Australia\"),\n \"ws\": CountryPower(voltage=TUP_400, freq=50, country=\"Samoa\"),\n \"sr\": CountryPower(voltage=(220, 400,), freq=60, country=\"Suriname\"),\n \"mn\": CountryPower(voltage=TUP_400, freq=50, country=\"Mongolia\"),\n \"bw\": CountryPower(voltage=TUP_400, freq=50, country=\"Botswana\"),\n \"gb\": CountryPower(voltage=TUP_415, freq=50, country=\"United Kingdom\"),\n \"pg\": CountryPower(voltage=TUP_415, freq=50, country=\"Papua New Guinea\"),\n \"dj\": CountryPower(voltage=TUP_380, freq=50, country=\"Djibouti\"),\n \"th\": CountryPower(voltage=TUP_400, freq=50, country=\"Thailand\"),\n \"us\": CountryPower(voltage=(120, 208, 277, 480, 120, 240, 240, CONST_480), freq=60, country=\"United States of America\"),\n \"gr\": CountryPower(voltage=TUP_400, freq=50, country=\"Greece\"),\n \"ug\": CountryPower(voltage=TUP_415, freq=50, country=\"Uganda\"),\n \"ie\": CountryPower(voltage=TUP_415, freq=50, country=\"Ireland\"),\n \"tg\": CountryPower(voltage=TUP_380, freq=50, country=\"Togo\"),\n \"td\": CountryPower(voltage=TUP_380, freq=50, country=\"Chad\"),\n \"la\": CountryPower(voltage=TUP_400, freq=50, country=\"Laos\"),\n \"sy\": CountryPower(voltage=TUP_380, freq=50, country=\"Syria\"),\n \"bm\": CountryPower(voltage=TUP_208, freq=60, country=\"Bermuda\"),\n \"il\": CountryPower(voltage=TUP_400, freq=50, country=\"Israel\"),\n \"nz\": CountryPower(voltage=TUP_400, freq=50, country=\"New Zealand\"),\n \"mg\": CountryPower(voltage=TUP_380, freq=50, country=\"Madagascar\"),\n \"ve\": CountryPower(voltage=(120,), freq=60, country=\"Venezuela\"),\n \"dk\": CountryPower(voltage=TUP_400, freq=50, country=\"Denmark\"),\n \"lb\": CountryPower(voltage=TUP_400, freq=50, country=\"Lebanon\"),\n \"kp\": CountryPower(voltage=TUP_380, freq=50, country=\"North Korea\"),\n \"vu\": CountryPower(voltage=TUP_400, freq=50, country=\"Vanuatu\"),\n \"cu\": CountryPower(voltage=(190, 440), freq=60, country=\"Cuba\"),\n \"kw\": CountryPower(voltage=TUP_415, freq=50, country=\"Kuwait\"),\n \"cd\": CountryPower(voltage=TUP_380, freq=50, country=\"Democratic Republic of Congo\"),\n \"nr\": CountryPower(voltage=TUP_415, freq=50, country=\"Nauru\"),\n \"si\": CountryPower(voltage=TUP_400, freq=50, country=\"Slovenia\"),\n \"mt\": CountryPower(voltage=TUP_400, freq=50, country=\"Malta\"),\n \"bd\": CountryPower(voltage=TUP_380, freq=50, country=\"Bangladesh\"),\n \"al\": CountryPower(voltage=TUP_400, freq=50, country=\"Albania\"),\n \"ec\": CountryPower(voltage=TUP_208, freq=60, country=\"Ecuador\"),\n \"gy\": CountryPower(voltage=TUP_190, freq=60, country=\"Guyana\"),\n \"bb\": CountryPower(voltage=(200,), freq=50, country=\"Barbados\"),\n \"ke\": CountryPower(voltage=TUP_415, freq=50, country=\"Kenya\"),\n \"mx\": CountryPower(voltage=(220, CONST_480), freq=60, country=\"Mexico\"),\n \"gn\": CountryPower(voltage=TUP_380, freq=50, country=\"Guinea\"),\n \"bi\": CountryPower(voltage=TUP_380, freq=50, country=\"Burundi\"),\n \"lv\": CountryPower(voltage=TUP_400, freq=50, country=\"Latvia\"),\n \"fj\": CountryPower(voltage=TUP_415, freq=50, country=\"Fiji\"),\n \"ci\": CountryPower(voltage=TUP_380, freq=50, country=\"Côte d’Ivoire\"),\n \"ai\": CountryPower(voltage=(120, 208, 127, 220, 240, 415), freq=60, country=\"Anguilla\"),\n \"gu\": CountryPower(voltage=TUP_190, freq=60, country=\"Guam\"),\n \"lr\": CountryPower(voltage=TUP_208, freq=60, country=\"Liberia\"),\n \"br\": CountryPower(voltage=(220, 380), freq=60, country=\"Brazil\"),\n \"cv\": CountryPower(voltage=TUP_400, freq=50, country=\"Cape Verde\"),\n \"cl\": CountryPower(voltage=TUP_380, freq=50, country=\"Chile\"),\n \"in\": CountryPower(voltage=TUP_400, freq=50, country=\"India\"),\n \"tt\": CountryPower(voltage=(115, 230, 230, 400), freq=60, country=\"Trinidad & Tobago\"),\n \"de\": CountryPower(voltage=TUP_400, freq=50, country=\"Germany\"),\n \"pa\": CountryPower(voltage=TUP_240, freq=60, country=\"Panama\"),\n \"qa\": CountryPower(voltage=TUP_415, freq=50, country=\"Qatar\"),\n \"ph\": CountryPower(voltage=TUP_380, freq=60, country=\"Philippines\"),\n \"jo\": CountryPower(voltage=TUP_400, freq=50, country=\"Jordan\"),\n \"mm\": CountryPower(voltage=TUP_400, freq=50, country=\"Myanmar\"),\n \"gd\": CountryPower(voltage=TUP_400, freq=50, country=\"Grenada\"),\n \"st\": CountryPower(voltage=TUP_400, freq=50, country=\"São Tomé and Príncipe\"),\n \"sz\": CountryPower(voltage=TUP_400, freq=50, country=\"Swaziland\"),\n \"ro\": CountryPower(voltage=TUP_400, freq=50, country=\"Romania\"),\n \"xk\": CountryPower(voltage=(230, 400), freq=50, country=\"Kosovo\"),\n \"cy\": CountryPower(voltage=TUP_400, freq=50, country=\"Cyprus\"),\n \"dz\": CountryPower(voltage=TUP_400, freq=50, country=\"Algeria\"),\n \"zm\": CountryPower(voltage=TUP_400, freq=50, country=\"Zambia\"),\n \"by\": CountryPower(voltage=TUP_380, freq=50, country=\"Belarus\"),\n \"hr\": CountryPower(voltage=TUP_400, freq=50, country=\"Croatia\"),\n \"lu\": CountryPower(voltage=TUP_400, freq=50, country=\"Luxembourg\"),\n \"fi\": CountryPower(voltage=TUP_400, freq=50, country=\"Finland\"),\n \"zw\": CountryPower(voltage=TUP_415, freq=50, country=\"Zimbabwe\"),\n \"km\": CountryPower(voltage=TUP_380, freq=50, country=\"Comoros\"),\n \"tl\": CountryPower(voltage=TUP_380, freq=50, country=\"East Timor\"),\n \"tz\": CountryPower(voltage=TUP_415, freq=50, country=\"Tanzania\"),\n \"ht\": CountryPower(voltage=TUP_190, freq=60, country=\"Haiti\"),\n \"vc\": CountryPower(voltage=TUP_400, freq=50, country=\"Saint Vincent and the Grenadines\"),\n \"es\": CountryPower(voltage=TUP_400, freq=50, country=\"Spain\"),\n \"my\": CountryPower(voltage=TUP_415, freq=50, country=\"Malaysia\"),\n \"lc\": CountryPower(voltage=TUP_400, freq=50, country=\"Saint Lucia\"),\n \"tm\": CountryPower(voltage=TUP_380, freq=50, country=\"Turkmenistan\"),\n \"pe\": CountryPower(voltage=(220,), freq=60, country=\"Peru\"),\n \"ua\": CountryPower(voltage=TUP_400, freq=50, country=\"Ukraine\"),\n \"eg\": CountryPower(voltage=TUP_380, freq=50, country=\"Egypt\"),\n \"to\": CountryPower(voltage=TUP_415, freq=50, country=\"Tonga\"),\n \"fr\": CountryPower(voltage=TUP_400, freq=50, country=\"France\"),\n \"ng\": CountryPower(voltage=TUP_415, freq=50, country=\"Nigeria\"),\n \"mw\": CountryPower(voltage=TUP_400, freq=50, country=\"Malawi\"),\n \"ms\": CountryPower(voltage=TUP_400, freq=60, country=\"Montserrat\"),\n \"ae\": CountryPower(voltage=TUP_400, freq=50, country=\"United Arab Emirates\"),\n \"nl\": CountryPower(voltage=TUP_400, freq=50, country=\"Netherlands\"),\n \"id\": CountryPower(voltage=TUP_400, freq=50, country=\"Indonesia\"),\n \"ru\": CountryPower(voltage=TUP_380, freq=50, country=\"Russia\"),\n \"ar\": CountryPower(voltage=TUP_380, freq=50, country=\"Argentina\"),\n \"bn\": CountryPower(voltage=TUP_415, freq=50, country=\"Brunei\"),\n \"pw\": CountryPower(voltage=TUP_208, freq=60, country=\"Palau\"),\n \"kg\": CountryPower(voltage=TUP_380, freq=50, country=\"Kyrgyzstan\"),\n \"bh\": CountryPower(voltage=TUP_400, freq=50, country=\"Bahrain\"),\n \"ml\": CountryPower(voltage=TUP_380, freq=50, country=\"Mali\"),\n \"it\": CountryPower(voltage=TUP_400, freq=50, country=\"Italy\"),\n \"cm\": CountryPower(voltage=TUP_380, freq=50, country=\"Cameroon\"),\n \"ag\": CountryPower(voltage=TUP_400, freq=60, country=\"Antigua and Barbuda\"),\n \"mr\": CountryPower(voltage=(220,), freq=50, country=\"Mauritania\"),\n \"om\": CountryPower(voltage=TUP_415, freq=50, country=\"Oman\"),\n \"lk\": CountryPower(voltage=TUP_400, freq=50, country=\"Sri Lanka\"),\n \"er\": CountryPower(voltage=TUP_400, freq=50, country=\"Eritrea\"),\n \"mk\": CountryPower(voltage=TUP_400, freq=50, country=\"Macedonia, Republic of\"),\n \"ni\": CountryPower(voltage=TUP_208, freq=60, country=\"Nicaragua\"),\n \"ch\": CountryPower(voltage=TUP_400, freq=50, country=\"Switzerland\"),\n \"ca\": CountryPower(voltage=(120, 208, 240, CONST_480, 347, 600), freq=60, country=\"Canada\"),\n \"cr\": CountryPower(voltage=TUP_240, freq=60, country=\"Costa Rica\")\n}\n\nelectrical_plug_types = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\"]\n\nvoltages_1_phase_residential = [100, 110, 115, 120, 127, 220, 230, 240]\n\nvoltages_3_phase = [120, 190, 200, 208, 220, 230, 240, 277, 380, 400, 415, 440, 480]\n\nresidential_power_frequencies = [50, 60]", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 31977}, "tests/test_pump.py::141": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/numerics/__init__.py", "fluids/pump.py"], "used_names": ["electrical_plug_types", "industrial_power", "residential_power", "residential_power_frequencies", "voltages_1_phase_residential", "voltages_3_phase"], "enclosing_function": "test_power_sources", "extracted_code": "# Source: fluids/pump.py\nresidential_power = {\n \"at\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Austria\"),\n \"bj\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Benin\"),\n \"gh\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Ghana\"),\n \"sc\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Seychelles\"),\n \"bg\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Bulgaria\"),\n \"me\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Montenegro\"),\n \"fo\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"K\"), voltage=230, freq=50, country=\"Faroe Islands\"),\n \"ne\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"), voltage=220, freq=50, country=\"Niger\"),\n \"za\": CountryPower(plugs=(\"C\", \"F\", \"M\", \"N\"), voltage=230, freq=50, country=\"South Africa\"),\n \"az\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Azerbaijan\"),\n \"so\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Somalia\"),\n \"sn\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"K\"), voltage=230, freq=50, country=\"Senegal\"),\n \"np\": CountryPower(plugs=(\"C\", \"D\", \"M\"), voltage=230, freq=50, country=\"Nepal\"),\n \"sl\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Sierra Leone\"),\n \"be\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Belgium\"),\n \"vg\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"British Virgin Islands\"),\n \"bz\": CountryPower(plugs=(\"A\", \"B\", \"G\"), voltage=110, freq=60, country=\"Belize\"),\n \"tw\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Taiwan\"),\n \"bf\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Burkina Faso\"),\n \"ao\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Angola\"),\n \"gi\": CountryPower(plugs=(\"C\", \"G\"), voltage=240, freq=50, country=\"Gibraltar\"),\n \"ee\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Estonia\"),\n \"bs\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Bahamas\"),\n \"ir\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Iran\"),\n \"sv\": CountryPower(plugs=(\"A\", \"B\"), voltage=115, freq=60, country=\"El Salvador\"),\n \"am\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Armenia\"),\n \"is\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Iceland\"),\n \"uy\": CountryPower(plugs=(\"C\", \"F\", \"I\", \"L\"), voltage=230, freq=50, country=\"Uruguay\"),\n \"mc\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"F\"), voltage=230, freq=50, country=\"Monaco\"),\n \"jm\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=50, country=\"Jamaica\"),\n \"im\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Isle of Man\"),\n \"dm\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Dominica\"),\n \"mu\": CountryPower(plugs=(\"C\", \"G\"), voltage=230, freq=50, country=\"Mauritius\"),\n \"cz\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Czech Republic\"),\n \"kh\": CountryPower(plugs=(\"A\", \"C\", \"G\"), voltage=230, freq=50, country=\"Cambodia\"),\n \"cf\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Central African Republic\"),\n \"se\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Sweden\"),\n \"uz\": CountryPower(plugs=(\"C\", \"I\"), voltage=220, freq=50, country=\"Uzbekistan\"),\n \"sk\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Slovakia\"),\n \"ky\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Cayman Islands\"),\n \"tn\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Tunisia\"),\n \"do\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Dominican Republic\"),\n \"hu\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Hungary\"),\n \"af\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Afghanistan\"),\n \"et\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"L\"), voltage=220, freq=50, country=\"Ethiopia\"),\n \"tv\": CountryPower(plugs=(\"I\",), voltage=220, freq=50, country=\"Tuvalu\"),\n \"ad\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Andorra\"),\n \"hn\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Honduras\"),\n \"ls\": CountryPower(plugs=(\"M\",), voltage=220, freq=50, country=\"Lesotho\"),\n \"na\": CountryPower(plugs=(\"D\", \"M\"), voltage=220, freq=50, country=\"Namibia\"),\n \"jo\": CountryPower(plugs=(\"B\", \"C\", \"D\", \"F\", \"G\", \"J\"), voltage=230, freq=50, country=\"Jordan\"),\n \"pl\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Poland\"),\n \"bt\": CountryPower(plugs=(\"C\", \"D\", \"F\", \"G\", \"M\"), voltage=230, freq=50, country=\"Bhutan\"),\n \"fm\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Micronesia\"),\n \"no\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Norway\"),\n \"fk\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Falkland Islands\"),\n \"je\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Jersey\"),\n \"ye\": CountryPower(plugs=(\"A\", \"D\", \"G\"), voltage=230, freq=50, country=\"Yemen\"),\n \"cm\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Cameroon\"),\n \"md\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Moldova\"),\n \"cn\": CountryPower(plugs=(\"A\", \"I\", \"C\"), voltage=220, freq=50, country=\"China\"),\n \"gm\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Gambia\"),\n \"sg\": CountryPower(plugs=(\"C\", \"G\", \"M\"), voltage=230, freq=50, country=\"Singapore\"),\n \"tj\": CountryPower(plugs=(\"C\", \"F\", \"I\"), voltage=220, freq=50, country=\"Tajikistan\"),\n \"gt\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Guatemala\"),\n \"ma\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Morocco\"),\n \"mv\": CountryPower(plugs=(\"D\", \"G\", \"J\", \"K\", \"L\"), voltage=230, freq=50, country=\"Maldives\"),\n \"ga\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Gabon\"),\n \"bo\": CountryPower(plugs=(\"A\", \"C\"), voltage=115, freq=50, country=\"Bolivia\"),\n \"ly\": CountryPower(plugs=(\"C\", \"D\", \"F\", \"L\"), voltage=127, freq=50, country=\"Libya\"),\n \"rw\": CountryPower(plugs=(\"C\", \"J\"), voltage=230, freq=50, country=\"Rwanda\"),\n \"cg\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Congo, Republic of the\"),\n \"kz\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Kazakhstan\"),\n \"jp\": CountryPower(plugs=(\"A\", \"B\"), voltage=100, freq=50, country=\"Japan\"),\n \"co\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Colombia\"),\n \"sm\": CountryPower(plugs=(\"C\", \"F\", \"L\"), voltage=230, freq=50, country=\"San Marino\"),\n \"rs\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Serbia\"),\n \"gw\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Guinea-Bissau\"),\n \"kr\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=60, country=\"South Korea\"),\n \"py\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Paraguay\"),\n \"lt\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Lithuania\"),\n \"tr\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Turkey\"),\n \"pa\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Panama\"),\n \"ba\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Bosnia and Herzegovina\"),\n \"vn\": CountryPower(plugs=(\"A\", \"C\", \"G\"), voltage=220, freq=50, country=\"Vietnam\"),\n \"iq\": CountryPower(plugs=(\"C\", \"D\", \"G\"), voltage=230, freq=50, country=\"Iraq\"),\n \"pk\": CountryPower(plugs=(\"C\", \"D\", \"G\", \"M\"), voltage=230, freq=50, country=\"Pakistan\"),\n \"li\": CountryPower(plugs=(\"C\", \"J\"), voltage=230, freq=50, country=\"Liechtenstein\"),\n \"mz\": CountryPower(plugs=(\"C\", \"F\", \"M\"), voltage=220, freq=50, country=\"Mozambique\"),\n \"au\": CountryPower(plugs=(\"I\",), voltage=230, freq=50, country=\"Australia\"),\n \"ws\": CountryPower(plugs=(\"I\",), voltage=230, freq=50, country=\"Samoa\"),\n \"sr\": CountryPower(plugs=(\"C\", \"F\"), voltage=127, freq=60, country=\"Suriname\"),\n \"mn\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Mongolia\"),\n \"bw\": CountryPower(plugs=(\"D\", \"G\", \"M\"), voltage=230, freq=50, country=\"Botswana\"),\n \"gb\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"United Kingdom\"),\n \"pg\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Papua New Guinea\"),\n \"dj\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Djibouti\"),\n \"th\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"F\"), voltage=220, freq=50, country=\"Thailand\"),\n \"us\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"United States\"),\n \"gr\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Greece\"),\n \"kn\": CountryPower(plugs=(\"A\", \"B\", \"D\", \"G\"), voltage=110, freq=60, country=\"St. Kitts and Nevis\"),\n \"ug\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Uganda\"),\n \"ie\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Ireland\"),\n \"tg\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Togo\"),\n \"td\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"F\"), voltage=220, freq=50, country=\"Chad\"),\n \"la\": CountryPower(plugs=(\"C\", \"E\", \"F\"), voltage=230, freq=50, country=\"Laos\"),\n \"sy\": CountryPower(plugs=(\"C\", \"E\", \"L\"), voltage=220, freq=50, country=\"Syria\"),\n \"bm\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Bermuda\"),\n \"il\": CountryPower(plugs=(\"C\", \"H\", \"M\"), voltage=230, freq=50, country=\"Israel\"),\n \"nz\": CountryPower(plugs=(\"I\",), voltage=230, freq=50, country=\"New Zealand\"),\n \"mg\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"J\", \"K\"), voltage=220, freq=50, country=\"Madagascar\"),\n \"ve\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Venezuela\"),\n \"dk\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"K\"), voltage=230, freq=50, country=\"Denmark\"),\n \"lb\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"D\", \"G\"), voltage=220, freq=50, country=\"Lebanon\"),\n \"kp\": CountryPower(plugs=(\"A\", \"C\", \"F\"), voltage=110, freq=60, country=\"North Korea\"),\n \"vu\": CountryPower(plugs=(\"C\", \"G\", \"I\"), voltage=220, freq=50, country=\"Vanuatu\"),\n \"cu\": CountryPower(plugs=(\"A\", \"B\", \"C\"), voltage=110, freq=60, country=\"Cuba\"),\n \"pt\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Portugal\"),\n \"kw\": CountryPower(plugs=(\"C\", \"G\"), voltage=240, freq=50, country=\"Kuwait\"),\n \"cd\": CountryPower(plugs=(\"C\", \"D\", \"E\"), voltage=220, freq=50, country=\"Congo, Democratic Republic of the\"),\n \"nr\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Nauru\"),\n \"si\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Slovenia\"),\n \"bd\": CountryPower(plugs=(\"C\", \"D\", \"G\", \"K\"), voltage=220, freq=50, country=\"Bangladesh\"),\n \"al\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Albania\"),\n \"ec\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Ecuador\"),\n \"gy\": CountryPower(plugs=(\"A\", \"B\", \"D\", \"G\"), voltage=110, freq=60, country=\"Guyana\"),\n \"bb\": CountryPower(plugs=(\"A\", \"B\"), voltage=115, freq=50, country=\"Barbados\"),\n \"ke\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Kenya\"),\n \"mx\": CountryPower(plugs=(\"A\", \"B\"), voltage=127, freq=60, country=\"Mexico\"),\n \"gq\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Equatorial Guinea\"),\n \"gn\": CountryPower(plugs=(\"C\", \"F\", \"K\"), voltage=220, freq=50, country=\"Guinea\"),\n \"bi\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Burundi\"),\n \"lv\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Latvia\"),\n \"fj\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Fiji\"),\n \"ci\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Côte d'Ivoire\"),\n \"ai\": CountryPower(plugs=(\"A\",), voltage=110, freq=60, country=\"Anguilla\"),\n \"gu\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Guam\"),\n \"lr\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"E\", \"F\"), voltage=120, freq=60, country=\"Liberia\"),\n \"br\": CountryPower(plugs=(\"C\", \"N\"), voltage=220, freq=60, country=\"Brazil\"),\n \"cv\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Cape Verde\"),\n \"cl\": CountryPower(plugs=(\"L\",), voltage=220, freq=50, country=\"Chile\"),\n \"in\": CountryPower(plugs=(\"C\", \"D\", \"M\"), voltage=230, freq=50, country=\"India\"),\n \"gg\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Guernsey\"),\n \"tt\": CountryPower(plugs=(\"A\", \"B\"), voltage=115, freq=60, country=\"Trinidad & Tobago\"),\n \"de\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Germany\"),\n \"qa\": CountryPower(plugs=(\"D\", \"G\"), voltage=240, freq=50, country=\"Qatar\"),\n \"ph\": CountryPower(plugs=(\"A\", \"B\"), voltage=220, freq=60, country=\"Philippines\"),\n \"sd\": CountryPower(plugs=(\"C\", \"D\"), voltage=230, freq=50, country=\"Sudan\"),\n \"mm\": CountryPower(plugs=(\"C\", \"D\", \"F\", \"G\"), voltage=230, freq=50, country=\"Myanmar\"),\n \"gd\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Grenada\"),\n \"st\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"São Tomé and Príncipe\"),\n \"sz\": CountryPower(plugs=(\"M\",), voltage=230, freq=50, country=\"Swaziland\"),\n \"ro\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Romania\"),\n \"xk\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Kosovo\"),\n \"cy\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Cyprus\"),\n \"dz\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Algeria\"),\n \"zm\": CountryPower(plugs=(\"C\", \"D\", \"G\"), voltage=230, freq=50, country=\"Zambia\"),\n \"by\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Belarus\"),\n \"hr\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Croatia\"),\n \"lu\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Luxembourg\"),\n \"fi\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Finland\"),\n \"zw\": CountryPower(plugs=(\"D\", \"G\"), voltage=220, freq=50, country=\"Zimbabwe\"),\n \"km\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Comoros\"),\n \"tl\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"I\"), voltage=220, freq=50, country=\"Timor-Leste \"),\n \"tz\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Tanzania\"),\n \"ht\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Haiti\"),\n \"vc\": CountryPower(plugs=(\"C\", \"E\", \"G\", \"I\", \"K\"), voltage=230, freq=50, country=\"St. Vincent and the Grenadines\"),\n \"es\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Spain\"),\n \"my\": CountryPower(plugs=(\"C\", \"G\", \"M\"), voltage=230, freq=50, country=\"Malaysia\"),\n \"lc\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"St. Lucia\"),\n \"tm\": CountryPower(plugs=(\"B\", \"C\", \"F\"), voltage=220, freq=50, country=\"Turkmenistan\"),\n \"pe\": CountryPower(plugs=(\"A\", \"B\", \"C\"), voltage=220, freq=60, country=\"Peru\"),\n \"ua\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Ukraine\"),\n \"eg\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Egypt\"),\n \"sb\": CountryPower(plugs=(\"I\", \"G\"), voltage=220, freq=50, country=\"Solomon Islands\"),\n \"to\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Tonga\"),\n \"fr\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"France\"),\n \"ng\": CountryPower(plugs=(\"D\", \"G\"), voltage=240, freq=50, country=\"Nigeria\"),\n \"sh\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Saint Helena, Ascension and Tristan da Cunha\"),\n \"mw\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Malawi\"),\n \"ms\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Montserrat\"),\n \"ae\": CountryPower(plugs=(\"C\", \"D\", \"G\"), voltage=220, freq=50, country=\"United Arab Emirates\"),\n \"nl\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Netherlands\"),\n \"id\": CountryPower(plugs=(\"C\", \"F\", \"G\"), voltage=230, freq=50, country=\"Indonesia\"),\n \"ru\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Russia\"),\n \"ar\": CountryPower(plugs=(\"C\", \"I\"), voltage=220, freq=50, country=\"Argentina\"),\n \"bn\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Brunei\"),\n \"pw\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Palau\"),\n \"kg\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Kyrgyzstan\"),\n \"bh\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Bahrain\"),\n \"ml\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Mali\"),\n \"it\": CountryPower(plugs=(\"C\", \"F\", \"L\"), voltage=230, freq=50, country=\"Italy\"),\n \"sa\": CountryPower(plugs=(\"A\", \"B\", \"G\"), voltage=220, freq=60, country=\"Saudi Arabia\"),\n \"ag\": CountryPower(plugs=(\"A\", \"B\"), voltage=230, freq=60, country=\"Antigua and Barbuda\"),\n \"mr\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Mauritania\"),\n \"om\": CountryPower(plugs=(\"C\", \"G\"), voltage=240, freq=50, country=\"Oman\"),\n \"lk\": CountryPower(plugs=(\"D\", \"G\", \"M\"), voltage=230, freq=50, country=\"Sri Lanka\"),\n \"er\": CountryPower(plugs=(\"C\", \"L\"), voltage=230, freq=50, country=\"Eritrea\"),\n \"mk\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Macedonia\"),\n \"ni\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Nicaragua\"),\n \"ch\": CountryPower(plugs=(\"C\", \"J\"), voltage=230, freq=50, country=\"Switzerland\"),\n \"ca\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Canada\"),\n \"cr\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Costa Rica\")\n}\n\nindustrial_power = {\n \"at\": CountryPower(voltage=TUP_400, freq=50, country=\"Austria\"),\n \"bj\": CountryPower(voltage=TUP_380, freq=50, country=\"Benin\"),\n \"gh\": CountryPower(voltage=TUP_400, freq=50, country=\"Ghana\"),\n \"sc\": CountryPower(voltage=TUP_240, freq=50, country=\"Seychelles\"),\n \"bg\": CountryPower(voltage=TUP_400, freq=50, country=\"Bulgaria\"),\n \"me\": CountryPower(voltage=TUP_400, freq=50, country=\"Montenegro\"),\n \"fo\": CountryPower(voltage=TUP_400, freq=50, country=\"Faeroe Islands\"),\n \"iq\": CountryPower(voltage=TUP_400, freq=50, country=\"Iraq\"),\n \"ne\": CountryPower(voltage=TUP_380, freq=50, country=\"Niger\"),\n \"za\": CountryPower(voltage=TUP_400, freq=50, country=\"South Africa\"),\n \"az\": CountryPower(voltage=TUP_380, freq=50, country=\"Azerbaijan\"),\n \"so\": CountryPower(voltage=TUP_380, freq=50, country=\"Somalia\"),\n \"sn\": CountryPower(voltage=TUP_400, freq=50, country=\"Senegal\"),\n \"np\": CountryPower(voltage=TUP_400, freq=50, country=\"Nepal\"),\n \"sl\": CountryPower(voltage=TUP_400, freq=50, country=\"Sierra Leone\"),\n \"be\": CountryPower(voltage=TUP_400, freq=50, country=\"Belgium\"),\n \"vg\": CountryPower(voltage=TUP_190, freq=60, country=\"British Virgin Islands\"),\n \"bz\": CountryPower(voltage=(190, CONST_380), freq=60, country=\"Belize\"),\n \"tw\": CountryPower(voltage=(220,), freq=60, country=\"Taiwan\"),\n \"bf\": CountryPower(voltage=TUP_380, freq=50, country=\"Burkina Faso\"),\n \"ao\": CountryPower(voltage=TUP_380, freq=50, country=\"Angola\"),\n \"ee\": CountryPower(voltage=TUP_400, freq=50, country=\"Estonia\"),\n \"bs\": CountryPower(voltage=TUP_208, freq=60, country=\"Bahamas\"),\n \"ir\": CountryPower(voltage=TUP_400, freq=50, country=\"Iran\"),\n \"sv\": CountryPower(voltage=(200,), freq=60, country=\"El Salvador\"),\n \"am\": CountryPower(voltage=TUP_400, freq=50, country=\"Armenia\"),\n \"is\": CountryPower(voltage=TUP_400, freq=50, country=\"Iceland\"),\n \"uy\": CountryPower(voltage=TUP_380, freq=50, country=\"Uruguay\"),\n \"mc\": CountryPower(voltage=TUP_400, freq=50, country=\"Monaco\"),\n \"jm\": CountryPower(voltage=TUP_190, freq=50, country=\"Jamaica\"),\n \"im\": CountryPower(voltage=TUP_415, freq=50, country=\"Isle of Man\"),\n \"dm\": CountryPower(voltage=TUP_400, freq=50, country=\"Dominica\"),\n \"mu\": CountryPower(voltage=TUP_400, freq=50, country=\"Mauritius\"),\n \"cz\": CountryPower(voltage=TUP_400, freq=50, country=\"Czech Republic\"),\n \"kh\": CountryPower(voltage=TUP_400, freq=50, country=\"Cambodia\"),\n \"cf\": CountryPower(voltage=TUP_380, freq=50, country=\"Central African Republic\"),\n \"se\": CountryPower(voltage=TUP_400, freq=50, country=\"Sweden\"),\n \"uz\": CountryPower(voltage=TUP_380, freq=50, country=\"Uzbekistan\"),\n \"sk\": CountryPower(voltage=TUP_400, freq=50, country=\"Slovakia\"),\n \"ky\": CountryPower(voltage=TUP_240, freq=60, country=\"Cayman Islands\"),\n \"tn\": CountryPower(voltage=TUP_400, freq=50, country=\"Tunisia\"),\n \"hu\": CountryPower(voltage=TUP_400, freq=50, country=\"Hungary\"),\n \"af\": CountryPower(voltage=TUP_380, freq=50, country=\"Afghanistan\"),\n \"tc\": CountryPower(voltage=TUP_240, freq=60, country=\"Turks and Caicos Islands\"),\n \"et\": CountryPower(voltage=TUP_380, freq=50, country=\"Ethiopia\"),\n \"sd\": CountryPower(voltage=TUP_400, freq=50, country=\"Sudan\"),\n \"ad\": CountryPower(voltage=TUP_400, freq=50, country=\"Andorra\"),\n \"hn\": CountryPower(voltage=(208, 230, 240, 460, CONST_480), freq=60, country=\"Honduras\"),\n \"ls\": CountryPower(voltage=TUP_380, freq=50, country=\"Lesotho\"),\n \"na\": CountryPower(voltage=TUP_380, freq=50, country=\"Namibia\"),\n \"pl\": CountryPower(voltage=TUP_400, freq=50, country=\"Poland\"),\n \"bt\": CountryPower(voltage=TUP_400, freq=50, country=\"Bhutan\"),\n \"sa\": CountryPower(voltage=TUP_400, freq=60, country=\"Saudi Arabia\"),\n \"no\": CountryPower(voltage=(230, 400), freq=50, country=\"Norway\"),\n \"fk\": CountryPower(voltage=TUP_415, freq=50, country=\"Falkland Islands\"),\n \"ye\": CountryPower(voltage=TUP_400, freq=50, country=\"Yemen\"),\n \"gi\": CountryPower(voltage=TUP_400, freq=50, country=\"Gibraltar\"),\n \"md\": CountryPower(voltage=TUP_400, freq=50, country=\"Moldova\"),\n \"cn\": CountryPower(voltage=TUP_380, freq=50, country=\"China\"),\n \"gm\": CountryPower(voltage=TUP_400, freq=50, country=\"Gambia\"),\n \"sg\": CountryPower(voltage=TUP_400, freq=50, country=\"Singapore\"),\n \"tj\": CountryPower(voltage=TUP_380, freq=50, country=\"Tajikistan\"),\n \"gt\": CountryPower(voltage=TUP_208, freq=60, country=\"Guatemala\"),\n \"ma\": CountryPower(voltage=TUP_380, freq=50, country=\"Morocco\"),\n \"mv\": CountryPower(voltage=TUP_400, freq=50, country=\"Maldives\"),\n \"ga\": CountryPower(voltage=TUP_380, freq=50, country=\"Gabon\"),\n \"bo\": CountryPower(voltage=TUP_400, freq=50, country=\"Bolivia\"),\n \"ly\": CountryPower(voltage=TUP_400, freq=50, country=\"Libya\"),\n \"rw\": CountryPower(voltage=TUP_400, freq=50, country=\"Rwanda\"),\n \"cg\": CountryPower(voltage=TUP_400, freq=50, country=\"People's Republic of Congo\"),\n \"kz\": CountryPower(voltage=TUP_380, freq=50, country=\"Kazakhstan\"),\n \"jp\": CountryPower(voltage=(200,), freq=50, country=\"Japan\"),\n \"co\": CountryPower(voltage=(220, 440), freq=60, country=\"Colombia\"),\n \"sm\": CountryPower(voltage=TUP_400, freq=50, country=\"San Marino\"),\n \"rs\": CountryPower(voltage=TUP_400, freq=50, country=\"Serbia\"),\n \"gw\": CountryPower(voltage=TUP_380, freq=50, country=\"Guinea-Bissau\"),\n \"kr\": CountryPower(voltage=TUP_380, freq=60, country=\"South Korea\"),\n \"py\": CountryPower(voltage=TUP_380, freq=50, country=\"Paraguay\"),\n \"lt\": CountryPower(voltage=TUP_400, freq=50, country=\"Lithuania\"),\n \"tr\": CountryPower(voltage=TUP_400, freq=50, country=\"Turkey\"),\n \"ss\": CountryPower(voltage=TUP_400, freq=50, country=\"South Sudan\"),\n \"ba\": CountryPower(voltage=TUP_400, freq=50, country=\"Bosnia & Herzegovina\"),\n \"vn\": CountryPower(voltage=TUP_380, freq=50, country=\"Vietnam\"),\n \"do\": CountryPower(voltage=(120, 208, 277, 480), freq=60, country=\"Dominican Republic\"),\n \"pk\": CountryPower(voltage=TUP_400, freq=50, country=\"Pakistan\"),\n \"li\": CountryPower(voltage=TUP_400, freq=50, country=\"Liechtenstein\"),\n \"mz\": CountryPower(voltage=TUP_380, freq=50, country=\"Mozambique\"),\n \"au\": CountryPower(voltage=TUP_400, freq=50, country=\"Australia\"),\n \"ws\": CountryPower(voltage=TUP_400, freq=50, country=\"Samoa\"),\n \"sr\": CountryPower(voltage=(220, 400,), freq=60, country=\"Suriname\"),\n \"mn\": CountryPower(voltage=TUP_400, freq=50, country=\"Mongolia\"),\n \"bw\": CountryPower(voltage=TUP_400, freq=50, country=\"Botswana\"),\n \"gb\": CountryPower(voltage=TUP_415, freq=50, country=\"United Kingdom\"),\n \"pg\": CountryPower(voltage=TUP_415, freq=50, country=\"Papua New Guinea\"),\n \"dj\": CountryPower(voltage=TUP_380, freq=50, country=\"Djibouti\"),\n \"th\": CountryPower(voltage=TUP_400, freq=50, country=\"Thailand\"),\n \"us\": CountryPower(voltage=(120, 208, 277, 480, 120, 240, 240, CONST_480), freq=60, country=\"United States of America\"),\n \"gr\": CountryPower(voltage=TUP_400, freq=50, country=\"Greece\"),\n \"ug\": CountryPower(voltage=TUP_415, freq=50, country=\"Uganda\"),\n \"ie\": CountryPower(voltage=TUP_415, freq=50, country=\"Ireland\"),\n \"tg\": CountryPower(voltage=TUP_380, freq=50, country=\"Togo\"),\n \"td\": CountryPower(voltage=TUP_380, freq=50, country=\"Chad\"),\n \"la\": CountryPower(voltage=TUP_400, freq=50, country=\"Laos\"),\n \"sy\": CountryPower(voltage=TUP_380, freq=50, country=\"Syria\"),\n \"bm\": CountryPower(voltage=TUP_208, freq=60, country=\"Bermuda\"),\n \"il\": CountryPower(voltage=TUP_400, freq=50, country=\"Israel\"),\n \"nz\": CountryPower(voltage=TUP_400, freq=50, country=\"New Zealand\"),\n \"mg\": CountryPower(voltage=TUP_380, freq=50, country=\"Madagascar\"),\n \"ve\": CountryPower(voltage=(120,), freq=60, country=\"Venezuela\"),\n \"dk\": CountryPower(voltage=TUP_400, freq=50, country=\"Denmark\"),\n \"lb\": CountryPower(voltage=TUP_400, freq=50, country=\"Lebanon\"),\n \"kp\": CountryPower(voltage=TUP_380, freq=50, country=\"North Korea\"),\n \"vu\": CountryPower(voltage=TUP_400, freq=50, country=\"Vanuatu\"),\n \"cu\": CountryPower(voltage=(190, 440), freq=60, country=\"Cuba\"),\n \"kw\": CountryPower(voltage=TUP_415, freq=50, country=\"Kuwait\"),\n \"cd\": CountryPower(voltage=TUP_380, freq=50, country=\"Democratic Republic of Congo\"),\n \"nr\": CountryPower(voltage=TUP_415, freq=50, country=\"Nauru\"),\n \"si\": CountryPower(voltage=TUP_400, freq=50, country=\"Slovenia\"),\n \"mt\": CountryPower(voltage=TUP_400, freq=50, country=\"Malta\"),\n \"bd\": CountryPower(voltage=TUP_380, freq=50, country=\"Bangladesh\"),\n \"al\": CountryPower(voltage=TUP_400, freq=50, country=\"Albania\"),\n \"ec\": CountryPower(voltage=TUP_208, freq=60, country=\"Ecuador\"),\n \"gy\": CountryPower(voltage=TUP_190, freq=60, country=\"Guyana\"),\n \"bb\": CountryPower(voltage=(200,), freq=50, country=\"Barbados\"),\n \"ke\": CountryPower(voltage=TUP_415, freq=50, country=\"Kenya\"),\n \"mx\": CountryPower(voltage=(220, CONST_480), freq=60, country=\"Mexico\"),\n \"gn\": CountryPower(voltage=TUP_380, freq=50, country=\"Guinea\"),\n \"bi\": CountryPower(voltage=TUP_380, freq=50, country=\"Burundi\"),\n \"lv\": CountryPower(voltage=TUP_400, freq=50, country=\"Latvia\"),\n \"fj\": CountryPower(voltage=TUP_415, freq=50, country=\"Fiji\"),\n \"ci\": CountryPower(voltage=TUP_380, freq=50, country=\"Côte d’Ivoire\"),\n \"ai\": CountryPower(voltage=(120, 208, 127, 220, 240, 415), freq=60, country=\"Anguilla\"),\n \"gu\": CountryPower(voltage=TUP_190, freq=60, country=\"Guam\"),\n \"lr\": CountryPower(voltage=TUP_208, freq=60, country=\"Liberia\"),\n \"br\": CountryPower(voltage=(220, 380), freq=60, country=\"Brazil\"),\n \"cv\": CountryPower(voltage=TUP_400, freq=50, country=\"Cape Verde\"),\n \"cl\": CountryPower(voltage=TUP_380, freq=50, country=\"Chile\"),\n \"in\": CountryPower(voltage=TUP_400, freq=50, country=\"India\"),\n \"tt\": CountryPower(voltage=(115, 230, 230, 400), freq=60, country=\"Trinidad & Tobago\"),\n \"de\": CountryPower(voltage=TUP_400, freq=50, country=\"Germany\"),\n \"pa\": CountryPower(voltage=TUP_240, freq=60, country=\"Panama\"),\n \"qa\": CountryPower(voltage=TUP_415, freq=50, country=\"Qatar\"),\n \"ph\": CountryPower(voltage=TUP_380, freq=60, country=\"Philippines\"),\n \"jo\": CountryPower(voltage=TUP_400, freq=50, country=\"Jordan\"),\n \"mm\": CountryPower(voltage=TUP_400, freq=50, country=\"Myanmar\"),\n \"gd\": CountryPower(voltage=TUP_400, freq=50, country=\"Grenada\"),\n \"st\": CountryPower(voltage=TUP_400, freq=50, country=\"São Tomé and Príncipe\"),\n \"sz\": CountryPower(voltage=TUP_400, freq=50, country=\"Swaziland\"),\n \"ro\": CountryPower(voltage=TUP_400, freq=50, country=\"Romania\"),\n \"xk\": CountryPower(voltage=(230, 400), freq=50, country=\"Kosovo\"),\n \"cy\": CountryPower(voltage=TUP_400, freq=50, country=\"Cyprus\"),\n \"dz\": CountryPower(voltage=TUP_400, freq=50, country=\"Algeria\"),\n \"zm\": CountryPower(voltage=TUP_400, freq=50, country=\"Zambia\"),\n \"by\": CountryPower(voltage=TUP_380, freq=50, country=\"Belarus\"),\n \"hr\": CountryPower(voltage=TUP_400, freq=50, country=\"Croatia\"),\n \"lu\": CountryPower(voltage=TUP_400, freq=50, country=\"Luxembourg\"),\n \"fi\": CountryPower(voltage=TUP_400, freq=50, country=\"Finland\"),\n \"zw\": CountryPower(voltage=TUP_415, freq=50, country=\"Zimbabwe\"),\n \"km\": CountryPower(voltage=TUP_380, freq=50, country=\"Comoros\"),\n \"tl\": CountryPower(voltage=TUP_380, freq=50, country=\"East Timor\"),\n \"tz\": CountryPower(voltage=TUP_415, freq=50, country=\"Tanzania\"),\n \"ht\": CountryPower(voltage=TUP_190, freq=60, country=\"Haiti\"),\n \"vc\": CountryPower(voltage=TUP_400, freq=50, country=\"Saint Vincent and the Grenadines\"),\n \"es\": CountryPower(voltage=TUP_400, freq=50, country=\"Spain\"),\n \"my\": CountryPower(voltage=TUP_415, freq=50, country=\"Malaysia\"),\n \"lc\": CountryPower(voltage=TUP_400, freq=50, country=\"Saint Lucia\"),\n \"tm\": CountryPower(voltage=TUP_380, freq=50, country=\"Turkmenistan\"),\n \"pe\": CountryPower(voltage=(220,), freq=60, country=\"Peru\"),\n \"ua\": CountryPower(voltage=TUP_400, freq=50, country=\"Ukraine\"),\n \"eg\": CountryPower(voltage=TUP_380, freq=50, country=\"Egypt\"),\n \"to\": CountryPower(voltage=TUP_415, freq=50, country=\"Tonga\"),\n \"fr\": CountryPower(voltage=TUP_400, freq=50, country=\"France\"),\n \"ng\": CountryPower(voltage=TUP_415, freq=50, country=\"Nigeria\"),\n \"mw\": CountryPower(voltage=TUP_400, freq=50, country=\"Malawi\"),\n \"ms\": CountryPower(voltage=TUP_400, freq=60, country=\"Montserrat\"),\n \"ae\": CountryPower(voltage=TUP_400, freq=50, country=\"United Arab Emirates\"),\n \"nl\": CountryPower(voltage=TUP_400, freq=50, country=\"Netherlands\"),\n \"id\": CountryPower(voltage=TUP_400, freq=50, country=\"Indonesia\"),\n \"ru\": CountryPower(voltage=TUP_380, freq=50, country=\"Russia\"),\n \"ar\": CountryPower(voltage=TUP_380, freq=50, country=\"Argentina\"),\n \"bn\": CountryPower(voltage=TUP_415, freq=50, country=\"Brunei\"),\n \"pw\": CountryPower(voltage=TUP_208, freq=60, country=\"Palau\"),\n \"kg\": CountryPower(voltage=TUP_380, freq=50, country=\"Kyrgyzstan\"),\n \"bh\": CountryPower(voltage=TUP_400, freq=50, country=\"Bahrain\"),\n \"ml\": CountryPower(voltage=TUP_380, freq=50, country=\"Mali\"),\n \"it\": CountryPower(voltage=TUP_400, freq=50, country=\"Italy\"),\n \"cm\": CountryPower(voltage=TUP_380, freq=50, country=\"Cameroon\"),\n \"ag\": CountryPower(voltage=TUP_400, freq=60, country=\"Antigua and Barbuda\"),\n \"mr\": CountryPower(voltage=(220,), freq=50, country=\"Mauritania\"),\n \"om\": CountryPower(voltage=TUP_415, freq=50, country=\"Oman\"),\n \"lk\": CountryPower(voltage=TUP_400, freq=50, country=\"Sri Lanka\"),\n \"er\": CountryPower(voltage=TUP_400, freq=50, country=\"Eritrea\"),\n \"mk\": CountryPower(voltage=TUP_400, freq=50, country=\"Macedonia, Republic of\"),\n \"ni\": CountryPower(voltage=TUP_208, freq=60, country=\"Nicaragua\"),\n \"ch\": CountryPower(voltage=TUP_400, freq=50, country=\"Switzerland\"),\n \"ca\": CountryPower(voltage=(120, 208, 240, CONST_480, 347, 600), freq=60, country=\"Canada\"),\n \"cr\": CountryPower(voltage=TUP_240, freq=60, country=\"Costa Rica\")\n}\n\nelectrical_plug_types = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\"]\n\nvoltages_1_phase_residential = [100, 110, 115, 120, 127, 220, 230, 240]\n\nvoltages_3_phase = [120, 190, 200, 208, 220, 230, 240, 277, 380, 400, 415, 440, 480]\n\nresidential_power_frequencies = [50, 60]", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 31977}, "tests/test_safety_valve.py::62": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/numerics/__init__.py", "fluids/safety_valve.py"], "used_names": ["API520_A_g", "API520_B", "API520_C", "API520_F2", "API520_N", "API520_W", "API520_round_size", "API526_A", "API526_letters", "assert_close", "assert_close1d", "atm", "pytest"], "enclosing_function": "test_safety_valve", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\n\n# Source: fluids/safety_valve.py\nAPI526_letters = [\"D\", \"E\", \"F\", \"G\", \"H\", \"J\", \"K\", \"L\", \"M\", \"N\", \"P\", \"Q\", \"R\",\"T\"]\n\nAPI526_A = [i*inch2 for i in API526_A_sq_inch]\n\ndef API520_round_size(A: float) -> float:\n r\"\"\"Rounds up the area from an API 520 calculation to an API526 standard\n valve area. The returned area is always larger or equal to the input area.\n\n Parameters\n ----------\n A : float\n Minimum discharge area [m^2]\n\n Returns\n -------\n area : float\n Actual discharge area [m^2]\n\n Notes\n -----\n To obtain the letter designation of an input area, lookup the area with\n the following:\n\n API526_letters[API526_A.index(area)]\n\n An exception is raised if the required relief area is larger than any of\n the API 526 sizes.\n\n Examples\n --------\n From [1]_, checked with many points on Table 8.\n\n >>> API520_round_size(1E-4)\n 0.00012645136\n >>> API526_letters[API526_A.index(API520_round_size(1E-4))]\n 'E'\n\n References\n ----------\n .. [1] API Standard 526.\n \"\"\"\n for area in API526_A:\n if area >= A:\n return area\n raise ValueError(\"Required relief area is larger than can be provided with one valve\")\n\ndef API520_C(k: float) -> float:\n r\"\"\"Calculates coefficient C for use in API 520 critical flow relief valve\n sizing.\n\n .. math::\n C = 0.03948\\sqrt{k\\left(\\frac{2}{k+1}\\right)^\\frac{k+1}{k-1}}\n\n Parameters\n ----------\n k : float\n Isentropic coefficient or ideal gas heat capacity ratio [-]\n\n Returns\n -------\n C : float\n Coefficient `C` [-]\n\n Notes\n -----\n If C cannot be established, assume a coefficient of 0.0239,\n the highest value possible for C.\n\n Although not dimensional, C varies with the units used.\n\n If k is exactly equal to 1, the expression is undefined, and the formula\n must be simplified as follows from an application of L'Hopital's rule.\n\n .. math::\n C = 0.03948\\sqrt{\\frac{1}{e}}\n\n Examples\n --------\n From [1]_, checked with many points on Table 8.\n\n >>> API520_C(1.35)\n 0.02669419967057233\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n if k != 1:\n kp1 = k+1\n return 0.03948*sqrt(k*(2./kp1)**(kp1/(k-1.)))\n else:\n return 0.023945830445454768\n\ndef API520_F2(k: float, P1: float, P2: float) -> float:\n r\"\"\"Calculates coefficient F2 for subcritical flow for use in API 520\n subcritical flow relief valve sizing.\n\n .. math::\n F_2 = \\sqrt{\\left(\\frac{k}{k-1}\\right)r^\\frac{2}{k}\n \\left[\\frac{1-r^\\frac{k-1}{k}}{1-r}\\right]}\n\n .. math::\n r = \\frac{P_2}{P_1}\n\n Parameters\n ----------\n k : float\n Isentropic coefficient or ideal gas heat capacity ratio [-]\n P1 : float\n Upstream relieving pressure; the set pressure plus the allowable\n overpressure, plus atmospheric pressure, [Pa]\n P2 : float\n Built-up backpressure; the increase in pressure during flow at the\n outlet of a pressure-relief device after it opens, [Pa]\n\n Returns\n -------\n F2 : float\n Subcritical flow coefficient `F2` [-]\n\n Notes\n -----\n F2 is completely dimensionless.\n\n Examples\n --------\n From [1]_ example 2, matches.\n\n >>> API520_F2(1.8, 1E6, 7E5)\n 0.8600724121105563\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n r = P2/P1\n return sqrt(k/(k-1.0)*r**(2./k) * ((1-r**((k-1.)/k))/(1.-r)))\n\ndef API520_N(P1: float) -> float:\n r\"\"\"Calculates correction due to steam pressure for steam flow for use in\n API 520 relief valve sizing.\n\n For pressures below 10339 kPa, the correction factor is 1.\n\n .. math::\n K_N = \\frac{0.02764P_1-1000}{0.03324P_1-1061}\n\n Parameters\n ----------\n P1 : float\n Upstream relieving pressure; the set pressure plus the allowable\n overpressure, plus atmospheric pressure, [Pa]\n\n Returns\n -------\n KN : float\n Correction due to steam temperature [-]\n\n Notes\n -----\n Although not dimensional, KN varies with the units used.\n\n For temperatures above 922 K or pressures above 22057 kPa, KN is not defined.\n\n Internally, units of kPa are used to match the equation in the standard.\n\n Examples\n --------\n >>> API520_N(10500e3)\n 0.9969100255\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n P1 = P1*1e-3 # Pa to kPa\n if P1 <= 10339.0:\n KN = 1.0\n else:\n KN = (0.02764*P1 - 1000.)/(0.03324*P1 - 1061.0)\n return KN\n\ndef API520_B(Pset: float, Pback: float, overpressure: float=0.1) -> float:\n r\"\"\"Calculates capacity correction due to backpressure on balanced\n spring-loaded PRVs in vapor service. For pilot operated valves,\n this is always 1. Applicable up to 50% of the percent gauge backpressure,\n For use in API 520 relief valve sizing. 1D interpolation among a table with\n 53 backpressures is performed.\n\n Parameters\n ----------\n Pset : float\n Set pressure for relief [Pa]\n Pback : float\n Backpressure, [Pa]\n overpressure : float, optional\n The maximum fraction overpressure; one of 0.1, 0.16, or 0.21, [-]\n\n Returns\n -------\n Kb : float\n Correction due to vapor backpressure [-]\n\n Notes\n -----\n If the calculated gauge backpressure is less than 30%, 38%, or 50% for\n overpressures of 0.1, 0.16, or 0.21, a value of 1 is returned.\n\n Percent gauge backpressure must be under 50%.\n\n Examples\n --------\n Custom examples from figure 30:\n\n >>> API520_B(1E6, 5E5)\n 0.7929945420944432\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n gauge_backpressure = (Pback-atm)/(Pset-atm)*100.0 # in percent\n if overpressure not in (0.1, 0.16, 0.21):\n raise ValueError(\"Only overpressure of 10%, 16%, or 21% are permitted\")\n if (overpressure == 0.1 and gauge_backpressure < 30.0) or (\n overpressure == 0.16 and gauge_backpressure < 38.0) or (\n overpressure == 0.21 and gauge_backpressure <= 50.0):\n return 1.0\n elif gauge_backpressure > 50.0:\n raise ValueError(\"Gauge pressure must be < 50%\")\n if overpressure == 0.16:\n Kb = interp(gauge_backpressure, Kb_16_over_x, Kb_16_over_y)\n elif overpressure == 0.1:\n Kb = interp(gauge_backpressure, Kb_10_over_x, Kb_10_over_y)\n return Kb\n\ndef API520_A_g(m: float, T: float, Z: float, MW: float, k: float, P1: float, P2: float=101325, Kd: float=0.975, Kb: float=1, Kc: float=1) -> float:\n r\"\"\"Calculates required relief valve area for an API 520 valve passing\n a gas or a vapor, at either critical or sub-critical flow.\n\n For critical flow:\n\n .. math::\n A = \\frac{m}{CK_dP_1K_bK_c}\\sqrt{\\frac{TZ}{M}}\n\n For sub-critical flow:\n\n .. math::\n A = \\frac{17.9m}{F_2K_dK_c}\\sqrt{\\frac{TZ}{MP_1(P_1-P_2)}}\n\n Parameters\n ----------\n m : float\n Mass flow rate of vapor through the valve, [kg/s]\n T : float\n Temperature of vapor entering the valve, [K]\n Z : float\n Compressibility factor of the vapor, [-]\n MW : float\n Molecular weight of the vapor, [g/mol]\n k : float\n Isentropic coefficient or ideal gas heat capacity ratio [-]\n P1 : float\n Upstream relieving pressure; the set pressure plus the allowable\n overpressure, plus atmospheric pressure, [Pa]\n P2 : float, optional\n Built-up backpressure; the increase in pressure during flow at the\n outlet of a pressure-relief device after it opens, [Pa]\n Kd : float, optional\n The effective coefficient of discharge, from the manufacturer or for\n preliminary sizing, using 0.975 normally or 0.62 when used with a\n rupture disc as described in [1]_, []\n Kb : float, optional\n Correction due to vapor backpressure [-]\n Kc : float, optional\n Combination correction factor for installation with a rupture disk\n upstream of the PRV; 1.0 when a rupture disk is not installed, and\n 0.9 if a rupture disk is present and the combination has not been\n certified, []\n\n Returns\n -------\n A : float\n Minimum area for relief valve according to [1]_, [m^2]\n\n Notes\n -----\n Units are interlally kg/hr, kPa, and mm^2 to match [1]_.\n\n Examples\n --------\n Example 1 from [1]_ for critical flow, matches:\n\n >>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, Kb=1, Kc=1)\n 0.0036990460646834414\n\n Example 2 from [1]_ for sub-critical flow, matches:\n\n >>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, P2=532E3, Kd=0.975, Kb=1, Kc=1)\n 0.004248358775943481\n\n The mass flux in (kg/(s*m^2)) can be found by dividing the specified mass\n flow by the calculated area:\n\n >>> (24270/3600.)/API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, Kb=1, Kc=1)\n 1822.541960488834\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n P1, P2 = P1*1e-3, P2*1e-3 # Pa to Kpa in the standard\n m = m*3600. # kg/s to kg/hr\n if is_critical_flow(P1, P2, k):\n C = API520_C(k)\n A = m/(C*Kd*Kb*Kc*P1)*sqrt(T*Z/MW)\n else:\n F2 = API520_F2(k, P1, P2)\n A = 17.9*m/(F2*Kd*Kc)*sqrt(T*Z/(MW*P1*(P1-P2)))\n return A*1e-6\n\ndef API520_W(Pset: float, Pback: float) -> float:\n r\"\"\"Calculates capacity correction due to backpressure on balanced\n spring-loaded PRVs in liquid service. For pilot operated valves,\n this is always 1. Applicable up to 50% of the percent gauge backpressure,\n For use in API 520 relief valve sizing. 1D interpolation among a table with\n 53 backpressures is performed.\n\n Parameters\n ----------\n Pset : float\n Set pressure for relief [Pa]\n Pback : float\n Backpressure, [Pa]\n\n Returns\n -------\n KW : float\n Correction due to liquid backpressure [-]\n\n Notes\n -----\n If the calculated gauge backpressure is less than 15%, a value of 1 is\n returned.\n\n Examples\n --------\n Custom example from figure 31 in [1]_:\n\n >>> API520_W(1E6, 3E5) # 22% overpressure\n 0.95114718480085\n\n Example 5 from [2]_, set pressure 250 psig and backpressure up to 50 psig:\n\n >>> API520_W(Pset=1825014, Pback=446062)\n 0.97242133397677\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection. 7E\n .. [2] API Standard 520, Part 1 - Sizing and Selection. 10E\n \"\"\"\n gauge_backpressure = (Pback-atm)/(Pset-atm)*100.0 # in percent\n if gauge_backpressure < 15.0:\n return 1.0\n return interp(gauge_backpressure, Kw_x, Kw_y)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 11658}, "tests/test_two_phase_voidage.py::242": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/two_phase_voidage.py"], "used_names": ["assert_close", "liquid_gas_voidage", "liquid_gas_voidage_methods", "pytest"], "enclosing_function": "test_liquid_gas_voidage", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/two_phase_voidage.py\ndef liquid_gas_voidage_methods(x: float, rhol: float, rhog: float, D: float | None=None, m: float | None=None, mul: float | None=None, mug: float | None=None,\n sigma: float | None=None, P: float | None=None, Pc: float | None=None, angle: float=0.0, g: float=g,\n check_ranges: bool=False) -> list[str]:\n r\"\"\"This function returns a list of liquid-gas voidage correlation names\n which can perform the calculation with the provided inputs. The holdup is\n for two-phase liquid-gas flow inside channels. 29 calculation methods are\n available, with varying input requirements.\n\n Parameters\n ----------\n x : float\n Quality of fluid, [-]\n rhol : float\n Liquid density, [kg/m^3]\n rhog : float\n Gas density, [kg/m^3]\n D : float, optional\n Diameter of pipe, [m]\n m : float, optional\n Mass flow rate of fluid, [kg/s]\n mul : float, optional\n Viscosity of liquid, [Pa*s]\n mug : float, optional\n Viscosity of gas, [Pa*s]\n sigma : float, optional\n Surface tension, [N/m]\n P : float, optional\n Pressure of fluid, [Pa]\n Pc : float, optional\n Critical pressure of fluid, [Pa]\n angle : float, optional\n Angle of the channel with respect to the horizontal (vertical = 90),\n [degrees]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n check_ranges : bool, optional\n Added for future use only\n\n Returns\n -------\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to calculate two-phase liquid-gas\n voidage with the given inputs.\n\n Examples\n --------\n >>> len(liquid_gas_voidage_methods(m=0.6, x=0.1, rhol=915., rhog=2.67, mul=180E-6, mug=14E-6, sigma=0.0487, D=0.05))\n 27\n \"\"\"\n vals = {\"x\": x, \"rhol\": rhol, \"rhog\": rhog, \"D\": D, \"m\": m, \"mul\": mul,\n \"mug\": mug, \"sigma\": sigma, \"P\": P, \"Pc\": Pc, \"angle\": angle,\n \"g\": g, \"check_ranges\": check_ranges}\n usable_methods = []\n for method, value in two_phase_voidage_correlations.items():\n f, args = value\n if all(vals[i] is not None for i in args):\n usable_methods.append(method)\n return usable_methods\n\ndef liquid_gas_voidage(x: float, rhol: float, rhog: float, D: float | None=None, m: float | None=None, mul: float | None=None, mug: float | None=None,\n sigma: float | None=None, P: float | None=None, Pc: float | None=None, angle: int=0, g: float=g, Method: str | None=None) -> float:\n r\"\"\"This function handles calculation of two-phase liquid-gas voidage\n for flow inside channels. 29 calculation methods are available, with\n varying input requirements. A correlation will be automatically selected if\n none is specified.\n\n This function is used to calculate the (liquid) holdup as well, as:\n\n .. math::\n \\text{holdup} = 1 - \\text{voidage}\n\n If no correlation is selected, the following rules are used, with the\n earlier options attempted first:\n\n * TODO: defaults\n\n Parameters\n ----------\n x : float\n Quality of fluid, [-]\n rhol : float\n Liquid density, [kg/m^3]\n rhog : float\n Gas density, [kg/m^3]\n D : float, optional\n Diameter of pipe, [m]\n m : float, optional\n Mass flow rate of fluid, [kg/s]\n mul : float, optional\n Viscosity of liquid, [Pa*s]\n mug : float, optional\n Viscosity of gas, [Pa*s]\n sigma : float, optional\n Surface tension, [N/m]\n P : float, optional\n Pressure of fluid, [Pa]\n Pc : float, optional\n Critical pressure of fluid, [Pa]\n angle : float, optional\n Angle of the channel with respect to the horizontal (vertical = 90),\n [degrees]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n alpha : float\n Void fraction (area of gas / total area of channel), [-]\n\n Other Parameters\n ----------------\n Method : string, optional\n A string of the function name to use, as in the dictionary\n two_phase_voidage_correlations.\n\n Notes\n -----\n\n Examples\n --------\n >>> liquid_gas_voidage(m=0.6, x=0.1, rhol=915., rhog=2.67, mul=180E-6, mug=14E-6,\n ... sigma=0.0487, D=0.05)\n 0.9744097632663492\n \"\"\"\n if Method is None:\n Method2 = \"homogeneous\"\n else:\n Method2 = Method\n\n # Type narrowing: validate required parameters based on selected method\n # Initialize to dummy values for numba (will be overwritten before use)\n D2 = 0.0\n m2 = 0.0\n mul2 = 0.0\n mug2 = 0.0\n sigma2 = 0.0\n P2 = 0.0\n Pc2 = 0.0\n\n if Method2 in liquid_gas_voidage_methods_needing_D:\n if D is None:\n raise TypeError(f\"{Method2} requires D\")\n D2 = D\n if Method2 in liquid_gas_voidage_methods_needing_m:\n if m is None:\n raise TypeError(f\"{Method2} requires m\")\n m2 = m\n if Method2 in liquid_gas_voidage_methods_needing_mul:\n if mul is None:\n raise TypeError(f\"{Method2} requires mul\")\n mul2 = mul\n if Method2 in liquid_gas_voidage_methods_needing_mug:\n if mug is None:\n raise TypeError(f\"{Method2} requires mug\")\n mug2 = mug\n if Method2 in liquid_gas_voidage_methods_needing_sigma:\n if sigma is None:\n raise TypeError(f\"{Method2} requires sigma\")\n sigma2 = sigma\n if Method2 in liquid_gas_voidage_methods_needing_P:\n if P is None:\n raise TypeError(f\"{Method2} requires P\")\n P2 = P\n if Method2 in liquid_gas_voidage_methods_needing_Pc:\n if Pc is None:\n raise TypeError(f\"{Method2} requires Pc\")\n Pc2 = Pc\n\n if Method2 == \"Thom\":\n return Thom(x=x, rhol=rhol, rhog=rhog, mul=mul2, mug=mug2)\n elif Method2 == \"Zivi\":\n return Zivi(x=x, rhol=rhol, rhog=rhog)\n elif Method2 == \"Smith\":\n return Smith(x=x, rhol=rhol, rhog=rhog)\n elif Method2 == \"Fauske\":\n return Fauske(x=x, rhol=rhol, rhog=rhog)\n elif Method2 == \"Chisholm_voidage\":\n return Chisholm_voidage(x=x, rhol=rhol, rhog=rhog)\n elif Method2 == \"Turner Wallis\":\n return Turner_Wallis(x=x, rhol=rhol, rhog=rhog, mul=mul2, mug=mug2)\n elif Method2 == \"homogeneous\":\n return homogeneous(x=x, rhol=rhol, rhog=rhog)\n elif Method2 == \"Chisholm Armand\":\n return Chisholm_Armand(x=x, rhol=rhol, rhog=rhog)\n elif Method2 == \"Armand\":\n return Armand(x=x, rhol=rhol, rhog=rhog)\n elif Method2 == \"Nishino Yamazaki\":\n return Nishino_Yamazaki(x=x, rhol=rhol, rhog=rhog)\n elif Method2 == \"Guzhov\":\n return Guzhov(x=x, rhol=rhol, rhog=rhog, m=m2, D=D2)\n elif Method2 == \"Kawahara\":\n return Kawahara(x=x, rhol=rhol, rhog=rhog, D=D2)\n elif Method2 == \"Baroczy\":\n return Baroczy(x=x, rhol=rhol, rhog=rhog, mul=mul2, mug=mug2)\n elif Method2 == \"Tandon Varma Gupta\":\n return Tandon_Varma_Gupta(x=x, rhol=rhol, rhog=rhog, mul=mul2, mug=mug2, m=m2, D=D2)\n elif Method2 == \"Harms\":\n return Harms(x=x, rhol=rhol, rhog=rhog, mul=mul2, mug=mug2, m=m2, D=D2)\n elif Method2 == \"Domanski Didion\":\n return Domanski_Didion(x=x, rhol=rhol, rhog=rhog, mul=mul2, mug=mug2)\n elif Method2 == \"Graham\":\n return Graham(x=x, rhol=rhol, rhog=rhog, mul=mul2, mug=mug2, m=m2, D=D2, g=g)\n elif Method2 == \"Yashar\":\n return Yashar(x=x, rhol=rhol, rhog=rhog, mul=mul2, mug=mug2, m=m2, D=D2, g=g)\n elif Method2 == \"Huq_Loth\":\n return Huq_Loth(x=x, rhol=rhol, rhog=rhog)\n elif Method2 == \"Kopte_Newell_Chato\":\n return Kopte_Newell_Chato(x=x, rhol=rhol, rhog=rhog, m=m2, D=D2, g=g)\n elif Method2 == \"Steiner\":\n return Steiner(x=x, rhol=rhol, rhog=rhog, sigma=sigma2, m=m2, D=D2, g=g)\n elif Method2 == \"Rouhani 1\":\n return Rouhani_1(x=x, rhol=rhol, rhog=rhog, sigma=sigma2, m=m2, D=D2, g=g)\n elif Method2 == \"Rouhani 2\":\n return Rouhani_2(x=x, rhol=rhol, rhog=rhog, sigma=sigma2, m=m2, D=D2, g=g)\n elif Method2 == \"Nicklin Wilkes Davidson\":\n return Nicklin_Wilkes_Davidson(x=x, rhol=rhol, rhog=rhog, m=m2, D=D2, g=g)\n elif Method2 == \"Gregory_Scott\":\n return Gregory_Scott(x=x, rhol=rhol, rhog=rhog)\n elif Method2 == \"Dix\":\n return Dix(x=x, rhol=rhol, rhog=rhog, sigma=sigma2, m=m2, D=D2, g=g)\n elif Method2 == \"Sun Duffey Peng\":\n return Sun_Duffey_Peng(x=x, rhol=rhol, rhog=rhog, sigma=sigma2, m=m2, D=D2, P=P2, Pc=Pc2, g=g)\n elif Method2 == \"Xu Fang voidage\":\n return Xu_Fang_voidage(x=x, rhol=rhol, rhog=rhog, m=m2, D=D2, g=g)\n elif Method2 == \"Woldesemayat Ghajar\":\n return Woldesemayat_Ghajar(x=x, rhol=rhol, rhog=rhog, sigma=sigma2, m=m2, D=D2, P=P2, angle=angle, g=g)\n else:\n raise ValueError(_unknown_two_phase_voidage_corr)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 9571}, "tests/test_two_phase_voidage.py::124": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/two_phase_voidage.py"], "used_names": ["assert_close", "homogeneous"], "enclosing_function": "test_homogeneous", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/two_phase_voidage.py\ndef homogeneous(x: float, rhol: float, rhog: float) -> float:\n r\"\"\"Calculates void fraction in two-phase flow according to the homogeneous\n flow model, reviewed in [1]_, [2]_, and [3]_.\n\n .. math::\n \\alpha = \\frac{1}{1 + \\left(\\frac{1-x}{x}\\right)\\frac{\\rho_g}{\\rho_l}}\n\n Parameters\n ----------\n x : float\n Quality at the specific tube interval []\n rhol : float\n Density of the liquid [kg/m^3]\n rhog : float\n Density of the gas [kg/m^3]\n\n Returns\n -------\n alpha : float\n Void fraction (area of gas / total area of channel), [-]\n\n Notes\n -----\n\n Examples\n --------\n >>> homogeneous(.4, 800, 2.5)\n 0.995334370139969\n\n References\n ----------\n .. [1] Xu, Yu, and Xiande Fang. \"Correlations of Void Fraction for Two-\n Phase Refrigerant Flow in Pipes.\" Applied Thermal Engineering 64, no.\n 1-2 (March 2014): 242-51. doi:10.1016/j.applthermaleng.2013.12.032.\n .. [2] Dalkilic, A. S., S. Laohalertdecha, and S. Wongwises. \"Effect of\n Void Fraction Models on the Two-Phase Friction Factor of R134a during\n Condensation in Vertical Downward Flow in a Smooth Tube.\" International\n Communications in Heat and Mass Transfer 35, no. 8 (October 2008):\n 921-27. doi:10.1016/j.icheatmasstransfer.2008.04.001.\n .. [3] Woldesemayat, Melkamu A., and Afshin J. Ghajar. \"Comparison of Void\n Fraction Correlations for Different Flow Patterns in Horizontal and\n Upward Inclined Pipes.\" International Journal of Multiphase Flow 33,\n no. 4 (April 2007): 347-370. doi:10.1016/j.ijmultiphaseflow.2006.09.004.\n \"\"\"\n if x == 1.0:\n return 1.0\n elif x == 0.0:\n return 0.0\n return 1.0/(1.0 + (1.0 - x)/x*(rhog/rhol))", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 2413}, "tests/test_two_phase_voidage.py::125": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/two_phase_voidage.py"], "used_names": ["assert_close", "homogeneous"], "enclosing_function": "test_homogeneous", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/two_phase_voidage.py\ndef homogeneous(x: float, rhol: float, rhog: float) -> float:\n r\"\"\"Calculates void fraction in two-phase flow according to the homogeneous\n flow model, reviewed in [1]_, [2]_, and [3]_.\n\n .. math::\n \\alpha = \\frac{1}{1 + \\left(\\frac{1-x}{x}\\right)\\frac{\\rho_g}{\\rho_l}}\n\n Parameters\n ----------\n x : float\n Quality at the specific tube interval []\n rhol : float\n Density of the liquid [kg/m^3]\n rhog : float\n Density of the gas [kg/m^3]\n\n Returns\n -------\n alpha : float\n Void fraction (area of gas / total area of channel), [-]\n\n Notes\n -----\n\n Examples\n --------\n >>> homogeneous(.4, 800, 2.5)\n 0.995334370139969\n\n References\n ----------\n .. [1] Xu, Yu, and Xiande Fang. \"Correlations of Void Fraction for Two-\n Phase Refrigerant Flow in Pipes.\" Applied Thermal Engineering 64, no.\n 1-2 (March 2014): 242-51. doi:10.1016/j.applthermaleng.2013.12.032.\n .. [2] Dalkilic, A. S., S. Laohalertdecha, and S. Wongwises. \"Effect of\n Void Fraction Models on the Two-Phase Friction Factor of R134a during\n Condensation in Vertical Downward Flow in a Smooth Tube.\" International\n Communications in Heat and Mass Transfer 35, no. 8 (October 2008):\n 921-27. doi:10.1016/j.icheatmasstransfer.2008.04.001.\n .. [3] Woldesemayat, Melkamu A., and Afshin J. Ghajar. \"Comparison of Void\n Fraction Correlations for Different Flow Patterns in Horizontal and\n Upward Inclined Pipes.\" International Journal of Multiphase Flow 33,\n no. 4 (April 2007): 347-370. doi:10.1016/j.ijmultiphaseflow.2006.09.004.\n \"\"\"\n if x == 1.0:\n return 1.0\n elif x == 0.0:\n return 0.0\n return 1.0/(1.0 + (1.0 - x)/x*(rhog/rhol))", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 2413}, "tests/test_units.py::393": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/units.py"], "used_names": ["TANK", "u"], "enclosing_function": "test_Tank_units_full", "extracted_code": "# Source: fluids/units.py\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 3436}, "tests/spa/test_spa.py::157": {"resolved_imports": ["fluids/optional/__init__.py", "fluids/optional/spa.py"], "used_names": ["assert_almost_equal", "spa"], "enclosing_function": "test_julian_day_dt", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/spa/test_spa.py::162": {"resolved_imports": ["fluids/optional/__init__.py", "fluids/optional/spa.py"], "used_names": ["assert_almost_equal", "spa"], "enclosing_function": "test_julian_ephemeris_day", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/spa/test_spa.py::227": {"resolved_imports": ["fluids/optional/__init__.py", "fluids/optional/spa.py"], "used_names": ["assert_almost_equal", "spa"], "enclosing_function": "test_mean_sidereal_time", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_design_climate.py::52": {"resolved_imports": ["fluids/design_climate.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "heating_degree_days"], "enclosing_function": "test_heating_degree_days", "extracted_code": "# Source: fluids/design_climate.py\ndef heating_degree_days(T, T_base=291.4833333333333, truncate=True):\n r\"\"\"Calculates the heating degree days for a period of time.\n\n .. math::\n \\text{heating degree days} = max(T - T_{base}, 0)\n\n Parameters\n ----------\n T : float\n Measured temperature; sometimes an average over a length of time is used,\n other times the average of the lowest and highest temperature in a\n period are used, [K]\n T_base : float, optional\n Reference temperature for the degree day calculation, defaults\n to 65 °F (18.33 °C, 291.483 K), the value most used in the US, [K]\n truncate : bool\n If truncate is True, no negative values will be returned; if negative,\n the value is truncated to 0, [-]\n\n Returns\n -------\n heating_degree_days : float\n Degree above the base temperature multiplied by the length of time of\n the measurement, normally days [day*K]\n\n Notes\n -----\n Some common base temperatures are 18 °C (Canada), 15.5 °C (EU),\n 17 °C (Denmark, Finland), 12 °C Switzerland. The base temperature\n should always be presented with the results.\n\n The time unit does not have to be days; it can be any time unit, and the\n calculation behaves the same.\n\n Examples\n --------\n >>> heating_degree_days(303.8)\n 12.31666666666672\n\n >>> heating_degree_days(273)\n 0.0\n\n >>> heating_degree_days(322, T_base=300)\n 22\n\n References\n ----------\n .. [1] \"Heating Degree Day.\" Wikipedia, January 24, 2018.\n https://en.wikipedia.org/w/index.php?title=Heating_degree_day&oldid=822187764.\n \"\"\"\n dd = T - T_base\n if truncate and dd < 0.0:\n dd = 0.0\n return dd\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 2346}, "tests/test_design_climate.py::60": {"resolved_imports": ["fluids/design_climate.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "cooling_degree_days"], "enclosing_function": "test_cooling_degree_days", "extracted_code": "# Source: fluids/design_climate.py\ndef cooling_degree_days(T, T_base=283.15, truncate=True):\n r\"\"\"Calculates the cooling degree days for a period of time.\n\n .. math::\n \\text{cooling degree days} = max(T_{base} - T, 0)\n\n Parameters\n ----------\n T : float\n Measured temperature; sometimes an average over a length of time is used,\n other times the average of the lowest and highest temperature in a\n period are used, [K]\n T_base : float, optional\n Reference temperature for the degree day calculation, defaults\n to 10 °C, 283.15 K, a common value, [K]\n truncate : bool\n If truncate is True, no negative values will be returned; if negative,\n the value is truncated to 0, [-]\n\n Returns\n -------\n cooling_degree_days : float\n Degree below the base temperature multiplied by the length of time of\n the measurement, normally days [day*K]\n\n Notes\n -----\n The base temperature should always be presented with the results.\n\n The time unit does not have to be days; it can be time unit, and the\n calculation behaves the same.\n\n Examples\n --------\n >>> cooling_degree_days(250)\n 33.14999999999998\n\n >>> cooling_degree_days(300)\n 0.0\n\n >>> cooling_degree_days(250, T_base=300)\n 50\n\n References\n ----------\n .. [1] \"Heating Degree Day.\" Wikipedia, January 24, 2018.\n https://en.wikipedia.org/w/index.php?title=Heating_degree_day&oldid=822187764.\n \"\"\"\n dd = T_base - T\n if truncate and dd < 0.0:\n dd = 0.0\n return dd\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 2185}, "tests/test_design_climate.py::88": {"resolved_imports": ["fluids/design_climate.py", "fluids/numerics/__init__.py"], "used_names": ["get_latlongs", "get_stations"], "enclosing_function": "test_data", "extracted_code": "# Source: fluids/design_climate.py\ndef get_stations():\n \"\"\"Get the list of weather stations.\"\"\"\n if _stations is None:\n _load_station_data()\n return _stations\n\ndef get_latlongs():\n \"\"\"Get the array of station coordinates.\"\"\"\n if _latlongs is None:\n _load_station_data()\n return _latlongs", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 319}, "tests/test_fittings_fits.py::297": {"resolved_imports": ["fluids/__init__.py", "fluids/core.py", "fluids/optional/pychebfun.py", "fluids/fittings.py"], "used_names": ["UnivariateSpline", "assert_allclose", "bend_rounded_Crane_coeffs", "bend_rounded_Crane_fds", "bend_rounded_Crane_ratios", "chebfun", "chebfun_to_poly"], "enclosing_function": "test_bend_rounded_Crane_coefficients", "extracted_code": "# Source: fluids/optional/pychebfun.py\ndef chebfun_to_poly(coeffs_or_fun, domain=None, text=False):\n if isinstance(coeffs_or_fun, Chebfun):\n coeffs = coeffs_or_fun.coefficients()\n domain = coeffs_or_fun._domain\n elif hasattr(coeffs_or_fun, \"__class__\") and coeffs_or_fun.__class__.__name__ == \"ChebyshevExpansion\":\n coeffs = coeffs_or_fun.coef()\n domain = coeffs_or_fun.xmin(), coeffs_or_fun.xmax()\n else:\n coeffs = coeffs_or_fun\n\n low, high = domain\n # Reverse the coefficients, and use cheb2poly to make it in the polynomial domain\n poly_coeffs = cheb2poly(coeffs)[::-1].tolist()\n if not text:\n return poly_coeffs\n s = f\"coeffs = {poly_coeffs}\\n\"\n delta = high - low\n delta_sum = high + low\n # Generate the expression\n s += f\"horner(coeffs, {2.0/delta:.18g}*(x - {0.5*delta_sum:.18g}))\"\n # return the string\n return s\n\ndef chebfun(f=None, domain=[-1,1], N=None, chebcoeff=None,):\n \"\"\"Create a Chebyshev polynomial approximation of the function $f$ on the\n interval :math:`[-1, 1]`.\n\n :param callable f: Python, Numpy, or Sage function\n :param int N: (default = None) specify number of interpolating points\n :param np.array chebcoeff: (default = np.array(0)) specify the coefficients\n \"\"\"\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n\n\n # Chebyshev coefficients\n if chebcoeff is not None:\n return Chebfun.from_coeff(chebcoeff, domain)\n\n # another instance\n if isinstance(f, Polyfun):\n return Chebfun.from_fun(f)\n\n # callable\n if hasattr(f, \"__call__\"):\n return Chebfun.from_function(f, domain, N)\n\n # from here on, assume that f is None, or iterable\n if np.isscalar(f):\n f = [f]\n\n try:\n iter(f) # interpolation values provided\n except TypeError:\n pass\n else:\n return Chebfun(f, domain)\n\n raise TypeError(f\"Impossible to initialise the object from an object of type {type(f)}\")\n\n\n# Source: fluids/fittings.py\nbend_rounded_Crane_ratios = [1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 10.0, 12.0,\n 14.0, 16.0, 20.0]\n\nbend_rounded_Crane_fds = [20.0, 14.0, 12.0, 12.0, 14.0, 17.0, 24.0, 30.0, 34.0,\n 38.0, 42.0, 50.0]\n\nbend_rounded_Crane_coeffs = [111.75011378177442, -331.89911345404107, -27.841951521656483,\n 1066.8916917931147, -857.8702190626232, -1151.4621655498092,\n 1775.2416673594603, 216.37911821941805, -1458.1661519377653,\n 447.169127650163, 515.361158769082, -322.58377486107577,\n -38.38349416327068, 71.12796602489138, -16.198233745350535,\n 19.377150177339015, 31.107110520349494]", "n_imports_parsed": 11, "n_files_resolved": 4, "n_chars_extracted": 2894}, "tests/test_numerics.py::2200": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["assert_close1d", "broyden2", "exp", "fixed_point", "fixed_point_aitken", "fixed_point_anderson", "fixed_point_gdem", "fixed_point_to_residual", "residual_to_fixed_point"], "enclosing_function": "test_fixed_point_process", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\ndef broyden2(xs, fun, jac, xtol=1e-7, maxiter=100, jac_has_fun=False,\n skip_J=False, args=()):\n iter = 0\n if skip_J:\n fcur = fun(xs, *args)\n N = len(fcur)\n J = eye(N)\n elif jac_has_fun:\n fcur, J = jac(xs, *args)\n J = inv(J)\n else:\n fcur = fun(xs, *args)\n J = inv(jac(xs, *args))\n\n N = len(fcur)\n eqns = range(N)\n\n err = 0.0\n for fi in fcur:\n err += abs(fi)\n\n while err > xtol and iter < maxiter:\n s = matrix_vector_dot(J, fcur)\n\n xs = [xs[i] - s[i] for i in eqns]\n\n fnew = fun(xs, *args)\n z = [fnew[i] - fcur[i] for i in eqns]\n\n u = matrix_vector_dot(J, z)\n\n d = [-i for i in s]\n\n\n dmu = [d[i]-u[i] for i in eqns]\n dmu_d = dot_product(dmu, d)\n den_inv = 1.0/dot_product(d, u)\n factor = den_inv*dmu_d\n J_delta = [[factor*j for j in row] for row in J]\n for i in eqns:\n for j in eqns:\n J[i][j] += J_delta[i][j]\n\n fcur = fnew\n iter += 1\n err = 0.0\n for fi in fcur:\n err += abs(fi)\n\n return xs, iter\n\ndef fixed_point(f, x0, xtol=None, ytol=None, maxiter=100, damping=1.0,\n args=(), require_progress=False, check_numbers=False):\n fcur = f(x0, *args)\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if xtol is None and (ytol is not None and err0 < ytol):\n return x0, 0.0\n x = [xi - fi for xi, fi in zip(x0, fcur)]\n iteration = 1\n while iteration < maxiter:\n fcur = f(x, *args)\n if check_numbers:\n for v in fcur:\n if isinf(v) or isnan(v):\n raise ValueError(\"Cannot continue - math error in function value\")\n x = [xi - fi*damping for xi, fi in zip(x, fcur)]\n err1 = 0.0\n for v in fcur:\n err1 += abs(v)\n iteration += 1\n if xtol is not None:\n if (norm2(fcur) < xtol) and (ytol is None or err1 < ytol):\n break\n elif ytol is not None:\n if err1 < ytol:\n break\n if err1 >= err0 and require_progress:\n raise ValueError(\"Fixed point is not making progress, cannot proceed\")\n err0 = err1\n\n\n\n if xtol is not None and norm2(fcur) > xtol:\n raise UnconvergedError(\"Failed to converge\")\n if ytol is not None:\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if err0 > ytol:\n raise UnconvergedError(\"Failed to converge\")\n return x, iteration\n\ndef fixed_point_aitken(f, x0, xtol=None, ytol=None, maxiter=100, damping=1.0,\n args=(), require_progress=False, check_numbers=False, acc_frequency=4,\n acc_damping=1.0, acc_max_change_ratio=1.0):\n all_guesses = [x0]\n fcur = f(x0, *args)\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if xtol is None and (ytol is not None and err0 < ytol):\n return x0, 0.0\n\n x = [xi - fi for xi, fi in zip(x0, fcur)]\n iteration = 1\n while iteration < maxiter:\n all_guesses.append(x)\n fcur = f(x, *args)\n if check_numbers:\n for v in fcur:\n if isinf(v) or isnan(v):\n raise ValueError(\"Cannot continue - math error in function value\")\n if (iteration % acc_frequency) == 0:\n x1, x2 = all_guesses[-2], all_guesses[-3]\n dx = aitken_delta_squared_accelerate(x, x1, x2, acc_max_change_ratio)\n x = [xi + dxi*acc_damping for xi, dxi in zip(x, dx)]\n else:\n x = [xi - fi*damping for xi, fi in zip(x, fcur)]\n err1 = 0.0\n for v in fcur:\n err1 += abs(v)\n iteration += 1\n if xtol is not None:\n if (norm2(fcur) < xtol) and (ytol is None or err1 < ytol):\n break\n elif ytol is not None:\n if err1 < ytol:\n break\n if err1 >= err0 and require_progress:\n raise ValueError(\"Fixed point is not making progress, cannot proceed\")\n err0 = err1\n\n if xtol is not None and norm2(fcur) > xtol:\n raise UnconvergedError(\"Failed to converge\")\n if ytol is not None:\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if err0 > ytol:\n raise UnconvergedError(\"Failed to converge\")\n return x, iteration\n\ndef fixed_point_gdem(f, x0, xtol=None, ytol=None, maxiter=100, damping=1.0,\n args=(), require_progress=False, check_numbers=False, acc_frequency=5,\n acc_damping=1.0, acc_max_change_ratio=1.0):\n all_guesses = [x0]\n fcur = f(x0, *args)\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if xtol is None and (ytol is not None and err0 < ytol):\n return x0, 0.0\n\n x = [xi - fi for xi, fi in zip(x0, fcur)]\n iteration = 1\n while iteration < maxiter:\n all_guesses.append(x)\n fcur = f(x, *args)\n if check_numbers:\n for v in fcur:\n if isinf(v) or isnan(v):\n raise ValueError(\"Cannot continue - math error in function value\")\n if (iteration % acc_frequency) == 0:\n x1, x2, x3 = all_guesses[-2], all_guesses[-3], all_guesses[-4]\n dx = gdem(x, x1, x2, x3, acc_max_change_ratio)\n # print(np.array([xi - fi*acc_damping for xi, fi in zip(x, fcur)])/[xi + dxi*acc_damping for xi, dxi in zip(x, dx)])\n x = [xi + dxi*acc_damping for xi, dxi in zip(x, dx)]\n else:\n x = [xi - fi*damping for xi, fi in zip(x, fcur)]\n err1 = 0.0\n for v in fcur:\n err1 += abs(v)\n iteration += 1\n if xtol is not None:\n if (norm2(fcur) < xtol) and (ytol is None or err1 < ytol):\n break\n elif ytol is not None:\n if err1 < ytol:\n break\n if err1 >= err0 and require_progress:\n raise ValueError(\"Fixed point is not making progress, cannot proceed\")\n err0 = err1\n\n if xtol is not None and norm2(fcur) > xtol:\n raise UnconvergedError(\"Failed to converge\")\n if ytol is not None:\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if err0 > ytol:\n raise UnconvergedError(\"Failed to converge\")\n return x, iteration\n\ndef fixed_point_anderson(\n f,\n x0,\n xtol: float = 1e-7,\n ytol: float | None = None,\n maxiter: int = 100,\n args: tuple = (),\n require_progress: bool = False,\n check_numbers: bool = False,\n window_size: int = 5,\n reg: float = 1e-8,\n mixing_param: float = 1.0,\n initial_iterations: int = 4,\n damping: float = 0.9,\n acc_damping: float = 1, # Damping for acceleration phase\n max_step_size: float = 10000, # Maximum allowed relative step size\n phase_in_steps: int = 3 # Number of steps to phase in acceleration\n):\n # Initialize state\n x_hist = []\n gx_hist = []\n residuals_hist = []\n x = x0\n # f = residual_to_fixed_point(f) # this commented out means the first lines should be uncommented; second lines commented\n fcur = f(x, *args)\n\n # Truncate window size based on the dimensionality of the problem\n # sometimes being 1 larger can be OK, for now not allowing it\n if len(fcur) < window_size:\n window_size = len(fcur)\n\n # Check initial convergence for ytol\n err0 = sum(abs(v) for v in fcur) if ytol is not None else 0.0\n if ytol is not None and xtol is None and err0 < ytol:\n return x0, 0\n\n # Main iteration loop\n for iteration in range(maxiter):\n x_new = f(x, *args)\n\n # Check for inf/nan\n if check_numbers and any(isnan(v) or isinf(v) for v in x_new):\n raise ValueError(\"Cannot continue - math error in function value\")\n\n if iteration < initial_iterations:\n # Damped fixed-point iteration\n x_acc = [\n (1 - damping) * x[i] + damping * x_new[i]\n for i in range(len(x))\n ]\n # Collect history for later use\n if iteration > 0:\n residual = [xi - xp for xi, xp in zip(x_new, x)]\n residuals_hist.append(residual)\n gx_hist.append(x_new)\n x_hist.append(x_acc)\n\n # Maintain window size\n if len(residuals_hist) > window_size:\n residuals_hist = residuals_hist[1:]\n gx_hist = gx_hist[1:]\n x_hist = x_hist[1:]\n else:\n # Apply Anderson acceleration with safeguards\n x_acc_raw, x_hist, gx_hist, residuals_hist = anderson_step(\n x_hist, gx_hist, residuals_hist, x_new,\n window_size, reg, mixing_param\n )\n\n # Calculate phase-in factor (gradually increase from 0 to 1)\n phase = min(1.0, (iteration - initial_iterations + 1) / phase_in_steps)\n\n # Compute damped acceleration step\n x_acc_damped = []\n for i in range(len(x)):\n # Regular damped fixed-point step\n fp_step = (1 - damping) * x[i] + damping * x_new[i]\n\n # Anderson acceleration step with its own damping\n acc_step = (1 - acc_damping) * x[i] + acc_damping * x_acc_raw[i]\n\n # Blend between fixed-point and acceleration based on phase\n x_acc_i = (1 - phase) * fp_step + phase * acc_step\n\n # Limit maximum step size relative to current position\n max_change = abs(x[i] * (1.0-max_step_size))\n change = x_acc_i - x[i]\n if abs(change) > max_change:\n # Clamp the change to the maximum allowed\n x_acc_i = x[i] + max_change * (1 if change > 0 else -1)\n\n x_acc_damped.append(x_acc_i)\n\n x_acc = x_acc_damped\n x_hist[-1] = x_acc\n\n # Calculate errors\n err1 = sum(abs(v) for v in fcur) if ytol is not None else 0.0\n\n # Check progress\n if require_progress and ytol is not None and err1 >= err0:\n raise ValueError(\"Fixed point is not making progress\")\n\n # Update error\n err0 = err1 if ytol is not None else 0.0\n\n # Check convergence\n if xtol is not None:\n x_err = max(abs((a - b) / abs(b)) for a, b in zip(x_acc, x))\n if x_err < xtol and (ytol is None or err1 < ytol):\n return x_acc, iteration\n elif ytol is not None and err1 < ytol:\n return x_acc, iteration\n\n x = x_acc\n\n # Check final convergence\n x_err = max(abs((a - b) / abs(b)) for a, b in zip(x_acc, x))\n if xtol is not None and x_err > xtol:\n raise ValueError(f\"Failed to converge after {maxiter} iterations. Error: {x_err}\")\n if ytol is not None and err1 > ytol:\n raise ValueError(f\"Failed to converge after {maxiter} iterations. Error: {err1}\")\n\n return x, iteration\n\ndef fixed_point_to_residual(f_fixed_point):\n \"\"\"\n Transforms a fixed-point iteration function to a residual-based function.\n\n Parameters\n ----------\n - f_fixed_point: Function that takes x and returns the difference x - thing\n\n Returns\n -------\n - A function that outputs residuals: thing - x\n \"\"\"\n def residual_function(x, *args):\n # Get the original fixed-point differences (x - thing)\n fp_diff = f_fixed_point(x, *args)\n # Calculate the residuals as (thing - x)\n return [-diff for diff in fp_diff]\n\n return residual_function\n\ndef residual_to_fixed_point(f_residual):\n \"\"\"\n Transforms a residual-based function to a fixed-point iteration function.\n\n Parameters\n ----------\n - f_residual: Function that takes x and returns residuals (thing - x)\n\n Returns\n -------\n - A function that outputs differences for fixed-point: x - thing\n \"\"\"\n def fixed_point_function(x, *args):\n # Get the residuals (thing - x)\n res = f_residual(x, *args)\n # Calculate the fixed-point differences as (x - thing)\n return [-r for r in res]\n\n return fixed_point_function", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 12387}, "tests/test_numerics.py::2234": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["assert_close1d", "broyden2", "exp", "fixed_point", "fixed_point_aitken", "fixed_point_anderson", "fixed_point_gdem", "fixed_point_to_residual", "residual_to_fixed_point"], "enclosing_function": "test_fixed_point_process", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\ndef broyden2(xs, fun, jac, xtol=1e-7, maxiter=100, jac_has_fun=False,\n skip_J=False, args=()):\n iter = 0\n if skip_J:\n fcur = fun(xs, *args)\n N = len(fcur)\n J = eye(N)\n elif jac_has_fun:\n fcur, J = jac(xs, *args)\n J = inv(J)\n else:\n fcur = fun(xs, *args)\n J = inv(jac(xs, *args))\n\n N = len(fcur)\n eqns = range(N)\n\n err = 0.0\n for fi in fcur:\n err += abs(fi)\n\n while err > xtol and iter < maxiter:\n s = matrix_vector_dot(J, fcur)\n\n xs = [xs[i] - s[i] for i in eqns]\n\n fnew = fun(xs, *args)\n z = [fnew[i] - fcur[i] for i in eqns]\n\n u = matrix_vector_dot(J, z)\n\n d = [-i for i in s]\n\n\n dmu = [d[i]-u[i] for i in eqns]\n dmu_d = dot_product(dmu, d)\n den_inv = 1.0/dot_product(d, u)\n factor = den_inv*dmu_d\n J_delta = [[factor*j for j in row] for row in J]\n for i in eqns:\n for j in eqns:\n J[i][j] += J_delta[i][j]\n\n fcur = fnew\n iter += 1\n err = 0.0\n for fi in fcur:\n err += abs(fi)\n\n return xs, iter\n\ndef fixed_point(f, x0, xtol=None, ytol=None, maxiter=100, damping=1.0,\n args=(), require_progress=False, check_numbers=False):\n fcur = f(x0, *args)\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if xtol is None and (ytol is not None and err0 < ytol):\n return x0, 0.0\n x = [xi - fi for xi, fi in zip(x0, fcur)]\n iteration = 1\n while iteration < maxiter:\n fcur = f(x, *args)\n if check_numbers:\n for v in fcur:\n if isinf(v) or isnan(v):\n raise ValueError(\"Cannot continue - math error in function value\")\n x = [xi - fi*damping for xi, fi in zip(x, fcur)]\n err1 = 0.0\n for v in fcur:\n err1 += abs(v)\n iteration += 1\n if xtol is not None:\n if (norm2(fcur) < xtol) and (ytol is None or err1 < ytol):\n break\n elif ytol is not None:\n if err1 < ytol:\n break\n if err1 >= err0 and require_progress:\n raise ValueError(\"Fixed point is not making progress, cannot proceed\")\n err0 = err1\n\n\n\n if xtol is not None and norm2(fcur) > xtol:\n raise UnconvergedError(\"Failed to converge\")\n if ytol is not None:\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if err0 > ytol:\n raise UnconvergedError(\"Failed to converge\")\n return x, iteration\n\ndef fixed_point_aitken(f, x0, xtol=None, ytol=None, maxiter=100, damping=1.0,\n args=(), require_progress=False, check_numbers=False, acc_frequency=4,\n acc_damping=1.0, acc_max_change_ratio=1.0):\n all_guesses = [x0]\n fcur = f(x0, *args)\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if xtol is None and (ytol is not None and err0 < ytol):\n return x0, 0.0\n\n x = [xi - fi for xi, fi in zip(x0, fcur)]\n iteration = 1\n while iteration < maxiter:\n all_guesses.append(x)\n fcur = f(x, *args)\n if check_numbers:\n for v in fcur:\n if isinf(v) or isnan(v):\n raise ValueError(\"Cannot continue - math error in function value\")\n if (iteration % acc_frequency) == 0:\n x1, x2 = all_guesses[-2], all_guesses[-3]\n dx = aitken_delta_squared_accelerate(x, x1, x2, acc_max_change_ratio)\n x = [xi + dxi*acc_damping for xi, dxi in zip(x, dx)]\n else:\n x = [xi - fi*damping for xi, fi in zip(x, fcur)]\n err1 = 0.0\n for v in fcur:\n err1 += abs(v)\n iteration += 1\n if xtol is not None:\n if (norm2(fcur) < xtol) and (ytol is None or err1 < ytol):\n break\n elif ytol is not None:\n if err1 < ytol:\n break\n if err1 >= err0 and require_progress:\n raise ValueError(\"Fixed point is not making progress, cannot proceed\")\n err0 = err1\n\n if xtol is not None and norm2(fcur) > xtol:\n raise UnconvergedError(\"Failed to converge\")\n if ytol is not None:\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if err0 > ytol:\n raise UnconvergedError(\"Failed to converge\")\n return x, iteration\n\ndef fixed_point_gdem(f, x0, xtol=None, ytol=None, maxiter=100, damping=1.0,\n args=(), require_progress=False, check_numbers=False, acc_frequency=5,\n acc_damping=1.0, acc_max_change_ratio=1.0):\n all_guesses = [x0]\n fcur = f(x0, *args)\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if xtol is None and (ytol is not None and err0 < ytol):\n return x0, 0.0\n\n x = [xi - fi for xi, fi in zip(x0, fcur)]\n iteration = 1\n while iteration < maxiter:\n all_guesses.append(x)\n fcur = f(x, *args)\n if check_numbers:\n for v in fcur:\n if isinf(v) or isnan(v):\n raise ValueError(\"Cannot continue - math error in function value\")\n if (iteration % acc_frequency) == 0:\n x1, x2, x3 = all_guesses[-2], all_guesses[-3], all_guesses[-4]\n dx = gdem(x, x1, x2, x3, acc_max_change_ratio)\n # print(np.array([xi - fi*acc_damping for xi, fi in zip(x, fcur)])/[xi + dxi*acc_damping for xi, dxi in zip(x, dx)])\n x = [xi + dxi*acc_damping for xi, dxi in zip(x, dx)]\n else:\n x = [xi - fi*damping for xi, fi in zip(x, fcur)]\n err1 = 0.0\n for v in fcur:\n err1 += abs(v)\n iteration += 1\n if xtol is not None:\n if (norm2(fcur) < xtol) and (ytol is None or err1 < ytol):\n break\n elif ytol is not None:\n if err1 < ytol:\n break\n if err1 >= err0 and require_progress:\n raise ValueError(\"Fixed point is not making progress, cannot proceed\")\n err0 = err1\n\n if xtol is not None and norm2(fcur) > xtol:\n raise UnconvergedError(\"Failed to converge\")\n if ytol is not None:\n err0 = 0.0\n for v in fcur:\n err0 += abs(v)\n if err0 > ytol:\n raise UnconvergedError(\"Failed to converge\")\n return x, iteration\n\ndef fixed_point_anderson(\n f,\n x0,\n xtol: float = 1e-7,\n ytol: float | None = None,\n maxiter: int = 100,\n args: tuple = (),\n require_progress: bool = False,\n check_numbers: bool = False,\n window_size: int = 5,\n reg: float = 1e-8,\n mixing_param: float = 1.0,\n initial_iterations: int = 4,\n damping: float = 0.9,\n acc_damping: float = 1, # Damping for acceleration phase\n max_step_size: float = 10000, # Maximum allowed relative step size\n phase_in_steps: int = 3 # Number of steps to phase in acceleration\n):\n # Initialize state\n x_hist = []\n gx_hist = []\n residuals_hist = []\n x = x0\n # f = residual_to_fixed_point(f) # this commented out means the first lines should be uncommented; second lines commented\n fcur = f(x, *args)\n\n # Truncate window size based on the dimensionality of the problem\n # sometimes being 1 larger can be OK, for now not allowing it\n if len(fcur) < window_size:\n window_size = len(fcur)\n\n # Check initial convergence for ytol\n err0 = sum(abs(v) for v in fcur) if ytol is not None else 0.0\n if ytol is not None and xtol is None and err0 < ytol:\n return x0, 0\n\n # Main iteration loop\n for iteration in range(maxiter):\n x_new = f(x, *args)\n\n # Check for inf/nan\n if check_numbers and any(isnan(v) or isinf(v) for v in x_new):\n raise ValueError(\"Cannot continue - math error in function value\")\n\n if iteration < initial_iterations:\n # Damped fixed-point iteration\n x_acc = [\n (1 - damping) * x[i] + damping * x_new[i]\n for i in range(len(x))\n ]\n # Collect history for later use\n if iteration > 0:\n residual = [xi - xp for xi, xp in zip(x_new, x)]\n residuals_hist.append(residual)\n gx_hist.append(x_new)\n x_hist.append(x_acc)\n\n # Maintain window size\n if len(residuals_hist) > window_size:\n residuals_hist = residuals_hist[1:]\n gx_hist = gx_hist[1:]\n x_hist = x_hist[1:]\n else:\n # Apply Anderson acceleration with safeguards\n x_acc_raw, x_hist, gx_hist, residuals_hist = anderson_step(\n x_hist, gx_hist, residuals_hist, x_new,\n window_size, reg, mixing_param\n )\n\n # Calculate phase-in factor (gradually increase from 0 to 1)\n phase = min(1.0, (iteration - initial_iterations + 1) / phase_in_steps)\n\n # Compute damped acceleration step\n x_acc_damped = []\n for i in range(len(x)):\n # Regular damped fixed-point step\n fp_step = (1 - damping) * x[i] + damping * x_new[i]\n\n # Anderson acceleration step with its own damping\n acc_step = (1 - acc_damping) * x[i] + acc_damping * x_acc_raw[i]\n\n # Blend between fixed-point and acceleration based on phase\n x_acc_i = (1 - phase) * fp_step + phase * acc_step\n\n # Limit maximum step size relative to current position\n max_change = abs(x[i] * (1.0-max_step_size))\n change = x_acc_i - x[i]\n if abs(change) > max_change:\n # Clamp the change to the maximum allowed\n x_acc_i = x[i] + max_change * (1 if change > 0 else -1)\n\n x_acc_damped.append(x_acc_i)\n\n x_acc = x_acc_damped\n x_hist[-1] = x_acc\n\n # Calculate errors\n err1 = sum(abs(v) for v in fcur) if ytol is not None else 0.0\n\n # Check progress\n if require_progress and ytol is not None and err1 >= err0:\n raise ValueError(\"Fixed point is not making progress\")\n\n # Update error\n err0 = err1 if ytol is not None else 0.0\n\n # Check convergence\n if xtol is not None:\n x_err = max(abs((a - b) / abs(b)) for a, b in zip(x_acc, x))\n if x_err < xtol and (ytol is None or err1 < ytol):\n return x_acc, iteration\n elif ytol is not None and err1 < ytol:\n return x_acc, iteration\n\n x = x_acc\n\n # Check final convergence\n x_err = max(abs((a - b) / abs(b)) for a, b in zip(x_acc, x))\n if xtol is not None and x_err > xtol:\n raise ValueError(f\"Failed to converge after {maxiter} iterations. Error: {x_err}\")\n if ytol is not None and err1 > ytol:\n raise ValueError(f\"Failed to converge after {maxiter} iterations. Error: {err1}\")\n\n return x, iteration\n\ndef fixed_point_to_residual(f_fixed_point):\n \"\"\"\n Transforms a fixed-point iteration function to a residual-based function.\n\n Parameters\n ----------\n - f_fixed_point: Function that takes x and returns the difference x - thing\n\n Returns\n -------\n - A function that outputs residuals: thing - x\n \"\"\"\n def residual_function(x, *args):\n # Get the original fixed-point differences (x - thing)\n fp_diff = f_fixed_point(x, *args)\n # Calculate the residuals as (thing - x)\n return [-diff for diff in fp_diff]\n\n return residual_function\n\ndef residual_to_fixed_point(f_residual):\n \"\"\"\n Transforms a residual-based function to a fixed-point iteration function.\n\n Parameters\n ----------\n - f_residual: Function that takes x and returns residuals (thing - x)\n\n Returns\n -------\n - A function that outputs differences for fixed-point: x - thing\n \"\"\"\n def fixed_point_function(x, *args):\n # Get the residuals (thing - x)\n res = f_residual(x, *args)\n # Calculate the fixed-point differences as (x - thing)\n return [-r for r in res]\n\n return fixed_point_function", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 12387}, "tests/test_particle_size_distribution.py::215": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/particle_size_distribution.py"], "used_names": ["assert_close", "cdf_lognormal", "stats"], "enclosing_function": "test_cdf_lognormal", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/particle_size_distribution.py\ndef cdf_lognormal(d: float, d_characteristic: float, s: float) -> float:\n r\"\"\"Calculates the cumulative distribution function of a lognormal particle\n distribution given a particle diameter `d`, characteristic particle\n diameter `d_characteristic`, and distribution standard deviation `s`.\n\n .. math::\n Q(d) = 0.5\\left(1 + \\text{err}\\left[\\left(\\frac{\\ln(d/d_c)}{s\\sqrt{2}}\n \\right)\\right]\\right)\n\n Parameters\n ----------\n d : float\n Specified particle diameter, [m]\n d_characteristic : float\n Characteristic particle diameter; often D[3, 3] is used for this\n purpose but not always, [m]\n s : float\n Distribution standard deviation, [-]\n\n Returns\n -------\n cdf : float\n Lognormal cumulative density function, [-]\n\n Notes\n -----\n The characteristic diameter can be in terns of number density (denoted\n :math:`q_0(d)`), length density (:math:`q_1(d)`), surface area density\n (:math:`q_2(d)`), or volume density (:math:`q_3(d)`). Volume density is\n most often used. Interconversions among the distributions is possible but\n tricky.\n\n The standard distribution (i.e. the one used in Scipy) can perform the same\n computation with `d_characteristic` as the value of `scale`.\n\n >>> import scipy.stats\n >>> float(scipy.stats.lognorm.cdf(x=1E-4, s=1.1, scale=1E-5))\n 0.9818369875798177\n\n Scipy's calculation is over 100 times slower however.\n\n Examples\n --------\n >>> cdf_lognormal(d=1E-4, d_characteristic=1E-5, s=1.1)\n 0.9818369875798\n\n References\n ----------\n .. [1] ISO 9276-2:2014 - Representation of Results of Particle Size\n Analysis - Part 2: Calculation of Average Particle Sizes/Diameters and\n Moments from Particle Size Distributions.\n \"\"\"\n try:\n return 0.5*(1.0 + erf((log(d/d_characteristic))/(s*sqrt(2.0))))\n except:\n # math error at cdf = 0 (x going as low as possible)\n return 0.0", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 2632}, "tests/test_particle_size_distribution.py::216": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/particle_size_distribution.py"], "used_names": ["assert_close", "cdf_lognormal", "stats"], "enclosing_function": "test_cdf_lognormal", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/particle_size_distribution.py\ndef cdf_lognormal(d: float, d_characteristic: float, s: float) -> float:\n r\"\"\"Calculates the cumulative distribution function of a lognormal particle\n distribution given a particle diameter `d`, characteristic particle\n diameter `d_characteristic`, and distribution standard deviation `s`.\n\n .. math::\n Q(d) = 0.5\\left(1 + \\text{err}\\left[\\left(\\frac{\\ln(d/d_c)}{s\\sqrt{2}}\n \\right)\\right]\\right)\n\n Parameters\n ----------\n d : float\n Specified particle diameter, [m]\n d_characteristic : float\n Characteristic particle diameter; often D[3, 3] is used for this\n purpose but not always, [m]\n s : float\n Distribution standard deviation, [-]\n\n Returns\n -------\n cdf : float\n Lognormal cumulative density function, [-]\n\n Notes\n -----\n The characteristic diameter can be in terns of number density (denoted\n :math:`q_0(d)`), length density (:math:`q_1(d)`), surface area density\n (:math:`q_2(d)`), or volume density (:math:`q_3(d)`). Volume density is\n most often used. Interconversions among the distributions is possible but\n tricky.\n\n The standard distribution (i.e. the one used in Scipy) can perform the same\n computation with `d_characteristic` as the value of `scale`.\n\n >>> import scipy.stats\n >>> float(scipy.stats.lognorm.cdf(x=1E-4, s=1.1, scale=1E-5))\n 0.9818369875798177\n\n Scipy's calculation is over 100 times slower however.\n\n Examples\n --------\n >>> cdf_lognormal(d=1E-4, d_characteristic=1E-5, s=1.1)\n 0.9818369875798\n\n References\n ----------\n .. [1] ISO 9276-2:2014 - Representation of Results of Particle Size\n Analysis - Part 2: Calculation of Average Particle Sizes/Diameters and\n Moments from Particle Size Distributions.\n \"\"\"\n try:\n return 0.5*(1.0 + erf((log(d/d_characteristic))/(s*sqrt(2.0))))\n except:\n # math error at cdf = 0 (x going as low as possible)\n return 0.0", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 2632}, "tests/test_pump.py::147": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/numerics/__init__.py", "fluids/pump.py"], "used_names": ["electrical_plug_types", "industrial_power", "residential_power", "residential_power_frequencies", "voltages_1_phase_residential", "voltages_3_phase"], "enclosing_function": "test_power_sources", "extracted_code": "# Source: fluids/pump.py\nresidential_power = {\n \"at\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Austria\"),\n \"bj\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Benin\"),\n \"gh\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Ghana\"),\n \"sc\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Seychelles\"),\n \"bg\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Bulgaria\"),\n \"me\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Montenegro\"),\n \"fo\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"K\"), voltage=230, freq=50, country=\"Faroe Islands\"),\n \"ne\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"), voltage=220, freq=50, country=\"Niger\"),\n \"za\": CountryPower(plugs=(\"C\", \"F\", \"M\", \"N\"), voltage=230, freq=50, country=\"South Africa\"),\n \"az\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Azerbaijan\"),\n \"so\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Somalia\"),\n \"sn\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"K\"), voltage=230, freq=50, country=\"Senegal\"),\n \"np\": CountryPower(plugs=(\"C\", \"D\", \"M\"), voltage=230, freq=50, country=\"Nepal\"),\n \"sl\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Sierra Leone\"),\n \"be\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Belgium\"),\n \"vg\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"British Virgin Islands\"),\n \"bz\": CountryPower(plugs=(\"A\", \"B\", \"G\"), voltage=110, freq=60, country=\"Belize\"),\n \"tw\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Taiwan\"),\n \"bf\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Burkina Faso\"),\n \"ao\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Angola\"),\n \"gi\": CountryPower(plugs=(\"C\", \"G\"), voltage=240, freq=50, country=\"Gibraltar\"),\n \"ee\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Estonia\"),\n \"bs\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Bahamas\"),\n \"ir\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Iran\"),\n \"sv\": CountryPower(plugs=(\"A\", \"B\"), voltage=115, freq=60, country=\"El Salvador\"),\n \"am\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Armenia\"),\n \"is\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Iceland\"),\n \"uy\": CountryPower(plugs=(\"C\", \"F\", \"I\", \"L\"), voltage=230, freq=50, country=\"Uruguay\"),\n \"mc\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"F\"), voltage=230, freq=50, country=\"Monaco\"),\n \"jm\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=50, country=\"Jamaica\"),\n \"im\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Isle of Man\"),\n \"dm\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Dominica\"),\n \"mu\": CountryPower(plugs=(\"C\", \"G\"), voltage=230, freq=50, country=\"Mauritius\"),\n \"cz\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Czech Republic\"),\n \"kh\": CountryPower(plugs=(\"A\", \"C\", \"G\"), voltage=230, freq=50, country=\"Cambodia\"),\n \"cf\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Central African Republic\"),\n \"se\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Sweden\"),\n \"uz\": CountryPower(plugs=(\"C\", \"I\"), voltage=220, freq=50, country=\"Uzbekistan\"),\n \"sk\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Slovakia\"),\n \"ky\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Cayman Islands\"),\n \"tn\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Tunisia\"),\n \"do\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Dominican Republic\"),\n \"hu\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Hungary\"),\n \"af\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Afghanistan\"),\n \"et\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"L\"), voltage=220, freq=50, country=\"Ethiopia\"),\n \"tv\": CountryPower(plugs=(\"I\",), voltage=220, freq=50, country=\"Tuvalu\"),\n \"ad\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Andorra\"),\n \"hn\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Honduras\"),\n \"ls\": CountryPower(plugs=(\"M\",), voltage=220, freq=50, country=\"Lesotho\"),\n \"na\": CountryPower(plugs=(\"D\", \"M\"), voltage=220, freq=50, country=\"Namibia\"),\n \"jo\": CountryPower(plugs=(\"B\", \"C\", \"D\", \"F\", \"G\", \"J\"), voltage=230, freq=50, country=\"Jordan\"),\n \"pl\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Poland\"),\n \"bt\": CountryPower(plugs=(\"C\", \"D\", \"F\", \"G\", \"M\"), voltage=230, freq=50, country=\"Bhutan\"),\n \"fm\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Micronesia\"),\n \"no\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Norway\"),\n \"fk\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Falkland Islands\"),\n \"je\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Jersey\"),\n \"ye\": CountryPower(plugs=(\"A\", \"D\", \"G\"), voltage=230, freq=50, country=\"Yemen\"),\n \"cm\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Cameroon\"),\n \"md\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Moldova\"),\n \"cn\": CountryPower(plugs=(\"A\", \"I\", \"C\"), voltage=220, freq=50, country=\"China\"),\n \"gm\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Gambia\"),\n \"sg\": CountryPower(plugs=(\"C\", \"G\", \"M\"), voltage=230, freq=50, country=\"Singapore\"),\n \"tj\": CountryPower(plugs=(\"C\", \"F\", \"I\"), voltage=220, freq=50, country=\"Tajikistan\"),\n \"gt\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Guatemala\"),\n \"ma\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Morocco\"),\n \"mv\": CountryPower(plugs=(\"D\", \"G\", \"J\", \"K\", \"L\"), voltage=230, freq=50, country=\"Maldives\"),\n \"ga\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Gabon\"),\n \"bo\": CountryPower(plugs=(\"A\", \"C\"), voltage=115, freq=50, country=\"Bolivia\"),\n \"ly\": CountryPower(plugs=(\"C\", \"D\", \"F\", \"L\"), voltage=127, freq=50, country=\"Libya\"),\n \"rw\": CountryPower(plugs=(\"C\", \"J\"), voltage=230, freq=50, country=\"Rwanda\"),\n \"cg\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Congo, Republic of the\"),\n \"kz\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Kazakhstan\"),\n \"jp\": CountryPower(plugs=(\"A\", \"B\"), voltage=100, freq=50, country=\"Japan\"),\n \"co\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Colombia\"),\n \"sm\": CountryPower(plugs=(\"C\", \"F\", \"L\"), voltage=230, freq=50, country=\"San Marino\"),\n \"rs\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Serbia\"),\n \"gw\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Guinea-Bissau\"),\n \"kr\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=60, country=\"South Korea\"),\n \"py\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Paraguay\"),\n \"lt\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Lithuania\"),\n \"tr\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Turkey\"),\n \"pa\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Panama\"),\n \"ba\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Bosnia and Herzegovina\"),\n \"vn\": CountryPower(plugs=(\"A\", \"C\", \"G\"), voltage=220, freq=50, country=\"Vietnam\"),\n \"iq\": CountryPower(plugs=(\"C\", \"D\", \"G\"), voltage=230, freq=50, country=\"Iraq\"),\n \"pk\": CountryPower(plugs=(\"C\", \"D\", \"G\", \"M\"), voltage=230, freq=50, country=\"Pakistan\"),\n \"li\": CountryPower(plugs=(\"C\", \"J\"), voltage=230, freq=50, country=\"Liechtenstein\"),\n \"mz\": CountryPower(plugs=(\"C\", \"F\", \"M\"), voltage=220, freq=50, country=\"Mozambique\"),\n \"au\": CountryPower(plugs=(\"I\",), voltage=230, freq=50, country=\"Australia\"),\n \"ws\": CountryPower(plugs=(\"I\",), voltage=230, freq=50, country=\"Samoa\"),\n \"sr\": CountryPower(plugs=(\"C\", \"F\"), voltage=127, freq=60, country=\"Suriname\"),\n \"mn\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Mongolia\"),\n \"bw\": CountryPower(plugs=(\"D\", \"G\", \"M\"), voltage=230, freq=50, country=\"Botswana\"),\n \"gb\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"United Kingdom\"),\n \"pg\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Papua New Guinea\"),\n \"dj\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Djibouti\"),\n \"th\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"F\"), voltage=220, freq=50, country=\"Thailand\"),\n \"us\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"United States\"),\n \"gr\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Greece\"),\n \"kn\": CountryPower(plugs=(\"A\", \"B\", \"D\", \"G\"), voltage=110, freq=60, country=\"St. Kitts and Nevis\"),\n \"ug\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Uganda\"),\n \"ie\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Ireland\"),\n \"tg\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Togo\"),\n \"td\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"F\"), voltage=220, freq=50, country=\"Chad\"),\n \"la\": CountryPower(plugs=(\"C\", \"E\", \"F\"), voltage=230, freq=50, country=\"Laos\"),\n \"sy\": CountryPower(plugs=(\"C\", \"E\", \"L\"), voltage=220, freq=50, country=\"Syria\"),\n \"bm\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Bermuda\"),\n \"il\": CountryPower(plugs=(\"C\", \"H\", \"M\"), voltage=230, freq=50, country=\"Israel\"),\n \"nz\": CountryPower(plugs=(\"I\",), voltage=230, freq=50, country=\"New Zealand\"),\n \"mg\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"J\", \"K\"), voltage=220, freq=50, country=\"Madagascar\"),\n \"ve\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Venezuela\"),\n \"dk\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"K\"), voltage=230, freq=50, country=\"Denmark\"),\n \"lb\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"D\", \"G\"), voltage=220, freq=50, country=\"Lebanon\"),\n \"kp\": CountryPower(plugs=(\"A\", \"C\", \"F\"), voltage=110, freq=60, country=\"North Korea\"),\n \"vu\": CountryPower(plugs=(\"C\", \"G\", \"I\"), voltage=220, freq=50, country=\"Vanuatu\"),\n \"cu\": CountryPower(plugs=(\"A\", \"B\", \"C\"), voltage=110, freq=60, country=\"Cuba\"),\n \"pt\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Portugal\"),\n \"kw\": CountryPower(plugs=(\"C\", \"G\"), voltage=240, freq=50, country=\"Kuwait\"),\n \"cd\": CountryPower(plugs=(\"C\", \"D\", \"E\"), voltage=220, freq=50, country=\"Congo, Democratic Republic of the\"),\n \"nr\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Nauru\"),\n \"si\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Slovenia\"),\n \"bd\": CountryPower(plugs=(\"C\", \"D\", \"G\", \"K\"), voltage=220, freq=50, country=\"Bangladesh\"),\n \"al\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Albania\"),\n \"ec\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Ecuador\"),\n \"gy\": CountryPower(plugs=(\"A\", \"B\", \"D\", \"G\"), voltage=110, freq=60, country=\"Guyana\"),\n \"bb\": CountryPower(plugs=(\"A\", \"B\"), voltage=115, freq=50, country=\"Barbados\"),\n \"ke\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Kenya\"),\n \"mx\": CountryPower(plugs=(\"A\", \"B\"), voltage=127, freq=60, country=\"Mexico\"),\n \"gq\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Equatorial Guinea\"),\n \"gn\": CountryPower(plugs=(\"C\", \"F\", \"K\"), voltage=220, freq=50, country=\"Guinea\"),\n \"bi\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Burundi\"),\n \"lv\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Latvia\"),\n \"fj\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Fiji\"),\n \"ci\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Côte d'Ivoire\"),\n \"ai\": CountryPower(plugs=(\"A\",), voltage=110, freq=60, country=\"Anguilla\"),\n \"gu\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Guam\"),\n \"lr\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"E\", \"F\"), voltage=120, freq=60, country=\"Liberia\"),\n \"br\": CountryPower(plugs=(\"C\", \"N\"), voltage=220, freq=60, country=\"Brazil\"),\n \"cv\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Cape Verde\"),\n \"cl\": CountryPower(plugs=(\"L\",), voltage=220, freq=50, country=\"Chile\"),\n \"in\": CountryPower(plugs=(\"C\", \"D\", \"M\"), voltage=230, freq=50, country=\"India\"),\n \"gg\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Guernsey\"),\n \"tt\": CountryPower(plugs=(\"A\", \"B\"), voltage=115, freq=60, country=\"Trinidad & Tobago\"),\n \"de\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Germany\"),\n \"qa\": CountryPower(plugs=(\"D\", \"G\"), voltage=240, freq=50, country=\"Qatar\"),\n \"ph\": CountryPower(plugs=(\"A\", \"B\"), voltage=220, freq=60, country=\"Philippines\"),\n \"sd\": CountryPower(plugs=(\"C\", \"D\"), voltage=230, freq=50, country=\"Sudan\"),\n \"mm\": CountryPower(plugs=(\"C\", \"D\", \"F\", \"G\"), voltage=230, freq=50, country=\"Myanmar\"),\n \"gd\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Grenada\"),\n \"st\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"São Tomé and Príncipe\"),\n \"sz\": CountryPower(plugs=(\"M\",), voltage=230, freq=50, country=\"Swaziland\"),\n \"ro\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Romania\"),\n \"xk\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Kosovo\"),\n \"cy\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Cyprus\"),\n \"dz\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Algeria\"),\n \"zm\": CountryPower(plugs=(\"C\", \"D\", \"G\"), voltage=230, freq=50, country=\"Zambia\"),\n \"by\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Belarus\"),\n \"hr\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Croatia\"),\n \"lu\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Luxembourg\"),\n \"fi\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Finland\"),\n \"zw\": CountryPower(plugs=(\"D\", \"G\"), voltage=220, freq=50, country=\"Zimbabwe\"),\n \"km\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Comoros\"),\n \"tl\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"I\"), voltage=220, freq=50, country=\"Timor-Leste \"),\n \"tz\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Tanzania\"),\n \"ht\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Haiti\"),\n \"vc\": CountryPower(plugs=(\"C\", \"E\", \"G\", \"I\", \"K\"), voltage=230, freq=50, country=\"St. Vincent and the Grenadines\"),\n \"es\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Spain\"),\n \"my\": CountryPower(plugs=(\"C\", \"G\", \"M\"), voltage=230, freq=50, country=\"Malaysia\"),\n \"lc\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"St. Lucia\"),\n \"tm\": CountryPower(plugs=(\"B\", \"C\", \"F\"), voltage=220, freq=50, country=\"Turkmenistan\"),\n \"pe\": CountryPower(plugs=(\"A\", \"B\", \"C\"), voltage=220, freq=60, country=\"Peru\"),\n \"ua\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Ukraine\"),\n \"eg\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Egypt\"),\n \"sb\": CountryPower(plugs=(\"I\", \"G\"), voltage=220, freq=50, country=\"Solomon Islands\"),\n \"to\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Tonga\"),\n \"fr\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"France\"),\n \"ng\": CountryPower(plugs=(\"D\", \"G\"), voltage=240, freq=50, country=\"Nigeria\"),\n \"sh\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Saint Helena, Ascension and Tristan da Cunha\"),\n \"mw\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Malawi\"),\n \"ms\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Montserrat\"),\n \"ae\": CountryPower(plugs=(\"C\", \"D\", \"G\"), voltage=220, freq=50, country=\"United Arab Emirates\"),\n \"nl\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Netherlands\"),\n \"id\": CountryPower(plugs=(\"C\", \"F\", \"G\"), voltage=230, freq=50, country=\"Indonesia\"),\n \"ru\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Russia\"),\n \"ar\": CountryPower(plugs=(\"C\", \"I\"), voltage=220, freq=50, country=\"Argentina\"),\n \"bn\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Brunei\"),\n \"pw\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Palau\"),\n \"kg\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Kyrgyzstan\"),\n \"bh\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Bahrain\"),\n \"ml\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Mali\"),\n \"it\": CountryPower(plugs=(\"C\", \"F\", \"L\"), voltage=230, freq=50, country=\"Italy\"),\n \"sa\": CountryPower(plugs=(\"A\", \"B\", \"G\"), voltage=220, freq=60, country=\"Saudi Arabia\"),\n \"ag\": CountryPower(plugs=(\"A\", \"B\"), voltage=230, freq=60, country=\"Antigua and Barbuda\"),\n \"mr\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Mauritania\"),\n \"om\": CountryPower(plugs=(\"C\", \"G\"), voltage=240, freq=50, country=\"Oman\"),\n \"lk\": CountryPower(plugs=(\"D\", \"G\", \"M\"), voltage=230, freq=50, country=\"Sri Lanka\"),\n \"er\": CountryPower(plugs=(\"C\", \"L\"), voltage=230, freq=50, country=\"Eritrea\"),\n \"mk\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Macedonia\"),\n \"ni\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Nicaragua\"),\n \"ch\": CountryPower(plugs=(\"C\", \"J\"), voltage=230, freq=50, country=\"Switzerland\"),\n \"ca\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Canada\"),\n \"cr\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Costa Rica\")\n}\n\nindustrial_power = {\n \"at\": CountryPower(voltage=TUP_400, freq=50, country=\"Austria\"),\n \"bj\": CountryPower(voltage=TUP_380, freq=50, country=\"Benin\"),\n \"gh\": CountryPower(voltage=TUP_400, freq=50, country=\"Ghana\"),\n \"sc\": CountryPower(voltage=TUP_240, freq=50, country=\"Seychelles\"),\n \"bg\": CountryPower(voltage=TUP_400, freq=50, country=\"Bulgaria\"),\n \"me\": CountryPower(voltage=TUP_400, freq=50, country=\"Montenegro\"),\n \"fo\": CountryPower(voltage=TUP_400, freq=50, country=\"Faeroe Islands\"),\n \"iq\": CountryPower(voltage=TUP_400, freq=50, country=\"Iraq\"),\n \"ne\": CountryPower(voltage=TUP_380, freq=50, country=\"Niger\"),\n \"za\": CountryPower(voltage=TUP_400, freq=50, country=\"South Africa\"),\n \"az\": CountryPower(voltage=TUP_380, freq=50, country=\"Azerbaijan\"),\n \"so\": CountryPower(voltage=TUP_380, freq=50, country=\"Somalia\"),\n \"sn\": CountryPower(voltage=TUP_400, freq=50, country=\"Senegal\"),\n \"np\": CountryPower(voltage=TUP_400, freq=50, country=\"Nepal\"),\n \"sl\": CountryPower(voltage=TUP_400, freq=50, country=\"Sierra Leone\"),\n \"be\": CountryPower(voltage=TUP_400, freq=50, country=\"Belgium\"),\n \"vg\": CountryPower(voltage=TUP_190, freq=60, country=\"British Virgin Islands\"),\n \"bz\": CountryPower(voltage=(190, CONST_380), freq=60, country=\"Belize\"),\n \"tw\": CountryPower(voltage=(220,), freq=60, country=\"Taiwan\"),\n \"bf\": CountryPower(voltage=TUP_380, freq=50, country=\"Burkina Faso\"),\n \"ao\": CountryPower(voltage=TUP_380, freq=50, country=\"Angola\"),\n \"ee\": CountryPower(voltage=TUP_400, freq=50, country=\"Estonia\"),\n \"bs\": CountryPower(voltage=TUP_208, freq=60, country=\"Bahamas\"),\n \"ir\": CountryPower(voltage=TUP_400, freq=50, country=\"Iran\"),\n \"sv\": CountryPower(voltage=(200,), freq=60, country=\"El Salvador\"),\n \"am\": CountryPower(voltage=TUP_400, freq=50, country=\"Armenia\"),\n \"is\": CountryPower(voltage=TUP_400, freq=50, country=\"Iceland\"),\n \"uy\": CountryPower(voltage=TUP_380, freq=50, country=\"Uruguay\"),\n \"mc\": CountryPower(voltage=TUP_400, freq=50, country=\"Monaco\"),\n \"jm\": CountryPower(voltage=TUP_190, freq=50, country=\"Jamaica\"),\n \"im\": CountryPower(voltage=TUP_415, freq=50, country=\"Isle of Man\"),\n \"dm\": CountryPower(voltage=TUP_400, freq=50, country=\"Dominica\"),\n \"mu\": CountryPower(voltage=TUP_400, freq=50, country=\"Mauritius\"),\n \"cz\": CountryPower(voltage=TUP_400, freq=50, country=\"Czech Republic\"),\n \"kh\": CountryPower(voltage=TUP_400, freq=50, country=\"Cambodia\"),\n \"cf\": CountryPower(voltage=TUP_380, freq=50, country=\"Central African Republic\"),\n \"se\": CountryPower(voltage=TUP_400, freq=50, country=\"Sweden\"),\n \"uz\": CountryPower(voltage=TUP_380, freq=50, country=\"Uzbekistan\"),\n \"sk\": CountryPower(voltage=TUP_400, freq=50, country=\"Slovakia\"),\n \"ky\": CountryPower(voltage=TUP_240, freq=60, country=\"Cayman Islands\"),\n \"tn\": CountryPower(voltage=TUP_400, freq=50, country=\"Tunisia\"),\n \"hu\": CountryPower(voltage=TUP_400, freq=50, country=\"Hungary\"),\n \"af\": CountryPower(voltage=TUP_380, freq=50, country=\"Afghanistan\"),\n \"tc\": CountryPower(voltage=TUP_240, freq=60, country=\"Turks and Caicos Islands\"),\n \"et\": CountryPower(voltage=TUP_380, freq=50, country=\"Ethiopia\"),\n \"sd\": CountryPower(voltage=TUP_400, freq=50, country=\"Sudan\"),\n \"ad\": CountryPower(voltage=TUP_400, freq=50, country=\"Andorra\"),\n \"hn\": CountryPower(voltage=(208, 230, 240, 460, CONST_480), freq=60, country=\"Honduras\"),\n \"ls\": CountryPower(voltage=TUP_380, freq=50, country=\"Lesotho\"),\n \"na\": CountryPower(voltage=TUP_380, freq=50, country=\"Namibia\"),\n \"pl\": CountryPower(voltage=TUP_400, freq=50, country=\"Poland\"),\n \"bt\": CountryPower(voltage=TUP_400, freq=50, country=\"Bhutan\"),\n \"sa\": CountryPower(voltage=TUP_400, freq=60, country=\"Saudi Arabia\"),\n \"no\": CountryPower(voltage=(230, 400), freq=50, country=\"Norway\"),\n \"fk\": CountryPower(voltage=TUP_415, freq=50, country=\"Falkland Islands\"),\n \"ye\": CountryPower(voltage=TUP_400, freq=50, country=\"Yemen\"),\n \"gi\": CountryPower(voltage=TUP_400, freq=50, country=\"Gibraltar\"),\n \"md\": CountryPower(voltage=TUP_400, freq=50, country=\"Moldova\"),\n \"cn\": CountryPower(voltage=TUP_380, freq=50, country=\"China\"),\n \"gm\": CountryPower(voltage=TUP_400, freq=50, country=\"Gambia\"),\n \"sg\": CountryPower(voltage=TUP_400, freq=50, country=\"Singapore\"),\n \"tj\": CountryPower(voltage=TUP_380, freq=50, country=\"Tajikistan\"),\n \"gt\": CountryPower(voltage=TUP_208, freq=60, country=\"Guatemala\"),\n \"ma\": CountryPower(voltage=TUP_380, freq=50, country=\"Morocco\"),\n \"mv\": CountryPower(voltage=TUP_400, freq=50, country=\"Maldives\"),\n \"ga\": CountryPower(voltage=TUP_380, freq=50, country=\"Gabon\"),\n \"bo\": CountryPower(voltage=TUP_400, freq=50, country=\"Bolivia\"),\n \"ly\": CountryPower(voltage=TUP_400, freq=50, country=\"Libya\"),\n \"rw\": CountryPower(voltage=TUP_400, freq=50, country=\"Rwanda\"),\n \"cg\": CountryPower(voltage=TUP_400, freq=50, country=\"People's Republic of Congo\"),\n \"kz\": CountryPower(voltage=TUP_380, freq=50, country=\"Kazakhstan\"),\n \"jp\": CountryPower(voltage=(200,), freq=50, country=\"Japan\"),\n \"co\": CountryPower(voltage=(220, 440), freq=60, country=\"Colombia\"),\n \"sm\": CountryPower(voltage=TUP_400, freq=50, country=\"San Marino\"),\n \"rs\": CountryPower(voltage=TUP_400, freq=50, country=\"Serbia\"),\n \"gw\": CountryPower(voltage=TUP_380, freq=50, country=\"Guinea-Bissau\"),\n \"kr\": CountryPower(voltage=TUP_380, freq=60, country=\"South Korea\"),\n \"py\": CountryPower(voltage=TUP_380, freq=50, country=\"Paraguay\"),\n \"lt\": CountryPower(voltage=TUP_400, freq=50, country=\"Lithuania\"),\n \"tr\": CountryPower(voltage=TUP_400, freq=50, country=\"Turkey\"),\n \"ss\": CountryPower(voltage=TUP_400, freq=50, country=\"South Sudan\"),\n \"ba\": CountryPower(voltage=TUP_400, freq=50, country=\"Bosnia & Herzegovina\"),\n \"vn\": CountryPower(voltage=TUP_380, freq=50, country=\"Vietnam\"),\n \"do\": CountryPower(voltage=(120, 208, 277, 480), freq=60, country=\"Dominican Republic\"),\n \"pk\": CountryPower(voltage=TUP_400, freq=50, country=\"Pakistan\"),\n \"li\": CountryPower(voltage=TUP_400, freq=50, country=\"Liechtenstein\"),\n \"mz\": CountryPower(voltage=TUP_380, freq=50, country=\"Mozambique\"),\n \"au\": CountryPower(voltage=TUP_400, freq=50, country=\"Australia\"),\n \"ws\": CountryPower(voltage=TUP_400, freq=50, country=\"Samoa\"),\n \"sr\": CountryPower(voltage=(220, 400,), freq=60, country=\"Suriname\"),\n \"mn\": CountryPower(voltage=TUP_400, freq=50, country=\"Mongolia\"),\n \"bw\": CountryPower(voltage=TUP_400, freq=50, country=\"Botswana\"),\n \"gb\": CountryPower(voltage=TUP_415, freq=50, country=\"United Kingdom\"),\n \"pg\": CountryPower(voltage=TUP_415, freq=50, country=\"Papua New Guinea\"),\n \"dj\": CountryPower(voltage=TUP_380, freq=50, country=\"Djibouti\"),\n \"th\": CountryPower(voltage=TUP_400, freq=50, country=\"Thailand\"),\n \"us\": CountryPower(voltage=(120, 208, 277, 480, 120, 240, 240, CONST_480), freq=60, country=\"United States of America\"),\n \"gr\": CountryPower(voltage=TUP_400, freq=50, country=\"Greece\"),\n \"ug\": CountryPower(voltage=TUP_415, freq=50, country=\"Uganda\"),\n \"ie\": CountryPower(voltage=TUP_415, freq=50, country=\"Ireland\"),\n \"tg\": CountryPower(voltage=TUP_380, freq=50, country=\"Togo\"),\n \"td\": CountryPower(voltage=TUP_380, freq=50, country=\"Chad\"),\n \"la\": CountryPower(voltage=TUP_400, freq=50, country=\"Laos\"),\n \"sy\": CountryPower(voltage=TUP_380, freq=50, country=\"Syria\"),\n \"bm\": CountryPower(voltage=TUP_208, freq=60, country=\"Bermuda\"),\n \"il\": CountryPower(voltage=TUP_400, freq=50, country=\"Israel\"),\n \"nz\": CountryPower(voltage=TUP_400, freq=50, country=\"New Zealand\"),\n \"mg\": CountryPower(voltage=TUP_380, freq=50, country=\"Madagascar\"),\n \"ve\": CountryPower(voltage=(120,), freq=60, country=\"Venezuela\"),\n \"dk\": CountryPower(voltage=TUP_400, freq=50, country=\"Denmark\"),\n \"lb\": CountryPower(voltage=TUP_400, freq=50, country=\"Lebanon\"),\n \"kp\": CountryPower(voltage=TUP_380, freq=50, country=\"North Korea\"),\n \"vu\": CountryPower(voltage=TUP_400, freq=50, country=\"Vanuatu\"),\n \"cu\": CountryPower(voltage=(190, 440), freq=60, country=\"Cuba\"),\n \"kw\": CountryPower(voltage=TUP_415, freq=50, country=\"Kuwait\"),\n \"cd\": CountryPower(voltage=TUP_380, freq=50, country=\"Democratic Republic of Congo\"),\n \"nr\": CountryPower(voltage=TUP_415, freq=50, country=\"Nauru\"),\n \"si\": CountryPower(voltage=TUP_400, freq=50, country=\"Slovenia\"),\n \"mt\": CountryPower(voltage=TUP_400, freq=50, country=\"Malta\"),\n \"bd\": CountryPower(voltage=TUP_380, freq=50, country=\"Bangladesh\"),\n \"al\": CountryPower(voltage=TUP_400, freq=50, country=\"Albania\"),\n \"ec\": CountryPower(voltage=TUP_208, freq=60, country=\"Ecuador\"),\n \"gy\": CountryPower(voltage=TUP_190, freq=60, country=\"Guyana\"),\n \"bb\": CountryPower(voltage=(200,), freq=50, country=\"Barbados\"),\n \"ke\": CountryPower(voltage=TUP_415, freq=50, country=\"Kenya\"),\n \"mx\": CountryPower(voltage=(220, CONST_480), freq=60, country=\"Mexico\"),\n \"gn\": CountryPower(voltage=TUP_380, freq=50, country=\"Guinea\"),\n \"bi\": CountryPower(voltage=TUP_380, freq=50, country=\"Burundi\"),\n \"lv\": CountryPower(voltage=TUP_400, freq=50, country=\"Latvia\"),\n \"fj\": CountryPower(voltage=TUP_415, freq=50, country=\"Fiji\"),\n \"ci\": CountryPower(voltage=TUP_380, freq=50, country=\"Côte d’Ivoire\"),\n \"ai\": CountryPower(voltage=(120, 208, 127, 220, 240, 415), freq=60, country=\"Anguilla\"),\n \"gu\": CountryPower(voltage=TUP_190, freq=60, country=\"Guam\"),\n \"lr\": CountryPower(voltage=TUP_208, freq=60, country=\"Liberia\"),\n \"br\": CountryPower(voltage=(220, 380), freq=60, country=\"Brazil\"),\n \"cv\": CountryPower(voltage=TUP_400, freq=50, country=\"Cape Verde\"),\n \"cl\": CountryPower(voltage=TUP_380, freq=50, country=\"Chile\"),\n \"in\": CountryPower(voltage=TUP_400, freq=50, country=\"India\"),\n \"tt\": CountryPower(voltage=(115, 230, 230, 400), freq=60, country=\"Trinidad & Tobago\"),\n \"de\": CountryPower(voltage=TUP_400, freq=50, country=\"Germany\"),\n \"pa\": CountryPower(voltage=TUP_240, freq=60, country=\"Panama\"),\n \"qa\": CountryPower(voltage=TUP_415, freq=50, country=\"Qatar\"),\n \"ph\": CountryPower(voltage=TUP_380, freq=60, country=\"Philippines\"),\n \"jo\": CountryPower(voltage=TUP_400, freq=50, country=\"Jordan\"),\n \"mm\": CountryPower(voltage=TUP_400, freq=50, country=\"Myanmar\"),\n \"gd\": CountryPower(voltage=TUP_400, freq=50, country=\"Grenada\"),\n \"st\": CountryPower(voltage=TUP_400, freq=50, country=\"São Tomé and Príncipe\"),\n \"sz\": CountryPower(voltage=TUP_400, freq=50, country=\"Swaziland\"),\n \"ro\": CountryPower(voltage=TUP_400, freq=50, country=\"Romania\"),\n \"xk\": CountryPower(voltage=(230, 400), freq=50, country=\"Kosovo\"),\n \"cy\": CountryPower(voltage=TUP_400, freq=50, country=\"Cyprus\"),\n \"dz\": CountryPower(voltage=TUP_400, freq=50, country=\"Algeria\"),\n \"zm\": CountryPower(voltage=TUP_400, freq=50, country=\"Zambia\"),\n \"by\": CountryPower(voltage=TUP_380, freq=50, country=\"Belarus\"),\n \"hr\": CountryPower(voltage=TUP_400, freq=50, country=\"Croatia\"),\n \"lu\": CountryPower(voltage=TUP_400, freq=50, country=\"Luxembourg\"),\n \"fi\": CountryPower(voltage=TUP_400, freq=50, country=\"Finland\"),\n \"zw\": CountryPower(voltage=TUP_415, freq=50, country=\"Zimbabwe\"),\n \"km\": CountryPower(voltage=TUP_380, freq=50, country=\"Comoros\"),\n \"tl\": CountryPower(voltage=TUP_380, freq=50, country=\"East Timor\"),\n \"tz\": CountryPower(voltage=TUP_415, freq=50, country=\"Tanzania\"),\n \"ht\": CountryPower(voltage=TUP_190, freq=60, country=\"Haiti\"),\n \"vc\": CountryPower(voltage=TUP_400, freq=50, country=\"Saint Vincent and the Grenadines\"),\n \"es\": CountryPower(voltage=TUP_400, freq=50, country=\"Spain\"),\n \"my\": CountryPower(voltage=TUP_415, freq=50, country=\"Malaysia\"),\n \"lc\": CountryPower(voltage=TUP_400, freq=50, country=\"Saint Lucia\"),\n \"tm\": CountryPower(voltage=TUP_380, freq=50, country=\"Turkmenistan\"),\n \"pe\": CountryPower(voltage=(220,), freq=60, country=\"Peru\"),\n \"ua\": CountryPower(voltage=TUP_400, freq=50, country=\"Ukraine\"),\n \"eg\": CountryPower(voltage=TUP_380, freq=50, country=\"Egypt\"),\n \"to\": CountryPower(voltage=TUP_415, freq=50, country=\"Tonga\"),\n \"fr\": CountryPower(voltage=TUP_400, freq=50, country=\"France\"),\n \"ng\": CountryPower(voltage=TUP_415, freq=50, country=\"Nigeria\"),\n \"mw\": CountryPower(voltage=TUP_400, freq=50, country=\"Malawi\"),\n \"ms\": CountryPower(voltage=TUP_400, freq=60, country=\"Montserrat\"),\n \"ae\": CountryPower(voltage=TUP_400, freq=50, country=\"United Arab Emirates\"),\n \"nl\": CountryPower(voltage=TUP_400, freq=50, country=\"Netherlands\"),\n \"id\": CountryPower(voltage=TUP_400, freq=50, country=\"Indonesia\"),\n \"ru\": CountryPower(voltage=TUP_380, freq=50, country=\"Russia\"),\n \"ar\": CountryPower(voltage=TUP_380, freq=50, country=\"Argentina\"),\n \"bn\": CountryPower(voltage=TUP_415, freq=50, country=\"Brunei\"),\n \"pw\": CountryPower(voltage=TUP_208, freq=60, country=\"Palau\"),\n \"kg\": CountryPower(voltage=TUP_380, freq=50, country=\"Kyrgyzstan\"),\n \"bh\": CountryPower(voltage=TUP_400, freq=50, country=\"Bahrain\"),\n \"ml\": CountryPower(voltage=TUP_380, freq=50, country=\"Mali\"),\n \"it\": CountryPower(voltage=TUP_400, freq=50, country=\"Italy\"),\n \"cm\": CountryPower(voltage=TUP_380, freq=50, country=\"Cameroon\"),\n \"ag\": CountryPower(voltage=TUP_400, freq=60, country=\"Antigua and Barbuda\"),\n \"mr\": CountryPower(voltage=(220,), freq=50, country=\"Mauritania\"),\n \"om\": CountryPower(voltage=TUP_415, freq=50, country=\"Oman\"),\n \"lk\": CountryPower(voltage=TUP_400, freq=50, country=\"Sri Lanka\"),\n \"er\": CountryPower(voltage=TUP_400, freq=50, country=\"Eritrea\"),\n \"mk\": CountryPower(voltage=TUP_400, freq=50, country=\"Macedonia, Republic of\"),\n \"ni\": CountryPower(voltage=TUP_208, freq=60, country=\"Nicaragua\"),\n \"ch\": CountryPower(voltage=TUP_400, freq=50, country=\"Switzerland\"),\n \"ca\": CountryPower(voltage=(120, 208, 240, CONST_480, 347, 600), freq=60, country=\"Canada\"),\n \"cr\": CountryPower(voltage=TUP_240, freq=60, country=\"Costa Rica\")\n}\n\nelectrical_plug_types = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\"]\n\nvoltages_1_phase_residential = [100, 110, 115, 120, 127, 220, 230, 240]\n\nvoltages_3_phase = [120, 190, 200, 208, 220, 230, 240, 277, 380, 400, 415, 440, 480]\n\nresidential_power_frequencies = [50, 60]", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 31977}, "tests/test_pump.py::154": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/numerics/__init__.py", "fluids/pump.py"], "used_names": ["electrical_plug_types", "industrial_power", "residential_power", "residential_power_frequencies", "voltages_1_phase_residential", "voltages_3_phase"], "enclosing_function": "test_power_sources", "extracted_code": "# Source: fluids/pump.py\nresidential_power = {\n \"at\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Austria\"),\n \"bj\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Benin\"),\n \"gh\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Ghana\"),\n \"sc\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Seychelles\"),\n \"bg\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Bulgaria\"),\n \"me\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Montenegro\"),\n \"fo\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"K\"), voltage=230, freq=50, country=\"Faroe Islands\"),\n \"ne\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"D\", \"E\", \"F\"), voltage=220, freq=50, country=\"Niger\"),\n \"za\": CountryPower(plugs=(\"C\", \"F\", \"M\", \"N\"), voltage=230, freq=50, country=\"South Africa\"),\n \"az\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Azerbaijan\"),\n \"so\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Somalia\"),\n \"sn\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"K\"), voltage=230, freq=50, country=\"Senegal\"),\n \"np\": CountryPower(plugs=(\"C\", \"D\", \"M\"), voltage=230, freq=50, country=\"Nepal\"),\n \"sl\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Sierra Leone\"),\n \"be\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Belgium\"),\n \"vg\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"British Virgin Islands\"),\n \"bz\": CountryPower(plugs=(\"A\", \"B\", \"G\"), voltage=110, freq=60, country=\"Belize\"),\n \"tw\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Taiwan\"),\n \"bf\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Burkina Faso\"),\n \"ao\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Angola\"),\n \"gi\": CountryPower(plugs=(\"C\", \"G\"), voltage=240, freq=50, country=\"Gibraltar\"),\n \"ee\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Estonia\"),\n \"bs\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Bahamas\"),\n \"ir\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Iran\"),\n \"sv\": CountryPower(plugs=(\"A\", \"B\"), voltage=115, freq=60, country=\"El Salvador\"),\n \"am\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Armenia\"),\n \"is\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Iceland\"),\n \"uy\": CountryPower(plugs=(\"C\", \"F\", \"I\", \"L\"), voltage=230, freq=50, country=\"Uruguay\"),\n \"mc\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"F\"), voltage=230, freq=50, country=\"Monaco\"),\n \"jm\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=50, country=\"Jamaica\"),\n \"im\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Isle of Man\"),\n \"dm\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Dominica\"),\n \"mu\": CountryPower(plugs=(\"C\", \"G\"), voltage=230, freq=50, country=\"Mauritius\"),\n \"cz\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Czech Republic\"),\n \"kh\": CountryPower(plugs=(\"A\", \"C\", \"G\"), voltage=230, freq=50, country=\"Cambodia\"),\n \"cf\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Central African Republic\"),\n \"se\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Sweden\"),\n \"uz\": CountryPower(plugs=(\"C\", \"I\"), voltage=220, freq=50, country=\"Uzbekistan\"),\n \"sk\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Slovakia\"),\n \"ky\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Cayman Islands\"),\n \"tn\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Tunisia\"),\n \"do\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Dominican Republic\"),\n \"hu\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Hungary\"),\n \"af\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Afghanistan\"),\n \"et\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"L\"), voltage=220, freq=50, country=\"Ethiopia\"),\n \"tv\": CountryPower(plugs=(\"I\",), voltage=220, freq=50, country=\"Tuvalu\"),\n \"ad\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Andorra\"),\n \"hn\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Honduras\"),\n \"ls\": CountryPower(plugs=(\"M\",), voltage=220, freq=50, country=\"Lesotho\"),\n \"na\": CountryPower(plugs=(\"D\", \"M\"), voltage=220, freq=50, country=\"Namibia\"),\n \"jo\": CountryPower(plugs=(\"B\", \"C\", \"D\", \"F\", \"G\", \"J\"), voltage=230, freq=50, country=\"Jordan\"),\n \"pl\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Poland\"),\n \"bt\": CountryPower(plugs=(\"C\", \"D\", \"F\", \"G\", \"M\"), voltage=230, freq=50, country=\"Bhutan\"),\n \"fm\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Micronesia\"),\n \"no\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Norway\"),\n \"fk\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Falkland Islands\"),\n \"je\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Jersey\"),\n \"ye\": CountryPower(plugs=(\"A\", \"D\", \"G\"), voltage=230, freq=50, country=\"Yemen\"),\n \"cm\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Cameroon\"),\n \"md\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Moldova\"),\n \"cn\": CountryPower(plugs=(\"A\", \"I\", \"C\"), voltage=220, freq=50, country=\"China\"),\n \"gm\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Gambia\"),\n \"sg\": CountryPower(plugs=(\"C\", \"G\", \"M\"), voltage=230, freq=50, country=\"Singapore\"),\n \"tj\": CountryPower(plugs=(\"C\", \"F\", \"I\"), voltage=220, freq=50, country=\"Tajikistan\"),\n \"gt\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Guatemala\"),\n \"ma\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Morocco\"),\n \"mv\": CountryPower(plugs=(\"D\", \"G\", \"J\", \"K\", \"L\"), voltage=230, freq=50, country=\"Maldives\"),\n \"ga\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Gabon\"),\n \"bo\": CountryPower(plugs=(\"A\", \"C\"), voltage=115, freq=50, country=\"Bolivia\"),\n \"ly\": CountryPower(plugs=(\"C\", \"D\", \"F\", \"L\"), voltage=127, freq=50, country=\"Libya\"),\n \"rw\": CountryPower(plugs=(\"C\", \"J\"), voltage=230, freq=50, country=\"Rwanda\"),\n \"cg\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Congo, Republic of the\"),\n \"kz\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Kazakhstan\"),\n \"jp\": CountryPower(plugs=(\"A\", \"B\"), voltage=100, freq=50, country=\"Japan\"),\n \"co\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Colombia\"),\n \"sm\": CountryPower(plugs=(\"C\", \"F\", \"L\"), voltage=230, freq=50, country=\"San Marino\"),\n \"rs\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Serbia\"),\n \"gw\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Guinea-Bissau\"),\n \"kr\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=60, country=\"South Korea\"),\n \"py\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Paraguay\"),\n \"lt\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Lithuania\"),\n \"tr\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Turkey\"),\n \"pa\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Panama\"),\n \"ba\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Bosnia and Herzegovina\"),\n \"vn\": CountryPower(plugs=(\"A\", \"C\", \"G\"), voltage=220, freq=50, country=\"Vietnam\"),\n \"iq\": CountryPower(plugs=(\"C\", \"D\", \"G\"), voltage=230, freq=50, country=\"Iraq\"),\n \"pk\": CountryPower(plugs=(\"C\", \"D\", \"G\", \"M\"), voltage=230, freq=50, country=\"Pakistan\"),\n \"li\": CountryPower(plugs=(\"C\", \"J\"), voltage=230, freq=50, country=\"Liechtenstein\"),\n \"mz\": CountryPower(plugs=(\"C\", \"F\", \"M\"), voltage=220, freq=50, country=\"Mozambique\"),\n \"au\": CountryPower(plugs=(\"I\",), voltage=230, freq=50, country=\"Australia\"),\n \"ws\": CountryPower(plugs=(\"I\",), voltage=230, freq=50, country=\"Samoa\"),\n \"sr\": CountryPower(plugs=(\"C\", \"F\"), voltage=127, freq=60, country=\"Suriname\"),\n \"mn\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Mongolia\"),\n \"bw\": CountryPower(plugs=(\"D\", \"G\", \"M\"), voltage=230, freq=50, country=\"Botswana\"),\n \"gb\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"United Kingdom\"),\n \"pg\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Papua New Guinea\"),\n \"dj\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Djibouti\"),\n \"th\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"F\"), voltage=220, freq=50, country=\"Thailand\"),\n \"us\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"United States\"),\n \"gr\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Greece\"),\n \"kn\": CountryPower(plugs=(\"A\", \"B\", \"D\", \"G\"), voltage=110, freq=60, country=\"St. Kitts and Nevis\"),\n \"ug\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Uganda\"),\n \"ie\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Ireland\"),\n \"tg\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Togo\"),\n \"td\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"F\"), voltage=220, freq=50, country=\"Chad\"),\n \"la\": CountryPower(plugs=(\"C\", \"E\", \"F\"), voltage=230, freq=50, country=\"Laos\"),\n \"sy\": CountryPower(plugs=(\"C\", \"E\", \"L\"), voltage=220, freq=50, country=\"Syria\"),\n \"bm\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Bermuda\"),\n \"il\": CountryPower(plugs=(\"C\", \"H\", \"M\"), voltage=230, freq=50, country=\"Israel\"),\n \"nz\": CountryPower(plugs=(\"I\",), voltage=230, freq=50, country=\"New Zealand\"),\n \"mg\": CountryPower(plugs=(\"C\", \"D\", \"E\", \"J\", \"K\"), voltage=220, freq=50, country=\"Madagascar\"),\n \"ve\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Venezuela\"),\n \"dk\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"K\"), voltage=230, freq=50, country=\"Denmark\"),\n \"lb\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"D\", \"G\"), voltage=220, freq=50, country=\"Lebanon\"),\n \"kp\": CountryPower(plugs=(\"A\", \"C\", \"F\"), voltage=110, freq=60, country=\"North Korea\"),\n \"vu\": CountryPower(plugs=(\"C\", \"G\", \"I\"), voltage=220, freq=50, country=\"Vanuatu\"),\n \"cu\": CountryPower(plugs=(\"A\", \"B\", \"C\"), voltage=110, freq=60, country=\"Cuba\"),\n \"pt\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Portugal\"),\n \"kw\": CountryPower(plugs=(\"C\", \"G\"), voltage=240, freq=50, country=\"Kuwait\"),\n \"cd\": CountryPower(plugs=(\"C\", \"D\", \"E\"), voltage=220, freq=50, country=\"Congo, Democratic Republic of the\"),\n \"nr\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Nauru\"),\n \"si\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Slovenia\"),\n \"bd\": CountryPower(plugs=(\"C\", \"D\", \"G\", \"K\"), voltage=220, freq=50, country=\"Bangladesh\"),\n \"al\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Albania\"),\n \"ec\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Ecuador\"),\n \"gy\": CountryPower(plugs=(\"A\", \"B\", \"D\", \"G\"), voltage=110, freq=60, country=\"Guyana\"),\n \"bb\": CountryPower(plugs=(\"A\", \"B\"), voltage=115, freq=50, country=\"Barbados\"),\n \"ke\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Kenya\"),\n \"mx\": CountryPower(plugs=(\"A\", \"B\"), voltage=127, freq=60, country=\"Mexico\"),\n \"gq\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Equatorial Guinea\"),\n \"gn\": CountryPower(plugs=(\"C\", \"F\", \"K\"), voltage=220, freq=50, country=\"Guinea\"),\n \"bi\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Burundi\"),\n \"lv\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Latvia\"),\n \"fj\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Fiji\"),\n \"ci\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"Côte d'Ivoire\"),\n \"ai\": CountryPower(plugs=(\"A\",), voltage=110, freq=60, country=\"Anguilla\"),\n \"gu\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Guam\"),\n \"lr\": CountryPower(plugs=(\"A\", \"B\", \"C\", \"E\", \"F\"), voltage=120, freq=60, country=\"Liberia\"),\n \"br\": CountryPower(plugs=(\"C\", \"N\"), voltage=220, freq=60, country=\"Brazil\"),\n \"cv\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Cape Verde\"),\n \"cl\": CountryPower(plugs=(\"L\",), voltage=220, freq=50, country=\"Chile\"),\n \"in\": CountryPower(plugs=(\"C\", \"D\", \"M\"), voltage=230, freq=50, country=\"India\"),\n \"gg\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Guernsey\"),\n \"tt\": CountryPower(plugs=(\"A\", \"B\"), voltage=115, freq=60, country=\"Trinidad & Tobago\"),\n \"de\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Germany\"),\n \"qa\": CountryPower(plugs=(\"D\", \"G\"), voltage=240, freq=50, country=\"Qatar\"),\n \"ph\": CountryPower(plugs=(\"A\", \"B\"), voltage=220, freq=60, country=\"Philippines\"),\n \"sd\": CountryPower(plugs=(\"C\", \"D\"), voltage=230, freq=50, country=\"Sudan\"),\n \"mm\": CountryPower(plugs=(\"C\", \"D\", \"F\", \"G\"), voltage=230, freq=50, country=\"Myanmar\"),\n \"gd\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Grenada\"),\n \"st\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"São Tomé and Príncipe\"),\n \"sz\": CountryPower(plugs=(\"M\",), voltage=230, freq=50, country=\"Swaziland\"),\n \"ro\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Romania\"),\n \"xk\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Kosovo\"),\n \"cy\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Cyprus\"),\n \"dz\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Algeria\"),\n \"zm\": CountryPower(plugs=(\"C\", \"D\", \"G\"), voltage=230, freq=50, country=\"Zambia\"),\n \"by\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Belarus\"),\n \"hr\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Croatia\"),\n \"lu\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Luxembourg\"),\n \"fi\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Finland\"),\n \"zw\": CountryPower(plugs=(\"D\", \"G\"), voltage=220, freq=50, country=\"Zimbabwe\"),\n \"km\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Comoros\"),\n \"tl\": CountryPower(plugs=(\"C\", \"E\", \"F\", \"I\"), voltage=220, freq=50, country=\"Timor-Leste \"),\n \"tz\": CountryPower(plugs=(\"D\", \"G\"), voltage=230, freq=50, country=\"Tanzania\"),\n \"ht\": CountryPower(plugs=(\"A\", \"B\"), voltage=110, freq=60, country=\"Haiti\"),\n \"vc\": CountryPower(plugs=(\"C\", \"E\", \"G\", \"I\", \"K\"), voltage=230, freq=50, country=\"St. Vincent and the Grenadines\"),\n \"es\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Spain\"),\n \"my\": CountryPower(plugs=(\"C\", \"G\", \"M\"), voltage=230, freq=50, country=\"Malaysia\"),\n \"lc\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"St. Lucia\"),\n \"tm\": CountryPower(plugs=(\"B\", \"C\", \"F\"), voltage=220, freq=50, country=\"Turkmenistan\"),\n \"pe\": CountryPower(plugs=(\"A\", \"B\", \"C\"), voltage=220, freq=60, country=\"Peru\"),\n \"ua\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Ukraine\"),\n \"eg\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Egypt\"),\n \"sb\": CountryPower(plugs=(\"I\", \"G\"), voltage=220, freq=50, country=\"Solomon Islands\"),\n \"to\": CountryPower(plugs=(\"I\",), voltage=240, freq=50, country=\"Tonga\"),\n \"fr\": CountryPower(plugs=(\"C\", \"E\"), voltage=230, freq=50, country=\"France\"),\n \"ng\": CountryPower(plugs=(\"D\", \"G\"), voltage=240, freq=50, country=\"Nigeria\"),\n \"sh\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Saint Helena, Ascension and Tristan da Cunha\"),\n \"mw\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Malawi\"),\n \"ms\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Montserrat\"),\n \"ae\": CountryPower(plugs=(\"C\", \"D\", \"G\"), voltage=220, freq=50, country=\"United Arab Emirates\"),\n \"nl\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Netherlands\"),\n \"id\": CountryPower(plugs=(\"C\", \"F\", \"G\"), voltage=230, freq=50, country=\"Indonesia\"),\n \"ru\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Russia\"),\n \"ar\": CountryPower(plugs=(\"C\", \"I\"), voltage=220, freq=50, country=\"Argentina\"),\n \"bn\": CountryPower(plugs=(\"G\",), voltage=240, freq=50, country=\"Brunei\"),\n \"pw\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Palau\"),\n \"kg\": CountryPower(plugs=(\"C\", \"F\"), voltage=220, freq=50, country=\"Kyrgyzstan\"),\n \"bh\": CountryPower(plugs=(\"G\",), voltage=230, freq=50, country=\"Bahrain\"),\n \"ml\": CountryPower(plugs=(\"C\", \"E\"), voltage=220, freq=50, country=\"Mali\"),\n \"it\": CountryPower(plugs=(\"C\", \"F\", \"L\"), voltage=230, freq=50, country=\"Italy\"),\n \"sa\": CountryPower(plugs=(\"A\", \"B\", \"G\"), voltage=220, freq=60, country=\"Saudi Arabia\"),\n \"ag\": CountryPower(plugs=(\"A\", \"B\"), voltage=230, freq=60, country=\"Antigua and Barbuda\"),\n \"mr\": CountryPower(plugs=(\"C\",), voltage=220, freq=50, country=\"Mauritania\"),\n \"om\": CountryPower(plugs=(\"C\", \"G\"), voltage=240, freq=50, country=\"Oman\"),\n \"lk\": CountryPower(plugs=(\"D\", \"G\", \"M\"), voltage=230, freq=50, country=\"Sri Lanka\"),\n \"er\": CountryPower(plugs=(\"C\", \"L\"), voltage=230, freq=50, country=\"Eritrea\"),\n \"mk\": CountryPower(plugs=(\"C\", \"F\"), voltage=230, freq=50, country=\"Macedonia\"),\n \"ni\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Nicaragua\"),\n \"ch\": CountryPower(plugs=(\"C\", \"J\"), voltage=230, freq=50, country=\"Switzerland\"),\n \"ca\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Canada\"),\n \"cr\": CountryPower(plugs=(\"A\", \"B\"), voltage=120, freq=60, country=\"Costa Rica\")\n}\n\nindustrial_power = {\n \"at\": CountryPower(voltage=TUP_400, freq=50, country=\"Austria\"),\n \"bj\": CountryPower(voltage=TUP_380, freq=50, country=\"Benin\"),\n \"gh\": CountryPower(voltage=TUP_400, freq=50, country=\"Ghana\"),\n \"sc\": CountryPower(voltage=TUP_240, freq=50, country=\"Seychelles\"),\n \"bg\": CountryPower(voltage=TUP_400, freq=50, country=\"Bulgaria\"),\n \"me\": CountryPower(voltage=TUP_400, freq=50, country=\"Montenegro\"),\n \"fo\": CountryPower(voltage=TUP_400, freq=50, country=\"Faeroe Islands\"),\n \"iq\": CountryPower(voltage=TUP_400, freq=50, country=\"Iraq\"),\n \"ne\": CountryPower(voltage=TUP_380, freq=50, country=\"Niger\"),\n \"za\": CountryPower(voltage=TUP_400, freq=50, country=\"South Africa\"),\n \"az\": CountryPower(voltage=TUP_380, freq=50, country=\"Azerbaijan\"),\n \"so\": CountryPower(voltage=TUP_380, freq=50, country=\"Somalia\"),\n \"sn\": CountryPower(voltage=TUP_400, freq=50, country=\"Senegal\"),\n \"np\": CountryPower(voltage=TUP_400, freq=50, country=\"Nepal\"),\n \"sl\": CountryPower(voltage=TUP_400, freq=50, country=\"Sierra Leone\"),\n \"be\": CountryPower(voltage=TUP_400, freq=50, country=\"Belgium\"),\n \"vg\": CountryPower(voltage=TUP_190, freq=60, country=\"British Virgin Islands\"),\n \"bz\": CountryPower(voltage=(190, CONST_380), freq=60, country=\"Belize\"),\n \"tw\": CountryPower(voltage=(220,), freq=60, country=\"Taiwan\"),\n \"bf\": CountryPower(voltage=TUP_380, freq=50, country=\"Burkina Faso\"),\n \"ao\": CountryPower(voltage=TUP_380, freq=50, country=\"Angola\"),\n \"ee\": CountryPower(voltage=TUP_400, freq=50, country=\"Estonia\"),\n \"bs\": CountryPower(voltage=TUP_208, freq=60, country=\"Bahamas\"),\n \"ir\": CountryPower(voltage=TUP_400, freq=50, country=\"Iran\"),\n \"sv\": CountryPower(voltage=(200,), freq=60, country=\"El Salvador\"),\n \"am\": CountryPower(voltage=TUP_400, freq=50, country=\"Armenia\"),\n \"is\": CountryPower(voltage=TUP_400, freq=50, country=\"Iceland\"),\n \"uy\": CountryPower(voltage=TUP_380, freq=50, country=\"Uruguay\"),\n \"mc\": CountryPower(voltage=TUP_400, freq=50, country=\"Monaco\"),\n \"jm\": CountryPower(voltage=TUP_190, freq=50, country=\"Jamaica\"),\n \"im\": CountryPower(voltage=TUP_415, freq=50, country=\"Isle of Man\"),\n \"dm\": CountryPower(voltage=TUP_400, freq=50, country=\"Dominica\"),\n \"mu\": CountryPower(voltage=TUP_400, freq=50, country=\"Mauritius\"),\n \"cz\": CountryPower(voltage=TUP_400, freq=50, country=\"Czech Republic\"),\n \"kh\": CountryPower(voltage=TUP_400, freq=50, country=\"Cambodia\"),\n \"cf\": CountryPower(voltage=TUP_380, freq=50, country=\"Central African Republic\"),\n \"se\": CountryPower(voltage=TUP_400, freq=50, country=\"Sweden\"),\n \"uz\": CountryPower(voltage=TUP_380, freq=50, country=\"Uzbekistan\"),\n \"sk\": CountryPower(voltage=TUP_400, freq=50, country=\"Slovakia\"),\n \"ky\": CountryPower(voltage=TUP_240, freq=60, country=\"Cayman Islands\"),\n \"tn\": CountryPower(voltage=TUP_400, freq=50, country=\"Tunisia\"),\n \"hu\": CountryPower(voltage=TUP_400, freq=50, country=\"Hungary\"),\n \"af\": CountryPower(voltage=TUP_380, freq=50, country=\"Afghanistan\"),\n \"tc\": CountryPower(voltage=TUP_240, freq=60, country=\"Turks and Caicos Islands\"),\n \"et\": CountryPower(voltage=TUP_380, freq=50, country=\"Ethiopia\"),\n \"sd\": CountryPower(voltage=TUP_400, freq=50, country=\"Sudan\"),\n \"ad\": CountryPower(voltage=TUP_400, freq=50, country=\"Andorra\"),\n \"hn\": CountryPower(voltage=(208, 230, 240, 460, CONST_480), freq=60, country=\"Honduras\"),\n \"ls\": CountryPower(voltage=TUP_380, freq=50, country=\"Lesotho\"),\n \"na\": CountryPower(voltage=TUP_380, freq=50, country=\"Namibia\"),\n \"pl\": CountryPower(voltage=TUP_400, freq=50, country=\"Poland\"),\n \"bt\": CountryPower(voltage=TUP_400, freq=50, country=\"Bhutan\"),\n \"sa\": CountryPower(voltage=TUP_400, freq=60, country=\"Saudi Arabia\"),\n \"no\": CountryPower(voltage=(230, 400), freq=50, country=\"Norway\"),\n \"fk\": CountryPower(voltage=TUP_415, freq=50, country=\"Falkland Islands\"),\n \"ye\": CountryPower(voltage=TUP_400, freq=50, country=\"Yemen\"),\n \"gi\": CountryPower(voltage=TUP_400, freq=50, country=\"Gibraltar\"),\n \"md\": CountryPower(voltage=TUP_400, freq=50, country=\"Moldova\"),\n \"cn\": CountryPower(voltage=TUP_380, freq=50, country=\"China\"),\n \"gm\": CountryPower(voltage=TUP_400, freq=50, country=\"Gambia\"),\n \"sg\": CountryPower(voltage=TUP_400, freq=50, country=\"Singapore\"),\n \"tj\": CountryPower(voltage=TUP_380, freq=50, country=\"Tajikistan\"),\n \"gt\": CountryPower(voltage=TUP_208, freq=60, country=\"Guatemala\"),\n \"ma\": CountryPower(voltage=TUP_380, freq=50, country=\"Morocco\"),\n \"mv\": CountryPower(voltage=TUP_400, freq=50, country=\"Maldives\"),\n \"ga\": CountryPower(voltage=TUP_380, freq=50, country=\"Gabon\"),\n \"bo\": CountryPower(voltage=TUP_400, freq=50, country=\"Bolivia\"),\n \"ly\": CountryPower(voltage=TUP_400, freq=50, country=\"Libya\"),\n \"rw\": CountryPower(voltage=TUP_400, freq=50, country=\"Rwanda\"),\n \"cg\": CountryPower(voltage=TUP_400, freq=50, country=\"People's Republic of Congo\"),\n \"kz\": CountryPower(voltage=TUP_380, freq=50, country=\"Kazakhstan\"),\n \"jp\": CountryPower(voltage=(200,), freq=50, country=\"Japan\"),\n \"co\": CountryPower(voltage=(220, 440), freq=60, country=\"Colombia\"),\n \"sm\": CountryPower(voltage=TUP_400, freq=50, country=\"San Marino\"),\n \"rs\": CountryPower(voltage=TUP_400, freq=50, country=\"Serbia\"),\n \"gw\": CountryPower(voltage=TUP_380, freq=50, country=\"Guinea-Bissau\"),\n \"kr\": CountryPower(voltage=TUP_380, freq=60, country=\"South Korea\"),\n \"py\": CountryPower(voltage=TUP_380, freq=50, country=\"Paraguay\"),\n \"lt\": CountryPower(voltage=TUP_400, freq=50, country=\"Lithuania\"),\n \"tr\": CountryPower(voltage=TUP_400, freq=50, country=\"Turkey\"),\n \"ss\": CountryPower(voltage=TUP_400, freq=50, country=\"South Sudan\"),\n \"ba\": CountryPower(voltage=TUP_400, freq=50, country=\"Bosnia & Herzegovina\"),\n \"vn\": CountryPower(voltage=TUP_380, freq=50, country=\"Vietnam\"),\n \"do\": CountryPower(voltage=(120, 208, 277, 480), freq=60, country=\"Dominican Republic\"),\n \"pk\": CountryPower(voltage=TUP_400, freq=50, country=\"Pakistan\"),\n \"li\": CountryPower(voltage=TUP_400, freq=50, country=\"Liechtenstein\"),\n \"mz\": CountryPower(voltage=TUP_380, freq=50, country=\"Mozambique\"),\n \"au\": CountryPower(voltage=TUP_400, freq=50, country=\"Australia\"),\n \"ws\": CountryPower(voltage=TUP_400, freq=50, country=\"Samoa\"),\n \"sr\": CountryPower(voltage=(220, 400,), freq=60, country=\"Suriname\"),\n \"mn\": CountryPower(voltage=TUP_400, freq=50, country=\"Mongolia\"),\n \"bw\": CountryPower(voltage=TUP_400, freq=50, country=\"Botswana\"),\n \"gb\": CountryPower(voltage=TUP_415, freq=50, country=\"United Kingdom\"),\n \"pg\": CountryPower(voltage=TUP_415, freq=50, country=\"Papua New Guinea\"),\n \"dj\": CountryPower(voltage=TUP_380, freq=50, country=\"Djibouti\"),\n \"th\": CountryPower(voltage=TUP_400, freq=50, country=\"Thailand\"),\n \"us\": CountryPower(voltage=(120, 208, 277, 480, 120, 240, 240, CONST_480), freq=60, country=\"United States of America\"),\n \"gr\": CountryPower(voltage=TUP_400, freq=50, country=\"Greece\"),\n \"ug\": CountryPower(voltage=TUP_415, freq=50, country=\"Uganda\"),\n \"ie\": CountryPower(voltage=TUP_415, freq=50, country=\"Ireland\"),\n \"tg\": CountryPower(voltage=TUP_380, freq=50, country=\"Togo\"),\n \"td\": CountryPower(voltage=TUP_380, freq=50, country=\"Chad\"),\n \"la\": CountryPower(voltage=TUP_400, freq=50, country=\"Laos\"),\n \"sy\": CountryPower(voltage=TUP_380, freq=50, country=\"Syria\"),\n \"bm\": CountryPower(voltage=TUP_208, freq=60, country=\"Bermuda\"),\n \"il\": CountryPower(voltage=TUP_400, freq=50, country=\"Israel\"),\n \"nz\": CountryPower(voltage=TUP_400, freq=50, country=\"New Zealand\"),\n \"mg\": CountryPower(voltage=TUP_380, freq=50, country=\"Madagascar\"),\n \"ve\": CountryPower(voltage=(120,), freq=60, country=\"Venezuela\"),\n \"dk\": CountryPower(voltage=TUP_400, freq=50, country=\"Denmark\"),\n \"lb\": CountryPower(voltage=TUP_400, freq=50, country=\"Lebanon\"),\n \"kp\": CountryPower(voltage=TUP_380, freq=50, country=\"North Korea\"),\n \"vu\": CountryPower(voltage=TUP_400, freq=50, country=\"Vanuatu\"),\n \"cu\": CountryPower(voltage=(190, 440), freq=60, country=\"Cuba\"),\n \"kw\": CountryPower(voltage=TUP_415, freq=50, country=\"Kuwait\"),\n \"cd\": CountryPower(voltage=TUP_380, freq=50, country=\"Democratic Republic of Congo\"),\n \"nr\": CountryPower(voltage=TUP_415, freq=50, country=\"Nauru\"),\n \"si\": CountryPower(voltage=TUP_400, freq=50, country=\"Slovenia\"),\n \"mt\": CountryPower(voltage=TUP_400, freq=50, country=\"Malta\"),\n \"bd\": CountryPower(voltage=TUP_380, freq=50, country=\"Bangladesh\"),\n \"al\": CountryPower(voltage=TUP_400, freq=50, country=\"Albania\"),\n \"ec\": CountryPower(voltage=TUP_208, freq=60, country=\"Ecuador\"),\n \"gy\": CountryPower(voltage=TUP_190, freq=60, country=\"Guyana\"),\n \"bb\": CountryPower(voltage=(200,), freq=50, country=\"Barbados\"),\n \"ke\": CountryPower(voltage=TUP_415, freq=50, country=\"Kenya\"),\n \"mx\": CountryPower(voltage=(220, CONST_480), freq=60, country=\"Mexico\"),\n \"gn\": CountryPower(voltage=TUP_380, freq=50, country=\"Guinea\"),\n \"bi\": CountryPower(voltage=TUP_380, freq=50, country=\"Burundi\"),\n \"lv\": CountryPower(voltage=TUP_400, freq=50, country=\"Latvia\"),\n \"fj\": CountryPower(voltage=TUP_415, freq=50, country=\"Fiji\"),\n \"ci\": CountryPower(voltage=TUP_380, freq=50, country=\"Côte d’Ivoire\"),\n \"ai\": CountryPower(voltage=(120, 208, 127, 220, 240, 415), freq=60, country=\"Anguilla\"),\n \"gu\": CountryPower(voltage=TUP_190, freq=60, country=\"Guam\"),\n \"lr\": CountryPower(voltage=TUP_208, freq=60, country=\"Liberia\"),\n \"br\": CountryPower(voltage=(220, 380), freq=60, country=\"Brazil\"),\n \"cv\": CountryPower(voltage=TUP_400, freq=50, country=\"Cape Verde\"),\n \"cl\": CountryPower(voltage=TUP_380, freq=50, country=\"Chile\"),\n \"in\": CountryPower(voltage=TUP_400, freq=50, country=\"India\"),\n \"tt\": CountryPower(voltage=(115, 230, 230, 400), freq=60, country=\"Trinidad & Tobago\"),\n \"de\": CountryPower(voltage=TUP_400, freq=50, country=\"Germany\"),\n \"pa\": CountryPower(voltage=TUP_240, freq=60, country=\"Panama\"),\n \"qa\": CountryPower(voltage=TUP_415, freq=50, country=\"Qatar\"),\n \"ph\": CountryPower(voltage=TUP_380, freq=60, country=\"Philippines\"),\n \"jo\": CountryPower(voltage=TUP_400, freq=50, country=\"Jordan\"),\n \"mm\": CountryPower(voltage=TUP_400, freq=50, country=\"Myanmar\"),\n \"gd\": CountryPower(voltage=TUP_400, freq=50, country=\"Grenada\"),\n \"st\": CountryPower(voltage=TUP_400, freq=50, country=\"São Tomé and Príncipe\"),\n \"sz\": CountryPower(voltage=TUP_400, freq=50, country=\"Swaziland\"),\n \"ro\": CountryPower(voltage=TUP_400, freq=50, country=\"Romania\"),\n \"xk\": CountryPower(voltage=(230, 400), freq=50, country=\"Kosovo\"),\n \"cy\": CountryPower(voltage=TUP_400, freq=50, country=\"Cyprus\"),\n \"dz\": CountryPower(voltage=TUP_400, freq=50, country=\"Algeria\"),\n \"zm\": CountryPower(voltage=TUP_400, freq=50, country=\"Zambia\"),\n \"by\": CountryPower(voltage=TUP_380, freq=50, country=\"Belarus\"),\n \"hr\": CountryPower(voltage=TUP_400, freq=50, country=\"Croatia\"),\n \"lu\": CountryPower(voltage=TUP_400, freq=50, country=\"Luxembourg\"),\n \"fi\": CountryPower(voltage=TUP_400, freq=50, country=\"Finland\"),\n \"zw\": CountryPower(voltage=TUP_415, freq=50, country=\"Zimbabwe\"),\n \"km\": CountryPower(voltage=TUP_380, freq=50, country=\"Comoros\"),\n \"tl\": CountryPower(voltage=TUP_380, freq=50, country=\"East Timor\"),\n \"tz\": CountryPower(voltage=TUP_415, freq=50, country=\"Tanzania\"),\n \"ht\": CountryPower(voltage=TUP_190, freq=60, country=\"Haiti\"),\n \"vc\": CountryPower(voltage=TUP_400, freq=50, country=\"Saint Vincent and the Grenadines\"),\n \"es\": CountryPower(voltage=TUP_400, freq=50, country=\"Spain\"),\n \"my\": CountryPower(voltage=TUP_415, freq=50, country=\"Malaysia\"),\n \"lc\": CountryPower(voltage=TUP_400, freq=50, country=\"Saint Lucia\"),\n \"tm\": CountryPower(voltage=TUP_380, freq=50, country=\"Turkmenistan\"),\n \"pe\": CountryPower(voltage=(220,), freq=60, country=\"Peru\"),\n \"ua\": CountryPower(voltage=TUP_400, freq=50, country=\"Ukraine\"),\n \"eg\": CountryPower(voltage=TUP_380, freq=50, country=\"Egypt\"),\n \"to\": CountryPower(voltage=TUP_415, freq=50, country=\"Tonga\"),\n \"fr\": CountryPower(voltage=TUP_400, freq=50, country=\"France\"),\n \"ng\": CountryPower(voltage=TUP_415, freq=50, country=\"Nigeria\"),\n \"mw\": CountryPower(voltage=TUP_400, freq=50, country=\"Malawi\"),\n \"ms\": CountryPower(voltage=TUP_400, freq=60, country=\"Montserrat\"),\n \"ae\": CountryPower(voltage=TUP_400, freq=50, country=\"United Arab Emirates\"),\n \"nl\": CountryPower(voltage=TUP_400, freq=50, country=\"Netherlands\"),\n \"id\": CountryPower(voltage=TUP_400, freq=50, country=\"Indonesia\"),\n \"ru\": CountryPower(voltage=TUP_380, freq=50, country=\"Russia\"),\n \"ar\": CountryPower(voltage=TUP_380, freq=50, country=\"Argentina\"),\n \"bn\": CountryPower(voltage=TUP_415, freq=50, country=\"Brunei\"),\n \"pw\": CountryPower(voltage=TUP_208, freq=60, country=\"Palau\"),\n \"kg\": CountryPower(voltage=TUP_380, freq=50, country=\"Kyrgyzstan\"),\n \"bh\": CountryPower(voltage=TUP_400, freq=50, country=\"Bahrain\"),\n \"ml\": CountryPower(voltage=TUP_380, freq=50, country=\"Mali\"),\n \"it\": CountryPower(voltage=TUP_400, freq=50, country=\"Italy\"),\n \"cm\": CountryPower(voltage=TUP_380, freq=50, country=\"Cameroon\"),\n \"ag\": CountryPower(voltage=TUP_400, freq=60, country=\"Antigua and Barbuda\"),\n \"mr\": CountryPower(voltage=(220,), freq=50, country=\"Mauritania\"),\n \"om\": CountryPower(voltage=TUP_415, freq=50, country=\"Oman\"),\n \"lk\": CountryPower(voltage=TUP_400, freq=50, country=\"Sri Lanka\"),\n \"er\": CountryPower(voltage=TUP_400, freq=50, country=\"Eritrea\"),\n \"mk\": CountryPower(voltage=TUP_400, freq=50, country=\"Macedonia, Republic of\"),\n \"ni\": CountryPower(voltage=TUP_208, freq=60, country=\"Nicaragua\"),\n \"ch\": CountryPower(voltage=TUP_400, freq=50, country=\"Switzerland\"),\n \"ca\": CountryPower(voltage=(120, 208, 240, CONST_480, 347, 600), freq=60, country=\"Canada\"),\n \"cr\": CountryPower(voltage=TUP_240, freq=60, country=\"Costa Rica\")\n}\n\nelectrical_plug_types = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\"]\n\nvoltages_1_phase_residential = [100, 110, 115, 120, 127, 220, 230, 240]\n\nvoltages_3_phase = [120, 190, 200, 208, 220, 230, 240, 277, 380, 400, 415, 440, 480]\n\nresidential_power_frequencies = [50, 60]", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 31977}, "tests/test_safety_valve.py::120": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/numerics/__init__.py", "fluids/safety_valve.py"], "used_names": ["API520_SH", "_KSH_K_10E", "_KSH_Pa_10E", "_KSH_Pa_7E", "_KSH_tempKs_7E", "assert_close", "linspace", "pytest"], "enclosing_function": "test_API520_SH", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):\n \"\"\"Port of numpy's linspace to pure python.\n\n Does not support dtype, and returns lists of floats.\n \"\"\"\n num = int(num)\n start = start * 1.\n stop = stop * 1.\n\n if num <= 0:\n return []\n if endpoint:\n if num == 1:\n return [start]\n step = (stop-start)/float(num-1)\n if num == 1:\n step = nan\n\n y = [start]\n for _ in range(num-2):\n y.append(y[-1] + step)\n y.append(stop)\n else:\n step = (stop-start)/float(num)\n if num == 1:\n step = nan\n y = [start]\n for _ in range(num-1):\n y.append(y[-1] + step)\n\n if retstep:\n return y, step\n else:\n return y\n\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/safety_valve.py\ndef API520_SH(T1, P1, edition=TENTH_EDITION):\n r\"\"\"Calculates correction due to steam superheat for steam flow for use in\n API 520 relief valve sizing. 2D interpolation among a table with 28\n pressures and 10 temperatures is performed.\n\n\n Parameters\n ----------\n T1 : float\n Temperature of the fluid entering the valve [K]\n P1 : float\n Upstream relieving pressure; the set pressure plus the allowable\n overpressure, plus atmospheric pressure, [Pa]\n edition : str, optional\n One of '10E', '7E', [-]\n\n Returns\n -------\n KSH : float\n Correction due to steam superheat [-]\n\n Notes\n -----\n For P above 20679 kPag, use the critical flow model.\n Superheat cannot be above 649 degrees Celsius.\n If T1 is above 149 degrees Celsius, returns 1.\n\n Examples\n --------\n Custom example from table 9, 7th edition:\n\n >>> API520_SH(593+273.15, 1066.325E3, '7E')\n 0.7201800000\n\n References\n ----------\n .. [1] API Standard 520, Part 1 - Sizing and Selection.\n \"\"\"\n if T1 > 922.15:\n raise ValueError(\"Superheat cannot be above 649 degrees Celcius\")\n if edition == SEVENTH_EDITION:\n if P1 > 20780325.0: # 20679E3+atm\n raise ValueError(\"For P above 20679 kPag, use the gas flow model\")\n if T1 < 422.15:\n return 1. # No superheat under 15 psig\n return float(bisplev(T1, P1, API520_KSH_tck_7E))\n elif edition == TENTH_EDITION:\n if T1 < 478.15:\n # Avoid extrapolating above 1.0\n return 1.0\n if P1 > 22063223.338138755:\n raise ValueError(\"For P1 above 22.06 MPa, use the gas flow model\")\n return float(bisplev(T1, P1, API520_KSH_tck_10E))\n else:\n raise ValueError(\"Acceptable editions are '7E', '10E'\")", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 3249}, "tests/test_control_valve.py::47": {"resolved_imports": ["fluids/control_valve.py", "fluids/fittings.py", "fluids/numerics/__init__.py"], "used_names": ["FF_critical_pressure_ratio_l", "Reynolds_factor", "Reynolds_valve", "assert_close", "cavitation_index", "control_valve_choke_P_g", "is_choked_turbulent_g", "is_choked_turbulent_l", "loss_coefficient_piping", "pytest"], "enclosing_function": "test_control_valve", "extracted_code": "# Source: fluids/control_valve.py\ndef cavitation_index(P1: float, P2: float, Psat: float) -> float:\n r\"\"\"Calculates the cavitation index of a valve with upstream and downstream\n absolute pressures `P1` and `P2` for a fluid with a vapor pressure `Psat`.\n\n .. math::\n \\sigma = \\frac{P_1 - P_{sat}}{P_1 - P_2}\n\n Parameters\n ----------\n P1 : float\n Absolute pressure upstream of the valve [Pa]\n P2 : float\n Absolute pressure downstream of the valve [Pa]\n Psat : float\n Saturation pressure of the liquid at inlet temperature [Pa]\n\n Returns\n -------\n sigma : float\n Cavitation index of the valve [-]\n\n Notes\n -----\n Larger values are safer. Models for adjusting cavitation indexes provided\n by the manufacturer to the user's conditions are available, making use\n of scaling the pressure differences and size differences.\n\n Values can be calculated for incipient cavitation, constant cavitation,\n maximum vibration cavitation, incipient damage, and choking cavitation.\n\n Has also been defined as:\n\n .. math::\n \\sigma = \\frac{P_2 - P_{sat}}{P_1 - P_2}\n\n Another definition and notation series is:\n\n .. math::\n K = xF = \\frac{1}{\\sigma} = \\frac{P_1 - P_2}{P_1 - P_{sat}}\n\n Examples\n --------\n >>> cavitation_index(1E6, 8E5, 2E5)\n 4.0\n\n References\n ----------\n .. [1] ISA. \"RP75.23 Considerations for Evaluating Control Valve\n Cavitation.\" 1995.\n \"\"\"\n return (P1 - Psat)/(P1 - P2)\n\ndef FF_critical_pressure_ratio_l(Psat: float, Pc: float) -> float:\n r\"\"\"Calculates FF, the liquid critical pressure ratio factor,\n for use in IEC 60534 liquid valve sizing calculations.\n\n .. math::\n F_F = 0.96 - 0.28\\sqrt{\\frac{P_{sat}}{P_c}}\n\n Parameters\n ----------\n Psat : float\n Saturation pressure of the liquid at inlet temperature [Pa]\n Pc : float\n Critical pressure of the liquid [Pa]\n\n Returns\n -------\n FF : float\n Liquid critical pressure ratio factor [-]\n\n Examples\n --------\n From [1]_, matching example.\n\n >>> FF_critical_pressure_ratio_l(70100.0, 22120000.0)\n 0.9442375225233299\n\n References\n ----------\n .. [1] IEC 60534-2-1 / ISA-75.01.01-2007\n \"\"\"\n return 0.96 - 0.28*sqrt(Psat/Pc)\n\ndef control_valve_choke_P_g(xT: float, gamma: float, P1: float | None=None, P2: float | None=None) -> float:\n r\"\"\"Calculates either the upstream or downstream pressure at which choked\n flow though a gas control valve occurs, given either a set upstream or\n downstream pressure. Implements an analytical solution of\n the needed equations from the full function\n :py:func:`~.size_control_valve_g`. A singularity arises as `xT` goes to 1\n and `gamma` goes to 1.4.\n\n .. math::\n P_1 = - \\frac{7 P_{2}}{5 \\gamma x_T - 7}\n\n .. math::\n P_2 = \\frac{P_{1}}{7} \\left(- 5 \\gamma x_T + 7\\right)\n\n Parameters\n ----------\n xT : float, optional\n Pressure difference ratio factor of a valve without fittings at choked\n flow [-]\n gamma : float\n Specific heat capacity ratio [-]\n P1 : float, optional\n Absolute pressure upstream of the valve [Pa]\n P2 : float, optional\n Absolute pressure downstream of the valve [Pa]\n\n Returns\n -------\n P_choke : float\n Pressure at which a choke occurs in the gas valve [Pa]\n\n Notes\n -----\n Extremely cheap to compute.\n\n Examples\n --------\n >>> control_valve_choke_P_g(1.0, 1.3, 1E5)\n 7142.857142857143\n >>> control_valve_choke_P_g(1.0, 1.3, P2=7142.857142857143)\n 100000.0\n \"\"\"\n if P2 is None:\n if P1 is None:\n raise ValueError(\"Either P1 or P2 needs to be specified\")\n ans = P2 = P1*(-5.0*gamma*xT + 7.0)/7.0\n elif P1 is None:\n ans = P1 = -7.0*P2/(5.0*gamma*xT - 7.0)\n else:\n raise ValueError(\"Either P1 or P2 needs to be specified\")\n return ans\n\ndef is_choked_turbulent_l(dP: float, P1: float, Psat: float, FF: float, FL: float | None=None, FLP: float | None=None, FP: float | None=None) -> bool:\n r\"\"\"Calculates if a liquid flow in IEC 60534 calculations is critical or\n not, for use in IEC 60534 liquid valve sizing calculations.\n Either FL may be provided or FLP and FP, depending on the calculation\n process.\n\n .. math::\n \\Delta P > F_L^2(P_1 - F_F P_{sat})\n\n .. math::\n \\Delta P >= \\left(\\frac{F_{LP}}{F_P}\\right)^2(P_1 - F_F P_{sat})\n\n Parameters\n ----------\n dP : float\n Differential pressure across the valve, with reducer/expanders [Pa]\n P1 : float\n Pressure of the fluid before the valve and reducers/expanders [Pa]\n Psat : float\n Saturation pressure of the fluid at inlet temperature [Pa]\n FF : float\n Liquid critical pressure ratio factor [-]\n FL : float, optional\n Liquid pressure recovery factor of a control valve without attached fittings [-]\n FLP : float, optional\n Combined liquid pressure recovery factor with piping geometry factor,\n for a control valve with attached fittings [-]\n FP : float, optional\n Piping geometry factor [-]\n\n Returns\n -------\n choked : bool\n Whether or not the flow is choked [-]\n\n Examples\n --------\n >>> is_choked_turbulent_l(460.0, 680.0, 70.1, 0.94, 0.9)\n False\n >>> is_choked_turbulent_l(460.0, 680.0, 70.1, 0.94, 0.6)\n True\n\n References\n ----------\n .. [1] IEC 60534-2-1 / ISA-75.01.01-2007\n \"\"\"\n if FLP and FP:\n return dP >= FLP*FLP/(FP*FP)*(P1-FF*Psat)\n elif FL:\n return dP >= FL*FL*(P1-FF*Psat)\n else:\n raise ValueError(\"Either (FLP and FP) or FL is needed\")\n\ndef is_choked_turbulent_g(x: float, Fgamma: float, xT: float | None=None, xTP: float | None=None) -> bool:\n r\"\"\"Calculates if a gas flow in IEC 60534 calculations is critical or\n not, for use in IEC 60534 gas valve sizing calculations.\n Either xT or xTP must be provided, depending on the calculation process.\n\n .. math::\n x \\ge F_\\gamma x_T\n\n .. math::\n x \\ge F_\\gamma x_{TP}\n\n Parameters\n ----------\n x : float\n Differential pressure over inlet pressure, [-]\n Fgamma : float\n Specific heat ratio factor [-]\n xT : float, optional\n Pressure difference ratio factor of a valve without fittings at choked\n flow [-]\n xTP : float\n Pressure difference ratio factor of a valve with fittings at choked\n flow [-]\n\n Returns\n -------\n choked : bool\n Whether or not the flow is choked [-]\n\n Examples\n --------\n Example 3, compressible flow, non-choked with attached fittings:\n\n >>> is_choked_turbulent_g(0.544, 0.929, 0.6)\n False\n >>> is_choked_turbulent_g(0.544, 0.929, xTP=0.625)\n False\n\n References\n ----------\n .. [1] IEC 60534-2-1 / ISA-75.01.01-2007\n \"\"\"\n if xT:\n return x >= Fgamma*xT\n elif xTP:\n return x >= Fgamma*xTP\n else:\n raise ValueError(\"Either xT or xTP is needed\")\n\ndef Reynolds_valve(nu: float, Q: float, D1: float, FL: float, Fd: float, C: float) -> float:\n r\"\"\"Calculates Reynolds number of a control valve for a liquid or gas\n flowing through it at a specified Q, for a specified D1, FL, Fd, C, and\n with kinematic viscosity `nu` according to IEC 60534 calculations.\n\n .. math::\n Re_v = \\frac{N_4 F_d Q}{\\nu \\sqrt{C F_L}}\\left(\\frac{F_L^2 C^2}\n {N_2D^4} +1\\right)^{1/4}\n\n Parameters\n ----------\n nu : float\n Kinematic viscosity, [m^2/s]\n Q : float\n Volumetric flow rate of the fluid [m^3/s]\n D1 : float\n Diameter of the pipe before the valve [m]\n FL : float, optional\n Liquid pressure recovery factor of a control valve without attached\n fittings [-]\n Fd : float\n Valve style modifier [-]\n C : float\n Metric Kv valve flow coefficient (flow rate of water at a pressure drop\n of 1 bar) [m^3/hr]\n\n Returns\n -------\n Rev : float\n Valve reynolds number [-]\n\n Examples\n --------\n >>> Reynolds_valve(3.26e-07, 360, 150.0, 0.9, 0.46, 165)\n 2966984.7525455453\n\n References\n ----------\n .. [1] IEC 60534-2-1 / ISA-75.01.01-2007\n \"\"\"\n return N4*Fd*Q/nu*1.0/sqrt(C*FL)*sqrt(sqrt(FL*FL*C*C/N2*D1**-4.0 + 1.0))\n\ndef loss_coefficient_piping(d: float, D1: float | None=None, D2: float | None=None) -> float:\n r\"\"\"Calculates the sum of loss coefficients from possible\n inlet/outlet reducers/expanders around a control valve according to\n IEC 60534 calculations.\n\n .. math::\n \\Sigma \\xi = \\xi_1 + \\xi_2 + \\xi_{B1} - \\xi_{B2}\n\n .. math::\n \\xi_1 = 0.5\\left[1 -\\left(\\frac{d}{D_1}\\right)^2\\right]^2\n\n .. math::\n \\xi_2 = 1.0\\left[1 -\\left(\\frac{d}{D_2}\\right)^2\\right]^2\n\n .. math::\n \\xi_{B1} = 1 - \\left(\\frac{d}{D_1}\\right)^4\n\n .. math::\n \\xi_{B2} = 1 - \\left(\\frac{d}{D_2}\\right)^4\n\n Parameters\n ----------\n d : float\n Diameter of the valve [m]\n D1 : float\n Diameter of the pipe before the valve [m]\n D2 : float\n Diameter of the pipe after the valve [m]\n\n Returns\n -------\n loss : float\n Sum of the four loss coefficients [-]\n\n Examples\n --------\n In example 3, non-choked compressible flow with fittings:\n\n >>> loss_coefficient_piping(0.05, 0.08, 0.1)\n 0.6580810546875\n\n References\n ----------\n .. [1] IEC 60534-2-1 / ISA-75.01.01-2007\n \"\"\"\n loss = 0.\n if D1:\n dr = d/D1\n dr2 = dr*dr\n loss += 1. - dr2*dr2 # Inlet flow energy\n loss += 0.5*(1. - dr2)*(1.0 - dr2) # Inlet reducer\n if D2:\n dr = d/D2\n dr2 = dr*dr\n loss += 1.0*(1. - dr2)*(1.0 - dr2) # Outlet reducer (expander)\n loss -= 1. - dr2*dr2 # Outlet flow energy\n return loss\n\ndef Reynolds_factor(FL: float, C: float, d: float, Rev: float, full_trim: bool=True) -> float:\n r\"\"\"Calculates the Reynolds number factor `FR` for a valve with a Reynolds\n number `Rev`, diameter `d`, flow coefficient `C`, liquid pressure recovery\n factor `FL`, and with either full or reduced trim, all according to\n IEC 60534 calculations.\n\n\n If full trim:\n\n .. math::\n F_{R,1a} = 1 + \\left(\\frac{0.33F_L^{0.5}}{n_1^{0.25}}\\right)\\log_{10}\n \\left(\\frac{Re_v}{10000}\\right)\n\n .. math::\n F_{R,2} = \\min(\\frac{0.026}{F_L}\\sqrt{n_1 Re_v},\\; 1)\n\n .. math::\n n_1 = \\frac{N_2}{\\left(\\frac{C}{d^2}\\right)^2}\n\n .. math::\n F_R = F_{R,2} \\text{ if Rev < 10 else } \\min(F_{R,1a}, F_{R,2})\n\n Otherwise :\n\n .. math::\n F_{R,3a} = 1 + \\left(\\frac{0.33F_L^{0.5}}{n_2^{0.25}}\\right)\\log_{10}\n \\left(\\frac{Re_v}{10000}\\right)\n\n .. math::\n F_{R,4} = \\frac{0.026}{F_L}\\sqrt{n_2 Re_v}\n\n .. math::\n n_2 = 1 + N_{32}\\left(\\frac{C}{d}\\right)^{2/3}\n\n .. math::\n F_R = F_{R,4} \\text{ if Rev < 10 else } \\min(F_{R,3a}, F_{R,4})\n\n Parameters\n ----------\n FL : float\n Liquid pressure recovery factor of a control valve without attached\n fittings []\n C : float\n Metric Kv valve flow coefficient (flow rate of water at a pressure drop\n of 1 bar) [m^3/hr]\n d : float\n Diameter of the valve [m]\n Rev : float\n Valve reynolds number [-]\n full_trim : bool\n Whether or not the valve has full trim\n\n Returns\n -------\n FR : float\n Reynolds number factor for laminar or transitional flow []\n\n Examples\n --------\n In Example 4, compressible flow with small flow trim sized for gas flow\n (Cv in the problem was converted to Kv here to make FR match with N32, N2):\n\n >>> Reynolds_factor(FL=0.98, C=0.015483, d=15., Rev=1202., full_trim=False)\n 0.7148753122302025\n\n\n References\n ----------\n .. [1] IEC 60534-2-1 / ISA-75.01.01-2007\n \"\"\"\n if full_trim:\n n1 = N2/(min(C/(d*d), 0.04))**2 # C/d**2 must not exceed 0.04\n FR_1a = 1.0 + (0.33*sqrt(FL))/sqrt(sqrt(n1))*log10(Rev/10000.)\n FR_2 = 0.026/FL*sqrt(n1*Rev)\n if Rev < 10.0:\n FR = FR_2\n else:\n FR = min(FR_2, FR_1a)\n else:\n n2 = 1 + N32*(C/d**2)**(2/3.)\n FR_3a = 1 + (0.33*sqrt(FL))/sqrt(sqrt(n2))*log10(Rev/10000.)\n FR_4 = min(0.026/FL*sqrt(n2*Rev), 1)\n if Rev < 10:\n FR = FR_4\n else:\n FR = min(FR_3a, FR_4)\n return FR\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 13055}, "tests/test_core.py::155": {"resolved_imports": ["fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["Archimedes", "Bejan_L", "Bejan_p", "Biot", "Boiling", "Bond", "Capillary", "Cavitation", "Confinement", "Dean", "Drag", "Eckert", "Euler", "Fourier_heat", "Fourier_mass", "Froude", "Froude_densimetric", "Graetz_heat", "Grashof", "Hagen", "Jakob", "Knudsen", "Lewis", "Mach", "Morton", "Nusselt", "Ohnesorge", "Peclet_heat", "Peclet_mass", "Power_number", "Prandtl", "Rayleigh", "Reynolds", "Schmidt", "Sherwood", "Stanton", "Stokes_number", "Strouhal", "Suratman", "Weber", "assert_close", "assert_close1d", "pytest", "relative_roughness"], "enclosing_function": "test_core_dimensionless", "extracted_code": "# Source: fluids/core.py\ndef Reynolds(V: float, D: float, rho: float | None=None, mu: float | None=None, nu: float | None=None) -> float:\n r\"\"\"Calculates Reynolds number or `Re` for a fluid with the given\n properties for the specified velocity and diameter.\n\n .. math::\n Re = \\frac{D \\cdot V}{\\nu} = \\frac{\\rho V D}{\\mu}\n\n Inputs either of any of the following sets:\n\n * V, D, density `rho` and dynamic viscosity `mu`\n * V, D, and kinematic viscosity `nu`\n\n Parameters\n ----------\n V : float\n Velocity [m/s]\n D : float\n Diameter [m]\n rho : float, optional\n Density, [kg/m^3]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n\n Returns\n -------\n Re : float\n Reynolds number []\n\n Notes\n -----\n .. math::\n Re = \\frac{\\text{Momentum}}{\\text{Viscosity}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Reynolds(2.5, 0.25, 1.1613, 1.9E-5)\n 38200.65789473684\n >>> Reynolds(2.5, 0.25, nu=1.636e-05)\n 38202.93398533008\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and mu is not None:\n nu = mu/rho\n elif nu is None:\n raise ValueError(\"Either density and viscosity, or kinematic viscosity is needed\")\n return V*D/nu\n\ndef Peclet_heat(V: float, L: float, rho: float | None=None, Cp: float | None=None, k: float | None=None, alpha: float | None=None) -> float:\n r\"\"\"Calculates heat transfer Peclet number or `Pe` for a specified velocity\n `V`, characteristic length `L`, and specified properties for the given\n fluid.\n\n .. math::\n Pe = \\frac{VL\\rho C_p}{k} = \\frac{LV}{\\alpha}\n\n Inputs either of any of the following sets:\n\n * V, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k`\n * V, L, and thermal diffusivity `alpha`\n\n Parameters\n ----------\n V : float\n Velocity [m/s]\n L : float\n Characteristic length [m]\n rho : float, optional\n Density, [kg/m^3]\n Cp : float, optional\n Heat capacity, [J/kg/K]\n k : float, optional\n Thermal conductivity, [W/m/K]\n alpha : float, optional\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Pe : float\n Peclet number (heat) []\n\n Notes\n -----\n .. math::\n Pe = \\frac{\\text{Bulk heat transfer}}{\\text{Conduction heat transfer}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Peclet_heat(1.5, 2, 1000., 4000., 0.6)\n 20000000.0\n >>> Peclet_heat(1.5, 2, alpha=1E-7)\n 30000000.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and Cp is not None and k is not None:\n alpha = k/(rho*Cp)\n elif alpha is None:\n raise ValueError(\"Either heat capacity and thermal conductivity and density, or thermal diffusivity is needed\")\n return V*L/alpha\n\ndef Peclet_mass(V: float, L: float, D: float) -> float:\n r\"\"\"Calculates mass transfer Peclet number or `Pe` for a specified velocity\n `V`, characteristic length `L`, and diffusion coefficient `D`.\n\n .. math::\n Pe = \\frac{L V}{D}\n\n Parameters\n ----------\n V : float\n Velocity [m/s]\n L : float\n Characteristic length [m]\n D : float\n Diffusivity of a species, [m^2/s]\n\n Returns\n -------\n Pe : float\n Peclet number (mass) []\n\n Notes\n -----\n .. math::\n Pe = \\frac{\\text{Advective transport rate}}{\\text{Diffusive transport rate}}\n\n Examples\n --------\n >>> Peclet_mass(1.5, 2, 1E-9)\n 3000000000.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return V*L/D\n\ndef Fourier_heat(t: float, L: float, rho: float | None=None, Cp: float | None=None, k: float | None=None, alpha: float | None=None) -> float:\n r\"\"\"Calculates heat transfer Fourier number or `Fo` for a specified time\n `t`, characteristic length `L`, and specified properties for the given\n fluid.\n\n .. math::\n Fo = \\frac{k t}{C_p \\rho L^2} = \\frac{\\alpha t}{L^2}\n\n Inputs either of any of the following sets:\n\n * t, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k`\n * t, L, and thermal diffusivity `alpha`\n\n Parameters\n ----------\n t : float\n time [s]\n L : float\n Characteristic length [m]\n rho : float, optional\n Density, [kg/m^3]\n Cp : float, optional\n Heat capacity, [J/kg/K]\n k : float, optional\n Thermal conductivity, [W/m/K]\n alpha : float, optional\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Fo : float\n Fourier number (heat) []\n\n Notes\n -----\n .. math::\n Fo = \\frac{\\text{Heat conduction rate}}\n {\\text{Rate of thermal energy storage in a solid}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Fourier_heat(t=1.5, L=2, rho=1000., Cp=4000., k=0.6)\n 5.625e-08\n >>> Fourier_heat(1.5, 2, alpha=1E-7)\n 3.75e-08\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and Cp is not None and k is not None:\n alpha = k/(rho*Cp)\n elif alpha is None:\n raise ValueError(\"Either heat capacity and thermal conductivity and density, or thermal diffusivity is needed\")\n return t*alpha/(L*L)\n\ndef Fourier_mass(t: float, L: float, D: float) -> float:\n r\"\"\"Calculates mass transfer Fourier number or `Fo` for a specified time\n `t`, characteristic length `L`, and diffusion coefficient `D`.\n\n .. math::\n Fo = \\frac{D t}{L^2}\n\n Parameters\n ----------\n t : float\n time [s]\n L : float\n Characteristic length [m]\n D : float\n Diffusivity of a species, [m^2/s]\n\n Returns\n -------\n Fo : float\n Fourier number (mass) []\n\n Notes\n -----\n .. math::\n Fo = \\frac{\\text{Diffusive transport rate}}{\\text{Storage rate}}\n\n Examples\n --------\n >>> Fourier_mass(t=1.5, L=2, D=1E-9)\n 3.7500000000000005e-10\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return t*D/(L*L)\n\ndef Graetz_heat(V: float, D: float, x: float, rho: float | None=None, Cp: float | None=None, k: float | None=None, alpha: float | None=None) -> float:\n r\"\"\"Calculates Graetz number or `Gz` for a specified velocity\n `V`, diameter `D`, axial distance `x`, and specified properties for the\n given fluid.\n\n .. math::\n Gz = \\frac{VD^2\\cdot C_p \\rho}{x\\cdot k} = \\frac{VD^2}{x \\alpha}\n\n Inputs either of any of the following sets:\n\n * V, D, x, density `rho`, heat capacity `Cp`, and thermal conductivity `k`\n * V, D, x, and thermal diffusivity `alpha`\n\n Parameters\n ----------\n V : float\n Velocity, [m/s]\n D : float\n Diameter [m]\n x : float\n Axial distance [m]\n rho : float, optional\n Density, [kg/m^3]\n Cp : float, optional\n Heat capacity, [J/kg/K]\n k : float, optional\n Thermal conductivity, [W/m/K]\n alpha : float, optional\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Gz : float\n Graetz number []\n\n Notes\n -----\n .. math::\n Gz = \\frac{\\text{Time for radial heat diffusion in a fluid by conduction}}\n {\\text{Time taken by fluid to reach distance x}}\n\n .. math::\n Gz = \\frac{D}{x}RePr\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Graetz_heat(1.5, 0.25, 5, 800., 2200., 0.6)\n 55000.0\n >>> Graetz_heat(1.5, 0.25, 5, alpha=1E-7)\n 187500.0\n\n References\n ----------\n .. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n Wiley, 2011.\n \"\"\"\n if rho is not None and Cp is not None and k is not None:\n alpha = k/(rho*Cp)\n elif alpha is None:\n raise ValueError(\"Either heat capacity and thermal conductivity and density, or thermal diffusivity is needed\")\n return V*D*D/(x*alpha)\n\ndef Schmidt(D: float, mu: float | None=None, nu: float | None=None, rho: float | None=None) -> float:\n r\"\"\"Calculates Schmidt number or `Sc` for a fluid with the given\n parameters.\n\n .. math::\n Sc = \\frac{\\mu}{D\\rho} = \\frac{\\nu}{D}\n\n Inputs can be any of the following sets:\n\n * Diffusivity, dynamic viscosity, and density\n * Diffusivity and kinematic viscosity\n\n Parameters\n ----------\n D : float\n Diffusivity of a species, [m^2/s]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n rho : float, optional\n Density, [kg/m^3]\n\n Returns\n -------\n Sc : float\n Schmidt number []\n\n Notes\n -----\n .. math::\n Sc =\\frac{\\text{kinematic viscosity}}{\\text{molecular diffusivity}}\n = \\frac{\\text{viscous diffusivity}}{\\text{species diffusivity}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Schmidt(D=2E-6, mu=4.61E-6, rho=800)\n 0.00288125\n >>> Schmidt(D=1E-9, nu=6E-7)\n 599.9999999999999\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and mu is not None:\n return mu/(rho*D)\n elif nu is not None:\n return nu/D\n else:\n raise ValueError(\"Insufficient information provided for Schmidt number calculation\")\n\ndef Lewis(D: float, alpha: float | None=None, Cp: float | None=None, k: float | None=None, rho: float | None=None) -> float:\n r\"\"\"Calculates Lewis number or `Le` for a fluid with the given parameters.\n\n .. math::\n Le = \\frac{k}{\\rho C_p D} = \\frac{\\alpha}{D}\n\n Inputs can be either of the following sets:\n\n * Diffusivity and Thermal diffusivity\n * Diffusivity, heat capacity, thermal conductivity, and density\n\n Parameters\n ----------\n D : float\n Diffusivity of a species, [m^2/s]\n alpha : float, optional\n Thermal diffusivity, [m^2/s]\n Cp : float, optional\n Heat capacity, [J/kg/K]\n k : float, optional\n Thermal conductivity, [W/m/K]\n rho : float, optional\n Density, [kg/m^3]\n\n Returns\n -------\n Le : float\n Lewis number []\n\n Notes\n -----\n .. math::\n Le=\\frac{\\text{Thermal diffusivity}}{\\text{Mass diffusivity}} =\n \\frac{Sc}{Pr}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Lewis(D=22.6E-6, alpha=19.1E-6)\n 0.8451327433628318\n >>> Lewis(D=22.6E-6, rho=800., k=.2, Cp=2200)\n 0.00502815768302494\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n Berlin; New York:: Springer, 2010.\n \"\"\"\n if D is None:\n raise ValueError(\"Diffusivity D is required for Le calculation\")\n if k is not None and Cp is not None and rho is not None:\n alpha = k/(rho*Cp)\n elif alpha is None:\n raise ValueError(\"Insufficient information provided for Le calculation\")\n return alpha/D\n\ndef Weber(V: float, L: float, rho: float, sigma: float) -> float:\n r\"\"\"Calculates Weber number, `We`, for a fluid with the given density,\n surface tension, velocity, and geometric parameter (usually diameter\n of bubble).\n\n .. math::\n We = \\frac{V^2 L\\rho}{\\sigma}\n\n Parameters\n ----------\n V : float\n Velocity of fluid, [m/s]\n L : float\n Characteristic length, typically bubble diameter [m]\n rho : float\n Density of fluid, [kg/m^3]\n sigma : float\n Surface tension, [N/m]\n\n Returns\n -------\n We : float\n Weber number []\n\n Notes\n -----\n Used in bubble calculations.\n\n .. math::\n We = \\frac{\\text{inertial force}}{\\text{surface tension force}}\n\n Examples\n --------\n >>> Weber(V=0.18, L=0.001, rho=900., sigma=0.01)\n 2.916\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n Berlin; New York:: Springer, 2010.\n \"\"\"\n return V*V*L*rho/sigma\n\ndef Mach(V: float, c: float) -> float:\n r\"\"\"Calculates Mach number or `Ma` for a fluid of velocity `V` with speed\n of sound `c`.\n\n .. math::\n Ma = \\frac{V}{c}\n\n Parameters\n ----------\n V : float\n Velocity of fluid, [m/s]\n c : float\n Speed of sound in fluid, [m/s]\n\n Returns\n -------\n Ma : float\n Mach number []\n\n Notes\n -----\n Used in compressible flow calculations.\n\n .. math::\n Ma = \\frac{\\text{fluid velocity}}{\\text{sonic velocity}}\n\n Examples\n --------\n >>> Mach(33., 330)\n 0.1\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return V/c\n\ndef Confinement(D: float, rhol: float, rhog: float, sigma: float, g: float=g) -> float:\n r\"\"\"Calculates Confinement number or `Co` for a fluid in a channel of\n diameter `D` with liquid and gas densities `rhol` and `rhog` and surface\n tension `sigma`, under the influence of gravitational force `g`.\n\n .. math::\n \\text{Co}=\\frac{\\left[\\frac{\\sigma}{g(\\rho_l-\\rho_g)}\\right]^{0.5}}{D}\n\n Parameters\n ----------\n D : float\n Diameter of channel, [m]\n rhol : float\n Density of liquid phase, [kg/m^3]\n rhog : float\n Density of gas phase, [kg/m^3]\n sigma : float\n Surface tension between liquid-gas phase, [N/m]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Co : float\n Confinement number [-]\n\n Notes\n -----\n Used in two-phase pressure drop and heat transfer correlations. First used\n in [1]_ according to [3]_.\n\n .. math::\n \\text{Co} = \\frac{\\frac{\\text{surface tension force}}\n {\\text{buoyancy force}}}{\\text{Channel area}}\n\n Examples\n --------\n >>> Confinement(0.001, 1077, 76.5, 4.27E-3)\n 0.6596978265315191\n\n References\n ----------\n .. [1] Cornwell, Keith, and Peter A. Kew. \"Boiling in Small Parallel\n Channels.\" In Energy Efficiency in Process Technology, edited by Dr P.\n A. Pilavachi, 624-638. Springer Netherlands, 1993.\n doi:10.1007/978-94-011-1454-7_56.\n .. [2] Kandlikar, Satish G. Heat Transfer and Fluid Flow in Minichannels\n and Microchannels. Elsevier, 2006.\n .. [3] Tran, T. N, M. -C Chyu, M. W Wambsganss, and D. M France. Two-Phase\n Pressure Drop of Refrigerants during Flow Boiling in Small Channels: An\n Experimental Investigation and Correlation Development.\" International\n Journal of Multiphase Flow 26, no. 11 (November 1, 2000): 1739-54.\n doi:10.1016/S0301-9322(99)00119-6.\n \"\"\"\n return sqrt(sigma/(g*(rhol-rhog)))/D\n\ndef Morton(rhol: float, rhog: float, mul: float, sigma: float, g: float=g) -> float:\n r\"\"\"Calculates Morton number or `Mo` for a liquid and vapor with the\n specified properties, under the influence of gravitational force `g`.\n\n .. math::\n Mo = \\frac{g \\mu_l^4(\\rho_l - \\rho_g)}{\\rho_l^2 \\sigma^3}\n\n Parameters\n ----------\n rhol : float\n Density of liquid phase, [kg/m^3]\n rhog : float\n Density of gas phase, [kg/m^3]\n mul : float\n Viscosity of liquid phase, [Pa*s]\n sigma : float\n Surface tension between liquid-gas phase, [N/m]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Mo : float\n Morton number, [-]\n\n Notes\n -----\n Used in modeling bubbles in liquid.\n\n Examples\n --------\n >>> Morton(1077.0, 76.5, 4.27E-3, 0.023)\n 2.311183104430743e-07\n\n References\n ----------\n .. [1] Kunes, Josef. Dimensionless Physical Quantities in Science and\n Engineering. Elsevier, 2012.\n .. [2] Yan, Xiaokang, Kaixin Zheng, Yan Jia, Zhenyong Miao, Lijun Wang,\n Yijun Cao, and Jiongtian Liu. “Drag Coefficient Prediction of a Single\n Bubble Rising in Liquids.” Industrial & Engineering Chemistry Research,\n April 2, 2018. https://doi.org/10.1021/acs.iecr.7b04743.\n \"\"\"\n mul2 = mul*mul\n return g*mul2*mul2*(rhol - rhog)/(rhol*rhol*sigma*sigma*sigma)\n\ndef Knudsen(path: float, L: float) -> float:\n r\"\"\"Calculates Knudsen number or `Kn` for a fluid with mean free path\n `path` and for a characteristic length `L`.\n\n .. math::\n Kn = \\frac{\\lambda}{L}\n\n Parameters\n ----------\n path : float\n Mean free path between molecular collisions, [m]\n L : float\n Characteristic length, [m]\n\n Returns\n -------\n Kn : float\n Knudsen number []\n\n Notes\n -----\n Used in mass transfer calculations.\n\n .. math::\n Kn = \\frac{\\text{Mean free path length}}{\\text{Characteristic length}}\n\n Examples\n --------\n >>> Knudsen(1e-10, .001)\n 1e-07\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return path/L\n\ndef Prandtl(Cp: float | None=None, k: float | None=None, mu: float | None=None, nu: float | None=None, rho: float | None=None, alpha: float | None=None) -> float:\n r\"\"\"Calculates Prandtl number or `Pr` for a fluid with the given\n parameters.\n\n .. math::\n Pr = \\frac{C_p \\mu}{k} = \\frac{\\nu}{\\alpha} = \\frac{C_p \\rho \\nu}{k}\n\n Inputs can be any of the following sets:\n\n * Heat capacity, dynamic viscosity, and thermal conductivity\n * Thermal diffusivity and kinematic viscosity\n * Heat capacity, kinematic viscosity, thermal conductivity, and density\n\n Parameters\n ----------\n Cp : float\n Heat capacity, [J/kg/K]\n k : float\n Thermal conductivity, [W/m/K]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n rho : float\n Density, [kg/m^3]\n alpha : float\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Pr : float\n Prandtl number []\n\n Notes\n -----\n .. math::\n Pr=\\frac{\\text{kinematic viscosity}}{\\text{thermal diffusivity}} = \\frac{\\text{momentum diffusivity}}{\\text{thermal diffusivity}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Prandtl(Cp=1637., k=0.010, mu=4.61E-6)\n 0.754657\n >>> Prandtl(Cp=1637., k=0.010, nu=6.4E-7, rho=7.1)\n 0.7438528\n >>> Prandtl(nu=6.3E-7, alpha=9E-7)\n 0.7000000000000001\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n Berlin; New York:: Springer, 2010.\n \"\"\"\n if k is not None and Cp is not None and mu is not None:\n return Cp*mu/k\n elif nu is not None and rho is not None and Cp is not None and k is not None:\n return nu*rho*Cp/k\n elif nu is not None and alpha is not None:\n return nu/alpha\n else:\n raise ValueError(\"Insufficient information provided for Pr calculation\")\n\ndef Grashof(L: float, beta: float, T1: float, T2: float=0, rho: float | None=None, mu: float | None=None, nu: float | None=None, g: float=g) -> float:\n r\"\"\"Calculates Grashof number or `Gr` for a fluid with the given\n properties, temperature difference, and characteristic length.\n\n .. math::\n Gr = \\frac{g\\beta (T_s-T_\\infty)L^3}{\\nu^2}\n = \\frac{g\\beta (T_s-T_\\infty)L^3\\rho^2}{\\mu^2}\n\n Inputs either of any of the following sets:\n\n * L, beta, T1 and T2, and density `rho` and dynamic viscosity `mu`\n * L, beta, T1 and T2, and kinematic viscosity `nu`\n\n Parameters\n ----------\n L : float\n Characteristic length [m]\n beta : float\n Volumetric thermal expansion coefficient [1/K]\n T1 : float\n Temperature 1, usually a film temperature [K]\n T2 : float, optional\n Temperature 2, usually a bulk temperature (or 0 if only a difference\n is provided to the function) [K]\n rho : float, optional\n Density, [kg/m^3]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Gr : float\n Grashof number []\n\n Notes\n -----\n .. math::\n Gr = \\frac{\\text{Buoyancy forces}}{\\text{Viscous forces}}\n\n An error is raised if none of the required input sets are provided.\n Used in free convection problems only.\n\n Examples\n --------\n Example 4 of [1]_, p. 1-21 (matches):\n\n >>> Grashof(L=0.9144, beta=0.000933, T1=178.2, rho=1.1613, mu=1.9E-5)\n 4656936556.178915\n >>> Grashof(L=0.9144, beta=0.000933, T1=378.2, T2=200, nu=1.636e-05)\n 4657491516.530312\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and mu is not None:\n nu = mu/rho\n elif nu is None:\n raise ValueError(\"Either density and viscosity, or kinematic viscosity is needed\")\n return g*beta*abs(T2-T1)*L*L*L/(nu*nu)\n\ndef Bond(rhol: float, rhog: float, sigma: float, L: float) -> float:\n r\"\"\"Calculates Bond number, `Bo` also known as Eotvos number,\n for a fluid with the given liquid and gas densities, surface tension,\n and geometric parameter (usually length).\n\n .. math::\n Bo = \\frac{g(\\rho_l-\\rho_g)L^2}{\\sigma}\n\n Parameters\n ----------\n rhol : float\n Density of liquid, [kg/m^3]\n rhog : float\n Density of gas, [kg/m^3]\n sigma : float\n Surface tension, [N/m]\n L : float\n Characteristic length, [m]\n\n Returns\n -------\n Bo : float\n Bond number []\n\n Examples\n --------\n >>> Bond(1000., 1.2, .0589, 2)\n 665187.2339558573\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return (g*(rhol-rhog)*L*L/sigma)\n\ndef Rayleigh(Pr: float, Gr: float) -> float:\n r\"\"\"Calculates Rayleigh number or `Ra` using Prandtl number `Pr` and\n Grashof number `Gr` for a fluid with the given\n properties, temperature difference, and characteristic length used\n to calculate `Gr` and `Pr`.\n\n .. math::\n Ra = PrGr\n\n Parameters\n ----------\n Pr : float\n Prandtl number []\n Gr : float\n Grashof number []\n\n Returns\n -------\n Ra : float\n Rayleigh number []\n\n Notes\n -----\n Used in free convection problems only.\n\n Examples\n --------\n >>> Rayleigh(1.2, 4.6E9)\n 5520000000.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return Pr*Gr\n\ndef Froude(V: float, L: float, g: float=g, squared: bool=False) -> float:\n r\"\"\"Calculates Froude number `Fr` for velocity `V` and geometric length\n `L`. If desired, gravity can be specified as well. Normally the function\n returns the result of the equation below; Froude number is also often\n said to be defined as the square of the equation below.\n\n .. math::\n Fr = \\frac{V}{\\sqrt{gL}}\n\n Parameters\n ----------\n V : float\n Velocity of the particle or fluid, [m/s]\n L : float\n Characteristic length, no typical definition [m]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n squared : bool, optional\n Whether to return the squared form of Froude number\n\n Returns\n -------\n Fr : float\n Froude number, [-]\n\n Notes\n -----\n Many alternate definitions including density ratios have been used.\n\n .. math::\n Fr = \\frac{\\text{Inertial Force}}{\\text{Gravity Force}}\n\n Examples\n --------\n >>> Froude(1.83, L=2., g=1.63)\n 1.0135432593877318\n >>> Froude(1.83, L=2., squared=True)\n 0.17074638128208924\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n Fr = V/sqrt(L*g)\n if squared:\n Fr *= Fr\n return Fr\n\ndef Froude_densimetric(V: float, L: float, rho1: float, rho2: float, heavy: bool=True, g: float=g) -> float:\n r\"\"\"Calculates the densimetric Froude number :math:`Fr_{den}` for velocity\n `V` geometric length `L`, heavier fluid density `rho1`, and lighter fluid\n density `rho2`. If desired, gravity can be specified as well. Depending on\n the application, this dimensionless number may be defined with the heavy\n phase or the light phase density in the numerator of the square root.\n For some applications, both need to be calculated. The default is to\n calculate with the heavy liquid density on top; set `heavy` to False\n to reverse this.\n\n .. math::\n Fr = \\frac{V}{\\sqrt{gL}} \\sqrt{\\frac{\\rho_\\text{(1 or 2)}}\n {\\rho_1 - \\rho_2}}\n\n Parameters\n ----------\n V : float\n Velocity of the specified phase, [m/s]\n L : float\n Characteristic length, no typical definition [m]\n rho1 : float\n Density of the heavier phase, [kg/m^3]\n rho2 : float\n Density of the lighter phase, [kg/m^3]\n heavy : bool, optional\n Whether or not the density used in the numerator is the heavy phase or\n the light phase, [-]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Fr_den : float\n Densimetric Froude number, [-]\n\n Notes\n -----\n Many alternate definitions including density ratios have been used.\n\n .. math::\n Fr = \\frac{\\text{Inertial Force}}{\\text{Gravity Force}}\n\n Where the gravity force is reduced by the relative densities of one fluid\n in another.\n\n Note that an Exception will be raised if rho1 < rho2, as the square root\n becomes negative.\n\n Examples\n --------\n >>> Froude_densimetric(1.83, L=2., rho1=800, rho2=1.2, g=9.81)\n 0.4134543386272418\n >>> Froude_densimetric(1.83, L=2., rho1=800, rho2=1.2, g=9.81, heavy=False)\n 0.016013017679205096\n\n References\n ----------\n .. [1] Hall, A, G Stobie, and R Steven. \"Further Evaluation of the\n Performance of Horizontally Installed Orifice Plate and Cone\n Differential Pressure Meters with Wet Gas Flows.\" In International\n SouthEast Asia Hydrocarbon Flow Measurement Workshop, KualaLumpur,\n Malaysia, 2008.\n \"\"\"\n if heavy:\n rho3 = rho1\n else:\n rho3 = rho2\n return V/(sqrt(g*L))*sqrt(rho3/(rho1 - rho2))\n\ndef Strouhal(f: float, L: float, V: float) -> float:\n r\"\"\"Calculates Strouhal number `St` for a characteristic frequency `f`,\n characteristic length `L`, and velocity `V`.\n\n .. math::\n St = \\frac{fL}{V}\n\n Parameters\n ----------\n f : float\n Characteristic frequency, usually that of vortex shedding, [Hz]\n L : float\n Characteristic length, [m]\n V : float\n Velocity of the fluid, [m/s]\n\n Returns\n -------\n St : float\n Strouhal number, [-]\n\n Notes\n -----\n Sometimes abbreviated to S or Sr.\n\n .. math::\n St = \\frac{\\text{Characteristic flow time}}\n {\\text{Period of oscillation}}\n\n Examples\n --------\n >>> Strouhal(8, 2., 4.)\n 4.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return f*L/V\n\ndef Nusselt(h: float, L: float, k: float) -> float:\n r\"\"\"Calculates Nusselt number `Nu` for a heat transfer coefficient `h`,\n characteristic length `L`, and thermal conductivity `k`.\n\n .. math::\n Nu = \\frac{hL}{k}\n\n Parameters\n ----------\n h : float\n Heat transfer coefficient, [W/m^2/K]\n L : float\n Characteristic length, no typical definition [m]\n k : float\n Thermal conductivity of fluid [W/m/K]\n\n Returns\n -------\n Nu : float\n Nusselt number, [-]\n\n Notes\n -----\n Do not confuse k, the thermal conductivity of the fluid, with that\n of a solid object!\n\n .. math::\n Nu = \\frac{\\text{Convective heat transfer}}\n {\\text{Conductive heat transfer}}\n\n Examples\n --------\n >>> Nusselt(1000., 1.2, 300.)\n 4.0\n >>> Nusselt(10000., .01, 4000.)\n 0.025\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n Wiley, 2011.\n \"\"\"\n return h*L/k\n\ndef Sherwood(K: float, L: float, D: float) -> float:\n r\"\"\"Calculates Sherwood number `Sh` for a mass transfer coefficient `K`,\n characteristic length `L`, and diffusivity `D`.\n\n .. math::\n Sh = \\frac{KL}{D}\n\n Parameters\n ----------\n K : float\n Mass transfer coefficient, [m/s]\n L : float\n Characteristic length, no typical definition [m]\n D : float\n Diffusivity of a species [m^2/s]\n\n Returns\n -------\n Sh : float\n Sherwood number, [-]\n\n Notes\n -----\n .. math::\n Sh = \\frac{\\text{Mass transfer by convection}}\n {\\text{Mass transfer by diffusion}} = \\frac{K}{D/L}\n\n Examples\n --------\n >>> Sherwood(1000., 1.2, 300.)\n 4.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return K*L/D\n\ndef Biot(h: float, L: float, k: float) -> float:\n r\"\"\"Calculates Biot number `Bi` for heat transfer coefficient `h`,\n geometric length `L`, and thermal conductivity `k`.\n\n .. math::\n Bi=\\frac{hL}{k}\n\n Parameters\n ----------\n h : float\n Heat transfer coefficient, [W/m^2/K]\n L : float\n Characteristic length, no typical definition [m]\n k : float\n Thermal conductivity, within the object [W/m/K]\n\n Returns\n -------\n Bi : float\n Biot number, [-]\n\n Notes\n -----\n Do not confuse k, the thermal conductivity within the object, with that\n of the medium h is calculated with!\n\n .. math::\n Bi = \\frac{\\text{Surface thermal resistance}}\n {\\text{Internal thermal resistance}}\n\n Examples\n --------\n >>> Biot(1000., 1.2, 300.)\n 4.0\n >>> Biot(10000., .01, 4000.)\n 0.025\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return h*L/k\n\ndef Stanton(h: float, V: float, rho: float, Cp: float) -> float:\n r\"\"\"Calculates Stanton number or `St` for a specified heat transfer\n coefficient `h`, velocity `V`, density `rho`, and heat capacity `Cp` [1]_\n [2]_.\n\n .. math::\n St = \\frac{h}{V\\rho Cp}\n\n Parameters\n ----------\n h : float\n Heat transfer coefficient, [W/m^2/K]\n V : float\n Velocity, [m/s]\n rho : float\n Density, [kg/m^3]\n Cp : float\n Heat capacity, [J/kg/K]\n\n Returns\n -------\n St : float\n Stanton number []\n\n Notes\n -----\n .. math::\n St = \\frac{\\text{Heat transfer coefficient}}{\\text{Thermal capacity}}\n\n Examples\n --------\n >>> Stanton(5000, 5, 800, 2000.)\n 0.000625\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n Wiley, 2011.\n \"\"\"\n return h/(V*rho*Cp)\n\ndef Euler(dP: float, rho: float, V: float) -> float:\n r\"\"\"Calculates Euler number or `Eu` for a fluid of velocity `V` and\n density `rho` experiencing a pressure drop `dP`.\n\n .. math::\n Eu = \\frac{\\Delta P}{\\rho V^2}\n\n Parameters\n ----------\n dP : float\n Pressure drop experience by the fluid, [Pa]\n rho : float\n Density of the fluid, [kg/m^3]\n V : float\n Velocity of fluid, [m/s]\n\n Returns\n -------\n Eu : float\n Euler number []\n\n Notes\n -----\n Used in pressure drop calculations.\n Rarely, this number is divided by two.\n Named after Leonhard Euler who applied calculus to fluid dynamics.\n\n .. math::\n Eu = \\frac{\\text{Pressure drop}}{2\\cdot \\text{velocity head}}\n\n Examples\n --------\n >>> Euler(1E5, 1000., 4)\n 6.25\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return dP/(rho*V*V)\n\ndef Cavitation(P: float, Psat: float, rho: float, V: float) -> float:\n r\"\"\"Calculates Cavitation number or `Ca` for a fluid of velocity `V` with\n a pressure `P`, vapor pressure `Psat`, and density `rho`.\n\n .. math::\n Ca = \\sigma_c = \\sigma = \\frac{P-P_{sat}}{\\frac{1}{2}\\rho V^2}\n\n Parameters\n ----------\n P : float\n Internal pressure of the fluid, [Pa]\n Psat : float\n Vapor pressure of the fluid, [Pa]\n rho : float\n Density of the fluid, [kg/m^3]\n V : float\n Velocity of fluid, [m/s]\n\n Returns\n -------\n Ca : float\n Cavitation number []\n\n Notes\n -----\n Used in determining if a flow through a restriction will cavitate.\n Sometimes, the multiplication by 2 will be omitted;\n\n .. math::\n Ca = \\frac{\\text{Pressure - Vapor pressure}}\n {\\text{Inertial pressure}}\n\n Examples\n --------\n >>> Cavitation(2E5, 1E4, 1000, 10)\n 3.8\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return (P-Psat)/(0.5*rho*V*V)\n\ndef Eckert(V: float, Cp: float, dT: float) -> float:\n r\"\"\"Calculates Eckert number or `Ec` for a fluid of velocity `V` with\n a heat capacity `Cp`, between two temperature given as `dT`.\n\n .. math::\n Ec = \\frac{V^2}{C_p \\Delta T}\n\n Parameters\n ----------\n V : float\n Velocity of fluid, [m/s]\n Cp : float\n Heat capacity of the fluid, [J/kg/K]\n dT : float\n Temperature difference, [K]\n\n Returns\n -------\n Ec : float\n Eckert number []\n\n Notes\n -----\n Used in certain heat transfer calculations. Fairly rare.\n\n .. math::\n Ec = \\frac{\\text{Kinetic energy} }{ \\text{Enthalpy difference}}\n\n Examples\n --------\n >>> Eckert(10, 2000., 25.)\n 0.002\n\n References\n ----------\n .. [1] Goldstein, Richard J. ECKERT NUMBER. Thermopedia. Hemisphere, 2011.\n 10.1615/AtoZ.e.eckert_number\n \"\"\"\n return V*V/(Cp*dT)\n\ndef Jakob(Cp: float, Hvap: float, Te: float) -> float:\n r\"\"\"Calculates Jakob number or `Ja` for a boiling fluid with sensible heat\n capacity `Cp`, enthalpy of vaporization `Hvap`, and boiling at `Te` degrees\n above its saturation boiling point.\n\n .. math::\n Ja = \\frac{C_{P}\\Delta T_e}{\\Delta H_{vap}}\n\n Parameters\n ----------\n Cp : float\n Heat capacity of the fluid, [J/kg/K]\n Hvap : float\n Enthalpy of vaporization of the fluid at its saturation temperature [J/kg]\n Te : float\n Temperature difference above the fluid's saturation boiling temperature, [K]\n\n Returns\n -------\n Ja : float\n Jakob number []\n\n Notes\n -----\n Used in boiling heat transfer analysis. Fairly rare.\n\n .. math::\n Ja = \\frac{\\Delta \\text{Sensible heat}}{\\Delta \\text{Latent heat}}\n\n Examples\n --------\n >>> Jakob(4000., 2E6, 10.)\n 0.02\n\n References\n ----------\n .. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n Wiley, 2011.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return Cp*Te/Hvap\n\ndef Power_number(P: float, L: float, N: float, rho: float) -> float:\n r\"\"\"Calculates power number, `Po`, for an agitator applying a specified\n power `P` with a characteristic length `L`, rotational speed `N`, to\n a fluid with a specified density `rho`.\n\n .. math::\n Po = \\frac{P}{\\rho N^3 D^5}\n\n Parameters\n ----------\n P : float\n Power applied, [W]\n L : float\n Characteristic length, typically agitator diameter [m]\n N : float\n Speed [revolutions/second]\n rho : float\n Density of fluid, [kg/m^3]\n\n Returns\n -------\n Po : float\n Power number []\n\n Notes\n -----\n Used in mixing calculations.\n\n .. math::\n Po = \\frac{\\text{Power}}{\\text{Rotational inertia}}\n\n Examples\n --------\n >>> Power_number(P=180, L=0.01, N=2.5, rho=800.)\n 144000000.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return P/(rho*N*N*N*L**5)\n\ndef Drag(F: float, A: float, V: float, rho: float) -> float:\n r\"\"\"Calculates drag coefficient `Cd` for a given drag force `F`,\n projected area `A`, characteristic velocity `V`, and density `rho`.\n\n .. math::\n C_D = \\frac{F_d}{A\\cdot\\frac{1}{2}\\rho V^2}\n\n Parameters\n ----------\n F : float\n Drag force, [N]\n A : float\n Projected area, [m^2]\n V : float\n Characteristic velocity, [m/s]\n rho : float\n Density, [kg/m^3]\n\n Returns\n -------\n Cd : float\n Drag coefficient, [-]\n\n Notes\n -----\n Used in flow around objects, or objects flowing within a fluid.\n\n .. math::\n C_D = \\frac{\\text{Drag forces}}{\\text{Projected area}\\cdot\n \\text{Velocity head}}\n\n Examples\n --------\n >>> Drag(1000, 0.0001, 5, 2000)\n 400.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return F/(0.5*A*rho*V*V)\n\ndef Stokes_number(V: float, Dp: float, D: float, rhop: float, mu: float) -> float:\n r\"\"\"Calculates Stokes Number for a given characteristic velocity `V`,\n particle diameter `Dp`, characteristic diameter `D`, particle density\n `rhop`, and fluid viscosity `mu`.\n\n .. math::\n \\text{Stk} = \\frac{\\rho_p V D_p^2}{18\\mu_f D}\n\n Parameters\n ----------\n V : float\n Characteristic velocity (often superficial), [m/s]\n Dp : float\n Particle diameter, [m]\n D : float\n Characteristic diameter (ex demister wire diameter or cyclone\n diameter), [m]\n rhop : float\n Particle density, [kg/m^3]\n mu : float\n Fluid viscosity, [Pa*s]\n\n Returns\n -------\n Stk : float\n Stokes number, [-]\n\n Notes\n -----\n Used in droplet impaction or collection studies.\n\n Examples\n --------\n >>> Stokes_number(V=0.9, Dp=1E-5, D=1E-3, rhop=1000, mu=1E-5)\n 0.5\n\n References\n ----------\n .. [1] Rhodes, Martin J. Introduction to Particle Technology. Wiley, 2013.\n .. [2] Al-Dughaither, Abdullah S., Ahmed A. Ibrahim, and Waheed A.\n Al-Masry. \"Investigating Droplet Separation Efficiency in Wire-Mesh Mist\n Eliminators in Bubble Column.\" Journal of Saudi Chemical Society 14, no.\n 4 (October 1, 2010): 331-39. https://doi.org/10.1016/j.jscs.2010.04.001.\n \"\"\"\n return rhop*V*(Dp*Dp)/(18.0*mu*D)\n\ndef Capillary(V: float, mu: float, sigma: float) -> float:\n r\"\"\"Calculates Capillary number `Ca` for a characteristic velocity `V`,\n viscosity `mu`, and surface tension `sigma`.\n\n .. math::\n Ca = \\frac{V \\mu}{\\sigma}\n\n Parameters\n ----------\n V : float\n Characteristic velocity, [m/s]\n mu : float\n Dynamic viscosity, [Pa*s]\n sigma : float\n Surface tension, [N/m]\n\n Returns\n -------\n Ca : float\n Capillary number, [-]\n\n Notes\n -----\n Used in porous media calculations and film flow calculations.\n Surface tension may gas-liquid, or liquid-liquid.\n\n .. math::\n Ca = \\frac{\\text{Viscous forces}}\n {\\text{Surface forces}}\n\n Examples\n --------\n >>> Capillary(1.2, 0.01, .1)\n 0.12\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Kundu, Pijush K., Ira M. Cohen, and David R. Dowling. Fluid\n Mechanics. Academic Press, 2012.\n \"\"\"\n return V*mu/sigma\n\ndef Archimedes(L: float, rhof: float, rhop: float, mu: float, g: float=g) -> float:\n r\"\"\"Calculates Archimedes number, `Ar`, for a fluid and particle with the\n given densities, characteristic length, viscosity, and gravity\n (usually diameter of particle).\n\n .. math::\n Ar = \\frac{L^3 \\rho_f(\\rho_p-\\rho_f)g}{\\mu^2}\n\n Parameters\n ----------\n L : float\n Characteristic length, typically particle diameter [m]\n rhof : float\n Density of fluid, [kg/m^3]\n rhop : float\n Density of particle, [kg/m^3]\n mu : float\n Viscosity of fluid, [Pa*s]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Ar : float\n Archimedes number []\n\n Notes\n -----\n Used in fluid-particle interaction calculations.\n\n .. math::\n Ar = \\frac{\\text{Gravitational force}}{\\text{Viscous force}}\n\n Examples\n --------\n >>> Archimedes(0.002, 2., 3000, 1E-3)\n 470.4053872\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return L*L*L*rhof*(rhop-rhof)*g/(mu*mu)\n\ndef Ohnesorge(L: float, rho: float, mu: float, sigma: float) -> float:\n r\"\"\"Calculates Ohnesorge number, `Oh`, for a fluid with the given\n characteristic length, density, viscosity, and surface tension.\n\n .. math::\n \\text{Oh} = \\frac{\\mu}{\\sqrt{\\rho \\sigma L }}\n\n Parameters\n ----------\n L : float\n Characteristic length [m]\n rho : float\n Density of fluid, [kg/m^3]\n mu : float\n Viscosity of fluid, [Pa*s]\n sigma : float\n Surface tension, [N/m]\n\n Returns\n -------\n Oh : float\n Ohnesorge number []\n\n Notes\n -----\n Often used in spray calculations. Sometimes given the symbol Z.\n\n .. math::\n Oh = \\frac{\\sqrt{\\text{We}}}{\\text{Re}}= \\frac{\\text{viscous forces}}\n {\\sqrt{\\text{Inertia}\\cdot\\text{Surface tension}} }\n\n Examples\n --------\n >>> Ohnesorge(1E-4, 1000., 1E-3, 1E-1)\n 0.01\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return mu/sqrt(L*rho*sigma)\n\ndef Suratman(L: float, rho: float, mu: float, sigma: float) -> float:\n r\"\"\"Calculates Suratman number, `Su`, for a fluid with the given\n characteristic length, density, viscosity, and surface tension.\n\n .. math::\n \\text{Su} = \\frac{\\rho\\sigma L}{\\mu^2}\n\n Parameters\n ----------\n L : float\n Characteristic length [m]\n rho : float\n Density of fluid, [kg/m^3]\n mu : float\n Viscosity of fluid, [Pa*s]\n sigma : float\n Surface tension, [N/m]\n\n Returns\n -------\n Su : float\n Suratman number []\n\n Notes\n -----\n Also known as Laplace number. Used in two-phase flow, especially the\n bubbly-slug regime. No confusion regarding the definition of this group\n has been observed.\n\n .. math::\n \\text{Su} = \\frac{\\text{Re}^2}{\\text{We}} =\\frac{\\text{Inertia}\\cdot\n \\text{Surface tension} }{\\text{(viscous forces)}^2}\n\n The oldest reference to this group found by the author is in 1963, from\n [2]_.\n\n Examples\n --------\n >>> Suratman(1E-4, 1000., 1E-3, 1E-1)\n 10000.0\n\n References\n ----------\n .. [1] Sen, Nilava. \"Suratman Number in Bubble-to-Slug Flow Pattern\n Transition under Microgravity.\" Acta Astronautica 65, no. 3-4 (August\n 2009): 423-28. doi:10.1016/j.actaastro.2009.02.013.\n .. [2] Catchpole, John P., and George. Fulford. \"DIMENSIONLESS GROUPS.\"\n Industrial & Engineering Chemistry 58, no. 3 (March 1, 1966): 46-60.\n doi:10.1021/ie50675a012.\n \"\"\"\n return rho*sigma*L/(mu*mu)\n\ndef Hagen(Re: float, fd: float) -> float:\n r\"\"\"Calculates Hagen number, `Hg`, for a fluid with the given\n Reynolds number and friction factor.\n\n .. math::\n \\text{Hg} = \\frac{f_d}{2} Re^2 = \\frac{1}{\\rho}\n \\frac{\\Delta P}{\\Delta z} \\frac{D^3}{\\nu^2}\n = \\frac{\\rho\\Delta P D^3}{\\mu^2 \\Delta z}\n\n Parameters\n ----------\n Re : float\n Reynolds number [-]\n fd : float, optional\n Darcy friction factor, [-]\n\n Returns\n -------\n Hg : float\n Hagen number, [-]\n\n Notes\n -----\n Introduced in [1]_; further use of it is mostly of the correlations\n introduced in [1]_.\n\n Notable for use in correlations, because it does not have any\n dependence on velocity.\n\n This expression is useful when designing backwards with a pressure drop\n spec already known.\n\n Examples\n --------\n Example from [3]_:\n\n >>> Hagen(Re=2610, fd=1.935235)\n 6591507.17175\n\n References\n ----------\n .. [1] Martin, Holger. \"The Generalized Lévêque Equation and Its Practical\n Use for the Prediction of Heat and Mass Transfer Rates from Pressure\n Drop.\" Chemical Engineering Science, Jean-Claude Charpentier\n Festschrift Issue, 57, no. 16 (August 1, 2002): 3217-23.\n https://doi.org/10.1016/S0009-2509(02)00194-X.\n .. [2] Shah, Ramesh K., and Dusan P. Sekulic. Fundamentals of Heat\n Exchanger Design. 1st edition. Hoboken, NJ: Wiley, 2002.\n .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n Berlin; New York:: Springer, 2010.\n \"\"\"\n return 0.5*fd*Re*Re\n\ndef Bejan_L(dP: float, L: float, mu: float, alpha: float) -> float:\n r\"\"\"Calculates Bejan number of a length or `Be_L` for a fluid with the\n given parameters flowing over a characteristic length `L` and experiencing\n a pressure drop `dP`.\n\n .. math::\n Be_L = \\frac{\\Delta P L^2}{\\mu \\alpha}\n\n Parameters\n ----------\n dP : float\n Pressure drop, [Pa]\n L : float\n Characteristic length, [m]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n alpha : float\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Be_L : float\n Bejan number with respect to length []\n\n Notes\n -----\n Termed a dimensionless number by someone in 1988.\n\n Examples\n --------\n >>> Bejan_L(1E4, 1, 1E-3, 1E-6)\n 10000000000000.0\n\n References\n ----------\n .. [1] Awad, M. M. \"The Science and the History of the Two Bejan Numbers.\"\n International Journal of Heat and Mass Transfer 94 (March 2016): 101-3.\n doi:10.1016/j.ijheatmasstransfer.2015.11.073.\n .. [2] Bejan, Adrian. Convection Heat Transfer. 4E. Hoboken, New Jersey:\n Wiley, 2013.\n \"\"\"\n return dP*L*L/(alpha*mu)\n\ndef Bejan_p(dP: float, K: float, mu: float, alpha: float) -> float:\n r\"\"\"Calculates Bejan number of a permeability or `Be_p` for a fluid with\n the given parameters and a permeability `K` experiencing a pressure drop\n `dP`.\n\n .. math::\n Be_p = \\frac{\\Delta P K}{\\mu \\alpha}\n\n Parameters\n ----------\n dP : float\n Pressure drop, [Pa]\n K : float\n Permeability, [m^2]\n mu : float\n Dynamic viscosity, [Pa*s]\n alpha : float\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Be_p : float\n Bejan number with respect to pore characteristics []\n\n Notes\n -----\n Termed a dimensionless number by someone in 1988.\n\n Examples\n --------\n >>> Bejan_p(1E4, 1, 1E-3, 1E-6)\n 10000000000000.0\n\n References\n ----------\n .. [1] Awad, M. M. \"The Science and the History of the Two Bejan Numbers.\"\n International Journal of Heat and Mass Transfer 94 (March 2016): 101-3.\n doi:10.1016/j.ijheatmasstransfer.2015.11.073.\n .. [2] Bejan, Adrian. Convection Heat Transfer. 4E. Hoboken, New Jersey:\n Wiley, 2013.\n \"\"\"\n return dP*K/(alpha*mu)\n\ndef Boiling(G: float, q: float, Hvap: float) -> float:\n r\"\"\"Calculates Boiling number or `Bg` using heat flux, two-phase mass flux,\n and heat of vaporization of the fluid flowing. Used in two-phase heat\n transfer calculations.\n\n .. math::\n \\text{Bg} = \\frac{q}{G_{tp} \\Delta H_{vap}}\n\n Parameters\n ----------\n G : float\n Two-phase mass flux in a channel (combined liquid and vapor) [kg/m^2/s]\n q : float\n Heat flux [W/m^2]\n Hvap : float\n Heat of vaporization of the fluid [J/kg]\n\n Returns\n -------\n Bg : float\n Boiling number [-]\n\n Notes\n -----\n Most often uses the symbol `Bo` instead of `Bg`, but this conflicts with\n Bond number.\n\n .. math::\n \\text{Bg} = \\frac{\\text{mass liquid evaporated / area heat transfer\n surface}}{\\text{mass flow rate fluid / flow cross sectional area}}\n\n First defined in [4]_, though not named.\n\n Examples\n --------\n >>> Boiling(300, 3000, 800000)\n 1.25e-05\n\n References\n ----------\n .. [1] Winterton, Richard H.S. BOILING NUMBER. Thermopedia. Hemisphere,\n 2011. 10.1615/AtoZ.b.boiling_number\n .. [2] Collier, John G., and John R. Thome. Convective Boiling and\n Condensation. 3rd edition. Clarendon Press, 1996.\n .. [3] Stephan, Karl. Heat Transfer in Condensation and Boiling. Translated\n by C. V. Green.. 1992 edition. Berlin; New York: Springer, 2013.\n .. [4] W. F. Davidson, P. H. Hardie, C. G. R. Humphreys, A. A. Markson,\n A. R. Mumford and T. Ravese \"Studies of heat transmission through boiler\n tubing at pressures from 500 to 3300 pounds\" Trans. ASME, Vol. 65, 9,\n February 1943, pp. 553-591.\n \"\"\"\n return q/(G*Hvap)\n\ndef Dean(Re: float, Di: float, D: float) -> float:\n r\"\"\"Calculates Dean number, `De`, for a fluid with the Reynolds number `Re`,\n inner diameter `Di`, and a secondary diameter `D`. `D` may be the\n diameter of curvature, the diameter of a spiral, or some other dimension.\n\n .. math::\n \\text{De} = \\sqrt{\\frac{D_i}{D}} \\text{Re} = \\sqrt{\\frac{D_i}{D}}\n \\frac{\\rho v D}{\\mu}\n\n Parameters\n ----------\n Re : float\n Reynolds number []\n Di : float\n Inner diameter []\n D : float\n Diameter of curvature or outer spiral or other dimension []\n\n Returns\n -------\n De : float\n Dean number [-]\n\n Notes\n -----\n Used in flow in curved geometry.\n\n .. math::\n \\text{De} = \\frac{\\sqrt{\\text{centripetal forces}\\cdot\n \\text{inertial forces}}}{\\text{viscous forces}}\n\n Examples\n --------\n >>> Dean(10000, 0.1, 0.4)\n 5000.0\n\n References\n ----------\n .. [1] Catchpole, John P., and George. Fulford. \"DIMENSIONLESS GROUPS.\"\n Industrial & Engineering Chemistry 58, no. 3 (March 1, 1966): 46-60.\n doi:10.1021/ie50675a012.\n \"\"\"\n return sqrt(Di/D)*Re\n\ndef relative_roughness(D: float, roughness: float=1.52e-06) -> float:\n r\"\"\"Calculates relative roughness `eD` using a diameter and the roughness\n of the material of the wall. Default roughness is that of steel.\n\n .. math::\n eD=\\frac{\\epsilon}{D}\n\n Parameters\n ----------\n D : float\n Diameter of pipe, [m]\n roughness : float, optional\n Roughness of pipe wall [m]\n\n Returns\n -------\n eD : float\n Relative Roughness, [-]\n\n Examples\n --------\n >>> relative_roughness(0.5, 1E-4)\n 0.0002\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return roughness/D\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 57102}, "tests/test_core.py::184": {"resolved_imports": ["fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["Archimedes", "Bejan_L", "Bejan_p", "Biot", "Boiling", "Bond", "Capillary", "Cavitation", "Confinement", "Dean", "Drag", "Eckert", "Euler", "Fourier_heat", "Fourier_mass", "Froude", "Froude_densimetric", "Graetz_heat", "Grashof", "Hagen", "Jakob", "Knudsen", "Lewis", "Mach", "Morton", "Nusselt", "Ohnesorge", "Peclet_heat", "Peclet_mass", "Power_number", "Prandtl", "Rayleigh", "Reynolds", "Schmidt", "Sherwood", "Stanton", "Stokes_number", "Strouhal", "Suratman", "Weber", "assert_close", "assert_close1d", "pytest", "relative_roughness"], "enclosing_function": "test_core_dimensionless", "extracted_code": "# Source: fluids/core.py\ndef Reynolds(V: float, D: float, rho: float | None=None, mu: float | None=None, nu: float | None=None) -> float:\n r\"\"\"Calculates Reynolds number or `Re` for a fluid with the given\n properties for the specified velocity and diameter.\n\n .. math::\n Re = \\frac{D \\cdot V}{\\nu} = \\frac{\\rho V D}{\\mu}\n\n Inputs either of any of the following sets:\n\n * V, D, density `rho` and dynamic viscosity `mu`\n * V, D, and kinematic viscosity `nu`\n\n Parameters\n ----------\n V : float\n Velocity [m/s]\n D : float\n Diameter [m]\n rho : float, optional\n Density, [kg/m^3]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n\n Returns\n -------\n Re : float\n Reynolds number []\n\n Notes\n -----\n .. math::\n Re = \\frac{\\text{Momentum}}{\\text{Viscosity}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Reynolds(2.5, 0.25, 1.1613, 1.9E-5)\n 38200.65789473684\n >>> Reynolds(2.5, 0.25, nu=1.636e-05)\n 38202.93398533008\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and mu is not None:\n nu = mu/rho\n elif nu is None:\n raise ValueError(\"Either density and viscosity, or kinematic viscosity is needed\")\n return V*D/nu\n\ndef Peclet_heat(V: float, L: float, rho: float | None=None, Cp: float | None=None, k: float | None=None, alpha: float | None=None) -> float:\n r\"\"\"Calculates heat transfer Peclet number or `Pe` for a specified velocity\n `V`, characteristic length `L`, and specified properties for the given\n fluid.\n\n .. math::\n Pe = \\frac{VL\\rho C_p}{k} = \\frac{LV}{\\alpha}\n\n Inputs either of any of the following sets:\n\n * V, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k`\n * V, L, and thermal diffusivity `alpha`\n\n Parameters\n ----------\n V : float\n Velocity [m/s]\n L : float\n Characteristic length [m]\n rho : float, optional\n Density, [kg/m^3]\n Cp : float, optional\n Heat capacity, [J/kg/K]\n k : float, optional\n Thermal conductivity, [W/m/K]\n alpha : float, optional\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Pe : float\n Peclet number (heat) []\n\n Notes\n -----\n .. math::\n Pe = \\frac{\\text{Bulk heat transfer}}{\\text{Conduction heat transfer}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Peclet_heat(1.5, 2, 1000., 4000., 0.6)\n 20000000.0\n >>> Peclet_heat(1.5, 2, alpha=1E-7)\n 30000000.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and Cp is not None and k is not None:\n alpha = k/(rho*Cp)\n elif alpha is None:\n raise ValueError(\"Either heat capacity and thermal conductivity and density, or thermal diffusivity is needed\")\n return V*L/alpha\n\ndef Peclet_mass(V: float, L: float, D: float) -> float:\n r\"\"\"Calculates mass transfer Peclet number or `Pe` for a specified velocity\n `V`, characteristic length `L`, and diffusion coefficient `D`.\n\n .. math::\n Pe = \\frac{L V}{D}\n\n Parameters\n ----------\n V : float\n Velocity [m/s]\n L : float\n Characteristic length [m]\n D : float\n Diffusivity of a species, [m^2/s]\n\n Returns\n -------\n Pe : float\n Peclet number (mass) []\n\n Notes\n -----\n .. math::\n Pe = \\frac{\\text{Advective transport rate}}{\\text{Diffusive transport rate}}\n\n Examples\n --------\n >>> Peclet_mass(1.5, 2, 1E-9)\n 3000000000.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return V*L/D\n\ndef Fourier_heat(t: float, L: float, rho: float | None=None, Cp: float | None=None, k: float | None=None, alpha: float | None=None) -> float:\n r\"\"\"Calculates heat transfer Fourier number or `Fo` for a specified time\n `t`, characteristic length `L`, and specified properties for the given\n fluid.\n\n .. math::\n Fo = \\frac{k t}{C_p \\rho L^2} = \\frac{\\alpha t}{L^2}\n\n Inputs either of any of the following sets:\n\n * t, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k`\n * t, L, and thermal diffusivity `alpha`\n\n Parameters\n ----------\n t : float\n time [s]\n L : float\n Characteristic length [m]\n rho : float, optional\n Density, [kg/m^3]\n Cp : float, optional\n Heat capacity, [J/kg/K]\n k : float, optional\n Thermal conductivity, [W/m/K]\n alpha : float, optional\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Fo : float\n Fourier number (heat) []\n\n Notes\n -----\n .. math::\n Fo = \\frac{\\text{Heat conduction rate}}\n {\\text{Rate of thermal energy storage in a solid}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Fourier_heat(t=1.5, L=2, rho=1000., Cp=4000., k=0.6)\n 5.625e-08\n >>> Fourier_heat(1.5, 2, alpha=1E-7)\n 3.75e-08\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and Cp is not None and k is not None:\n alpha = k/(rho*Cp)\n elif alpha is None:\n raise ValueError(\"Either heat capacity and thermal conductivity and density, or thermal diffusivity is needed\")\n return t*alpha/(L*L)\n\ndef Fourier_mass(t: float, L: float, D: float) -> float:\n r\"\"\"Calculates mass transfer Fourier number or `Fo` for a specified time\n `t`, characteristic length `L`, and diffusion coefficient `D`.\n\n .. math::\n Fo = \\frac{D t}{L^2}\n\n Parameters\n ----------\n t : float\n time [s]\n L : float\n Characteristic length [m]\n D : float\n Diffusivity of a species, [m^2/s]\n\n Returns\n -------\n Fo : float\n Fourier number (mass) []\n\n Notes\n -----\n .. math::\n Fo = \\frac{\\text{Diffusive transport rate}}{\\text{Storage rate}}\n\n Examples\n --------\n >>> Fourier_mass(t=1.5, L=2, D=1E-9)\n 3.7500000000000005e-10\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return t*D/(L*L)\n\ndef Graetz_heat(V: float, D: float, x: float, rho: float | None=None, Cp: float | None=None, k: float | None=None, alpha: float | None=None) -> float:\n r\"\"\"Calculates Graetz number or `Gz` for a specified velocity\n `V`, diameter `D`, axial distance `x`, and specified properties for the\n given fluid.\n\n .. math::\n Gz = \\frac{VD^2\\cdot C_p \\rho}{x\\cdot k} = \\frac{VD^2}{x \\alpha}\n\n Inputs either of any of the following sets:\n\n * V, D, x, density `rho`, heat capacity `Cp`, and thermal conductivity `k`\n * V, D, x, and thermal diffusivity `alpha`\n\n Parameters\n ----------\n V : float\n Velocity, [m/s]\n D : float\n Diameter [m]\n x : float\n Axial distance [m]\n rho : float, optional\n Density, [kg/m^3]\n Cp : float, optional\n Heat capacity, [J/kg/K]\n k : float, optional\n Thermal conductivity, [W/m/K]\n alpha : float, optional\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Gz : float\n Graetz number []\n\n Notes\n -----\n .. math::\n Gz = \\frac{\\text{Time for radial heat diffusion in a fluid by conduction}}\n {\\text{Time taken by fluid to reach distance x}}\n\n .. math::\n Gz = \\frac{D}{x}RePr\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Graetz_heat(1.5, 0.25, 5, 800., 2200., 0.6)\n 55000.0\n >>> Graetz_heat(1.5, 0.25, 5, alpha=1E-7)\n 187500.0\n\n References\n ----------\n .. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n Wiley, 2011.\n \"\"\"\n if rho is not None and Cp is not None and k is not None:\n alpha = k/(rho*Cp)\n elif alpha is None:\n raise ValueError(\"Either heat capacity and thermal conductivity and density, or thermal diffusivity is needed\")\n return V*D*D/(x*alpha)\n\ndef Schmidt(D: float, mu: float | None=None, nu: float | None=None, rho: float | None=None) -> float:\n r\"\"\"Calculates Schmidt number or `Sc` for a fluid with the given\n parameters.\n\n .. math::\n Sc = \\frac{\\mu}{D\\rho} = \\frac{\\nu}{D}\n\n Inputs can be any of the following sets:\n\n * Diffusivity, dynamic viscosity, and density\n * Diffusivity and kinematic viscosity\n\n Parameters\n ----------\n D : float\n Diffusivity of a species, [m^2/s]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n rho : float, optional\n Density, [kg/m^3]\n\n Returns\n -------\n Sc : float\n Schmidt number []\n\n Notes\n -----\n .. math::\n Sc =\\frac{\\text{kinematic viscosity}}{\\text{molecular diffusivity}}\n = \\frac{\\text{viscous diffusivity}}{\\text{species diffusivity}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Schmidt(D=2E-6, mu=4.61E-6, rho=800)\n 0.00288125\n >>> Schmidt(D=1E-9, nu=6E-7)\n 599.9999999999999\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and mu is not None:\n return mu/(rho*D)\n elif nu is not None:\n return nu/D\n else:\n raise ValueError(\"Insufficient information provided for Schmidt number calculation\")\n\ndef Lewis(D: float, alpha: float | None=None, Cp: float | None=None, k: float | None=None, rho: float | None=None) -> float:\n r\"\"\"Calculates Lewis number or `Le` for a fluid with the given parameters.\n\n .. math::\n Le = \\frac{k}{\\rho C_p D} = \\frac{\\alpha}{D}\n\n Inputs can be either of the following sets:\n\n * Diffusivity and Thermal diffusivity\n * Diffusivity, heat capacity, thermal conductivity, and density\n\n Parameters\n ----------\n D : float\n Diffusivity of a species, [m^2/s]\n alpha : float, optional\n Thermal diffusivity, [m^2/s]\n Cp : float, optional\n Heat capacity, [J/kg/K]\n k : float, optional\n Thermal conductivity, [W/m/K]\n rho : float, optional\n Density, [kg/m^3]\n\n Returns\n -------\n Le : float\n Lewis number []\n\n Notes\n -----\n .. math::\n Le=\\frac{\\text{Thermal diffusivity}}{\\text{Mass diffusivity}} =\n \\frac{Sc}{Pr}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Lewis(D=22.6E-6, alpha=19.1E-6)\n 0.8451327433628318\n >>> Lewis(D=22.6E-6, rho=800., k=.2, Cp=2200)\n 0.00502815768302494\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n Berlin; New York:: Springer, 2010.\n \"\"\"\n if D is None:\n raise ValueError(\"Diffusivity D is required for Le calculation\")\n if k is not None and Cp is not None and rho is not None:\n alpha = k/(rho*Cp)\n elif alpha is None:\n raise ValueError(\"Insufficient information provided for Le calculation\")\n return alpha/D\n\ndef Weber(V: float, L: float, rho: float, sigma: float) -> float:\n r\"\"\"Calculates Weber number, `We`, for a fluid with the given density,\n surface tension, velocity, and geometric parameter (usually diameter\n of bubble).\n\n .. math::\n We = \\frac{V^2 L\\rho}{\\sigma}\n\n Parameters\n ----------\n V : float\n Velocity of fluid, [m/s]\n L : float\n Characteristic length, typically bubble diameter [m]\n rho : float\n Density of fluid, [kg/m^3]\n sigma : float\n Surface tension, [N/m]\n\n Returns\n -------\n We : float\n Weber number []\n\n Notes\n -----\n Used in bubble calculations.\n\n .. math::\n We = \\frac{\\text{inertial force}}{\\text{surface tension force}}\n\n Examples\n --------\n >>> Weber(V=0.18, L=0.001, rho=900., sigma=0.01)\n 2.916\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n Berlin; New York:: Springer, 2010.\n \"\"\"\n return V*V*L*rho/sigma\n\ndef Mach(V: float, c: float) -> float:\n r\"\"\"Calculates Mach number or `Ma` for a fluid of velocity `V` with speed\n of sound `c`.\n\n .. math::\n Ma = \\frac{V}{c}\n\n Parameters\n ----------\n V : float\n Velocity of fluid, [m/s]\n c : float\n Speed of sound in fluid, [m/s]\n\n Returns\n -------\n Ma : float\n Mach number []\n\n Notes\n -----\n Used in compressible flow calculations.\n\n .. math::\n Ma = \\frac{\\text{fluid velocity}}{\\text{sonic velocity}}\n\n Examples\n --------\n >>> Mach(33., 330)\n 0.1\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return V/c\n\ndef Confinement(D: float, rhol: float, rhog: float, sigma: float, g: float=g) -> float:\n r\"\"\"Calculates Confinement number or `Co` for a fluid in a channel of\n diameter `D` with liquid and gas densities `rhol` and `rhog` and surface\n tension `sigma`, under the influence of gravitational force `g`.\n\n .. math::\n \\text{Co}=\\frac{\\left[\\frac{\\sigma}{g(\\rho_l-\\rho_g)}\\right]^{0.5}}{D}\n\n Parameters\n ----------\n D : float\n Diameter of channel, [m]\n rhol : float\n Density of liquid phase, [kg/m^3]\n rhog : float\n Density of gas phase, [kg/m^3]\n sigma : float\n Surface tension between liquid-gas phase, [N/m]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Co : float\n Confinement number [-]\n\n Notes\n -----\n Used in two-phase pressure drop and heat transfer correlations. First used\n in [1]_ according to [3]_.\n\n .. math::\n \\text{Co} = \\frac{\\frac{\\text{surface tension force}}\n {\\text{buoyancy force}}}{\\text{Channel area}}\n\n Examples\n --------\n >>> Confinement(0.001, 1077, 76.5, 4.27E-3)\n 0.6596978265315191\n\n References\n ----------\n .. [1] Cornwell, Keith, and Peter A. Kew. \"Boiling in Small Parallel\n Channels.\" In Energy Efficiency in Process Technology, edited by Dr P.\n A. Pilavachi, 624-638. Springer Netherlands, 1993.\n doi:10.1007/978-94-011-1454-7_56.\n .. [2] Kandlikar, Satish G. Heat Transfer and Fluid Flow in Minichannels\n and Microchannels. Elsevier, 2006.\n .. [3] Tran, T. N, M. -C Chyu, M. W Wambsganss, and D. M France. Two-Phase\n Pressure Drop of Refrigerants during Flow Boiling in Small Channels: An\n Experimental Investigation and Correlation Development.\" International\n Journal of Multiphase Flow 26, no. 11 (November 1, 2000): 1739-54.\n doi:10.1016/S0301-9322(99)00119-6.\n \"\"\"\n return sqrt(sigma/(g*(rhol-rhog)))/D\n\ndef Morton(rhol: float, rhog: float, mul: float, sigma: float, g: float=g) -> float:\n r\"\"\"Calculates Morton number or `Mo` for a liquid and vapor with the\n specified properties, under the influence of gravitational force `g`.\n\n .. math::\n Mo = \\frac{g \\mu_l^4(\\rho_l - \\rho_g)}{\\rho_l^2 \\sigma^3}\n\n Parameters\n ----------\n rhol : float\n Density of liquid phase, [kg/m^3]\n rhog : float\n Density of gas phase, [kg/m^3]\n mul : float\n Viscosity of liquid phase, [Pa*s]\n sigma : float\n Surface tension between liquid-gas phase, [N/m]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Mo : float\n Morton number, [-]\n\n Notes\n -----\n Used in modeling bubbles in liquid.\n\n Examples\n --------\n >>> Morton(1077.0, 76.5, 4.27E-3, 0.023)\n 2.311183104430743e-07\n\n References\n ----------\n .. [1] Kunes, Josef. Dimensionless Physical Quantities in Science and\n Engineering. Elsevier, 2012.\n .. [2] Yan, Xiaokang, Kaixin Zheng, Yan Jia, Zhenyong Miao, Lijun Wang,\n Yijun Cao, and Jiongtian Liu. “Drag Coefficient Prediction of a Single\n Bubble Rising in Liquids.” Industrial & Engineering Chemistry Research,\n April 2, 2018. https://doi.org/10.1021/acs.iecr.7b04743.\n \"\"\"\n mul2 = mul*mul\n return g*mul2*mul2*(rhol - rhog)/(rhol*rhol*sigma*sigma*sigma)\n\ndef Knudsen(path: float, L: float) -> float:\n r\"\"\"Calculates Knudsen number or `Kn` for a fluid with mean free path\n `path` and for a characteristic length `L`.\n\n .. math::\n Kn = \\frac{\\lambda}{L}\n\n Parameters\n ----------\n path : float\n Mean free path between molecular collisions, [m]\n L : float\n Characteristic length, [m]\n\n Returns\n -------\n Kn : float\n Knudsen number []\n\n Notes\n -----\n Used in mass transfer calculations.\n\n .. math::\n Kn = \\frac{\\text{Mean free path length}}{\\text{Characteristic length}}\n\n Examples\n --------\n >>> Knudsen(1e-10, .001)\n 1e-07\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return path/L\n\ndef Prandtl(Cp: float | None=None, k: float | None=None, mu: float | None=None, nu: float | None=None, rho: float | None=None, alpha: float | None=None) -> float:\n r\"\"\"Calculates Prandtl number or `Pr` for a fluid with the given\n parameters.\n\n .. math::\n Pr = \\frac{C_p \\mu}{k} = \\frac{\\nu}{\\alpha} = \\frac{C_p \\rho \\nu}{k}\n\n Inputs can be any of the following sets:\n\n * Heat capacity, dynamic viscosity, and thermal conductivity\n * Thermal diffusivity and kinematic viscosity\n * Heat capacity, kinematic viscosity, thermal conductivity, and density\n\n Parameters\n ----------\n Cp : float\n Heat capacity, [J/kg/K]\n k : float\n Thermal conductivity, [W/m/K]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n rho : float\n Density, [kg/m^3]\n alpha : float\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Pr : float\n Prandtl number []\n\n Notes\n -----\n .. math::\n Pr=\\frac{\\text{kinematic viscosity}}{\\text{thermal diffusivity}} = \\frac{\\text{momentum diffusivity}}{\\text{thermal diffusivity}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Prandtl(Cp=1637., k=0.010, mu=4.61E-6)\n 0.754657\n >>> Prandtl(Cp=1637., k=0.010, nu=6.4E-7, rho=7.1)\n 0.7438528\n >>> Prandtl(nu=6.3E-7, alpha=9E-7)\n 0.7000000000000001\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n Berlin; New York:: Springer, 2010.\n \"\"\"\n if k is not None and Cp is not None and mu is not None:\n return Cp*mu/k\n elif nu is not None and rho is not None and Cp is not None and k is not None:\n return nu*rho*Cp/k\n elif nu is not None and alpha is not None:\n return nu/alpha\n else:\n raise ValueError(\"Insufficient information provided for Pr calculation\")\n\ndef Grashof(L: float, beta: float, T1: float, T2: float=0, rho: float | None=None, mu: float | None=None, nu: float | None=None, g: float=g) -> float:\n r\"\"\"Calculates Grashof number or `Gr` for a fluid with the given\n properties, temperature difference, and characteristic length.\n\n .. math::\n Gr = \\frac{g\\beta (T_s-T_\\infty)L^3}{\\nu^2}\n = \\frac{g\\beta (T_s-T_\\infty)L^3\\rho^2}{\\mu^2}\n\n Inputs either of any of the following sets:\n\n * L, beta, T1 and T2, and density `rho` and dynamic viscosity `mu`\n * L, beta, T1 and T2, and kinematic viscosity `nu`\n\n Parameters\n ----------\n L : float\n Characteristic length [m]\n beta : float\n Volumetric thermal expansion coefficient [1/K]\n T1 : float\n Temperature 1, usually a film temperature [K]\n T2 : float, optional\n Temperature 2, usually a bulk temperature (or 0 if only a difference\n is provided to the function) [K]\n rho : float, optional\n Density, [kg/m^3]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Gr : float\n Grashof number []\n\n Notes\n -----\n .. math::\n Gr = \\frac{\\text{Buoyancy forces}}{\\text{Viscous forces}}\n\n An error is raised if none of the required input sets are provided.\n Used in free convection problems only.\n\n Examples\n --------\n Example 4 of [1]_, p. 1-21 (matches):\n\n >>> Grashof(L=0.9144, beta=0.000933, T1=178.2, rho=1.1613, mu=1.9E-5)\n 4656936556.178915\n >>> Grashof(L=0.9144, beta=0.000933, T1=378.2, T2=200, nu=1.636e-05)\n 4657491516.530312\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and mu is not None:\n nu = mu/rho\n elif nu is None:\n raise ValueError(\"Either density and viscosity, or kinematic viscosity is needed\")\n return g*beta*abs(T2-T1)*L*L*L/(nu*nu)\n\ndef Bond(rhol: float, rhog: float, sigma: float, L: float) -> float:\n r\"\"\"Calculates Bond number, `Bo` also known as Eotvos number,\n for a fluid with the given liquid and gas densities, surface tension,\n and geometric parameter (usually length).\n\n .. math::\n Bo = \\frac{g(\\rho_l-\\rho_g)L^2}{\\sigma}\n\n Parameters\n ----------\n rhol : float\n Density of liquid, [kg/m^3]\n rhog : float\n Density of gas, [kg/m^3]\n sigma : float\n Surface tension, [N/m]\n L : float\n Characteristic length, [m]\n\n Returns\n -------\n Bo : float\n Bond number []\n\n Examples\n --------\n >>> Bond(1000., 1.2, .0589, 2)\n 665187.2339558573\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return (g*(rhol-rhog)*L*L/sigma)\n\ndef Rayleigh(Pr: float, Gr: float) -> float:\n r\"\"\"Calculates Rayleigh number or `Ra` using Prandtl number `Pr` and\n Grashof number `Gr` for a fluid with the given\n properties, temperature difference, and characteristic length used\n to calculate `Gr` and `Pr`.\n\n .. math::\n Ra = PrGr\n\n Parameters\n ----------\n Pr : float\n Prandtl number []\n Gr : float\n Grashof number []\n\n Returns\n -------\n Ra : float\n Rayleigh number []\n\n Notes\n -----\n Used in free convection problems only.\n\n Examples\n --------\n >>> Rayleigh(1.2, 4.6E9)\n 5520000000.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return Pr*Gr\n\ndef Froude(V: float, L: float, g: float=g, squared: bool=False) -> float:\n r\"\"\"Calculates Froude number `Fr` for velocity `V` and geometric length\n `L`. If desired, gravity can be specified as well. Normally the function\n returns the result of the equation below; Froude number is also often\n said to be defined as the square of the equation below.\n\n .. math::\n Fr = \\frac{V}{\\sqrt{gL}}\n\n Parameters\n ----------\n V : float\n Velocity of the particle or fluid, [m/s]\n L : float\n Characteristic length, no typical definition [m]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n squared : bool, optional\n Whether to return the squared form of Froude number\n\n Returns\n -------\n Fr : float\n Froude number, [-]\n\n Notes\n -----\n Many alternate definitions including density ratios have been used.\n\n .. math::\n Fr = \\frac{\\text{Inertial Force}}{\\text{Gravity Force}}\n\n Examples\n --------\n >>> Froude(1.83, L=2., g=1.63)\n 1.0135432593877318\n >>> Froude(1.83, L=2., squared=True)\n 0.17074638128208924\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n Fr = V/sqrt(L*g)\n if squared:\n Fr *= Fr\n return Fr\n\ndef Froude_densimetric(V: float, L: float, rho1: float, rho2: float, heavy: bool=True, g: float=g) -> float:\n r\"\"\"Calculates the densimetric Froude number :math:`Fr_{den}` for velocity\n `V` geometric length `L`, heavier fluid density `rho1`, and lighter fluid\n density `rho2`. If desired, gravity can be specified as well. Depending on\n the application, this dimensionless number may be defined with the heavy\n phase or the light phase density in the numerator of the square root.\n For some applications, both need to be calculated. The default is to\n calculate with the heavy liquid density on top; set `heavy` to False\n to reverse this.\n\n .. math::\n Fr = \\frac{V}{\\sqrt{gL}} \\sqrt{\\frac{\\rho_\\text{(1 or 2)}}\n {\\rho_1 - \\rho_2}}\n\n Parameters\n ----------\n V : float\n Velocity of the specified phase, [m/s]\n L : float\n Characteristic length, no typical definition [m]\n rho1 : float\n Density of the heavier phase, [kg/m^3]\n rho2 : float\n Density of the lighter phase, [kg/m^3]\n heavy : bool, optional\n Whether or not the density used in the numerator is the heavy phase or\n the light phase, [-]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Fr_den : float\n Densimetric Froude number, [-]\n\n Notes\n -----\n Many alternate definitions including density ratios have been used.\n\n .. math::\n Fr = \\frac{\\text{Inertial Force}}{\\text{Gravity Force}}\n\n Where the gravity force is reduced by the relative densities of one fluid\n in another.\n\n Note that an Exception will be raised if rho1 < rho2, as the square root\n becomes negative.\n\n Examples\n --------\n >>> Froude_densimetric(1.83, L=2., rho1=800, rho2=1.2, g=9.81)\n 0.4134543386272418\n >>> Froude_densimetric(1.83, L=2., rho1=800, rho2=1.2, g=9.81, heavy=False)\n 0.016013017679205096\n\n References\n ----------\n .. [1] Hall, A, G Stobie, and R Steven. \"Further Evaluation of the\n Performance of Horizontally Installed Orifice Plate and Cone\n Differential Pressure Meters with Wet Gas Flows.\" In International\n SouthEast Asia Hydrocarbon Flow Measurement Workshop, KualaLumpur,\n Malaysia, 2008.\n \"\"\"\n if heavy:\n rho3 = rho1\n else:\n rho3 = rho2\n return V/(sqrt(g*L))*sqrt(rho3/(rho1 - rho2))\n\ndef Strouhal(f: float, L: float, V: float) -> float:\n r\"\"\"Calculates Strouhal number `St` for a characteristic frequency `f`,\n characteristic length `L`, and velocity `V`.\n\n .. math::\n St = \\frac{fL}{V}\n\n Parameters\n ----------\n f : float\n Characteristic frequency, usually that of vortex shedding, [Hz]\n L : float\n Characteristic length, [m]\n V : float\n Velocity of the fluid, [m/s]\n\n Returns\n -------\n St : float\n Strouhal number, [-]\n\n Notes\n -----\n Sometimes abbreviated to S or Sr.\n\n .. math::\n St = \\frac{\\text{Characteristic flow time}}\n {\\text{Period of oscillation}}\n\n Examples\n --------\n >>> Strouhal(8, 2., 4.)\n 4.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return f*L/V\n\ndef Nusselt(h: float, L: float, k: float) -> float:\n r\"\"\"Calculates Nusselt number `Nu` for a heat transfer coefficient `h`,\n characteristic length `L`, and thermal conductivity `k`.\n\n .. math::\n Nu = \\frac{hL}{k}\n\n Parameters\n ----------\n h : float\n Heat transfer coefficient, [W/m^2/K]\n L : float\n Characteristic length, no typical definition [m]\n k : float\n Thermal conductivity of fluid [W/m/K]\n\n Returns\n -------\n Nu : float\n Nusselt number, [-]\n\n Notes\n -----\n Do not confuse k, the thermal conductivity of the fluid, with that\n of a solid object!\n\n .. math::\n Nu = \\frac{\\text{Convective heat transfer}}\n {\\text{Conductive heat transfer}}\n\n Examples\n --------\n >>> Nusselt(1000., 1.2, 300.)\n 4.0\n >>> Nusselt(10000., .01, 4000.)\n 0.025\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n Wiley, 2011.\n \"\"\"\n return h*L/k\n\ndef Sherwood(K: float, L: float, D: float) -> float:\n r\"\"\"Calculates Sherwood number `Sh` for a mass transfer coefficient `K`,\n characteristic length `L`, and diffusivity `D`.\n\n .. math::\n Sh = \\frac{KL}{D}\n\n Parameters\n ----------\n K : float\n Mass transfer coefficient, [m/s]\n L : float\n Characteristic length, no typical definition [m]\n D : float\n Diffusivity of a species [m^2/s]\n\n Returns\n -------\n Sh : float\n Sherwood number, [-]\n\n Notes\n -----\n .. math::\n Sh = \\frac{\\text{Mass transfer by convection}}\n {\\text{Mass transfer by diffusion}} = \\frac{K}{D/L}\n\n Examples\n --------\n >>> Sherwood(1000., 1.2, 300.)\n 4.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return K*L/D\n\ndef Biot(h: float, L: float, k: float) -> float:\n r\"\"\"Calculates Biot number `Bi` for heat transfer coefficient `h`,\n geometric length `L`, and thermal conductivity `k`.\n\n .. math::\n Bi=\\frac{hL}{k}\n\n Parameters\n ----------\n h : float\n Heat transfer coefficient, [W/m^2/K]\n L : float\n Characteristic length, no typical definition [m]\n k : float\n Thermal conductivity, within the object [W/m/K]\n\n Returns\n -------\n Bi : float\n Biot number, [-]\n\n Notes\n -----\n Do not confuse k, the thermal conductivity within the object, with that\n of the medium h is calculated with!\n\n .. math::\n Bi = \\frac{\\text{Surface thermal resistance}}\n {\\text{Internal thermal resistance}}\n\n Examples\n --------\n >>> Biot(1000., 1.2, 300.)\n 4.0\n >>> Biot(10000., .01, 4000.)\n 0.025\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return h*L/k\n\ndef Stanton(h: float, V: float, rho: float, Cp: float) -> float:\n r\"\"\"Calculates Stanton number or `St` for a specified heat transfer\n coefficient `h`, velocity `V`, density `rho`, and heat capacity `Cp` [1]_\n [2]_.\n\n .. math::\n St = \\frac{h}{V\\rho Cp}\n\n Parameters\n ----------\n h : float\n Heat transfer coefficient, [W/m^2/K]\n V : float\n Velocity, [m/s]\n rho : float\n Density, [kg/m^3]\n Cp : float\n Heat capacity, [J/kg/K]\n\n Returns\n -------\n St : float\n Stanton number []\n\n Notes\n -----\n .. math::\n St = \\frac{\\text{Heat transfer coefficient}}{\\text{Thermal capacity}}\n\n Examples\n --------\n >>> Stanton(5000, 5, 800, 2000.)\n 0.000625\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n Wiley, 2011.\n \"\"\"\n return h/(V*rho*Cp)\n\ndef Euler(dP: float, rho: float, V: float) -> float:\n r\"\"\"Calculates Euler number or `Eu` for a fluid of velocity `V` and\n density `rho` experiencing a pressure drop `dP`.\n\n .. math::\n Eu = \\frac{\\Delta P}{\\rho V^2}\n\n Parameters\n ----------\n dP : float\n Pressure drop experience by the fluid, [Pa]\n rho : float\n Density of the fluid, [kg/m^3]\n V : float\n Velocity of fluid, [m/s]\n\n Returns\n -------\n Eu : float\n Euler number []\n\n Notes\n -----\n Used in pressure drop calculations.\n Rarely, this number is divided by two.\n Named after Leonhard Euler who applied calculus to fluid dynamics.\n\n .. math::\n Eu = \\frac{\\text{Pressure drop}}{2\\cdot \\text{velocity head}}\n\n Examples\n --------\n >>> Euler(1E5, 1000., 4)\n 6.25\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return dP/(rho*V*V)\n\ndef Cavitation(P: float, Psat: float, rho: float, V: float) -> float:\n r\"\"\"Calculates Cavitation number or `Ca` for a fluid of velocity `V` with\n a pressure `P`, vapor pressure `Psat`, and density `rho`.\n\n .. math::\n Ca = \\sigma_c = \\sigma = \\frac{P-P_{sat}}{\\frac{1}{2}\\rho V^2}\n\n Parameters\n ----------\n P : float\n Internal pressure of the fluid, [Pa]\n Psat : float\n Vapor pressure of the fluid, [Pa]\n rho : float\n Density of the fluid, [kg/m^3]\n V : float\n Velocity of fluid, [m/s]\n\n Returns\n -------\n Ca : float\n Cavitation number []\n\n Notes\n -----\n Used in determining if a flow through a restriction will cavitate.\n Sometimes, the multiplication by 2 will be omitted;\n\n .. math::\n Ca = \\frac{\\text{Pressure - Vapor pressure}}\n {\\text{Inertial pressure}}\n\n Examples\n --------\n >>> Cavitation(2E5, 1E4, 1000, 10)\n 3.8\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return (P-Psat)/(0.5*rho*V*V)\n\ndef Eckert(V: float, Cp: float, dT: float) -> float:\n r\"\"\"Calculates Eckert number or `Ec` for a fluid of velocity `V` with\n a heat capacity `Cp`, between two temperature given as `dT`.\n\n .. math::\n Ec = \\frac{V^2}{C_p \\Delta T}\n\n Parameters\n ----------\n V : float\n Velocity of fluid, [m/s]\n Cp : float\n Heat capacity of the fluid, [J/kg/K]\n dT : float\n Temperature difference, [K]\n\n Returns\n -------\n Ec : float\n Eckert number []\n\n Notes\n -----\n Used in certain heat transfer calculations. Fairly rare.\n\n .. math::\n Ec = \\frac{\\text{Kinetic energy} }{ \\text{Enthalpy difference}}\n\n Examples\n --------\n >>> Eckert(10, 2000., 25.)\n 0.002\n\n References\n ----------\n .. [1] Goldstein, Richard J. ECKERT NUMBER. Thermopedia. Hemisphere, 2011.\n 10.1615/AtoZ.e.eckert_number\n \"\"\"\n return V*V/(Cp*dT)\n\ndef Jakob(Cp: float, Hvap: float, Te: float) -> float:\n r\"\"\"Calculates Jakob number or `Ja` for a boiling fluid with sensible heat\n capacity `Cp`, enthalpy of vaporization `Hvap`, and boiling at `Te` degrees\n above its saturation boiling point.\n\n .. math::\n Ja = \\frac{C_{P}\\Delta T_e}{\\Delta H_{vap}}\n\n Parameters\n ----------\n Cp : float\n Heat capacity of the fluid, [J/kg/K]\n Hvap : float\n Enthalpy of vaporization of the fluid at its saturation temperature [J/kg]\n Te : float\n Temperature difference above the fluid's saturation boiling temperature, [K]\n\n Returns\n -------\n Ja : float\n Jakob number []\n\n Notes\n -----\n Used in boiling heat transfer analysis. Fairly rare.\n\n .. math::\n Ja = \\frac{\\Delta \\text{Sensible heat}}{\\Delta \\text{Latent heat}}\n\n Examples\n --------\n >>> Jakob(4000., 2E6, 10.)\n 0.02\n\n References\n ----------\n .. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n Wiley, 2011.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return Cp*Te/Hvap\n\ndef Power_number(P: float, L: float, N: float, rho: float) -> float:\n r\"\"\"Calculates power number, `Po`, for an agitator applying a specified\n power `P` with a characteristic length `L`, rotational speed `N`, to\n a fluid with a specified density `rho`.\n\n .. math::\n Po = \\frac{P}{\\rho N^3 D^5}\n\n Parameters\n ----------\n P : float\n Power applied, [W]\n L : float\n Characteristic length, typically agitator diameter [m]\n N : float\n Speed [revolutions/second]\n rho : float\n Density of fluid, [kg/m^3]\n\n Returns\n -------\n Po : float\n Power number []\n\n Notes\n -----\n Used in mixing calculations.\n\n .. math::\n Po = \\frac{\\text{Power}}{\\text{Rotational inertia}}\n\n Examples\n --------\n >>> Power_number(P=180, L=0.01, N=2.5, rho=800.)\n 144000000.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return P/(rho*N*N*N*L**5)\n\ndef Drag(F: float, A: float, V: float, rho: float) -> float:\n r\"\"\"Calculates drag coefficient `Cd` for a given drag force `F`,\n projected area `A`, characteristic velocity `V`, and density `rho`.\n\n .. math::\n C_D = \\frac{F_d}{A\\cdot\\frac{1}{2}\\rho V^2}\n\n Parameters\n ----------\n F : float\n Drag force, [N]\n A : float\n Projected area, [m^2]\n V : float\n Characteristic velocity, [m/s]\n rho : float\n Density, [kg/m^3]\n\n Returns\n -------\n Cd : float\n Drag coefficient, [-]\n\n Notes\n -----\n Used in flow around objects, or objects flowing within a fluid.\n\n .. math::\n C_D = \\frac{\\text{Drag forces}}{\\text{Projected area}\\cdot\n \\text{Velocity head}}\n\n Examples\n --------\n >>> Drag(1000, 0.0001, 5, 2000)\n 400.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return F/(0.5*A*rho*V*V)\n\ndef Stokes_number(V: float, Dp: float, D: float, rhop: float, mu: float) -> float:\n r\"\"\"Calculates Stokes Number for a given characteristic velocity `V`,\n particle diameter `Dp`, characteristic diameter `D`, particle density\n `rhop`, and fluid viscosity `mu`.\n\n .. math::\n \\text{Stk} = \\frac{\\rho_p V D_p^2}{18\\mu_f D}\n\n Parameters\n ----------\n V : float\n Characteristic velocity (often superficial), [m/s]\n Dp : float\n Particle diameter, [m]\n D : float\n Characteristic diameter (ex demister wire diameter or cyclone\n diameter), [m]\n rhop : float\n Particle density, [kg/m^3]\n mu : float\n Fluid viscosity, [Pa*s]\n\n Returns\n -------\n Stk : float\n Stokes number, [-]\n\n Notes\n -----\n Used in droplet impaction or collection studies.\n\n Examples\n --------\n >>> Stokes_number(V=0.9, Dp=1E-5, D=1E-3, rhop=1000, mu=1E-5)\n 0.5\n\n References\n ----------\n .. [1] Rhodes, Martin J. Introduction to Particle Technology. Wiley, 2013.\n .. [2] Al-Dughaither, Abdullah S., Ahmed A. Ibrahim, and Waheed A.\n Al-Masry. \"Investigating Droplet Separation Efficiency in Wire-Mesh Mist\n Eliminators in Bubble Column.\" Journal of Saudi Chemical Society 14, no.\n 4 (October 1, 2010): 331-39. https://doi.org/10.1016/j.jscs.2010.04.001.\n \"\"\"\n return rhop*V*(Dp*Dp)/(18.0*mu*D)\n\ndef Capillary(V: float, mu: float, sigma: float) -> float:\n r\"\"\"Calculates Capillary number `Ca` for a characteristic velocity `V`,\n viscosity `mu`, and surface tension `sigma`.\n\n .. math::\n Ca = \\frac{V \\mu}{\\sigma}\n\n Parameters\n ----------\n V : float\n Characteristic velocity, [m/s]\n mu : float\n Dynamic viscosity, [Pa*s]\n sigma : float\n Surface tension, [N/m]\n\n Returns\n -------\n Ca : float\n Capillary number, [-]\n\n Notes\n -----\n Used in porous media calculations and film flow calculations.\n Surface tension may gas-liquid, or liquid-liquid.\n\n .. math::\n Ca = \\frac{\\text{Viscous forces}}\n {\\text{Surface forces}}\n\n Examples\n --------\n >>> Capillary(1.2, 0.01, .1)\n 0.12\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Kundu, Pijush K., Ira M. Cohen, and David R. Dowling. Fluid\n Mechanics. Academic Press, 2012.\n \"\"\"\n return V*mu/sigma\n\ndef Archimedes(L: float, rhof: float, rhop: float, mu: float, g: float=g) -> float:\n r\"\"\"Calculates Archimedes number, `Ar`, for a fluid and particle with the\n given densities, characteristic length, viscosity, and gravity\n (usually diameter of particle).\n\n .. math::\n Ar = \\frac{L^3 \\rho_f(\\rho_p-\\rho_f)g}{\\mu^2}\n\n Parameters\n ----------\n L : float\n Characteristic length, typically particle diameter [m]\n rhof : float\n Density of fluid, [kg/m^3]\n rhop : float\n Density of particle, [kg/m^3]\n mu : float\n Viscosity of fluid, [Pa*s]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Ar : float\n Archimedes number []\n\n Notes\n -----\n Used in fluid-particle interaction calculations.\n\n .. math::\n Ar = \\frac{\\text{Gravitational force}}{\\text{Viscous force}}\n\n Examples\n --------\n >>> Archimedes(0.002, 2., 3000, 1E-3)\n 470.4053872\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return L*L*L*rhof*(rhop-rhof)*g/(mu*mu)\n\ndef Ohnesorge(L: float, rho: float, mu: float, sigma: float) -> float:\n r\"\"\"Calculates Ohnesorge number, `Oh`, for a fluid with the given\n characteristic length, density, viscosity, and surface tension.\n\n .. math::\n \\text{Oh} = \\frac{\\mu}{\\sqrt{\\rho \\sigma L }}\n\n Parameters\n ----------\n L : float\n Characteristic length [m]\n rho : float\n Density of fluid, [kg/m^3]\n mu : float\n Viscosity of fluid, [Pa*s]\n sigma : float\n Surface tension, [N/m]\n\n Returns\n -------\n Oh : float\n Ohnesorge number []\n\n Notes\n -----\n Often used in spray calculations. Sometimes given the symbol Z.\n\n .. math::\n Oh = \\frac{\\sqrt{\\text{We}}}{\\text{Re}}= \\frac{\\text{viscous forces}}\n {\\sqrt{\\text{Inertia}\\cdot\\text{Surface tension}} }\n\n Examples\n --------\n >>> Ohnesorge(1E-4, 1000., 1E-3, 1E-1)\n 0.01\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return mu/sqrt(L*rho*sigma)\n\ndef Suratman(L: float, rho: float, mu: float, sigma: float) -> float:\n r\"\"\"Calculates Suratman number, `Su`, for a fluid with the given\n characteristic length, density, viscosity, and surface tension.\n\n .. math::\n \\text{Su} = \\frac{\\rho\\sigma L}{\\mu^2}\n\n Parameters\n ----------\n L : float\n Characteristic length [m]\n rho : float\n Density of fluid, [kg/m^3]\n mu : float\n Viscosity of fluid, [Pa*s]\n sigma : float\n Surface tension, [N/m]\n\n Returns\n -------\n Su : float\n Suratman number []\n\n Notes\n -----\n Also known as Laplace number. Used in two-phase flow, especially the\n bubbly-slug regime. No confusion regarding the definition of this group\n has been observed.\n\n .. math::\n \\text{Su} = \\frac{\\text{Re}^2}{\\text{We}} =\\frac{\\text{Inertia}\\cdot\n \\text{Surface tension} }{\\text{(viscous forces)}^2}\n\n The oldest reference to this group found by the author is in 1963, from\n [2]_.\n\n Examples\n --------\n >>> Suratman(1E-4, 1000., 1E-3, 1E-1)\n 10000.0\n\n References\n ----------\n .. [1] Sen, Nilava. \"Suratman Number in Bubble-to-Slug Flow Pattern\n Transition under Microgravity.\" Acta Astronautica 65, no. 3-4 (August\n 2009): 423-28. doi:10.1016/j.actaastro.2009.02.013.\n .. [2] Catchpole, John P., and George. Fulford. \"DIMENSIONLESS GROUPS.\"\n Industrial & Engineering Chemistry 58, no. 3 (March 1, 1966): 46-60.\n doi:10.1021/ie50675a012.\n \"\"\"\n return rho*sigma*L/(mu*mu)\n\ndef Hagen(Re: float, fd: float) -> float:\n r\"\"\"Calculates Hagen number, `Hg`, for a fluid with the given\n Reynolds number and friction factor.\n\n .. math::\n \\text{Hg} = \\frac{f_d}{2} Re^2 = \\frac{1}{\\rho}\n \\frac{\\Delta P}{\\Delta z} \\frac{D^3}{\\nu^2}\n = \\frac{\\rho\\Delta P D^3}{\\mu^2 \\Delta z}\n\n Parameters\n ----------\n Re : float\n Reynolds number [-]\n fd : float, optional\n Darcy friction factor, [-]\n\n Returns\n -------\n Hg : float\n Hagen number, [-]\n\n Notes\n -----\n Introduced in [1]_; further use of it is mostly of the correlations\n introduced in [1]_.\n\n Notable for use in correlations, because it does not have any\n dependence on velocity.\n\n This expression is useful when designing backwards with a pressure drop\n spec already known.\n\n Examples\n --------\n Example from [3]_:\n\n >>> Hagen(Re=2610, fd=1.935235)\n 6591507.17175\n\n References\n ----------\n .. [1] Martin, Holger. \"The Generalized Lévêque Equation and Its Practical\n Use for the Prediction of Heat and Mass Transfer Rates from Pressure\n Drop.\" Chemical Engineering Science, Jean-Claude Charpentier\n Festschrift Issue, 57, no. 16 (August 1, 2002): 3217-23.\n https://doi.org/10.1016/S0009-2509(02)00194-X.\n .. [2] Shah, Ramesh K., and Dusan P. Sekulic. Fundamentals of Heat\n Exchanger Design. 1st edition. Hoboken, NJ: Wiley, 2002.\n .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n Berlin; New York:: Springer, 2010.\n \"\"\"\n return 0.5*fd*Re*Re\n\ndef Bejan_L(dP: float, L: float, mu: float, alpha: float) -> float:\n r\"\"\"Calculates Bejan number of a length or `Be_L` for a fluid with the\n given parameters flowing over a characteristic length `L` and experiencing\n a pressure drop `dP`.\n\n .. math::\n Be_L = \\frac{\\Delta P L^2}{\\mu \\alpha}\n\n Parameters\n ----------\n dP : float\n Pressure drop, [Pa]\n L : float\n Characteristic length, [m]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n alpha : float\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Be_L : float\n Bejan number with respect to length []\n\n Notes\n -----\n Termed a dimensionless number by someone in 1988.\n\n Examples\n --------\n >>> Bejan_L(1E4, 1, 1E-3, 1E-6)\n 10000000000000.0\n\n References\n ----------\n .. [1] Awad, M. M. \"The Science and the History of the Two Bejan Numbers.\"\n International Journal of Heat and Mass Transfer 94 (March 2016): 101-3.\n doi:10.1016/j.ijheatmasstransfer.2015.11.073.\n .. [2] Bejan, Adrian. Convection Heat Transfer. 4E. Hoboken, New Jersey:\n Wiley, 2013.\n \"\"\"\n return dP*L*L/(alpha*mu)\n\ndef Bejan_p(dP: float, K: float, mu: float, alpha: float) -> float:\n r\"\"\"Calculates Bejan number of a permeability or `Be_p` for a fluid with\n the given parameters and a permeability `K` experiencing a pressure drop\n `dP`.\n\n .. math::\n Be_p = \\frac{\\Delta P K}{\\mu \\alpha}\n\n Parameters\n ----------\n dP : float\n Pressure drop, [Pa]\n K : float\n Permeability, [m^2]\n mu : float\n Dynamic viscosity, [Pa*s]\n alpha : float\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Be_p : float\n Bejan number with respect to pore characteristics []\n\n Notes\n -----\n Termed a dimensionless number by someone in 1988.\n\n Examples\n --------\n >>> Bejan_p(1E4, 1, 1E-3, 1E-6)\n 10000000000000.0\n\n References\n ----------\n .. [1] Awad, M. M. \"The Science and the History of the Two Bejan Numbers.\"\n International Journal of Heat and Mass Transfer 94 (March 2016): 101-3.\n doi:10.1016/j.ijheatmasstransfer.2015.11.073.\n .. [2] Bejan, Adrian. Convection Heat Transfer. 4E. Hoboken, New Jersey:\n Wiley, 2013.\n \"\"\"\n return dP*K/(alpha*mu)\n\ndef Boiling(G: float, q: float, Hvap: float) -> float:\n r\"\"\"Calculates Boiling number or `Bg` using heat flux, two-phase mass flux,\n and heat of vaporization of the fluid flowing. Used in two-phase heat\n transfer calculations.\n\n .. math::\n \\text{Bg} = \\frac{q}{G_{tp} \\Delta H_{vap}}\n\n Parameters\n ----------\n G : float\n Two-phase mass flux in a channel (combined liquid and vapor) [kg/m^2/s]\n q : float\n Heat flux [W/m^2]\n Hvap : float\n Heat of vaporization of the fluid [J/kg]\n\n Returns\n -------\n Bg : float\n Boiling number [-]\n\n Notes\n -----\n Most often uses the symbol `Bo` instead of `Bg`, but this conflicts with\n Bond number.\n\n .. math::\n \\text{Bg} = \\frac{\\text{mass liquid evaporated / area heat transfer\n surface}}{\\text{mass flow rate fluid / flow cross sectional area}}\n\n First defined in [4]_, though not named.\n\n Examples\n --------\n >>> Boiling(300, 3000, 800000)\n 1.25e-05\n\n References\n ----------\n .. [1] Winterton, Richard H.S. BOILING NUMBER. Thermopedia. Hemisphere,\n 2011. 10.1615/AtoZ.b.boiling_number\n .. [2] Collier, John G., and John R. Thome. Convective Boiling and\n Condensation. 3rd edition. Clarendon Press, 1996.\n .. [3] Stephan, Karl. Heat Transfer in Condensation and Boiling. Translated\n by C. V. Green.. 1992 edition. Berlin; New York: Springer, 2013.\n .. [4] W. F. Davidson, P. H. Hardie, C. G. R. Humphreys, A. A. Markson,\n A. R. Mumford and T. Ravese \"Studies of heat transmission through boiler\n tubing at pressures from 500 to 3300 pounds\" Trans. ASME, Vol. 65, 9,\n February 1943, pp. 553-591.\n \"\"\"\n return q/(G*Hvap)\n\ndef Dean(Re: float, Di: float, D: float) -> float:\n r\"\"\"Calculates Dean number, `De`, for a fluid with the Reynolds number `Re`,\n inner diameter `Di`, and a secondary diameter `D`. `D` may be the\n diameter of curvature, the diameter of a spiral, or some other dimension.\n\n .. math::\n \\text{De} = \\sqrt{\\frac{D_i}{D}} \\text{Re} = \\sqrt{\\frac{D_i}{D}}\n \\frac{\\rho v D}{\\mu}\n\n Parameters\n ----------\n Re : float\n Reynolds number []\n Di : float\n Inner diameter []\n D : float\n Diameter of curvature or outer spiral or other dimension []\n\n Returns\n -------\n De : float\n Dean number [-]\n\n Notes\n -----\n Used in flow in curved geometry.\n\n .. math::\n \\text{De} = \\frac{\\sqrt{\\text{centripetal forces}\\cdot\n \\text{inertial forces}}}{\\text{viscous forces}}\n\n Examples\n --------\n >>> Dean(10000, 0.1, 0.4)\n 5000.0\n\n References\n ----------\n .. [1] Catchpole, John P., and George. Fulford. \"DIMENSIONLESS GROUPS.\"\n Industrial & Engineering Chemistry 58, no. 3 (March 1, 1966): 46-60.\n doi:10.1021/ie50675a012.\n \"\"\"\n return sqrt(Di/D)*Re\n\ndef relative_roughness(D: float, roughness: float=1.52e-06) -> float:\n r\"\"\"Calculates relative roughness `eD` using a diameter and the roughness\n of the material of the wall. Default roughness is that of steel.\n\n .. math::\n eD=\\frac{\\epsilon}{D}\n\n Parameters\n ----------\n D : float\n Diameter of pipe, [m]\n roughness : float, optional\n Roughness of pipe wall [m]\n\n Returns\n -------\n eD : float\n Relative Roughness, [-]\n\n Examples\n --------\n >>> relative_roughness(0.5, 1E-4)\n 0.0002\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return roughness/D\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 57102}, "tests/test_core.py::204": {"resolved_imports": ["fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["Archimedes", "Bejan_L", "Bejan_p", "Biot", "Boiling", "Bond", "Capillary", "Cavitation", "Confinement", "Dean", "Drag", "Eckert", "Euler", "Fourier_heat", "Fourier_mass", "Froude", "Froude_densimetric", "Graetz_heat", "Grashof", "Hagen", "Jakob", "Knudsen", "Lewis", "Mach", "Morton", "Nusselt", "Ohnesorge", "Peclet_heat", "Peclet_mass", "Power_number", "Prandtl", "Rayleigh", "Reynolds", "Schmidt", "Sherwood", "Stanton", "Stokes_number", "Strouhal", "Suratman", "Weber", "assert_close", "assert_close1d", "pytest", "relative_roughness"], "enclosing_function": "test_core_dimensionless", "extracted_code": "# Source: fluids/core.py\ndef Reynolds(V: float, D: float, rho: float | None=None, mu: float | None=None, nu: float | None=None) -> float:\n r\"\"\"Calculates Reynolds number or `Re` for a fluid with the given\n properties for the specified velocity and diameter.\n\n .. math::\n Re = \\frac{D \\cdot V}{\\nu} = \\frac{\\rho V D}{\\mu}\n\n Inputs either of any of the following sets:\n\n * V, D, density `rho` and dynamic viscosity `mu`\n * V, D, and kinematic viscosity `nu`\n\n Parameters\n ----------\n V : float\n Velocity [m/s]\n D : float\n Diameter [m]\n rho : float, optional\n Density, [kg/m^3]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n\n Returns\n -------\n Re : float\n Reynolds number []\n\n Notes\n -----\n .. math::\n Re = \\frac{\\text{Momentum}}{\\text{Viscosity}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Reynolds(2.5, 0.25, 1.1613, 1.9E-5)\n 38200.65789473684\n >>> Reynolds(2.5, 0.25, nu=1.636e-05)\n 38202.93398533008\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and mu is not None:\n nu = mu/rho\n elif nu is None:\n raise ValueError(\"Either density and viscosity, or kinematic viscosity is needed\")\n return V*D/nu\n\ndef Peclet_heat(V: float, L: float, rho: float | None=None, Cp: float | None=None, k: float | None=None, alpha: float | None=None) -> float:\n r\"\"\"Calculates heat transfer Peclet number or `Pe` for a specified velocity\n `V`, characteristic length `L`, and specified properties for the given\n fluid.\n\n .. math::\n Pe = \\frac{VL\\rho C_p}{k} = \\frac{LV}{\\alpha}\n\n Inputs either of any of the following sets:\n\n * V, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k`\n * V, L, and thermal diffusivity `alpha`\n\n Parameters\n ----------\n V : float\n Velocity [m/s]\n L : float\n Characteristic length [m]\n rho : float, optional\n Density, [kg/m^3]\n Cp : float, optional\n Heat capacity, [J/kg/K]\n k : float, optional\n Thermal conductivity, [W/m/K]\n alpha : float, optional\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Pe : float\n Peclet number (heat) []\n\n Notes\n -----\n .. math::\n Pe = \\frac{\\text{Bulk heat transfer}}{\\text{Conduction heat transfer}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Peclet_heat(1.5, 2, 1000., 4000., 0.6)\n 20000000.0\n >>> Peclet_heat(1.5, 2, alpha=1E-7)\n 30000000.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and Cp is not None and k is not None:\n alpha = k/(rho*Cp)\n elif alpha is None:\n raise ValueError(\"Either heat capacity and thermal conductivity and density, or thermal diffusivity is needed\")\n return V*L/alpha\n\ndef Peclet_mass(V: float, L: float, D: float) -> float:\n r\"\"\"Calculates mass transfer Peclet number or `Pe` for a specified velocity\n `V`, characteristic length `L`, and diffusion coefficient `D`.\n\n .. math::\n Pe = \\frac{L V}{D}\n\n Parameters\n ----------\n V : float\n Velocity [m/s]\n L : float\n Characteristic length [m]\n D : float\n Diffusivity of a species, [m^2/s]\n\n Returns\n -------\n Pe : float\n Peclet number (mass) []\n\n Notes\n -----\n .. math::\n Pe = \\frac{\\text{Advective transport rate}}{\\text{Diffusive transport rate}}\n\n Examples\n --------\n >>> Peclet_mass(1.5, 2, 1E-9)\n 3000000000.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return V*L/D\n\ndef Fourier_heat(t: float, L: float, rho: float | None=None, Cp: float | None=None, k: float | None=None, alpha: float | None=None) -> float:\n r\"\"\"Calculates heat transfer Fourier number or `Fo` for a specified time\n `t`, characteristic length `L`, and specified properties for the given\n fluid.\n\n .. math::\n Fo = \\frac{k t}{C_p \\rho L^2} = \\frac{\\alpha t}{L^2}\n\n Inputs either of any of the following sets:\n\n * t, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k`\n * t, L, and thermal diffusivity `alpha`\n\n Parameters\n ----------\n t : float\n time [s]\n L : float\n Characteristic length [m]\n rho : float, optional\n Density, [kg/m^3]\n Cp : float, optional\n Heat capacity, [J/kg/K]\n k : float, optional\n Thermal conductivity, [W/m/K]\n alpha : float, optional\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Fo : float\n Fourier number (heat) []\n\n Notes\n -----\n .. math::\n Fo = \\frac{\\text{Heat conduction rate}}\n {\\text{Rate of thermal energy storage in a solid}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Fourier_heat(t=1.5, L=2, rho=1000., Cp=4000., k=0.6)\n 5.625e-08\n >>> Fourier_heat(1.5, 2, alpha=1E-7)\n 3.75e-08\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and Cp is not None and k is not None:\n alpha = k/(rho*Cp)\n elif alpha is None:\n raise ValueError(\"Either heat capacity and thermal conductivity and density, or thermal diffusivity is needed\")\n return t*alpha/(L*L)\n\ndef Fourier_mass(t: float, L: float, D: float) -> float:\n r\"\"\"Calculates mass transfer Fourier number or `Fo` for a specified time\n `t`, characteristic length `L`, and diffusion coefficient `D`.\n\n .. math::\n Fo = \\frac{D t}{L^2}\n\n Parameters\n ----------\n t : float\n time [s]\n L : float\n Characteristic length [m]\n D : float\n Diffusivity of a species, [m^2/s]\n\n Returns\n -------\n Fo : float\n Fourier number (mass) []\n\n Notes\n -----\n .. math::\n Fo = \\frac{\\text{Diffusive transport rate}}{\\text{Storage rate}}\n\n Examples\n --------\n >>> Fourier_mass(t=1.5, L=2, D=1E-9)\n 3.7500000000000005e-10\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return t*D/(L*L)\n\ndef Graetz_heat(V: float, D: float, x: float, rho: float | None=None, Cp: float | None=None, k: float | None=None, alpha: float | None=None) -> float:\n r\"\"\"Calculates Graetz number or `Gz` for a specified velocity\n `V`, diameter `D`, axial distance `x`, and specified properties for the\n given fluid.\n\n .. math::\n Gz = \\frac{VD^2\\cdot C_p \\rho}{x\\cdot k} = \\frac{VD^2}{x \\alpha}\n\n Inputs either of any of the following sets:\n\n * V, D, x, density `rho`, heat capacity `Cp`, and thermal conductivity `k`\n * V, D, x, and thermal diffusivity `alpha`\n\n Parameters\n ----------\n V : float\n Velocity, [m/s]\n D : float\n Diameter [m]\n x : float\n Axial distance [m]\n rho : float, optional\n Density, [kg/m^3]\n Cp : float, optional\n Heat capacity, [J/kg/K]\n k : float, optional\n Thermal conductivity, [W/m/K]\n alpha : float, optional\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Gz : float\n Graetz number []\n\n Notes\n -----\n .. math::\n Gz = \\frac{\\text{Time for radial heat diffusion in a fluid by conduction}}\n {\\text{Time taken by fluid to reach distance x}}\n\n .. math::\n Gz = \\frac{D}{x}RePr\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Graetz_heat(1.5, 0.25, 5, 800., 2200., 0.6)\n 55000.0\n >>> Graetz_heat(1.5, 0.25, 5, alpha=1E-7)\n 187500.0\n\n References\n ----------\n .. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n Wiley, 2011.\n \"\"\"\n if rho is not None and Cp is not None and k is not None:\n alpha = k/(rho*Cp)\n elif alpha is None:\n raise ValueError(\"Either heat capacity and thermal conductivity and density, or thermal diffusivity is needed\")\n return V*D*D/(x*alpha)\n\ndef Schmidt(D: float, mu: float | None=None, nu: float | None=None, rho: float | None=None) -> float:\n r\"\"\"Calculates Schmidt number or `Sc` for a fluid with the given\n parameters.\n\n .. math::\n Sc = \\frac{\\mu}{D\\rho} = \\frac{\\nu}{D}\n\n Inputs can be any of the following sets:\n\n * Diffusivity, dynamic viscosity, and density\n * Diffusivity and kinematic viscosity\n\n Parameters\n ----------\n D : float\n Diffusivity of a species, [m^2/s]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n rho : float, optional\n Density, [kg/m^3]\n\n Returns\n -------\n Sc : float\n Schmidt number []\n\n Notes\n -----\n .. math::\n Sc =\\frac{\\text{kinematic viscosity}}{\\text{molecular diffusivity}}\n = \\frac{\\text{viscous diffusivity}}{\\text{species diffusivity}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Schmidt(D=2E-6, mu=4.61E-6, rho=800)\n 0.00288125\n >>> Schmidt(D=1E-9, nu=6E-7)\n 599.9999999999999\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and mu is not None:\n return mu/(rho*D)\n elif nu is not None:\n return nu/D\n else:\n raise ValueError(\"Insufficient information provided for Schmidt number calculation\")\n\ndef Lewis(D: float, alpha: float | None=None, Cp: float | None=None, k: float | None=None, rho: float | None=None) -> float:\n r\"\"\"Calculates Lewis number or `Le` for a fluid with the given parameters.\n\n .. math::\n Le = \\frac{k}{\\rho C_p D} = \\frac{\\alpha}{D}\n\n Inputs can be either of the following sets:\n\n * Diffusivity and Thermal diffusivity\n * Diffusivity, heat capacity, thermal conductivity, and density\n\n Parameters\n ----------\n D : float\n Diffusivity of a species, [m^2/s]\n alpha : float, optional\n Thermal diffusivity, [m^2/s]\n Cp : float, optional\n Heat capacity, [J/kg/K]\n k : float, optional\n Thermal conductivity, [W/m/K]\n rho : float, optional\n Density, [kg/m^3]\n\n Returns\n -------\n Le : float\n Lewis number []\n\n Notes\n -----\n .. math::\n Le=\\frac{\\text{Thermal diffusivity}}{\\text{Mass diffusivity}} =\n \\frac{Sc}{Pr}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Lewis(D=22.6E-6, alpha=19.1E-6)\n 0.8451327433628318\n >>> Lewis(D=22.6E-6, rho=800., k=.2, Cp=2200)\n 0.00502815768302494\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n Berlin; New York:: Springer, 2010.\n \"\"\"\n if D is None:\n raise ValueError(\"Diffusivity D is required for Le calculation\")\n if k is not None and Cp is not None and rho is not None:\n alpha = k/(rho*Cp)\n elif alpha is None:\n raise ValueError(\"Insufficient information provided for Le calculation\")\n return alpha/D\n\ndef Weber(V: float, L: float, rho: float, sigma: float) -> float:\n r\"\"\"Calculates Weber number, `We`, for a fluid with the given density,\n surface tension, velocity, and geometric parameter (usually diameter\n of bubble).\n\n .. math::\n We = \\frac{V^2 L\\rho}{\\sigma}\n\n Parameters\n ----------\n V : float\n Velocity of fluid, [m/s]\n L : float\n Characteristic length, typically bubble diameter [m]\n rho : float\n Density of fluid, [kg/m^3]\n sigma : float\n Surface tension, [N/m]\n\n Returns\n -------\n We : float\n Weber number []\n\n Notes\n -----\n Used in bubble calculations.\n\n .. math::\n We = \\frac{\\text{inertial force}}{\\text{surface tension force}}\n\n Examples\n --------\n >>> Weber(V=0.18, L=0.001, rho=900., sigma=0.01)\n 2.916\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n Berlin; New York:: Springer, 2010.\n \"\"\"\n return V*V*L*rho/sigma\n\ndef Mach(V: float, c: float) -> float:\n r\"\"\"Calculates Mach number or `Ma` for a fluid of velocity `V` with speed\n of sound `c`.\n\n .. math::\n Ma = \\frac{V}{c}\n\n Parameters\n ----------\n V : float\n Velocity of fluid, [m/s]\n c : float\n Speed of sound in fluid, [m/s]\n\n Returns\n -------\n Ma : float\n Mach number []\n\n Notes\n -----\n Used in compressible flow calculations.\n\n .. math::\n Ma = \\frac{\\text{fluid velocity}}{\\text{sonic velocity}}\n\n Examples\n --------\n >>> Mach(33., 330)\n 0.1\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return V/c\n\ndef Confinement(D: float, rhol: float, rhog: float, sigma: float, g: float=g) -> float:\n r\"\"\"Calculates Confinement number or `Co` for a fluid in a channel of\n diameter `D` with liquid and gas densities `rhol` and `rhog` and surface\n tension `sigma`, under the influence of gravitational force `g`.\n\n .. math::\n \\text{Co}=\\frac{\\left[\\frac{\\sigma}{g(\\rho_l-\\rho_g)}\\right]^{0.5}}{D}\n\n Parameters\n ----------\n D : float\n Diameter of channel, [m]\n rhol : float\n Density of liquid phase, [kg/m^3]\n rhog : float\n Density of gas phase, [kg/m^3]\n sigma : float\n Surface tension between liquid-gas phase, [N/m]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Co : float\n Confinement number [-]\n\n Notes\n -----\n Used in two-phase pressure drop and heat transfer correlations. First used\n in [1]_ according to [3]_.\n\n .. math::\n \\text{Co} = \\frac{\\frac{\\text{surface tension force}}\n {\\text{buoyancy force}}}{\\text{Channel area}}\n\n Examples\n --------\n >>> Confinement(0.001, 1077, 76.5, 4.27E-3)\n 0.6596978265315191\n\n References\n ----------\n .. [1] Cornwell, Keith, and Peter A. Kew. \"Boiling in Small Parallel\n Channels.\" In Energy Efficiency in Process Technology, edited by Dr P.\n A. Pilavachi, 624-638. Springer Netherlands, 1993.\n doi:10.1007/978-94-011-1454-7_56.\n .. [2] Kandlikar, Satish G. Heat Transfer and Fluid Flow in Minichannels\n and Microchannels. Elsevier, 2006.\n .. [3] Tran, T. N, M. -C Chyu, M. W Wambsganss, and D. M France. Two-Phase\n Pressure Drop of Refrigerants during Flow Boiling in Small Channels: An\n Experimental Investigation and Correlation Development.\" International\n Journal of Multiphase Flow 26, no. 11 (November 1, 2000): 1739-54.\n doi:10.1016/S0301-9322(99)00119-6.\n \"\"\"\n return sqrt(sigma/(g*(rhol-rhog)))/D\n\ndef Morton(rhol: float, rhog: float, mul: float, sigma: float, g: float=g) -> float:\n r\"\"\"Calculates Morton number or `Mo` for a liquid and vapor with the\n specified properties, under the influence of gravitational force `g`.\n\n .. math::\n Mo = \\frac{g \\mu_l^4(\\rho_l - \\rho_g)}{\\rho_l^2 \\sigma^3}\n\n Parameters\n ----------\n rhol : float\n Density of liquid phase, [kg/m^3]\n rhog : float\n Density of gas phase, [kg/m^3]\n mul : float\n Viscosity of liquid phase, [Pa*s]\n sigma : float\n Surface tension between liquid-gas phase, [N/m]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Mo : float\n Morton number, [-]\n\n Notes\n -----\n Used in modeling bubbles in liquid.\n\n Examples\n --------\n >>> Morton(1077.0, 76.5, 4.27E-3, 0.023)\n 2.311183104430743e-07\n\n References\n ----------\n .. [1] Kunes, Josef. Dimensionless Physical Quantities in Science and\n Engineering. Elsevier, 2012.\n .. [2] Yan, Xiaokang, Kaixin Zheng, Yan Jia, Zhenyong Miao, Lijun Wang,\n Yijun Cao, and Jiongtian Liu. “Drag Coefficient Prediction of a Single\n Bubble Rising in Liquids.” Industrial & Engineering Chemistry Research,\n April 2, 2018. https://doi.org/10.1021/acs.iecr.7b04743.\n \"\"\"\n mul2 = mul*mul\n return g*mul2*mul2*(rhol - rhog)/(rhol*rhol*sigma*sigma*sigma)\n\ndef Knudsen(path: float, L: float) -> float:\n r\"\"\"Calculates Knudsen number or `Kn` for a fluid with mean free path\n `path` and for a characteristic length `L`.\n\n .. math::\n Kn = \\frac{\\lambda}{L}\n\n Parameters\n ----------\n path : float\n Mean free path between molecular collisions, [m]\n L : float\n Characteristic length, [m]\n\n Returns\n -------\n Kn : float\n Knudsen number []\n\n Notes\n -----\n Used in mass transfer calculations.\n\n .. math::\n Kn = \\frac{\\text{Mean free path length}}{\\text{Characteristic length}}\n\n Examples\n --------\n >>> Knudsen(1e-10, .001)\n 1e-07\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return path/L\n\ndef Prandtl(Cp: float | None=None, k: float | None=None, mu: float | None=None, nu: float | None=None, rho: float | None=None, alpha: float | None=None) -> float:\n r\"\"\"Calculates Prandtl number or `Pr` for a fluid with the given\n parameters.\n\n .. math::\n Pr = \\frac{C_p \\mu}{k} = \\frac{\\nu}{\\alpha} = \\frac{C_p \\rho \\nu}{k}\n\n Inputs can be any of the following sets:\n\n * Heat capacity, dynamic viscosity, and thermal conductivity\n * Thermal diffusivity and kinematic viscosity\n * Heat capacity, kinematic viscosity, thermal conductivity, and density\n\n Parameters\n ----------\n Cp : float\n Heat capacity, [J/kg/K]\n k : float\n Thermal conductivity, [W/m/K]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n rho : float\n Density, [kg/m^3]\n alpha : float\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Pr : float\n Prandtl number []\n\n Notes\n -----\n .. math::\n Pr=\\frac{\\text{kinematic viscosity}}{\\text{thermal diffusivity}} = \\frac{\\text{momentum diffusivity}}{\\text{thermal diffusivity}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Prandtl(Cp=1637., k=0.010, mu=4.61E-6)\n 0.754657\n >>> Prandtl(Cp=1637., k=0.010, nu=6.4E-7, rho=7.1)\n 0.7438528\n >>> Prandtl(nu=6.3E-7, alpha=9E-7)\n 0.7000000000000001\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n Berlin; New York:: Springer, 2010.\n \"\"\"\n if k is not None and Cp is not None and mu is not None:\n return Cp*mu/k\n elif nu is not None and rho is not None and Cp is not None and k is not None:\n return nu*rho*Cp/k\n elif nu is not None and alpha is not None:\n return nu/alpha\n else:\n raise ValueError(\"Insufficient information provided for Pr calculation\")\n\ndef Grashof(L: float, beta: float, T1: float, T2: float=0, rho: float | None=None, mu: float | None=None, nu: float | None=None, g: float=g) -> float:\n r\"\"\"Calculates Grashof number or `Gr` for a fluid with the given\n properties, temperature difference, and characteristic length.\n\n .. math::\n Gr = \\frac{g\\beta (T_s-T_\\infty)L^3}{\\nu^2}\n = \\frac{g\\beta (T_s-T_\\infty)L^3\\rho^2}{\\mu^2}\n\n Inputs either of any of the following sets:\n\n * L, beta, T1 and T2, and density `rho` and dynamic viscosity `mu`\n * L, beta, T1 and T2, and kinematic viscosity `nu`\n\n Parameters\n ----------\n L : float\n Characteristic length [m]\n beta : float\n Volumetric thermal expansion coefficient [1/K]\n T1 : float\n Temperature 1, usually a film temperature [K]\n T2 : float, optional\n Temperature 2, usually a bulk temperature (or 0 if only a difference\n is provided to the function) [K]\n rho : float, optional\n Density, [kg/m^3]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Gr : float\n Grashof number []\n\n Notes\n -----\n .. math::\n Gr = \\frac{\\text{Buoyancy forces}}{\\text{Viscous forces}}\n\n An error is raised if none of the required input sets are provided.\n Used in free convection problems only.\n\n Examples\n --------\n Example 4 of [1]_, p. 1-21 (matches):\n\n >>> Grashof(L=0.9144, beta=0.000933, T1=178.2, rho=1.1613, mu=1.9E-5)\n 4656936556.178915\n >>> Grashof(L=0.9144, beta=0.000933, T1=378.2, T2=200, nu=1.636e-05)\n 4657491516.530312\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and mu is not None:\n nu = mu/rho\n elif nu is None:\n raise ValueError(\"Either density and viscosity, or kinematic viscosity is needed\")\n return g*beta*abs(T2-T1)*L*L*L/(nu*nu)\n\ndef Bond(rhol: float, rhog: float, sigma: float, L: float) -> float:\n r\"\"\"Calculates Bond number, `Bo` also known as Eotvos number,\n for a fluid with the given liquid and gas densities, surface tension,\n and geometric parameter (usually length).\n\n .. math::\n Bo = \\frac{g(\\rho_l-\\rho_g)L^2}{\\sigma}\n\n Parameters\n ----------\n rhol : float\n Density of liquid, [kg/m^3]\n rhog : float\n Density of gas, [kg/m^3]\n sigma : float\n Surface tension, [N/m]\n L : float\n Characteristic length, [m]\n\n Returns\n -------\n Bo : float\n Bond number []\n\n Examples\n --------\n >>> Bond(1000., 1.2, .0589, 2)\n 665187.2339558573\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return (g*(rhol-rhog)*L*L/sigma)\n\ndef Rayleigh(Pr: float, Gr: float) -> float:\n r\"\"\"Calculates Rayleigh number or `Ra` using Prandtl number `Pr` and\n Grashof number `Gr` for a fluid with the given\n properties, temperature difference, and characteristic length used\n to calculate `Gr` and `Pr`.\n\n .. math::\n Ra = PrGr\n\n Parameters\n ----------\n Pr : float\n Prandtl number []\n Gr : float\n Grashof number []\n\n Returns\n -------\n Ra : float\n Rayleigh number []\n\n Notes\n -----\n Used in free convection problems only.\n\n Examples\n --------\n >>> Rayleigh(1.2, 4.6E9)\n 5520000000.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return Pr*Gr\n\ndef Froude(V: float, L: float, g: float=g, squared: bool=False) -> float:\n r\"\"\"Calculates Froude number `Fr` for velocity `V` and geometric length\n `L`. If desired, gravity can be specified as well. Normally the function\n returns the result of the equation below; Froude number is also often\n said to be defined as the square of the equation below.\n\n .. math::\n Fr = \\frac{V}{\\sqrt{gL}}\n\n Parameters\n ----------\n V : float\n Velocity of the particle or fluid, [m/s]\n L : float\n Characteristic length, no typical definition [m]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n squared : bool, optional\n Whether to return the squared form of Froude number\n\n Returns\n -------\n Fr : float\n Froude number, [-]\n\n Notes\n -----\n Many alternate definitions including density ratios have been used.\n\n .. math::\n Fr = \\frac{\\text{Inertial Force}}{\\text{Gravity Force}}\n\n Examples\n --------\n >>> Froude(1.83, L=2., g=1.63)\n 1.0135432593877318\n >>> Froude(1.83, L=2., squared=True)\n 0.17074638128208924\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n Fr = V/sqrt(L*g)\n if squared:\n Fr *= Fr\n return Fr\n\ndef Froude_densimetric(V: float, L: float, rho1: float, rho2: float, heavy: bool=True, g: float=g) -> float:\n r\"\"\"Calculates the densimetric Froude number :math:`Fr_{den}` for velocity\n `V` geometric length `L`, heavier fluid density `rho1`, and lighter fluid\n density `rho2`. If desired, gravity can be specified as well. Depending on\n the application, this dimensionless number may be defined with the heavy\n phase or the light phase density in the numerator of the square root.\n For some applications, both need to be calculated. The default is to\n calculate with the heavy liquid density on top; set `heavy` to False\n to reverse this.\n\n .. math::\n Fr = \\frac{V}{\\sqrt{gL}} \\sqrt{\\frac{\\rho_\\text{(1 or 2)}}\n {\\rho_1 - \\rho_2}}\n\n Parameters\n ----------\n V : float\n Velocity of the specified phase, [m/s]\n L : float\n Characteristic length, no typical definition [m]\n rho1 : float\n Density of the heavier phase, [kg/m^3]\n rho2 : float\n Density of the lighter phase, [kg/m^3]\n heavy : bool, optional\n Whether or not the density used in the numerator is the heavy phase or\n the light phase, [-]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Fr_den : float\n Densimetric Froude number, [-]\n\n Notes\n -----\n Many alternate definitions including density ratios have been used.\n\n .. math::\n Fr = \\frac{\\text{Inertial Force}}{\\text{Gravity Force}}\n\n Where the gravity force is reduced by the relative densities of one fluid\n in another.\n\n Note that an Exception will be raised if rho1 < rho2, as the square root\n becomes negative.\n\n Examples\n --------\n >>> Froude_densimetric(1.83, L=2., rho1=800, rho2=1.2, g=9.81)\n 0.4134543386272418\n >>> Froude_densimetric(1.83, L=2., rho1=800, rho2=1.2, g=9.81, heavy=False)\n 0.016013017679205096\n\n References\n ----------\n .. [1] Hall, A, G Stobie, and R Steven. \"Further Evaluation of the\n Performance of Horizontally Installed Orifice Plate and Cone\n Differential Pressure Meters with Wet Gas Flows.\" In International\n SouthEast Asia Hydrocarbon Flow Measurement Workshop, KualaLumpur,\n Malaysia, 2008.\n \"\"\"\n if heavy:\n rho3 = rho1\n else:\n rho3 = rho2\n return V/(sqrt(g*L))*sqrt(rho3/(rho1 - rho2))\n\ndef Strouhal(f: float, L: float, V: float) -> float:\n r\"\"\"Calculates Strouhal number `St` for a characteristic frequency `f`,\n characteristic length `L`, and velocity `V`.\n\n .. math::\n St = \\frac{fL}{V}\n\n Parameters\n ----------\n f : float\n Characteristic frequency, usually that of vortex shedding, [Hz]\n L : float\n Characteristic length, [m]\n V : float\n Velocity of the fluid, [m/s]\n\n Returns\n -------\n St : float\n Strouhal number, [-]\n\n Notes\n -----\n Sometimes abbreviated to S or Sr.\n\n .. math::\n St = \\frac{\\text{Characteristic flow time}}\n {\\text{Period of oscillation}}\n\n Examples\n --------\n >>> Strouhal(8, 2., 4.)\n 4.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return f*L/V\n\ndef Nusselt(h: float, L: float, k: float) -> float:\n r\"\"\"Calculates Nusselt number `Nu` for a heat transfer coefficient `h`,\n characteristic length `L`, and thermal conductivity `k`.\n\n .. math::\n Nu = \\frac{hL}{k}\n\n Parameters\n ----------\n h : float\n Heat transfer coefficient, [W/m^2/K]\n L : float\n Characteristic length, no typical definition [m]\n k : float\n Thermal conductivity of fluid [W/m/K]\n\n Returns\n -------\n Nu : float\n Nusselt number, [-]\n\n Notes\n -----\n Do not confuse k, the thermal conductivity of the fluid, with that\n of a solid object!\n\n .. math::\n Nu = \\frac{\\text{Convective heat transfer}}\n {\\text{Conductive heat transfer}}\n\n Examples\n --------\n >>> Nusselt(1000., 1.2, 300.)\n 4.0\n >>> Nusselt(10000., .01, 4000.)\n 0.025\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n Wiley, 2011.\n \"\"\"\n return h*L/k\n\ndef Sherwood(K: float, L: float, D: float) -> float:\n r\"\"\"Calculates Sherwood number `Sh` for a mass transfer coefficient `K`,\n characteristic length `L`, and diffusivity `D`.\n\n .. math::\n Sh = \\frac{KL}{D}\n\n Parameters\n ----------\n K : float\n Mass transfer coefficient, [m/s]\n L : float\n Characteristic length, no typical definition [m]\n D : float\n Diffusivity of a species [m^2/s]\n\n Returns\n -------\n Sh : float\n Sherwood number, [-]\n\n Notes\n -----\n .. math::\n Sh = \\frac{\\text{Mass transfer by convection}}\n {\\text{Mass transfer by diffusion}} = \\frac{K}{D/L}\n\n Examples\n --------\n >>> Sherwood(1000., 1.2, 300.)\n 4.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return K*L/D\n\ndef Biot(h: float, L: float, k: float) -> float:\n r\"\"\"Calculates Biot number `Bi` for heat transfer coefficient `h`,\n geometric length `L`, and thermal conductivity `k`.\n\n .. math::\n Bi=\\frac{hL}{k}\n\n Parameters\n ----------\n h : float\n Heat transfer coefficient, [W/m^2/K]\n L : float\n Characteristic length, no typical definition [m]\n k : float\n Thermal conductivity, within the object [W/m/K]\n\n Returns\n -------\n Bi : float\n Biot number, [-]\n\n Notes\n -----\n Do not confuse k, the thermal conductivity within the object, with that\n of the medium h is calculated with!\n\n .. math::\n Bi = \\frac{\\text{Surface thermal resistance}}\n {\\text{Internal thermal resistance}}\n\n Examples\n --------\n >>> Biot(1000., 1.2, 300.)\n 4.0\n >>> Biot(10000., .01, 4000.)\n 0.025\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return h*L/k\n\ndef Stanton(h: float, V: float, rho: float, Cp: float) -> float:\n r\"\"\"Calculates Stanton number or `St` for a specified heat transfer\n coefficient `h`, velocity `V`, density `rho`, and heat capacity `Cp` [1]_\n [2]_.\n\n .. math::\n St = \\frac{h}{V\\rho Cp}\n\n Parameters\n ----------\n h : float\n Heat transfer coefficient, [W/m^2/K]\n V : float\n Velocity, [m/s]\n rho : float\n Density, [kg/m^3]\n Cp : float\n Heat capacity, [J/kg/K]\n\n Returns\n -------\n St : float\n Stanton number []\n\n Notes\n -----\n .. math::\n St = \\frac{\\text{Heat transfer coefficient}}{\\text{Thermal capacity}}\n\n Examples\n --------\n >>> Stanton(5000, 5, 800, 2000.)\n 0.000625\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n Wiley, 2011.\n \"\"\"\n return h/(V*rho*Cp)\n\ndef Euler(dP: float, rho: float, V: float) -> float:\n r\"\"\"Calculates Euler number or `Eu` for a fluid of velocity `V` and\n density `rho` experiencing a pressure drop `dP`.\n\n .. math::\n Eu = \\frac{\\Delta P}{\\rho V^2}\n\n Parameters\n ----------\n dP : float\n Pressure drop experience by the fluid, [Pa]\n rho : float\n Density of the fluid, [kg/m^3]\n V : float\n Velocity of fluid, [m/s]\n\n Returns\n -------\n Eu : float\n Euler number []\n\n Notes\n -----\n Used in pressure drop calculations.\n Rarely, this number is divided by two.\n Named after Leonhard Euler who applied calculus to fluid dynamics.\n\n .. math::\n Eu = \\frac{\\text{Pressure drop}}{2\\cdot \\text{velocity head}}\n\n Examples\n --------\n >>> Euler(1E5, 1000., 4)\n 6.25\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return dP/(rho*V*V)\n\ndef Cavitation(P: float, Psat: float, rho: float, V: float) -> float:\n r\"\"\"Calculates Cavitation number or `Ca` for a fluid of velocity `V` with\n a pressure `P`, vapor pressure `Psat`, and density `rho`.\n\n .. math::\n Ca = \\sigma_c = \\sigma = \\frac{P-P_{sat}}{\\frac{1}{2}\\rho V^2}\n\n Parameters\n ----------\n P : float\n Internal pressure of the fluid, [Pa]\n Psat : float\n Vapor pressure of the fluid, [Pa]\n rho : float\n Density of the fluid, [kg/m^3]\n V : float\n Velocity of fluid, [m/s]\n\n Returns\n -------\n Ca : float\n Cavitation number []\n\n Notes\n -----\n Used in determining if a flow through a restriction will cavitate.\n Sometimes, the multiplication by 2 will be omitted;\n\n .. math::\n Ca = \\frac{\\text{Pressure - Vapor pressure}}\n {\\text{Inertial pressure}}\n\n Examples\n --------\n >>> Cavitation(2E5, 1E4, 1000, 10)\n 3.8\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return (P-Psat)/(0.5*rho*V*V)\n\ndef Eckert(V: float, Cp: float, dT: float) -> float:\n r\"\"\"Calculates Eckert number or `Ec` for a fluid of velocity `V` with\n a heat capacity `Cp`, between two temperature given as `dT`.\n\n .. math::\n Ec = \\frac{V^2}{C_p \\Delta T}\n\n Parameters\n ----------\n V : float\n Velocity of fluid, [m/s]\n Cp : float\n Heat capacity of the fluid, [J/kg/K]\n dT : float\n Temperature difference, [K]\n\n Returns\n -------\n Ec : float\n Eckert number []\n\n Notes\n -----\n Used in certain heat transfer calculations. Fairly rare.\n\n .. math::\n Ec = \\frac{\\text{Kinetic energy} }{ \\text{Enthalpy difference}}\n\n Examples\n --------\n >>> Eckert(10, 2000., 25.)\n 0.002\n\n References\n ----------\n .. [1] Goldstein, Richard J. ECKERT NUMBER. Thermopedia. Hemisphere, 2011.\n 10.1615/AtoZ.e.eckert_number\n \"\"\"\n return V*V/(Cp*dT)\n\ndef Jakob(Cp: float, Hvap: float, Te: float) -> float:\n r\"\"\"Calculates Jakob number or `Ja` for a boiling fluid with sensible heat\n capacity `Cp`, enthalpy of vaporization `Hvap`, and boiling at `Te` degrees\n above its saturation boiling point.\n\n .. math::\n Ja = \\frac{C_{P}\\Delta T_e}{\\Delta H_{vap}}\n\n Parameters\n ----------\n Cp : float\n Heat capacity of the fluid, [J/kg/K]\n Hvap : float\n Enthalpy of vaporization of the fluid at its saturation temperature [J/kg]\n Te : float\n Temperature difference above the fluid's saturation boiling temperature, [K]\n\n Returns\n -------\n Ja : float\n Jakob number []\n\n Notes\n -----\n Used in boiling heat transfer analysis. Fairly rare.\n\n .. math::\n Ja = \\frac{\\Delta \\text{Sensible heat}}{\\Delta \\text{Latent heat}}\n\n Examples\n --------\n >>> Jakob(4000., 2E6, 10.)\n 0.02\n\n References\n ----------\n .. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n Wiley, 2011.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return Cp*Te/Hvap\n\ndef Power_number(P: float, L: float, N: float, rho: float) -> float:\n r\"\"\"Calculates power number, `Po`, for an agitator applying a specified\n power `P` with a characteristic length `L`, rotational speed `N`, to\n a fluid with a specified density `rho`.\n\n .. math::\n Po = \\frac{P}{\\rho N^3 D^5}\n\n Parameters\n ----------\n P : float\n Power applied, [W]\n L : float\n Characteristic length, typically agitator diameter [m]\n N : float\n Speed [revolutions/second]\n rho : float\n Density of fluid, [kg/m^3]\n\n Returns\n -------\n Po : float\n Power number []\n\n Notes\n -----\n Used in mixing calculations.\n\n .. math::\n Po = \\frac{\\text{Power}}{\\text{Rotational inertia}}\n\n Examples\n --------\n >>> Power_number(P=180, L=0.01, N=2.5, rho=800.)\n 144000000.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return P/(rho*N*N*N*L**5)\n\ndef Drag(F: float, A: float, V: float, rho: float) -> float:\n r\"\"\"Calculates drag coefficient `Cd` for a given drag force `F`,\n projected area `A`, characteristic velocity `V`, and density `rho`.\n\n .. math::\n C_D = \\frac{F_d}{A\\cdot\\frac{1}{2}\\rho V^2}\n\n Parameters\n ----------\n F : float\n Drag force, [N]\n A : float\n Projected area, [m^2]\n V : float\n Characteristic velocity, [m/s]\n rho : float\n Density, [kg/m^3]\n\n Returns\n -------\n Cd : float\n Drag coefficient, [-]\n\n Notes\n -----\n Used in flow around objects, or objects flowing within a fluid.\n\n .. math::\n C_D = \\frac{\\text{Drag forces}}{\\text{Projected area}\\cdot\n \\text{Velocity head}}\n\n Examples\n --------\n >>> Drag(1000, 0.0001, 5, 2000)\n 400.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return F/(0.5*A*rho*V*V)\n\ndef Stokes_number(V: float, Dp: float, D: float, rhop: float, mu: float) -> float:\n r\"\"\"Calculates Stokes Number for a given characteristic velocity `V`,\n particle diameter `Dp`, characteristic diameter `D`, particle density\n `rhop`, and fluid viscosity `mu`.\n\n .. math::\n \\text{Stk} = \\frac{\\rho_p V D_p^2}{18\\mu_f D}\n\n Parameters\n ----------\n V : float\n Characteristic velocity (often superficial), [m/s]\n Dp : float\n Particle diameter, [m]\n D : float\n Characteristic diameter (ex demister wire diameter or cyclone\n diameter), [m]\n rhop : float\n Particle density, [kg/m^3]\n mu : float\n Fluid viscosity, [Pa*s]\n\n Returns\n -------\n Stk : float\n Stokes number, [-]\n\n Notes\n -----\n Used in droplet impaction or collection studies.\n\n Examples\n --------\n >>> Stokes_number(V=0.9, Dp=1E-5, D=1E-3, rhop=1000, mu=1E-5)\n 0.5\n\n References\n ----------\n .. [1] Rhodes, Martin J. Introduction to Particle Technology. Wiley, 2013.\n .. [2] Al-Dughaither, Abdullah S., Ahmed A. Ibrahim, and Waheed A.\n Al-Masry. \"Investigating Droplet Separation Efficiency in Wire-Mesh Mist\n Eliminators in Bubble Column.\" Journal of Saudi Chemical Society 14, no.\n 4 (October 1, 2010): 331-39. https://doi.org/10.1016/j.jscs.2010.04.001.\n \"\"\"\n return rhop*V*(Dp*Dp)/(18.0*mu*D)\n\ndef Capillary(V: float, mu: float, sigma: float) -> float:\n r\"\"\"Calculates Capillary number `Ca` for a characteristic velocity `V`,\n viscosity `mu`, and surface tension `sigma`.\n\n .. math::\n Ca = \\frac{V \\mu}{\\sigma}\n\n Parameters\n ----------\n V : float\n Characteristic velocity, [m/s]\n mu : float\n Dynamic viscosity, [Pa*s]\n sigma : float\n Surface tension, [N/m]\n\n Returns\n -------\n Ca : float\n Capillary number, [-]\n\n Notes\n -----\n Used in porous media calculations and film flow calculations.\n Surface tension may gas-liquid, or liquid-liquid.\n\n .. math::\n Ca = \\frac{\\text{Viscous forces}}\n {\\text{Surface forces}}\n\n Examples\n --------\n >>> Capillary(1.2, 0.01, .1)\n 0.12\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Kundu, Pijush K., Ira M. Cohen, and David R. Dowling. Fluid\n Mechanics. Academic Press, 2012.\n \"\"\"\n return V*mu/sigma\n\ndef Archimedes(L: float, rhof: float, rhop: float, mu: float, g: float=g) -> float:\n r\"\"\"Calculates Archimedes number, `Ar`, for a fluid and particle with the\n given densities, characteristic length, viscosity, and gravity\n (usually diameter of particle).\n\n .. math::\n Ar = \\frac{L^3 \\rho_f(\\rho_p-\\rho_f)g}{\\mu^2}\n\n Parameters\n ----------\n L : float\n Characteristic length, typically particle diameter [m]\n rhof : float\n Density of fluid, [kg/m^3]\n rhop : float\n Density of particle, [kg/m^3]\n mu : float\n Viscosity of fluid, [Pa*s]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Ar : float\n Archimedes number []\n\n Notes\n -----\n Used in fluid-particle interaction calculations.\n\n .. math::\n Ar = \\frac{\\text{Gravitational force}}{\\text{Viscous force}}\n\n Examples\n --------\n >>> Archimedes(0.002, 2., 3000, 1E-3)\n 470.4053872\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return L*L*L*rhof*(rhop-rhof)*g/(mu*mu)\n\ndef Ohnesorge(L: float, rho: float, mu: float, sigma: float) -> float:\n r\"\"\"Calculates Ohnesorge number, `Oh`, for a fluid with the given\n characteristic length, density, viscosity, and surface tension.\n\n .. math::\n \\text{Oh} = \\frac{\\mu}{\\sqrt{\\rho \\sigma L }}\n\n Parameters\n ----------\n L : float\n Characteristic length [m]\n rho : float\n Density of fluid, [kg/m^3]\n mu : float\n Viscosity of fluid, [Pa*s]\n sigma : float\n Surface tension, [N/m]\n\n Returns\n -------\n Oh : float\n Ohnesorge number []\n\n Notes\n -----\n Often used in spray calculations. Sometimes given the symbol Z.\n\n .. math::\n Oh = \\frac{\\sqrt{\\text{We}}}{\\text{Re}}= \\frac{\\text{viscous forces}}\n {\\sqrt{\\text{Inertia}\\cdot\\text{Surface tension}} }\n\n Examples\n --------\n >>> Ohnesorge(1E-4, 1000., 1E-3, 1E-1)\n 0.01\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return mu/sqrt(L*rho*sigma)\n\ndef Suratman(L: float, rho: float, mu: float, sigma: float) -> float:\n r\"\"\"Calculates Suratman number, `Su`, for a fluid with the given\n characteristic length, density, viscosity, and surface tension.\n\n .. math::\n \\text{Su} = \\frac{\\rho\\sigma L}{\\mu^2}\n\n Parameters\n ----------\n L : float\n Characteristic length [m]\n rho : float\n Density of fluid, [kg/m^3]\n mu : float\n Viscosity of fluid, [Pa*s]\n sigma : float\n Surface tension, [N/m]\n\n Returns\n -------\n Su : float\n Suratman number []\n\n Notes\n -----\n Also known as Laplace number. Used in two-phase flow, especially the\n bubbly-slug regime. No confusion regarding the definition of this group\n has been observed.\n\n .. math::\n \\text{Su} = \\frac{\\text{Re}^2}{\\text{We}} =\\frac{\\text{Inertia}\\cdot\n \\text{Surface tension} }{\\text{(viscous forces)}^2}\n\n The oldest reference to this group found by the author is in 1963, from\n [2]_.\n\n Examples\n --------\n >>> Suratman(1E-4, 1000., 1E-3, 1E-1)\n 10000.0\n\n References\n ----------\n .. [1] Sen, Nilava. \"Suratman Number in Bubble-to-Slug Flow Pattern\n Transition under Microgravity.\" Acta Astronautica 65, no. 3-4 (August\n 2009): 423-28. doi:10.1016/j.actaastro.2009.02.013.\n .. [2] Catchpole, John P., and George. Fulford. \"DIMENSIONLESS GROUPS.\"\n Industrial & Engineering Chemistry 58, no. 3 (March 1, 1966): 46-60.\n doi:10.1021/ie50675a012.\n \"\"\"\n return rho*sigma*L/(mu*mu)\n\ndef Hagen(Re: float, fd: float) -> float:\n r\"\"\"Calculates Hagen number, `Hg`, for a fluid with the given\n Reynolds number and friction factor.\n\n .. math::\n \\text{Hg} = \\frac{f_d}{2} Re^2 = \\frac{1}{\\rho}\n \\frac{\\Delta P}{\\Delta z} \\frac{D^3}{\\nu^2}\n = \\frac{\\rho\\Delta P D^3}{\\mu^2 \\Delta z}\n\n Parameters\n ----------\n Re : float\n Reynolds number [-]\n fd : float, optional\n Darcy friction factor, [-]\n\n Returns\n -------\n Hg : float\n Hagen number, [-]\n\n Notes\n -----\n Introduced in [1]_; further use of it is mostly of the correlations\n introduced in [1]_.\n\n Notable for use in correlations, because it does not have any\n dependence on velocity.\n\n This expression is useful when designing backwards with a pressure drop\n spec already known.\n\n Examples\n --------\n Example from [3]_:\n\n >>> Hagen(Re=2610, fd=1.935235)\n 6591507.17175\n\n References\n ----------\n .. [1] Martin, Holger. \"The Generalized Lévêque Equation and Its Practical\n Use for the Prediction of Heat and Mass Transfer Rates from Pressure\n Drop.\" Chemical Engineering Science, Jean-Claude Charpentier\n Festschrift Issue, 57, no. 16 (August 1, 2002): 3217-23.\n https://doi.org/10.1016/S0009-2509(02)00194-X.\n .. [2] Shah, Ramesh K., and Dusan P. Sekulic. Fundamentals of Heat\n Exchanger Design. 1st edition. Hoboken, NJ: Wiley, 2002.\n .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n Berlin; New York:: Springer, 2010.\n \"\"\"\n return 0.5*fd*Re*Re\n\ndef Bejan_L(dP: float, L: float, mu: float, alpha: float) -> float:\n r\"\"\"Calculates Bejan number of a length or `Be_L` for a fluid with the\n given parameters flowing over a characteristic length `L` and experiencing\n a pressure drop `dP`.\n\n .. math::\n Be_L = \\frac{\\Delta P L^2}{\\mu \\alpha}\n\n Parameters\n ----------\n dP : float\n Pressure drop, [Pa]\n L : float\n Characteristic length, [m]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n alpha : float\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Be_L : float\n Bejan number with respect to length []\n\n Notes\n -----\n Termed a dimensionless number by someone in 1988.\n\n Examples\n --------\n >>> Bejan_L(1E4, 1, 1E-3, 1E-6)\n 10000000000000.0\n\n References\n ----------\n .. [1] Awad, M. M. \"The Science and the History of the Two Bejan Numbers.\"\n International Journal of Heat and Mass Transfer 94 (March 2016): 101-3.\n doi:10.1016/j.ijheatmasstransfer.2015.11.073.\n .. [2] Bejan, Adrian. Convection Heat Transfer. 4E. Hoboken, New Jersey:\n Wiley, 2013.\n \"\"\"\n return dP*L*L/(alpha*mu)\n\ndef Bejan_p(dP: float, K: float, mu: float, alpha: float) -> float:\n r\"\"\"Calculates Bejan number of a permeability or `Be_p` for a fluid with\n the given parameters and a permeability `K` experiencing a pressure drop\n `dP`.\n\n .. math::\n Be_p = \\frac{\\Delta P K}{\\mu \\alpha}\n\n Parameters\n ----------\n dP : float\n Pressure drop, [Pa]\n K : float\n Permeability, [m^2]\n mu : float\n Dynamic viscosity, [Pa*s]\n alpha : float\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Be_p : float\n Bejan number with respect to pore characteristics []\n\n Notes\n -----\n Termed a dimensionless number by someone in 1988.\n\n Examples\n --------\n >>> Bejan_p(1E4, 1, 1E-3, 1E-6)\n 10000000000000.0\n\n References\n ----------\n .. [1] Awad, M. M. \"The Science and the History of the Two Bejan Numbers.\"\n International Journal of Heat and Mass Transfer 94 (March 2016): 101-3.\n doi:10.1016/j.ijheatmasstransfer.2015.11.073.\n .. [2] Bejan, Adrian. Convection Heat Transfer. 4E. Hoboken, New Jersey:\n Wiley, 2013.\n \"\"\"\n return dP*K/(alpha*mu)\n\ndef Boiling(G: float, q: float, Hvap: float) -> float:\n r\"\"\"Calculates Boiling number or `Bg` using heat flux, two-phase mass flux,\n and heat of vaporization of the fluid flowing. Used in two-phase heat\n transfer calculations.\n\n .. math::\n \\text{Bg} = \\frac{q}{G_{tp} \\Delta H_{vap}}\n\n Parameters\n ----------\n G : float\n Two-phase mass flux in a channel (combined liquid and vapor) [kg/m^2/s]\n q : float\n Heat flux [W/m^2]\n Hvap : float\n Heat of vaporization of the fluid [J/kg]\n\n Returns\n -------\n Bg : float\n Boiling number [-]\n\n Notes\n -----\n Most often uses the symbol `Bo` instead of `Bg`, but this conflicts with\n Bond number.\n\n .. math::\n \\text{Bg} = \\frac{\\text{mass liquid evaporated / area heat transfer\n surface}}{\\text{mass flow rate fluid / flow cross sectional area}}\n\n First defined in [4]_, though not named.\n\n Examples\n --------\n >>> Boiling(300, 3000, 800000)\n 1.25e-05\n\n References\n ----------\n .. [1] Winterton, Richard H.S. BOILING NUMBER. Thermopedia. Hemisphere,\n 2011. 10.1615/AtoZ.b.boiling_number\n .. [2] Collier, John G., and John R. Thome. Convective Boiling and\n Condensation. 3rd edition. Clarendon Press, 1996.\n .. [3] Stephan, Karl. Heat Transfer in Condensation and Boiling. Translated\n by C. V. Green.. 1992 edition. Berlin; New York: Springer, 2013.\n .. [4] W. F. Davidson, P. H. Hardie, C. G. R. Humphreys, A. A. Markson,\n A. R. Mumford and T. Ravese \"Studies of heat transmission through boiler\n tubing at pressures from 500 to 3300 pounds\" Trans. ASME, Vol. 65, 9,\n February 1943, pp. 553-591.\n \"\"\"\n return q/(G*Hvap)\n\ndef Dean(Re: float, Di: float, D: float) -> float:\n r\"\"\"Calculates Dean number, `De`, for a fluid with the Reynolds number `Re`,\n inner diameter `Di`, and a secondary diameter `D`. `D` may be the\n diameter of curvature, the diameter of a spiral, or some other dimension.\n\n .. math::\n \\text{De} = \\sqrt{\\frac{D_i}{D}} \\text{Re} = \\sqrt{\\frac{D_i}{D}}\n \\frac{\\rho v D}{\\mu}\n\n Parameters\n ----------\n Re : float\n Reynolds number []\n Di : float\n Inner diameter []\n D : float\n Diameter of curvature or outer spiral or other dimension []\n\n Returns\n -------\n De : float\n Dean number [-]\n\n Notes\n -----\n Used in flow in curved geometry.\n\n .. math::\n \\text{De} = \\frac{\\sqrt{\\text{centripetal forces}\\cdot\n \\text{inertial forces}}}{\\text{viscous forces}}\n\n Examples\n --------\n >>> Dean(10000, 0.1, 0.4)\n 5000.0\n\n References\n ----------\n .. [1] Catchpole, John P., and George. Fulford. \"DIMENSIONLESS GROUPS.\"\n Industrial & Engineering Chemistry 58, no. 3 (March 1, 1966): 46-60.\n doi:10.1021/ie50675a012.\n \"\"\"\n return sqrt(Di/D)*Re\n\ndef relative_roughness(D: float, roughness: float=1.52e-06) -> float:\n r\"\"\"Calculates relative roughness `eD` using a diameter and the roughness\n of the material of the wall. Default roughness is that of steel.\n\n .. math::\n eD=\\frac{\\epsilon}{D}\n\n Parameters\n ----------\n D : float\n Diameter of pipe, [m]\n roughness : float, optional\n Roughness of pipe wall [m]\n\n Returns\n -------\n eD : float\n Relative Roughness, [-]\n\n Examples\n --------\n >>> relative_roughness(0.5, 1E-4)\n 0.0002\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return roughness/D\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 57102}, "tests/test_core.py::216": {"resolved_imports": ["fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["Archimedes", "Bejan_L", "Bejan_p", "Biot", "Boiling", "Bond", "Capillary", "Cavitation", "Confinement", "Dean", "Drag", "Eckert", "Euler", "Fourier_heat", "Fourier_mass", "Froude", "Froude_densimetric", "Graetz_heat", "Grashof", "Hagen", "Jakob", "Knudsen", "Lewis", "Mach", "Morton", "Nusselt", "Ohnesorge", "Peclet_heat", "Peclet_mass", "Power_number", "Prandtl", "Rayleigh", "Reynolds", "Schmidt", "Sherwood", "Stanton", "Stokes_number", "Strouhal", "Suratman", "Weber", "assert_close", "assert_close1d", "pytest", "relative_roughness"], "enclosing_function": "test_core_dimensionless", "extracted_code": "# Source: fluids/core.py\ndef Reynolds(V: float, D: float, rho: float | None=None, mu: float | None=None, nu: float | None=None) -> float:\n r\"\"\"Calculates Reynolds number or `Re` for a fluid with the given\n properties for the specified velocity and diameter.\n\n .. math::\n Re = \\frac{D \\cdot V}{\\nu} = \\frac{\\rho V D}{\\mu}\n\n Inputs either of any of the following sets:\n\n * V, D, density `rho` and dynamic viscosity `mu`\n * V, D, and kinematic viscosity `nu`\n\n Parameters\n ----------\n V : float\n Velocity [m/s]\n D : float\n Diameter [m]\n rho : float, optional\n Density, [kg/m^3]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n\n Returns\n -------\n Re : float\n Reynolds number []\n\n Notes\n -----\n .. math::\n Re = \\frac{\\text{Momentum}}{\\text{Viscosity}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Reynolds(2.5, 0.25, 1.1613, 1.9E-5)\n 38200.65789473684\n >>> Reynolds(2.5, 0.25, nu=1.636e-05)\n 38202.93398533008\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and mu is not None:\n nu = mu/rho\n elif nu is None:\n raise ValueError(\"Either density and viscosity, or kinematic viscosity is needed\")\n return V*D/nu\n\ndef Peclet_heat(V: float, L: float, rho: float | None=None, Cp: float | None=None, k: float | None=None, alpha: float | None=None) -> float:\n r\"\"\"Calculates heat transfer Peclet number or `Pe` for a specified velocity\n `V`, characteristic length `L`, and specified properties for the given\n fluid.\n\n .. math::\n Pe = \\frac{VL\\rho C_p}{k} = \\frac{LV}{\\alpha}\n\n Inputs either of any of the following sets:\n\n * V, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k`\n * V, L, and thermal diffusivity `alpha`\n\n Parameters\n ----------\n V : float\n Velocity [m/s]\n L : float\n Characteristic length [m]\n rho : float, optional\n Density, [kg/m^3]\n Cp : float, optional\n Heat capacity, [J/kg/K]\n k : float, optional\n Thermal conductivity, [W/m/K]\n alpha : float, optional\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Pe : float\n Peclet number (heat) []\n\n Notes\n -----\n .. math::\n Pe = \\frac{\\text{Bulk heat transfer}}{\\text{Conduction heat transfer}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Peclet_heat(1.5, 2, 1000., 4000., 0.6)\n 20000000.0\n >>> Peclet_heat(1.5, 2, alpha=1E-7)\n 30000000.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and Cp is not None and k is not None:\n alpha = k/(rho*Cp)\n elif alpha is None:\n raise ValueError(\"Either heat capacity and thermal conductivity and density, or thermal diffusivity is needed\")\n return V*L/alpha\n\ndef Peclet_mass(V: float, L: float, D: float) -> float:\n r\"\"\"Calculates mass transfer Peclet number or `Pe` for a specified velocity\n `V`, characteristic length `L`, and diffusion coefficient `D`.\n\n .. math::\n Pe = \\frac{L V}{D}\n\n Parameters\n ----------\n V : float\n Velocity [m/s]\n L : float\n Characteristic length [m]\n D : float\n Diffusivity of a species, [m^2/s]\n\n Returns\n -------\n Pe : float\n Peclet number (mass) []\n\n Notes\n -----\n .. math::\n Pe = \\frac{\\text{Advective transport rate}}{\\text{Diffusive transport rate}}\n\n Examples\n --------\n >>> Peclet_mass(1.5, 2, 1E-9)\n 3000000000.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return V*L/D\n\ndef Fourier_heat(t: float, L: float, rho: float | None=None, Cp: float | None=None, k: float | None=None, alpha: float | None=None) -> float:\n r\"\"\"Calculates heat transfer Fourier number or `Fo` for a specified time\n `t`, characteristic length `L`, and specified properties for the given\n fluid.\n\n .. math::\n Fo = \\frac{k t}{C_p \\rho L^2} = \\frac{\\alpha t}{L^2}\n\n Inputs either of any of the following sets:\n\n * t, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k`\n * t, L, and thermal diffusivity `alpha`\n\n Parameters\n ----------\n t : float\n time [s]\n L : float\n Characteristic length [m]\n rho : float, optional\n Density, [kg/m^3]\n Cp : float, optional\n Heat capacity, [J/kg/K]\n k : float, optional\n Thermal conductivity, [W/m/K]\n alpha : float, optional\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Fo : float\n Fourier number (heat) []\n\n Notes\n -----\n .. math::\n Fo = \\frac{\\text{Heat conduction rate}}\n {\\text{Rate of thermal energy storage in a solid}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Fourier_heat(t=1.5, L=2, rho=1000., Cp=4000., k=0.6)\n 5.625e-08\n >>> Fourier_heat(1.5, 2, alpha=1E-7)\n 3.75e-08\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and Cp is not None and k is not None:\n alpha = k/(rho*Cp)\n elif alpha is None:\n raise ValueError(\"Either heat capacity and thermal conductivity and density, or thermal diffusivity is needed\")\n return t*alpha/(L*L)\n\ndef Fourier_mass(t: float, L: float, D: float) -> float:\n r\"\"\"Calculates mass transfer Fourier number or `Fo` for a specified time\n `t`, characteristic length `L`, and diffusion coefficient `D`.\n\n .. math::\n Fo = \\frac{D t}{L^2}\n\n Parameters\n ----------\n t : float\n time [s]\n L : float\n Characteristic length [m]\n D : float\n Diffusivity of a species, [m^2/s]\n\n Returns\n -------\n Fo : float\n Fourier number (mass) []\n\n Notes\n -----\n .. math::\n Fo = \\frac{\\text{Diffusive transport rate}}{\\text{Storage rate}}\n\n Examples\n --------\n >>> Fourier_mass(t=1.5, L=2, D=1E-9)\n 3.7500000000000005e-10\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return t*D/(L*L)\n\ndef Graetz_heat(V: float, D: float, x: float, rho: float | None=None, Cp: float | None=None, k: float | None=None, alpha: float | None=None) -> float:\n r\"\"\"Calculates Graetz number or `Gz` for a specified velocity\n `V`, diameter `D`, axial distance `x`, and specified properties for the\n given fluid.\n\n .. math::\n Gz = \\frac{VD^2\\cdot C_p \\rho}{x\\cdot k} = \\frac{VD^2}{x \\alpha}\n\n Inputs either of any of the following sets:\n\n * V, D, x, density `rho`, heat capacity `Cp`, and thermal conductivity `k`\n * V, D, x, and thermal diffusivity `alpha`\n\n Parameters\n ----------\n V : float\n Velocity, [m/s]\n D : float\n Diameter [m]\n x : float\n Axial distance [m]\n rho : float, optional\n Density, [kg/m^3]\n Cp : float, optional\n Heat capacity, [J/kg/K]\n k : float, optional\n Thermal conductivity, [W/m/K]\n alpha : float, optional\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Gz : float\n Graetz number []\n\n Notes\n -----\n .. math::\n Gz = \\frac{\\text{Time for radial heat diffusion in a fluid by conduction}}\n {\\text{Time taken by fluid to reach distance x}}\n\n .. math::\n Gz = \\frac{D}{x}RePr\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Graetz_heat(1.5, 0.25, 5, 800., 2200., 0.6)\n 55000.0\n >>> Graetz_heat(1.5, 0.25, 5, alpha=1E-7)\n 187500.0\n\n References\n ----------\n .. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n Wiley, 2011.\n \"\"\"\n if rho is not None and Cp is not None and k is not None:\n alpha = k/(rho*Cp)\n elif alpha is None:\n raise ValueError(\"Either heat capacity and thermal conductivity and density, or thermal diffusivity is needed\")\n return V*D*D/(x*alpha)\n\ndef Schmidt(D: float, mu: float | None=None, nu: float | None=None, rho: float | None=None) -> float:\n r\"\"\"Calculates Schmidt number or `Sc` for a fluid with the given\n parameters.\n\n .. math::\n Sc = \\frac{\\mu}{D\\rho} = \\frac{\\nu}{D}\n\n Inputs can be any of the following sets:\n\n * Diffusivity, dynamic viscosity, and density\n * Diffusivity and kinematic viscosity\n\n Parameters\n ----------\n D : float\n Diffusivity of a species, [m^2/s]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n rho : float, optional\n Density, [kg/m^3]\n\n Returns\n -------\n Sc : float\n Schmidt number []\n\n Notes\n -----\n .. math::\n Sc =\\frac{\\text{kinematic viscosity}}{\\text{molecular diffusivity}}\n = \\frac{\\text{viscous diffusivity}}{\\text{species diffusivity}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Schmidt(D=2E-6, mu=4.61E-6, rho=800)\n 0.00288125\n >>> Schmidt(D=1E-9, nu=6E-7)\n 599.9999999999999\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and mu is not None:\n return mu/(rho*D)\n elif nu is not None:\n return nu/D\n else:\n raise ValueError(\"Insufficient information provided for Schmidt number calculation\")\n\ndef Lewis(D: float, alpha: float | None=None, Cp: float | None=None, k: float | None=None, rho: float | None=None) -> float:\n r\"\"\"Calculates Lewis number or `Le` for a fluid with the given parameters.\n\n .. math::\n Le = \\frac{k}{\\rho C_p D} = \\frac{\\alpha}{D}\n\n Inputs can be either of the following sets:\n\n * Diffusivity and Thermal diffusivity\n * Diffusivity, heat capacity, thermal conductivity, and density\n\n Parameters\n ----------\n D : float\n Diffusivity of a species, [m^2/s]\n alpha : float, optional\n Thermal diffusivity, [m^2/s]\n Cp : float, optional\n Heat capacity, [J/kg/K]\n k : float, optional\n Thermal conductivity, [W/m/K]\n rho : float, optional\n Density, [kg/m^3]\n\n Returns\n -------\n Le : float\n Lewis number []\n\n Notes\n -----\n .. math::\n Le=\\frac{\\text{Thermal diffusivity}}{\\text{Mass diffusivity}} =\n \\frac{Sc}{Pr}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Lewis(D=22.6E-6, alpha=19.1E-6)\n 0.8451327433628318\n >>> Lewis(D=22.6E-6, rho=800., k=.2, Cp=2200)\n 0.00502815768302494\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n Berlin; New York:: Springer, 2010.\n \"\"\"\n if D is None:\n raise ValueError(\"Diffusivity D is required for Le calculation\")\n if k is not None and Cp is not None and rho is not None:\n alpha = k/(rho*Cp)\n elif alpha is None:\n raise ValueError(\"Insufficient information provided for Le calculation\")\n return alpha/D\n\ndef Weber(V: float, L: float, rho: float, sigma: float) -> float:\n r\"\"\"Calculates Weber number, `We`, for a fluid with the given density,\n surface tension, velocity, and geometric parameter (usually diameter\n of bubble).\n\n .. math::\n We = \\frac{V^2 L\\rho}{\\sigma}\n\n Parameters\n ----------\n V : float\n Velocity of fluid, [m/s]\n L : float\n Characteristic length, typically bubble diameter [m]\n rho : float\n Density of fluid, [kg/m^3]\n sigma : float\n Surface tension, [N/m]\n\n Returns\n -------\n We : float\n Weber number []\n\n Notes\n -----\n Used in bubble calculations.\n\n .. math::\n We = \\frac{\\text{inertial force}}{\\text{surface tension force}}\n\n Examples\n --------\n >>> Weber(V=0.18, L=0.001, rho=900., sigma=0.01)\n 2.916\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n Berlin; New York:: Springer, 2010.\n \"\"\"\n return V*V*L*rho/sigma\n\ndef Mach(V: float, c: float) -> float:\n r\"\"\"Calculates Mach number or `Ma` for a fluid of velocity `V` with speed\n of sound `c`.\n\n .. math::\n Ma = \\frac{V}{c}\n\n Parameters\n ----------\n V : float\n Velocity of fluid, [m/s]\n c : float\n Speed of sound in fluid, [m/s]\n\n Returns\n -------\n Ma : float\n Mach number []\n\n Notes\n -----\n Used in compressible flow calculations.\n\n .. math::\n Ma = \\frac{\\text{fluid velocity}}{\\text{sonic velocity}}\n\n Examples\n --------\n >>> Mach(33., 330)\n 0.1\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return V/c\n\ndef Confinement(D: float, rhol: float, rhog: float, sigma: float, g: float=g) -> float:\n r\"\"\"Calculates Confinement number or `Co` for a fluid in a channel of\n diameter `D` with liquid and gas densities `rhol` and `rhog` and surface\n tension `sigma`, under the influence of gravitational force `g`.\n\n .. math::\n \\text{Co}=\\frac{\\left[\\frac{\\sigma}{g(\\rho_l-\\rho_g)}\\right]^{0.5}}{D}\n\n Parameters\n ----------\n D : float\n Diameter of channel, [m]\n rhol : float\n Density of liquid phase, [kg/m^3]\n rhog : float\n Density of gas phase, [kg/m^3]\n sigma : float\n Surface tension between liquid-gas phase, [N/m]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Co : float\n Confinement number [-]\n\n Notes\n -----\n Used in two-phase pressure drop and heat transfer correlations. First used\n in [1]_ according to [3]_.\n\n .. math::\n \\text{Co} = \\frac{\\frac{\\text{surface tension force}}\n {\\text{buoyancy force}}}{\\text{Channel area}}\n\n Examples\n --------\n >>> Confinement(0.001, 1077, 76.5, 4.27E-3)\n 0.6596978265315191\n\n References\n ----------\n .. [1] Cornwell, Keith, and Peter A. Kew. \"Boiling in Small Parallel\n Channels.\" In Energy Efficiency in Process Technology, edited by Dr P.\n A. Pilavachi, 624-638. Springer Netherlands, 1993.\n doi:10.1007/978-94-011-1454-7_56.\n .. [2] Kandlikar, Satish G. Heat Transfer and Fluid Flow in Minichannels\n and Microchannels. Elsevier, 2006.\n .. [3] Tran, T. N, M. -C Chyu, M. W Wambsganss, and D. M France. Two-Phase\n Pressure Drop of Refrigerants during Flow Boiling in Small Channels: An\n Experimental Investigation and Correlation Development.\" International\n Journal of Multiphase Flow 26, no. 11 (November 1, 2000): 1739-54.\n doi:10.1016/S0301-9322(99)00119-6.\n \"\"\"\n return sqrt(sigma/(g*(rhol-rhog)))/D\n\ndef Morton(rhol: float, rhog: float, mul: float, sigma: float, g: float=g) -> float:\n r\"\"\"Calculates Morton number or `Mo` for a liquid and vapor with the\n specified properties, under the influence of gravitational force `g`.\n\n .. math::\n Mo = \\frac{g \\mu_l^4(\\rho_l - \\rho_g)}{\\rho_l^2 \\sigma^3}\n\n Parameters\n ----------\n rhol : float\n Density of liquid phase, [kg/m^3]\n rhog : float\n Density of gas phase, [kg/m^3]\n mul : float\n Viscosity of liquid phase, [Pa*s]\n sigma : float\n Surface tension between liquid-gas phase, [N/m]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Mo : float\n Morton number, [-]\n\n Notes\n -----\n Used in modeling bubbles in liquid.\n\n Examples\n --------\n >>> Morton(1077.0, 76.5, 4.27E-3, 0.023)\n 2.311183104430743e-07\n\n References\n ----------\n .. [1] Kunes, Josef. Dimensionless Physical Quantities in Science and\n Engineering. Elsevier, 2012.\n .. [2] Yan, Xiaokang, Kaixin Zheng, Yan Jia, Zhenyong Miao, Lijun Wang,\n Yijun Cao, and Jiongtian Liu. “Drag Coefficient Prediction of a Single\n Bubble Rising in Liquids.” Industrial & Engineering Chemistry Research,\n April 2, 2018. https://doi.org/10.1021/acs.iecr.7b04743.\n \"\"\"\n mul2 = mul*mul\n return g*mul2*mul2*(rhol - rhog)/(rhol*rhol*sigma*sigma*sigma)\n\ndef Knudsen(path: float, L: float) -> float:\n r\"\"\"Calculates Knudsen number or `Kn` for a fluid with mean free path\n `path` and for a characteristic length `L`.\n\n .. math::\n Kn = \\frac{\\lambda}{L}\n\n Parameters\n ----------\n path : float\n Mean free path between molecular collisions, [m]\n L : float\n Characteristic length, [m]\n\n Returns\n -------\n Kn : float\n Knudsen number []\n\n Notes\n -----\n Used in mass transfer calculations.\n\n .. math::\n Kn = \\frac{\\text{Mean free path length}}{\\text{Characteristic length}}\n\n Examples\n --------\n >>> Knudsen(1e-10, .001)\n 1e-07\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return path/L\n\ndef Prandtl(Cp: float | None=None, k: float | None=None, mu: float | None=None, nu: float | None=None, rho: float | None=None, alpha: float | None=None) -> float:\n r\"\"\"Calculates Prandtl number or `Pr` for a fluid with the given\n parameters.\n\n .. math::\n Pr = \\frac{C_p \\mu}{k} = \\frac{\\nu}{\\alpha} = \\frac{C_p \\rho \\nu}{k}\n\n Inputs can be any of the following sets:\n\n * Heat capacity, dynamic viscosity, and thermal conductivity\n * Thermal diffusivity and kinematic viscosity\n * Heat capacity, kinematic viscosity, thermal conductivity, and density\n\n Parameters\n ----------\n Cp : float\n Heat capacity, [J/kg/K]\n k : float\n Thermal conductivity, [W/m/K]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n rho : float\n Density, [kg/m^3]\n alpha : float\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Pr : float\n Prandtl number []\n\n Notes\n -----\n .. math::\n Pr=\\frac{\\text{kinematic viscosity}}{\\text{thermal diffusivity}} = \\frac{\\text{momentum diffusivity}}{\\text{thermal diffusivity}}\n\n An error is raised if none of the required input sets are provided.\n\n Examples\n --------\n >>> Prandtl(Cp=1637., k=0.010, mu=4.61E-6)\n 0.754657\n >>> Prandtl(Cp=1637., k=0.010, nu=6.4E-7, rho=7.1)\n 0.7438528\n >>> Prandtl(nu=6.3E-7, alpha=9E-7)\n 0.7000000000000001\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n Berlin; New York:: Springer, 2010.\n \"\"\"\n if k is not None and Cp is not None and mu is not None:\n return Cp*mu/k\n elif nu is not None and rho is not None and Cp is not None and k is not None:\n return nu*rho*Cp/k\n elif nu is not None and alpha is not None:\n return nu/alpha\n else:\n raise ValueError(\"Insufficient information provided for Pr calculation\")\n\ndef Grashof(L: float, beta: float, T1: float, T2: float=0, rho: float | None=None, mu: float | None=None, nu: float | None=None, g: float=g) -> float:\n r\"\"\"Calculates Grashof number or `Gr` for a fluid with the given\n properties, temperature difference, and characteristic length.\n\n .. math::\n Gr = \\frac{g\\beta (T_s-T_\\infty)L^3}{\\nu^2}\n = \\frac{g\\beta (T_s-T_\\infty)L^3\\rho^2}{\\mu^2}\n\n Inputs either of any of the following sets:\n\n * L, beta, T1 and T2, and density `rho` and dynamic viscosity `mu`\n * L, beta, T1 and T2, and kinematic viscosity `nu`\n\n Parameters\n ----------\n L : float\n Characteristic length [m]\n beta : float\n Volumetric thermal expansion coefficient [1/K]\n T1 : float\n Temperature 1, usually a film temperature [K]\n T2 : float, optional\n Temperature 2, usually a bulk temperature (or 0 if only a difference\n is provided to the function) [K]\n rho : float, optional\n Density, [kg/m^3]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Gr : float\n Grashof number []\n\n Notes\n -----\n .. math::\n Gr = \\frac{\\text{Buoyancy forces}}{\\text{Viscous forces}}\n\n An error is raised if none of the required input sets are provided.\n Used in free convection problems only.\n\n Examples\n --------\n Example 4 of [1]_, p. 1-21 (matches):\n\n >>> Grashof(L=0.9144, beta=0.000933, T1=178.2, rho=1.1613, mu=1.9E-5)\n 4656936556.178915\n >>> Grashof(L=0.9144, beta=0.000933, T1=378.2, T2=200, nu=1.636e-05)\n 4657491516.530312\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if rho is not None and mu is not None:\n nu = mu/rho\n elif nu is None:\n raise ValueError(\"Either density and viscosity, or kinematic viscosity is needed\")\n return g*beta*abs(T2-T1)*L*L*L/(nu*nu)\n\ndef Bond(rhol: float, rhog: float, sigma: float, L: float) -> float:\n r\"\"\"Calculates Bond number, `Bo` also known as Eotvos number,\n for a fluid with the given liquid and gas densities, surface tension,\n and geometric parameter (usually length).\n\n .. math::\n Bo = \\frac{g(\\rho_l-\\rho_g)L^2}{\\sigma}\n\n Parameters\n ----------\n rhol : float\n Density of liquid, [kg/m^3]\n rhog : float\n Density of gas, [kg/m^3]\n sigma : float\n Surface tension, [N/m]\n L : float\n Characteristic length, [m]\n\n Returns\n -------\n Bo : float\n Bond number []\n\n Examples\n --------\n >>> Bond(1000., 1.2, .0589, 2)\n 665187.2339558573\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return (g*(rhol-rhog)*L*L/sigma)\n\ndef Rayleigh(Pr: float, Gr: float) -> float:\n r\"\"\"Calculates Rayleigh number or `Ra` using Prandtl number `Pr` and\n Grashof number `Gr` for a fluid with the given\n properties, temperature difference, and characteristic length used\n to calculate `Gr` and `Pr`.\n\n .. math::\n Ra = PrGr\n\n Parameters\n ----------\n Pr : float\n Prandtl number []\n Gr : float\n Grashof number []\n\n Returns\n -------\n Ra : float\n Rayleigh number []\n\n Notes\n -----\n Used in free convection problems only.\n\n Examples\n --------\n >>> Rayleigh(1.2, 4.6E9)\n 5520000000.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return Pr*Gr\n\ndef Froude(V: float, L: float, g: float=g, squared: bool=False) -> float:\n r\"\"\"Calculates Froude number `Fr` for velocity `V` and geometric length\n `L`. If desired, gravity can be specified as well. Normally the function\n returns the result of the equation below; Froude number is also often\n said to be defined as the square of the equation below.\n\n .. math::\n Fr = \\frac{V}{\\sqrt{gL}}\n\n Parameters\n ----------\n V : float\n Velocity of the particle or fluid, [m/s]\n L : float\n Characteristic length, no typical definition [m]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n squared : bool, optional\n Whether to return the squared form of Froude number\n\n Returns\n -------\n Fr : float\n Froude number, [-]\n\n Notes\n -----\n Many alternate definitions including density ratios have been used.\n\n .. math::\n Fr = \\frac{\\text{Inertial Force}}{\\text{Gravity Force}}\n\n Examples\n --------\n >>> Froude(1.83, L=2., g=1.63)\n 1.0135432593877318\n >>> Froude(1.83, L=2., squared=True)\n 0.17074638128208924\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n Fr = V/sqrt(L*g)\n if squared:\n Fr *= Fr\n return Fr\n\ndef Froude_densimetric(V: float, L: float, rho1: float, rho2: float, heavy: bool=True, g: float=g) -> float:\n r\"\"\"Calculates the densimetric Froude number :math:`Fr_{den}` for velocity\n `V` geometric length `L`, heavier fluid density `rho1`, and lighter fluid\n density `rho2`. If desired, gravity can be specified as well. Depending on\n the application, this dimensionless number may be defined with the heavy\n phase or the light phase density in the numerator of the square root.\n For some applications, both need to be calculated. The default is to\n calculate with the heavy liquid density on top; set `heavy` to False\n to reverse this.\n\n .. math::\n Fr = \\frac{V}{\\sqrt{gL}} \\sqrt{\\frac{\\rho_\\text{(1 or 2)}}\n {\\rho_1 - \\rho_2}}\n\n Parameters\n ----------\n V : float\n Velocity of the specified phase, [m/s]\n L : float\n Characteristic length, no typical definition [m]\n rho1 : float\n Density of the heavier phase, [kg/m^3]\n rho2 : float\n Density of the lighter phase, [kg/m^3]\n heavy : bool, optional\n Whether or not the density used in the numerator is the heavy phase or\n the light phase, [-]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Fr_den : float\n Densimetric Froude number, [-]\n\n Notes\n -----\n Many alternate definitions including density ratios have been used.\n\n .. math::\n Fr = \\frac{\\text{Inertial Force}}{\\text{Gravity Force}}\n\n Where the gravity force is reduced by the relative densities of one fluid\n in another.\n\n Note that an Exception will be raised if rho1 < rho2, as the square root\n becomes negative.\n\n Examples\n --------\n >>> Froude_densimetric(1.83, L=2., rho1=800, rho2=1.2, g=9.81)\n 0.4134543386272418\n >>> Froude_densimetric(1.83, L=2., rho1=800, rho2=1.2, g=9.81, heavy=False)\n 0.016013017679205096\n\n References\n ----------\n .. [1] Hall, A, G Stobie, and R Steven. \"Further Evaluation of the\n Performance of Horizontally Installed Orifice Plate and Cone\n Differential Pressure Meters with Wet Gas Flows.\" In International\n SouthEast Asia Hydrocarbon Flow Measurement Workshop, KualaLumpur,\n Malaysia, 2008.\n \"\"\"\n if heavy:\n rho3 = rho1\n else:\n rho3 = rho2\n return V/(sqrt(g*L))*sqrt(rho3/(rho1 - rho2))\n\ndef Strouhal(f: float, L: float, V: float) -> float:\n r\"\"\"Calculates Strouhal number `St` for a characteristic frequency `f`,\n characteristic length `L`, and velocity `V`.\n\n .. math::\n St = \\frac{fL}{V}\n\n Parameters\n ----------\n f : float\n Characteristic frequency, usually that of vortex shedding, [Hz]\n L : float\n Characteristic length, [m]\n V : float\n Velocity of the fluid, [m/s]\n\n Returns\n -------\n St : float\n Strouhal number, [-]\n\n Notes\n -----\n Sometimes abbreviated to S or Sr.\n\n .. math::\n St = \\frac{\\text{Characteristic flow time}}\n {\\text{Period of oscillation}}\n\n Examples\n --------\n >>> Strouhal(8, 2., 4.)\n 4.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return f*L/V\n\ndef Nusselt(h: float, L: float, k: float) -> float:\n r\"\"\"Calculates Nusselt number `Nu` for a heat transfer coefficient `h`,\n characteristic length `L`, and thermal conductivity `k`.\n\n .. math::\n Nu = \\frac{hL}{k}\n\n Parameters\n ----------\n h : float\n Heat transfer coefficient, [W/m^2/K]\n L : float\n Characteristic length, no typical definition [m]\n k : float\n Thermal conductivity of fluid [W/m/K]\n\n Returns\n -------\n Nu : float\n Nusselt number, [-]\n\n Notes\n -----\n Do not confuse k, the thermal conductivity of the fluid, with that\n of a solid object!\n\n .. math::\n Nu = \\frac{\\text{Convective heat transfer}}\n {\\text{Conductive heat transfer}}\n\n Examples\n --------\n >>> Nusselt(1000., 1.2, 300.)\n 4.0\n >>> Nusselt(10000., .01, 4000.)\n 0.025\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n Wiley, 2011.\n \"\"\"\n return h*L/k\n\ndef Sherwood(K: float, L: float, D: float) -> float:\n r\"\"\"Calculates Sherwood number `Sh` for a mass transfer coefficient `K`,\n characteristic length `L`, and diffusivity `D`.\n\n .. math::\n Sh = \\frac{KL}{D}\n\n Parameters\n ----------\n K : float\n Mass transfer coefficient, [m/s]\n L : float\n Characteristic length, no typical definition [m]\n D : float\n Diffusivity of a species [m^2/s]\n\n Returns\n -------\n Sh : float\n Sherwood number, [-]\n\n Notes\n -----\n .. math::\n Sh = \\frac{\\text{Mass transfer by convection}}\n {\\text{Mass transfer by diffusion}} = \\frac{K}{D/L}\n\n Examples\n --------\n >>> Sherwood(1000., 1.2, 300.)\n 4.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return K*L/D\n\ndef Biot(h: float, L: float, k: float) -> float:\n r\"\"\"Calculates Biot number `Bi` for heat transfer coefficient `h`,\n geometric length `L`, and thermal conductivity `k`.\n\n .. math::\n Bi=\\frac{hL}{k}\n\n Parameters\n ----------\n h : float\n Heat transfer coefficient, [W/m^2/K]\n L : float\n Characteristic length, no typical definition [m]\n k : float\n Thermal conductivity, within the object [W/m/K]\n\n Returns\n -------\n Bi : float\n Biot number, [-]\n\n Notes\n -----\n Do not confuse k, the thermal conductivity within the object, with that\n of the medium h is calculated with!\n\n .. math::\n Bi = \\frac{\\text{Surface thermal resistance}}\n {\\text{Internal thermal resistance}}\n\n Examples\n --------\n >>> Biot(1000., 1.2, 300.)\n 4.0\n >>> Biot(10000., .01, 4000.)\n 0.025\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return h*L/k\n\ndef Stanton(h: float, V: float, rho: float, Cp: float) -> float:\n r\"\"\"Calculates Stanton number or `St` for a specified heat transfer\n coefficient `h`, velocity `V`, density `rho`, and heat capacity `Cp` [1]_\n [2]_.\n\n .. math::\n St = \\frac{h}{V\\rho Cp}\n\n Parameters\n ----------\n h : float\n Heat transfer coefficient, [W/m^2/K]\n V : float\n Velocity, [m/s]\n rho : float\n Density, [kg/m^3]\n Cp : float\n Heat capacity, [J/kg/K]\n\n Returns\n -------\n St : float\n Stanton number []\n\n Notes\n -----\n .. math::\n St = \\frac{\\text{Heat transfer coefficient}}{\\text{Thermal capacity}}\n\n Examples\n --------\n >>> Stanton(5000, 5, 800, 2000.)\n 0.000625\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n Wiley, 2011.\n \"\"\"\n return h/(V*rho*Cp)\n\ndef Euler(dP: float, rho: float, V: float) -> float:\n r\"\"\"Calculates Euler number or `Eu` for a fluid of velocity `V` and\n density `rho` experiencing a pressure drop `dP`.\n\n .. math::\n Eu = \\frac{\\Delta P}{\\rho V^2}\n\n Parameters\n ----------\n dP : float\n Pressure drop experience by the fluid, [Pa]\n rho : float\n Density of the fluid, [kg/m^3]\n V : float\n Velocity of fluid, [m/s]\n\n Returns\n -------\n Eu : float\n Euler number []\n\n Notes\n -----\n Used in pressure drop calculations.\n Rarely, this number is divided by two.\n Named after Leonhard Euler who applied calculus to fluid dynamics.\n\n .. math::\n Eu = \\frac{\\text{Pressure drop}}{2\\cdot \\text{velocity head}}\n\n Examples\n --------\n >>> Euler(1E5, 1000., 4)\n 6.25\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return dP/(rho*V*V)\n\ndef Cavitation(P: float, Psat: float, rho: float, V: float) -> float:\n r\"\"\"Calculates Cavitation number or `Ca` for a fluid of velocity `V` with\n a pressure `P`, vapor pressure `Psat`, and density `rho`.\n\n .. math::\n Ca = \\sigma_c = \\sigma = \\frac{P-P_{sat}}{\\frac{1}{2}\\rho V^2}\n\n Parameters\n ----------\n P : float\n Internal pressure of the fluid, [Pa]\n Psat : float\n Vapor pressure of the fluid, [Pa]\n rho : float\n Density of the fluid, [kg/m^3]\n V : float\n Velocity of fluid, [m/s]\n\n Returns\n -------\n Ca : float\n Cavitation number []\n\n Notes\n -----\n Used in determining if a flow through a restriction will cavitate.\n Sometimes, the multiplication by 2 will be omitted;\n\n .. math::\n Ca = \\frac{\\text{Pressure - Vapor pressure}}\n {\\text{Inertial pressure}}\n\n Examples\n --------\n >>> Cavitation(2E5, 1E4, 1000, 10)\n 3.8\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return (P-Psat)/(0.5*rho*V*V)\n\ndef Eckert(V: float, Cp: float, dT: float) -> float:\n r\"\"\"Calculates Eckert number or `Ec` for a fluid of velocity `V` with\n a heat capacity `Cp`, between two temperature given as `dT`.\n\n .. math::\n Ec = \\frac{V^2}{C_p \\Delta T}\n\n Parameters\n ----------\n V : float\n Velocity of fluid, [m/s]\n Cp : float\n Heat capacity of the fluid, [J/kg/K]\n dT : float\n Temperature difference, [K]\n\n Returns\n -------\n Ec : float\n Eckert number []\n\n Notes\n -----\n Used in certain heat transfer calculations. Fairly rare.\n\n .. math::\n Ec = \\frac{\\text{Kinetic energy} }{ \\text{Enthalpy difference}}\n\n Examples\n --------\n >>> Eckert(10, 2000., 25.)\n 0.002\n\n References\n ----------\n .. [1] Goldstein, Richard J. ECKERT NUMBER. Thermopedia. Hemisphere, 2011.\n 10.1615/AtoZ.e.eckert_number\n \"\"\"\n return V*V/(Cp*dT)\n\ndef Jakob(Cp: float, Hvap: float, Te: float) -> float:\n r\"\"\"Calculates Jakob number or `Ja` for a boiling fluid with sensible heat\n capacity `Cp`, enthalpy of vaporization `Hvap`, and boiling at `Te` degrees\n above its saturation boiling point.\n\n .. math::\n Ja = \\frac{C_{P}\\Delta T_e}{\\Delta H_{vap}}\n\n Parameters\n ----------\n Cp : float\n Heat capacity of the fluid, [J/kg/K]\n Hvap : float\n Enthalpy of vaporization of the fluid at its saturation temperature [J/kg]\n Te : float\n Temperature difference above the fluid's saturation boiling temperature, [K]\n\n Returns\n -------\n Ja : float\n Jakob number []\n\n Notes\n -----\n Used in boiling heat transfer analysis. Fairly rare.\n\n .. math::\n Ja = \\frac{\\Delta \\text{Sensible heat}}{\\Delta \\text{Latent heat}}\n\n Examples\n --------\n >>> Jakob(4000., 2E6, 10.)\n 0.02\n\n References\n ----------\n .. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and\n David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:\n Wiley, 2011.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return Cp*Te/Hvap\n\ndef Power_number(P: float, L: float, N: float, rho: float) -> float:\n r\"\"\"Calculates power number, `Po`, for an agitator applying a specified\n power `P` with a characteristic length `L`, rotational speed `N`, to\n a fluid with a specified density `rho`.\n\n .. math::\n Po = \\frac{P}{\\rho N^3 D^5}\n\n Parameters\n ----------\n P : float\n Power applied, [W]\n L : float\n Characteristic length, typically agitator diameter [m]\n N : float\n Speed [revolutions/second]\n rho : float\n Density of fluid, [kg/m^3]\n\n Returns\n -------\n Po : float\n Power number []\n\n Notes\n -----\n Used in mixing calculations.\n\n .. math::\n Po = \\frac{\\text{Power}}{\\text{Rotational inertia}}\n\n Examples\n --------\n >>> Power_number(P=180, L=0.01, N=2.5, rho=800.)\n 144000000.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return P/(rho*N*N*N*L**5)\n\ndef Drag(F: float, A: float, V: float, rho: float) -> float:\n r\"\"\"Calculates drag coefficient `Cd` for a given drag force `F`,\n projected area `A`, characteristic velocity `V`, and density `rho`.\n\n .. math::\n C_D = \\frac{F_d}{A\\cdot\\frac{1}{2}\\rho V^2}\n\n Parameters\n ----------\n F : float\n Drag force, [N]\n A : float\n Projected area, [m^2]\n V : float\n Characteristic velocity, [m/s]\n rho : float\n Density, [kg/m^3]\n\n Returns\n -------\n Cd : float\n Drag coefficient, [-]\n\n Notes\n -----\n Used in flow around objects, or objects flowing within a fluid.\n\n .. math::\n C_D = \\frac{\\text{Drag forces}}{\\text{Projected area}\\cdot\n \\text{Velocity head}}\n\n Examples\n --------\n >>> Drag(1000, 0.0001, 5, 2000)\n 400.0\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return F/(0.5*A*rho*V*V)\n\ndef Stokes_number(V: float, Dp: float, D: float, rhop: float, mu: float) -> float:\n r\"\"\"Calculates Stokes Number for a given characteristic velocity `V`,\n particle diameter `Dp`, characteristic diameter `D`, particle density\n `rhop`, and fluid viscosity `mu`.\n\n .. math::\n \\text{Stk} = \\frac{\\rho_p V D_p^2}{18\\mu_f D}\n\n Parameters\n ----------\n V : float\n Characteristic velocity (often superficial), [m/s]\n Dp : float\n Particle diameter, [m]\n D : float\n Characteristic diameter (ex demister wire diameter or cyclone\n diameter), [m]\n rhop : float\n Particle density, [kg/m^3]\n mu : float\n Fluid viscosity, [Pa*s]\n\n Returns\n -------\n Stk : float\n Stokes number, [-]\n\n Notes\n -----\n Used in droplet impaction or collection studies.\n\n Examples\n --------\n >>> Stokes_number(V=0.9, Dp=1E-5, D=1E-3, rhop=1000, mu=1E-5)\n 0.5\n\n References\n ----------\n .. [1] Rhodes, Martin J. Introduction to Particle Technology. Wiley, 2013.\n .. [2] Al-Dughaither, Abdullah S., Ahmed A. Ibrahim, and Waheed A.\n Al-Masry. \"Investigating Droplet Separation Efficiency in Wire-Mesh Mist\n Eliminators in Bubble Column.\" Journal of Saudi Chemical Society 14, no.\n 4 (October 1, 2010): 331-39. https://doi.org/10.1016/j.jscs.2010.04.001.\n \"\"\"\n return rhop*V*(Dp*Dp)/(18.0*mu*D)\n\ndef Capillary(V: float, mu: float, sigma: float) -> float:\n r\"\"\"Calculates Capillary number `Ca` for a characteristic velocity `V`,\n viscosity `mu`, and surface tension `sigma`.\n\n .. math::\n Ca = \\frac{V \\mu}{\\sigma}\n\n Parameters\n ----------\n V : float\n Characteristic velocity, [m/s]\n mu : float\n Dynamic viscosity, [Pa*s]\n sigma : float\n Surface tension, [N/m]\n\n Returns\n -------\n Ca : float\n Capillary number, [-]\n\n Notes\n -----\n Used in porous media calculations and film flow calculations.\n Surface tension may gas-liquid, or liquid-liquid.\n\n .. math::\n Ca = \\frac{\\text{Viscous forces}}\n {\\text{Surface forces}}\n\n Examples\n --------\n >>> Capillary(1.2, 0.01, .1)\n 0.12\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Kundu, Pijush K., Ira M. Cohen, and David R. Dowling. Fluid\n Mechanics. Academic Press, 2012.\n \"\"\"\n return V*mu/sigma\n\ndef Archimedes(L: float, rhof: float, rhop: float, mu: float, g: float=g) -> float:\n r\"\"\"Calculates Archimedes number, `Ar`, for a fluid and particle with the\n given densities, characteristic length, viscosity, and gravity\n (usually diameter of particle).\n\n .. math::\n Ar = \\frac{L^3 \\rho_f(\\rho_p-\\rho_f)g}{\\mu^2}\n\n Parameters\n ----------\n L : float\n Characteristic length, typically particle diameter [m]\n rhof : float\n Density of fluid, [kg/m^3]\n rhop : float\n Density of particle, [kg/m^3]\n mu : float\n Viscosity of fluid, [Pa*s]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n Ar : float\n Archimedes number []\n\n Notes\n -----\n Used in fluid-particle interaction calculations.\n\n .. math::\n Ar = \\frac{\\text{Gravitational force}}{\\text{Viscous force}}\n\n Examples\n --------\n >>> Archimedes(0.002, 2., 3000, 1E-3)\n 470.4053872\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return L*L*L*rhof*(rhop-rhof)*g/(mu*mu)\n\ndef Ohnesorge(L: float, rho: float, mu: float, sigma: float) -> float:\n r\"\"\"Calculates Ohnesorge number, `Oh`, for a fluid with the given\n characteristic length, density, viscosity, and surface tension.\n\n .. math::\n \\text{Oh} = \\frac{\\mu}{\\sqrt{\\rho \\sigma L }}\n\n Parameters\n ----------\n L : float\n Characteristic length [m]\n rho : float\n Density of fluid, [kg/m^3]\n mu : float\n Viscosity of fluid, [Pa*s]\n sigma : float\n Surface tension, [N/m]\n\n Returns\n -------\n Oh : float\n Ohnesorge number []\n\n Notes\n -----\n Often used in spray calculations. Sometimes given the symbol Z.\n\n .. math::\n Oh = \\frac{\\sqrt{\\text{We}}}{\\text{Re}}= \\frac{\\text{viscous forces}}\n {\\sqrt{\\text{Inertia}\\cdot\\text{Surface tension}} }\n\n Examples\n --------\n >>> Ohnesorge(1E-4, 1000., 1E-3, 1E-1)\n 0.01\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n \"\"\"\n return mu/sqrt(L*rho*sigma)\n\ndef Suratman(L: float, rho: float, mu: float, sigma: float) -> float:\n r\"\"\"Calculates Suratman number, `Su`, for a fluid with the given\n characteristic length, density, viscosity, and surface tension.\n\n .. math::\n \\text{Su} = \\frac{\\rho\\sigma L}{\\mu^2}\n\n Parameters\n ----------\n L : float\n Characteristic length [m]\n rho : float\n Density of fluid, [kg/m^3]\n mu : float\n Viscosity of fluid, [Pa*s]\n sigma : float\n Surface tension, [N/m]\n\n Returns\n -------\n Su : float\n Suratman number []\n\n Notes\n -----\n Also known as Laplace number. Used in two-phase flow, especially the\n bubbly-slug regime. No confusion regarding the definition of this group\n has been observed.\n\n .. math::\n \\text{Su} = \\frac{\\text{Re}^2}{\\text{We}} =\\frac{\\text{Inertia}\\cdot\n \\text{Surface tension} }{\\text{(viscous forces)}^2}\n\n The oldest reference to this group found by the author is in 1963, from\n [2]_.\n\n Examples\n --------\n >>> Suratman(1E-4, 1000., 1E-3, 1E-1)\n 10000.0\n\n References\n ----------\n .. [1] Sen, Nilava. \"Suratman Number in Bubble-to-Slug Flow Pattern\n Transition under Microgravity.\" Acta Astronautica 65, no. 3-4 (August\n 2009): 423-28. doi:10.1016/j.actaastro.2009.02.013.\n .. [2] Catchpole, John P., and George. Fulford. \"DIMENSIONLESS GROUPS.\"\n Industrial & Engineering Chemistry 58, no. 3 (March 1, 1966): 46-60.\n doi:10.1021/ie50675a012.\n \"\"\"\n return rho*sigma*L/(mu*mu)\n\ndef Hagen(Re: float, fd: float) -> float:\n r\"\"\"Calculates Hagen number, `Hg`, for a fluid with the given\n Reynolds number and friction factor.\n\n .. math::\n \\text{Hg} = \\frac{f_d}{2} Re^2 = \\frac{1}{\\rho}\n \\frac{\\Delta P}{\\Delta z} \\frac{D^3}{\\nu^2}\n = \\frac{\\rho\\Delta P D^3}{\\mu^2 \\Delta z}\n\n Parameters\n ----------\n Re : float\n Reynolds number [-]\n fd : float, optional\n Darcy friction factor, [-]\n\n Returns\n -------\n Hg : float\n Hagen number, [-]\n\n Notes\n -----\n Introduced in [1]_; further use of it is mostly of the correlations\n introduced in [1]_.\n\n Notable for use in correlations, because it does not have any\n dependence on velocity.\n\n This expression is useful when designing backwards with a pressure drop\n spec already known.\n\n Examples\n --------\n Example from [3]_:\n\n >>> Hagen(Re=2610, fd=1.935235)\n 6591507.17175\n\n References\n ----------\n .. [1] Martin, Holger. \"The Generalized Lévêque Equation and Its Practical\n Use for the Prediction of Heat and Mass Transfer Rates from Pressure\n Drop.\" Chemical Engineering Science, Jean-Claude Charpentier\n Festschrift Issue, 57, no. 16 (August 1, 2002): 3217-23.\n https://doi.org/10.1016/S0009-2509(02)00194-X.\n .. [2] Shah, Ramesh K., and Dusan P. Sekulic. Fundamentals of Heat\n Exchanger Design. 1st edition. Hoboken, NJ: Wiley, 2002.\n .. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.\n Berlin; New York:: Springer, 2010.\n \"\"\"\n return 0.5*fd*Re*Re\n\ndef Bejan_L(dP: float, L: float, mu: float, alpha: float) -> float:\n r\"\"\"Calculates Bejan number of a length or `Be_L` for a fluid with the\n given parameters flowing over a characteristic length `L` and experiencing\n a pressure drop `dP`.\n\n .. math::\n Be_L = \\frac{\\Delta P L^2}{\\mu \\alpha}\n\n Parameters\n ----------\n dP : float\n Pressure drop, [Pa]\n L : float\n Characteristic length, [m]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n alpha : float\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Be_L : float\n Bejan number with respect to length []\n\n Notes\n -----\n Termed a dimensionless number by someone in 1988.\n\n Examples\n --------\n >>> Bejan_L(1E4, 1, 1E-3, 1E-6)\n 10000000000000.0\n\n References\n ----------\n .. [1] Awad, M. M. \"The Science and the History of the Two Bejan Numbers.\"\n International Journal of Heat and Mass Transfer 94 (March 2016): 101-3.\n doi:10.1016/j.ijheatmasstransfer.2015.11.073.\n .. [2] Bejan, Adrian. Convection Heat Transfer. 4E. Hoboken, New Jersey:\n Wiley, 2013.\n \"\"\"\n return dP*L*L/(alpha*mu)\n\ndef Bejan_p(dP: float, K: float, mu: float, alpha: float) -> float:\n r\"\"\"Calculates Bejan number of a permeability or `Be_p` for a fluid with\n the given parameters and a permeability `K` experiencing a pressure drop\n `dP`.\n\n .. math::\n Be_p = \\frac{\\Delta P K}{\\mu \\alpha}\n\n Parameters\n ----------\n dP : float\n Pressure drop, [Pa]\n K : float\n Permeability, [m^2]\n mu : float\n Dynamic viscosity, [Pa*s]\n alpha : float\n Thermal diffusivity, [m^2/s]\n\n Returns\n -------\n Be_p : float\n Bejan number with respect to pore characteristics []\n\n Notes\n -----\n Termed a dimensionless number by someone in 1988.\n\n Examples\n --------\n >>> Bejan_p(1E4, 1, 1E-3, 1E-6)\n 10000000000000.0\n\n References\n ----------\n .. [1] Awad, M. M. \"The Science and the History of the Two Bejan Numbers.\"\n International Journal of Heat and Mass Transfer 94 (March 2016): 101-3.\n doi:10.1016/j.ijheatmasstransfer.2015.11.073.\n .. [2] Bejan, Adrian. Convection Heat Transfer. 4E. Hoboken, New Jersey:\n Wiley, 2013.\n \"\"\"\n return dP*K/(alpha*mu)\n\ndef Boiling(G: float, q: float, Hvap: float) -> float:\n r\"\"\"Calculates Boiling number or `Bg` using heat flux, two-phase mass flux,\n and heat of vaporization of the fluid flowing. Used in two-phase heat\n transfer calculations.\n\n .. math::\n \\text{Bg} = \\frac{q}{G_{tp} \\Delta H_{vap}}\n\n Parameters\n ----------\n G : float\n Two-phase mass flux in a channel (combined liquid and vapor) [kg/m^2/s]\n q : float\n Heat flux [W/m^2]\n Hvap : float\n Heat of vaporization of the fluid [J/kg]\n\n Returns\n -------\n Bg : float\n Boiling number [-]\n\n Notes\n -----\n Most often uses the symbol `Bo` instead of `Bg`, but this conflicts with\n Bond number.\n\n .. math::\n \\text{Bg} = \\frac{\\text{mass liquid evaporated / area heat transfer\n surface}}{\\text{mass flow rate fluid / flow cross sectional area}}\n\n First defined in [4]_, though not named.\n\n Examples\n --------\n >>> Boiling(300, 3000, 800000)\n 1.25e-05\n\n References\n ----------\n .. [1] Winterton, Richard H.S. BOILING NUMBER. Thermopedia. Hemisphere,\n 2011. 10.1615/AtoZ.b.boiling_number\n .. [2] Collier, John G., and John R. Thome. Convective Boiling and\n Condensation. 3rd edition. Clarendon Press, 1996.\n .. [3] Stephan, Karl. Heat Transfer in Condensation and Boiling. Translated\n by C. V. Green.. 1992 edition. Berlin; New York: Springer, 2013.\n .. [4] W. F. Davidson, P. H. Hardie, C. G. R. Humphreys, A. A. Markson,\n A. R. Mumford and T. Ravese \"Studies of heat transmission through boiler\n tubing at pressures from 500 to 3300 pounds\" Trans. ASME, Vol. 65, 9,\n February 1943, pp. 553-591.\n \"\"\"\n return q/(G*Hvap)\n\ndef Dean(Re: float, Di: float, D: float) -> float:\n r\"\"\"Calculates Dean number, `De`, for a fluid with the Reynolds number `Re`,\n inner diameter `Di`, and a secondary diameter `D`. `D` may be the\n diameter of curvature, the diameter of a spiral, or some other dimension.\n\n .. math::\n \\text{De} = \\sqrt{\\frac{D_i}{D}} \\text{Re} = \\sqrt{\\frac{D_i}{D}}\n \\frac{\\rho v D}{\\mu}\n\n Parameters\n ----------\n Re : float\n Reynolds number []\n Di : float\n Inner diameter []\n D : float\n Diameter of curvature or outer spiral or other dimension []\n\n Returns\n -------\n De : float\n Dean number [-]\n\n Notes\n -----\n Used in flow in curved geometry.\n\n .. math::\n \\text{De} = \\frac{\\sqrt{\\text{centripetal forces}\\cdot\n \\text{inertial forces}}}{\\text{viscous forces}}\n\n Examples\n --------\n >>> Dean(10000, 0.1, 0.4)\n 5000.0\n\n References\n ----------\n .. [1] Catchpole, John P., and George. Fulford. \"DIMENSIONLESS GROUPS.\"\n Industrial & Engineering Chemistry 58, no. 3 (March 1, 1966): 46-60.\n doi:10.1021/ie50675a012.\n \"\"\"\n return sqrt(Di/D)*Re\n\ndef relative_roughness(D: float, roughness: float=1.52e-06) -> float:\n r\"\"\"Calculates relative roughness `eD` using a diameter and the roughness\n of the material of the wall. Default roughness is that of steel.\n\n .. math::\n eD=\\frac{\\epsilon}{D}\n\n Parameters\n ----------\n D : float\n Diameter of pipe, [m]\n roughness : float, optional\n Roughness of pipe wall [m]\n\n Returns\n -------\n eD : float\n Relative Roughness, [-]\n\n Examples\n --------\n >>> relative_roughness(0.5, 1E-4)\n 0.0002\n\n References\n ----------\n .. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,\n Eighth Edition. McGraw-Hill Professional, 2007.\n .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n return roughness/D\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 57102}, "tests/test_core.py::287": {"resolved_imports": ["fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["K_from_L_equiv", "K_from_f", "L_equiv_from_K", "L_from_K", "P_from_head", "assert_close", "assert_close1d", "dP_from_K", "f_from_K", "gravity", "head_from_K", "head_from_P", "nu_mu_converter", "pytest"], "enclosing_function": "test_core_misc2", "extracted_code": "# Source: fluids/core.py\ndef nu_mu_converter(rho: float, mu: float | None=None, nu: float | None=None) -> float:\n r\"\"\"Calculates either kinematic or dynamic viscosity, depending on inputs.\n Used when one type of viscosity is known as well as density, to obtain\n the other type. Raises an error if both types of viscosity or neither type\n of viscosity is provided.\n\n .. math::\n \\nu = \\frac{\\mu}{\\rho}\n\n .. math::\n \\mu = \\nu\\rho\n\n Parameters\n ----------\n rho : float\n Density, [kg/m^3]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n\n Returns\n -------\n mu or nu : float\n Dynamic viscosity, Pa*s or Kinematic viscosity, m^2/s\n\n Examples\n --------\n >>> nu_mu_converter(998., nu=1.0E-6)\n 0.000998\n\n References\n ----------\n .. [1] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if mu is not None and nu is None:\n return mu/rho\n elif nu is not None and mu is None:\n return nu*rho\n raise ValueError(\"Inputs must be rho and one of mu and nu.\")\n\ndef gravity(latitude: float, H: float) -> float:\n r\"\"\"Calculates local acceleration due to gravity `g` according to [1]_.\n Uses latitude and height to calculate `g`.\n\n .. math::\n g = 9.780356(1 + 0.0052885\\sin^2\\phi - 0.0000059\\sin^2(2\\phi))\n - 3.086\\times 10^{-6} H\n\n Parameters\n ----------\n latitude : float\n Degrees, [degrees]\n H : float\n Height above earth's surface [m]\n\n Returns\n -------\n g : float\n Acceleration due to gravity, [m/s^2]\n\n Notes\n -----\n Better models, such as EGM2008 exist.\n\n Examples\n --------\n >>> gravity(55, 1E4)\n 9.784151976863571\n\n References\n ----------\n .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n Chemistry and Physics. [Boca Raton, FL]: CRC press, 2014.\n \"\"\"\n lat = latitude*pi/180\n g = 9.780356*(1+0.0052885*sin(lat)**2 -0.0000059*sin(2*lat)**2)-3.086E-6*H\n return g\n\ndef K_from_f(fd: float, L: float, D: float) -> float:\n r\"\"\"Calculates loss coefficient, K, for a given section of pipe\n at a specified friction factor.\n\n .. math::\n K = f_dL/D\n\n Parameters\n ----------\n fd : float\n friction factor of pipe, []\n L : float\n Length of pipe, [m]\n D : float\n Inner diameter of pipe, [m]\n\n Returns\n -------\n K : float\n Loss coefficient, []\n\n Notes\n -----\n For fittings with a specified L/D ratio, use D = 1 and set L to\n specified L/D ratio.\n\n Examples\n --------\n >>> K_from_f(fd=0.018, L=100., D=.3)\n 6.0\n \"\"\"\n return fd*L/D\n\ndef f_from_K(K: float, L: float, D: float) -> float:\n r\"\"\"Calculates friction factor, `fd`, from a loss coefficient, K,\n for a given section of pipe.\n\n .. math::\n f_d = \\frac{K D}{L}\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n L : float\n Length of pipe, [m]\n D : float\n Inner diameter of pipe, [m]\n\n Returns\n -------\n fd : float\n Darcy friction factor of pipe, [-]\n\n Notes\n -----\n This can be useful to blend fittings at specific locations in a pipe into\n a pressure drop which is evenly distributed along a pipe.\n\n Examples\n --------\n >>> f_from_K(K=0.6, L=100., D=.3)\n 0.0018\n \"\"\"\n return K*D/L\n\ndef K_from_L_equiv(L_D: float, fd: float=0.015) -> float:\n r\"\"\"Calculates loss coefficient, for a given equivalent length (L/D).\n\n .. math::\n K = f_d \\frac{L}{D}\n\n Parameters\n ----------\n L_D : float\n Length over diameter, []\n fd : float, optional\n Darcy friction factor, [-]\n\n Returns\n -------\n K : float\n Loss coefficient, []\n\n Notes\n -----\n Almost identical to `K_from_f`, but with a default friction factor for\n fully turbulent flow in steel pipes.\n\n Examples\n --------\n >>> K_from_L_equiv(240)\n 3.5999999999999996\n \"\"\"\n return fd*L_D\n\ndef L_equiv_from_K(K: float, fd: float=0.015) -> float:\n r\"\"\"Calculates equivalent length of pipe (L/D), for a given loss\n coefficient.\n\n .. math::\n \\frac{L}{D} = \\frac{K}{f_d}\n\n Parameters\n ----------\n K : float\n Loss coefficient, [-]\n fd : float, optional\n Darcy friction factor, [-]\n\n Returns\n -------\n L_D : float\n Length over diameter, [-]\n\n Notes\n -----\n Assumes a default friction factor for fully turbulent flow in steel pipes.\n\n Examples\n --------\n >>> L_equiv_from_K(3.6)\n 240.00000000000003\n \"\"\"\n return K/fd\n\ndef L_from_K(K: float, D: float, fd: float=0.015) -> float:\n r\"\"\"Calculates the length of straight pipe at a specified friction factor\n required to produce a given loss coefficient `K`.\n\n .. math::\n L = \\frac{K D}{f_d}\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n D : float\n Inner diameter of pipe, [m]\n fd : float\n friction factor of pipe, []\n\n Returns\n -------\n L : float\n Length of pipe, [m]\n\n Examples\n --------\n >>> L_from_K(K=6, D=.3, fd=0.018)\n 100.0\n \"\"\"\n return K*D/fd\n\ndef dP_from_K(K: float, rho: float, V: float) -> float:\n r\"\"\"Calculates pressure drop, for a given loss coefficient,\n at a specified density and velocity.\n\n .. math::\n dP = 0.5K\\rho V^2\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n rho : float\n Density of fluid, [kg/m^3]\n V : float\n Velocity of fluid in pipe, [m/s]\n\n Returns\n -------\n dP : float\n Pressure drop, [Pa]\n\n Notes\n -----\n Loss coefficient `K` is usually the sum of several factors, including\n the friction factor.\n\n Examples\n --------\n >>> dP_from_K(K=10, rho=1000, V=3)\n 45000.0\n \"\"\"\n return K*0.5*rho*V*V\n\ndef head_from_K(K: float, V: float, g: float=g) -> float:\n r\"\"\"Calculates head loss, for a given loss coefficient,\n at a specified velocity.\n\n .. math::\n \\text{head} = \\frac{K V^2}{2g}\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n V : float\n Velocity of fluid in pipe, [m/s]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n head : float\n Head loss, [m]\n\n Notes\n -----\n Loss coefficient `K` is usually the sum of several factors, including\n the friction factor.\n\n Examples\n --------\n >>> head_from_K(K=10, V=1.5)\n 1.1471807396001694\n \"\"\"\n return K*0.5*V*V/g\n\ndef head_from_P(P: float, rho: float, g: float=g) -> float:\n r\"\"\"Calculates head for a fluid of specified density at specified\n pressure.\n\n .. math::\n \\text{head} = {P\\over{\\rho g}}\n\n Parameters\n ----------\n P : float\n Pressure fluid in pipe, [Pa]\n rho : float\n Density of fluid, [kg/m^3]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n head : float\n Head, [m]\n\n Notes\n -----\n By definition. Head varies with location, inversely proportional to the\n increase in gravitational constant.\n\n Examples\n --------\n >>> head_from_P(P=98066.5, rho=1000)\n 10.000000000000002\n \"\"\"\n return P/rho/g\n\ndef P_from_head(head: float, rho: float, g: float=g) -> float:\n r\"\"\"Calculates pressure for a fluid of specified density at specified\n head.\n\n .. math::\n P = \\rho g \\cdot \\text{head}\n\n Parameters\n ----------\n head : float\n Head, [m]\n rho : float\n Density of fluid, [kg/m^3]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n P : float\n Pressure fluid in pipe, [Pa]\n\n Notes\n -----\n\n Examples\n --------\n >>> P_from_head(head=5., rho=800.)\n 39226.6\n \"\"\"\n return head*rho*g\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 8864}, "tests/test_core.py::290": {"resolved_imports": ["fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["K_from_L_equiv", "K_from_f", "L_equiv_from_K", "L_from_K", "P_from_head", "assert_close", "assert_close1d", "dP_from_K", "f_from_K", "gravity", "head_from_K", "head_from_P", "nu_mu_converter", "pytest"], "enclosing_function": "test_core_misc2", "extracted_code": "# Source: fluids/core.py\ndef nu_mu_converter(rho: float, mu: float | None=None, nu: float | None=None) -> float:\n r\"\"\"Calculates either kinematic or dynamic viscosity, depending on inputs.\n Used when one type of viscosity is known as well as density, to obtain\n the other type. Raises an error if both types of viscosity or neither type\n of viscosity is provided.\n\n .. math::\n \\nu = \\frac{\\mu}{\\rho}\n\n .. math::\n \\mu = \\nu\\rho\n\n Parameters\n ----------\n rho : float\n Density, [kg/m^3]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n\n Returns\n -------\n mu or nu : float\n Dynamic viscosity, Pa*s or Kinematic viscosity, m^2/s\n\n Examples\n --------\n >>> nu_mu_converter(998., nu=1.0E-6)\n 0.000998\n\n References\n ----------\n .. [1] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if mu is not None and nu is None:\n return mu/rho\n elif nu is not None and mu is None:\n return nu*rho\n raise ValueError(\"Inputs must be rho and one of mu and nu.\")\n\ndef gravity(latitude: float, H: float) -> float:\n r\"\"\"Calculates local acceleration due to gravity `g` according to [1]_.\n Uses latitude and height to calculate `g`.\n\n .. math::\n g = 9.780356(1 + 0.0052885\\sin^2\\phi - 0.0000059\\sin^2(2\\phi))\n - 3.086\\times 10^{-6} H\n\n Parameters\n ----------\n latitude : float\n Degrees, [degrees]\n H : float\n Height above earth's surface [m]\n\n Returns\n -------\n g : float\n Acceleration due to gravity, [m/s^2]\n\n Notes\n -----\n Better models, such as EGM2008 exist.\n\n Examples\n --------\n >>> gravity(55, 1E4)\n 9.784151976863571\n\n References\n ----------\n .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n Chemistry and Physics. [Boca Raton, FL]: CRC press, 2014.\n \"\"\"\n lat = latitude*pi/180\n g = 9.780356*(1+0.0052885*sin(lat)**2 -0.0000059*sin(2*lat)**2)-3.086E-6*H\n return g\n\ndef K_from_f(fd: float, L: float, D: float) -> float:\n r\"\"\"Calculates loss coefficient, K, for a given section of pipe\n at a specified friction factor.\n\n .. math::\n K = f_dL/D\n\n Parameters\n ----------\n fd : float\n friction factor of pipe, []\n L : float\n Length of pipe, [m]\n D : float\n Inner diameter of pipe, [m]\n\n Returns\n -------\n K : float\n Loss coefficient, []\n\n Notes\n -----\n For fittings with a specified L/D ratio, use D = 1 and set L to\n specified L/D ratio.\n\n Examples\n --------\n >>> K_from_f(fd=0.018, L=100., D=.3)\n 6.0\n \"\"\"\n return fd*L/D\n\ndef f_from_K(K: float, L: float, D: float) -> float:\n r\"\"\"Calculates friction factor, `fd`, from a loss coefficient, K,\n for a given section of pipe.\n\n .. math::\n f_d = \\frac{K D}{L}\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n L : float\n Length of pipe, [m]\n D : float\n Inner diameter of pipe, [m]\n\n Returns\n -------\n fd : float\n Darcy friction factor of pipe, [-]\n\n Notes\n -----\n This can be useful to blend fittings at specific locations in a pipe into\n a pressure drop which is evenly distributed along a pipe.\n\n Examples\n --------\n >>> f_from_K(K=0.6, L=100., D=.3)\n 0.0018\n \"\"\"\n return K*D/L\n\ndef K_from_L_equiv(L_D: float, fd: float=0.015) -> float:\n r\"\"\"Calculates loss coefficient, for a given equivalent length (L/D).\n\n .. math::\n K = f_d \\frac{L}{D}\n\n Parameters\n ----------\n L_D : float\n Length over diameter, []\n fd : float, optional\n Darcy friction factor, [-]\n\n Returns\n -------\n K : float\n Loss coefficient, []\n\n Notes\n -----\n Almost identical to `K_from_f`, but with a default friction factor for\n fully turbulent flow in steel pipes.\n\n Examples\n --------\n >>> K_from_L_equiv(240)\n 3.5999999999999996\n \"\"\"\n return fd*L_D\n\ndef L_equiv_from_K(K: float, fd: float=0.015) -> float:\n r\"\"\"Calculates equivalent length of pipe (L/D), for a given loss\n coefficient.\n\n .. math::\n \\frac{L}{D} = \\frac{K}{f_d}\n\n Parameters\n ----------\n K : float\n Loss coefficient, [-]\n fd : float, optional\n Darcy friction factor, [-]\n\n Returns\n -------\n L_D : float\n Length over diameter, [-]\n\n Notes\n -----\n Assumes a default friction factor for fully turbulent flow in steel pipes.\n\n Examples\n --------\n >>> L_equiv_from_K(3.6)\n 240.00000000000003\n \"\"\"\n return K/fd\n\ndef L_from_K(K: float, D: float, fd: float=0.015) -> float:\n r\"\"\"Calculates the length of straight pipe at a specified friction factor\n required to produce a given loss coefficient `K`.\n\n .. math::\n L = \\frac{K D}{f_d}\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n D : float\n Inner diameter of pipe, [m]\n fd : float\n friction factor of pipe, []\n\n Returns\n -------\n L : float\n Length of pipe, [m]\n\n Examples\n --------\n >>> L_from_K(K=6, D=.3, fd=0.018)\n 100.0\n \"\"\"\n return K*D/fd\n\ndef dP_from_K(K: float, rho: float, V: float) -> float:\n r\"\"\"Calculates pressure drop, for a given loss coefficient,\n at a specified density and velocity.\n\n .. math::\n dP = 0.5K\\rho V^2\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n rho : float\n Density of fluid, [kg/m^3]\n V : float\n Velocity of fluid in pipe, [m/s]\n\n Returns\n -------\n dP : float\n Pressure drop, [Pa]\n\n Notes\n -----\n Loss coefficient `K` is usually the sum of several factors, including\n the friction factor.\n\n Examples\n --------\n >>> dP_from_K(K=10, rho=1000, V=3)\n 45000.0\n \"\"\"\n return K*0.5*rho*V*V\n\ndef head_from_K(K: float, V: float, g: float=g) -> float:\n r\"\"\"Calculates head loss, for a given loss coefficient,\n at a specified velocity.\n\n .. math::\n \\text{head} = \\frac{K V^2}{2g}\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n V : float\n Velocity of fluid in pipe, [m/s]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n head : float\n Head loss, [m]\n\n Notes\n -----\n Loss coefficient `K` is usually the sum of several factors, including\n the friction factor.\n\n Examples\n --------\n >>> head_from_K(K=10, V=1.5)\n 1.1471807396001694\n \"\"\"\n return K*0.5*V*V/g\n\ndef head_from_P(P: float, rho: float, g: float=g) -> float:\n r\"\"\"Calculates head for a fluid of specified density at specified\n pressure.\n\n .. math::\n \\text{head} = {P\\over{\\rho g}}\n\n Parameters\n ----------\n P : float\n Pressure fluid in pipe, [Pa]\n rho : float\n Density of fluid, [kg/m^3]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n head : float\n Head, [m]\n\n Notes\n -----\n By definition. Head varies with location, inversely proportional to the\n increase in gravitational constant.\n\n Examples\n --------\n >>> head_from_P(P=98066.5, rho=1000)\n 10.000000000000002\n \"\"\"\n return P/rho/g\n\ndef P_from_head(head: float, rho: float, g: float=g) -> float:\n r\"\"\"Calculates pressure for a fluid of specified density at specified\n head.\n\n .. math::\n P = \\rho g \\cdot \\text{head}\n\n Parameters\n ----------\n head : float\n Head, [m]\n rho : float\n Density of fluid, [kg/m^3]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n P : float\n Pressure fluid in pipe, [Pa]\n\n Notes\n -----\n\n Examples\n --------\n >>> P_from_head(head=5., rho=800.)\n 39226.6\n \"\"\"\n return head*rho*g\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 8864}, "tests/test_core.py::296": {"resolved_imports": ["fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["K_from_L_equiv", "K_from_f", "L_equiv_from_K", "L_from_K", "P_from_head", "assert_close", "assert_close1d", "dP_from_K", "f_from_K", "gravity", "head_from_K", "head_from_P", "nu_mu_converter", "pytest"], "enclosing_function": "test_core_misc2", "extracted_code": "# Source: fluids/core.py\ndef nu_mu_converter(rho: float, mu: float | None=None, nu: float | None=None) -> float:\n r\"\"\"Calculates either kinematic or dynamic viscosity, depending on inputs.\n Used when one type of viscosity is known as well as density, to obtain\n the other type. Raises an error if both types of viscosity or neither type\n of viscosity is provided.\n\n .. math::\n \\nu = \\frac{\\mu}{\\rho}\n\n .. math::\n \\mu = \\nu\\rho\n\n Parameters\n ----------\n rho : float\n Density, [kg/m^3]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n\n Returns\n -------\n mu or nu : float\n Dynamic viscosity, Pa*s or Kinematic viscosity, m^2/s\n\n Examples\n --------\n >>> nu_mu_converter(998., nu=1.0E-6)\n 0.000998\n\n References\n ----------\n .. [1] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if mu is not None and nu is None:\n return mu/rho\n elif nu is not None and mu is None:\n return nu*rho\n raise ValueError(\"Inputs must be rho and one of mu and nu.\")\n\ndef gravity(latitude: float, H: float) -> float:\n r\"\"\"Calculates local acceleration due to gravity `g` according to [1]_.\n Uses latitude and height to calculate `g`.\n\n .. math::\n g = 9.780356(1 + 0.0052885\\sin^2\\phi - 0.0000059\\sin^2(2\\phi))\n - 3.086\\times 10^{-6} H\n\n Parameters\n ----------\n latitude : float\n Degrees, [degrees]\n H : float\n Height above earth's surface [m]\n\n Returns\n -------\n g : float\n Acceleration due to gravity, [m/s^2]\n\n Notes\n -----\n Better models, such as EGM2008 exist.\n\n Examples\n --------\n >>> gravity(55, 1E4)\n 9.784151976863571\n\n References\n ----------\n .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n Chemistry and Physics. [Boca Raton, FL]: CRC press, 2014.\n \"\"\"\n lat = latitude*pi/180\n g = 9.780356*(1+0.0052885*sin(lat)**2 -0.0000059*sin(2*lat)**2)-3.086E-6*H\n return g\n\ndef K_from_f(fd: float, L: float, D: float) -> float:\n r\"\"\"Calculates loss coefficient, K, for a given section of pipe\n at a specified friction factor.\n\n .. math::\n K = f_dL/D\n\n Parameters\n ----------\n fd : float\n friction factor of pipe, []\n L : float\n Length of pipe, [m]\n D : float\n Inner diameter of pipe, [m]\n\n Returns\n -------\n K : float\n Loss coefficient, []\n\n Notes\n -----\n For fittings with a specified L/D ratio, use D = 1 and set L to\n specified L/D ratio.\n\n Examples\n --------\n >>> K_from_f(fd=0.018, L=100., D=.3)\n 6.0\n \"\"\"\n return fd*L/D\n\ndef f_from_K(K: float, L: float, D: float) -> float:\n r\"\"\"Calculates friction factor, `fd`, from a loss coefficient, K,\n for a given section of pipe.\n\n .. math::\n f_d = \\frac{K D}{L}\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n L : float\n Length of pipe, [m]\n D : float\n Inner diameter of pipe, [m]\n\n Returns\n -------\n fd : float\n Darcy friction factor of pipe, [-]\n\n Notes\n -----\n This can be useful to blend fittings at specific locations in a pipe into\n a pressure drop which is evenly distributed along a pipe.\n\n Examples\n --------\n >>> f_from_K(K=0.6, L=100., D=.3)\n 0.0018\n \"\"\"\n return K*D/L\n\ndef K_from_L_equiv(L_D: float, fd: float=0.015) -> float:\n r\"\"\"Calculates loss coefficient, for a given equivalent length (L/D).\n\n .. math::\n K = f_d \\frac{L}{D}\n\n Parameters\n ----------\n L_D : float\n Length over diameter, []\n fd : float, optional\n Darcy friction factor, [-]\n\n Returns\n -------\n K : float\n Loss coefficient, []\n\n Notes\n -----\n Almost identical to `K_from_f`, but with a default friction factor for\n fully turbulent flow in steel pipes.\n\n Examples\n --------\n >>> K_from_L_equiv(240)\n 3.5999999999999996\n \"\"\"\n return fd*L_D\n\ndef L_equiv_from_K(K: float, fd: float=0.015) -> float:\n r\"\"\"Calculates equivalent length of pipe (L/D), for a given loss\n coefficient.\n\n .. math::\n \\frac{L}{D} = \\frac{K}{f_d}\n\n Parameters\n ----------\n K : float\n Loss coefficient, [-]\n fd : float, optional\n Darcy friction factor, [-]\n\n Returns\n -------\n L_D : float\n Length over diameter, [-]\n\n Notes\n -----\n Assumes a default friction factor for fully turbulent flow in steel pipes.\n\n Examples\n --------\n >>> L_equiv_from_K(3.6)\n 240.00000000000003\n \"\"\"\n return K/fd\n\ndef L_from_K(K: float, D: float, fd: float=0.015) -> float:\n r\"\"\"Calculates the length of straight pipe at a specified friction factor\n required to produce a given loss coefficient `K`.\n\n .. math::\n L = \\frac{K D}{f_d}\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n D : float\n Inner diameter of pipe, [m]\n fd : float\n friction factor of pipe, []\n\n Returns\n -------\n L : float\n Length of pipe, [m]\n\n Examples\n --------\n >>> L_from_K(K=6, D=.3, fd=0.018)\n 100.0\n \"\"\"\n return K*D/fd\n\ndef dP_from_K(K: float, rho: float, V: float) -> float:\n r\"\"\"Calculates pressure drop, for a given loss coefficient,\n at a specified density and velocity.\n\n .. math::\n dP = 0.5K\\rho V^2\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n rho : float\n Density of fluid, [kg/m^3]\n V : float\n Velocity of fluid in pipe, [m/s]\n\n Returns\n -------\n dP : float\n Pressure drop, [Pa]\n\n Notes\n -----\n Loss coefficient `K` is usually the sum of several factors, including\n the friction factor.\n\n Examples\n --------\n >>> dP_from_K(K=10, rho=1000, V=3)\n 45000.0\n \"\"\"\n return K*0.5*rho*V*V\n\ndef head_from_K(K: float, V: float, g: float=g) -> float:\n r\"\"\"Calculates head loss, for a given loss coefficient,\n at a specified velocity.\n\n .. math::\n \\text{head} = \\frac{K V^2}{2g}\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n V : float\n Velocity of fluid in pipe, [m/s]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n head : float\n Head loss, [m]\n\n Notes\n -----\n Loss coefficient `K` is usually the sum of several factors, including\n the friction factor.\n\n Examples\n --------\n >>> head_from_K(K=10, V=1.5)\n 1.1471807396001694\n \"\"\"\n return K*0.5*V*V/g\n\ndef head_from_P(P: float, rho: float, g: float=g) -> float:\n r\"\"\"Calculates head for a fluid of specified density at specified\n pressure.\n\n .. math::\n \\text{head} = {P\\over{\\rho g}}\n\n Parameters\n ----------\n P : float\n Pressure fluid in pipe, [Pa]\n rho : float\n Density of fluid, [kg/m^3]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n head : float\n Head, [m]\n\n Notes\n -----\n By definition. Head varies with location, inversely proportional to the\n increase in gravitational constant.\n\n Examples\n --------\n >>> head_from_P(P=98066.5, rho=1000)\n 10.000000000000002\n \"\"\"\n return P/rho/g\n\ndef P_from_head(head: float, rho: float, g: float=g) -> float:\n r\"\"\"Calculates pressure for a fluid of specified density at specified\n head.\n\n .. math::\n P = \\rho g \\cdot \\text{head}\n\n Parameters\n ----------\n head : float\n Head, [m]\n rho : float\n Density of fluid, [kg/m^3]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n P : float\n Pressure fluid in pipe, [Pa]\n\n Notes\n -----\n\n Examples\n --------\n >>> P_from_head(head=5., rho=800.)\n 39226.6\n \"\"\"\n return head*rho*g\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 8864}, "tests/test_design_climate.py::53": {"resolved_imports": ["fluids/design_climate.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "heating_degree_days"], "enclosing_function": "test_heating_degree_days", "extracted_code": "# Source: fluids/design_climate.py\ndef heating_degree_days(T, T_base=291.4833333333333, truncate=True):\n r\"\"\"Calculates the heating degree days for a period of time.\n\n .. math::\n \\text{heating degree days} = max(T - T_{base}, 0)\n\n Parameters\n ----------\n T : float\n Measured temperature; sometimes an average over a length of time is used,\n other times the average of the lowest and highest temperature in a\n period are used, [K]\n T_base : float, optional\n Reference temperature for the degree day calculation, defaults\n to 65 °F (18.33 °C, 291.483 K), the value most used in the US, [K]\n truncate : bool\n If truncate is True, no negative values will be returned; if negative,\n the value is truncated to 0, [-]\n\n Returns\n -------\n heating_degree_days : float\n Degree above the base temperature multiplied by the length of time of\n the measurement, normally days [day*K]\n\n Notes\n -----\n Some common base temperatures are 18 °C (Canada), 15.5 °C (EU),\n 17 °C (Denmark, Finland), 12 °C Switzerland. The base temperature\n should always be presented with the results.\n\n The time unit does not have to be days; it can be any time unit, and the\n calculation behaves the same.\n\n Examples\n --------\n >>> heating_degree_days(303.8)\n 12.31666666666672\n\n >>> heating_degree_days(273)\n 0.0\n\n >>> heating_degree_days(322, T_base=300)\n 22\n\n References\n ----------\n .. [1] \"Heating Degree Day.\" Wikipedia, January 24, 2018.\n https://en.wikipedia.org/w/index.php?title=Heating_degree_day&oldid=822187764.\n \"\"\"\n dd = T - T_base\n if truncate and dd < 0.0:\n dd = 0.0\n return dd\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 2346}, "tests/test_fittings.py::332": {"resolved_imports": ["fluids/fittings.py", "fluids/constants/__init__.py", "fluids/core.py", "fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "assert_close1d", "bend_rounded", "ft_Crane"], "enclosing_function": "test_bend_rounded", "extracted_code": "# Source: fluids/fittings.py\ndef bend_rounded(Di: float, angle: float, fd: float | None=None, rc: float | None=None, bend_diameters: float | None=None,\n Re: float | None=None, roughness: float=0.0, L_unimpeded: None=None, method: str=\"Rennels\") -> float:\n r\"\"\"Returns loss coefficient for rounded bend in a pipe of diameter `Di`,\n `angle`, with a specified either radius of curvature `rc` or curvature\n defined by `bend_diameters`, Reynolds number `Re` and optionally pipe\n roughness, unimpeded length downstream, and with the specified method.\n This calculation has six methods available.\n\n It is hard to describe one method as more conservative than another as\n depending on the conditions, the relative results change significantly.\n\n The 'Miller' method is the most complicated and slowest method; the 'Ito'\n method comprehensive as well and a source of original data, and the primary\n basis for the 'Rennels' method. The 'Swamee' method is very simple and\n generally does not match the other methods. The 'Crane' method may match\n or not match other methods depending on the inputs. There is also a\n 'Crane standard' method for use with threaded fittings which have higher\n pressure drops. It is a linear interpolation of values at angles of\n 45, 90, and 180 degrees.\n\n The Rennels [1]_ formula is:\n\n .. math::\n K = f\\alpha\\frac{r}{d} + (0.10 + 2.4f)\\sin(\\alpha/2)\n + \\frac{6.6f(\\sqrt{\\sin(\\alpha/2)}+\\sin(\\alpha/2))}\n {(r/d)^{\\frac{4\\alpha}{\\pi}}}\n\n The Swamee [5]_ formula is:\n\n .. math::\n K = \\left[0.0733 + 0.923 \\left(\\frac{d}{rc}\\right)^{3.5} \\right]\n \\theta^{0.5}\n\n .. figure:: fittings/bend_rounded.png\n :scale: 30 %\n :alt: rounded bend; after [1]_\n\n Parameters\n ----------\n Di : float\n Inside diameter of pipe, [m]\n angle : float\n Angle of bend, [degrees]\n fd : float, optional\n Darcy friction factor; used only in Rennels method; calculated if not\n provided from Reynolds number, diameter, and roughness [-]\n rc : float, optional\n Radius of curvature of the entrance, optional [m]\n bend_diameters : float, optional (used if rc not provided)\n Number of diameters of pipe making up the bend radius [-]\n Re : float, optional\n Reynolds number of the pipe (used in Miller, Ito methods primarily, and\n Rennels method if no friction factor given), [-]\n roughness : float, optional\n Roughness of bend wall (used in Miller, Ito methods primarily, and\n Rennels method if no friction factor given), [m]\n L_unimpeded : float, optional\n The length of unimpeded pipe without any fittings, instrumentation,\n or flow disturbances downstream (assumed 20 diameters if not\n specified); used only in Miller method, [m]\n method : str, optional\n One of 'Rennels', 'Miller', 'Crane', 'Crane standard', 'Ito', or\n 'Swamee', [-]\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n When inputting bend diameters, note that manufacturers often specify\n this as a multiplier of nominal diameter, which is different than actual\n diameter. Those require that rc be specified.\n\n In the 'Rennels' method, `rc` is limited to 0.5 or above; which represents\n a sharp, square, inner edge - and an outer bend radius of 1.0. Losses are\n at a minimum when this value is large. Its first term represents surface\n friction loss; the second, secondary flows; and the third, flow separation.\n It encompasses the entire range of elbow and pipe bend configurations.\n It was developed for bend angles between 0 and 180 degrees; and r/D\n ratios above 0.5. Only smooth pipe data was used in its development.\n Note the loss coefficient includes the surface friction of the pipe as if\n it was straight.\n\n Examples\n --------\n >>> bend_rounded(Di=4.020, rc=4.0*5, angle=30, Re=1E5)\n 0.11519070808085191\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n .. [2] Miller, Donald S. Internal Flow Systems: Design and Performance\n Prediction. Gulf Publishing Company, 1990.\n .. [3] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,\n 2009.\n .. [4] Swamee, Prabhata K., and Ashok K. Sharma. Design of Water Supply\n Pipe Networks. John Wiley & Sons, 2008.\n .. [5] Itō, H.\"Pressure Losses in Smooth Pipe Bends.\" Journal of Fluids\n Engineering 82, no. 1 (March 1, 1960): 131-40. doi:10.1115/1.3662501\n .. [6] Blevins, Robert D. Applied Fluid Dynamics Handbook. New York, N.Y.:\n Van Nostrand Reinhold Co., 1984.\n \"\"\"\n if method is None:\n method = \"Rennels\"\n if bend_diameters is None and rc is None:\n bend_diameters = 5.0\n if rc is None:\n if bend_diameters is None:\n bend_diameters = 5.0 # already handled by earlier check\n bend_diameters2 = bend_diameters\n rc = Di*bend_diameters2\n else:\n bend_diameters2 = bend_diameters if bend_diameters is not None else 5.0\n\n if method == \"Rennels\":\n angle = radians(angle)\n if fd is None:\n if Re is None:\n raise ValueError(\"The `Rennels` method requires either a \"\n \"specified friction factor or `Re`\")\n fd = Clamond(Re=Re, eD=roughness/Di, fast=False)\n sin_term = sin(0.5*angle)\n return (fd*angle*rc/Di + (0.10 + 2.4*fd)*sin_term\n + 6.6*fd*(sqrt(sin_term) + sin_term)/(rc/Di)**(4.*angle/pi))\n elif method == \"Miller\":\n if Re is None:\n raise ValueError(\"Miller method requires Reynolds number\")\n return bend_rounded_Miller(Di=Di, angle=angle, Re=Re, rc=rc,\n bend_diameters=bend_diameters2,\n roughness=roughness,\n L_unimpeded=L_unimpeded)\n elif method == \"Crane\":\n return bend_rounded_Crane(Di=Di, angle=angle, rc=rc,\n bend_diameters=bend_diameters2)\n elif method == \"Crane standard\":\n return ft_Crane(Di)*interp(angle, crane_standard_bend_angles, crane_standard_bend_losses, extrapolate=True)\n elif method == \"Ito\":\n if Re is None:\n raise ValueError(\"The `Ito` method requires `Re`\")\n return bend_rounded_Ito(Di=Di, angle=angle, Re=Re, rc=rc, bend_diameters=bend_diameters2,\n roughness=roughness)\n elif method == \"Swamee\":\n return (0.0733 + 0.923*(Di/rc)**3.5)*sqrt(radians(angle))\n else:\n raise ValueError(bend_rounded_method_unknown)\n\n\n# Source: fluids/friction.py\ndef ft_Crane(D: float) -> float:\n r\"\"\"Calculates the Crane fully turbulent Darcy friction factor for flow in\n commercial pipe, as used in the Crane formulas for loss coefficients in\n various fittings. Note that this is **not generally applicable to loss\n due to friction in pipes**, as it does not take into account the roughness\n of various pipe materials. But for fittings in any type of pipe, this is\n the friction factor to use in the Crane [1]_ method to get their loss\n coefficients.\n\n Parameters\n ----------\n D : float\n Pipe inner diameter, [m]\n\n Returns\n -------\n fd : float\n Darcy Crane friction factor for fully turbulent flow, [-]\n\n Notes\n -----\n There is confusion and uncertainty regarding the friction factor table\n given in Crane TP 410M [1]_. This function does not help: it implements a\n new way to obtain Crane friction factors, so that it can better be based in\n theory and give more precision (not accuracy) and trend better with\n diameters not tabulated in [1]_.\n\n The data in [1]_ was digitized, and nominal pipe diameters were converted\n to actual pipe diameters. An objective function was sought which would\n produce the exact same values as in [1]_ when rounded to the same decimal\n place. One was found fairly easily by using the standard `Colebrook`\n friction factor formula, and using the diameter-dependent roughness values\n calculated with the `roughness_Farshad` method for bare Carbon steel. A\n diameter-dependent Reynolds number was required to match the values;\n the :math:`\\rho V/\\mu` term is set to 7.5E6.\n\n The formula given in [1]_ is:\n\n .. math::\n f_T = \\frac{0.25}{\\left[\\log_{10}\\left(\\frac{\\epsilon/D}{3.7}\\right)\n \\right]^2}\n\n However, this function does not match the rounded values in [1]_ well and\n it is not very clear which roughness to use. Using both the value for new\n commercial steel (.05 mm) or a diameter-dependent value\n (`roughness_Farshad`), values were found to be too high and too low\n respectively. That function is based in theory - the limit of the\n `Colebrook` equation when `Re` goes to infinity - but in the end real pipe\n flow is not infinity, and so a large error occurs from that use.\n\n The following plot shows all these options, and that the method implemented\n here matches perfectly the rounded values in [1]_.\n\n .. plot:: plots/ft_Crane_plot.py\n\n Examples\n --------\n >>> ft_Crane(.1)\n 0.01628845962146481\n\n Explicitly spelling out the function (note the exact same answer is not\n returned; it is accurate to 5-8 decimals however, for increased speed):\n\n >>> Di = 0.1\n >>> Colebrook(7.5E6*Di, eD=roughness_Farshad(ID='Carbon steel, bare', D=Di)/Di)\n 0.0162884254312\n\n References\n ----------\n .. [1] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,\n 2009.\n \"\"\"\n fast = True\n if D < 1E-2:\n fast = False\n return Clamond(7.5E6*D, 3.4126825352925e-5*D**-1.0112, fast)\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 10737}, "tests/test_fittings.py::389": {"resolved_imports": ["fluids/fittings.py", "fluids/constants/__init__.py", "fluids/core.py", "fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["bend_rounded_Miller", "isinf", "isnan", "pytest"], "enclosing_function": "test_bend_rounded_Miller_fuzz", "extracted_code": "# Source: fluids/fittings.py\ndef bend_rounded_Miller(Di: float, angle: float, Re: float, rc: float | None=None, bend_diameters: float | None=None,\n roughness: float=0.0, L_unimpeded: float | None=None) -> float:\n r\"\"\"Calculates the loss coefficient for a rounded pipe bend according to\n Miller [1]_. This is a sophisticated model which uses corrections for\n pipe roughness, the length of the pipe downstream before another\n interruption, and a correction for Reynolds number. It interpolates several\n times using several corrections graphs in [1]_.\n\n Parameters\n ----------\n Di : float\n Inside diameter of pipe, [m]\n angle : float\n Angle of bend, [degrees]\n Re : float\n Reynolds number of the pipe (no specification if inlet or outlet\n properties should be used), [m]\n rc : float, optional\n Radius of curvature of the entrance, [m]\n bend_diameters : float, optional\n Number of diameters of pipe making up the bend radius (used if rc not\n provided; defaults to 5), [-]\n roughness : float, optional\n Roughness of bend wall, [m]\n L_unimpeded : float, optional\n The length of unimpeded pipe without any fittings, instrumentation,\n or flow disturbances downstream (assumed 20 diameters if not\n specified), [m]\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n When inputting bend diameters, note that manufacturers often specify\n this as a multiplier of nominal diameter, which is different than actual\n diameter. Those require that rc be specified.\n\n `rc` is limited to 0.5 or above; which represents a sharp, square, inner\n edge - and an outer bend radius of 1.0. Losses are at a minimum when this\n value is large.\n\n This was developed for bend angles between 10 and 180 degrees; and r/D\n ratios between 0.5 and 10. Both smooth and rough data was used in its\n development from several sources.\n\n Note the loss coefficient includes the surface friction of the pipe as if\n it was straight.\n\n Examples\n --------\n >>> bend_rounded_Miller(Di=.6, bend_diameters=2, angle=90, Re=2e6,\n ... roughness=2E-5, L_unimpeded=30*.6)\n 0.15261820705145895\n\n References\n ----------\n .. [1] Miller, Donald S. Internal Flow Systems: Design and Performance\n Prediction. Gulf Publishing Company, 1990.\n \"\"\"\n if rc is None:\n if bend_diameters is None:\n bend_diameters = 5.0\n rc = Di*bend_diameters\n\n radius_ratio = rc/Di\n\n if L_unimpeded is None:\n # Assumption - smooth outlet\n L_unimpeded = 20.0*Di\n\n # Graph is defined for angles 10 to 180 degrees, ratios 0.5 to 10\n if radius_ratio < 0.5:\n radius_ratio = 0.5\n if radius_ratio > 10.0:\n radius_ratio = 10.0\n if angle < 10.0:\n angle = 10.0\n\n # Curve fit in terms of degrees\n # Caching could work here - angle, radius ratio does not change often\n Kb = bend_rounded_Miller_Kb(radius_ratio, angle)\n\n C_roughness = Miller_bend_roughness_correction(Re=Re, Di=Di,\n roughness=roughness)\n \"\"\"Section 9.2.2 - Reynolds Number Correction\n Allow some extrapolation up to 1E8 (1E7 max in graph but the trend looks good)\n \"\"\"\n Re_C_Re = min(max(Re, 1E4), 1E8)\n if radius_ratio >= 2.0:\n if Re_C_Re == 1E8:\n C_Re = 0.4196741237602154 # bend_rounded_Miller_C_Re(1e8, 2.0)\n elif Re_C_Re == 1E4:\n C_Re = 2.1775876405173977 # bend_rounded_Miller_C_Re(1e4, 2.0)\n else:\n C_Re = bend_rounded_Miller_C_Re(Re_C_Re, 2.0)\n elif radius_ratio <= 1.0:\n # newton(lambda x: bend_rounded_Miller_C_Re(x, 1.0)-1, 2e5) to get the boundary value\n C_Re_1 = bend_rounded_Miller_C_Re(Re_C_Re, 1.0) if Re_C_Re < 207956.58904584477 else 1.0\n if radius_ratio > 0.7 or Kb < 0.4:\n C_Re = C_Re_1\n else:\n C_Re = Kb/(Kb - 0.2*C_Re_1 + 0.2)\n if C_Re > 2.2 or C_Re < 0:\n C_Re = 2.2\n else:\n # regardless of ratio - 1\n if Re_C_Re > 1048884.4656835075:\n C_Re = 1.0\n elif Re_C_Re > horner(bend_rounded_Miller_C_Re_limit_1, radius_ratio):\n C_Re = 1.0\n# ps = np.linspace(1, 2)\n# qs = [secant(lambda x: bend_rounded_Miller_C_Re(x, i)-1, 2e5) for i in ps]\n# np.polyfit(ps, qs, 4).tolist()\n # Line of C_Re=1 as a function of r_d between 0 and 1\n else:\n C_Re = bend_rounded_Miller_C_Re(Re_C_Re, radius_ratio)\n C_o = Miller_bend_unimpeded_correction(Kb=Kb, Di=Di, L_unimpeded=L_unimpeded)\n\n# print('Kb=%g, C Re=%g, C rough =%g, Co=%g' %(Kb, C_Re, C_roughness, C_o))\n return Kb*C_Re*C_roughness*C_o", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 4818}, "tests/test_fittings.py::106": {"resolved_imports": ["fluids/fittings.py", "fluids/constants/__init__.py", "fluids/core.py", "fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["Darby", "Darby3K", "Hooper", "Hooper2K", "assert_close", "assert_close1d", "change_K_basis", "contraction_beveled", "diffuser_curved", "diffuser_pipe_reducer", "entrance_beveled_orifice", "exit_normal", "helix", "pytest", "spiral"], "enclosing_function": "test_fittings", "extracted_code": "# Source: fluids/fittings.py\ndef change_K_basis(K1: float, D1: float, D2: float) -> float:\n r\"\"\"Converts a loss coefficient `K1` from the basis of one diameter `D1`\n to another diameter, `D2`. This is necessary when dealing with pipelines\n of changing diameter.\n\n .. math::\n K_2 = K_1\\frac{D_2^4}{D_1^4} = K_1 \\frac{A_2^2}{A_1^2}\n\n Parameters\n ----------\n K1 : float\n Loss coefficient with respect to diameter `D`, [-]\n D1 : float\n Diameter of pipe for which `K1` has been calculated, [m]\n D2 : float\n Diameter of pipe for which `K2` will be calculated, [m]\n\n Returns\n -------\n K2 : float\n Loss coefficient with respect to the second diameter, [-]\n\n Notes\n -----\n This expression is shown in [1]_ and can easily be derived:\n\n .. math::\n \\frac{\\rho V_{1}^{2}}{2} \\cdot K_{1} = \\frac{\\rho V_{2}^{2} }{2}\n \\cdot K_{2}\n\n Substitute velocities for flow rate divided by area:\n\n .. math::\n \\frac{8 K_{1} Q^{2} \\rho}{\\pi^{2} D_{1}^{4}} = \\frac{8 K_{2} Q^{2}\n \\rho}{\\pi^{2} D_{2}^{4}}\n\n From here, simplification and rearrangement is all that is required.\n\n Examples\n --------\n >>> change_K_basis(K1=32.68875692997804, D1=.01, D2=.02)\n 523.020110879\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n \"\"\"\n r = D2/D1\n r *= r\n return K1*r*r\n\ndef entrance_beveled_orifice(Di: float, Do: float, l: float, angle: float) -> float:\n r\"\"\"Returns loss coefficient for a beveled or chamfered orifice entrance to\n a pipe flush with the wall of a reservoir, as shown in [1]_.\n\n .. math::\n K = 0.0696\\left(1 - C_b\\frac{l}{D_o}\\right)\\lambda^2 + \\left(\\lambda\n -\\left(\\frac{D_o}{D_i}\\right)^2\\right)^2\n\n .. math::\n \\lambda = 1 + 0.622\\left[1-C_b\\left(\\frac{l}{D_o}\\right)^{\\frac{1-\n (l/D_o)^{0.25}}{2}}\\right]\n\n .. math::\n C_b = \\left(1 - \\frac{\\Psi}{90}\\right)\\left(\\frac{\\Psi}{90}\n \\right)^{\\frac{1}{1+l/D_o}}\n\n .. figure:: fittings/flush_mounted_beveled_orifice_entrance.png\n :scale: 30 %\n :alt: Beveled orifice entrance mounted straight; after [1]_\n\n Parameters\n ----------\n Di : float\n Inside diameter of pipe, [m]\n Do : float\n Inside diameter of orifice, [m]\n l : float\n Length of bevel measured parallel to the pipe length, [m]\n angle : float\n Angle of bevel with respect to the pipe length, [degrees]\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Examples\n --------\n >>> entrance_beveled_orifice(Di=0.1, Do=.07, l=0.003, angle=45)\n 1.2987552913818574\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n \"\"\"\n Cb = (1-angle/90.)*(angle/90.)**(1./(1 + l/Do ))\n lbd = 1 + 0.622*(1 - Cb*(l/Do)**((1 - sqrt(sqrt(l/Do)))/2.))\n return 0.0696*(1 - Cb*l/Do)*lbd**2 + (lbd - (Do/Di)**2)**2\n\ndef exit_normal() -> float:\n r\"\"\"Returns loss coefficient for any exit to a pipe\n as shown in [1]_ and in other sources.\n\n .. math::\n K = 1\n\n .. figure:: fittings/flush_mounted_exit.png\n :scale: 28 %\n :alt: Exit from a flush mounted wall; after [1]_\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n It has been found on occasion that K = 2.0 for laminar flow, and ranges\n from about 1.04 to 1.10 for turbulent flow.\n\n Examples\n --------\n >>> exit_normal()\n 1.0\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n \"\"\"\n return 1.0\n\ndef helix(Di: float, rs: float, pitch: float, N: int, fd: float) -> float:\n r\"\"\"Returns loss coefficient for any size constant-pitch helix\n as shown in [1]_. Has applications in immersed coils in tanks.\n\n .. math::\n K = N \\left[f\\frac{\\sqrt{(2\\pi r)^2 + p^2}}{d} + 0.20 + 4.8 f\\right]\n\n Parameters\n ----------\n Di : float\n Inside diameter of pipe, [m]\n rs : float\n Radius of spiral, [m]\n pitch : float\n Distance between two subsequent coil centers, [m]\n N : float\n Number of coils in the helix [-]\n fd : float\n Darcy friction factor [-]\n\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n Formulation based on peak secondary flow as in two 180 degree bends per\n coil. Flow separation ignored. No f, Re, geometry limitations.\n Source not compared against others.\n\n Examples\n --------\n >>> helix(Di=0.01, rs=0.1, pitch=.03, N=10, fd=.0185)\n 14.525134924495514\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n \"\"\"\n return N*(fd*sqrt((2*pi*rs)**2 + pitch**2)/Di + 0.20 + 4.8*fd)\n\ndef spiral(Di: float, rmax: float, rmin: float, pitch: float, fd: float) -> float:\n r\"\"\"Returns loss coefficient for any size constant-pitch spiral\n as shown in [1]_. Has applications in immersed coils in tanks.\n\n .. math::\n K = \\frac{r_{max} - r_{min}}{p} \\left[ f\\pi\\left(\\frac{r_{max}\n +r_{min}}{d}\\right) + 0.20 + 4.8f\\right]\n + \\frac{13.2f}{(r_{min}/d)^2}\n\n Parameters\n ----------\n Di : float\n Inside diameter of pipe, [m]\n rmax : float\n Radius of spiral at extremity, [m]\n rmin : float\n Radius of spiral at end near center, [m]\n pitch : float\n Distance between two subsequent coil centers, [m]\n fd : float\n Darcy friction factor [-]\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n Source not compared against others.\n\n Examples\n --------\n >>> spiral(Di=0.01, rmax=.1, rmin=.02, pitch=.01, fd=0.0185)\n 7.950918552775473\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n \"\"\"\n return (rmax-rmin)/pitch*(fd*pi*(rmax+rmin)/Di + 0.20 + 4.8*fd) + 13.2*fd/(rmin/Di)**2\n\ndef contraction_beveled(Di1: float, Di2: float, l: float, angle: float) -> float:\n r\"\"\"Returns loss coefficient for any sharp beveled pipe contraction\n as shown in [1]_.\n\n .. math::\n K = 0.0696[1+C_B(\\sin(\\alpha/2)-1)](1-\\beta^5)\\lambda^2 + (\\lambda-1)^2\n\n .. math::\n \\lambda = 1 + 0.622\\left[1+C_B\\left(\\left(\\frac{\\alpha}{180}\n \\right)^{0.8}-1\\right)\\right](1-0.215\\beta^2-0.785\\beta^5)\n\n .. math::\n C_B = \\frac{l}{d_2}\\frac{2\\beta\\tan(\\alpha/2)}{1-\\beta}\n\n .. math::\n \\beta = d_2/d_1\n\n .. figure:: fittings/contraction_beveled.png\n :scale: 30 %\n :alt: contraction beveled; after [1]_\n\n Parameters\n ----------\n Di1 : float\n Inside diameter of original pipe, [m]\n Di2 : float\n Inside diameter of following pipe, [m]\n l : float\n Length of the bevel along the pipe axis, [m]\n angle : float\n Angle of bevel, [degrees]\n\n Returns\n -------\n K : float\n Loss coefficient in terms of the following pipe [-]\n\n Notes\n -----\n\n Examples\n --------\n >>> contraction_beveled(Di1=0.5, Di2=0.1, l=.7*.1, angle=120)\n 0.40946469413070485\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n \"\"\"\n angle = radians(angle)\n beta = Di2/Di1\n CB = l/Di2*2.0*beta*tan(0.5*angle)/(1.0 - beta)\n beta2 = beta*beta\n beta5 = beta2*beta2*beta\n lbd = 1.0 + 0.622*(1.0 + CB*((angle/pi)**0.8 - 1.0))*(1.0 - 0.215*beta2 - 0.785*beta5)\n return 0.0696*(1.0 + CB*(sin(0.5*angle) - 1.0))*(1.0 - beta5)*lbd*lbd + (lbd-1.0)**2\n\ndef diffuser_curved(Di1: float, Di2: float, l: float) -> float:\n r\"\"\"Returns loss coefficient for any curved wall pipe expansion\n as shown in [1]_.\n\n .. math::\n K_1 = \\phi(1.43-1.3\\beta^2)(1-\\beta^2)^2\n\n .. math::\n \\phi = 1.01 - 0.624\\frac{l}{d_1} + 0.30\\left(\\frac{l}{d_1}\\right)^2\n - 0.074\\left(\\frac{l}{d_1}\\right)^3 + 0.0070\\left(\\frac{l}{d_1}\\right)^4\n\n .. figure:: fittings/curved_wall_diffuser.png\n :scale: 25 %\n :alt: diffuser curved; after [1]_\n\n Parameters\n ----------\n Di1 : float\n Inside diameter of original pipe (smaller), [m]\n Di2 : float\n Inside diameter of following pipe (larger), [m]\n l : float\n Length of the curve along the pipe axis, [m]\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n Beta^2 should be between 0.1 and 0.9.\n A small mismatch between tabulated values of this function in table 11.3\n is observed with the equation presented.\n\n Examples\n --------\n >>> diffuser_curved(Di1=.25**0.5, Di2=1., l=2.)\n 0.2299781250000002\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n \"\"\"\n beta = Di1/Di2\n phi = 1.01 - 0.624*l/Di1 + 0.30*(l/Di1)**2 - 0.074*(l/Di1)**3 + 0.0070*(l/Di1)**4\n return phi*(1.43 - 1.3*beta**2)*(1 - beta**2)**2\n\ndef diffuser_pipe_reducer(Di1: float, Di2: float, l: float, fd1: float, fd2: float | None=None) -> float:\n r\"\"\"Returns loss coefficient for any pipe reducer pipe expansion\n as shown in [1]. This is an approximate formula.\n\n .. math::\n K_f = f_1\\frac{0.20l}{d_1} + \\frac{f_1(1-\\beta)}{8\\sin(\\alpha/2)}\n + f_2\\frac{0.20l}{d_2}\\beta^4\n\n .. math::\n \\alpha = 2\\tan^{-1}\\left(\\frac{d_1-d_2}{1.20l}\\right)\n\n Parameters\n ----------\n Di1 : float\n Inside diameter of original pipe (smaller), [m]\n Di2 : float\n Inside diameter of following pipe (larger), [m]\n l : float\n Length of the pipe reducer along the pipe axis, [m]\n fd1 : float\n Darcy friction factor at inlet diameter [-]\n fd2 : float\n Darcy friction factor at outlet diameter, optional [-]\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n Industry lack of standardization prevents better formulas from being\n developed. Add 15% if the reducer is eccentric.\n Friction factor at outlet will be assumed the same as at inlet if not specified.\n\n Doubt about the validity of this equation is raised.\n\n Examples\n --------\n >>> diffuser_pipe_reducer(Di1=.5, Di2=.75, l=1.5, fd1=0.07)\n 0.06873244301714816\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n \"\"\"\n if fd2 is None:\n fd2 = fd1\n beta = Di1/Di2\n angle = -2*atan((Di1-Di2)/1.20/l)\n K = fd1*0.20*l/Di1 + fd1*(1-beta)/8./sin(angle/2) + fd2*0.20*l/Di2*beta**4\n return K\n\nDarby = {}\n\ndef Darby3K(NPS: float | None=None, Re: float | None=None, name: str | None=None, K1: float | None=None, Ki: float | None=None, Kd: float | None=None, Di: float | None=None) -> float:\n r\"\"\"Returns loss coefficient for any various fittings, depending\n on the name input. Alternatively, the Darby constants K1, Ki and Kd\n may be provided and used instead. Source of data is [1]_.\n Reviews of this model are favorable.\n\n .. math::\n K_f = \\frac{K_1}{Re} + K_i\\left(1 + \\frac{K_d}{D_{\\text{NPS}}^{0.3}}\n \\right)\n\n Note this model uses nominal pipe diameter in inches.\n\n Parameters\n ----------\n NPS : float\n Nominal diameter of the pipe, [in]\n Re : float\n Reynolds number, [-]\n name : str\n String from Darby dict representing a fitting\n K1 : float\n K1 parameter of Darby model, optional [-]\n Ki : float\n Ki parameter of Darby model, optional [-]\n Kd : float\n Kd parameter of Darby model, optional [in]\n Di : float\n If specified, the NPS will be found by interpolating linearly (with\n extrapolation) along the schedule 40 diameters and NPSs;\n this will supersede NPS if it is specified, [m]\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n Also described in Albright's Handbook and Ludwig's Applied Process Design.\n Relatively uncommon to see it used.\n\n The possibility of combining these methods with those above are attractive.\n\n Examples\n --------\n >>> Darby3K(NPS=2., Re=10000., name='Valve, Angle valve, 45°, full line size, β = 1')\n 1.1572523963562356\n >>> Darby3K(Di=.05248, Re=10000., name='Valve, Angle valve, 45°, full line size, β = 1')\n 1.1572523963562356\n >>> Darby3K(NPS=12., Re=10000., K1=950, Ki=0.25, Kd=4)\n 0.819510280626355\n\n References\n ----------\n .. [1] Silverberg, Peter, and Ron Darby. \"Correlate Pressure Drops through\n Fittings: Three Constants Accurately Calculate Flow through Elbows,\n Valves and Tees.\" Chemical Engineering 106, no. 7 (July 1999): 101.\n .. [2] Silverberg, Peter. \"Correlate Pressure Drops Through Fittings.\"\n Chemical Engineering 108, no. 4 (April 2001): 127,129-130.\n \"\"\"\n if Di is not None:\n NPS = interp(Di*1000.0, S40i, NPS40, extrapolate=True)\n if name is not None:\n K1 = None\n if name in Darby: # NUMBA: DELETE\n K1, Ki, Kd = Darby[name] # NUMBA: DELETE\n if K1 is None:\n try:\n K1, Ki, Kd = Darby_values[Darby_keys.index(name)]\n except:\n raise ValueError(\"Name of fitting is not in database\")\n elif K1 is not None and Ki is not None and Kd is not None:\n pass\n else:\n raise ValueError(\"Name of fitting or constants are required\")\n if NPS is None or Re is None or K1 is None or Ki is None or Kd is None:\n raise ValueError(\"NPS, Re, and K constants must be set\")\n return K1/Re + Ki*(1. + Kd*NPS**-0.3)\n\nHooper = {}\n\ndef Hooper2K(Di: float, Re: float, name: str | None=None, K1: float | None=None, Kinfty: float | None=None) -> float:\n r\"\"\"Returns loss coefficient for any various fittings, depending\n on the name input. Alternatively, the Hooper constants K1, Kinfty\n may be provided and used instead. Source of data is [1]_.\n Reviews of this model are less favorable than the Darby method\n but superior to the constant-K method.\n\n .. math::\n K = \\frac{K_1}{Re} + K_\\infty\\left(1 + \\frac{1\\text{ inch}}{D_{in}}\\right)\n\n **Note this model uses actual inside pipe diameter in inches.**\n\n Parameters\n ----------\n Di : float\n Actual inside diameter of the pipe, [in]\n Re : float\n Reynolds number, [-]\n name : str, optional\n String from Hooper dict representing a fitting\n K1 : float, optional\n K1 parameter of Hooper model, optional [-]\n Kinfty : float, optional\n Kinfty parameter of Hooper model, optional [-]\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n Also described in Ludwig's Applied Process Design.\n Relatively uncommon to see it used.\n No actual example found.\n\n Examples\n --------\n >>> Hooper2K(Di=2., Re=10000., name='Valve, Globe, Standard')\n 6.15\n >>> Hooper2K(Di=2., Re=10000., K1=900, Kinfty=4)\n 6.09\n\n References\n ----------\n .. [1] Hooper, W. B., \"The 2-K Method Predicts Head Losses in Pipe\n Fittings,\" Chem. Eng., p. 97, Aug. 24 (1981).\n .. [2] Hooper, William B. \"Calculate Head Loss Caused by Change in Pipe\n Size.\" Chemical Engineering 95, no. 16 (November 7, 1988): 89.\n .. [3] Kayode Coker. Ludwig's Applied Process Design for Chemical and\n Petrochemical Plants. 4E. Amsterdam ; Boston: Gulf Professional\n Publishing, 2007.\n \"\"\"\n if name is not None:\n K1 = None\n if name in Hooper: # NUMBA: DELETE\n K1, Kinfty = Hooper[name] # NUMBA: DELETE\n if K1 is None:\n try:\n K1, Kinfty = Hooper_values[Hooper_keys.index(name)]\n except:\n raise ValueError(\"Name of fitting is not in database\")\n elif K1 is not None and Kinfty is not None:\n pass\n else:\n raise ValueError(\"Name of fitting or constants are required\")\n if K1 is None or Kinfty is None:\n raise ValueError(\"K1 and Kinfty must be set\")\n return K1/Re + Kinfty*(1. + 1./Di)\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 17500}, "tests/test_fittings.py::208": {"resolved_imports": ["fluids/fittings.py", "fluids/constants/__init__.py", "fluids/core.py", "fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "entrance_rounded", "pytest"], "enclosing_function": "test_entrance_rounded", "extracted_code": "# Source: fluids/fittings.py\ndef entrance_rounded(Di: float, rc: float, method: str=\"Rennels\") -> float:\n r\"\"\"Returns loss coefficient for a rounded entrance to a pipe\n flush with the wall of a reservoir. This calculation has six methods\n available.\n\n The most conservative formulation is that of Rennels; with the Swamee\n correlation being 0.02-0.07 lower. They were published in 2012 and 2008\n respectively, and for this reason could be regarded as more reliable.\n\n The Idel'chik correlation appears based on the Hamilton data; and the\n Miller correlation as well, except a little more conservative. The Crane\n model trends similarly but only has a few points. The Harris data set is\n the lowest.\n\n The Rennels [1]_ formulas are:\n\n .. math::\n K = 0.0696\\left(1 - 0.569\\frac{r}{d}\\right)\\lambda^2 + (\\lambda-1)^2\n\n .. math::\n \\lambda = 1 + 0.622\\left(1 - 0.30\\sqrt{\\frac{r}{d}}\n - 0.70\\frac{r}{d}\\right)^4\n\n The Swamee [5]_ formula is:\n\n .. math::\n K = 0.5\\left[1 + 36\\left(\\frac{r}{D}\\right)^{1.2}\\right]^{-1}\n\n .. figure:: fittings/flush_mounted_rounded_entrance.png\n :scale: 30 %\n :alt: rounded entrance mounted straight and flush; after [1]_\n\n Parameters\n ----------\n Di : float\n Inside diameter of pipe, [m]\n rc : float\n Radius of curvature of the entrance, [m]\n method : str, optional\n One of 'Rennels', 'Crane', 'Miller', 'Idelchik', 'Harris', or 'Swamee'.\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n For generously rounded entrance (rc/Di >= 1), the loss coefficient\n converges to 0.03 in the Rennels method.\n\n The Rennels formulation was derived primarily from data and theoretical\n analysis from different flow scenarios than a rounded pipe entrance; the\n only available data in [2]_ is quite old and [1]_ casts doubt on it.\n\n The Hamilton data set is available in [1]_ and [6]_.\n\n .. plot:: plots/entrance_rounded_plot.py\n\n\n Examples\n --------\n Point from Diagram 9.2 in [1]_, which was used to confirm the Rennels\n model implementation:\n\n >>> entrance_rounded(Di=0.1, rc=0.0235)\n 0.09839534618360923\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n .. [2] Hamilton, James Baker. Suppression of Pipe Intake Losses by Various\n Degrees of Rounding. Seattle: Published by the University of Washington,\n 1929. https://search.library.wisc.edu/catalog/999823652202121.\n .. [3] Miller, Donald S. Internal Flow Systems: Design and Performance\n Prediction. Gulf Publishing Company, 1990.\n .. [4] Harris, Charles William. Elimination of Hydraulic Eddy Current Loss\n at Intake, Agreement of Theory and Experiment. University of Washington,\n 1930.\n .. [5] Swamee, Prabhata K., and Ashok K. Sharma. Design of Water Supply\n Pipe Networks. John Wiley & Sons, 2008.\n .. [6] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,\n 2009.\n .. [7] Blevins, Robert D. Applied Fluid Dynamics Handbook. New York, N.Y.:\n Van Nostrand Reinhold Co., 1984.\n .. [8] Idel`chik, I. E. Handbook of Hydraulic Resistance: Coefficients of\n Local Resistance and of Friction (Spravochnik Po Gidravlicheskim\n Soprotivleniyam, Koeffitsienty Mestnykh Soprotivlenii i Soprotivleniya\n Treniya). National technical information Service, 1966.\n \"\"\"\n if method is None:\n method = \"Rennels\"\n ratio = rc/Di\n if method == \"Rennels\":\n if ratio > 1.0:\n return 0.03\n\n lbd = (1.0 - 0.30*sqrt(ratio) - 0.70*ratio)\n lbd *= lbd\n lbd = 1.0 + 0.622*lbd*lbd\n return 0.0696*(1.0 - 0.569*ratio)*lbd*lbd + (lbd - 1.0)*(lbd - 1.0)\n elif method == \"Swamee\":\n return 0.5/(1.0 + 36.0*(ratio)**1.2)\n elif method == \"Crane\":\n if ratio < 0:\n return 0.5\n elif ratio > 0.15:\n return 0.04\n else:\n return interp(ratio, entrance_rounded_ratios_Crane,\n entrance_rounded_Ks_Crane)\n elif method == \"Miller\":\n if ratio > 0.3:\n ratio = 0.3\n return horner(entrance_rounded_Miller_coeffs, (20.0/3.0)*(ratio - 0.15))\n elif method == \"Harris\":\n if ratio > .16:\n return 0.0\n return float(splev(ratio, entrance_rounded_Harris_tck))\n elif method == \"Idelchik\":\n if ratio > .2:\n return entrance_rounded_Ks_Idelchik[-1]\n return float(splev(ratio, entrance_rounded_Idelchik_tck))\n else:\n raise ValueError(entrance_rounded_methods_error)\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 5361}, "tests/test_fittings.py::215": {"resolved_imports": ["fluids/fittings.py", "fluids/constants/__init__.py", "fluids/core.py", "fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "entrance_rounded", "pytest"], "enclosing_function": "test_entrance_rounded", "extracted_code": "# Source: fluids/fittings.py\ndef entrance_rounded(Di: float, rc: float, method: str=\"Rennels\") -> float:\n r\"\"\"Returns loss coefficient for a rounded entrance to a pipe\n flush with the wall of a reservoir. This calculation has six methods\n available.\n\n The most conservative formulation is that of Rennels; with the Swamee\n correlation being 0.02-0.07 lower. They were published in 2012 and 2008\n respectively, and for this reason could be regarded as more reliable.\n\n The Idel'chik correlation appears based on the Hamilton data; and the\n Miller correlation as well, except a little more conservative. The Crane\n model trends similarly but only has a few points. The Harris data set is\n the lowest.\n\n The Rennels [1]_ formulas are:\n\n .. math::\n K = 0.0696\\left(1 - 0.569\\frac{r}{d}\\right)\\lambda^2 + (\\lambda-1)^2\n\n .. math::\n \\lambda = 1 + 0.622\\left(1 - 0.30\\sqrt{\\frac{r}{d}}\n - 0.70\\frac{r}{d}\\right)^4\n\n The Swamee [5]_ formula is:\n\n .. math::\n K = 0.5\\left[1 + 36\\left(\\frac{r}{D}\\right)^{1.2}\\right]^{-1}\n\n .. figure:: fittings/flush_mounted_rounded_entrance.png\n :scale: 30 %\n :alt: rounded entrance mounted straight and flush; after [1]_\n\n Parameters\n ----------\n Di : float\n Inside diameter of pipe, [m]\n rc : float\n Radius of curvature of the entrance, [m]\n method : str, optional\n One of 'Rennels', 'Crane', 'Miller', 'Idelchik', 'Harris', or 'Swamee'.\n\n Returns\n -------\n K : float\n Loss coefficient [-]\n\n Notes\n -----\n For generously rounded entrance (rc/Di >= 1), the loss coefficient\n converges to 0.03 in the Rennels method.\n\n The Rennels formulation was derived primarily from data and theoretical\n analysis from different flow scenarios than a rounded pipe entrance; the\n only available data in [2]_ is quite old and [1]_ casts doubt on it.\n\n The Hamilton data set is available in [1]_ and [6]_.\n\n .. plot:: plots/entrance_rounded_plot.py\n\n\n Examples\n --------\n Point from Diagram 9.2 in [1]_, which was used to confirm the Rennels\n model implementation:\n\n >>> entrance_rounded(Di=0.1, rc=0.0235)\n 0.09839534618360923\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n .. [2] Hamilton, James Baker. Suppression of Pipe Intake Losses by Various\n Degrees of Rounding. Seattle: Published by the University of Washington,\n 1929. https://search.library.wisc.edu/catalog/999823652202121.\n .. [3] Miller, Donald S. Internal Flow Systems: Design and Performance\n Prediction. Gulf Publishing Company, 1990.\n .. [4] Harris, Charles William. Elimination of Hydraulic Eddy Current Loss\n at Intake, Agreement of Theory and Experiment. University of Washington,\n 1930.\n .. [5] Swamee, Prabhata K., and Ashok K. Sharma. Design of Water Supply\n Pipe Networks. John Wiley & Sons, 2008.\n .. [6] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,\n 2009.\n .. [7] Blevins, Robert D. Applied Fluid Dynamics Handbook. New York, N.Y.:\n Van Nostrand Reinhold Co., 1984.\n .. [8] Idel`chik, I. E. Handbook of Hydraulic Resistance: Coefficients of\n Local Resistance and of Friction (Spravochnik Po Gidravlicheskim\n Soprotivleniyam, Koeffitsienty Mestnykh Soprotivlenii i Soprotivleniya\n Treniya). National technical information Service, 1966.\n \"\"\"\n if method is None:\n method = \"Rennels\"\n ratio = rc/Di\n if method == \"Rennels\":\n if ratio > 1.0:\n return 0.03\n\n lbd = (1.0 - 0.30*sqrt(ratio) - 0.70*ratio)\n lbd *= lbd\n lbd = 1.0 + 0.622*lbd*lbd\n return 0.0696*(1.0 - 0.569*ratio)*lbd*lbd + (lbd - 1.0)*(lbd - 1.0)\n elif method == \"Swamee\":\n return 0.5/(1.0 + 36.0*(ratio)**1.2)\n elif method == \"Crane\":\n if ratio < 0:\n return 0.5\n elif ratio > 0.15:\n return 0.04\n else:\n return interp(ratio, entrance_rounded_ratios_Crane,\n entrance_rounded_Ks_Crane)\n elif method == \"Miller\":\n if ratio > 0.3:\n ratio = 0.3\n return horner(entrance_rounded_Miller_coeffs, (20.0/3.0)*(ratio - 0.15))\n elif method == \"Harris\":\n if ratio > .16:\n return 0.0\n return float(splev(ratio, entrance_rounded_Harris_tck))\n elif method == \"Idelchik\":\n if ratio > .2:\n return entrance_rounded_Ks_Idelchik[-1]\n return float(splev(ratio, entrance_rounded_Idelchik_tck))\n else:\n raise ValueError(entrance_rounded_methods_error)\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 5361}, "tests/test_fittings.py::618": {"resolved_imports": ["fluids/fittings.py", "fluids/constants/__init__.py", "fluids/core.py", "fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "assert_close1d", "contraction_conical", "pytest"], "enclosing_function": "test_contraction_conical", "extracted_code": "# Source: fluids/fittings.py\ndef contraction_conical(Di1: float, Di2: float, fd: float | None=None, l: float | None=None, angle: float | None=None,\n Re: float | None=None, roughness: float=0.0, method: str=\"Rennels\") -> float:\n r\"\"\"Returns the loss coefficient for any conical pipe contraction.\n This calculation has seven methods available. The 'Idelchik' [2]_ and\n 'Blevins' [3]_ methods use interpolation among tables of values; 'Miller'\n uses a 2d spline representation of a graph; and the\n 'Rennels' [1]_, 'Crane' [4]_, 'Swamee' [5]_ and 'Hooper' methods use\n formulas for their calculations.\n\n The 'Rennels' [1]_ formulas are:\n\n .. math::\n K_2 = K_{fr,2} + K_{conv,2}\n\n .. math::\n K_{fr,2} = \\frac{f_d ({1 - \\beta^4})}{8\\sin(\\theta/2)}\n\n .. math::\n K_{conv,2} = 0.0696[1+C_B(\\sin(\\alpha/2)-1)](1-\\beta^5)\\lambda^2 + (\\lambda-1)^2\n\n .. math::\n \\lambda = 1 + 0.622(\\alpha/180)^{0.8}(1-0.215\\beta^2-0.785\\beta^5)\n\n .. math::\n \\beta = d_2/d_1\n\n The 'Swamee' [5]_ formula is:\n\n .. math::\n K = 0.315 \\theta^{1/3}\n\n The Hooper [7]_ formulas are:\n\n If :math:`{Re}_1 \\le 2500`:\n\n .. math::\n K_{1,sharp} = \\left[1.2 + \\frac{160}{\\text{Re}_1}\\right]\n \\left[ \\left(\\frac{D_1} {D_2} \\right)^4 -1 \\right]\n\n If :math:`{Re}_1 > 2500`:\n\n .. math::\n K_{1,sharp} = \\left[0.6 + 0.48f_1\\right] \\left(\\frac{D_1} {D_2} \\right)^2\n \\left[ \\left(\\frac{D_1} {D_2} \\right)^2 -1 \\right]\n\n In both cases, a multiplier is added for the angle:\n\n For angles between 45 and 180 degrees:\n\n .. math::\n K_1 = K_{1,sharp} \\sqrt{\\sin \\frac{\\theta}{2}}\n\n For angles between 0 and 45 degrees:\n\n .. math::\n K_1 = K_{1,sharp} 1.6 \\sin \\frac{\\theta}{2}\n\n Converting the Hooper loss coefficient to a consistent basis:\n\n .. math::\n K_2 = K_1\\frac{D_2^4}{D_1^4}\n\n .. figure:: fittings/contraction_conical.png\n :scale: 30 %\n :alt: contraction conical; after [1]_\n\n Parameters\n ----------\n Di1 : float\n Inside pipe diameter of the larger, upstream, pipe, [m]\n Di2 : float\n Inside pipe diameter of the smaller, downstream, pipe, [m]\n fd : float, optional\n Darcy friction factor; used only in the `Rennels` and `Hooper` method\n and will be calculated from `Re` and `roughness` if not given, [-]\n l : float, optional\n Length of the contraction, optional [m]\n angle : float, optional\n Angle of contraction (180 = sharp, 0 = infinitely long contraction),\n optional [degrees]\n Re : float, optional\n Reynolds number of the pipe (used in `Rennels` and `Hooper` method only\n if no friction factor given), [m]\n roughness : float, optional\n Roughness of bend wall (used in Rennels method if no friction factor\n given), [m]\n method : str, optional\n The method to use for the calculation; one of 'Rennels', 'Idelchik',\n 'Crane', 'Swamee', 'Hooper', 'Miller', or 'Blevins', [-]\n\n Returns\n -------\n K : float\n Loss coefficient in terms of the following pipe [-]\n\n Notes\n -----\n Cheap and has substantial impact on pressure drop.\n\n The 'Idelchik' method includes two tabular interpolations; its friction\n term is limited to angles between 2 and 20 degrees and area ratios 0.05 to\n 0.6, while its main term is limited to length over diameter ratios 0.025 to\n 0.6. This seems to give it high results for angles < 25 degrees.\n\n The 'Blevins' method is based on Idelchik data; it should not be used,\n because its data jumps around and its data is limited to area ratios .1 to\n 0.83, and length over diameter ratios 0 to 0.6. The 'Miller' method jumps\n around as well. Unlike most of Miller's method, there is no correction for\n Reynolds number.\n\n There is quite a bit of variance in the predictions of the methods, as\n demonstrated by the following figure.\n\n .. plot:: plots/contraction_conical_plot.py\n\n Examples\n --------\n >>> contraction_conical(Di1=0.1, Di2=0.04, l=0.04, Re=1E6)\n 0.15639885880609544\n\n References\n ----------\n .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical\n and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.\n .. [2] Idel`chik, I. E. Handbook of Hydraulic Resistance: Coefficients of\n Local Resistance and of Friction (Spravochnik Po Gidravlicheskim\n Soprotivleniyam, Koeffitsienty Mestnykh Soprotivlenii i Soprotivleniya\n Treniya). National technical information Service, 1966.\n .. [3] Blevins, Robert D. Applied Fluid Dynamics Handbook. New York, N.Y.:\n Van Nostrand Reinhold Co., 1984.\n .. [4] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,\n 2009.\n .. [5] Swamee, Prabhata K., and Ashok K. Sharma. Design of Water Supply\n Pipe Networks. John Wiley & Sons, 2008.\n .. [6] Miller, Donald S. Internal Flow Systems: Design and Performance\n Prediction. Gulf Publishing Company, 1990.\n .. [7] Hooper, William B. \"Calculate Head Loss Caused by Change in Pipe\n Size.\" Chemical Engineering 95, no. 16 (November 7, 1988): 89.\n \"\"\"\n beta = Di2/Di1\n if angle is not None:\n angle_rad = angle*deg2rad\n l = (Di1 - Di2)/(2.0*tan(0.5*angle_rad))\n elif l is not None:\n if l != 0.0:\n angle_rad = 2.0*atan((Di1-Di2)/(2.0*l))\n else:\n angle_rad = pi\n else:\n raise ValueError(\"Either l or angle is required\")\n if method == \"Rennels\":\n if fd is None:\n if Re is None:\n raise ValueError(\"The `Rennels` method requires either a \"\n \"specified friction factor or `Re`\")\n fd = Clamond(Re=Re, eD=roughness/Di2, fast=False)\n\n beta2 = beta*beta\n beta4 = beta2*beta2\n beta5 = beta4*beta\n lbd = 1.0 + 0.622*(angle_rad/pi)**0.8*(1.0 - 0.215*beta2 - 0.785*beta5)\n sin_half_angle = sin(0.5*angle_rad)\n K_fr2 = fd*(1.0 - beta4)/(8.0*sin_half_angle)\n K_conv2 = 0.0696*sin_half_angle*(1.0 - beta5)*lbd*lbd + (lbd - 1.0)**2\n return K_fr2 + K_conv2\n elif method == \"Crane\":\n return contraction_conical_Crane(Di1=Di1, Di2=Di2, l=l, angle=angle_rad*rad2deg)\n elif method == \"Swamee\":\n return 0.315*angle_rad**(1.0/3.0)\n elif method == \"Idelchik\":\n # Diagram 3-6; already digitized for beveled entrance\n K0 = float(bisplev(angle_rad*rad2deg, l/Di2, entrance_beveled_Idelchik_tck))\n\n # Angles 0 to 20, ratios 0.05 to 0.06\n if angle_rad > 20.0*deg2rad:\n angle_fric = 20.0\n elif angle_rad < 2.0*deg2rad:\n angle_fric = 2.0\n else:\n angle_fric = angle_rad*rad2deg\n\n A_ratio = A_ratio_fric = Di2*Di2/(Di1*Di1)\n if A_ratio_fric < 0.05:\n A_ratio_fric = 0.05\n elif A_ratio_fric > 0.6:\n A_ratio_fric = 0.6\n\n K_fr = float(contraction_conical_friction_Idelchik_obj(angle_fric, A_ratio_fric))\n return K0*(1.0 - A_ratio) + K_fr\n elif method == \"Blevins\":\n A_ratio = Di1*Di1/(Di2*Di2)\n if A_ratio < 1.2:\n A_ratio = 1.2\n elif A_ratio > 10.0:\n A_ratio = 10.0\n\n l_ratio = l/Di2\n if l_ratio > 0.6:\n l_ratio = 0.6\n return float(contraction_conical_Blevins_obj(l_ratio, A_ratio))\n elif method == \"Miller\":\n A_ratio = Di1*Di1/(Di2*Di2)\n if A_ratio > 4.0:\n A_ratio = 4.0\n elif A_ratio < 1.1:\n A_ratio = 1.1\n l_ratio = l/(Di2*0.5)\n if l_ratio < 0.1:\n l_ratio = 0.1\n elif l_ratio > 10.0:\n l_ratio = 10.0\n # Turning on or off the limits - little difference in plot\n return contraction_conical_Miller_obj(l_ratio, A_ratio)\n elif method == \"Hooper\":\n if Re is None:\n raise ValueError(\"Hooper method requires `Re`\")\n D1_D2 = Di1/Di2\n D1_D2_2 = D1_D2*D1_D2\n if Re <= 2500.0:\n K = (1.2 + 160.0/Re)*(D1_D2_2*D1_D2_2 - 1.0)\n else:\n if fd is None:\n fd = Clamond(Re=Re, eD=roughness/Di1)\n K = (0.6 + 0.48*fd)*D1_D2_2*(D1_D2_2 - 1.0)\n\n if angle_rad > 0.25*pi:\n K *= sqrt(sin(0.5*angle_rad))\n else:\n K *= 1.6*sin(0.5*angle_rad)\n K = change_K_basis(K, Di1, Di2)\n return K\n else:\n raise ValueError(contraction_conical_method_unknown)\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 9399}, "tests/test_fittings.py::756": {"resolved_imports": ["fluids/fittings.py", "fluids/constants/__init__.py", "fluids/core.py", "fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["K_angle_valve_Crane", "assert_close", "pytest"], "enclosing_function": "test_K_angle_valve_Crane", "extracted_code": "# Source: fluids/fittings.py\ndef K_angle_valve_Crane(D1: float, D2: float, fd: float | None=None, style: int=0) -> float:\n r\"\"\"Returns the loss coefficient for all types of angle valve, (reduced\n seat or throttled) as shown in [1]_.\n\n If β = 1:\n\n .. math::\n K = K_1 = K_2 = N\\cdot f_d\n\n Otherwise:\n\n .. math::\n K_2 = \\frac{K + \\left[0.5(1-\\beta^2) + (1-\\beta^2)^2\\right]}{\\beta^4}\n\n For style 0 and 2, N = 55; for style 1, N=150.\n\n Parameters\n ----------\n D1 : float\n Diameter of the valve seat bore (must be smaller or equal to `D2`), [m]\n D2 : float\n Diameter of the pipe attached to the valve, [m]\n fd : float, optional\n Darcy friction factor calculated for the actual pipe flow in clean\n steel (roughness = 0.0018 inch) in the fully developed turbulent\n region; do not specify this to use the original Crane friction factor!,\n [-]\n style : int, optional\n One of 0, 1, or 2; refers to three different types of angle valves\n as shown in [1]_ [-]\n\n Returns\n -------\n K : float\n Loss coefficient with respect to the pipe inside diameter [-]\n\n Notes\n -----\n This method is not valid in the laminar regime and the pressure drop will\n be underestimated in those conditions.\n\n Examples\n --------\n >>> K_angle_valve_Crane(.01, .02)\n 26.597361811128465\n\n References\n ----------\n .. [1] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,\n 2009.\n \"\"\"\n beta = D1/D2\n if style not in (0, 1, 2):\n raise ValueError(\"Valve style should be 0, 1, or 2\")\n if fd is None:\n fd = ft_Crane(D2)\n\n if style in (0, 2):\n K1 = 55.0*fd\n else:\n K1 = 150.0*fd\n if beta == 1:\n return K1 # upstream and down\n else:\n return (K1 + beta*(0.5*(1-beta)**2 + (1-beta**2)**2))/beta**4\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 2504}, "tests/test_fittings.py::767": {"resolved_imports": ["fluids/fittings.py", "fluids/constants/__init__.py", "fluids/core.py", "fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["K_swing_check_valve_Crane", "assert_close"], "enclosing_function": "test_K_swing_check_valve_Crane", "extracted_code": "# Source: fluids/fittings.py\ndef K_swing_check_valve_Crane(D: float | None=None, fd: float | None=None, angled: bool=True) -> float:\n r\"\"\"Returns the loss coefficient for a swing check valve as shown in [1]_.\n\n .. math::\n K_2 = N\\cdot f_d\n\n For angled swing check valves N = 100; for straight valves, N = 50.\n\n Parameters\n ----------\n D : float, optional\n Diameter of the pipe attached to the valve, [m]\n fd : float, optional\n Darcy friction factor calculated for the actual pipe flow in clean\n steel (roughness = 0.0018 inch) in the fully developed turbulent\n region; do not specify this to use the original Crane friction factor!,\n [-]\n angled : bool, optional\n If True, returns a value 2x the unangled value; the style of the valve\n [-]\n\n Returns\n -------\n K : float\n Loss coefficient with respect to the pipe inside diameter [-]\n\n Notes\n -----\n This method is not valid in the laminar regime and the pressure drop will\n be underestimated in those conditions.\n\n Examples\n --------\n >>> K_swing_check_valve_Crane(D=.02)\n 2.3974274785373257\n\n References\n ----------\n .. [1] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,\n 2009.\n \"\"\"\n if fd is None:\n if D is None:\n raise ValueError(\"D must be specified if fd is not provided\")\n fd = ft_Crane(D)\n if angled:\n return 100.*fd\n return 50.*fd\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 2098}, "tests/test_fittings.py::769": {"resolved_imports": ["fluids/fittings.py", "fluids/constants/__init__.py", "fluids/core.py", "fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["K_swing_check_valve_Crane", "assert_close"], "enclosing_function": "test_K_swing_check_valve_Crane", "extracted_code": "# Source: fluids/fittings.py\ndef K_swing_check_valve_Crane(D: float | None=None, fd: float | None=None, angled: bool=True) -> float:\n r\"\"\"Returns the loss coefficient for a swing check valve as shown in [1]_.\n\n .. math::\n K_2 = N\\cdot f_d\n\n For angled swing check valves N = 100; for straight valves, N = 50.\n\n Parameters\n ----------\n D : float, optional\n Diameter of the pipe attached to the valve, [m]\n fd : float, optional\n Darcy friction factor calculated for the actual pipe flow in clean\n steel (roughness = 0.0018 inch) in the fully developed turbulent\n region; do not specify this to use the original Crane friction factor!,\n [-]\n angled : bool, optional\n If True, returns a value 2x the unangled value; the style of the valve\n [-]\n\n Returns\n -------\n K : float\n Loss coefficient with respect to the pipe inside diameter [-]\n\n Notes\n -----\n This method is not valid in the laminar regime and the pressure drop will\n be underestimated in those conditions.\n\n Examples\n --------\n >>> K_swing_check_valve_Crane(D=.02)\n 2.3974274785373257\n\n References\n ----------\n .. [1] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,\n 2009.\n \"\"\"\n if fd is None:\n if D is None:\n raise ValueError(\"D must be specified if fd is not provided\")\n fd = ft_Crane(D)\n if angled:\n return 100.*fd\n return 50.*fd\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 2098}, "tests/test_fittings.py::783": {"resolved_imports": ["fluids/fittings.py", "fluids/constants/__init__.py", "fluids/core.py", "fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["K_lift_check_valve_Crane", "assert_close"], "enclosing_function": "test_K_lift_check_valve_Crane", "extracted_code": "# Source: fluids/fittings.py\ndef K_lift_check_valve_Crane(D1: float, D2: float, fd: float | None=None, angled: bool=True) -> float:\n r\"\"\"Returns the loss coefficient for a lift check valve as shown in [1]_.\n\n If β = 1:\n\n .. math::\n K = K_1 = K_2 = N\\cdot f_d\n\n Otherwise:\n\n .. math::\n K_2 = \\frac{K + \\left[0.5(1-\\beta^2) + (1-\\beta^2)^2\\right]}{\\beta^4}\n\n For angled lift check valves N = 55; for straight valves, N = 600.\n\n Parameters\n ----------\n D1 : float\n Diameter of the valve seat bore (must be smaller or equal to `D2`), [m]\n D2 : float\n Diameter of the pipe attached to the valve, [m]\n fd : float, optional\n Darcy friction factor calculated for the actual pipe flow in clean\n steel (roughness = 0.0018 inch) in the fully developed turbulent\n region; do not specify this to use the original Crane friction factor!,\n [-]\n angled : bool, optional\n If True, returns a value 2x the unangled value; the style of the valve\n [-]\n\n Returns\n -------\n K : float\n Loss coefficient with respect to the pipe inside diameter [-]\n\n Notes\n -----\n This method is not valid in the laminar regime and the pressure drop will\n be underestimated in those conditions.\n\n Examples\n --------\n >>> K_lift_check_valve_Crane(.01, .02)\n 28.597361811128465\n\n References\n ----------\n .. [1] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,\n 2009.\n \"\"\"\n beta = D1/D2\n if fd is None:\n fd = ft_Crane(D2)\n if angled:\n K1 = 55*fd\n if beta == 1:\n return K1\n else:\n return (K1 + beta*(0.5*(1 - beta**2) + (1 - beta**2)**2))/beta**4\n else:\n K1 = 600.*fd\n if beta == 1:\n return K1\n else:\n return (K1 + beta*(0.5*(1 - beta**2) + (1 - beta**2)**2))/beta**4\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 2520}, "tests/test_fittings.py::797": {"resolved_imports": ["fluids/fittings.py", "fluids/constants/__init__.py", "fluids/core.py", "fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["K_tilting_disk_check_valve_Crane", "assert_close"], "enclosing_function": "test_K_tilting_disk_check_valve_Crane", "extracted_code": "# Source: fluids/fittings.py\ndef K_tilting_disk_check_valve_Crane(D: float, angle: float, fd: float | None=None) -> float:\n r\"\"\"Returns the loss coefficient for a tilting disk check valve as shown in\n [1]_. Results are specified in [1]_ to be for the disk's resting position\n to be at 5 or 25 degrees to the flow direction. The model is implemented\n here so as to switch to the higher loss 15 degree coefficients at 10\n degrees, and use the lesser coefficients for any angle under 10 degrees.\n\n .. math::\n K = N\\cdot f_d\n\n N is obtained from the following table:\n\n +--------+-------------+-------------+\n | | angle = 5 ° | angle = 15° |\n +========+=============+=============+\n | 2-8\" | 40 | 120 |\n +--------+-------------+-------------+\n | 10-14\" | 30 | 90 |\n +--------+-------------+-------------+\n | 16-48\" | 20 | 60 |\n +--------+-------------+-------------+\n\n The actual change of coefficients happen at <= 9\" and <= 15\".\n\n Parameters\n ----------\n D : float\n Diameter of the pipe section the valve in mounted in; the\n same as the line size [m]\n angle : float\n Angle of the tilting disk to the flow direction; nominally 5 or 15\n degrees [degrees]\n fd : float, optional\n Darcy friction factor calculated for the actual pipe flow in clean\n steel (roughness = 0.0018 inch) in the fully developed turbulent\n region; do not specify this to use the original Crane friction factor!,\n [-]\n\n Returns\n -------\n K : float\n Loss coefficient with respect to the pipe inside diameter [-]\n\n Notes\n -----\n This method is not valid in the laminar regime and the pressure drop will\n be underestimated in those conditions.\n\n Examples\n --------\n >>> K_tilting_disk_check_valve_Crane(.01, 5)\n 1.1626516551826345\n\n References\n ----------\n .. [1] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,\n 2009.\n \"\"\"\n if fd is None:\n fd = ft_Crane(D)\n if angle < 10:\n # 5 degree case\n if D <= 0.2286:\n # 2-8 inches, split at 9 inch\n return 40*fd\n elif D <= 0.381:\n # 10-14 inches, split at 15 inch\n return 30*fd\n else:\n # 16-18 inches\n return 20*fd\n else:\n # 15 degree case\n if D < 0.2286:\n # 2-8 inches\n return 120*fd\n elif D < 0.381:\n # 10-14 inches\n return 90*fd\n else:\n # 16-18 inches\n return 60*fd\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 3256}, "tests/test_fittings_fits.py::298": {"resolved_imports": ["fluids/__init__.py", "fluids/core.py", "fluids/optional/pychebfun.py", "fluids/fittings.py"], "used_names": ["UnivariateSpline", "assert_allclose", "bend_rounded_Crane_coeffs", "bend_rounded_Crane_fds", "bend_rounded_Crane_ratios", "chebfun", "chebfun_to_poly"], "enclosing_function": "test_bend_rounded_Crane_coefficients", "extracted_code": "# Source: fluids/optional/pychebfun.py\ndef chebfun_to_poly(coeffs_or_fun, domain=None, text=False):\n if isinstance(coeffs_or_fun, Chebfun):\n coeffs = coeffs_or_fun.coefficients()\n domain = coeffs_or_fun._domain\n elif hasattr(coeffs_or_fun, \"__class__\") and coeffs_or_fun.__class__.__name__ == \"ChebyshevExpansion\":\n coeffs = coeffs_or_fun.coef()\n domain = coeffs_or_fun.xmin(), coeffs_or_fun.xmax()\n else:\n coeffs = coeffs_or_fun\n\n low, high = domain\n # Reverse the coefficients, and use cheb2poly to make it in the polynomial domain\n poly_coeffs = cheb2poly(coeffs)[::-1].tolist()\n if not text:\n return poly_coeffs\n s = f\"coeffs = {poly_coeffs}\\n\"\n delta = high - low\n delta_sum = high + low\n # Generate the expression\n s += f\"horner(coeffs, {2.0/delta:.18g}*(x - {0.5*delta_sum:.18g}))\"\n # return the string\n return s\n\ndef chebfun(f=None, domain=[-1,1], N=None, chebcoeff=None,):\n \"\"\"Create a Chebyshev polynomial approximation of the function $f$ on the\n interval :math:`[-1, 1]`.\n\n :param callable f: Python, Numpy, or Sage function\n :param int N: (default = None) specify number of interpolating points\n :param np.array chebcoeff: (default = np.array(0)) specify the coefficients\n \"\"\"\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n\n\n # Chebyshev coefficients\n if chebcoeff is not None:\n return Chebfun.from_coeff(chebcoeff, domain)\n\n # another instance\n if isinstance(f, Polyfun):\n return Chebfun.from_fun(f)\n\n # callable\n if hasattr(f, \"__call__\"):\n return Chebfun.from_function(f, domain, N)\n\n # from here on, assume that f is None, or iterable\n if np.isscalar(f):\n f = [f]\n\n try:\n iter(f) # interpolation values provided\n except TypeError:\n pass\n else:\n return Chebfun(f, domain)\n\n raise TypeError(f\"Impossible to initialise the object from an object of type {type(f)}\")\n\n\n# Source: fluids/fittings.py\nbend_rounded_Crane_ratios = [1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 10.0, 12.0,\n 14.0, 16.0, 20.0]\n\nbend_rounded_Crane_fds = [20.0, 14.0, 12.0, 12.0, 14.0, 17.0, 24.0, 30.0, 34.0,\n 38.0, 42.0, 50.0]\n\nbend_rounded_Crane_coeffs = [111.75011378177442, -331.89911345404107, -27.841951521656483,\n 1066.8916917931147, -857.8702190626232, -1151.4621655498092,\n 1775.2416673594603, 216.37911821941805, -1458.1661519377653,\n 447.169127650163, 515.361158769082, -322.58377486107577,\n -38.38349416327068, 71.12796602489138, -16.198233745350535,\n 19.377150177339015, 31.107110520349494]", "n_imports_parsed": 11, "n_files_resolved": 4, "n_chars_extracted": 2894}, "tests/test_flow_meter.py::218": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/flow_meter.py", "fluids/numerics/__init__.py"], "used_names": ["C_Miller_1996", "C_Reader_Harris_Gallagher", "MILLER_CONICAL_ORIFICE", "MILLER_ECCENTRIC_ORIFICE", "MILLER_ORIFICE", "MILLER_QUARTER_CIRCLE_ORIFICE", "MILLER_SEGMENTAL_ORIFICE", "ORIFICE_CORNER_TAPS", "ORIFICE_D_AND_D_2_TAPS", "ORIFICE_FLANGE_TAPS", "ORIFICE_PIPE_TAPS", "ORIFICE_VENA_CONTRACTA_TAPS", "TAPS_OPPOSITE", "TAPS_SIDE", "assert_close", "pytest"], "enclosing_function": "test_C_Miller_1996", "extracted_code": "# Source: fluids/flow_meter.py\nORIFICE_CORNER_TAPS = \"corner\"\n\nORIFICE_FLANGE_TAPS = \"flange\"\n\nORIFICE_D_AND_D_2_TAPS = \"D and D/2\"\n\nORIFICE_PIPE_TAPS = \"pipe\"\n\nORIFICE_VENA_CONTRACTA_TAPS = \"vena contracta\"\n\nTAPS_OPPOSITE = \"180 degree\"\n\nTAPS_SIDE = \"90 degree\"\n\nMILLER_ORIFICE = \"Miller orifice\"\n\nMILLER_ECCENTRIC_ORIFICE = \"Miller eccentric orifice\"\n\nMILLER_SEGMENTAL_ORIFICE = \"Miller segmental orifice\"\n\nMILLER_CONICAL_ORIFICE = \"Miller conical orifice\"\n\nMILLER_QUARTER_CIRCLE_ORIFICE = \"Miller quarter circle orifice\"\n\ndef C_Reader_Harris_Gallagher(D: float, Do: float, rho: float, mu: float, m: float, taps: str=\"corner\") -> float:\n r\"\"\"Calculates the coefficient of discharge of the orifice based on the\n geometry of the plate, measured pressures of the orifice, mass flow rate\n through the orifice, and the density and viscosity of the fluid.\n\n .. math::\n C = 0.5961 + 0.0261\\beta^2 - 0.216\\beta^8 + 0.000521\\left(\\frac{\n 10^6\\beta}{Re_D}\\right)^{0.7}\\\\\n + (0.0188 + 0.0063A)\\beta^{3.5} \\left(\\frac{10^6}{Re_D}\\right)^{0.3} \\\\\n +(0.043 + 0.080\\exp(-10L_1) -0.123\\exp(-7L_1))(1-0.11A)\\frac{\\beta^4}\n {1-\\beta^4} \\\\\n - 0.031(M_2' - 0.8M_2'^{1.1})\\beta^{1.3}\n\n .. math::\n M_2' = \\frac{2L_2'}{1-\\beta}\n\n .. math::\n A = \\left(\\frac{19000\\beta}{Re_{D}}\\right)^{0.8}\n\n .. math::\n Re_D = \\frac{\\rho v D}{\\mu}\n\n\n If D < 71.12 mm (2.8 in.) (Note this is a continuous addition; there is no\n discontinuity):\n\n .. math::\n C += 0.11(0.75-\\beta)\\left(2.8-\\frac{D}{0.0254}\\right)\n\n If the orifice has corner taps:\n\n .. math::\n L_1 = L_2' = 0\n\n If the orifice has D and D/2 taps:\n\n .. math::\n L_1 = 1\n\n .. math::\n L_2' = 0.47\n\n If the orifice has Flange taps:\n\n .. math::\n L_1 = L_2' = \\frac{0.0254}{D}\n\n Parameters\n ----------\n D : float\n Upstream internal pipe diameter, [m]\n Do : float\n Diameter of orifice at flow conditions, [m]\n rho : float\n Density of fluid at `P1`, [kg/m^3]\n mu : float\n Viscosity of fluid at `P1`, [Pa*s]\n m : float\n Mass flow rate of fluid through the orifice, [kg/s]\n taps : str\n The orientation of the taps; one of 'corner', 'flange', 'D', or 'D/2',\n [-]\n\n Returns\n -------\n C : float\n Coefficient of discharge of the orifice, [-]\n\n Notes\n -----\n The following limits apply to the orifice plate standard [1]_:\n\n The measured pressure difference for the orifice plate should be under\n 250 kPa.\n\n There are roughness limits as well; the roughness should be under 6\n micrometers, although there are many more conditions to that given in [1]_.\n\n For orifice plates with D and D/2 or corner pressure taps:\n\n * Orifice bore diameter must be larger than 12.5 mm (0.5 inches)\n * Pipe diameter between 50 mm and 1 m (2 to 40 inches)\n * Beta between 0.1 and 0.75 inclusive\n * Reynolds number larger than 5000 (for :math:`0.10 \\le \\beta \\le 0.56`)\n or for :math:`\\beta \\ge 0.56, Re_D \\ge 16000\\beta^2`\n\n For orifice plates with flange pressure taps:\n\n * Orifice bore diameter must be larger than 12.5 mm (0.5 inches)\n * Pipe diameter between 50 mm and 1 m (2 to 40 inches)\n * Beta between 0.1 and 0.75 inclusive\n * Reynolds number larger than 5000 and also larger than\n :math:`170000\\beta^2 D`.\n\n This is also presented in Crane's TP410 (2009) publication, whereas the\n 1999 and 1982 editions showed only a graph for discharge coefficients.\n\n Examples\n --------\n >>> C_Reader_Harris_Gallagher(D=0.07391, Do=0.0222, rho=1.165, mu=1.85E-5,\n ... m=0.12, taps='flange')\n 0.5990326277163659\n\n References\n ----------\n .. [1] American Society of Mechanical Engineers. Mfc-3M-2004 Measurement\n Of Fluid Flow In Pipes Using Orifice, Nozzle, And Venturi. ASME, 2001.\n .. [2] ISO 5167-2:2003 - Measurement of Fluid Flow by Means of Pressure\n Differential Devices Inserted in Circular Cross-Section Conduits Running\n Full -- Part 2: Orifice Plates.\n .. [3] Reader-Harris, M. J., \"The Equation for the Expansibility Factor for\n Orifice Plates,\" Proceedings of FLOMEKO 1998, Lund, Sweden, 1998:\n 209-214.\n .. [4] Reader-Harris, Michael. Orifice Plates and Venturi Tubes. Springer,\n 2015.\n \"\"\"\n A_pipe = 0.25*pi*D*D\n v = m/(A_pipe*rho)\n Re_D = rho*v*D/mu\n Re_D_inv = 1.0/Re_D\n\n beta = Do/D\n if taps == \"corner\":\n L1, L2_prime = 0.0, 0.0\n elif taps == \"flange\":\n L1 = L2_prime = 0.0254/D\n elif taps in (\"D\", \"D/2\", ORIFICE_D_AND_D_2_TAPS):\n L1 = 1.0\n L2_prime = 0.47\n else:\n raise ValueError(\"Unsupported tap location\")\n\n beta2 = beta*beta\n beta4 = beta2*beta2\n beta8 = beta4*beta4\n\n A = 2648.5177066967326*(beta*Re_D_inv)**0.8 # 19000.0^0.8 = 2648.51....\n M2_prime = 2.0*L2_prime/(1.0 - beta)\n\n # These two exps\n expnL1 = exp(-L1)\n expnL2 = expnL1*expnL1\n expnL3 = expnL1*expnL2\n delta_C_upstream = ((0.043 + expnL3*expnL2*expnL2*(0.080*expnL3 - 0.123))\n *(1.0 - 0.11*A)*beta4/(1.0 - beta4))\n\n # The max part is not in the ISO standard\n t1 = log10(3700.*Re_D_inv)\n if t1 < 0.0:\n t1 = 0.0\n delta_C_downstream = (-0.031*(M2_prime - 0.8*M2_prime**1.1)*beta**1.3\n *(1.0 + 8.0*t1))\n\n # C_inf is discharge coefficient with corner taps for infinite Re\n # Cs, slope term, provides increase in discharge coefficient for lower\n # Reynolds numbers.\n x1 = 63.095734448019314*(Re_D_inv)**0.3 # 63.095... = (1e6)**0.3\n x2 = 22.7 - 0.0047*Re_D\n t2 = max(x2, x1)\n # max term is not in the ISO standard\n C_inf_C_s = (0.5961 + 0.0261*beta2 - 0.216*beta8\n + 0.000521*(1E6*beta*Re_D_inv)**0.7\n + (0.0188 + 0.0063*A)*beta2*beta*sqrt(beta)*(\n t2))\n\n C = (C_inf_C_s + delta_C_upstream + delta_C_downstream)\n if D < 0.07112:\n # Limit is 2.8 inches, .1 inches smaller than the internal diameter of\n # a sched. 80 pipe.\n # Suggested to be required not because of any effect of small\n # diameters themselves, but because of edge radius differences.\n # max term is given in [4]_ Reader-Harris, Michael book\n # There is a check for t3 being negative and setting it to zero if so\n # in some sources but that only occurs when t3 is exactly the limit\n # (0.07112) so it is not needed\n t3 = (2.8 - D*inch_inv)\n delta_C_diameter = 0.011*(0.75 - beta)*t3\n C += delta_C_diameter\n\n return C\n\ndef C_Miller_1996(D: float, Do: float, rho: float, mu: float, m: float, subtype: str=\"orifice\",\n taps: str | None=ORIFICE_CORNER_TAPS, tap_position: str | None=TAPS_OPPOSITE) -> float:\n r\"\"\"Calculates the coefficient of discharge of any of the orifice types\n supported by the Miller (1996) [1]_ correlation set. These correlations\n cover a wide range of industrial applications and sizes. Most of them are\n functions of `beta` ratio and Reynolds number. Unlike the ISO standards,\n these correlations do not come with well defined ranges of validity, so\n caution should be applied using these correlations.\n\n The base equation is as follows, and each orifice type and range has\n different values or correlations for :math:`C_{\\infty}`, `b`, and `n`.\n\n .. math::\n C = C_{\\infty} + \\frac{b}{{Re}_D^n}\n\n Parameters\n ----------\n D : float\n Upstream internal pipe diameter, [m]\n Do : float\n Diameter of orifice at flow conditions, [m]\n rho : float\n Density of fluid at `P1`, [kg/m^3]\n mu : float\n Viscosity of fluid at `P1`, [Pa*s]\n m : float\n Mass flow rate of fluid through the orifice, [kg/s]\n subtype : str, optional\n One of 'orifice', 'eccentric orifice', 'segmental orifice',\n 'conical orifice', or 'quarter circle orifice', [-]\n taps : str, optional\n The orientation of the taps; one of 'corner', 'flange',\n 'D and D/2', 'pipe', or 'vena contracta'; not all orifice subtypes\n support all tap types [-]\n tap_position : str, optional\n The rotation of the taps, used **only for the eccentric orifice case**\n where the pressure profiles are not symmetric; '180 degree' for the\n normal case where the taps are opposite the orifice bore, and\n '90 degree' for the case where, normally for operational reasons, the\n taps are near the bore [-]\n\n Returns\n -------\n C : float\n Coefficient of discharge of the orifice, [-]\n\n Notes\n -----\n Many of the correlations transition at a pipe diameter of 100 mm to\n different equations, which will lead to discontinuous behavior.\n\n It should also be noted the author of these correlations developed a\n commercial flow meter rating software package, at [2]_.\n He passed away in 2014, but contributed massively to the field of flow\n measurement.\n\n The numerous equations for the different cases are as follows:\n\n For all **regular (concentric) orifices**, the `b` equation is as follows\n and n = 0.75:\n\n .. math::\n b = 91.706\\beta^{2.5}\n\n Regular (concentric) orifice, corner taps:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.0312\\beta^2.1 - 0.184\\beta^8\n\n Regular (concentric) orifice, flange taps, D > 58.4 mm:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.0312\\beta^{2.1} - 0.184\\beta^8\n + \\frac{2.286\\beta^4}{(D_{mm}(1.0 - \\beta^4))}\n - \\frac{0.856\\beta^3}{D_{mm}}\n\n Regular (concentric) orifice, flange taps, D < 58.4 mm:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.0312\\beta^{2.1} - 0.184\\beta^8\n + \\frac{0.039\\beta^4}{(1.0 - \\beta^4)} - \\frac{0.856\\beta^3}{D_{mm}}\n\n Regular (concentric) orifice, 'D and D/2' taps:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.0312\\beta^{2.1} - 0.184\\beta^8\n + \\frac{0.039\\beta^4}{(1.0 - \\beta^4)} - 0.01584\n\n Regular (concentric) orifice, 'pipe' taps:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.461\\beta^{2.1} + 0.48\\beta^8\n + \\frac{0.039\\beta^4}{(1.0 - \\beta^4)}\n\n For the case of a **conical orifice**, there is no tap dependence\n and one equation (`b` = 0, `n` = 0):\n\n .. math::\n C_{\\infty} = 0.734 \\text{ if } 250\\beta \\le Re \\le 500\\beta \\text{ else } 0.730\n\n For the case of a **quarter circle orifice**, corner and flange taps have\n the same dependence (`b` = 0, `n` = 0):\n\n .. math::\n C_{\\infty} = (0.7746 - 0.1334\\beta^{2.1} + 1.4098\\beta^8\n + \\frac{0.0675\\beta^4}{(1 - \\beta^4)} + 0.3865\\beta^3)\n\n For all **segmental orifice** types, `b` = 0 and `n` = 0\n\n Segmental orifice, 'flange' taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.6284 + 0.1462\\beta^{2.1} - 0.8464\\beta^8\n + \\frac{0.2603\\beta^4}{(1-\\beta^4)} - 0.2886\\beta^3\n\n Segmental orifice, 'flange' taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.6276 + 0.0828\\beta^{2.1} + 0.2739\\beta^8\n - \\frac{0.0934\\beta^4}{(1-\\beta^4)} - 0.1132\\beta^3\n\n Segmental orifice, 'vena contracta' taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.6261 + 0.1851\\beta^{2.1} - 0.2879\\beta^8\n + \\frac{0.1170\\beta^4}{(1-\\beta^4)} - 0.2845\\beta^3\n\n Segmental orifice, 'vena contracta' taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.6276 + 0.0828\\beta^{2.1} + 0.2739\\beta^8\n - \\frac{0.0934\\beta^4}{(1-\\beta^4)} - 0.1132\\beta^3\n\n For all **eccentric orifice** types, `n` = 0.75 and `b` is fit to a\n polynomial of `beta`.\n\n Eccentric orifice, 'flange' taps, 180 degree opposite taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.5917 + 0.3061\\beta^{2.1} + .3406\\beta^8 -\\frac{.1019\\beta^4}{(1-\\beta^4)} - 0.2715\\beta^3\n\n .. math::\n b = 7.3 - 15.7\\beta + 170.8\\beta^2 - 399.7\\beta^3 + 332.2\\beta^4\n\n Eccentric orifice, 'flange' taps, 180 degree opposite taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.6016 + 0.3312\\beta^{2.1} -1.5581\\beta^8 + \\frac{0.6510\\beta^4}{(1-\\beta^4)} - 0.7308\\beta^3\n\n .. math::\n b = -139.7 + 1328.8\\beta - 4228.2\\beta^2 + 5691.9\\beta^3 - 2710.4\\beta^4\n\n Eccentric orifice, 'flange' taps, 90 degree side taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.5866 + 0.3917\\beta^{2.1} + .7586\\beta^8 - \\frac{.2273\\beta^4}{(1-\\beta^4)} - .3343\\beta^3\n\n .. math::\n b = 69.1 - 469.4\\beta + 1245.6\\beta^2 -1287.5\\beta^3 + 486.2\\beta^4\n\n Eccentric orifice, 'flange' taps, 90 degree side taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.6037 + 0.1598\\beta^{2.1} -.2918\\beta^8 + \\frac{0.0244\\beta^4}{(1-\\beta^4)} - 0.0790\\beta^3\n\n .. math::\n b = -103.2 + 898.3\\beta - 2557.3\\beta^2 + 2977.0\\beta^3 - 1131.3\\beta^4\n\n Eccentric orifice, 'vena contracta' taps, 180 degree opposite taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.5925 + 0.3380\\beta^{2.1} + 0.4016\\beta^8 - \\frac{.1046\\beta^4}{(1-\\beta^4)} - 0.3212\\beta^3\n\n .. math::\n b = 23.3 -207.0\\beta + 821.5\\beta^2 -1388.6\\beta^3 + 900.3\\beta^4\n\n Eccentric orifice, 'vena contracta' taps, 180 degree opposite taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.5922 + 0.3932\\beta^{2.1} + .3412\\beta^8 - \\frac{.0569\\beta^4}{(1-\\beta^4)} - 0.4628\\beta^3\n\n .. math::\n b = 55.7 - 471.4\\beta + 1721.8\\beta^2 - 2722.6\\beta^3 + 1569.4\\beta^4\n\n Eccentric orifice, 'vena contracta' taps, 90 degree side taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.5875 + 0.3813\\beta^{2.1} + 0.6898\\beta^8 - \\frac{0.1963\\beta^4}{(1-\\beta^4)} - 0.3366\\beta^3\n\n .. math::\n b = -69.3 + 556.9\\beta - 1332.2\\beta^2 + 1303.7\\beta^3 - 394.8\\beta^4\n\n Eccentric orifice, 'vena contracta' taps, 90 degree side taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.5949 + 0.4078\\beta^{2.1} + 0.0547\\beta^8 + \\frac{0.0955\\beta^4}{(1-\\beta^4)} - 0.5608\\beta^3\n\n .. math::\n b = 52.8 - 434.2\\beta + 1571.2\\beta^2 - 2460.9\\beta^3 + 1420.2\\beta^4\n\n\n Examples\n --------\n >>> C_Miller_1996(D=0.07391, Do=0.0222, rho=1.165, mu=1.85E-5, m=0.12, taps='flange', subtype='orifice')\n 0.599065557156788\n\n References\n ----------\n .. [1] Miller, Richard W. Flow Measurement Engineering Handbook.\n McGraw-Hill Education, 1996.\n .. [2] \"RW Miller & Associates.\" Accessed April 13, 2020.\n http://rwmillerassociates.com/.\n \"\"\"\n A_pipe = 0.25*pi*D*D\n v = m/(A_pipe*rho)\n Re = rho*v*D/mu\n D_mm = D*1000.0\n\n beta = Do/D\n beta2 = beta*beta\n beta3 = beta2*beta\n beta4 = beta*beta3\n beta8 = beta4*beta4\n beta21 = beta**2.1\n\n if subtype in (MILLER_ORIFICE, CONCENTRIC_ORIFICE):\n b = 91.706*beta2*sqrt(beta)\n n = 0.75\n if taps == ORIFICE_CORNER_TAPS:\n C_inf = 0.5959 + 0.0312*beta21 - 0.184*beta8\n elif taps == ORIFICE_FLANGE_TAPS:\n if D_mm >= 58.4:\n C_inf = 0.5959 + 0.0312*beta21 - 0.184*beta8 + 2.286*beta4/(D_mm*(1.0 - beta4)) - 0.856*beta3/D_mm\n else:\n C_inf = 0.5959 + 0.0312*beta21 - 0.184*beta8 + 0.039*beta4/(1.0 - beta4) - 0.856*beta3/D_mm\n elif taps == ORIFICE_D_AND_D_2_TAPS:\n C_inf = 0.5959 + 0.0312*beta21 - 0.184*beta8 + 0.039*beta4/(1.0 - beta4) - 0.01584\n elif taps == ORIFICE_PIPE_TAPS:\n C_inf = 0.5959 + 0.461*beta21 + 0.48*beta8 + 0.039*beta4/(1.0 - beta4)\n else:\n raise ValueError(_Miller_1996_unsupported_tap_concentric)\n elif subtype in (MILLER_ECCENTRIC_ORIFICE, ECCENTRIC_ORIFICE):\n if tap_position not in (TAPS_OPPOSITE, TAPS_SIDE):\n raise ValueError(_Miller_1996_unsupported_tap_pos_eccentric)\n n = 0.75\n if taps == ORIFICE_FLANGE_TAPS:\n if tap_position == TAPS_OPPOSITE:\n if D < 0.1:\n b = 7.3 - 15.7*beta + 170.8*beta2 - 399.7*beta3 + 332.2*beta4\n C_inf = 0.5917 + 0.3061*beta21 + 0.3406*beta8 - 0.1019*beta4/(1.0-beta4) - 0.2715*beta3\n else:\n b = -139.7 + 1328.8*beta - 4228.2*beta2 + 5691.9*beta3 - 2710.4*beta4\n C_inf = 0.6016 + 0.3312*beta21 - 1.5581*beta8 + 0.6510*beta4/(1.0-beta4) - 0.7308*beta3\n elif tap_position == TAPS_SIDE:\n if D < 0.1:\n b = 69.1 - 469.4*beta + 1245.6*beta2 -1287.5*beta3 + 486.2*beta4\n C_inf = 0.5866 + 0.3917*beta21 + 0.7586*beta8 - 0.2273*beta4/(1.0-beta4) - 0.3343*beta3\n else:\n b = -103.2 + 898.3*beta - 2557.3*beta2 + 2977.0*beta3 - 1131.3*beta4\n C_inf = 0.6037 + 0.1598*beta21 - 0.2918*beta8 + 0.0244*beta4/(1.0-beta4) - 0.0790*beta3\n elif taps == ORIFICE_VENA_CONTRACTA_TAPS:\n if tap_position == TAPS_OPPOSITE:\n if D < 0.1:\n b = 23.3 -207.0*beta + 821.5*beta2 -1388.6*beta3 + 900.3*beta4\n C_inf = 0.5925 + 0.3380*beta21 + 0.4016*beta8 - 0.1046*beta4/(1.0-beta4) - 0.3212*beta3\n else:\n b = 55.7 - 471.4*beta + 1721.8*beta2 - 2722.6*beta3 + 1569.4*beta4\n C_inf = 0.5922 + 0.3932*beta21 + 0.3412*beta8 - 0.0569*beta4/(1.0-beta4) - 0.4628*beta3\n elif tap_position == TAPS_SIDE:\n if D < 0.1:\n b = -69.3 + 556.9*beta - 1332.2*beta2 + 1303.7*beta3 - 394.8*beta4\n C_inf = 0.5875 + 0.3813*beta21 + 0.6898*beta8 - 0.1963*beta4/(1.0-beta4) - 0.3366*beta3\n else:\n b = 52.8 - 434.2*beta + 1571.2*beta2 - 2460.9*beta3 + 1420.2*beta4\n C_inf = 0.5949 + 0.4078*beta21 + 0.0547*beta8 + 0.0955*beta4/(1.0-beta4) - 0.5608*beta3\n else:\n raise ValueError(_Miller_1996_unsupported_tap_eccentric)\n elif subtype in (MILLER_SEGMENTAL_ORIFICE, SEGMENTAL_ORIFICE):\n n = b = 0.0\n if taps == ORIFICE_FLANGE_TAPS:\n if D < 0.1:\n C_inf = 0.6284 + 0.1462*beta21 - 0.8464*beta8 + 0.2603*beta4/(1.0-beta4) - 0.2886*beta3\n else:\n C_inf = 0.6276 + 0.0828*beta21 + 0.2739*beta8 - 0.0934*beta4/(1.0-beta4) - 0.1132*beta3\n elif taps == ORIFICE_VENA_CONTRACTA_TAPS:\n if D < 0.1:\n C_inf = 0.6261 + 0.1851*beta21 - 0.2879*beta8 + 0.1170*beta4/(1.0-beta4) - 0.2845*beta3\n else:\n # Yes these are supposed to be the same as the flange, large set\n C_inf = 0.6276 + 0.0828*beta21 + 0.2739*beta8 - 0.0934*beta4/(1.0-beta4) - 0.1132*beta3\n else:\n raise ValueError(_Miller_1996_unsupported_tap_segmental)\n elif subtype in (MILLER_CONICAL_ORIFICE, CONICAL_ORIFICE):\n n = b = 0.0\n if 250.0*beta <= Re <= 500.0*beta:\n C_inf = 0.734\n else:\n C_inf = 0.730\n elif subtype in (MILLER_QUARTER_CIRCLE_ORIFICE, QUARTER_CIRCLE_ORIFICE):\n n = b = 0.0\n C_inf = (0.7746 - 0.1334*beta21 + 1.4098*beta8\n + 0.0675*beta4/(1.0 - beta4) + 0.3865*beta3)\n else:\n raise ValueError(_Miller_1996_unsupported_type)\n C = C_inf + b*Re**-n\n return C\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 19793}, "tests/test_friction.py::168": {"resolved_imports": ["fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["Clamond", "_roughness", "assert_close", "friction_factor", "friction_factor_methods", "ft_Crane", "pytest", "roughness_Farshad"], "enclosing_function": "test_friction", "extracted_code": "# Source: fluids/friction.py\ndef Clamond(Re: float, eD: float, fast: bool=False) -> float:\n r\"\"\"Calculates Darcy friction factor using a solution accurate to almost\n machine precision. Recommended very strongly. For details of the algorithm,\n see [1]_.\n\n Parameters\n ----------\n Re : float\n Reynolds number, [-]\n eD : float\n Relative roughness, [-]\n fast : bool, optional\n If true, performs only one iteration, which gives roughly half the\n number of decimals of accuracy, [-]\n\n Returns\n -------\n fd : float\n Darcy friction factor [-]\n\n Notes\n -----\n This is a highly optimized function, 4 times faster than the solution using\n the LambertW function, and faster than many other approximations which are\n much less accurate.\n\n The code used here is only slightly modified from that in [1]_, for further\n performance improvements.\n\n For 10 < Re < 1E12, and 0 < eD < 0.01, this equation has been confirmed\n numerically to provide a solution to the Colebrook equation accurate to an\n rtol of 1E-9 or better - the same level of accuracy as the analytical\n solution to the Colebrook equation due to floating point precision.\n\n Comparing this to the numerical solution of the Colebrook equation,\n identical values are given accurate to an rtol of 1E-9 for 10 < Re < 1E100,\n and 0 < eD < 1 and beyond.\n\n However, for values of Re under 10, different answers from the `Colebrook`\n equation appear and then quickly a ValueError is raised.\n\n Examples\n --------\n >>> Clamond(1E5, 1E-4)\n 0.01851386607747165\n\n References\n ----------\n .. [1] Clamond, Didier. \"Efficient Resolution of the Colebrook Equation.\"\n Industrial & Engineering Chemistry Research 48, no. 7 (April 1, 2009):\n 3665-71. doi:10.1021/ie801626g.\n http://math.unice.fr/%7Edidierc/DidPublis/ICR_2009.pdf\n \"\"\"\n X1 = eD*Re*0.1239681863354175460160858261654858382699 # (log(10)/18.574).evalf(40)\n X2 = log(Re) - 0.7793974884556819406441139701653776731705 # log(log(10)/5.02).evalf(40)\n F = X2 - 0.2\n X1F = X1 + F\n X1F1 = 1. + X1F\n\n E = (log(X1F) - 0.2)/(X1F1)\n F = F - (X1F1 + 0.5*E)*E*(X1F)/(X1F1 + E*(1. + (1.0/3.0)*E))\n\n if not fast:\n X1F = X1 + F\n X1F1 = 1. + X1F\n E = (log(X1F) + F - X2)/(X1F1)\n\n b = (X1F1 + E*(1. + 1.0/3.0*E))\n F = b/(b*F - ((X1F1 + 0.5*E)*E*(X1F)))\n return 1.325474527619599502640416597148504422899*(F*F) # ((0.5*log(10))**2).evalf(40)\n\n return 1.325474527619599502640416597148504422899/(F*F)\n\ndef ft_Crane(D: float) -> float:\n r\"\"\"Calculates the Crane fully turbulent Darcy friction factor for flow in\n commercial pipe, as used in the Crane formulas for loss coefficients in\n various fittings. Note that this is **not generally applicable to loss\n due to friction in pipes**, as it does not take into account the roughness\n of various pipe materials. But for fittings in any type of pipe, this is\n the friction factor to use in the Crane [1]_ method to get their loss\n coefficients.\n\n Parameters\n ----------\n D : float\n Pipe inner diameter, [m]\n\n Returns\n -------\n fd : float\n Darcy Crane friction factor for fully turbulent flow, [-]\n\n Notes\n -----\n There is confusion and uncertainty regarding the friction factor table\n given in Crane TP 410M [1]_. This function does not help: it implements a\n new way to obtain Crane friction factors, so that it can better be based in\n theory and give more precision (not accuracy) and trend better with\n diameters not tabulated in [1]_.\n\n The data in [1]_ was digitized, and nominal pipe diameters were converted\n to actual pipe diameters. An objective function was sought which would\n produce the exact same values as in [1]_ when rounded to the same decimal\n place. One was found fairly easily by using the standard `Colebrook`\n friction factor formula, and using the diameter-dependent roughness values\n calculated with the `roughness_Farshad` method for bare Carbon steel. A\n diameter-dependent Reynolds number was required to match the values;\n the :math:`\\rho V/\\mu` term is set to 7.5E6.\n\n The formula given in [1]_ is:\n\n .. math::\n f_T = \\frac{0.25}{\\left[\\log_{10}\\left(\\frac{\\epsilon/D}{3.7}\\right)\n \\right]^2}\n\n However, this function does not match the rounded values in [1]_ well and\n it is not very clear which roughness to use. Using both the value for new\n commercial steel (.05 mm) or a diameter-dependent value\n (`roughness_Farshad`), values were found to be too high and too low\n respectively. That function is based in theory - the limit of the\n `Colebrook` equation when `Re` goes to infinity - but in the end real pipe\n flow is not infinity, and so a large error occurs from that use.\n\n The following plot shows all these options, and that the method implemented\n here matches perfectly the rounded values in [1]_.\n\n .. plot:: plots/ft_Crane_plot.py\n\n Examples\n --------\n >>> ft_Crane(.1)\n 0.01628845962146481\n\n Explicitly spelling out the function (note the exact same answer is not\n returned; it is accurate to 5-8 decimals however, for increased speed):\n\n >>> Di = 0.1\n >>> Colebrook(7.5E6*Di, eD=roughness_Farshad(ID='Carbon steel, bare', D=Di)/Di)\n 0.0162884254312\n\n References\n ----------\n .. [1] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,\n 2009.\n \"\"\"\n fast = True\n if D < 1E-2:\n fast = False\n return Clamond(7.5E6*D, 3.4126825352925e-5*D**-1.0112, fast)\n\ndef friction_factor_methods(Re: float, eD: float=0.0, check_ranges: bool=True) -> list[str]:\n r\"\"\"Returns a list of correlation names for calculating friction factor\n for internal pipe flow.\n\n Examples\n --------\n >>> len(friction_factor_methods(Re=1E5, eD=1E-4))\n 30\n\n Parameters\n ----------\n Re : float\n Reynolds number, [-]\n eD : float, optional\n Relative roughness of the wall, [-]\n check_ranges : bool, optional\n Whether to filter the list for correlations which claim to be valid for\n the given values, [-]\n\n Returns\n -------\n methods : list\n List of methods which claim to be valid for the range of `Re` and `eD`\n given, [-]\n \"\"\"\n if check_ranges:\n if Re < LAMINAR_TRANSITION_PIPE:\n return [\"laminar\"]\n methods = []\n for n, (Re_min, Re_max, eD_min, eD_max) in fmethods.items():\n if Re_min is not None and Re < Re_min:\n continue\n if Re_max is not None and Re > Re_max:\n continue\n if eD_min is not None and eD < eD_min:\n continue\n if eD_max is not None and eD > eD_max:\n continue\n methods.append(n)\n return methods\n else:\n return list(fmethods.keys()) + [\"laminar\"]\n\ndef friction_factor(Re: float, eD: float=0.0, Method: str | None=\"Clamond\", Darcy: bool=True) -> float:\n r\"\"\"Calculates friction factor. Uses a specified method, or automatically\n picks one from the dictionary of available methods. 29 approximations are\n available as well as the direct solution, described in the table below.\n The default is to use the exact solution.\n\n For Re < 2040, [1]_ the laminar solution is always returned, regardless of\n selected method.\n\n Examples\n --------\n >>> friction_factor(Re=1E5, eD=1E-4)\n 0.01851386607747165\n >>> friction_factor(Re=2.9E5, eD=1E-5, Method='Serghides_2')\n 0.0146199041093456\n\n Parameters\n ----------\n Re : float\n Reynolds number, [-]\n eD : float, optional\n Relative roughness of the wall, [-]\n\n Returns\n -------\n f : float\n Friction factor, [-]\n\n Other Parameters\n ----------------\n Method : string, optional\n A string of the function name to use\n Darcy : bool, optional\n If False, will return fanning friction factor, 1/4 of the Darcy value\n\n See Also\n --------\n Colebrook\n Clamond\n\n Notes\n -----\n A table of the supposed limits of each correlation is as follows. Note that\n the spaces in the method names are replaced by underscores in the actual\n function names and when provided as the `Method` argument. The default\n method is likely to be sufficient.\n\n\n +-------------------+------+------+----------------------+----------------------+\n |Nice name |Re min|Re max|:math:`\\epsilon/D` Min|:math:`\\epsilon/D` Max|\n +===================+======+======+======================+======================+\n |Clamond |0 |None |0 |None |\n +-------------------+------+------+----------------------+----------------------+\n |Rao Kumar 2007 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Eck 1973 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Jain 1976 |5000 |1.0E+7|4.0E-5 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Avci Karagoz 2009 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Swamee Jain 1976 |5000 |1.0E+8|1.0E-6 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Churchill 1977 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Brkic 2011 1 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Chen 1979 |4000 |4.0E+8|1.0E-7 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Round 1980 |4000 |4.0E+8|0 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Papaevangelo 2010 |10000 |1.0E+7|1.0E-5 |0.001 |\n +-------------------+------+------+----------------------+----------------------+\n |Fang 2011 |3000 |1.0E+8|0 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Shacham 1980 |4000 |4.0E+8|None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Barr 1981 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Churchill 1973 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Moody |4000 |1.0E+8|0 |1 |\n +-------------------+------+------+----------------------+----------------------+\n |Zigrang Sylvester 1|4000 |1.0E+8|4.0E-5 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Zigrang Sylvester 2|4000 |1.0E+8|4.0E-5 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Buzzelli 2008 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Haaland |4000 |1.0E+8|1.0E-6 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Serghides 1 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Serghides 2 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Tsal 1989 |4000 |1.0E+8|0 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Alshul 1952 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Wood 1966 |4000 |5.0E+7|1.0E-5 |0.04 |\n +-------------------+------+------+----------------------+----------------------+\n |Manadilli 1997 |5245 |1.0E+8|0 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Brkic 2011 2 |None |None |None |None |\n +-------------------+------+------+----------------------+----------------------+\n |Romeo 2002 |3000 |1.5E+8|0 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n |Sonnad Goudar 2006 |4000 |1.0E+8|1.0E-6 |0.05 |\n +-------------------+------+------+----------------------+----------------------+\n\n References\n ----------\n .. [1] Avila, Kerstin, David Moxey, Alberto de Lozar, Marc Avila, Dwight\n Barkley, and Björn Hof. \"The Onset of Turbulence in Pipe Flow.\" Science\n 333, no. 6039 (July 8, 2011): 192-96. doi:10.1126/science.1203223.\n \"\"\"\n if Method is None:\n Method = \"Clamond\"\n\n if Re < LAMINAR_TRANSITION_PIPE or Method == \"laminar\":\n f = friction_laminar(Re)\n elif Method == \"Clamond\":\n f = Clamond(Re, eD, False)\n elif Method == \"Colebrook\":\n f = Colebrook(Re, eD)\n elif Method == \"Moody\":\n f = Moody(Re, eD)\n elif Method == \"Alshul_1952\":\n f = Alshul_1952(Re, eD)\n elif Method == \"Wood_1966\":\n f = Wood_1966(Re, eD)\n elif Method == \"Churchill_1973\":\n f = Churchill_1973(Re, eD)\n elif Method == \"Eck_1973\":\n f = Eck_1973(Re, eD)\n elif Method == \"Jain_1976\":\n f = Jain_1976(Re, eD)\n elif Method == \"Swamee_Jain_1976\":\n f = Swamee_Jain_1976(Re, eD)\n elif Method == \"Churchill_1977\":\n f = Churchill_1977(Re, eD)\n elif Method == \"Chen_1979\":\n f = Chen_1979(Re, eD)\n elif Method == \"Round_1980\":\n f = Round_1980(Re, eD)\n elif Method == \"Shacham_1980\":\n f = Shacham_1980(Re, eD)\n elif Method == \"Barr_1981\":\n f = Barr_1981(Re, eD)\n elif Method == \"Zigrang_Sylvester_1\":\n f = Zigrang_Sylvester_1(Re, eD)\n elif Method == \"Zigrang_Sylvester_2\":\n f = Zigrang_Sylvester_2(Re, eD)\n elif Method == \"Haaland\":\n f = Haaland(Re, eD)\n elif Method == \"Serghides_1\":\n f = Serghides_1(Re, eD)\n elif Method == \"Serghides_2\":\n f = Serghides_2(Re, eD)\n elif Method == \"Tsal_1989\":\n f = Tsal_1989(Re, eD)\n elif Method == \"Manadilli_1997\":\n f = Manadilli_1997(Re, eD)\n elif Method == \"Romeo_2002\":\n f = Romeo_2002(Re, eD)\n elif Method == \"Sonnad_Goudar_2006\":\n f = Sonnad_Goudar_2006(Re, eD)\n elif Method == \"Rao_Kumar_2007\":\n f = Rao_Kumar_2007(Re, eD)\n elif Method == \"Buzzelli_2008\":\n f = Buzzelli_2008(Re, eD)\n elif Method == \"Avci_Karagoz_2009\":\n f = Avci_Karagoz_2009(Re, eD)\n elif Method == \"Papaevangelo_2010\":\n f = Papaevangelo_2010(Re, eD)\n elif Method == \"Brkic_2011_1\":\n f = Brkic_2011_1(Re, eD)\n elif Method == \"Brkic_2011_2\":\n f = Brkic_2011_2(Re, eD)\n elif Method == \"Fang_2011\":\n f = Fang_2011(Re, eD)\n else:\n raise ValueError(\"Method not recognized\")\n if not Darcy:\n f *= 0.25\n return f\n\n_roughness = {\"Brass\": .00000152, \"Lead\": .00000152, \"Glass\": .00000152,\n\"Steel\": .00000152, \"Asphalted cast iron\": .000122, \"Galvanized iron\": .000152,\n\"Cast iron\": .000259, \"Wood stave\": .000183, \"Rough wood stave\": .000914,\n\"Concrete\": .000305, \"Rough concrete\": .00305, \"Riveted steel\": .000914,\n\"Rough riveted steel\": .00914}\n\ndef roughness_Farshad(ID: str | None=None, D: float | None=None, coeffs: tuple[float, float] | None=None) -> float:\n r\"\"\"Calculates or retrieves the roughness of a pipe based on the work of\n [1]_. This function will return an average value for pipes of a given\n material, or if diameter is provided, will calculate one specifically for\n the pipe inner diameter according to the following expression with\n constants `A` and `B`:\n\n .. math::\n \\epsilon = A\\cdot D^{B+1}\n\n Please note that `A` has units of inches, and `B` requires `D` to be in\n inches as well.\n\n The list of supported materials is as follows:\n\n * 'Plastic coated'\n * 'Carbon steel, honed bare'\n * 'Cr13, electropolished bare'\n * 'Cement lining'\n * 'Carbon steel, bare'\n * 'Fiberglass lining'\n * 'Cr13, bare'\n\n If `coeffs` and `D` are given, the custom coefficients for the equation as\n given by the user will be used and `ID` is not required.\n\n Parameters\n ----------\n ID : str, optional\n Name of pipe material from above list\n D : float, optional\n Actual inner diameter of pipe, [m]\n coeffs : tuple, optional\n (A, B) Coefficients to use directly, instead of looking them up;\n they are actually dimensional, in the forms (inch^-B, -) but only\n coefficients with those dimensions are available [-]\n\n Returns\n -------\n epsilon : float\n Roughness of pipe [m]\n\n Notes\n -----\n The diameter-dependent form provides lower roughness values for larger\n diameters.\n\n The measurements were based on DIN 4768/1 (1987), using both a\n \"Dektak ST Surface Profiler\" and a \"Hommel Tester T1000\". Both instruments\n were found to be in agreement. A series of flow tests, in which pressure\n drop directly measured, were performed as well, with nitrogen gas as an\n operating fluid. The accuracy of the data from these tests is claimed to be\n within 1%.\n\n Using those results, the authors back-calculated what relative roughness\n values would be necessary to produce the observed pressure drops. The\n average difference between this back-calculated roughness and the measured\n roughness was 6.75%.\n\n For microchannels, this model will predict roughness much larger than the\n actual channel diameter.\n\n Examples\n --------\n >>> roughness_Farshad('Cr13, bare', 0.05)\n 5.3141677781137006e-05\n\n References\n ----------\n .. [1] Farshad, Fred F., and Herman H. Rieke. \"Surface Roughness Design\n Values for Modern Pipes.\" SPE Drilling & Completion 21, no. 3 (September\n 1, 2006): 212-215. doi:10.2118/89040-PA.\n \"\"\"\n # Case 1, coeffs given; only run if ID is not given.\n if ID is None and coeffs is not None:\n if D is None:\n raise ValueError(\"D is required when using coeffs\")\n A, B = coeffs\n return A*(D/inch)**(B + 1.0)*inch\n # Case 2, lookup parameters\n if ID in _Farshad_roughness: # numba: delete\n dat = _Farshad_roughness[ID] # numba: delete\n# try: # numba: uncomment\n# dat = _Farshad_roughness_values[_Farshad_roughness_keys.index(ID)] # numba: uncomment\n# except: # numba: uncomment\n# raise KeyError('ID was not in _Farshad_roughness.') # numba: uncomment\n if D is None:\n return dat[0]\n else:\n A, B = dat[1], dat[2]\n return A*(D/inch)**(B+1)*inch\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 20600}, "tests/test_mixing.py::48": {"resolved_imports": ["fluids/mixing.py", "fluids/numerics/__init__.py"], "used_names": ["COV_motionless_mixer", "K_motionless_mixer", "Kp_helical_ribbon_Rieger", "agitator_time_homogeneous", "assert_close", "assert_close1d", "size_tee", "time_helical_ribbon_Grenville"], "enclosing_function": "test_mixing", "extracted_code": "# Source: fluids/mixing.py\ndef agitator_time_homogeneous(N: float, P: float, T: float, H: float, mu: float, rho: float, D: float | None=None, homogeneity: float=.95) -> float:\n r\"\"\"Calculates time for a fluid mizing in a tank with an impeller to\n reach a specified level of homogeneity, according to [1]_.\n\n .. math::\n N_p = \\frac{Pg}{\\rho N^3 D^5}\n\n .. math::\n Re_{imp} = \\frac{\\rho D^2 N}{\\mu}\n\n .. math::\n \\text{constant} = N_p^{1/3} Re_{imp}\n\n .. math::\n Fo = 5.2/\\text{constant} \\text{for turbulent regime}\n\n .. math::\n Fo = (183/\\text{constant})^2 \\text{for transition regime}\n\n Parameters\n ----------\n N : float:\n Speed of impeller, [revolutions/s]\n P : float\n Actual power required to mix, ignoring mechanical inefficiencies [W]\n T : float\n Tank diameter, [m]\n H : float\n Tank height, [m]\n mu : float\n Mixture viscosity, [Pa*s]\n rho : float\n Mixture density, [kg/m^3]\n D : float, optional\n Impeller diameter [m]\n homogeneity : float, optional\n Fraction completion of mixing, []\n\n Returns\n -------\n t : float\n Time for specified degree of homogeneity [s]\n\n Notes\n -----\n If impeller diameter is not specified, assumed to be 0.5 tank diameters.\n\n The first example is solved forward rather than backwards here. A rather\n different result is obtained, but is accurate.\n\n No check to see if the mixture if laminar is currently implemented.\n This would under predict the required time.\n\n Examples\n --------\n >>> agitator_time_homogeneous(D=36*.0254, N=56/60., P=957., T=1.83, H=1.83, mu=0.018, rho=1020, homogeneity=.995)\n 15.143198226374668\n\n >>> agitator_time_homogeneous(D=1, N=125/60., P=298., T=3, H=2.5, mu=.5, rho=980, homogeneity=.95)\n 67.7575069865228\n\n References\n ----------\n .. [1] Paul, Edward L, Victor A Atiemo-Obeng, and Suzanne M Kresta.\n Handbook of Industrial Mixing: Science and Practice.\n Hoboken, N.J.: Wiley-Interscience, 2004.\n \"\"\"\n if not D:\n D = T*0.5\n Np = P*g/rho/N**3/D**5\n Re_imp = rho/mu*D**2*N\n regime_constant = Np**(1/3.)*Re_imp\n if regime_constant >= min_regime_constant_for_turbulent:\n Fo = (5.2/regime_constant)\n else:\n Fo = (183./regime_constant)**2\n time = rho*T**1.5*sqrt(H)/mu*Fo\n multiplier = adjust_homogeneity(homogeneity)\n return time*multiplier\n\ndef Kp_helical_ribbon_Rieger(D: float, h: float, nb: int, pitch: float, width: float, T: float) -> float:\n r\"\"\"Calculates product of power number and Reynolds number for a\n specified geometry for a heilical ribbon mixer in the laminar regime.\n One of several correlations listed in [1]_, it used more data than other\n listed correlations and was recommended.\n\n .. math::\n K_p = 82.8\\frac{h}{D}\\left(\\frac{c}{D}\\right)^{-0.38} \\left(\\frac{p}{D}\\right)^{-0.35}\n \\left(\\frac{w}{D}\\right)^{0.20} n_b^{0.78}\n\n Parameters\n ----------\n D : float\n Impeller diameter [m]\n h : float\n Ribbon mixer height, [m]\n nb : float:\n Number of blades, [-]\n pitch : float\n Height of one turn around a helix [m]\n width : float\n Width of one blade [m]\n T : float\n Tank diameter, [m]\n\n Returns\n -------\n Kp : float\n Product of Power number and Reynolds number for laminar regime []\n\n Notes\n -----\n Example is from example 9-6 in [1]_. Confirmed.\n\n Examples\n --------\n >>> Kp_helical_ribbon_Rieger(D=1.9, h=1.9, nb=2, pitch=1.9, width=.19, T=2)\n 357.39749163259256\n\n References\n ----------\n .. [1] Paul, Edward L, Victor A Atiemo-Obeng, and Suzanne M Kresta.\n Handbook of Industrial Mixing: Science and Practice.\n Hoboken, N.J.: Wiley-Interscience, 2004.\n .. [2] Rieger, F., V. Novak, and D. Havelkov (1988). The influence of the\n geometrical shape on the power requirements of ribbon impellers,\n Int. Chem. Eng., 28, 376-383.\n \"\"\"\n c = 0.5*(T - D)\n return 82.8*h/D*(c/D)**-.38*(pitch/D)**-0.35*(width/D)**0.2*nb**0.78\n\ndef time_helical_ribbon_Grenville(Kp: float, N: float) -> float:\n r\"\"\"Calculates product of time required for mixing in a helical ribbon\n coil in the laminar regime according to the Grenville [2]_ method\n recommended in [1]_.\n\n .. math::\n t = 896\\times10^3K_p^{-1.69}/N\n\n Parameters\n ----------\n Kp : float\n Product of power number and Reynolds number for laminar regime []\n N : float\n Speed of impeller, [revolutions/s]\n\n Returns\n -------\n t : float\n Time for homogeneity [s]\n\n Notes\n -----\n Degree of homogeneity is not specified.\n Example is from example 9-6 in [1]_. Confirmed.\n\n Examples\n --------\n >>> time_helical_ribbon_Grenville(357.4, 4/60.)\n 650.980654028894\n\n References\n ----------\n .. [1] Paul, Edward L, Victor A Atiemo-Obeng, and Suzanne M Kresta.\n Handbook of Industrial Mixing: Science and Practice.\n Hoboken, N.J.: Wiley-Interscience, 2004.\n .. [2] Grenville, R. K., T. M. Hutchinson, and R. W. Higbee (2001).\n Optimisation of helical ribbon geometry for blending in the laminar\n regime, presented at MIXING XVIII, NAMF.\n \"\"\"\n return 896E3*Kp**-1.69/N\n\ndef size_tee(Q1: float, Q2: float, D: float, D2: float | None, n: int=1, pipe_diameters: float=5) -> float:\n r\"\"\"Calculates CoV of an optimal or specified tee for mixing at a tee\n according to [1]_. Assumes turbulent flow.\n The smaller stream in injected into the main pipe, which continues\n straight.\n COV calculation is according to [2]_.\n\n Parameters\n ----------\n Q1 : float\n Volumetric flow rate of larger stream [m^3/s]\n Q2 : float\n Volumetric flow rate of smaller stream [m^3/s]\n D : float\n Diameter of pipe after tee [m]\n D2 : float\n Diameter of mixing inlet, optional (optimally calculated if not\n specified) [m]\n n : float\n Number of jets, 1 to 4 []\n pipe_diameters : float\n Number of diameters along tail pipe for CoV calculation, 0 to 5 []\n\n Returns\n -------\n CoV : float\n Standard deviation of dimensionless concentration [-]\n\n Notes\n -----\n Not specified if this works for liquid also, though probably not.\n Example is from example Example 9-6 in [1]_. Low precision used in example.\n\n Examples\n --------\n >>> size_tee(Q1=11.7, Q2=2.74, D=0.762, D2=None, n=1, pipe_diameters=5)\n 0.2940930233038544\n\n References\n ----------\n .. [1] Paul, Edward L, Victor A Atiemo-Obeng, and Suzanne M Kresta.\n Handbook of Industrial Mixing: Science and Practice.\n Hoboken, N.J.: Wiley-Interscience, 2004.\n .. [2] Giorges, Aklilu T. G., Larry J. Forney, and Xiaodong Wang.\n \"Numerical Study of Multi-Jet Mixing.\" Chemical Engineering Research and\n Design, Fluid Flow, 79, no. 5 (July 2001): 515-22.\n doi:10.1205/02638760152424280.\n \"\"\"\n V1 = Q1/(pi/4*D**2)\n # Cv = Q2/(Q1 + Q2)\n # COV0 = sqrt((1-Cv)/Cv)\n if D2 is None:\n D2 = (Q2/Q1)**(2/3.)*D\n V2 = Q2/(pi/4*D2**2)\n B = n**2*(D2/D)**2*(V2/V1)**2\n if not n == 1 and not n == 2 and not n == 3 and not n ==4:\n raise ValueError(\"Only 1 or 4 side streams investigated\")\n if n == 1:\n if B < 0.7:\n E = 1.33\n else:\n E = 1/33. + 0.95*log(B/0.7)\n elif n == 2:\n if B < 0.8:\n E = 1.44\n else:\n E = 1.44 + 0.95*log(B/0.8)**1.5\n elif n == 3:\n if B < 0.8:\n E = 1.75\n else:\n E = 1.75 + 0.95*log(B/0.8)**1.8\n else:\n if B < 2:\n E = 1.97\n else:\n E = 1.97 + 0.95*log(B/2.)**2\n COV = sqrt(0.32/B**0.86*(pipe_diameters)**-E)\n return COV\n\ndef COV_motionless_mixer(Ki: float, Q1: float, Q2: float, pipe_diameters: float) -> float:\n r\"\"\"Calculates CoV of a motionless mixer with a regression parameter in\n [1]_ and originally in [2]_.\n\n .. math::\n \\frac{CoV}{CoV_0} = K_i^{L/D}\n\n Parameters\n ----------\n Ki : float\n Correlation parameter specific to a mixer's design, [-]\n Q1 : float\n Volumetric flow rate of larger stream [m^3/s]\n Q2 : float\n Volumetric flow rate of smaller stream [m^3/s]\n pipe_diameters : float\n Number of diameters along tail pipe for CoV calculation, 0 to 5 []\n\n Returns\n -------\n CoV : float\n Standard deviation of dimensionless concentration [-]\n\n Notes\n -----\n Example 7-8.3.2 in [1]_, solved backwards.\n\n Examples\n --------\n >>> COV_motionless_mixer(Ki=.33, Q1=11.7, Q2=2.74, pipe_diameters=4.74/.762)\n 0.0020900028665727685\n\n References\n ----------\n .. [1] Paul, Edward L, Victor A Atiemo-Obeng, and Suzanne M Kresta.\n Handbook of Industrial Mixing: Science and Practice.\n Hoboken, N.J.: Wiley-Interscience, 2004.\n .. [2] Streiff, F. A., S. Jaffer, and G. Schneider (1999). Design and\n application of motionless mixer technology, Proc. ISMIP3, Osaka,\n pp. 107-114.\n \"\"\"\n Cv = Q2/(Q1 + Q2)\n COV0 = sqrt((1-Cv)/Cv)\n COVr = Ki**(pipe_diameters)\n COV = COV0*COVr\n return COV\n\ndef K_motionless_mixer(K: float, L: float, D: float, fd: float) -> float:\n r\"\"\"Calculates loss coefficient of a motionless mixer with a regression\n parameter in [1]_ and originally in [2]_.\n\n .. math::\n K = K_{L/T}f\\frac{L}{D}\n\n Parameters\n ----------\n K : float\n Correlation parameter specific to a mixer's design, [-]\n Also specific to laminar or turbulent regime.\n L : float\n Length of the motionless mixer [m]\n D : float\n Diameter of pipe [m]\n fd : float\n Darcy friction factor [-]\n\n Returns\n -------\n K : float\n Loss coefficient of mixer [-]\n\n Notes\n -----\n Related to example 7-8.3.2 in [1]_.\n\n Examples\n --------\n >>> K_motionless_mixer(K=150, L=.762*5, D=.762, fd=.01)\n 7.5\n\n References\n ----------\n .. [1] Paul, Edward L, Victor A Atiemo-Obeng, and Suzanne M Kresta.\n Handbook of Industrial Mixing: Science and Practice.\n Hoboken, N.J.: Wiley-Interscience, 2004.\n .. [2] Streiff, F. A., S. Jaffer, and G. Schneider (1999). Design and\n application of motionless mixer technology, Proc. ISMIP3, Osaka,\n pp. 107-114.\n \"\"\"\n return L/D*fd*K\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 11319}, "tests/test_numerics_polynomial_evaluation.py::53": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/polynomial_evaluation.py", "fluids/numerics/polynomial_utils.py"], "used_names": ["assert_close", "assert_close1d", "horner", "horner_and_der2", "horner_and_der3", "horner_and_der4", "horner_backwards"], "enclosing_function": "test_horner", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 846}, "tests/test_numerics_polynomial_evaluation.py::55": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/polynomial_evaluation.py", "fluids/numerics/polynomial_utils.py"], "used_names": ["assert_close", "assert_close1d", "horner", "horner_and_der2", "horner_and_der3", "horner_and_der4", "horner_backwards"], "enclosing_function": "test_horner", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 846}, "tests/test_numerics_polynomial_evaluation.py::233": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/polynomial_evaluation.py", "fluids/numerics/polynomial_utils.py"], "used_names": ["assert_close", "assert_close1d", "horner_stable_ln_tau", "horner_stable_ln_tau_and_der", "horner_stable_ln_tau_and_der2", "horner_stable_ln_tau_and_der3", "log", "polynomial_offset_scale"], "enclosing_function": "test_stablepoly_ln_tau", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\n\n# Source: fluids/numerics/polynomial_evaluation.py\ndef horner_stable_ln_tau(T, Tc, coeffs, offset, scale):\n if T >= Tc:\n return 0.0\n lntau = log(1.0 - T/Tc)\n return horner_stable(lntau, coeffs, offset, scale)\n\ndef horner_stable_ln_tau_and_der(T, Tc, coeffs, offset, scale):\n if T >= Tc:\n return 0.0, 0.0\n lntau = log(1.0 - T/Tc)\n val, poly_der = horner_stable_and_der(lntau, coeffs, offset, scale)\n der = -poly_der/(Tc*(-T/Tc + 1))\n return val, der\n\ndef horner_stable_ln_tau_and_der2(T, Tc, coeffs, offset, scale):\n if T >= Tc:\n return 0.0, 0.0, 0.0\n tau = 1.0 - T/Tc\n lntau = log(tau)\n val, poly_der, poly_der2 = horner_stable_and_der2(lntau, coeffs, offset, scale)\n den = 1.0/(Tc*tau)\n der = -poly_der*den\n\n der2 = (-poly_der + poly_der2)*den*den\n return val, der, der2\n\ndef horner_stable_ln_tau_and_der3(T, Tc, coeffs, offset, scale):\n if T >= Tc:\n return 0.0, 0.0, 0.0, 00\n tau = 1.0 - T/Tc\n lntau = log(tau)\n val, poly_der, poly_der2, poly_der3 = horner_stable_and_der3(lntau, coeffs, offset, scale)\n den = 1.0/(Tc*tau)\n der = -poly_der*den\n der2 = (-poly_der + poly_der2)*den*den\n der3 = -(2.0*poly_der - 3.0*poly_der2 + poly_der3)*den*den*den\n\n return val, der, der2, der3\n\n\n# Source: fluids/numerics/polynomial_utils.py\ndef polynomial_offset_scale(xmin, xmax):\n range_inv = 1.0/(xmax - xmin)\n offset = (-xmax - xmin)*range_inv\n scale = 2.0*range_inv\n return offset, scale", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 2343}, "tests/test_numerics_polynomial_utils.py::86": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["assert_close", "assert_close1d", "polyint_over_x"], "enclosing_function": "test_polyint_over_x", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 846}, "tests/test_two_phase_voidage.py::269": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/two_phase_voidage.py"], "used_names": ["assert_close", "two_phase_voidage_experimental"], "enclosing_function": "test_two_phase_voidage_experimental", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/two_phase_voidage.py\ndef two_phase_voidage_experimental(rho_lg: float, rhol: float, rhog: float) -> float:\n r\"\"\"Calculates the void fraction for two-phase liquid-gas pipeflow. If\n the weight of fluid in a pipe pipe could be measured and the volume of\n the pipe were known, an effective density of the two-phase mixture could be\n calculated. This is directly relatable to the void fraction of the pipe,\n a parameter used to predict the pressure drop. This function converts\n that measured effective two-phase density to void fraction for use in\n developing correlations.\n\n .. math::\n \\alpha = \\frac{\\rho_m - \\rho_l}{\\rho_g - \\rho_l}\n\n Parameters\n ----------\n rho_lg : float\n Two-phase effective density [kg/m^3]\n rhol : float\n Density of the liquid [kg/m^3]\n rhog : float\n Density of the gas [kg/m^3]\n\n Returns\n -------\n alpha : float\n Void fraction (area of gas / total area of channel), [-]\n\n Notes\n -----\n\n Examples\n --------\n >>> two_phase_voidage_experimental(481.0, 800, 2.5)\n 0.4\n\n References\n ----------\n .. [1] Awad, M. M., and Y. S. Muzychka. \"Effective Property Models for\n Homogeneous Two-Phase Flows.\" Experimental Thermal and Fluid Science 33,\n no. 1 (October 1, 2008): 106-13.\n \"\"\"\n return (rho_lg - rhol)/(rhog - rhol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1988}, "tests/test_units.py::139": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/units.py"], "used_names": ["assert_close", "convert_output", "u"], "enclosing_function": "test_convert_output", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/units.py\ndef convert_output(result, out_units, out_vars, ureg):\n # Attempt to handle multiple return values\n # Must be able to convert all values to a pint expression\n t = type(result)\n output_count = len(out_units)\n if t is str or t is bool or result is None:\n return result\n elif t is dict:\n for key, ans in result.items():\n unit = out_units[out_vars.index(key)]\n result[key] = ans*parse_expression_cached(unit, ureg)\n return result\n elif (t is list or t is ndarray) and output_count == 1:\n return np.array(result)*parse_expression_cached(out_units[0], ureg)\n elif isinstance(result, Iterable):\n conveted_result = []\n for ans, unit in zip(result, out_units):\n conveted_result.append(ans*parse_expression_cached(unit, ureg))\n return conveted_result\n else:\n return result*parse_expression_cached(out_units[0], ureg)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 1558}, "tests/test_core.py::293": {"resolved_imports": ["fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["K_from_L_equiv", "K_from_f", "L_equiv_from_K", "L_from_K", "P_from_head", "assert_close", "assert_close1d", "dP_from_K", "f_from_K", "gravity", "head_from_K", "head_from_P", "nu_mu_converter", "pytest"], "enclosing_function": "test_core_misc2", "extracted_code": "# Source: fluids/core.py\ndef nu_mu_converter(rho: float, mu: float | None=None, nu: float | None=None) -> float:\n r\"\"\"Calculates either kinematic or dynamic viscosity, depending on inputs.\n Used when one type of viscosity is known as well as density, to obtain\n the other type. Raises an error if both types of viscosity or neither type\n of viscosity is provided.\n\n .. math::\n \\nu = \\frac{\\mu}{\\rho}\n\n .. math::\n \\mu = \\nu\\rho\n\n Parameters\n ----------\n rho : float\n Density, [kg/m^3]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n\n Returns\n -------\n mu or nu : float\n Dynamic viscosity, Pa*s or Kinematic viscosity, m^2/s\n\n Examples\n --------\n >>> nu_mu_converter(998., nu=1.0E-6)\n 0.000998\n\n References\n ----------\n .. [1] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if mu is not None and nu is None:\n return mu/rho\n elif nu is not None and mu is None:\n return nu*rho\n raise ValueError(\"Inputs must be rho and one of mu and nu.\")\n\ndef gravity(latitude: float, H: float) -> float:\n r\"\"\"Calculates local acceleration due to gravity `g` according to [1]_.\n Uses latitude and height to calculate `g`.\n\n .. math::\n g = 9.780356(1 + 0.0052885\\sin^2\\phi - 0.0000059\\sin^2(2\\phi))\n - 3.086\\times 10^{-6} H\n\n Parameters\n ----------\n latitude : float\n Degrees, [degrees]\n H : float\n Height above earth's surface [m]\n\n Returns\n -------\n g : float\n Acceleration due to gravity, [m/s^2]\n\n Notes\n -----\n Better models, such as EGM2008 exist.\n\n Examples\n --------\n >>> gravity(55, 1E4)\n 9.784151976863571\n\n References\n ----------\n .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n Chemistry and Physics. [Boca Raton, FL]: CRC press, 2014.\n \"\"\"\n lat = latitude*pi/180\n g = 9.780356*(1+0.0052885*sin(lat)**2 -0.0000059*sin(2*lat)**2)-3.086E-6*H\n return g\n\ndef K_from_f(fd: float, L: float, D: float) -> float:\n r\"\"\"Calculates loss coefficient, K, for a given section of pipe\n at a specified friction factor.\n\n .. math::\n K = f_dL/D\n\n Parameters\n ----------\n fd : float\n friction factor of pipe, []\n L : float\n Length of pipe, [m]\n D : float\n Inner diameter of pipe, [m]\n\n Returns\n -------\n K : float\n Loss coefficient, []\n\n Notes\n -----\n For fittings with a specified L/D ratio, use D = 1 and set L to\n specified L/D ratio.\n\n Examples\n --------\n >>> K_from_f(fd=0.018, L=100., D=.3)\n 6.0\n \"\"\"\n return fd*L/D\n\ndef f_from_K(K: float, L: float, D: float) -> float:\n r\"\"\"Calculates friction factor, `fd`, from a loss coefficient, K,\n for a given section of pipe.\n\n .. math::\n f_d = \\frac{K D}{L}\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n L : float\n Length of pipe, [m]\n D : float\n Inner diameter of pipe, [m]\n\n Returns\n -------\n fd : float\n Darcy friction factor of pipe, [-]\n\n Notes\n -----\n This can be useful to blend fittings at specific locations in a pipe into\n a pressure drop which is evenly distributed along a pipe.\n\n Examples\n --------\n >>> f_from_K(K=0.6, L=100., D=.3)\n 0.0018\n \"\"\"\n return K*D/L\n\ndef K_from_L_equiv(L_D: float, fd: float=0.015) -> float:\n r\"\"\"Calculates loss coefficient, for a given equivalent length (L/D).\n\n .. math::\n K = f_d \\frac{L}{D}\n\n Parameters\n ----------\n L_D : float\n Length over diameter, []\n fd : float, optional\n Darcy friction factor, [-]\n\n Returns\n -------\n K : float\n Loss coefficient, []\n\n Notes\n -----\n Almost identical to `K_from_f`, but with a default friction factor for\n fully turbulent flow in steel pipes.\n\n Examples\n --------\n >>> K_from_L_equiv(240)\n 3.5999999999999996\n \"\"\"\n return fd*L_D\n\ndef L_equiv_from_K(K: float, fd: float=0.015) -> float:\n r\"\"\"Calculates equivalent length of pipe (L/D), for a given loss\n coefficient.\n\n .. math::\n \\frac{L}{D} = \\frac{K}{f_d}\n\n Parameters\n ----------\n K : float\n Loss coefficient, [-]\n fd : float, optional\n Darcy friction factor, [-]\n\n Returns\n -------\n L_D : float\n Length over diameter, [-]\n\n Notes\n -----\n Assumes a default friction factor for fully turbulent flow in steel pipes.\n\n Examples\n --------\n >>> L_equiv_from_K(3.6)\n 240.00000000000003\n \"\"\"\n return K/fd\n\ndef L_from_K(K: float, D: float, fd: float=0.015) -> float:\n r\"\"\"Calculates the length of straight pipe at a specified friction factor\n required to produce a given loss coefficient `K`.\n\n .. math::\n L = \\frac{K D}{f_d}\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n D : float\n Inner diameter of pipe, [m]\n fd : float\n friction factor of pipe, []\n\n Returns\n -------\n L : float\n Length of pipe, [m]\n\n Examples\n --------\n >>> L_from_K(K=6, D=.3, fd=0.018)\n 100.0\n \"\"\"\n return K*D/fd\n\ndef dP_from_K(K: float, rho: float, V: float) -> float:\n r\"\"\"Calculates pressure drop, for a given loss coefficient,\n at a specified density and velocity.\n\n .. math::\n dP = 0.5K\\rho V^2\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n rho : float\n Density of fluid, [kg/m^3]\n V : float\n Velocity of fluid in pipe, [m/s]\n\n Returns\n -------\n dP : float\n Pressure drop, [Pa]\n\n Notes\n -----\n Loss coefficient `K` is usually the sum of several factors, including\n the friction factor.\n\n Examples\n --------\n >>> dP_from_K(K=10, rho=1000, V=3)\n 45000.0\n \"\"\"\n return K*0.5*rho*V*V\n\ndef head_from_K(K: float, V: float, g: float=g) -> float:\n r\"\"\"Calculates head loss, for a given loss coefficient,\n at a specified velocity.\n\n .. math::\n \\text{head} = \\frac{K V^2}{2g}\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n V : float\n Velocity of fluid in pipe, [m/s]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n head : float\n Head loss, [m]\n\n Notes\n -----\n Loss coefficient `K` is usually the sum of several factors, including\n the friction factor.\n\n Examples\n --------\n >>> head_from_K(K=10, V=1.5)\n 1.1471807396001694\n \"\"\"\n return K*0.5*V*V/g\n\ndef head_from_P(P: float, rho: float, g: float=g) -> float:\n r\"\"\"Calculates head for a fluid of specified density at specified\n pressure.\n\n .. math::\n \\text{head} = {P\\over{\\rho g}}\n\n Parameters\n ----------\n P : float\n Pressure fluid in pipe, [Pa]\n rho : float\n Density of fluid, [kg/m^3]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n head : float\n Head, [m]\n\n Notes\n -----\n By definition. Head varies with location, inversely proportional to the\n increase in gravitational constant.\n\n Examples\n --------\n >>> head_from_P(P=98066.5, rho=1000)\n 10.000000000000002\n \"\"\"\n return P/rho/g\n\ndef P_from_head(head: float, rho: float, g: float=g) -> float:\n r\"\"\"Calculates pressure for a fluid of specified density at specified\n head.\n\n .. math::\n P = \\rho g \\cdot \\text{head}\n\n Parameters\n ----------\n head : float\n Head, [m]\n rho : float\n Density of fluid, [kg/m^3]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n P : float\n Pressure fluid in pipe, [Pa]\n\n Notes\n -----\n\n Examples\n --------\n >>> P_from_head(head=5., rho=800.)\n 39226.6\n \"\"\"\n return head*rho*g\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 8864}, "tests/test_core.py::305": {"resolved_imports": ["fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["K_from_L_equiv", "K_from_f", "L_equiv_from_K", "L_from_K", "P_from_head", "assert_close", "assert_close1d", "dP_from_K", "f_from_K", "gravity", "head_from_K", "head_from_P", "nu_mu_converter", "pytest"], "enclosing_function": "test_core_misc2", "extracted_code": "# Source: fluids/core.py\ndef nu_mu_converter(rho: float, mu: float | None=None, nu: float | None=None) -> float:\n r\"\"\"Calculates either kinematic or dynamic viscosity, depending on inputs.\n Used when one type of viscosity is known as well as density, to obtain\n the other type. Raises an error if both types of viscosity or neither type\n of viscosity is provided.\n\n .. math::\n \\nu = \\frac{\\mu}{\\rho}\n\n .. math::\n \\mu = \\nu\\rho\n\n Parameters\n ----------\n rho : float\n Density, [kg/m^3]\n mu : float, optional\n Dynamic viscosity, [Pa*s]\n nu : float, optional\n Kinematic viscosity, [m^2/s]\n\n Returns\n -------\n mu or nu : float\n Dynamic viscosity, Pa*s or Kinematic viscosity, m^2/s\n\n Examples\n --------\n >>> nu_mu_converter(998., nu=1.0E-6)\n 0.000998\n\n References\n ----------\n .. [1] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and\n Applications. Boston: McGraw Hill Higher Education, 2006.\n \"\"\"\n if mu is not None and nu is None:\n return mu/rho\n elif nu is not None and mu is None:\n return nu*rho\n raise ValueError(\"Inputs must be rho and one of mu and nu.\")\n\ndef gravity(latitude: float, H: float) -> float:\n r\"\"\"Calculates local acceleration due to gravity `g` according to [1]_.\n Uses latitude and height to calculate `g`.\n\n .. math::\n g = 9.780356(1 + 0.0052885\\sin^2\\phi - 0.0000059\\sin^2(2\\phi))\n - 3.086\\times 10^{-6} H\n\n Parameters\n ----------\n latitude : float\n Degrees, [degrees]\n H : float\n Height above earth's surface [m]\n\n Returns\n -------\n g : float\n Acceleration due to gravity, [m/s^2]\n\n Notes\n -----\n Better models, such as EGM2008 exist.\n\n Examples\n --------\n >>> gravity(55, 1E4)\n 9.784151976863571\n\n References\n ----------\n .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of\n Chemistry and Physics. [Boca Raton, FL]: CRC press, 2014.\n \"\"\"\n lat = latitude*pi/180\n g = 9.780356*(1+0.0052885*sin(lat)**2 -0.0000059*sin(2*lat)**2)-3.086E-6*H\n return g\n\ndef K_from_f(fd: float, L: float, D: float) -> float:\n r\"\"\"Calculates loss coefficient, K, for a given section of pipe\n at a specified friction factor.\n\n .. math::\n K = f_dL/D\n\n Parameters\n ----------\n fd : float\n friction factor of pipe, []\n L : float\n Length of pipe, [m]\n D : float\n Inner diameter of pipe, [m]\n\n Returns\n -------\n K : float\n Loss coefficient, []\n\n Notes\n -----\n For fittings with a specified L/D ratio, use D = 1 and set L to\n specified L/D ratio.\n\n Examples\n --------\n >>> K_from_f(fd=0.018, L=100., D=.3)\n 6.0\n \"\"\"\n return fd*L/D\n\ndef f_from_K(K: float, L: float, D: float) -> float:\n r\"\"\"Calculates friction factor, `fd`, from a loss coefficient, K,\n for a given section of pipe.\n\n .. math::\n f_d = \\frac{K D}{L}\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n L : float\n Length of pipe, [m]\n D : float\n Inner diameter of pipe, [m]\n\n Returns\n -------\n fd : float\n Darcy friction factor of pipe, [-]\n\n Notes\n -----\n This can be useful to blend fittings at specific locations in a pipe into\n a pressure drop which is evenly distributed along a pipe.\n\n Examples\n --------\n >>> f_from_K(K=0.6, L=100., D=.3)\n 0.0018\n \"\"\"\n return K*D/L\n\ndef K_from_L_equiv(L_D: float, fd: float=0.015) -> float:\n r\"\"\"Calculates loss coefficient, for a given equivalent length (L/D).\n\n .. math::\n K = f_d \\frac{L}{D}\n\n Parameters\n ----------\n L_D : float\n Length over diameter, []\n fd : float, optional\n Darcy friction factor, [-]\n\n Returns\n -------\n K : float\n Loss coefficient, []\n\n Notes\n -----\n Almost identical to `K_from_f`, but with a default friction factor for\n fully turbulent flow in steel pipes.\n\n Examples\n --------\n >>> K_from_L_equiv(240)\n 3.5999999999999996\n \"\"\"\n return fd*L_D\n\ndef L_equiv_from_K(K: float, fd: float=0.015) -> float:\n r\"\"\"Calculates equivalent length of pipe (L/D), for a given loss\n coefficient.\n\n .. math::\n \\frac{L}{D} = \\frac{K}{f_d}\n\n Parameters\n ----------\n K : float\n Loss coefficient, [-]\n fd : float, optional\n Darcy friction factor, [-]\n\n Returns\n -------\n L_D : float\n Length over diameter, [-]\n\n Notes\n -----\n Assumes a default friction factor for fully turbulent flow in steel pipes.\n\n Examples\n --------\n >>> L_equiv_from_K(3.6)\n 240.00000000000003\n \"\"\"\n return K/fd\n\ndef L_from_K(K: float, D: float, fd: float=0.015) -> float:\n r\"\"\"Calculates the length of straight pipe at a specified friction factor\n required to produce a given loss coefficient `K`.\n\n .. math::\n L = \\frac{K D}{f_d}\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n D : float\n Inner diameter of pipe, [m]\n fd : float\n friction factor of pipe, []\n\n Returns\n -------\n L : float\n Length of pipe, [m]\n\n Examples\n --------\n >>> L_from_K(K=6, D=.3, fd=0.018)\n 100.0\n \"\"\"\n return K*D/fd\n\ndef dP_from_K(K: float, rho: float, V: float) -> float:\n r\"\"\"Calculates pressure drop, for a given loss coefficient,\n at a specified density and velocity.\n\n .. math::\n dP = 0.5K\\rho V^2\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n rho : float\n Density of fluid, [kg/m^3]\n V : float\n Velocity of fluid in pipe, [m/s]\n\n Returns\n -------\n dP : float\n Pressure drop, [Pa]\n\n Notes\n -----\n Loss coefficient `K` is usually the sum of several factors, including\n the friction factor.\n\n Examples\n --------\n >>> dP_from_K(K=10, rho=1000, V=3)\n 45000.0\n \"\"\"\n return K*0.5*rho*V*V\n\ndef head_from_K(K: float, V: float, g: float=g) -> float:\n r\"\"\"Calculates head loss, for a given loss coefficient,\n at a specified velocity.\n\n .. math::\n \\text{head} = \\frac{K V^2}{2g}\n\n Parameters\n ----------\n K : float\n Loss coefficient, []\n V : float\n Velocity of fluid in pipe, [m/s]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n head : float\n Head loss, [m]\n\n Notes\n -----\n Loss coefficient `K` is usually the sum of several factors, including\n the friction factor.\n\n Examples\n --------\n >>> head_from_K(K=10, V=1.5)\n 1.1471807396001694\n \"\"\"\n return K*0.5*V*V/g\n\ndef head_from_P(P: float, rho: float, g: float=g) -> float:\n r\"\"\"Calculates head for a fluid of specified density at specified\n pressure.\n\n .. math::\n \\text{head} = {P\\over{\\rho g}}\n\n Parameters\n ----------\n P : float\n Pressure fluid in pipe, [Pa]\n rho : float\n Density of fluid, [kg/m^3]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n head : float\n Head, [m]\n\n Notes\n -----\n By definition. Head varies with location, inversely proportional to the\n increase in gravitational constant.\n\n Examples\n --------\n >>> head_from_P(P=98066.5, rho=1000)\n 10.000000000000002\n \"\"\"\n return P/rho/g\n\ndef P_from_head(head: float, rho: float, g: float=g) -> float:\n r\"\"\"Calculates pressure for a fluid of specified density at specified\n head.\n\n .. math::\n P = \\rho g \\cdot \\text{head}\n\n Parameters\n ----------\n head : float\n Head, [m]\n rho : float\n Density of fluid, [kg/m^3]\n g : float, optional\n Acceleration due to gravity, [m/s^2]\n\n Returns\n -------\n P : float\n Pressure fluid in pipe, [Pa]\n\n Notes\n -----\n\n Examples\n --------\n >>> P_from_head(head=5., rho=800.)\n 39226.6\n \"\"\"\n return head*rho*g\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 8864}, "tests/test_design_climate.py::85": {"resolved_imports": ["fluids/design_climate.py", "fluids/numerics/__init__.py"], "used_names": ["get_latlongs", "get_stations"], "enclosing_function": "test_data", "extracted_code": "# Source: fluids/design_climate.py\ndef get_stations():\n \"\"\"Get the list of weather stations.\"\"\"\n if _stations is None:\n _load_station_data()\n return _stations\n\ndef get_latlongs():\n \"\"\"Get the array of station coordinates.\"\"\"\n if _latlongs is None:\n _load_station_data()\n return _latlongs", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 319}, "tests/test_flow_meter.py::220": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/flow_meter.py", "fluids/numerics/__init__.py"], "used_names": ["C_Miller_1996", "C_Reader_Harris_Gallagher", "MILLER_CONICAL_ORIFICE", "MILLER_ECCENTRIC_ORIFICE", "MILLER_ORIFICE", "MILLER_QUARTER_CIRCLE_ORIFICE", "MILLER_SEGMENTAL_ORIFICE", "ORIFICE_CORNER_TAPS", "ORIFICE_D_AND_D_2_TAPS", "ORIFICE_FLANGE_TAPS", "ORIFICE_PIPE_TAPS", "ORIFICE_VENA_CONTRACTA_TAPS", "TAPS_OPPOSITE", "TAPS_SIDE", "assert_close", "pytest"], "enclosing_function": "test_C_Miller_1996", "extracted_code": "# Source: fluids/flow_meter.py\nORIFICE_CORNER_TAPS = \"corner\"\n\nORIFICE_FLANGE_TAPS = \"flange\"\n\nORIFICE_D_AND_D_2_TAPS = \"D and D/2\"\n\nORIFICE_PIPE_TAPS = \"pipe\"\n\nORIFICE_VENA_CONTRACTA_TAPS = \"vena contracta\"\n\nTAPS_OPPOSITE = \"180 degree\"\n\nTAPS_SIDE = \"90 degree\"\n\nMILLER_ORIFICE = \"Miller orifice\"\n\nMILLER_ECCENTRIC_ORIFICE = \"Miller eccentric orifice\"\n\nMILLER_SEGMENTAL_ORIFICE = \"Miller segmental orifice\"\n\nMILLER_CONICAL_ORIFICE = \"Miller conical orifice\"\n\nMILLER_QUARTER_CIRCLE_ORIFICE = \"Miller quarter circle orifice\"\n\ndef C_Reader_Harris_Gallagher(D: float, Do: float, rho: float, mu: float, m: float, taps: str=\"corner\") -> float:\n r\"\"\"Calculates the coefficient of discharge of the orifice based on the\n geometry of the plate, measured pressures of the orifice, mass flow rate\n through the orifice, and the density and viscosity of the fluid.\n\n .. math::\n C = 0.5961 + 0.0261\\beta^2 - 0.216\\beta^8 + 0.000521\\left(\\frac{\n 10^6\\beta}{Re_D}\\right)^{0.7}\\\\\n + (0.0188 + 0.0063A)\\beta^{3.5} \\left(\\frac{10^6}{Re_D}\\right)^{0.3} \\\\\n +(0.043 + 0.080\\exp(-10L_1) -0.123\\exp(-7L_1))(1-0.11A)\\frac{\\beta^4}\n {1-\\beta^4} \\\\\n - 0.031(M_2' - 0.8M_2'^{1.1})\\beta^{1.3}\n\n .. math::\n M_2' = \\frac{2L_2'}{1-\\beta}\n\n .. math::\n A = \\left(\\frac{19000\\beta}{Re_{D}}\\right)^{0.8}\n\n .. math::\n Re_D = \\frac{\\rho v D}{\\mu}\n\n\n If D < 71.12 mm (2.8 in.) (Note this is a continuous addition; there is no\n discontinuity):\n\n .. math::\n C += 0.11(0.75-\\beta)\\left(2.8-\\frac{D}{0.0254}\\right)\n\n If the orifice has corner taps:\n\n .. math::\n L_1 = L_2' = 0\n\n If the orifice has D and D/2 taps:\n\n .. math::\n L_1 = 1\n\n .. math::\n L_2' = 0.47\n\n If the orifice has Flange taps:\n\n .. math::\n L_1 = L_2' = \\frac{0.0254}{D}\n\n Parameters\n ----------\n D : float\n Upstream internal pipe diameter, [m]\n Do : float\n Diameter of orifice at flow conditions, [m]\n rho : float\n Density of fluid at `P1`, [kg/m^3]\n mu : float\n Viscosity of fluid at `P1`, [Pa*s]\n m : float\n Mass flow rate of fluid through the orifice, [kg/s]\n taps : str\n The orientation of the taps; one of 'corner', 'flange', 'D', or 'D/2',\n [-]\n\n Returns\n -------\n C : float\n Coefficient of discharge of the orifice, [-]\n\n Notes\n -----\n The following limits apply to the orifice plate standard [1]_:\n\n The measured pressure difference for the orifice plate should be under\n 250 kPa.\n\n There are roughness limits as well; the roughness should be under 6\n micrometers, although there are many more conditions to that given in [1]_.\n\n For orifice plates with D and D/2 or corner pressure taps:\n\n * Orifice bore diameter must be larger than 12.5 mm (0.5 inches)\n * Pipe diameter between 50 mm and 1 m (2 to 40 inches)\n * Beta between 0.1 and 0.75 inclusive\n * Reynolds number larger than 5000 (for :math:`0.10 \\le \\beta \\le 0.56`)\n or for :math:`\\beta \\ge 0.56, Re_D \\ge 16000\\beta^2`\n\n For orifice plates with flange pressure taps:\n\n * Orifice bore diameter must be larger than 12.5 mm (0.5 inches)\n * Pipe diameter between 50 mm and 1 m (2 to 40 inches)\n * Beta between 0.1 and 0.75 inclusive\n * Reynolds number larger than 5000 and also larger than\n :math:`170000\\beta^2 D`.\n\n This is also presented in Crane's TP410 (2009) publication, whereas the\n 1999 and 1982 editions showed only a graph for discharge coefficients.\n\n Examples\n --------\n >>> C_Reader_Harris_Gallagher(D=0.07391, Do=0.0222, rho=1.165, mu=1.85E-5,\n ... m=0.12, taps='flange')\n 0.5990326277163659\n\n References\n ----------\n .. [1] American Society of Mechanical Engineers. Mfc-3M-2004 Measurement\n Of Fluid Flow In Pipes Using Orifice, Nozzle, And Venturi. ASME, 2001.\n .. [2] ISO 5167-2:2003 - Measurement of Fluid Flow by Means of Pressure\n Differential Devices Inserted in Circular Cross-Section Conduits Running\n Full -- Part 2: Orifice Plates.\n .. [3] Reader-Harris, M. J., \"The Equation for the Expansibility Factor for\n Orifice Plates,\" Proceedings of FLOMEKO 1998, Lund, Sweden, 1998:\n 209-214.\n .. [4] Reader-Harris, Michael. Orifice Plates and Venturi Tubes. Springer,\n 2015.\n \"\"\"\n A_pipe = 0.25*pi*D*D\n v = m/(A_pipe*rho)\n Re_D = rho*v*D/mu\n Re_D_inv = 1.0/Re_D\n\n beta = Do/D\n if taps == \"corner\":\n L1, L2_prime = 0.0, 0.0\n elif taps == \"flange\":\n L1 = L2_prime = 0.0254/D\n elif taps in (\"D\", \"D/2\", ORIFICE_D_AND_D_2_TAPS):\n L1 = 1.0\n L2_prime = 0.47\n else:\n raise ValueError(\"Unsupported tap location\")\n\n beta2 = beta*beta\n beta4 = beta2*beta2\n beta8 = beta4*beta4\n\n A = 2648.5177066967326*(beta*Re_D_inv)**0.8 # 19000.0^0.8 = 2648.51....\n M2_prime = 2.0*L2_prime/(1.0 - beta)\n\n # These two exps\n expnL1 = exp(-L1)\n expnL2 = expnL1*expnL1\n expnL3 = expnL1*expnL2\n delta_C_upstream = ((0.043 + expnL3*expnL2*expnL2*(0.080*expnL3 - 0.123))\n *(1.0 - 0.11*A)*beta4/(1.0 - beta4))\n\n # The max part is not in the ISO standard\n t1 = log10(3700.*Re_D_inv)\n if t1 < 0.0:\n t1 = 0.0\n delta_C_downstream = (-0.031*(M2_prime - 0.8*M2_prime**1.1)*beta**1.3\n *(1.0 + 8.0*t1))\n\n # C_inf is discharge coefficient with corner taps for infinite Re\n # Cs, slope term, provides increase in discharge coefficient for lower\n # Reynolds numbers.\n x1 = 63.095734448019314*(Re_D_inv)**0.3 # 63.095... = (1e6)**0.3\n x2 = 22.7 - 0.0047*Re_D\n t2 = max(x2, x1)\n # max term is not in the ISO standard\n C_inf_C_s = (0.5961 + 0.0261*beta2 - 0.216*beta8\n + 0.000521*(1E6*beta*Re_D_inv)**0.7\n + (0.0188 + 0.0063*A)*beta2*beta*sqrt(beta)*(\n t2))\n\n C = (C_inf_C_s + delta_C_upstream + delta_C_downstream)\n if D < 0.07112:\n # Limit is 2.8 inches, .1 inches smaller than the internal diameter of\n # a sched. 80 pipe.\n # Suggested to be required not because of any effect of small\n # diameters themselves, but because of edge radius differences.\n # max term is given in [4]_ Reader-Harris, Michael book\n # There is a check for t3 being negative and setting it to zero if so\n # in some sources but that only occurs when t3 is exactly the limit\n # (0.07112) so it is not needed\n t3 = (2.8 - D*inch_inv)\n delta_C_diameter = 0.011*(0.75 - beta)*t3\n C += delta_C_diameter\n\n return C\n\ndef C_Miller_1996(D: float, Do: float, rho: float, mu: float, m: float, subtype: str=\"orifice\",\n taps: str | None=ORIFICE_CORNER_TAPS, tap_position: str | None=TAPS_OPPOSITE) -> float:\n r\"\"\"Calculates the coefficient of discharge of any of the orifice types\n supported by the Miller (1996) [1]_ correlation set. These correlations\n cover a wide range of industrial applications and sizes. Most of them are\n functions of `beta` ratio and Reynolds number. Unlike the ISO standards,\n these correlations do not come with well defined ranges of validity, so\n caution should be applied using these correlations.\n\n The base equation is as follows, and each orifice type and range has\n different values or correlations for :math:`C_{\\infty}`, `b`, and `n`.\n\n .. math::\n C = C_{\\infty} + \\frac{b}{{Re}_D^n}\n\n Parameters\n ----------\n D : float\n Upstream internal pipe diameter, [m]\n Do : float\n Diameter of orifice at flow conditions, [m]\n rho : float\n Density of fluid at `P1`, [kg/m^3]\n mu : float\n Viscosity of fluid at `P1`, [Pa*s]\n m : float\n Mass flow rate of fluid through the orifice, [kg/s]\n subtype : str, optional\n One of 'orifice', 'eccentric orifice', 'segmental orifice',\n 'conical orifice', or 'quarter circle orifice', [-]\n taps : str, optional\n The orientation of the taps; one of 'corner', 'flange',\n 'D and D/2', 'pipe', or 'vena contracta'; not all orifice subtypes\n support all tap types [-]\n tap_position : str, optional\n The rotation of the taps, used **only for the eccentric orifice case**\n where the pressure profiles are not symmetric; '180 degree' for the\n normal case where the taps are opposite the orifice bore, and\n '90 degree' for the case where, normally for operational reasons, the\n taps are near the bore [-]\n\n Returns\n -------\n C : float\n Coefficient of discharge of the orifice, [-]\n\n Notes\n -----\n Many of the correlations transition at a pipe diameter of 100 mm to\n different equations, which will lead to discontinuous behavior.\n\n It should also be noted the author of these correlations developed a\n commercial flow meter rating software package, at [2]_.\n He passed away in 2014, but contributed massively to the field of flow\n measurement.\n\n The numerous equations for the different cases are as follows:\n\n For all **regular (concentric) orifices**, the `b` equation is as follows\n and n = 0.75:\n\n .. math::\n b = 91.706\\beta^{2.5}\n\n Regular (concentric) orifice, corner taps:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.0312\\beta^2.1 - 0.184\\beta^8\n\n Regular (concentric) orifice, flange taps, D > 58.4 mm:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.0312\\beta^{2.1} - 0.184\\beta^8\n + \\frac{2.286\\beta^4}{(D_{mm}(1.0 - \\beta^4))}\n - \\frac{0.856\\beta^3}{D_{mm}}\n\n Regular (concentric) orifice, flange taps, D < 58.4 mm:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.0312\\beta^{2.1} - 0.184\\beta^8\n + \\frac{0.039\\beta^4}{(1.0 - \\beta^4)} - \\frac{0.856\\beta^3}{D_{mm}}\n\n Regular (concentric) orifice, 'D and D/2' taps:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.0312\\beta^{2.1} - 0.184\\beta^8\n + \\frac{0.039\\beta^4}{(1.0 - \\beta^4)} - 0.01584\n\n Regular (concentric) orifice, 'pipe' taps:\n\n .. math::\n C_{\\infty} = 0.5959 + 0.461\\beta^{2.1} + 0.48\\beta^8\n + \\frac{0.039\\beta^4}{(1.0 - \\beta^4)}\n\n For the case of a **conical orifice**, there is no tap dependence\n and one equation (`b` = 0, `n` = 0):\n\n .. math::\n C_{\\infty} = 0.734 \\text{ if } 250\\beta \\le Re \\le 500\\beta \\text{ else } 0.730\n\n For the case of a **quarter circle orifice**, corner and flange taps have\n the same dependence (`b` = 0, `n` = 0):\n\n .. math::\n C_{\\infty} = (0.7746 - 0.1334\\beta^{2.1} + 1.4098\\beta^8\n + \\frac{0.0675\\beta^4}{(1 - \\beta^4)} + 0.3865\\beta^3)\n\n For all **segmental orifice** types, `b` = 0 and `n` = 0\n\n Segmental orifice, 'flange' taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.6284 + 0.1462\\beta^{2.1} - 0.8464\\beta^8\n + \\frac{0.2603\\beta^4}{(1-\\beta^4)} - 0.2886\\beta^3\n\n Segmental orifice, 'flange' taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.6276 + 0.0828\\beta^{2.1} + 0.2739\\beta^8\n - \\frac{0.0934\\beta^4}{(1-\\beta^4)} - 0.1132\\beta^3\n\n Segmental orifice, 'vena contracta' taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.6261 + 0.1851\\beta^{2.1} - 0.2879\\beta^8\n + \\frac{0.1170\\beta^4}{(1-\\beta^4)} - 0.2845\\beta^3\n\n Segmental orifice, 'vena contracta' taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.6276 + 0.0828\\beta^{2.1} + 0.2739\\beta^8\n - \\frac{0.0934\\beta^4}{(1-\\beta^4)} - 0.1132\\beta^3\n\n For all **eccentric orifice** types, `n` = 0.75 and `b` is fit to a\n polynomial of `beta`.\n\n Eccentric orifice, 'flange' taps, 180 degree opposite taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.5917 + 0.3061\\beta^{2.1} + .3406\\beta^8 -\\frac{.1019\\beta^4}{(1-\\beta^4)} - 0.2715\\beta^3\n\n .. math::\n b = 7.3 - 15.7\\beta + 170.8\\beta^2 - 399.7\\beta^3 + 332.2\\beta^4\n\n Eccentric orifice, 'flange' taps, 180 degree opposite taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.6016 + 0.3312\\beta^{2.1} -1.5581\\beta^8 + \\frac{0.6510\\beta^4}{(1-\\beta^4)} - 0.7308\\beta^3\n\n .. math::\n b = -139.7 + 1328.8\\beta - 4228.2\\beta^2 + 5691.9\\beta^3 - 2710.4\\beta^4\n\n Eccentric orifice, 'flange' taps, 90 degree side taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.5866 + 0.3917\\beta^{2.1} + .7586\\beta^8 - \\frac{.2273\\beta^4}{(1-\\beta^4)} - .3343\\beta^3\n\n .. math::\n b = 69.1 - 469.4\\beta + 1245.6\\beta^2 -1287.5\\beta^3 + 486.2\\beta^4\n\n Eccentric orifice, 'flange' taps, 90 degree side taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.6037 + 0.1598\\beta^{2.1} -.2918\\beta^8 + \\frac{0.0244\\beta^4}{(1-\\beta^4)} - 0.0790\\beta^3\n\n .. math::\n b = -103.2 + 898.3\\beta - 2557.3\\beta^2 + 2977.0\\beta^3 - 1131.3\\beta^4\n\n Eccentric orifice, 'vena contracta' taps, 180 degree opposite taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.5925 + 0.3380\\beta^{2.1} + 0.4016\\beta^8 - \\frac{.1046\\beta^4}{(1-\\beta^4)} - 0.3212\\beta^3\n\n .. math::\n b = 23.3 -207.0\\beta + 821.5\\beta^2 -1388.6\\beta^3 + 900.3\\beta^4\n\n Eccentric orifice, 'vena contracta' taps, 180 degree opposite taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.5922 + 0.3932\\beta^{2.1} + .3412\\beta^8 - \\frac{.0569\\beta^4}{(1-\\beta^4)} - 0.4628\\beta^3\n\n .. math::\n b = 55.7 - 471.4\\beta + 1721.8\\beta^2 - 2722.6\\beta^3 + 1569.4\\beta^4\n\n Eccentric orifice, 'vena contracta' taps, 90 degree side taps, D < 10 cm:\n\n .. math::\n C_{\\infty} = 0.5875 + 0.3813\\beta^{2.1} + 0.6898\\beta^8 - \\frac{0.1963\\beta^4}{(1-\\beta^4)} - 0.3366\\beta^3\n\n .. math::\n b = -69.3 + 556.9\\beta - 1332.2\\beta^2 + 1303.7\\beta^3 - 394.8\\beta^4\n\n Eccentric orifice, 'vena contracta' taps, 90 degree side taps, D > 10 cm:\n\n .. math::\n C_{\\infty} = 0.5949 + 0.4078\\beta^{2.1} + 0.0547\\beta^8 + \\frac{0.0955\\beta^4}{(1-\\beta^4)} - 0.5608\\beta^3\n\n .. math::\n b = 52.8 - 434.2\\beta + 1571.2\\beta^2 - 2460.9\\beta^3 + 1420.2\\beta^4\n\n\n Examples\n --------\n >>> C_Miller_1996(D=0.07391, Do=0.0222, rho=1.165, mu=1.85E-5, m=0.12, taps='flange', subtype='orifice')\n 0.599065557156788\n\n References\n ----------\n .. [1] Miller, Richard W. Flow Measurement Engineering Handbook.\n McGraw-Hill Education, 1996.\n .. [2] \"RW Miller & Associates.\" Accessed April 13, 2020.\n http://rwmillerassociates.com/.\n \"\"\"\n A_pipe = 0.25*pi*D*D\n v = m/(A_pipe*rho)\n Re = rho*v*D/mu\n D_mm = D*1000.0\n\n beta = Do/D\n beta2 = beta*beta\n beta3 = beta2*beta\n beta4 = beta*beta3\n beta8 = beta4*beta4\n beta21 = beta**2.1\n\n if subtype in (MILLER_ORIFICE, CONCENTRIC_ORIFICE):\n b = 91.706*beta2*sqrt(beta)\n n = 0.75\n if taps == ORIFICE_CORNER_TAPS:\n C_inf = 0.5959 + 0.0312*beta21 - 0.184*beta8\n elif taps == ORIFICE_FLANGE_TAPS:\n if D_mm >= 58.4:\n C_inf = 0.5959 + 0.0312*beta21 - 0.184*beta8 + 2.286*beta4/(D_mm*(1.0 - beta4)) - 0.856*beta3/D_mm\n else:\n C_inf = 0.5959 + 0.0312*beta21 - 0.184*beta8 + 0.039*beta4/(1.0 - beta4) - 0.856*beta3/D_mm\n elif taps == ORIFICE_D_AND_D_2_TAPS:\n C_inf = 0.5959 + 0.0312*beta21 - 0.184*beta8 + 0.039*beta4/(1.0 - beta4) - 0.01584\n elif taps == ORIFICE_PIPE_TAPS:\n C_inf = 0.5959 + 0.461*beta21 + 0.48*beta8 + 0.039*beta4/(1.0 - beta4)\n else:\n raise ValueError(_Miller_1996_unsupported_tap_concentric)\n elif subtype in (MILLER_ECCENTRIC_ORIFICE, ECCENTRIC_ORIFICE):\n if tap_position not in (TAPS_OPPOSITE, TAPS_SIDE):\n raise ValueError(_Miller_1996_unsupported_tap_pos_eccentric)\n n = 0.75\n if taps == ORIFICE_FLANGE_TAPS:\n if tap_position == TAPS_OPPOSITE:\n if D < 0.1:\n b = 7.3 - 15.7*beta + 170.8*beta2 - 399.7*beta3 + 332.2*beta4\n C_inf = 0.5917 + 0.3061*beta21 + 0.3406*beta8 - 0.1019*beta4/(1.0-beta4) - 0.2715*beta3\n else:\n b = -139.7 + 1328.8*beta - 4228.2*beta2 + 5691.9*beta3 - 2710.4*beta4\n C_inf = 0.6016 + 0.3312*beta21 - 1.5581*beta8 + 0.6510*beta4/(1.0-beta4) - 0.7308*beta3\n elif tap_position == TAPS_SIDE:\n if D < 0.1:\n b = 69.1 - 469.4*beta + 1245.6*beta2 -1287.5*beta3 + 486.2*beta4\n C_inf = 0.5866 + 0.3917*beta21 + 0.7586*beta8 - 0.2273*beta4/(1.0-beta4) - 0.3343*beta3\n else:\n b = -103.2 + 898.3*beta - 2557.3*beta2 + 2977.0*beta3 - 1131.3*beta4\n C_inf = 0.6037 + 0.1598*beta21 - 0.2918*beta8 + 0.0244*beta4/(1.0-beta4) - 0.0790*beta3\n elif taps == ORIFICE_VENA_CONTRACTA_TAPS:\n if tap_position == TAPS_OPPOSITE:\n if D < 0.1:\n b = 23.3 -207.0*beta + 821.5*beta2 -1388.6*beta3 + 900.3*beta4\n C_inf = 0.5925 + 0.3380*beta21 + 0.4016*beta8 - 0.1046*beta4/(1.0-beta4) - 0.3212*beta3\n else:\n b = 55.7 - 471.4*beta + 1721.8*beta2 - 2722.6*beta3 + 1569.4*beta4\n C_inf = 0.5922 + 0.3932*beta21 + 0.3412*beta8 - 0.0569*beta4/(1.0-beta4) - 0.4628*beta3\n elif tap_position == TAPS_SIDE:\n if D < 0.1:\n b = -69.3 + 556.9*beta - 1332.2*beta2 + 1303.7*beta3 - 394.8*beta4\n C_inf = 0.5875 + 0.3813*beta21 + 0.6898*beta8 - 0.1963*beta4/(1.0-beta4) - 0.3366*beta3\n else:\n b = 52.8 - 434.2*beta + 1571.2*beta2 - 2460.9*beta3 + 1420.2*beta4\n C_inf = 0.5949 + 0.4078*beta21 + 0.0547*beta8 + 0.0955*beta4/(1.0-beta4) - 0.5608*beta3\n else:\n raise ValueError(_Miller_1996_unsupported_tap_eccentric)\n elif subtype in (MILLER_SEGMENTAL_ORIFICE, SEGMENTAL_ORIFICE):\n n = b = 0.0\n if taps == ORIFICE_FLANGE_TAPS:\n if D < 0.1:\n C_inf = 0.6284 + 0.1462*beta21 - 0.8464*beta8 + 0.2603*beta4/(1.0-beta4) - 0.2886*beta3\n else:\n C_inf = 0.6276 + 0.0828*beta21 + 0.2739*beta8 - 0.0934*beta4/(1.0-beta4) - 0.1132*beta3\n elif taps == ORIFICE_VENA_CONTRACTA_TAPS:\n if D < 0.1:\n C_inf = 0.6261 + 0.1851*beta21 - 0.2879*beta8 + 0.1170*beta4/(1.0-beta4) - 0.2845*beta3\n else:\n # Yes these are supposed to be the same as the flange, large set\n C_inf = 0.6276 + 0.0828*beta21 + 0.2739*beta8 - 0.0934*beta4/(1.0-beta4) - 0.1132*beta3\n else:\n raise ValueError(_Miller_1996_unsupported_tap_segmental)\n elif subtype in (MILLER_CONICAL_ORIFICE, CONICAL_ORIFICE):\n n = b = 0.0\n if 250.0*beta <= Re <= 500.0*beta:\n C_inf = 0.734\n else:\n C_inf = 0.730\n elif subtype in (MILLER_QUARTER_CIRCLE_ORIFICE, QUARTER_CIRCLE_ORIFICE):\n n = b = 0.0\n C_inf = (0.7746 - 0.1334*beta21 + 1.4098*beta8\n + 0.0675*beta4/(1.0 - beta4) + 0.3865*beta3)\n else:\n raise ValueError(_Miller_1996_unsupported_type)\n C = C_inf + b*Re**-n\n return C\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 19793}, "tests/test_flow_meter.py::882": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/flow_meter.py", "fluids/numerics/__init__.py"], "used_names": ["CONCENTRIC_ORIFICE", "HOLLINGSHEAD_CONE", "HOLLINGSHEAD_ORIFICE", "HOLLINGSHEAD_VENTURI_SHARP", "HOLLINGSHEAD_VENTURI_SMOOTH", "HOLLINGSHEAD_WEDGE", "ISO_15377_CONICAL_ORIFICE", "ISO_15377_ECCENTRIC_ORIFICE", "ISO_15377_QUARTER_CIRCLE_ORIFICE", "MILLER_CONICAL_ORIFICE", "MILLER_ORIFICE", "assert_close", "differential_pressure_meter_C_epsilon", "pytest"], "enclosing_function": "test_differential_pressure_meter_C_epsilon", "extracted_code": "# Source: fluids/flow_meter.py\nCONCENTRIC_ORIFICE = \"orifice\"\n\nISO_15377_ECCENTRIC_ORIFICE = \"ISO 15377 eccentric orifice\"\n\nISO_15377_QUARTER_CIRCLE_ORIFICE = \"ISO 15377 quarter-circle orifice\"\n\nISO_15377_CONICAL_ORIFICE = \"ISO 15377 conical orifice\"\n\nMILLER_ORIFICE = \"Miller orifice\"\n\nMILLER_CONICAL_ORIFICE = \"Miller conical orifice\"\n\nHOLLINGSHEAD_ORIFICE = \"Hollingshead orifice\"\n\nHOLLINGSHEAD_VENTURI_SMOOTH = \"Hollingshead venturi smooth\"\n\nHOLLINGSHEAD_VENTURI_SHARP = \"Hollingshead venturi sharp\"\n\nHOLLINGSHEAD_CONE = \"Hollingshead v cone\"\n\nHOLLINGSHEAD_WEDGE = \"Hollingshead wedge\"\n\ndef differential_pressure_meter_C_epsilon(D: float, D2: float, m: float, P1: float, P2: float, rho: float, mu: float, k: float,\n meter_type: str, taps: str | None=None,\n tap_position: str | None=None, C_specified: float | None=None,\n epsilon_specified: int | None=None) -> tuple[float, float] | tuple[float, int]:\n r\"\"\"Calculates the discharge coefficient and expansibility of a flow\n meter given the mass flow rate, the upstream pressure, the second\n pressure value, and the orifice diameter for a differential\n pressure flow meter based on the geometry of the meter, measured pressures\n of the meter, and the density, viscosity, and isentropic exponent of the\n fluid.\n\n Parameters\n ----------\n D : float\n Upstream internal pipe diameter, [m]\n D2 : float\n Diameter of orifice, or venturi meter orifice, or flow tube orifice,\n or cone meter end diameter, or wedge meter fluid flow height, [m]\n m : float\n Mass flow rate of fluid through the flow meter, [kg/s]\n P1 : float\n Static pressure of fluid upstream of differential pressure meter at the\n cross-section of the pressure tap, [Pa]\n P2 : float\n Static pressure of fluid downstream of differential pressure meter or\n at the prescribed location (varies by type of meter) [Pa]\n rho : float\n Density of fluid at `P1`, [kg/m^3]\n mu : float\n Viscosity of fluid at `P1`, [Pa*s]\n k : float\n Isentropic exponent of fluid, [-]\n meter_type : str\n One of {'conical orifice', 'orifice', 'machined convergent venturi tube',\n 'ISO 5167 orifice', 'Miller quarter circle orifice', 'Hollingshead venturi sharp',\n 'segmental orifice', 'Miller conical orifice', 'Miller segmental orifice',\n 'quarter circle orifice', 'Hollingshead v cone', 'wedge meter', 'eccentric orifice',\n 'venturi nozzle', 'rough welded convergent venturi tube', 'ISA 1932 nozzle',\n 'ISO 15377 quarter-circle orifice', 'Hollingshead venturi smooth',\n 'Hollingshead orifice', 'cone meter', 'Hollingshead wedge', 'Miller orifice',\n 'long radius nozzle', 'ISO 15377 conical orifice', 'unspecified meter',\n 'as cast convergent venturi tube', 'Miller eccentric orifice',\n 'ISO 15377 eccentric orifice'}, [-]\n taps : str, optional\n The orientation of the taps; one of 'corner', 'flange', 'D', or 'D/2';\n applies for orifice meters only, [-]\n tap_position : str, optional\n The rotation of the taps, used **only for the eccentric orifice case**\n where the pressure profiles are not symmetric; '180 degree' for the\n normal case where the taps are opposite the orifice bore, and\n '90 degree' for the case where, normally for operational reasons, the\n taps are near the bore [-]\n C_specified : float, optional\n If specified, the correlation for the meter type is not used - this\n value is returned for `C`\n epsilon_specified : float, optional\n If specified, the correlation for the fluid expansibility is not used -\n this value is returned for :math:`\\epsilon`, [-]\n\n Returns\n -------\n C : float\n Coefficient of discharge of the specified flow meter type at the\n specified conditions, [-]\n expansibility : float\n Expansibility factor (1 for incompressible fluids, less than 1 for\n real fluids), [-]\n\n Notes\n -----\n This function should be called by an outer loop when solving for a\n variable.\n\n The latest ISO formulations for `expansibility` are used with the Miller\n correlations.\n\n Examples\n --------\n >>> differential_pressure_meter_C_epsilon(D=0.07366, D2=0.05, P1=200000.0,\n ... P2=183000.0, rho=999.1, mu=0.0011, k=1.33, m=7.702338035732168,\n ... meter_type='ISO 5167 orifice', taps='D')\n (0.6151252900244296, 0.9711026966676307)\n \"\"\"\n # Translate default meter type to implementation specific correlation\n if meter_type == CONCENTRIC_ORIFICE:\n meter_type = ISO_5167_ORIFICE\n elif meter_type == ECCENTRIC_ORIFICE:\n meter_type = ISO_15377_ECCENTRIC_ORIFICE\n elif meter_type == CONICAL_ORIFICE:\n meter_type = ISO_15377_CONICAL_ORIFICE\n elif meter_type == QUARTER_CIRCLE_ORIFICE:\n meter_type = ISO_15377_QUARTER_CIRCLE_ORIFICE\n elif meter_type == SEGMENTAL_ORIFICE:\n meter_type = MILLER_SEGMENTAL_ORIFICE\n\n if meter_type == ISO_5167_ORIFICE:\n taps_val = taps if taps is not None else \"corner\"\n C = C_Reader_Harris_Gallagher(D, D2, rho, mu, m, taps_val)\n epsilon = orifice_expansibility(D, D2, P1, P2, k)\n elif meter_type == ISO_15377_ECCENTRIC_ORIFICE:\n C = C_eccentric_orifice_ISO_15377_1998(D, D2)\n epsilon = orifice_expansibility(D, D2, P1, P2, k)\n elif meter_type == ISO_15377_QUARTER_CIRCLE_ORIFICE:\n C = C_quarter_circle_orifice_ISO_15377_1998(D, D2)\n epsilon = orifice_expansibility(D, D2, P1, P2, k)\n elif meter_type == ISO_15377_CONICAL_ORIFICE:\n C = ISO_15377_CONICAL_ORIFICE_C\n # Average of concentric square edge orifice and ISA 1932 nozzles\n epsilon = 0.5*(orifice_expansibility(D, D2, P1, P2, k)\n + nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k))\n\n elif meter_type in (MILLER_ORIFICE, MILLER_ECCENTRIC_ORIFICE,\n MILLER_SEGMENTAL_ORIFICE, MILLER_QUARTER_CIRCLE_ORIFICE):\n C = C_Miller_1996(D, D2, rho, mu, m, subtype=meter_type, taps=taps,\n tap_position=tap_position)\n epsilon = orifice_expansibility(D, D2, P1, P2, k)\n elif meter_type == MILLER_CONICAL_ORIFICE:\n C = C_Miller_1996(D, D2, rho, mu, m, subtype=meter_type, taps=taps,\n tap_position=tap_position)\n epsilon = 0.5*(orifice_expansibility(D, D2, P1, P2, k)\n + nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k))\n elif meter_type == LONG_RADIUS_NOZZLE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = C_long_radius_nozzle(D=D, Do=D2, rho=rho, mu=mu, m=m)\n elif meter_type == ISA_1932_NOZZLE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = C_ISA_1932_nozzle(D=D, Do=D2, rho=rho, mu=mu, m=m)\n elif meter_type == VENTURI_NOZZLE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = C_venturi_nozzle(D=D, Do=D2)\n\n elif meter_type == AS_CAST_VENTURI_TUBE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = AS_CAST_VENTURI_TUBE_C\n elif meter_type == MACHINED_CONVERGENT_VENTURI_TUBE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = MACHINED_CONVERGENT_VENTURI_TUBE_C\n elif meter_type == ROUGH_WELDED_CONVERGENT_VENTURI_TUBE:\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n C = ROUGH_WELDED_CONVERGENT_VENTURI_TUBE_C\n\n elif meter_type == CONE_METER:\n epsilon = cone_meter_expansibility_Stewart(D=D, Dc=D2, P1=P1, P2=P2, k=k)\n C = CONE_METER_C\n elif meter_type == WEDGE_METER:\n beta = diameter_ratio_wedge_meter(D=D, H=D2)\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k, beta=beta)\n C = C_wedge_meter_ISO_5167_6_2017(D=D, H=D2)\n elif meter_type == HOLLINGSHEAD_ORIFICE:\n v = m/((0.25*pi*D*D)*rho)\n Re_D = rho*v*D/mu\n C = float(bisplev(D2/D, log(Re_D), orifice_std_Hollingshead_tck))\n epsilon = orifice_expansibility(D, D2, P1, P2, k)\n elif meter_type == HOLLINGSHEAD_VENTURI_SMOOTH:\n v = m/((0.25*pi*D*D)*rho)\n Re_D = rho*v*D/mu\n C = interp(log(Re_D), venturi_logRes_Hollingshead, venturi_smooth_Cs_Hollingshead, extrapolate=True)\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n elif meter_type == HOLLINGSHEAD_VENTURI_SHARP:\n v = m/((0.25*pi*D*D)*rho)\n Re_D = rho*v*D/mu\n C = interp(log(Re_D), venturi_logRes_Hollingshead, venturi_sharp_Cs_Hollingshead, extrapolate=True)\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k)\n elif meter_type == HOLLINGSHEAD_CONE:\n v = m/((0.25*pi*D*D)*rho)\n Re_D = rho*v*D/mu\n beta = diameter_ratio_cone_meter(D, D2)\n C = float(bisplev(beta, log(Re_D), cone_Hollingshead_tck))\n epsilon = cone_meter_expansibility_Stewart(D=D, Dc=D2, P1=P1, P2=P2, k=k)\n elif meter_type == HOLLINGSHEAD_WEDGE:\n v = m/((0.25*pi*D*D)*rho)\n Re_D = rho*v*D/mu\n beta = diameter_ratio_wedge_meter(D=D, H=D2)\n C = float(bisplev(beta, log(Re_D), wedge_Hollingshead_tck))\n epsilon = nozzle_expansibility(D=D, Do=D2, P1=P1, P2=P2, k=k, beta=beta)\n elif meter_type == UNSPECIFIED_METER:\n epsilon = orifice_expansibility(D, D2, P1, P2, k) # Default to orifice type expansibility\n if C_specified is None:\n raise ValueError(\"For unspecified meter type, C_specified is required\")\n else:\n raise ValueError(_unsupported_meter_msg)\n if C_specified is not None:\n C = C_specified\n if epsilon_specified is not None:\n epsilon = epsilon_specified\n return C, epsilon\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 10525}, "tests/test_flow_meter.py::269": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/flow_meter.py", "fluids/numerics/__init__.py"], "used_names": ["AS_CAST_VENTURI_TUBE", "CONE_METER", "ISA_1932_NOZZLE", "ISO_5167_ORIFICE", "LONG_RADIUS_NOZZLE", "MACHINED_CONVERGENT_VENTURI_TUBE", "ROUGH_WELDED_CONVERGENT_VENTURI_TUBE", "VENTURI_NOZZLE", "WEDGE_METER", "assert_close", "differential_pressure_meter_solver"], "enclosing_function": "test_differential_pressure_meter_diameter", "extracted_code": "# Source: fluids/flow_meter.py\nISO_5167_ORIFICE = \"ISO 5167 orifice\"\n\nLONG_RADIUS_NOZZLE = \"long radius nozzle\"\n\nISA_1932_NOZZLE = \"ISA 1932 nozzle\"\n\nVENTURI_NOZZLE = \"venturi nozzle\"\n\nAS_CAST_VENTURI_TUBE = \"as cast convergent venturi tube\"\n\nMACHINED_CONVERGENT_VENTURI_TUBE = \"machined convergent venturi tube\"\n\nROUGH_WELDED_CONVERGENT_VENTURI_TUBE = \"rough welded convergent venturi tube\"\n\nCONE_METER = \"cone meter\"\n\nWEDGE_METER = \"wedge meter\"\n\ndef differential_pressure_meter_solver(D: float, rho: float, mu: float, k: float | None=None, D2: float | None=None, P1: float | None=None, P2: float | None=None,\n m: float | None=None, meter_type: str=ISO_5167_ORIFICE,\n taps: str | None=None, tap_position: str | None=None,\n C_specified: float | None=None, epsilon_specified: int | None=None) -> float:\n r\"\"\"Calculates either the mass flow rate, the upstream pressure, the second\n pressure value, or the orifice diameter for a differential\n pressure flow meter based on the geometry of the meter, measured pressures\n of the meter, and the density, viscosity, and isentropic exponent of the\n fluid. This solves an equation iteratively to obtain the correct flow rate.\n\n Parameters\n ----------\n D : float\n Upstream internal pipe diameter, [m]\n rho : float\n Density of fluid at `P1`, [kg/m^3]\n mu : float\n Viscosity of fluid at `P1`, [Pa*s]\n k : float, optional\n Isentropic exponent of fluid; required unless `epsilon_specified` is\n specified , [-]\n D2 : float, optional\n Diameter of orifice, or venturi meter orifice, or flow tube orifice,\n or cone meter end diameter, or wedge meter fluid flow height, [m]\n P1 : float, optional\n Static pressure of fluid upstream of differential pressure meter at the\n cross-section of the pressure tap, [Pa]\n P2 : float, optional\n Static pressure of fluid downstream of differential pressure meter or\n at the prescribed location (varies by type of meter) [Pa]\n m : float, optional\n Mass flow rate of fluid through the flow meter, [kg/s]\n meter_type : str\n One of {'conical orifice', 'orifice', 'machined convergent venturi tube',\n 'ISO 5167 orifice', 'Miller quarter circle orifice', 'Hollingshead venturi sharp',\n 'segmental orifice', 'Miller conical orifice', 'Miller segmental orifice',\n 'quarter circle orifice', 'Hollingshead v cone', 'wedge meter', 'eccentric orifice',\n 'venturi nozzle', 'rough welded convergent venturi tube', 'ISA 1932 nozzle',\n 'ISO 15377 quarter-circle orifice', 'Hollingshead venturi smooth',\n 'Hollingshead orifice', 'cone meter', 'Hollingshead wedge', 'Miller orifice',\n 'long radius nozzle', 'ISO 15377 conical orifice', 'unspecified meter',\n 'as cast convergent venturi tube', 'Miller eccentric orifice',\n 'ISO 15377 eccentric orifice'}, [-]\n taps : str, optional\n The orientation of the taps; one of 'corner', 'flange', 'D', or 'D/2';\n applies for orifice meters only, [-]\n tap_position : str, optional\n The rotation of the taps, used **only for the eccentric orifice case**\n where the pressure profiles are not symmetric; '180 degree' for the\n normal case where the taps are opposite the orifice bore, and\n '90 degree' for the case where, normally for operational reasons, the\n taps are near the bore [-]\n C_specified : float, optional\n If specified, the correlation for the meter type is not used - this\n value is used for `C`\n epsilon_specified : float, optional\n If specified, the correlation for the fluid expansibility is not used -\n this value is used for :math:`\\epsilon`. Many publications recommend\n this be set to 1 for incompressible fluids [-]\n\n Returns\n -------\n ans : float\n One of `m`, the mass flow rate of the fluid; `P1`, the pressure\n upstream of the flow meter; `P2`, the second pressure\n tap's value; and `D2`, the diameter of the measuring device; units\n of respectively, kg/s, Pa, Pa, or m\n\n Notes\n -----\n See the appropriate functions for the documentation for the formulas and\n references used in each method.\n\n The solvers make some assumptions about the range of values answers may be\n in.\n\n Note that the solver for the upstream pressure uses the provided values of\n density, viscosity and isentropic exponent; whereas these values all\n depend on pressure (albeit to a small extent). An outer loop should be\n added with pressure-dependent values calculated in it for maximum accuracy.\n\n It would be possible to solve for the upstream pipe diameter, but there is\n no use for that functionality.\n\n If a meter has already been calibrated to have a known `C`, this may be\n provided and it will be used in place of calculating one.\n\n Examples\n --------\n >>> differential_pressure_meter_solver(D=0.07366, D2=0.05, P1=200000.0,\n ... P2=183000.0, rho=999.1, mu=0.0011, k=1.33,\n ... meter_type='ISO 5167 orifice', taps='D')\n 7.70233803573\n\n >>> differential_pressure_meter_solver(D=0.07366, m=7.702338, P1=200000.0,\n ... P2=183000.0, rho=999.1, mu=0.0011, k=1.33,\n ... meter_type='ISO 5167 orifice', taps='D')\n 0.0499999999\n \"\"\"\n if k is None and epsilon_specified is not None:\n k = 1.4\n if m is None and D is not None and D2 is not None and P1 is not None and P2 is not None:\n # Initialize via analytical formulas\n C_guess = 0.7\n D4 = D*D\n D4 *= D4\n D24 = D2*D2\n D24 *= D24\n m_guess = root_two*pi*C_guess*D2*D2*sqrt(D4*rho*(P1 - P2)/(D4 - D24))*0.25\n m_D_guess = m_guess/D\n # Diameter to mass flow ratio\n # m_D_guess = 40\n # if rho < 100.0:\n # m_D_guess *= 1e-2\n return secant(err_dp_meter_solver_m, m_D_guess, args=(D, D2, P1, P2, rho, mu, k, meter_type, taps, tap_position, C_specified, epsilon_specified), low=1e-40)*D\n elif D2 is None and D is not None and m is not None and P1 is not None and P2 is not None:\n args = (D, m, P1, P2, rho, mu, k, meter_type, taps, tap_position, C_specified, epsilon_specified)\n try:\n try:\n return secant(err_dp_meter_solver_D2, D*.3, args=args, high=D, low=D*1e-10, bisection=True)\n except:\n return secant(err_dp_meter_solver_D2, D*.75, args=args, high=D, low=D*1e-10, bisection=True)\n except:\n return brenth(err_dp_meter_solver_D2, D*(1-1E-9), D*5E-3, args=args)\n elif P2 is None and D is not None and D2 is not None and m is not None and P1 is not None:\n args = (D, D2, m, P1, rho, mu, k, meter_type, taps, tap_position, C_specified, epsilon_specified)\n try:\n try:\n return secant(err_dp_meter_solver_P2, P1*0.9, low=P1*0.5, args=args, high=P1, bisection=True)\n except:\n return secant(err_dp_meter_solver_P2, P1*0.9, low=P1*1e-10, args=args, high=P1, bisection=True)\n except:\n return brenth(err_dp_meter_solver_P2, P1*(1-1E-9), P1*0.5, args=args)\n elif P1 is None and D is not None and D2 is not None and m is not None and P2 is not None:\n args = (D, D2, m, P2, rho, mu, k, meter_type, taps, tap_position, C_specified, epsilon_specified)\n try:\n return secant(err_dp_meter_solver_P1, P2*1.5, args=args, low=P2, bisection=True)\n except:\n return brenth(err_dp_meter_solver_P1, P2*(1+1E-9), P2*1.4, args=args)\n else:\n raise ValueError(\"Solver is capable of solving for one of P1, P2, D2, or m only.\")\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 8393}, "tests/test_friction.py::505": {"resolved_imports": ["fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "helical_transition_Re_Seth_Stahel"], "enclosing_function": "test_helical_transition_Re_Seth_Stahel", "extracted_code": "# Source: fluids/friction.py\ndef helical_transition_Re_Seth_Stahel(Di: float, Dc: float) -> float:\n r\"\"\"Calculates the transition Reynolds number for flow inside a curved or\n helical coil between laminar and turbulent flow, using the method of [1]_.\n\n .. math::\n Re_{crit} = 1900\\left[1 + 8 \\sqrt{\\frac{D_i}{D_c}}\\right]\n\n Parameters\n ----------\n Di : float\n Inner diameter of the coil, [m]\n Dc : float\n Diameter of the helix/coil measured from the center of the tube on one\n side to the center of the tube on the other side, [m]\n\n Returns\n -------\n Re_crit : float\n Transition Reynolds number between laminar and turbulent [-]\n\n Notes\n -----\n At very low curvatures, converges to Re = 1900.\n\n Examples\n --------\n >>> helical_transition_Re_Seth_Stahel(1, 7.)\n 7645.0599897402535\n\n References\n ----------\n .. [1] Seth, K. K., and E. P. Stahel. \"HEAT TRANSFER FROM HELICAL COILS\n IMMERSED IN AGITATED VESSELS.\" Industrial & Engineering Chemistry 61,\n no. 6 (June 1, 1969): 39-49. doi:10.1021/ie50714a007.\n \"\"\"\n return 1900.*(1. + 8.*sqrt(Di/Dc))\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 1766}, "tests/test_friction.py::523": {"resolved_imports": ["fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "helical_transition_Re_Schmidt"], "enclosing_function": "test_helical_transition_Re_Schmidt", "extracted_code": "# Source: fluids/friction.py\ndef helical_transition_Re_Schmidt(Di: float, Dc: float) -> float:\n r\"\"\"Calculates the transition Reynolds number for flow inside a curved or\n helical coil between laminar and turbulent flow, using the method of [1]_,\n also shown in [2]_ and [3]_. Correlation recommended in [3]_.\n\n .. math::\n Re_{crit} = 2300\\left[1 + 8.6\\left(\\frac{D_i}{D_c}\\right)^{0.45}\\right]\n\n Parameters\n ----------\n Di : float\n Inner diameter of the coil, [m]\n Dc : float\n Diameter of the helix/coil measured from the center of the tube on one\n side to the center of the tube on the other side, [m]\n\n Returns\n -------\n Re_crit : float\n Transition Reynolds number between laminar and turbulent [-]\n\n Notes\n -----\n At very low curvatures, converges to Re = 2300.\n Recommended for :math:`d_i/D_c < 0.14`\n\n Examples\n --------\n >>> helical_transition_Re_Schmidt(1, 7.)\n 10540.094061770815\n\n References\n ----------\n .. [1] Schmidt, Eckehard F. \"Wärmeübergang Und Druckverlust in\n Rohrschlangen.\" Chemie Ingenieur Technik 39, no. 13 (July 10, 1967):\n 781-89. doi:10.1002/cite.330391302.\n .. [2] El-Genk, Mohamed S., and Timothy M. Schriener. \"A Review and\n Correlations for Convection Heat Transfer and Pressure Losses in\n Toroidal and Helically Coiled Tubes.\" Heat Transfer Engineering 0, no. 0\n (June 7, 2016): 1-28. doi:10.1080/01457632.2016.1194693.\n .. [3] Schlunder, Ernst U, and International Center for Heat and Mass\n Transfer. Heat Exchanger Design Handbook. Washington:\n Hemisphere Pub. Corp., 1983.\n \"\"\"\n return 2300.*(1. + 8.6*(Di/Dc)**0.45)\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 2315}, "tests/test_friction.py::528": {"resolved_imports": ["fluids/friction.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "helical_transition_Re_Srinivasan"], "enclosing_function": "test_helical_transition_Re_Srinivasan", "extracted_code": "# Source: fluids/friction.py\ndef helical_transition_Re_Srinivasan(Di: float, Dc: float) -> float:\n r\"\"\"Calculates the transition Reynolds number for flow inside a curved or\n helical coil between laminar and turbulent flow, using the method of [1]_,\n also shown in [2]_ and [3]_. Correlation recommended in [3]_.\n\n .. math::\n Re_{crit} = 2100\\left[1 + 12\\left(\\frac{D_i}{D_c}\\right)^{0.5}\\right]\n\n Parameters\n ----------\n Di : float\n Inner diameter of the coil, [m]\n Dc : float\n Diameter of the helix/coil measured from the center of the tube on one\n side to the center of the tube on the other side, [m]\n\n Returns\n -------\n Re_crit : float\n Transition Reynolds number between laminar and turbulent [-]\n\n Notes\n -----\n At very low curvatures, converges to Re = 2100.\n Recommended for :math:`0.004 < d_i/D_c < 0.1`.\n\n Examples\n --------\n >>> helical_transition_Re_Srinivasan(1, 7.)\n 11624.704719832524\n\n References\n ----------\n .. [1] Srinivasan, P. S., Nandapurkar, S. S., and Holland, F. A., \"Pressure\n Drop and Heat Transfer in Coils\", Chemical Engineering, 218, CE131-119,\n (1968).\n .. [2] El-Genk, Mohamed S., and Timothy M. Schriener. \"A Review and\n Correlations for Convection Heat Transfer and Pressure Losses in\n Toroidal and Helically Coiled Tubes.\" Heat Transfer Engineering 0, no. 0\n (June 7, 2016): 1-28. doi:10.1080/01457632.2016.1194693.\n .. [3] Rohsenow, Warren and James Hartnett and Young Cho. Handbook of Heat\n Transfer, 3E. New York: McGraw-Hill, 1998.\n \"\"\"\n return 2100.*(1. + 12.*sqrt(Di/Dc))\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 2271}, "tests/test_numba.py::100": {"resolved_imports": ["fluids/__init__.py", "fluids/vectorized.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "fluids", "hp"], "enclosing_function": "test_interp", "extracted_code": "# Source: fluids/__init__.py\n def __getattr__(name):\n if name == \"vectorized\":\n import fluids.vectorized\n globals()[name] = fluids.vectorized\n return fluids.vectorized\n if name == \"numba\":\n import fluids.numba\n globals()[name] = fluids.numba\n return fluids.numba\n if name == \"units\":\n import fluids.units\n globals()[name] = fluids.units\n\n if name == \"vectorized\":\n import fluids.vectorized\n globals()[name] = fluids.vectorized\n return fluids.vectorized\n if name == \"numba\":\n import fluids.numba\n globals()[name] = fluids.numba\n return fluids.numba\n if name == \"units\":\n import fluids.units\n globals()[name] = fluids.units\n return fluids.units\n\n import fluids.vectorized\n globals()[name] = fluids.vectorized\n return fluids.vectorized\n if name == \"numba\":\n import fluids.numba\n globals()[name] = fluids.numba\n return fluids.numba\n if name == \"units\":\n import fluids.units\n globals()[name] = fluids.units\n return fluids.units\n if name == \"numba_vectorized\":\n\n return fluids.vectorized\n if name == \"numba\":\n import fluids.numba\n globals()[name] = fluids.numba\n return fluids.numba\n if name == \"units\":\n import fluids.units\n globals()[name] = fluids.units\n return fluids.units\n if name == \"numba_vectorized\":\n import fluids.numba_vectorized\n globals()[name] = fluids.numba_vectorized\n\n if name == \"numba\":\n import fluids.numba\n globals()[name] = fluids.numba\n return fluids.numba\n if name == \"units\":\n import fluids.units\n globals()[name] = fluids.units\n return fluids.units\n if name == \"numba_vectorized\":\n import fluids.numba_vectorized\n globals()[name] = fluids.numba_vectorized\n return fluids.numba_vectorized\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 2810}, "tests/test_control_valve.py::162": {"resolved_imports": ["fluids/control_valve.py", "fluids/fittings.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "pytest", "size_control_valve_g", "size_control_valve_l"], "enclosing_function": "test_control_valve_size_l", "extracted_code": "# Source: fluids/control_valve.py\ndef size_control_valve_l(rho: float, Psat: float, Pc: float, mu: float, P1: float, P2: float, Q: float, D1: float | None=None, D2: float | None=None,\n d: float | None=None, FL: float=0.9, Fd: float=1, allow_choked: bool=True,\n allow_laminar: bool=True, full_output: bool=False) -> float | dict[str, bool | float | None] | dict[str, float | bool | str | None]:\n r\"\"\"Calculates flow coefficient of a control valve passing a liquid\n according to IEC 60534. Uses a large number of inputs in SI units. Note the\n return value is not standard SI. All parameters are required.\n This sizing model does not officially apply to liquid mixtures, slurries,\n non-Newtonian fluids, or liquid-solid conveyance systems. For details\n of the calculations, consult [1]_.\n\n Parameters\n ----------\n rho : float\n Density of the liquid at the inlet [kg/m^3]\n Psat : float\n Saturation pressure of the fluid at inlet temperature [Pa]\n Pc : float\n Critical pressure of the fluid [Pa]\n mu : float\n Viscosity of the fluid [Pa*s]\n P1 : float\n Inlet pressure of the fluid before valves and reducers [Pa]\n P2 : float\n Outlet pressure of the fluid after valves and reducers [Pa]\n Q : float\n Volumetric flow rate of the fluid [m^3/s]\n D1 : float, optional\n Diameter of the pipe before the valve [m]\n D2 : float, optional\n Diameter of the pipe after the valve [m]\n d : float, optional\n Diameter of the valve [m]\n FL : float, optional\n Liquid pressure recovery factor of a control valve without attached\n fittings (normally 0.8-0.9 at full open and decreasing as opened\n further to below 0.5; use default very cautiously!) []\n Fd : float, optional\n Valve style modifier (0.1 to 1; varies tremendously depending on the\n type of valve and position; do not use the default at all!) []\n allow_choked : bool, optional\n Overrides the automatic transition into the choked regime if this is\n False and returns as if choked flow does not exist\n allow_laminar : bool, optional\n Overrides the automatic transition into the laminar regime if this is\n False and returns as if laminar flow does not exist\n full_output : bool, optional\n If True, returns intermediate calculation values as\n well as Kv in the form of a dictionary containing 'Kv', 'Rev', 'choked',\n 'FL', 'FLP', 'FR', 'FP', and 'laminar'. Some may be None if they are\n not used in the calculation.\n\n Returns\n -------\n Kv : float\n Metric Kv valve flow coefficient (flow rate of water at a pressure drop\n of 1 bar) [m^3/hr]\n\n Notes\n -----\n It is possible to use this model without any diameters specified; in that\n case, turbulent flow is assumed. Choked flow can still be modeled. This is\n not recommended. All three diameters need to be None for this to work.\n `FL` and `Fd` are not used by the models when the diameters are not\n specified.\n\n Examples\n --------\n From [1]_, matching example 1 for a globe, parabolic plug,\n flow-to-open valve.\n\n >>> size_control_valve_l(rho=965.4, Psat=70.1E3, Pc=22120E3, mu=3.1472E-4,\n ... P1=680E3, P2=220E3, Q=0.1, D1=0.15, D2=0.15, d=0.15,\n ... FL=0.9, Fd=0.46)\n 164.9954763704956\n\n From [1]_, matching example 2 for a ball, segmented ball,\n flow-to-open valve.\n\n >>> size_control_valve_l(rho=965.4, Psat=70.1E3, Pc=22120E3, mu=3.1472E-4,\n ... P1=680E3, P2=220E3, Q=0.1, D1=0.1, D2=0.1, d=0.1,\n ... FL=0.6, Fd=0.98)\n 238.05817216710483\n\n References\n ----------\n .. [1] IEC 60534-2-1 / ISA-75.01.01-2007\n \"\"\"\n if full_output:\n ans: dict[str, bool | float | None] = {\"FLP\": None, \"FP\": None, \"FR\": None}\n # Pa to kPa, according to constants in standard\n P1, P2, Psat, Pc = P1/1000., P2/1000., Psat/1000., Pc/1000.\n Q = Q*3600. # m^3/s to m^3/hr, according to constants in standard\n nu = mu/rho # kinematic viscosity used in standard\n MAX_C_POSSIBLE = 1E40 # Quit iterations if C reaches this high\n\n dP = P1 - P2\n FF = FF_critical_pressure_ratio_l(Psat=Psat, Pc=Pc)\n choked = is_choked_turbulent_l(dP=dP, P1=P1, Psat=Psat, FF=FF, FL=FL)\n if choked and allow_choked:\n # Choked flow, equation 3\n C = Q/N1/FL*sqrt(rho/rho0/(P1 - FF*Psat))\n else:\n # non-choked flow, eq 1\n C = Q/N1*sqrt(rho/rho0/dP)\n if D1 is None and D2 is None and d is None:\n # Assume turbulent if no diameters are provided, no other calculations\n Rev = 1e5\n else:\n # m to mm, according to constants in standard\n if D1 is None or D2 is None or d is None:\n raise ValueError(\"If any diameter is specified, all three (D1, D2, d) must be specified\")\n D1, D2, d = D1*1000., D2*1000., d*1000.\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=C)\n # normal calculation path\n if (Rev > 10000 or not allow_laminar) and (D1 != d or D2 != d):\n # liquid, using Fp and FLP\n FP = 1.0\n Ci = C\n MAX_ITER = 20\n def iterate_piping_turbulent_l(Ci, iterations):\n loss = loss_coefficient_piping(d, D1, D2)\n FP = 1.0/sqrt(1 + loss/N2*(Ci/d**2)**2)\n if d > D1:\n loss_upstream = 0.0\n else:\n loss_upstream = loss_coefficient_piping(d, D1)\n\n FLP = FL*1.0/sqrt(1 + FL**2/N2*loss_upstream*(Ci/d**2)**2)\n choked = is_choked_turbulent_l(dP, P1, Psat, FF, FLP=FLP, FP=FP)\n if choked:\n # Choked flow with piping, equation 4\n C = Q/N1/FLP*sqrt(rho/rho0/(P1-FF*Psat))\n else:\n # Non-Choked flow with piping, equation 5\n C = Q/N1/FP*sqrt(rho/rho0/dP)\n if Ci/C < 0.99 and iterations < MAX_ITER and Ci < MAX_C_POSSIBLE:\n C = iterate_piping_turbulent_l(C, iterations+1)\n if MAX_ITER == iterations or Ci >= MAX_C_POSSIBLE:\n ans[\"warning\"] = \"Not converged in inner loop\"\n if full_output:\n ans[\"FLP\"] = FLP\n ans[\"FP\"] = FP\n return C\n\n C = iterate_piping_turbulent_l(Ci, 0)\n elif Rev <= 10000 and allow_laminar:\n # Laminar\n def iterate_piping_laminar_l(C):\n Ci = 1.3*C\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=Ci)\n if Ci/(d*d) > 0.016*N18:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=False)\n else:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=True)\n if C/FR >= Ci:\n Ci = iterate_piping_laminar_l(Ci) # pragma: no cover\n\n if full_output:\n ans[\"Rev\"] = Rev\n ans[\"FR\"] = FR\n return Ci\n C = iterate_piping_laminar_l(C)\n if full_output:\n ans[\"FF\"] = FF\n ans[\"choked\"] = choked\n ans[\"Kv\"] = C\n ans[\"laminar\"] = Rev <= 10000\n\n # For the laminar case this is already set and needs to not be overwritten\n if \"Rev\" not in ans:\n ans[\"Rev\"] = Rev\n return ans\n else:\n# return C, choked, laminar, FF, FR, Rev, FP, FLP, warning\n return C\n\ndef size_control_valve_g(T: float, MW: float, mu: float, gamma: float, Z: float, P1: float, P2: float, Q: float, D1: float | None=None, D2: float | None=None,\n d: float | None=None, FL: float=0.9, Fd: float=1, xT: float=0.7, allow_choked: bool=True,\n allow_laminar: bool=True, full_output: bool=False) -> float | dict[str, bool | float | None] | dict[str, float | bool | str | None]:\n r\"\"\"Calculates flow coefficient of a control valve passing a gas\n according to IEC 60534. Uses a large number of inputs in SI units. Note the\n return value is not standard SI. All parameters are required. For details\n of the calculations, consult [1]_. Note the inlet gas flow conditions.\n\n Parameters\n ----------\n T : float\n Temperature of the gas at the inlet [K]\n MW : float\n Molecular weight of the gas [g/mol]\n mu : float\n Viscosity of the fluid at inlet conditions [Pa*s]\n gamma : float\n Specific heat capacity ratio [-]\n Z : float\n Compressibility factor at inlet conditions, [-]\n P1 : float\n Inlet pressure of the gas before valves and reducers [Pa]\n P2 : float\n Outlet pressure of the gas after valves and reducers [Pa]\n Q : float\n Volumetric flow rate of the gas at *273.15 K* and 1 atm specifically\n [m^3/s]\n D1 : float, optional\n Diameter of the pipe before the valve [m]\n D2 : float, optional\n Diameter of the pipe after the valve [m]\n d : float, optional\n Diameter of the valve [m]\n FL : float, optional\n Liquid pressure recovery factor of a control valve without attached\n fittings (normally 0.8-0.9 at full open and decreasing as opened\n further to below 0.5; use default very cautiously!) []\n Fd : float, optional\n Valve style modifier (0.1 to 1; varies tremendously depending on the\n type of valve and position; do not use the default at all!) []\n xT : float, optional\n Pressure difference ratio factor of a valve without fittings at choked\n flow (increasing to 0.9 or higher as the valve is closed further and\n decreasing to 0.1 or lower as the valve is opened further; use default\n very cautiously!) [-]\n allow_choked : bool, optional\n Overrides the automatic transition into the choked regime if this is\n False and returns as if choked flow does not exist\n allow_laminar : bool, optional\n Overrides the automatic transition into the laminar regime if this is\n False and returns as if laminar flow does not exist\n full_output : bool, optional\n If True, returns intermediate calculation values as\n well as Kv in the form of a dictionary containing 'Kv', 'Rev', 'choked',\n 'Y', 'FR', 'FP', 'xTP', and 'laminar'. Some may be None if they are\n not used in the calculation.\n\n Returns\n -------\n Kv : float\n Metric Kv valve flow coefficient (flow rate of water at a pressure drop\n of 1 bar) [m^3/hr]\n\n Notes\n -----\n It is possible to use this model without any diameters specified; in that\n case, turbulent flow is assumed. Choked flow can still be modeled. This is\n not recommended. All three diameters need to be None for this to work.\n `FL` and `Fd` are not used by the models when the diameters are not\n specified, but `xT` definitely is used by the model.\n\n When this model does not converge, the result is normally because of the\n specified delta P being less than that caused by the piping diameter\n changes.\n\n Examples\n --------\n From [1]_, matching example 3 for non-choked gas flow with attached\n fittings and a rotary, eccentric plug, flow-to-open control valve:\n\n >>> size_control_valve_g(T=433., MW=44.01, mu=1.4665E-4, gamma=1.30,\n ... Z=0.988, P1=680E3, P2=310E3, Q=38/36., D1=0.08, D2=0.1, d=0.05,\n ... FL=0.85, Fd=0.42, xT=0.60)\n 72.5866454539105\n\n From [1]_, roughly matching example 4 for a small flow trim sized tapered\n needle plug valve. Difference is 3% and explained by the difference in\n algorithms used.\n\n >>> size_control_valve_g(T=320., MW=39.95, mu=5.625E-5, gamma=1.67, Z=1.0,\n ... P1=2.8E5, P2=1.3E5, Q=0.46/3600., D1=0.015, D2=0.015, d=0.015, FL=0.98,\n ... Fd=0.07, xT=0.8)\n 0.016498765335995726\n\n References\n ----------\n .. [1] IEC 60534-2-1 / ISA-75.01.01-2007\n \"\"\"\n MAX_C_POSSIBLE = 1E40 # Quit iterations if C reaches this high\n # Pa to kPa, according to constants in standard\n P1, P2 = P1*1e-3, P2*1e-3\n Q = Q*3600. # m^3/s to m^3/hr, according to constants in standard\n # Convert dynamic viscosity to kinematic viscosity\n Vm = Z*R*T/(P1*1000)\n rho = MW*1e-3/Vm\n nu = mu/rho # kinematic viscosity used in standard\n\n dP = P1 - P2\n Fgamma = gamma/1.40\n x = dP/P1\n Y = max(1 - x/(3*Fgamma*xT), 2/3.)\n\n choked = is_choked_turbulent_g(x, Fgamma, xT)\n if choked and allow_choked:\n # Choked, and flow coefficient from eq 14a\n C = Q/(N9*P1*Y)*sqrt(MW*T*Z/xT/Fgamma)\n else:\n # Non-choked, and flow coefficient from eq 8a\n C = Q/(N9*P1*Y)*sqrt(MW*T*Z/x)\n\n\n if full_output: # numba: delete\n ans = {\"FP\": None, \"xTP\": None, \"FR\": None, \"choked\": choked, \"Y\": Y} # numba: delete\n\n if D1 is None and D2 is None and d is None:\n # Assume turbulent if no diameters are provided, no other calculations\n Rev = 1e5\n if full_output: # numba: delete\n ans[\"Rev\"] = None # numba: delete\n else:\n # m to mm, according to constants in standard\n if D1 is None or D2 is None or d is None:\n raise ValueError(\"If any diameter is specified, all three (D1, D2, d) must be specified\")\n D1, D2, d = D1*1000., D2*1000., d*1000. # Convert diameters to mm which is used in the standard\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=C)\n if full_output: # numba: delete\n ans[\"Rev\"] = Rev # numba: delete\n\n if (Rev > 10000 or not allow_laminar) and (D1 != d or D2 != d):\n # gas, using xTP and FLP\n FP = 1.\n MAX_ITER = 20\n\n def iterate_piping_coef_g(Ci, iterations):\n loss = loss_coefficient_piping(d, D1, D2)\n FP = 1.0/sqrt(1. + loss/N2*(Ci/d**2)**2)\n loss_upstream = loss_coefficient_piping(d, D1)\n xTP = xT/FP**2/(1 + xT*loss_upstream/N5*(Ci/d**2)**2)\n choked = is_choked_turbulent_g(x, Fgamma, xTP=xTP)\n if choked:\n # Choked flow with piping, equation 17a\n C = Q/(N9*FP*P1*Y)*sqrt(MW*T*Z/xTP/Fgamma)\n else:\n # Non-choked flow with piping, equation 11a\n C = Q/(N9*FP*P1*Y)*sqrt(MW*T*Z/x)\n if Ci/C < 0.99 and iterations < MAX_ITER and Ci < MAX_C_POSSIBLE:\n C = iterate_piping_coef_g(C, iterations+1)\n if full_output: # numba: delete\n ans[\"xTP\"] = xTP # numba: delete\n ans[\"FP\"] = FP # numba: delete\n ans[\"choked\"] = choked # numba: delete\n if MAX_ITER == iterations or Ci >= MAX_C_POSSIBLE: # numba: delete\n ans[\"warning\"] = \"Not converged in inner loop\" # numba: delete\n return C\n\n# def err_piping_coeff(Ci):\n# loss = loss_coefficient_piping(d, D1, D2)\n# FP = (1. + loss/N2*(Ci/d**2)**2)**-0.5\n# loss_upstream = loss_coefficient_piping(d, D1)\n# xTP = xT/FP**2/(1 + xT*loss_upstream/N5*(Ci/d**2)**2)\n# choked = is_choked_turbulent_g(x, Fgamma, xTP=xTP)\n# if choked:\n# # Choked flow with piping, equation 17a\n# C = Q/(N9*FP*P1*Y)*(MW*T*Z/xTP/Fgamma)**0.5\n# else:\n# # Non-choked flow with piping, equation 11a\n# C = Q/(N9*FP*P1*Y)*(MW*T*Z/x)**0.5\n# return C - Ci\n# import matplotlib.pyplot as plt\n# from fluids.numerics import linspace\n# Cs = linspace(C/50, C*50, 5000)\n# errs = [err_piping_coeff(C_test) for C_test in Cs]\n# plt.plot(Cs, errs)\n# plt.show()\n\n C = iterate_piping_coef_g(C, 0)\n elif Rev <= 10000 and allow_laminar:\n # Laminar;\n def iterate_piping_laminar_g(C):\n Ci = 1.3*C\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=Ci)\n if Ci/(d*d) > 0.016*N18:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=False)\n else:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=True)\n if C/FR >= Ci:\n Ci = iterate_piping_laminar_g(Ci)\n if full_output: # numba: delete\n ans[\"FR\"] = FR # numba: delete\n ans[\"Rev\"] = Rev # numba: delete\n return Ci\n C = iterate_piping_laminar_g(C)\n if full_output: # numba: delete\n ans[\"Kv\"] = C # numba: delete\n ans[\"laminar\"] = Rev <= 10000 # numba: delete\n ans[\"choked\"] = choked # numba: delete\n return ans # numba: delete\n return C\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 17543}, "tests/test_control_valve.py::164": {"resolved_imports": ["fluids/control_valve.py", "fluids/fittings.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "pytest", "size_control_valve_g", "size_control_valve_l"], "enclosing_function": "test_control_valve_size_l", "extracted_code": "# Source: fluids/control_valve.py\ndef size_control_valve_l(rho: float, Psat: float, Pc: float, mu: float, P1: float, P2: float, Q: float, D1: float | None=None, D2: float | None=None,\n d: float | None=None, FL: float=0.9, Fd: float=1, allow_choked: bool=True,\n allow_laminar: bool=True, full_output: bool=False) -> float | dict[str, bool | float | None] | dict[str, float | bool | str | None]:\n r\"\"\"Calculates flow coefficient of a control valve passing a liquid\n according to IEC 60534. Uses a large number of inputs in SI units. Note the\n return value is not standard SI. All parameters are required.\n This sizing model does not officially apply to liquid mixtures, slurries,\n non-Newtonian fluids, or liquid-solid conveyance systems. For details\n of the calculations, consult [1]_.\n\n Parameters\n ----------\n rho : float\n Density of the liquid at the inlet [kg/m^3]\n Psat : float\n Saturation pressure of the fluid at inlet temperature [Pa]\n Pc : float\n Critical pressure of the fluid [Pa]\n mu : float\n Viscosity of the fluid [Pa*s]\n P1 : float\n Inlet pressure of the fluid before valves and reducers [Pa]\n P2 : float\n Outlet pressure of the fluid after valves and reducers [Pa]\n Q : float\n Volumetric flow rate of the fluid [m^3/s]\n D1 : float, optional\n Diameter of the pipe before the valve [m]\n D2 : float, optional\n Diameter of the pipe after the valve [m]\n d : float, optional\n Diameter of the valve [m]\n FL : float, optional\n Liquid pressure recovery factor of a control valve without attached\n fittings (normally 0.8-0.9 at full open and decreasing as opened\n further to below 0.5; use default very cautiously!) []\n Fd : float, optional\n Valve style modifier (0.1 to 1; varies tremendously depending on the\n type of valve and position; do not use the default at all!) []\n allow_choked : bool, optional\n Overrides the automatic transition into the choked regime if this is\n False and returns as if choked flow does not exist\n allow_laminar : bool, optional\n Overrides the automatic transition into the laminar regime if this is\n False and returns as if laminar flow does not exist\n full_output : bool, optional\n If True, returns intermediate calculation values as\n well as Kv in the form of a dictionary containing 'Kv', 'Rev', 'choked',\n 'FL', 'FLP', 'FR', 'FP', and 'laminar'. Some may be None if they are\n not used in the calculation.\n\n Returns\n -------\n Kv : float\n Metric Kv valve flow coefficient (flow rate of water at a pressure drop\n of 1 bar) [m^3/hr]\n\n Notes\n -----\n It is possible to use this model without any diameters specified; in that\n case, turbulent flow is assumed. Choked flow can still be modeled. This is\n not recommended. All three diameters need to be None for this to work.\n `FL` and `Fd` are not used by the models when the diameters are not\n specified.\n\n Examples\n --------\n From [1]_, matching example 1 for a globe, parabolic plug,\n flow-to-open valve.\n\n >>> size_control_valve_l(rho=965.4, Psat=70.1E3, Pc=22120E3, mu=3.1472E-4,\n ... P1=680E3, P2=220E3, Q=0.1, D1=0.15, D2=0.15, d=0.15,\n ... FL=0.9, Fd=0.46)\n 164.9954763704956\n\n From [1]_, matching example 2 for a ball, segmented ball,\n flow-to-open valve.\n\n >>> size_control_valve_l(rho=965.4, Psat=70.1E3, Pc=22120E3, mu=3.1472E-4,\n ... P1=680E3, P2=220E3, Q=0.1, D1=0.1, D2=0.1, d=0.1,\n ... FL=0.6, Fd=0.98)\n 238.05817216710483\n\n References\n ----------\n .. [1] IEC 60534-2-1 / ISA-75.01.01-2007\n \"\"\"\n if full_output:\n ans: dict[str, bool | float | None] = {\"FLP\": None, \"FP\": None, \"FR\": None}\n # Pa to kPa, according to constants in standard\n P1, P2, Psat, Pc = P1/1000., P2/1000., Psat/1000., Pc/1000.\n Q = Q*3600. # m^3/s to m^3/hr, according to constants in standard\n nu = mu/rho # kinematic viscosity used in standard\n MAX_C_POSSIBLE = 1E40 # Quit iterations if C reaches this high\n\n dP = P1 - P2\n FF = FF_critical_pressure_ratio_l(Psat=Psat, Pc=Pc)\n choked = is_choked_turbulent_l(dP=dP, P1=P1, Psat=Psat, FF=FF, FL=FL)\n if choked and allow_choked:\n # Choked flow, equation 3\n C = Q/N1/FL*sqrt(rho/rho0/(P1 - FF*Psat))\n else:\n # non-choked flow, eq 1\n C = Q/N1*sqrt(rho/rho0/dP)\n if D1 is None and D2 is None and d is None:\n # Assume turbulent if no diameters are provided, no other calculations\n Rev = 1e5\n else:\n # m to mm, according to constants in standard\n if D1 is None or D2 is None or d is None:\n raise ValueError(\"If any diameter is specified, all three (D1, D2, d) must be specified\")\n D1, D2, d = D1*1000., D2*1000., d*1000.\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=C)\n # normal calculation path\n if (Rev > 10000 or not allow_laminar) and (D1 != d or D2 != d):\n # liquid, using Fp and FLP\n FP = 1.0\n Ci = C\n MAX_ITER = 20\n def iterate_piping_turbulent_l(Ci, iterations):\n loss = loss_coefficient_piping(d, D1, D2)\n FP = 1.0/sqrt(1 + loss/N2*(Ci/d**2)**2)\n if d > D1:\n loss_upstream = 0.0\n else:\n loss_upstream = loss_coefficient_piping(d, D1)\n\n FLP = FL*1.0/sqrt(1 + FL**2/N2*loss_upstream*(Ci/d**2)**2)\n choked = is_choked_turbulent_l(dP, P1, Psat, FF, FLP=FLP, FP=FP)\n if choked:\n # Choked flow with piping, equation 4\n C = Q/N1/FLP*sqrt(rho/rho0/(P1-FF*Psat))\n else:\n # Non-Choked flow with piping, equation 5\n C = Q/N1/FP*sqrt(rho/rho0/dP)\n if Ci/C < 0.99 and iterations < MAX_ITER and Ci < MAX_C_POSSIBLE:\n C = iterate_piping_turbulent_l(C, iterations+1)\n if MAX_ITER == iterations or Ci >= MAX_C_POSSIBLE:\n ans[\"warning\"] = \"Not converged in inner loop\"\n if full_output:\n ans[\"FLP\"] = FLP\n ans[\"FP\"] = FP\n return C\n\n C = iterate_piping_turbulent_l(Ci, 0)\n elif Rev <= 10000 and allow_laminar:\n # Laminar\n def iterate_piping_laminar_l(C):\n Ci = 1.3*C\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=Ci)\n if Ci/(d*d) > 0.016*N18:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=False)\n else:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=True)\n if C/FR >= Ci:\n Ci = iterate_piping_laminar_l(Ci) # pragma: no cover\n\n if full_output:\n ans[\"Rev\"] = Rev\n ans[\"FR\"] = FR\n return Ci\n C = iterate_piping_laminar_l(C)\n if full_output:\n ans[\"FF\"] = FF\n ans[\"choked\"] = choked\n ans[\"Kv\"] = C\n ans[\"laminar\"] = Rev <= 10000\n\n # For the laminar case this is already set and needs to not be overwritten\n if \"Rev\" not in ans:\n ans[\"Rev\"] = Rev\n return ans\n else:\n# return C, choked, laminar, FF, FR, Rev, FP, FLP, warning\n return C\n\ndef size_control_valve_g(T: float, MW: float, mu: float, gamma: float, Z: float, P1: float, P2: float, Q: float, D1: float | None=None, D2: float | None=None,\n d: float | None=None, FL: float=0.9, Fd: float=1, xT: float=0.7, allow_choked: bool=True,\n allow_laminar: bool=True, full_output: bool=False) -> float | dict[str, bool | float | None] | dict[str, float | bool | str | None]:\n r\"\"\"Calculates flow coefficient of a control valve passing a gas\n according to IEC 60534. Uses a large number of inputs in SI units. Note the\n return value is not standard SI. All parameters are required. For details\n of the calculations, consult [1]_. Note the inlet gas flow conditions.\n\n Parameters\n ----------\n T : float\n Temperature of the gas at the inlet [K]\n MW : float\n Molecular weight of the gas [g/mol]\n mu : float\n Viscosity of the fluid at inlet conditions [Pa*s]\n gamma : float\n Specific heat capacity ratio [-]\n Z : float\n Compressibility factor at inlet conditions, [-]\n P1 : float\n Inlet pressure of the gas before valves and reducers [Pa]\n P2 : float\n Outlet pressure of the gas after valves and reducers [Pa]\n Q : float\n Volumetric flow rate of the gas at *273.15 K* and 1 atm specifically\n [m^3/s]\n D1 : float, optional\n Diameter of the pipe before the valve [m]\n D2 : float, optional\n Diameter of the pipe after the valve [m]\n d : float, optional\n Diameter of the valve [m]\n FL : float, optional\n Liquid pressure recovery factor of a control valve without attached\n fittings (normally 0.8-0.9 at full open and decreasing as opened\n further to below 0.5; use default very cautiously!) []\n Fd : float, optional\n Valve style modifier (0.1 to 1; varies tremendously depending on the\n type of valve and position; do not use the default at all!) []\n xT : float, optional\n Pressure difference ratio factor of a valve without fittings at choked\n flow (increasing to 0.9 or higher as the valve is closed further and\n decreasing to 0.1 or lower as the valve is opened further; use default\n very cautiously!) [-]\n allow_choked : bool, optional\n Overrides the automatic transition into the choked regime if this is\n False and returns as if choked flow does not exist\n allow_laminar : bool, optional\n Overrides the automatic transition into the laminar regime if this is\n False and returns as if laminar flow does not exist\n full_output : bool, optional\n If True, returns intermediate calculation values as\n well as Kv in the form of a dictionary containing 'Kv', 'Rev', 'choked',\n 'Y', 'FR', 'FP', 'xTP', and 'laminar'. Some may be None if they are\n not used in the calculation.\n\n Returns\n -------\n Kv : float\n Metric Kv valve flow coefficient (flow rate of water at a pressure drop\n of 1 bar) [m^3/hr]\n\n Notes\n -----\n It is possible to use this model without any diameters specified; in that\n case, turbulent flow is assumed. Choked flow can still be modeled. This is\n not recommended. All three diameters need to be None for this to work.\n `FL` and `Fd` are not used by the models when the diameters are not\n specified, but `xT` definitely is used by the model.\n\n When this model does not converge, the result is normally because of the\n specified delta P being less than that caused by the piping diameter\n changes.\n\n Examples\n --------\n From [1]_, matching example 3 for non-choked gas flow with attached\n fittings and a rotary, eccentric plug, flow-to-open control valve:\n\n >>> size_control_valve_g(T=433., MW=44.01, mu=1.4665E-4, gamma=1.30,\n ... Z=0.988, P1=680E3, P2=310E3, Q=38/36., D1=0.08, D2=0.1, d=0.05,\n ... FL=0.85, Fd=0.42, xT=0.60)\n 72.5866454539105\n\n From [1]_, roughly matching example 4 for a small flow trim sized tapered\n needle plug valve. Difference is 3% and explained by the difference in\n algorithms used.\n\n >>> size_control_valve_g(T=320., MW=39.95, mu=5.625E-5, gamma=1.67, Z=1.0,\n ... P1=2.8E5, P2=1.3E5, Q=0.46/3600., D1=0.015, D2=0.015, d=0.015, FL=0.98,\n ... Fd=0.07, xT=0.8)\n 0.016498765335995726\n\n References\n ----------\n .. [1] IEC 60534-2-1 / ISA-75.01.01-2007\n \"\"\"\n MAX_C_POSSIBLE = 1E40 # Quit iterations if C reaches this high\n # Pa to kPa, according to constants in standard\n P1, P2 = P1*1e-3, P2*1e-3\n Q = Q*3600. # m^3/s to m^3/hr, according to constants in standard\n # Convert dynamic viscosity to kinematic viscosity\n Vm = Z*R*T/(P1*1000)\n rho = MW*1e-3/Vm\n nu = mu/rho # kinematic viscosity used in standard\n\n dP = P1 - P2\n Fgamma = gamma/1.40\n x = dP/P1\n Y = max(1 - x/(3*Fgamma*xT), 2/3.)\n\n choked = is_choked_turbulent_g(x, Fgamma, xT)\n if choked and allow_choked:\n # Choked, and flow coefficient from eq 14a\n C = Q/(N9*P1*Y)*sqrt(MW*T*Z/xT/Fgamma)\n else:\n # Non-choked, and flow coefficient from eq 8a\n C = Q/(N9*P1*Y)*sqrt(MW*T*Z/x)\n\n\n if full_output: # numba: delete\n ans = {\"FP\": None, \"xTP\": None, \"FR\": None, \"choked\": choked, \"Y\": Y} # numba: delete\n\n if D1 is None and D2 is None and d is None:\n # Assume turbulent if no diameters are provided, no other calculations\n Rev = 1e5\n if full_output: # numba: delete\n ans[\"Rev\"] = None # numba: delete\n else:\n # m to mm, according to constants in standard\n if D1 is None or D2 is None or d is None:\n raise ValueError(\"If any diameter is specified, all three (D1, D2, d) must be specified\")\n D1, D2, d = D1*1000., D2*1000., d*1000. # Convert diameters to mm which is used in the standard\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=C)\n if full_output: # numba: delete\n ans[\"Rev\"] = Rev # numba: delete\n\n if (Rev > 10000 or not allow_laminar) and (D1 != d or D2 != d):\n # gas, using xTP and FLP\n FP = 1.\n MAX_ITER = 20\n\n def iterate_piping_coef_g(Ci, iterations):\n loss = loss_coefficient_piping(d, D1, D2)\n FP = 1.0/sqrt(1. + loss/N2*(Ci/d**2)**2)\n loss_upstream = loss_coefficient_piping(d, D1)\n xTP = xT/FP**2/(1 + xT*loss_upstream/N5*(Ci/d**2)**2)\n choked = is_choked_turbulent_g(x, Fgamma, xTP=xTP)\n if choked:\n # Choked flow with piping, equation 17a\n C = Q/(N9*FP*P1*Y)*sqrt(MW*T*Z/xTP/Fgamma)\n else:\n # Non-choked flow with piping, equation 11a\n C = Q/(N9*FP*P1*Y)*sqrt(MW*T*Z/x)\n if Ci/C < 0.99 and iterations < MAX_ITER and Ci < MAX_C_POSSIBLE:\n C = iterate_piping_coef_g(C, iterations+1)\n if full_output: # numba: delete\n ans[\"xTP\"] = xTP # numba: delete\n ans[\"FP\"] = FP # numba: delete\n ans[\"choked\"] = choked # numba: delete\n if MAX_ITER == iterations or Ci >= MAX_C_POSSIBLE: # numba: delete\n ans[\"warning\"] = \"Not converged in inner loop\" # numba: delete\n return C\n\n# def err_piping_coeff(Ci):\n# loss = loss_coefficient_piping(d, D1, D2)\n# FP = (1. + loss/N2*(Ci/d**2)**2)**-0.5\n# loss_upstream = loss_coefficient_piping(d, D1)\n# xTP = xT/FP**2/(1 + xT*loss_upstream/N5*(Ci/d**2)**2)\n# choked = is_choked_turbulent_g(x, Fgamma, xTP=xTP)\n# if choked:\n# # Choked flow with piping, equation 17a\n# C = Q/(N9*FP*P1*Y)*(MW*T*Z/xTP/Fgamma)**0.5\n# else:\n# # Non-choked flow with piping, equation 11a\n# C = Q/(N9*FP*P1*Y)*(MW*T*Z/x)**0.5\n# return C - Ci\n# import matplotlib.pyplot as plt\n# from fluids.numerics import linspace\n# Cs = linspace(C/50, C*50, 5000)\n# errs = [err_piping_coeff(C_test) for C_test in Cs]\n# plt.plot(Cs, errs)\n# plt.show()\n\n C = iterate_piping_coef_g(C, 0)\n elif Rev <= 10000 and allow_laminar:\n # Laminar;\n def iterate_piping_laminar_g(C):\n Ci = 1.3*C\n Rev = Reynolds_valve(nu=nu, Q=Q, D1=D1, FL=FL, Fd=Fd, C=Ci)\n if Ci/(d*d) > 0.016*N18:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=False)\n else:\n FR = Reynolds_factor(FL=FL, C=Ci, d=d, Rev=Rev, full_trim=True)\n if C/FR >= Ci:\n Ci = iterate_piping_laminar_g(Ci)\n if full_output: # numba: delete\n ans[\"FR\"] = FR # numba: delete\n ans[\"Rev\"] = Rev # numba: delete\n return Ci\n C = iterate_piping_laminar_g(C)\n if full_output: # numba: delete\n ans[\"Kv\"] = C # numba: delete\n ans[\"laminar\"] = Rev <= 10000 # numba: delete\n ans[\"choked\"] = choked # numba: delete\n return ans # numba: delete\n return C\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 17543}, "tests/test_numerics.py::338": {"resolved_imports": ["fluids/numerics/__init__.py"], "used_names": ["cumulative_trapezoid", "linspace", "pytest"], "enclosing_function": "test_cumulative_trapezoid", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):\n \"\"\"Port of numpy's linspace to pure python.\n\n Does not support dtype, and returns lists of floats.\n \"\"\"\n num = int(num)\n start = start * 1.\n stop = stop * 1.\n\n if num <= 0:\n return []\n if endpoint:\n if num == 1:\n return [start]\n step = (stop-start)/float(num-1)\n if num == 1:\n step = nan\n\n y = [start]\n for _ in range(num-2):\n y.append(y[-1] + step)\n y.append(stop)\n else:\n step = (stop-start)/float(num)\n if num == 1:\n step = nan\n y = [start]\n for _ in range(num-1):\n y.append(y[-1] + step)\n\n if retstep:\n return y, step\n else:\n return y\n\ndef cumulative_trapezoid(y, x=None, dx=None):\n \"\"\"Compute cumulative integral using trapezoidal rule.\n\n Parameters\n ----------\n y : list[float]\n Values of the function to integrate\n x : list[float], optional\n The x coordinates. If None, assumes unit spacing.\n\n Returns\n -------\n list[float]\n Cumulative integral. Length is len(y)-1\n\n Examples\n --------\n >>> x = [0, 1, 2]\n >>> y = [1, 2, 3] # y = x + 1\n >>> cumulative_trapezoid(y, x) # Integral of (x+1) is x^2/2 + x\n [1.5, 4.0]\n \"\"\"\n if not y:\n return []\n\n n = len(y)\n if n < 2:\n return []\n\n if x is None:\n # Unit spacing\n if dx is None:\n raise ValueError(\"either dx or x should be provided\")\n result = []\n integral = 0.0\n for i in range(n-1):\n integral += (y[i] + y[i+1]) * dx*0.5\n result.append(integral)\n return result\n\n if len(x) != n:\n raise ValueError(\"x and y must have same length\")\n\n # potentially variable spacing\n result = []\n integral = 0.0\n for i in range(n-1):\n dx = x[i+1] - x[i]\n integral += (y[i] + y[i+1]) * dx*0.5\n result.append(integral)\n return result", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 2074}, "tests/test_numerics_arrays.py::1782": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/arrays.py"], "used_names": ["transpose"], "enclosing_function": "test_transpose", "extracted_code": "# Source: fluids/numerics/arrays.py\ndef transpose(matrix):\n \"\"\"Convert a matrix into its transpose by switching rows and columns.\n\n Parameters\n ----------\n matrix : list[list[float]]\n Input matrix as a list of lists where each inner list represents a row.\n All rows must have the same length.\n\n Returns\n -------\n list[list[float]]\n The transposed matrix where element [i][j] in the input becomes [j][i]\n in the output.\n\n Raises\n ------\n ValueError\n If the input matrix has inconsistent row lengths.\n TypeError\n If the input is not a list of lists.\n\n Examples\n --------\n >>> transpose([[1, 2, 3], [4, 5, 6]])\n [[1, 4], [2, 5], [3, 6]]\n\n >>> transpose([[1, 2], [3, 4]]) # Square matrix\n [[1, 3], [2, 4]]\n\n >>> transpose([[1, 2, 3]]) # Single row matrix\n [[1], [2], [3]]\n\n Notes\n -----\n - Empty matrices are preserved as empty lists\n - The function creates a new matrix rather than modifying in place\n - For an MxN matrix, the result will be an NxM matrix\n \"\"\"\n # Handle empty matrix cases\n if not matrix:\n return []\n if not matrix[0]:\n return []\n\n # # Validate input\n # if not isinstance(matrix, list) or not all(isinstance(row, list) for row in matrix):\n # raise TypeError(\"Input must be a list of lists\")\n\n # Check for consistent row lengths\n row_length = len(matrix[0])\n if not all(len(row) == row_length for row in matrix):\n raise ValueError(\"All rows must have the same length\")\n\n return [list(i) for i in zip(*matrix)]", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 1596}, "tests/test_units.py::153": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/units.py"], "used_names": ["API520_A_g", "API520_round_size", "Bond", "C_Chezy_to_n_Manning", "Cv_to_K", "Geldart_Ling", "K_separator_Watkins", "K_to_Cv", "Q_weir_rectangular_SIA", "Reynolds", "Robbins", "T_critical_flow", "agitator_time_homogeneous", "assert_close", "current_ideal", "dP_packed_bed", "drag_sphere", "friction_factor", "head_from_P", "integrate_drag_sphere", "is_critical_flow", "pytest", "roughness_Farshad", "size_control_valve_g", "specific_speed", "speed_synchronous", "t_from_gauge", "u"], "enclosing_function": "test_sample_cases", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/units.py\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 4046}, "tests/test_core.py::328": {"resolved_imports": ["fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["F2C", "assert_close", "assert_close1d"], "enclosing_function": "test_fahrenheit_to_celcius", "extracted_code": "# Source: fluids/core.py\ndef F2C(F: float) -> float:\n \"\"\"Convert Fahrenheit to Celsius.\n\n Parameters\n ----------\n F : float\n Fahrenheit temperature to be converted.\n\n Returns\n -------\n C : float\n Equivalent Celsius temperature.\n\n Notes\n -----\n Computes ``C = (F - 32) / 1.8``.\n\n Examples\n --------\n >>> F2C(-40.0)\n -40.0\n \"\"\"\n return (F - 32.0) / 1.8\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1261}, "tests/test_piping.py::63": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/piping.py"], "used_names": ["assert_close1d", "gauge_from_t", "pytest", "t_from_gauge"], "enclosing_function": "test_gauge", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\n\n# Source: fluids/piping.py\ndef gauge_from_t(t: float, SI: bool=True, schedule: str=\"BWG\") -> float:\n r\"\"\"Looks up the gauge of a given wire thickness of given schedule.\n Values are all non-linear, and tabulated internally.\n\n Parameters\n ----------\n t : float\n Thickness, [m]\n SI : bool, optional\n If False, requires that the thickness is given in inches not meters\n schedule : str\n Gauge schedule, one of 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', or 'SSWG'\n\n Returns\n -------\n gauge : float-like\n Wire Gauge, [-]\n\n Notes\n -----\n An internal variable, tol, is used in the selection of the wire gauge. If\n the next smaller wire gauge is within 10% of the difference between it and\n the previous wire gauge, the smaller wire gauge is selected. Accordingly,\n this function can return a gauge with a thickness smaller than desired\n in some circumstances.\n\n * Birmingham Wire Gauge (BWG) ranges from 0.2 (0.5 inch) to 36 (0.004 inch).\n * American Wire Gauge (AWG) ranges from 0.167 (0.58 inch) to 51 (0.00099\n inch). These are used for electrical wires.\n * Steel Wire Gauge (SWG) ranges from 0.143 (0.49 inch) to 51 (0.0044 inch).\n Also called Washburn & Moen wire gauge, American Steel gauge, Wire Co.\n gauge, and Roebling wire gauge.\n * Music Wire Gauge (MWG) ranges from 0.167 (0.004 inch) to 46 (0.18\n inch). Also called Piano Wire Gauge.\n * British Standard Wire Gage (BSWG) ranges from 0.143 (0.5 inch) to\n 51 (0.001 inch). Also called Imperial Wire Gage (IWG).\n * Stub's Steel Wire Gage (SSWG) ranges from 1 (0.227 inch) to 80 (0.013 inch)\n\n Examples\n --------\n >>> gauge_from_t(.5, SI=False, schedule='BWG')\n 0.2\n\n References\n ----------\n .. [1] Oberg, Erik, Franklin D. Jones, and Henry H. Ryffel. Machinery's\n Handbook. Industrial Press, Incorporated, 2012.\n \"\"\"\n tol = 0.1\n # Handle units\n if SI:\n t_inch = round(t/inch, 9) # all schedules are in inches\n else:\n t_inch = t\n\n # Get the schedule\n try:\n sch_integers, sch_inch, sch_SI, decreasing = wire_schedules[schedule]\n except:\n raise ValueError(\"Wire gauge schedule not found\")\n\n # Check if outside limits\n sch_max, sch_min = sch_inch[0], sch_inch[-1]\n if t_inch > sch_max:\n raise ValueError(\"Input thickness is above the largest in the selected schedule\")\n\n\n # If given thickness is exactly in the index, be happy\n if t_inch in sch_inch:\n gauge = sch_integers[sch_inch.index(t_inch)]\n\n else:\n for i in range(len(sch_inch)):\n if sch_inch[i] >= t_inch:\n larger = sch_inch[i]\n else:\n break\n if larger == sch_min:\n gauge = sch_min # If t is under the lowest schedule, be happy\n else:\n smaller = sch_inch[i]\n if (t_inch - smaller) <= tol*(larger - smaller):\n gauge = sch_integers[i]\n else:\n gauge = sch_integers[i-1]\n return gauge\n\ndef t_from_gauge(gauge: float, SI: bool=True, schedule: str=\"BWG\") -> float:\n r\"\"\"Looks up the thickness of a given wire gauge of given schedule.\n Values are all non-linear, and tabulated internally.\n\n Parameters\n ----------\n gauge : float-like\n Wire Gauge, []\n SI : bool, optional\n If False, will return a thickness in inches not meters\n schedule : str\n Gauge schedule, one of 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', or 'SSWG'\n\n Returns\n -------\n t : float\n Thickness, [m]\n\n Notes\n -----\n * Birmingham Wire Gauge (BWG) ranges from 0.2 (0.5 inch) to 36 (0.004 inch).\n * American Wire Gauge (AWG) ranges from 0.167 (0.58 inch) to 51 (0.00099\n inch). These are used for electrical wires.\n * Steel Wire Gauge (SWG) ranges from 0.143 (0.49 inch) to 51 (0.0044 inch).\n Also called Washburn & Moen wire gauge, American Steel gauge, Wire Co.\n gauge, and Roebling wire gauge.\n * Music Wire Gauge (MWG) ranges from 0.167 (0.004 inch) to 46 (0.18\n inch). Also called Piano Wire Gauge.\n * British Standard Wire Gage (BSWG) ranges from 0.143 (0.5 inch) to\n 51 (0.001 inch). Also called Imperial Wire Gage (IWG).\n * Stub's Steel Wire Gage (SSWG) ranges from 1 (0.227 inch) to 80 (0.013 inch)\n\n Examples\n --------\n >>> t_from_gauge(.2, False, 'BWG')\n 0.5\n\n References\n ----------\n .. [1] Oberg, Erik, Franklin D. Jones, and Henry H. Ryffel. Machinery's\n Handbook. Industrial Press, Incorporated, 2012.\n \"\"\"\n try:\n sch_integers, sch_inch, sch_SI, decreasing = wire_schedules[schedule]\n except:\n raise ValueError(\"Wire gauge schedule not found; supported gauges are \\\n'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', and 'SSWG'.\")\n\n try:\n i = sch_integers.index(gauge)\n except:\n raise ValueError(\"Input gauge not found in selected schedule\")\n if SI:\n return sch_SI[i] # returns thickness in m\n else:\n return sch_inch[i]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 5324}, "tests/test_core.py::332": {"resolved_imports": ["fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["C2K", "assert_close1d"], "enclosing_function": "test_celcius_to_kelvin", "extracted_code": "# Source: fluids/core.py\ndef C2K(C: float) -> float:\n \"\"\"Convert Celsius to Kelvin.\n\n Parameters\n ----------\n C : float\n Celsius temperature to be converted, [degC]\n\n Returns\n -------\n K : float\n Equivalent Kelvin temperature, [K]\n\n Notes\n -----\n Computes ``K = C + zero_Celsius`` where `zero_Celsius` = 273.15, i.e.,\n (the absolute value of) temperature \"absolute zero\" as measured in Celsius.\n\n Examples\n --------\n >>> C2K(-40)\n 233.14999999999998\n \"\"\"\n return C + zero_Celsius\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 822}, "tests/test_core.py::344": {"resolved_imports": ["fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["K2F", "assert_close1d"], "enclosing_function": "test_kelvin_to_fahrenheit", "extracted_code": "# Source: fluids/core.py\ndef K2F(K: float) -> float:\n \"\"\"Convert Kelvin to Fahrenheit.\n\n Parameters\n ----------\n K : float\n Kelvin temperature to be converted.\n\n Returns\n -------\n F : float\n Equivalent Fahrenheit temperature.\n\n Notes\n -----\n Computes ``F = 1.8 * (K - zero_Celsius) + 32`` where `zero_Celsius` =\n 273.15, i.e., (the absolute value of) temperature \"absolute zero\" as\n measured in Celsius.\n\n Examples\n --------\n >>> K2F(233.15)\n -39.99999999999996\n \"\"\"\n return 1.8*(K - zero_Celsius) + 32.0\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 850}, "tests/test_core.py::370": {"resolved_imports": ["fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["R2C", "assert_close1d"], "enclosing_function": "test_rankine_to_celcius", "extracted_code": "# Source: fluids/core.py\ndef R2C(Ra: float) -> float:\n \"\"\"Convert Rankine to Celsius.\n\n Parameters\n ----------\n Ra : float\n Rankine temperature to be converted.\n\n Returns\n -------\n C : float\n Equivalent Celsius temperature.\n\n Notes\n -----\n Computes ``C = Ra / 1.8 - zero_Celsius`` where `zero_Celsius` = 273.15,\n i.e., (the absolute value of) temperature \"absolute zero\" as measured in\n Celsius.\n\n Examples\n --------\n >>> R2C(459.67)\n -17.777777777777743\n \"\"\"\n return Ra / 1.8 - zero_Celsius\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 837}, "tests/test_piping.py::53": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/piping.py"], "used_names": ["assert_close1d", "gauge_from_t", "pytest", "t_from_gauge"], "enclosing_function": "test_gauge", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\n\n# Source: fluids/piping.py\ndef gauge_from_t(t: float, SI: bool=True, schedule: str=\"BWG\") -> float:\n r\"\"\"Looks up the gauge of a given wire thickness of given schedule.\n Values are all non-linear, and tabulated internally.\n\n Parameters\n ----------\n t : float\n Thickness, [m]\n SI : bool, optional\n If False, requires that the thickness is given in inches not meters\n schedule : str\n Gauge schedule, one of 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', or 'SSWG'\n\n Returns\n -------\n gauge : float-like\n Wire Gauge, [-]\n\n Notes\n -----\n An internal variable, tol, is used in the selection of the wire gauge. If\n the next smaller wire gauge is within 10% of the difference between it and\n the previous wire gauge, the smaller wire gauge is selected. Accordingly,\n this function can return a gauge with a thickness smaller than desired\n in some circumstances.\n\n * Birmingham Wire Gauge (BWG) ranges from 0.2 (0.5 inch) to 36 (0.004 inch).\n * American Wire Gauge (AWG) ranges from 0.167 (0.58 inch) to 51 (0.00099\n inch). These are used for electrical wires.\n * Steel Wire Gauge (SWG) ranges from 0.143 (0.49 inch) to 51 (0.0044 inch).\n Also called Washburn & Moen wire gauge, American Steel gauge, Wire Co.\n gauge, and Roebling wire gauge.\n * Music Wire Gauge (MWG) ranges from 0.167 (0.004 inch) to 46 (0.18\n inch). Also called Piano Wire Gauge.\n * British Standard Wire Gage (BSWG) ranges from 0.143 (0.5 inch) to\n 51 (0.001 inch). Also called Imperial Wire Gage (IWG).\n * Stub's Steel Wire Gage (SSWG) ranges from 1 (0.227 inch) to 80 (0.013 inch)\n\n Examples\n --------\n >>> gauge_from_t(.5, SI=False, schedule='BWG')\n 0.2\n\n References\n ----------\n .. [1] Oberg, Erik, Franklin D. Jones, and Henry H. Ryffel. Machinery's\n Handbook. Industrial Press, Incorporated, 2012.\n \"\"\"\n tol = 0.1\n # Handle units\n if SI:\n t_inch = round(t/inch, 9) # all schedules are in inches\n else:\n t_inch = t\n\n # Get the schedule\n try:\n sch_integers, sch_inch, sch_SI, decreasing = wire_schedules[schedule]\n except:\n raise ValueError(\"Wire gauge schedule not found\")\n\n # Check if outside limits\n sch_max, sch_min = sch_inch[0], sch_inch[-1]\n if t_inch > sch_max:\n raise ValueError(\"Input thickness is above the largest in the selected schedule\")\n\n\n # If given thickness is exactly in the index, be happy\n if t_inch in sch_inch:\n gauge = sch_integers[sch_inch.index(t_inch)]\n\n else:\n for i in range(len(sch_inch)):\n if sch_inch[i] >= t_inch:\n larger = sch_inch[i]\n else:\n break\n if larger == sch_min:\n gauge = sch_min # If t is under the lowest schedule, be happy\n else:\n smaller = sch_inch[i]\n if (t_inch - smaller) <= tol*(larger - smaller):\n gauge = sch_integers[i]\n else:\n gauge = sch_integers[i-1]\n return gauge\n\ndef t_from_gauge(gauge: float, SI: bool=True, schedule: str=\"BWG\") -> float:\n r\"\"\"Looks up the thickness of a given wire gauge of given schedule.\n Values are all non-linear, and tabulated internally.\n\n Parameters\n ----------\n gauge : float-like\n Wire Gauge, []\n SI : bool, optional\n If False, will return a thickness in inches not meters\n schedule : str\n Gauge schedule, one of 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', or 'SSWG'\n\n Returns\n -------\n t : float\n Thickness, [m]\n\n Notes\n -----\n * Birmingham Wire Gauge (BWG) ranges from 0.2 (0.5 inch) to 36 (0.004 inch).\n * American Wire Gauge (AWG) ranges from 0.167 (0.58 inch) to 51 (0.00099\n inch). These are used for electrical wires.\n * Steel Wire Gauge (SWG) ranges from 0.143 (0.49 inch) to 51 (0.0044 inch).\n Also called Washburn & Moen wire gauge, American Steel gauge, Wire Co.\n gauge, and Roebling wire gauge.\n * Music Wire Gauge (MWG) ranges from 0.167 (0.004 inch) to 46 (0.18\n inch). Also called Piano Wire Gauge.\n * British Standard Wire Gage (BSWG) ranges from 0.143 (0.5 inch) to\n 51 (0.001 inch). Also called Imperial Wire Gage (IWG).\n * Stub's Steel Wire Gage (SSWG) ranges from 1 (0.227 inch) to 80 (0.013 inch)\n\n Examples\n --------\n >>> t_from_gauge(.2, False, 'BWG')\n 0.5\n\n References\n ----------\n .. [1] Oberg, Erik, Franklin D. Jones, and Henry H. Ryffel. Machinery's\n Handbook. Industrial Press, Incorporated, 2012.\n \"\"\"\n try:\n sch_integers, sch_inch, sch_SI, decreasing = wire_schedules[schedule]\n except:\n raise ValueError(\"Wire gauge schedule not found; supported gauges are \\\n'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', and 'SSWG'.\")\n\n try:\n i = sch_integers.index(gauge)\n except:\n raise ValueError(\"Input gauge not found in selected schedule\")\n if SI:\n return sch_SI[i] # returns thickness in m\n else:\n return sch_inch[i]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 5324}, "tests/test_core.py::336": {"resolved_imports": ["fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["K2C", "assert_close1d"], "enclosing_function": "test_kelvin_to_celcius", "extracted_code": "# Source: fluids/core.py\ndef K2C(K: float) -> float:\n \"\"\"Convert Kelvin to Celsius.\n\n Parameters\n ----------\n K : float\n Kelvin temperature to be converted.\n\n Returns\n -------\n C : float\n Equivalent Celsius temperature.\n\n Notes\n -----\n Computes ``C = K - zero_Celsius`` where `zero_Celsius` = 273.15, i.e.,\n (the absolute value of) temperature \"absolute zero\" as measured in Celsius.\n\n Examples\n --------\n >>> K2C(233.15)\n -39.99999999999997\n \"\"\"\n return K - zero_Celsius\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 814}, "tests/test_core.py::365": {"resolved_imports": ["fluids/core.py", "fluids/numerics/__init__.py"], "used_names": ["R2F", "assert_close1d"], "enclosing_function": "test_rankine_to_fahrenheit", "extracted_code": "# Source: fluids/core.py\ndef R2F(Ra: float) -> float:\n \"\"\"Convert Rankine to Fahrenheit.\n\n Parameters\n ----------\n Ra : float\n Rankine temperature to be converted.\n\n Returns\n -------\n F : float\n Equivalent Fahrenheit temperature.\n\n Notes\n -----\n Computes ``F = Ra + 32 - 1.8 * zero_Celsius`` where `zero_Celsius` = 273.15,\n i.e., (the absolute value of) temperature \"absolute zero\" as measured in\n Celsius.\n\n Examples\n --------\n >>> R2F(491.67)\n 32.00000000000006\n \"\"\"\n return Ra - 1.8*zero_Celsius + 32.0\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 851}, "tests/test_pump.py::116": {"resolved_imports": ["fluids/constants/__init__.py", "fluids/numerics/__init__.py", "fluids/pump.py"], "used_names": ["assert_close1d", "speed_synchronous"], "enclosing_function": "test_speed_synchronous", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close1d(a, b, rtol=1e-7, atol=0.0):\n N = len(a)\n if N != len(b):\n raise ValueError(f\"Variables are not the same length: {N}, {len(b)}\")\n for i in range(N):\n assert_close(a[i], b[i], rtol=rtol, atol=atol)\n\n\n# Source: fluids/pump.py\ndef speed_synchronous(f, poles=2):\n r\"\"\"Returns the synchronous speed of a synchronous AC motor according to [1]_.\n\n .. math::\n N_s = \\frac{120 f}{\\text{poles}}\n\n Parameters\n ----------\n f : float\n Line frequency, [Hz]\n poles : int, optional\n The number of poles of the motor\n\n Returns\n -------\n Ns : float\n Speed of synchronous motor, [rpm]\n\n Notes\n -----\n Synchronous motors have no slip. Large synchronous motors are not\n self-starting.\n\n Examples\n --------\n >>> speed_synchronous(50, poles=12)\n 500.0\n >>> speed_synchronous(60, poles=2)\n 3600.0\n\n References\n ----------\n .. [1] All About Circuits. Synchronous Motors. Chapter 13 - AC Motors\n http://www.allaboutcircuits.com/textbook/alternating-current/chpt-13/synchronous-motors/\n \"\"\"\n return 120.*f/poles", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 1169}, "tests/test_units.py::136": {"resolved_imports": ["fluids/__init__.py", "fluids/numerics/__init__.py", "fluids/units.py"], "used_names": ["assert_close", "convert_output", "u"], "enclosing_function": "test_convert_output", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/units.py\ndef convert_output(result, out_units, out_vars, ureg):\n # Attempt to handle multiple return values\n # Must be able to convert all values to a pint expression\n t = type(result)\n output_count = len(out_units)\n if t is str or t is bool or result is None:\n return result\n elif t is dict:\n for key, ans in result.items():\n unit = out_units[out_vars.index(key)]\n result[key] = ans*parse_expression_cached(unit, ureg)\n return result\n elif (t is list or t is ndarray) and output_count == 1:\n return np.array(result)*parse_expression_cached(out_units[0], ureg)\n elif isinstance(result, Iterable):\n conveted_result = []\n for ans, unit in zip(result, out_units):\n conveted_result.append(ans*parse_expression_cached(unit, ureg))\n return conveted_result\n else:\n return result*parse_expression_cached(out_units[0], ureg)", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 1558}, "tests/test_two_phase.py::677": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/two_phase.py", "fluids/two_phase_voidage.py"], "used_names": ["Mandhane_Gregory_Aziz_regime"], "enclosing_function": "test_Mandhane_Gregory_Aziz_regime", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_two_phase.py::686": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/two_phase.py", "fluids/two_phase_voidage.py"], "used_names": ["Mandhane_Gregory_Aziz_regime"], "enclosing_function": "test_Mandhane_Gregory_Aziz_regime", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/test_design_climate.py::95": {"resolved_imports": ["fluids/design_climate.py", "fluids/numerics/__init__.py"], "used_names": ["StationDataGSOD", "get_closest_station", "pytest"], "enclosing_function": "test_correct_WBAN", "extracted_code": "# Source: fluids/design_climate.py\nclass StationDataGSOD:\n # Holds data, caches and retrieves data\n def __init__(self, station, data_dir_override=None):\n self.data_dir_override = data_dir_override\n self.station = station\n\n self.begin = datetime.datetime.strptime(str(self.station.BEGIN), \"%Y%m%d\")\n self.end = datetime.datetime.strptime(str(self.station.END), \"%Y%m%d\")\n\n self.year_range = range(self.begin.year, self.end.year + 1)\n\n# Would be nice to create these later, when using a download_data method\n self.raw_text = {}\n self.raw_data = {}\n self.parsed_data = {}\n self.load_empty_vectors()\n self.download_data()\n self.parse_data()\n\n def load_empty_vectors(self):\n for year in self.year_range:\n days_in_year = 366 if isleap(year) else 365\n self.raw_data[year] = [None]*days_in_year\n self.parsed_data[year] = [None]*days_in_year\n self.raw_text[year] = None\n# days = [None]*days_in_year(y)\n\n def download_data(self):\n for year in self.year_range:\n if self.raw_text[year] is None:\n try:\n year_data = get_station_year_text(self.station.USAF, self.station.WBAN, year, data_dir_override=self.data_dir_override)\n self.raw_text[year] = year_data\n except:\n pass\n\n def parse_data(self):\n for year, data in self.raw_text.items():\n if data is not None:\n days = self.parsed_data[year]\n for line in data.split(\"\\n\")[1:-1]:\n parsed = gsod_day_parser(line)\n doy = parsed.DATE.timetuple().tm_yday-1\n days[doy] = parsed\n\n def coldest_month(self, older_year=None, newer_year=None, minimum_days=23):\n # Tested\n month_data = self.month_average_temperature(older_year=older_year,\n newer_year=newer_year,\n minimum_days=minimum_days)\n return month_data.index(min(month_data))\n\n def warmest_month(self, older_year=None, newer_year=None, minimum_days=23):\n # Tested\n month_data = self.month_average_temperature(older_year=older_year,\n newer_year=newer_year,\n minimum_days=minimum_days)\n return month_data.index(max(month_data))\n\n def month_average_temperature(self, older_year=None, newer_year=None,\n include_yearly=False, minimum_days=23):\n \"\"\"\n >> station = get_closest_station(38.8572, -77.0369)\n >> station_data = StationDataGSOD(station)\n >> station_data.month_average_temperature(1990, 2000, include_yearly=False)\n [276.1599380905833, 277.5375516246206, 281.1881231671554, 286.7367003367004, 291.8689638318671, 296.79545454545456, 299.51868686868687, 298.2097914630174, 294.4116161616162, 288.25883023786247, 282.3188552188553, 277.8282339524275]\n \"\"\"\n # Take years, make them inclusive; add minimum valid days.\n year_month_averages = {}\n year_month_counts = {}\n\n for year, data in self.parsed_data.items():\n if not (older_year <= year <= newer_year):\n continue # Ignore out-of-range years easily\n year_month_averages[year] = [0.0]*12\n year_month_counts[year] = [0]*12\n\n for i, day in enumerate(data):\n if day is None:\n continue\n # Don't do these comparisons to make it fast\n if day.DATE.year < older_year or day.DATE.year > newer_year:\n continue # Ignore out-of-range days as possible\n\n T = day.TEMP\n if T is None:\n continue\n # Cache these lookups\n year_month_averages[year][day.DATE.month-1] += T\n year_month_counts[year][day.DATE.month-1] += 1\n\n for month in range(12):\n count = year_month_counts[year][month]\n if count < minimum_days:\n ans = None\n else:\n ans = year_month_averages[year][month]/count\n year_month_averages[year][month] = ans\n\n # Compute the average of the month\n actual_averages = [0.0]*12\n actual_averages_counts = [0]*12\n for year, average in year_month_averages.items():\n for month in range(12):\n if average is not None and average[month] is not None:\n count = actual_averages_counts[month]\n if count is None:\n count = 1\n else:\n count += 1\n actual_averages_counts[month] = count\n month_average_sum = actual_averages[month]\n if month_average_sum is None:\n month_average_sum = average[month]\n else:\n month_average_sum += average[month]\n actual_averages[month] = month_average_sum\n\n for month in range(12):\n actual_averages[month] = actual_averages[month]/actual_averages_counts[month]\n\n # Don't set anything as properties - too many variables used in calculating thems\n # Speed is not that important.\n if include_yearly:\n return actual_averages, year_month_averages\n else:\n return actual_averages\n\n # Copy and paste\n def month_average_windspeed(self, older_year=None, newer_year=None,\n include_yearly=False, minimum_days=23):\n # Take years, make them inclusive; add minimum valid days.\n year_month_averages = {}\n year_month_counts = {}\n\n for year, data in self.parsed_data.items():\n if not (older_year <= year <= newer_year):\n continue # Ignore out-of-range years easily\n year_month_averages[year] = [0.0]*12\n year_month_counts[year] = [0]*12\n\n for i, day in enumerate(data):\n if day is None:\n continue\n # Don't do these comparisons to make it fast\n if day.DATE.year < older_year or day.DATE.year > newer_year:\n continue # Ignore out-of-range days as possible\n\n wind_speed = day.WDSP\n if wind_speed is None:\n continue\n # Cache these lookups\n year_month_averages[year][day.DATE.month-1] += wind_speed\n year_month_counts[year][day.DATE.month-1] += 1\n\n for month in range(12):\n count = year_month_counts[year][month]\n if count < minimum_days:\n ans = None\n else:\n ans = year_month_averages[year][month]/count\n year_month_averages[year][month] = ans\n\n # Compute the average of the month\n actual_averages = [0.0]*12\n actual_averages_counts = [0]*12\n for year, average in year_month_averages.items():\n for month in range(12):\n if average is not None and average[month] is not None:\n count = actual_averages_counts[month]\n if count is None:\n count = 1\n else:\n count += 1\n actual_averages_counts[month] = count\n month_average_sum = actual_averages[month]\n if month_average_sum is None:\n month_average_sum = average[month]\n else:\n month_average_sum += average[month]\n actual_averages[month] = month_average_sum\n\n for month in range(12):\n actual_averages[month] = actual_averages[month]/actual_averages_counts[month]\n\n # Don't set anything as properties - too many variables used in calculating thems\n # Speed is not that important.\n if include_yearly:\n return actual_averages, year_month_averages\n else:\n return actual_averages\n\n def percentile_extreme_condition(self, older_year=None, newer_year=None,\n include_yearly=False, minimum_days=23, attr=\"WDSP\"):\n # Really need to normalize data with interpolation etc here.\n # Need to get the data, and process it and score interpolation regimes.\n # Or could just randomly drop data and try to fill it in.\n accepted_values = []\n for year in self.parsed_data.keys():\n if not (older_year <= year <= newer_year):\n continue\n\ndef get_closest_station(latitude, longitude, minumum_recent_data=20140000,\n match_max=100):\n \"\"\"Query function to find the nearest weather station to a particular set of\n coordinates. Optionally allows for a recent date by which the station is\n required to be still active at.\n\n Parameters\n ----------\n latitude : float\n Latitude to search for nearby weather stations at, [degrees]\n longitude : float\n Longitude to search for nearby weather stations at, [degrees]\n minumum_recent_data : int, optional\n Date that the weather station is required to have more recent\n weather data than; format YYYYMMDD; set this to 0 to not restrict data\n by date.\n match_max : int, optional\n The maximum number of results in the KDTree to search for before\n applying the filtering criteria; an internal parameter which is\n increased automatically if the default value is insufficient [-]\n\n Returns\n -------\n station : IntegratedSurfaceDatabaseStation\n Instance of IntegratedSurfaceDatabaseStation which was nearest\n to the requested coordinates and with sufficiently recent data\n available [-]\n\n Notes\n -----\n Searching for 100 stations is a reasonable choice as it takes, ~70\n microseconds vs 50 microsecond to find only 1 station. The search does get\n slower as more points are requested. Bad data is returned from a KDTree\n search if more points are requested than are available.\n\n Examples\n --------\n >>> get_closest_station(51.02532675, -114.049868485806, 20150000)\n \n \"\"\"\n # Both station strings may be important\n # Searching for 100 stations is fine, 70 microseconds vs 50 microsecond for 1\n # but there's little point for more points, it gets slower.\n # bad data is returned if k > station_count\n station_count = get_station_count()\n stations = get_stations()\n distances, indexes = get_kd_tree().query([latitude, longitude], k=min(match_max, station_count))\n for i in indexes:\n latlon = _latlongs[i]\n enddate = stations[i].END\n # Iterate for all indexes until one is found whose date is current\n if enddate > minumum_recent_data:\n return stations[i]\n if match_max < station_count:\n return get_closest_station(latitude, longitude, minumum_recent_data=minumum_recent_data, match_max=match_max*10)\n raise ValueError(\"Could not find a station with more recent data than \"\n \"specified near the specified coordinates.\")", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 11615}, "tests/test_numerics_special.py::38": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/special.py"], "used_names": ["assert_close", "exp", "isinf", "isnan", "trunc_exp"], "enclosing_function": "test_trunc_exp", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/numerics/special.py\ndef trunc_exp(x, trunc=1.7976931348622732e+308):\n # maximum value occurs at 709.782712893384 exactly\n try:\n return exp(x)\n except:\n # Really exp(709.7) 1.6549840276802644e+308\n return trunc", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 866}, "tests/test_numerics_special.py::46": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/special.py"], "used_names": ["assert_close", "isinf", "isnan", "log", "trunc_log"], "enclosing_function": "test_trunc_log", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/numerics/special.py\ndef trunc_log(x, trunc=-744.4400719213812):\n # 5e-324 is the smallest floating point number above zero and its log is -744.4400719213812\n # do not allow negative numbers though, do not error on zero\n # 3e-324 same answer\n if x == 0.0:\n return trunc\n return log(x)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 932}, "tests/test_piping.py::182": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/piping.py"], "used_names": ["schedule_lookup"], "enclosing_function": "test_piping_schedule_basics", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_numerics_special.py::40": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/special.py"], "used_names": ["assert_close", "exp", "isinf", "isnan", "trunc_exp"], "enclosing_function": "test_trunc_exp", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/numerics/special.py\ndef trunc_exp(x, trunc=1.7976931348622732e+308):\n # maximum value occurs at 709.782712893384 exactly\n try:\n return exp(x)\n except:\n # Really exp(709.7) 1.6549840276802644e+308\n return trunc", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 866}, "tests/test_numerics_special.py::33": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/special.py"], "used_names": ["assert_close", "hypot", "py_hypot"], "enclosing_function": "test_hypot", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)\n\n\n# Source: fluids/numerics/special.py\ndef py_hypot(x, y):\n x = fabs(x)\n y = fabs(y)\n if x < y:\n x, y = y, x\n if x == 0.0:\n return 0.0\n yx = y/x\n return x*sqrt(1.0 + yx*yx)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 812}, "tests/test_jet_pump.py::165": {"resolved_imports": ["fluids/__init__.py", "fluids/constants/__init__.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "liquid_jet_pump"], "enclosing_function": "validate_liquid_jet_pump", "extracted_code": "# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 607}, "tests/test_drag.py::175": {"resolved_imports": ["fluids/drag.py", "fluids/numerics/__init__.py"], "used_names": ["assert_close", "drag_sphere", "drag_sphere_methods", "pytest"], "enclosing_function": "test_drag_sphere", "extracted_code": "# Source: fluids/drag.py\ndef drag_sphere_methods(Re: float, check_ranges: bool=True) -> list[str]:\n r\"\"\"This function returns a list of methods that can be used to calculate\n the drag coefficient of a sphere.\n Twenty one methods are available, all requiring only the Reynolds number of\n the sphere. Most methods are valid from Re=0 to Re=200,000.\n\n Examples\n --------\n >>> len(drag_sphere_methods(200))\n 20\n >>> len(drag_sphere_methods(200000, check_ranges=False))\n 21\n >>> len(drag_sphere_methods(200000, check_ranges=True))\n 5\n\n Parameters\n ----------\n Re : float\n Particle Reynolds number of the sphere using the surrounding fluid\n density and viscosity, [-]\n check_ranges : bool, optional\n Whether to return only correlations claiming to be valid for the given\n `Re` or not, [-]\n\n Returns\n -------\n methods : list\n List of methods which can be used to calculate `Cd` with the given `Re`\n \"\"\"\n methods = []\n for key, (func, Re_min, Re_max) in drag_sphere_correlations.items():\n if ((Re_min is None or Re > Re_min) and (Re_max is None or Re < Re_max)) or not check_ranges:\n methods.append(key)\n return methods\n\ndef drag_sphere(Re: float, Method: str | None=None) -> float:\n r\"\"\"This function handles calculation of drag coefficient on spheres.\n Twenty methods are available, all requiring only the Reynolds number of the\n sphere. Most methods are valid from Re=0 to Re=200,000. A correlation will\n be automatically selected if none is specified.\n If no correlation is selected, the following rules are used:\n\n * If Re < 0.01, use Stoke's solution.\n * If 0.01 <= Re < 0.1, linearly combine 'Barati' with Stokes's solution\n such that at Re = 0.1 the solution is 'Barati', and at Re = 0.01 the\n solution is 'Stokes'.\n * If 0.1 <= Re <= ~212963, use the 'Barati' solution.\n * If ~212963 < Re <= 1E6, use the 'Barati_high' solution.\n * For Re > 1E6, raises an exception; no valid results have been found.\n\n Examples\n --------\n >>> drag_sphere(200)\n 0.7682237950389874\n\n Parameters\n ----------\n Re : float\n Particle Reynolds number of the sphere using the surrounding fluid\n density and viscosity, [-]\n Method : string, optional\n A string of the function name to use, as in the dictionary\n drag_sphere_correlations\n\n Returns\n -------\n Cd : float\n Drag coefficient [-]\n\n Notes\n -----\n Note that diameter is the characteristic number in the Reynolds number.\n \"\"\"\n if Method is None:\n if Re > 0.1:\n # Smooth transition point between the two models\n if Re <= 212963.26847812787:\n return Barati(Re)\n else:\n return Barati_high(Re)\n elif Re >= 0.01:\n # Re from 0.01 to 0.1\n ratio = (Re - 0.01)/(0.1 - 0.01)\n # Ensure a smooth transition by linearly switching to Stokes' law\n return ratio*Barati(Re) + (1-ratio)*Stokes(Re)\n else:\n return Stokes(Re)\n\n if Method == \"Stokes\":\n return Stokes(Re)\n elif Method == \"Barati\":\n return Barati(Re)\n elif Method == \"Barati_high\":\n return Barati_high(Re)\n elif Method == \"Rouse\":\n return Rouse(Re)\n elif Method == \"Engelund_Hansen\":\n return Engelund_Hansen(Re)\n elif Method == \"Clift_Gauvin\":\n return Clift_Gauvin(Re)\n elif Method == \"Morsi_Alexander\":\n return Morsi_Alexander(Re)\n elif Method == \"Graf\":\n return Graf(Re)\n elif Method == \"Flemmer_Banks\":\n return Flemmer_Banks(Re)\n elif Method == \"Khan_Richardson\":\n return Khan_Richardson(Re)\n elif Method == \"Swamee_Ojha\":\n return Swamee_Ojha(Re)\n elif Method == \"Yen\":\n return Yen(Re)\n elif Method == \"Haider_Levenspiel\":\n return Haider_Levenspiel(Re)\n elif Method == \"Cheng\":\n return Cheng(Re)\n elif Method == \"Terfous\":\n return Terfous(Re)\n elif Method == \"Mikhailov_Freire\":\n return Mikhailov_Freire(Re)\n elif Method == \"Clift\":\n return Clift(Re)\n elif Method == \"Ceylan\":\n return Ceylan(Re)\n elif Method == \"Almedeij\":\n return Almedeij(Re)\n elif Method == \"Morrison\":\n return Morrison(Re)\n elif Method == \"Song_Xu\":\n return Song_Xu(Re)\n else:\n raise ValueError(\"Unrecognized method\")\n\n\n# Source: fluids/numerics/__init__.py\ndef assert_close(a, b, rtol=1e-7, atol=0.0):\n if a is b:\n # Nice to handle None\n return True\n\n if __debug__:\n # Do not run these branches in -O, -OO mode\n try:\n try:\n assert isclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n assert cisclose(a, b, rel_tol=rtol, abs_tol=atol) # noqa: S101\n return\n except:\n pass\n from numpy.testing import assert_allclose\n return assert_allclose(a, b, rtol=rtol, atol=atol)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 5108}, "tests/test_numerics_special.py::193": {"resolved_imports": ["fluids/numerics/__init__.py", "fluids/numerics/special.py"], "used_names": ["math", "py_factorial"], "enclosing_function": "test_py_factorial", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}}}