repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
AguaClara/aguaclara
aguaclara/core/head_loss.py
_k_value_square_reduction
def _k_value_square_reduction(ent_pipe_id, exit_pipe_id, re, f): """Returns the minor loss coefficient for a square reducer. Parameters: ent_pipe_id: Entrance pipe's inner diameter. exit_pipe_id: Exit pipe's inner diameter. re: Reynold's number. f: Darcy friction factor. """ if re < 2500: return (1.2 + (160 / re)) * ((ent_pipe_id / exit_pipe_id) ** 4) else: return (0.6 + 0.48 * f) * (ent_pipe_id / exit_pipe_id) ** 2\ * ((ent_pipe_id / exit_pipe_id) ** 2 - 1)
python
def _k_value_square_reduction(ent_pipe_id, exit_pipe_id, re, f): """Returns the minor loss coefficient for a square reducer. Parameters: ent_pipe_id: Entrance pipe's inner diameter. exit_pipe_id: Exit pipe's inner diameter. re: Reynold's number. f: Darcy friction factor. """ if re < 2500: return (1.2 + (160 / re)) * ((ent_pipe_id / exit_pipe_id) ** 4) else: return (0.6 + 0.48 * f) * (ent_pipe_id / exit_pipe_id) ** 2\ * ((ent_pipe_id / exit_pipe_id) ** 2 - 1)
Returns the minor loss coefficient for a square reducer. Parameters: ent_pipe_id: Entrance pipe's inner diameter. exit_pipe_id: Exit pipe's inner diameter. re: Reynold's number. f: Darcy friction factor.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/head_loss.py#L158-L172
AguaClara/aguaclara
aguaclara/core/head_loss.py
_k_value_tapered_reduction
def _k_value_tapered_reduction(ent_pipe_id, exit_pipe_id, fitting_angle, re, f): """Returns the minor loss coefficient for a tapered reducer. Parameters: ent_pipe_id: Entrance pipe's inner diameter. exit_pipe_id: Exit pipe's inner diameter. fitting_angle: Fitting angle between entrance and exit pipes. re: Reynold's number. f: Darcy friction factor. """ k_value_square_reduction = _k_value_square_reduction(ent_pipe_id, exit_pipe_id, re, f) if 45 < fitting_angle <= 180: return k_value_square_reduction * np.sqrt(np.sin(fitting_angle / 2)) elif 0 < fitting_angle <= 45: return k_value_square_reduction * 1.6 * np.sin(fitting_angle / 2) else: raise ValueError('k_value_tapered_reduction: The reducer angle (' + fitting_angle + ') cannot be outside of [0,180].')
python
def _k_value_tapered_reduction(ent_pipe_id, exit_pipe_id, fitting_angle, re, f): """Returns the minor loss coefficient for a tapered reducer. Parameters: ent_pipe_id: Entrance pipe's inner diameter. exit_pipe_id: Exit pipe's inner diameter. fitting_angle: Fitting angle between entrance and exit pipes. re: Reynold's number. f: Darcy friction factor. """ k_value_square_reduction = _k_value_square_reduction(ent_pipe_id, exit_pipe_id, re, f) if 45 < fitting_angle <= 180: return k_value_square_reduction * np.sqrt(np.sin(fitting_angle / 2)) elif 0 < fitting_angle <= 45: return k_value_square_reduction * 1.6 * np.sin(fitting_angle / 2) else: raise ValueError('k_value_tapered_reduction: The reducer angle (' + fitting_angle + ') cannot be outside of [0,180].')
Returns the minor loss coefficient for a tapered reducer. Parameters: ent_pipe_id: Entrance pipe's inner diameter. exit_pipe_id: Exit pipe's inner diameter. fitting_angle: Fitting angle between entrance and exit pipes. re: Reynold's number. f: Darcy friction factor.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/head_loss.py#L175-L195
AguaClara/aguaclara
aguaclara/unit_process_design/ent_tank.py
drain_OD
def drain_OD(q_plant, T, depth_end, SDR): """Return the nominal diameter of the entrance tank drain pipe. Depth at the end of the flocculator is used for headloss and length calculation inputs in the diam_pipe calculation. Parameters ---------- q_plant: float Plant flow rate T: float Design temperature depth_end: float The depth of water at the end of the flocculator SDR: float Standard dimension ratio Returns ------- float ? Examples -------- >>> from aguaclara.play import* ?? """ nu = pc.viscosity_kinematic(T) K_minor = con.PIPE_ENTRANCE_K_MINOR + con.PIPE_EXIT_K_MINOR + con.EL90_K_MINOR drain_ID = pc.diam_pipe(q_plant, depth_end, depth_end, nu, mat.PVC_PIPE_ROUGH, K_minor) drain_ND = pipe.SDR_available_ND(drain_ID, SDR) return pipe.OD(drain_ND).magnitude
python
def drain_OD(q_plant, T, depth_end, SDR): """Return the nominal diameter of the entrance tank drain pipe. Depth at the end of the flocculator is used for headloss and length calculation inputs in the diam_pipe calculation. Parameters ---------- q_plant: float Plant flow rate T: float Design temperature depth_end: float The depth of water at the end of the flocculator SDR: float Standard dimension ratio Returns ------- float ? Examples -------- >>> from aguaclara.play import* ?? """ nu = pc.viscosity_kinematic(T) K_minor = con.PIPE_ENTRANCE_K_MINOR + con.PIPE_EXIT_K_MINOR + con.EL90_K_MINOR drain_ID = pc.diam_pipe(q_plant, depth_end, depth_end, nu, mat.PVC_PIPE_ROUGH, K_minor) drain_ND = pipe.SDR_available_ND(drain_ID, SDR) return pipe.OD(drain_ND).magnitude
Return the nominal diameter of the entrance tank drain pipe. Depth at the end of the flocculator is used for headloss and length calculation inputs in the diam_pipe calculation. Parameters ---------- q_plant: float Plant flow rate T: float Design temperature depth_end: float The depth of water at the end of the flocculator SDR: float Standard dimension ratio Returns ------- float ? Examples -------- >>> from aguaclara.play import* ??
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/unit_process_design/ent_tank.py#L9-L42
AguaClara/aguaclara
aguaclara/unit_process_design/ent_tank.py
num_plates_ET
def num_plates_ET(q_plant, W_chan): """Return the number of plates in the entrance tank. This number minimizes the total length of the plate settler unit. Parameters ---------- q_plant: float Plant flow rate W_chan: float Width of channel Returns ------- float ? Examples -------- >>> from aguaclara.play import* >>> num_plates_ET(20*u.L/u.s,2*u.m) 1.0 """ num_plates = np.ceil(np.sqrt(q_plant / (design.ent_tank.CENTER_PLATE_DIST.magnitude * W_chan * design.ent_tank.CAPTURE_BOD_VEL.magnitude * np.sin( design.ent_tank.PLATE_ANGLE.to(u.rad).magnitude)))) return num_plates
python
def num_plates_ET(q_plant, W_chan): """Return the number of plates in the entrance tank. This number minimizes the total length of the plate settler unit. Parameters ---------- q_plant: float Plant flow rate W_chan: float Width of channel Returns ------- float ? Examples -------- >>> from aguaclara.play import* >>> num_plates_ET(20*u.L/u.s,2*u.m) 1.0 """ num_plates = np.ceil(np.sqrt(q_plant / (design.ent_tank.CENTER_PLATE_DIST.magnitude * W_chan * design.ent_tank.CAPTURE_BOD_VEL.magnitude * np.sin( design.ent_tank.PLATE_ANGLE.to(u.rad).magnitude)))) return num_plates
Return the number of plates in the entrance tank. This number minimizes the total length of the plate settler unit. Parameters ---------- q_plant: float Plant flow rate W_chan: float Width of channel Returns ------- float ? Examples -------- >>> from aguaclara.play import* >>> num_plates_ET(20*u.L/u.s,2*u.m) 1.0
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/unit_process_design/ent_tank.py#L45-L72
AguaClara/aguaclara
aguaclara/unit_process_design/ent_tank.py
L_plate_ET
def L_plate_ET(q_plant, W_chan): """Return the length of the plates in the entrance tank. Parameters ---------- q_plant: float Plant flow rate W_chan: float Width of channel Returns ------- float ? Examples -------- >>> from aguaclara.play import* >>> L_plate_ET(20*u.L/u.s,2*u.m) 0.00194 """ L_plate = (q_plant / (num_plates_ET(q_plant, W_chan) * W_chan * design.ent_tank.CAPTURE_BOD_VEL.magnitude * np.cos( design.ent_tank.PLATE_ANGLE.to(u.rad).magnitude))) - (design.ent_tank.PLATE_S.magnitude * np.tan(design.ent_tank.PLATE_ANGLE.to(u.rad).magnitude)) return L_plate
python
def L_plate_ET(q_plant, W_chan): """Return the length of the plates in the entrance tank. Parameters ---------- q_plant: float Plant flow rate W_chan: float Width of channel Returns ------- float ? Examples -------- >>> from aguaclara.play import* >>> L_plate_ET(20*u.L/u.s,2*u.m) 0.00194 """ L_plate = (q_plant / (num_plates_ET(q_plant, W_chan) * W_chan * design.ent_tank.CAPTURE_BOD_VEL.magnitude * np.cos( design.ent_tank.PLATE_ANGLE.to(u.rad).magnitude))) - (design.ent_tank.PLATE_S.magnitude * np.tan(design.ent_tank.PLATE_ANGLE.to(u.rad).magnitude)) return L_plate
Return the length of the plates in the entrance tank. Parameters ---------- q_plant: float Plant flow rate W_chan: float Width of channel Returns ------- float ? Examples -------- >>> from aguaclara.play import* >>> L_plate_ET(20*u.L/u.s,2*u.m) 0.00194
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/unit_process_design/ent_tank.py#L75-L101
AguaClara/aguaclara
aguaclara/research/environmental_processes_analysis.py
alpha0_carbonate
def alpha0_carbonate(pH): """Calculate the fraction of total carbonates in carbonic acid form (H2CO3) :param pH: pH of the system :type pH: float :return: Fraction of carbonates in carbonic acid form (H2CO3) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import alpha0_carbonate >>> round(alpha0_carbonate(10), 7) <Quantity(0.00015, 'dimensionless')> """ alpha0_carbonate = 1/(1+(K1_carbonate/invpH(pH)) * (1+(K2_carbonate/invpH(pH)))) return alpha0_carbonate
python
def alpha0_carbonate(pH): """Calculate the fraction of total carbonates in carbonic acid form (H2CO3) :param pH: pH of the system :type pH: float :return: Fraction of carbonates in carbonic acid form (H2CO3) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import alpha0_carbonate >>> round(alpha0_carbonate(10), 7) <Quantity(0.00015, 'dimensionless')> """ alpha0_carbonate = 1/(1+(K1_carbonate/invpH(pH)) * (1+(K2_carbonate/invpH(pH)))) return alpha0_carbonate
Calculate the fraction of total carbonates in carbonic acid form (H2CO3) :param pH: pH of the system :type pH: float :return: Fraction of carbonates in carbonic acid form (H2CO3) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import alpha0_carbonate >>> round(alpha0_carbonate(10), 7) <Quantity(0.00015, 'dimensionless')>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L38-L55
AguaClara/aguaclara
aguaclara/research/environmental_processes_analysis.py
alpha1_carbonate
def alpha1_carbonate(pH): """Calculate the fraction of total carbonates in bicarbonate form (HCO3-) :param pH: pH of the system :type pH: float :return: Fraction of carbonates in bicarbonate form (HCO3-) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import alpha1_carbonate >>> round(alpha1_carbonate(10), 7) <Quantity(0.639969, 'dimensionless')> """ alpha1_carbonate = 1/((invpH(pH)/K1_carbonate) + 1 + (K2_carbonate/invpH(pH))) return alpha1_carbonate
python
def alpha1_carbonate(pH): """Calculate the fraction of total carbonates in bicarbonate form (HCO3-) :param pH: pH of the system :type pH: float :return: Fraction of carbonates in bicarbonate form (HCO3-) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import alpha1_carbonate >>> round(alpha1_carbonate(10), 7) <Quantity(0.639969, 'dimensionless')> """ alpha1_carbonate = 1/((invpH(pH)/K1_carbonate) + 1 + (K2_carbonate/invpH(pH))) return alpha1_carbonate
Calculate the fraction of total carbonates in bicarbonate form (HCO3-) :param pH: pH of the system :type pH: float :return: Fraction of carbonates in bicarbonate form (HCO3-) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import alpha1_carbonate >>> round(alpha1_carbonate(10), 7) <Quantity(0.639969, 'dimensionless')>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L58-L75
AguaClara/aguaclara
aguaclara/research/environmental_processes_analysis.py
alpha2_carbonate
def alpha2_carbonate(pH): """Calculate the fraction of total carbonates in carbonate form (CO3-2) :param pH: pH of the system :type pH: float :return: Fraction of carbonates in carbonate form (CO3-2) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import alpha2_carbonate >>> round(alpha2_carbonate(10), 7) <Quantity(0.359881, 'dimensionless')> """ alpha2_carbonate = 1/(1+(invpH(pH)/K2_carbonate) * (1+(invpH(pH)/K1_carbonate))) return alpha2_carbonate
python
def alpha2_carbonate(pH): """Calculate the fraction of total carbonates in carbonate form (CO3-2) :param pH: pH of the system :type pH: float :return: Fraction of carbonates in carbonate form (CO3-2) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import alpha2_carbonate >>> round(alpha2_carbonate(10), 7) <Quantity(0.359881, 'dimensionless')> """ alpha2_carbonate = 1/(1+(invpH(pH)/K2_carbonate) * (1+(invpH(pH)/K1_carbonate))) return alpha2_carbonate
Calculate the fraction of total carbonates in carbonate form (CO3-2) :param pH: pH of the system :type pH: float :return: Fraction of carbonates in carbonate form (CO3-2) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import alpha2_carbonate >>> round(alpha2_carbonate(10), 7) <Quantity(0.359881, 'dimensionless')>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L78-L95
AguaClara/aguaclara
aguaclara/research/environmental_processes_analysis.py
ANC_closed
def ANC_closed(pH, total_carbonates): """Calculate the acid neutralizing capacity (ANC) under a closed system in which no carbonates are exchanged with the atmosphere during the experiment. Based on pH and total carbonates in the system. :param pH: pH of the system :type pH: float :param total_carbonates: Total carbonate concentration in the system (mole/L) :type total_carbonates: float :return: The acid neutralizing capacity of the closed system (eq/L) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import ANC_closed >>> from aguaclara.core.units import unit_registry as u >>> round(ANC_closed(10, 1*u.mol/u.L), 7) <Quantity(1.359831, 'equivalent / liter')> """ return (total_carbonates * (u.eq/u.mol * alpha1_carbonate(pH) + 2 * u.eq/u.mol * alpha2_carbonate(pH)) + 1 * u.eq/u.mol * Kw/invpH(pH) - 1 * u.eq/u.mol * invpH(pH))
python
def ANC_closed(pH, total_carbonates): """Calculate the acid neutralizing capacity (ANC) under a closed system in which no carbonates are exchanged with the atmosphere during the experiment. Based on pH and total carbonates in the system. :param pH: pH of the system :type pH: float :param total_carbonates: Total carbonate concentration in the system (mole/L) :type total_carbonates: float :return: The acid neutralizing capacity of the closed system (eq/L) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import ANC_closed >>> from aguaclara.core.units import unit_registry as u >>> round(ANC_closed(10, 1*u.mol/u.L), 7) <Quantity(1.359831, 'equivalent / liter')> """ return (total_carbonates * (u.eq/u.mol * alpha1_carbonate(pH) + 2 * u.eq/u.mol * alpha2_carbonate(pH)) + 1 * u.eq/u.mol * Kw/invpH(pH) - 1 * u.eq/u.mol * invpH(pH))
Calculate the acid neutralizing capacity (ANC) under a closed system in which no carbonates are exchanged with the atmosphere during the experiment. Based on pH and total carbonates in the system. :param pH: pH of the system :type pH: float :param total_carbonates: Total carbonate concentration in the system (mole/L) :type total_carbonates: float :return: The acid neutralizing capacity of the closed system (eq/L) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import ANC_closed >>> from aguaclara.core.units import unit_registry as u >>> round(ANC_closed(10, 1*u.mol/u.L), 7) <Quantity(1.359831, 'equivalent / liter')>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L98-L120
AguaClara/aguaclara
aguaclara/research/environmental_processes_analysis.py
aeration_data
def aeration_data(DO_column, dirpath): """Extract the data from folder containing tab delimited files of aeration data. The file must be the original tab delimited file. All text strings below the header must be removed from these files. The file names must be the air flow rates with units of micromoles/s. An example file name would be "300.xls" where 300 is the flow rate in micromoles/s. The function opens a file dialog for the user to select the directory containing the data. :param DO_column: Index of the column that contains the dissolved oxygen concentration data. :type DO_columm: int :param dirpath: Path to the directory containing aeration data you want to analyze :type dirpath: string :return: collection of * **filepaths** (*string list*) - All file paths in the directory sorted by flow rate * **airflows** (*numpy.array*) - Sorted array of air flow rates with units of micromole/s * **DO_data** (*numpy.array list*) - Sorted list of Numpy arrays. Thus each of the numpy data arrays can have different lengths to accommodate short and long experiments * **time_data** (*numpy.array list*) - Sorted list of Numpy arrays containing the times with units of seconds """ #return the list of files in the directory filenames = os.listdir(dirpath) #extract the flowrates from the filenames and apply units airflows = ((np.array([i.split('.', 1)[0] for i in filenames])).astype(np.float32)) #sort airflows and filenames so that they are in ascending order of flow rates idx = np.argsort(airflows) airflows = (np.array(airflows)[idx])*u.umole/u.s filenames = np.array(filenames)[idx] filepaths = [os.path.join(dirpath, i) for i in filenames] #DO_data is a list of numpy arrays. Thus each of the numpy data arrays can have different lengths to accommodate short and long experiments # cycle through all of the files and extract the column of data with oxygen concentrations and the times DO_data=[column_of_data(i,0,DO_column,-1,'mg/L') for i in filepaths] time_data=[(column_of_time(i,0,-1)).to(u.s) for i in filepaths] aeration_collection = collections.namedtuple('aeration_results','filepaths airflows DO_data time_data') aeration_results = aeration_collection(filepaths, airflows, DO_data, time_data) return aeration_results
python
def aeration_data(DO_column, dirpath): """Extract the data from folder containing tab delimited files of aeration data. The file must be the original tab delimited file. All text strings below the header must be removed from these files. The file names must be the air flow rates with units of micromoles/s. An example file name would be "300.xls" where 300 is the flow rate in micromoles/s. The function opens a file dialog for the user to select the directory containing the data. :param DO_column: Index of the column that contains the dissolved oxygen concentration data. :type DO_columm: int :param dirpath: Path to the directory containing aeration data you want to analyze :type dirpath: string :return: collection of * **filepaths** (*string list*) - All file paths in the directory sorted by flow rate * **airflows** (*numpy.array*) - Sorted array of air flow rates with units of micromole/s * **DO_data** (*numpy.array list*) - Sorted list of Numpy arrays. Thus each of the numpy data arrays can have different lengths to accommodate short and long experiments * **time_data** (*numpy.array list*) - Sorted list of Numpy arrays containing the times with units of seconds """ #return the list of files in the directory filenames = os.listdir(dirpath) #extract the flowrates from the filenames and apply units airflows = ((np.array([i.split('.', 1)[0] for i in filenames])).astype(np.float32)) #sort airflows and filenames so that they are in ascending order of flow rates idx = np.argsort(airflows) airflows = (np.array(airflows)[idx])*u.umole/u.s filenames = np.array(filenames)[idx] filepaths = [os.path.join(dirpath, i) for i in filenames] #DO_data is a list of numpy arrays. Thus each of the numpy data arrays can have different lengths to accommodate short and long experiments # cycle through all of the files and extract the column of data with oxygen concentrations and the times DO_data=[column_of_data(i,0,DO_column,-1,'mg/L') for i in filepaths] time_data=[(column_of_time(i,0,-1)).to(u.s) for i in filepaths] aeration_collection = collections.namedtuple('aeration_results','filepaths airflows DO_data time_data') aeration_results = aeration_collection(filepaths, airflows, DO_data, time_data) return aeration_results
Extract the data from folder containing tab delimited files of aeration data. The file must be the original tab delimited file. All text strings below the header must be removed from these files. The file names must be the air flow rates with units of micromoles/s. An example file name would be "300.xls" where 300 is the flow rate in micromoles/s. The function opens a file dialog for the user to select the directory containing the data. :param DO_column: Index of the column that contains the dissolved oxygen concentration data. :type DO_columm: int :param dirpath: Path to the directory containing aeration data you want to analyze :type dirpath: string :return: collection of * **filepaths** (*string list*) - All file paths in the directory sorted by flow rate * **airflows** (*numpy.array*) - Sorted array of air flow rates with units of micromole/s * **DO_data** (*numpy.array list*) - Sorted list of Numpy arrays. Thus each of the numpy data arrays can have different lengths to accommodate short and long experiments * **time_data** (*numpy.array list*) - Sorted list of Numpy arrays containing the times with units of seconds
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L142-L179
AguaClara/aguaclara
aguaclara/research/environmental_processes_analysis.py
O2_sat
def O2_sat(P_air, temp): """Calculate saturaed oxygen concentration in mg/L for 278 K < T < 318 K :param P_air: Air pressure with appropriate units :type P_air: float :param temp: Water temperature with appropriate units :type temp: float :return: Saturated oxygen concentration in mg/L :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import O2_sat >>> from aguaclara.core.units import unit_registry as u >>> round(O2_sat(1*u.atm , 300*u.kelvin), 7) <Quantity(8.0931572, 'milligram / liter')> """ fraction_O2 = 0.21 P_O2 = P_air * fraction_O2 return ((P_O2.to(u.atm).magnitude) * u.mg/u.L*np.exp(1727 / temp.to(u.K).magnitude - 2.105))
python
def O2_sat(P_air, temp): """Calculate saturaed oxygen concentration in mg/L for 278 K < T < 318 K :param P_air: Air pressure with appropriate units :type P_air: float :param temp: Water temperature with appropriate units :type temp: float :return: Saturated oxygen concentration in mg/L :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import O2_sat >>> from aguaclara.core.units import unit_registry as u >>> round(O2_sat(1*u.atm , 300*u.kelvin), 7) <Quantity(8.0931572, 'milligram / liter')> """ fraction_O2 = 0.21 P_O2 = P_air * fraction_O2 return ((P_O2.to(u.atm).magnitude) * u.mg/u.L*np.exp(1727 / temp.to(u.K).magnitude - 2.105))
Calculate saturaed oxygen concentration in mg/L for 278 K < T < 318 K :param P_air: Air pressure with appropriate units :type P_air: float :param temp: Water temperature with appropriate units :type temp: float :return: Saturated oxygen concentration in mg/L :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import O2_sat >>> from aguaclara.core.units import unit_registry as u >>> round(O2_sat(1*u.atm , 300*u.kelvin), 7) <Quantity(8.0931572, 'milligram / liter')>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L182-L203
AguaClara/aguaclara
aguaclara/research/environmental_processes_analysis.py
Gran
def Gran(data_file_path): """Extract the data from a ProCoDA Gran plot file. The file must be the original tab delimited file. :param data_file_path: The path to the file. If the file is in the working directory, then the file name is sufficient. :return: collection of * **V_titrant** (*float*) - Volume of titrant in mL * **ph_data** (*numpy.array*) - pH of the sample * **V_sample** (*float*) - Volume of the original sample that was titrated in mL * **Normality_titrant** (*float*) - Normality of the acid used to titrate the sample in mole/L * **V_equivalent** (*float*) - Volume of acid required to consume all of the ANC in mL * **ANC** (*float*) - Acid Neutralizing Capacity of the sample in mole/L """ df = pd.read_csv(data_file_path, delimiter='\t', header=5) V_t = np.array(pd.to_numeric(df.iloc[0:, 0]))*u.mL pH = np.array(pd.to_numeric(df.iloc[0:, 1])) df = pd.read_csv(data_file_path, delimiter='\t', header=-1, nrows=5) V_S = pd.to_numeric(df.iloc[0, 1])*u.mL N_t = pd.to_numeric(df.iloc[1, 1])*u.mole/u.L V_eq = pd.to_numeric(df.iloc[2, 1])*u.mL ANC_sample = pd.to_numeric(df.iloc[3, 1])*u.mole/u.L Gran_collection = collections.namedtuple('Gran_results', 'V_titrant ph_data V_sample Normality_titrant V_equivalent ANC') Gran = Gran_collection(V_titrant=V_t, ph_data=pH, V_sample=V_S, Normality_titrant=N_t, V_equivalent=V_eq, ANC=ANC_sample) return Gran
python
def Gran(data_file_path): """Extract the data from a ProCoDA Gran plot file. The file must be the original tab delimited file. :param data_file_path: The path to the file. If the file is in the working directory, then the file name is sufficient. :return: collection of * **V_titrant** (*float*) - Volume of titrant in mL * **ph_data** (*numpy.array*) - pH of the sample * **V_sample** (*float*) - Volume of the original sample that was titrated in mL * **Normality_titrant** (*float*) - Normality of the acid used to titrate the sample in mole/L * **V_equivalent** (*float*) - Volume of acid required to consume all of the ANC in mL * **ANC** (*float*) - Acid Neutralizing Capacity of the sample in mole/L """ df = pd.read_csv(data_file_path, delimiter='\t', header=5) V_t = np.array(pd.to_numeric(df.iloc[0:, 0]))*u.mL pH = np.array(pd.to_numeric(df.iloc[0:, 1])) df = pd.read_csv(data_file_path, delimiter='\t', header=-1, nrows=5) V_S = pd.to_numeric(df.iloc[0, 1])*u.mL N_t = pd.to_numeric(df.iloc[1, 1])*u.mole/u.L V_eq = pd.to_numeric(df.iloc[2, 1])*u.mL ANC_sample = pd.to_numeric(df.iloc[3, 1])*u.mole/u.L Gran_collection = collections.namedtuple('Gran_results', 'V_titrant ph_data V_sample Normality_titrant V_equivalent ANC') Gran = Gran_collection(V_titrant=V_t, ph_data=pH, V_sample=V_S, Normality_titrant=N_t, V_equivalent=V_eq, ANC=ANC_sample) return Gran
Extract the data from a ProCoDA Gran plot file. The file must be the original tab delimited file. :param data_file_path: The path to the file. If the file is in the working directory, then the file name is sufficient. :return: collection of * **V_titrant** (*float*) - Volume of titrant in mL * **ph_data** (*numpy.array*) - pH of the sample * **V_sample** (*float*) - Volume of the original sample that was titrated in mL * **Normality_titrant** (*float*) - Normality of the acid used to titrate the sample in mole/L * **V_equivalent** (*float*) - Volume of acid required to consume all of the ANC in mL * **ANC** (*float*) - Acid Neutralizing Capacity of the sample in mole/L
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L206-L232
AguaClara/aguaclara
aguaclara/research/environmental_processes_analysis.py
CMFR
def CMFR(t, C_initial, C_influent): """Calculate the effluent concentration of a conversative (non-reacting) material with continuous input to a completely mixed flow reactor. Note: time t=0 is the time at which the material starts to flow into the reactor. :param C_initial: The concentration in the CMFR at time t=0. :type C_initial: float :param C_influent: The concentration entering the CMFR. :type C_influent: float :param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR. :type t: float or numpy.array :return: Effluent concentration :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import CMFR >>> from aguaclara.core.units import unit_registry as u >>> round(CMFR(0.1, 0*u.mg/u.L, 10*u.mg/u.L), 7) <Quantity(0.9516258, 'milligram / liter')> >>> round(CMFR(0.9, 5*u.mg/u.L, 10*u.mg/u.L), 7) <Quantity(7.9671517, 'milligram / liter')> """ return C_influent * (1-np.exp(-t)) + C_initial*np.exp(-t)
python
def CMFR(t, C_initial, C_influent): """Calculate the effluent concentration of a conversative (non-reacting) material with continuous input to a completely mixed flow reactor. Note: time t=0 is the time at which the material starts to flow into the reactor. :param C_initial: The concentration in the CMFR at time t=0. :type C_initial: float :param C_influent: The concentration entering the CMFR. :type C_influent: float :param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR. :type t: float or numpy.array :return: Effluent concentration :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import CMFR >>> from aguaclara.core.units import unit_registry as u >>> round(CMFR(0.1, 0*u.mg/u.L, 10*u.mg/u.L), 7) <Quantity(0.9516258, 'milligram / liter')> >>> round(CMFR(0.9, 5*u.mg/u.L, 10*u.mg/u.L), 7) <Quantity(7.9671517, 'milligram / liter')> """ return C_influent * (1-np.exp(-t)) + C_initial*np.exp(-t)
Calculate the effluent concentration of a conversative (non-reacting) material with continuous input to a completely mixed flow reactor. Note: time t=0 is the time at which the material starts to flow into the reactor. :param C_initial: The concentration in the CMFR at time t=0. :type C_initial: float :param C_influent: The concentration entering the CMFR. :type C_influent: float :param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR. :type t: float or numpy.array :return: Effluent concentration :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import CMFR >>> from aguaclara.core.units import unit_registry as u >>> round(CMFR(0.1, 0*u.mg/u.L, 10*u.mg/u.L), 7) <Quantity(0.9516258, 'milligram / liter')> >>> round(CMFR(0.9, 5*u.mg/u.L, 10*u.mg/u.L), 7) <Quantity(7.9671517, 'milligram / liter')>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L237-L263
AguaClara/aguaclara
aguaclara/research/environmental_processes_analysis.py
E_CMFR_N
def E_CMFR_N(t, N): """Calculate a dimensionless measure of the output tracer concentration from a spike input to a series of completely mixed flow reactors. :param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR. :type t: float or numpy.array :param N: The number of completely mixed flow reactors (CMFRS) in series. Must be greater than 1. :type N: int :return: Dimensionless measure of the output tracer concentration (concentration * volume of 1 CMFR) / (mass of tracer) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import E_CMFR_N >>> round(E_CMFR_N(0.5, 3), 7) 0.7530643 >>> round(E_CMFR_N(0.1, 1), 7) 0.9048374 """ return (N**N)/special.gamma(N) * (t**(N-1))*np.exp(-N*t)
python
def E_CMFR_N(t, N): """Calculate a dimensionless measure of the output tracer concentration from a spike input to a series of completely mixed flow reactors. :param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR. :type t: float or numpy.array :param N: The number of completely mixed flow reactors (CMFRS) in series. Must be greater than 1. :type N: int :return: Dimensionless measure of the output tracer concentration (concentration * volume of 1 CMFR) / (mass of tracer) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import E_CMFR_N >>> round(E_CMFR_N(0.5, 3), 7) 0.7530643 >>> round(E_CMFR_N(0.1, 1), 7) 0.9048374 """ return (N**N)/special.gamma(N) * (t**(N-1))*np.exp(-N*t)
Calculate a dimensionless measure of the output tracer concentration from a spike input to a series of completely mixed flow reactors. :param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR. :type t: float or numpy.array :param N: The number of completely mixed flow reactors (CMFRS) in series. Must be greater than 1. :type N: int :return: Dimensionless measure of the output tracer concentration (concentration * volume of 1 CMFR) / (mass of tracer) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import E_CMFR_N >>> round(E_CMFR_N(0.5, 3), 7) 0.7530643 >>> round(E_CMFR_N(0.1, 1), 7) 0.9048374
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L266-L286
AguaClara/aguaclara
aguaclara/research/environmental_processes_analysis.py
E_Advective_Dispersion
def E_Advective_Dispersion(t, Pe): """Calculate a dimensionless measure of the output tracer concentration from a spike input to reactor with advection and dispersion. :param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR. :type t: float or numpy.array :param Pe: The ratio of advection to dispersion ((mean fluid velocity)/(Dispersion*flow path length)) :type Pe: float :return: dimensionless measure of the output tracer concentration (concentration * volume of reactor) / (mass of tracer) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import E_Advective_Dispersion >>> round(E_Advective_Dispersion(0.5, 5), 7) 0.4774864 """ # replace any times at zero with a number VERY close to zero to avoid # divide by zero errors if isinstance(t, list): t[t == 0] = 10**(-10) return (Pe/(4*np.pi*t))**(0.5)*np.exp((-Pe*((1-t)**2))/(4*t))
python
def E_Advective_Dispersion(t, Pe): """Calculate a dimensionless measure of the output tracer concentration from a spike input to reactor with advection and dispersion. :param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR. :type t: float or numpy.array :param Pe: The ratio of advection to dispersion ((mean fluid velocity)/(Dispersion*flow path length)) :type Pe: float :return: dimensionless measure of the output tracer concentration (concentration * volume of reactor) / (mass of tracer) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import E_Advective_Dispersion >>> round(E_Advective_Dispersion(0.5, 5), 7) 0.4774864 """ # replace any times at zero with a number VERY close to zero to avoid # divide by zero errors if isinstance(t, list): t[t == 0] = 10**(-10) return (Pe/(4*np.pi*t))**(0.5)*np.exp((-Pe*((1-t)**2))/(4*t))
Calculate a dimensionless measure of the output tracer concentration from a spike input to reactor with advection and dispersion. :param t: The time(s) at which to calculate the effluent concentration. Time can be made dimensionless by dividing by the residence time of the CMFR. :type t: float or numpy.array :param Pe: The ratio of advection to dispersion ((mean fluid velocity)/(Dispersion*flow path length)) :type Pe: float :return: dimensionless measure of the output tracer concentration (concentration * volume of reactor) / (mass of tracer) :rtype: float :Examples: >>> from aguaclara.research.environmental_processes_analysis import E_Advective_Dispersion >>> round(E_Advective_Dispersion(0.5, 5), 7) 0.4774864
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L289-L311
AguaClara/aguaclara
aguaclara/research/environmental_processes_analysis.py
Tracer_CMFR_N
def Tracer_CMFR_N(t_seconds, t_bar, C_bar, N): """Used by Solver_CMFR_N. All inputs and outputs are unitless. This is The model function, f(x, ...). It takes the independent variable as the first argument and the parameters to fit as separate remaining arguments. :param t_seconds: List of times :type t_seconds: float list :param t_bar: Average time spent in the reactor :type t_bar: float :param C_bar: Average concentration (mass of tracer)/(volume of the reactor) :type C_bar: float :param N: Number of completely mixed flow reactors (CMFRs) in series, must be greater than 1 :type N: int :return: The model concentration as a function of time :rtype: float list :Examples: >>> from aguaclara.research.environmental_processes_analysis import Tracer_CMFR_N >>> from aguaclara.core.units import unit_registry as u >>> Tracer_CMFR_N([1, 2, 3, 4, 5]*u.s, 5*u.s, 10*u.mg/u.L, 3) <Quantity([2.96358283 6.50579498 8.03352597 7.83803116 6.72125423], 'milligram / liter')> """ return C_bar*E_CMFR_N(t_seconds/t_bar, N)
python
def Tracer_CMFR_N(t_seconds, t_bar, C_bar, N): """Used by Solver_CMFR_N. All inputs and outputs are unitless. This is The model function, f(x, ...). It takes the independent variable as the first argument and the parameters to fit as separate remaining arguments. :param t_seconds: List of times :type t_seconds: float list :param t_bar: Average time spent in the reactor :type t_bar: float :param C_bar: Average concentration (mass of tracer)/(volume of the reactor) :type C_bar: float :param N: Number of completely mixed flow reactors (CMFRs) in series, must be greater than 1 :type N: int :return: The model concentration as a function of time :rtype: float list :Examples: >>> from aguaclara.research.environmental_processes_analysis import Tracer_CMFR_N >>> from aguaclara.core.units import unit_registry as u >>> Tracer_CMFR_N([1, 2, 3, 4, 5]*u.s, 5*u.s, 10*u.mg/u.L, 3) <Quantity([2.96358283 6.50579498 8.03352597 7.83803116 6.72125423], 'milligram / liter')> """ return C_bar*E_CMFR_N(t_seconds/t_bar, N)
Used by Solver_CMFR_N. All inputs and outputs are unitless. This is The model function, f(x, ...). It takes the independent variable as the first argument and the parameters to fit as separate remaining arguments. :param t_seconds: List of times :type t_seconds: float list :param t_bar: Average time spent in the reactor :type t_bar: float :param C_bar: Average concentration (mass of tracer)/(volume of the reactor) :type C_bar: float :param N: Number of completely mixed flow reactors (CMFRs) in series, must be greater than 1 :type N: int :return: The model concentration as a function of time :rtype: float list :Examples: >>> from aguaclara.research.environmental_processes_analysis import Tracer_CMFR_N >>> from aguaclara.core.units import unit_registry as u >>> Tracer_CMFR_N([1, 2, 3, 4, 5]*u.s, 5*u.s, 10*u.mg/u.L, 3) <Quantity([2.96358283 6.50579498 8.03352597 7.83803116 6.72125423], 'milligram / liter')>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L314-L338
AguaClara/aguaclara
aguaclara/research/environmental_processes_analysis.py
Solver_CMFR_N
def Solver_CMFR_N(t_data, C_data, theta_guess, C_bar_guess): """Use non-linear least squares to fit the function Tracer_CMFR_N(t_seconds, t_bar, C_bar, N) to reactor data. :param t_data: Array of times with units :type t_data: float list :param C_data: Array of tracer concentration data with units :type C_data: float list :param theta_guess: Estimate of time spent in one CMFR with units. :type theta_guess: float :param C_bar_guess: Estimate of average concentration with units ((mass of tracer)/(volume of one CMFR)) :type C_bar_guess: float :return: tuple of * **theta** (*float*)- Residence time in seconds * **C_bar** (*float*) - Average concentration with same units as C_bar_guess * **N** (*float*)- Number of CMFRS in series that best fit the data """ C_unitless = C_data.magnitude C_units = str(C_bar_guess.units) t_seconds = (t_data.to(u.s)).magnitude # assume that a guess of 1 reactor in series is close enough to get a solution p0 = [theta_guess.to(u.s).magnitude, C_bar_guess.magnitude,1] popt, pcov = curve_fit(Tracer_CMFR_N, t_seconds, C_unitless, p0) Solver_theta = popt[0]*u.s Solver_C_bar = popt[1]*u(C_units) Solver_N = popt[2] Reactor_results = collections.namedtuple('Reactor_results','theta C_bar N') CMFR = Reactor_results(theta=Solver_theta, C_bar=Solver_C_bar, N=Solver_N) return CMFR
python
def Solver_CMFR_N(t_data, C_data, theta_guess, C_bar_guess): """Use non-linear least squares to fit the function Tracer_CMFR_N(t_seconds, t_bar, C_bar, N) to reactor data. :param t_data: Array of times with units :type t_data: float list :param C_data: Array of tracer concentration data with units :type C_data: float list :param theta_guess: Estimate of time spent in one CMFR with units. :type theta_guess: float :param C_bar_guess: Estimate of average concentration with units ((mass of tracer)/(volume of one CMFR)) :type C_bar_guess: float :return: tuple of * **theta** (*float*)- Residence time in seconds * **C_bar** (*float*) - Average concentration with same units as C_bar_guess * **N** (*float*)- Number of CMFRS in series that best fit the data """ C_unitless = C_data.magnitude C_units = str(C_bar_guess.units) t_seconds = (t_data.to(u.s)).magnitude # assume that a guess of 1 reactor in series is close enough to get a solution p0 = [theta_guess.to(u.s).magnitude, C_bar_guess.magnitude,1] popt, pcov = curve_fit(Tracer_CMFR_N, t_seconds, C_unitless, p0) Solver_theta = popt[0]*u.s Solver_C_bar = popt[1]*u(C_units) Solver_N = popt[2] Reactor_results = collections.namedtuple('Reactor_results','theta C_bar N') CMFR = Reactor_results(theta=Solver_theta, C_bar=Solver_C_bar, N=Solver_N) return CMFR
Use non-linear least squares to fit the function Tracer_CMFR_N(t_seconds, t_bar, C_bar, N) to reactor data. :param t_data: Array of times with units :type t_data: float list :param C_data: Array of tracer concentration data with units :type C_data: float list :param theta_guess: Estimate of time spent in one CMFR with units. :type theta_guess: float :param C_bar_guess: Estimate of average concentration with units ((mass of tracer)/(volume of one CMFR)) :type C_bar_guess: float :return: tuple of * **theta** (*float*)- Residence time in seconds * **C_bar** (*float*) - Average concentration with same units as C_bar_guess * **N** (*float*)- Number of CMFRS in series that best fit the data
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L341-L371
AguaClara/aguaclara
aguaclara/research/environmental_processes_analysis.py
Tracer_AD_Pe
def Tracer_AD_Pe(t_seconds, t_bar, C_bar, Pe): """Used by Solver_AD_Pe. All inputs and outputs are unitless. This is the model function, f(x, ...). It takes the independent variable as the first argument and the parameters to fit as separate remaining arguments. :param t_seconds: List of times :type t_seconds: float list :param t_bar: Average time spent in the reactor :type t_bar: float :param C_bar: Average concentration ((mass of tracer)/(volume of the reactor)) :type C_bar: float :param Pe: The Peclet number for the reactor. :type Pe: float :return: The model concentration as a function of time :rtype: float list :Examples: >>> from aguaclara.research.environmental_processes_analysis import Tracer_AD_Pe >>> from aguaclara.core.units import unit_registry as u >>> Tracer_AD_Pe([1, 2, 3, 4, 5]*u.s, 5*u.s, 10*u.mg/u.L, 5) <Quantity([0.25833732 3.23793989 5.8349833 6.62508831 6.30783131], 'milligram / liter')> """ return C_bar*E_Advective_Dispersion(t_seconds/t_bar, Pe)
python
def Tracer_AD_Pe(t_seconds, t_bar, C_bar, Pe): """Used by Solver_AD_Pe. All inputs and outputs are unitless. This is the model function, f(x, ...). It takes the independent variable as the first argument and the parameters to fit as separate remaining arguments. :param t_seconds: List of times :type t_seconds: float list :param t_bar: Average time spent in the reactor :type t_bar: float :param C_bar: Average concentration ((mass of tracer)/(volume of the reactor)) :type C_bar: float :param Pe: The Peclet number for the reactor. :type Pe: float :return: The model concentration as a function of time :rtype: float list :Examples: >>> from aguaclara.research.environmental_processes_analysis import Tracer_AD_Pe >>> from aguaclara.core.units import unit_registry as u >>> Tracer_AD_Pe([1, 2, 3, 4, 5]*u.s, 5*u.s, 10*u.mg/u.L, 5) <Quantity([0.25833732 3.23793989 5.8349833 6.62508831 6.30783131], 'milligram / liter')> """ return C_bar*E_Advective_Dispersion(t_seconds/t_bar, Pe)
Used by Solver_AD_Pe. All inputs and outputs are unitless. This is the model function, f(x, ...). It takes the independent variable as the first argument and the parameters to fit as separate remaining arguments. :param t_seconds: List of times :type t_seconds: float list :param t_bar: Average time spent in the reactor :type t_bar: float :param C_bar: Average concentration ((mass of tracer)/(volume of the reactor)) :type C_bar: float :param Pe: The Peclet number for the reactor. :type Pe: float :return: The model concentration as a function of time :rtype: float list :Examples: >>> from aguaclara.research.environmental_processes_analysis import Tracer_AD_Pe >>> from aguaclara.core.units import unit_registry as u >>> Tracer_AD_Pe([1, 2, 3, 4, 5]*u.s, 5*u.s, 10*u.mg/u.L, 5) <Quantity([0.25833732 3.23793989 5.8349833 6.62508831 6.30783131], 'milligram / liter')>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L374-L399
AguaClara/aguaclara
aguaclara/research/environmental_processes_analysis.py
Solver_AD_Pe
def Solver_AD_Pe(t_data, C_data, theta_guess, C_bar_guess): """Use non-linear least squares to fit the function Tracer_AD_Pe(t_seconds, t_bar, C_bar, Pe) to reactor data. :param t_data: Array of times with units :type t_data: float list :param C_data: Array of tracer concentration data with units :type C_data: float list :param theta_guess: Estimate of time spent in one CMFR with units. :type theta_guess: float :param C_bar_guess: Estimate of average concentration with units ((mass of tracer)/(volume of one CMFR)) :type C_bar_guess: float :return: tuple of * **theta** (*float*)- Residence time in seconds * **C_bar** (*float*) - Average concentration with same units as C_bar_guess * **Pe** (*float*) - Peclet number that best fits the data """ #remove time=0 data to eliminate divide by zero error t_data = t_data[1:-1] C_data = C_data[1:-1] C_unitless = C_data.magnitude C_units = str(C_bar_guess.units) t_seconds = (t_data.to(u.s)).magnitude # assume that a guess of 1 reactor in series is close enough to get a solution p0 = [theta_guess.to(u.s).magnitude, C_bar_guess.magnitude,5] popt, pcov = curve_fit(Tracer_AD_Pe, t_seconds, C_unitless, p0, bounds=(0.01,np.inf)) Solver_theta = popt[0]*u.s Solver_C_bar = popt[1]*u(C_units) Solver_Pe = popt[2] Reactor_results = collections.namedtuple('Reactor_results', 'theta C_bar Pe') AD = Reactor_results(theta=Solver_theta, C_bar=Solver_C_bar, Pe=Solver_Pe) return AD
python
def Solver_AD_Pe(t_data, C_data, theta_guess, C_bar_guess): """Use non-linear least squares to fit the function Tracer_AD_Pe(t_seconds, t_bar, C_bar, Pe) to reactor data. :param t_data: Array of times with units :type t_data: float list :param C_data: Array of tracer concentration data with units :type C_data: float list :param theta_guess: Estimate of time spent in one CMFR with units. :type theta_guess: float :param C_bar_guess: Estimate of average concentration with units ((mass of tracer)/(volume of one CMFR)) :type C_bar_guess: float :return: tuple of * **theta** (*float*)- Residence time in seconds * **C_bar** (*float*) - Average concentration with same units as C_bar_guess * **Pe** (*float*) - Peclet number that best fits the data """ #remove time=0 data to eliminate divide by zero error t_data = t_data[1:-1] C_data = C_data[1:-1] C_unitless = C_data.magnitude C_units = str(C_bar_guess.units) t_seconds = (t_data.to(u.s)).magnitude # assume that a guess of 1 reactor in series is close enough to get a solution p0 = [theta_guess.to(u.s).magnitude, C_bar_guess.magnitude,5] popt, pcov = curve_fit(Tracer_AD_Pe, t_seconds, C_unitless, p0, bounds=(0.01,np.inf)) Solver_theta = popt[0]*u.s Solver_C_bar = popt[1]*u(C_units) Solver_Pe = popt[2] Reactor_results = collections.namedtuple('Reactor_results', 'theta C_bar Pe') AD = Reactor_results(theta=Solver_theta, C_bar=Solver_C_bar, Pe=Solver_Pe) return AD
Use non-linear least squares to fit the function Tracer_AD_Pe(t_seconds, t_bar, C_bar, Pe) to reactor data. :param t_data: Array of times with units :type t_data: float list :param C_data: Array of tracer concentration data with units :type C_data: float list :param theta_guess: Estimate of time spent in one CMFR with units. :type theta_guess: float :param C_bar_guess: Estimate of average concentration with units ((mass of tracer)/(volume of one CMFR)) :type C_bar_guess: float :return: tuple of * **theta** (*float*)- Residence time in seconds * **C_bar** (*float*) - Average concentration with same units as C_bar_guess * **Pe** (*float*) - Peclet number that best fits the data
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/environmental_processes_analysis.py#L402-L435
AguaClara/aguaclara
aguaclara/play.py
set_sig_figs
def set_sig_figs(n=4): """Set the number of significant figures used to print Pint, Pandas, and NumPy quantities. Args: n (int): Number of significant figures to display. """ u.default_format = '.' + str(n) + 'g' pd.options.display.float_format = ('{:,.' + str(n) + '}').format
python
def set_sig_figs(n=4): """Set the number of significant figures used to print Pint, Pandas, and NumPy quantities. Args: n (int): Number of significant figures to display. """ u.default_format = '.' + str(n) + 'g' pd.options.display.float_format = ('{:,.' + str(n) + '}').format
Set the number of significant figures used to print Pint, Pandas, and NumPy quantities. Args: n (int): Number of significant figures to display.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/play.py#L43-L51
AguaClara/aguaclara
aguaclara/research/procoda_parser.py
get_data_by_time
def get_data_by_time(path, columns, dates, start_time='00:00', end_time='23:59'): """Extract columns of data from a ProCoDA datalog based on date(s) and time(s) Note: Column 0 is time. The first data column is column 1. :param path: The path to the folder containing the ProCoDA data file(s) :type path: string :param columns: A single index of a column OR a list of indices of columns of data to extract. :type columns: int or int list :param dates: A single date or list of dates for which data was recorded, formatted "M-D-YYYY" :type dates: string or string list :param start_time: Starting time of data to extract, formatted 'HH:MM' (24-hour time) :type start_time: string, optional :param end_time: Ending time of data to extract, formatted 'HH:MM' (24-hour time) :type end_time: string, optional :return: a list containing the single column of data to extract, OR a list of lists containing the columns to extract, in order of the indices given in the columns variable :rtype: list or list list :Examples: .. code-block:: python data = get_data_by_time(path='/Users/.../ProCoDA Data/', columns=4, dates=['6-14-2018', '6-15-2018'], start_time='12:20', end_time='10:50') data = get_data_by_time(path='/Users/.../ProCoDA Data/', columns=[0,4], dates='6-14-2018', start_time='12:20', end_time='23:59') data = get_data_by_time(path='/Users/.../ProCoDA Data/', columns=[0,3,4], dates='6-14-2018') """ data = data_from_dates(path, dates) first_time_column = pd.to_numeric(data[0].iloc[:, 0]) start = max(day_fraction(start_time), first_time_column[0]) start_idx = time_column_index(start, first_time_column) end_idx = time_column_index(day_fraction(end_time), pd.to_numeric(data[-1].iloc[:, 0])) + 1 if isinstance(columns, int): return column_start_to_end(data, columns, start_idx, end_idx) else: result = [] for c in columns: result.append(column_start_to_end(data, c, start_idx, end_idx)) return result
python
def get_data_by_time(path, columns, dates, start_time='00:00', end_time='23:59'): """Extract columns of data from a ProCoDA datalog based on date(s) and time(s) Note: Column 0 is time. The first data column is column 1. :param path: The path to the folder containing the ProCoDA data file(s) :type path: string :param columns: A single index of a column OR a list of indices of columns of data to extract. :type columns: int or int list :param dates: A single date or list of dates for which data was recorded, formatted "M-D-YYYY" :type dates: string or string list :param start_time: Starting time of data to extract, formatted 'HH:MM' (24-hour time) :type start_time: string, optional :param end_time: Ending time of data to extract, formatted 'HH:MM' (24-hour time) :type end_time: string, optional :return: a list containing the single column of data to extract, OR a list of lists containing the columns to extract, in order of the indices given in the columns variable :rtype: list or list list :Examples: .. code-block:: python data = get_data_by_time(path='/Users/.../ProCoDA Data/', columns=4, dates=['6-14-2018', '6-15-2018'], start_time='12:20', end_time='10:50') data = get_data_by_time(path='/Users/.../ProCoDA Data/', columns=[0,4], dates='6-14-2018', start_time='12:20', end_time='23:59') data = get_data_by_time(path='/Users/.../ProCoDA Data/', columns=[0,3,4], dates='6-14-2018') """ data = data_from_dates(path, dates) first_time_column = pd.to_numeric(data[0].iloc[:, 0]) start = max(day_fraction(start_time), first_time_column[0]) start_idx = time_column_index(start, first_time_column) end_idx = time_column_index(day_fraction(end_time), pd.to_numeric(data[-1].iloc[:, 0])) + 1 if isinstance(columns, int): return column_start_to_end(data, columns, start_idx, end_idx) else: result = [] for c in columns: result.append(column_start_to_end(data, c, start_idx, end_idx)) return result
Extract columns of data from a ProCoDA datalog based on date(s) and time(s) Note: Column 0 is time. The first data column is column 1. :param path: The path to the folder containing the ProCoDA data file(s) :type path: string :param columns: A single index of a column OR a list of indices of columns of data to extract. :type columns: int or int list :param dates: A single date or list of dates for which data was recorded, formatted "M-D-YYYY" :type dates: string or string list :param start_time: Starting time of data to extract, formatted 'HH:MM' (24-hour time) :type start_time: string, optional :param end_time: Ending time of data to extract, formatted 'HH:MM' (24-hour time) :type end_time: string, optional :return: a list containing the single column of data to extract, OR a list of lists containing the columns to extract, in order of the indices given in the columns variable :rtype: list or list list :Examples: .. code-block:: python data = get_data_by_time(path='/Users/.../ProCoDA Data/', columns=4, dates=['6-14-2018', '6-15-2018'], start_time='12:20', end_time='10:50') data = get_data_by_time(path='/Users/.../ProCoDA Data/', columns=[0,4], dates='6-14-2018', start_time='12:20', end_time='23:59') data = get_data_by_time(path='/Users/.../ProCoDA Data/', columns=[0,3,4], dates='6-14-2018')
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/procoda_parser.py#L9-L50
AguaClara/aguaclara
aguaclara/research/procoda_parser.py
remove_notes
def remove_notes(data): """Omit notes from a DataFrame object, where notes are identified as rows with non-numerical entries in the first column. :param data: DataFrame object to remove notes from :type data: Pandas.DataFrame :return: DataFrame object with no notes :rtype: Pandas.DataFrame """ has_text = data.iloc[:, 0].astype(str).str.contains('(?!e-)[a-zA-Z]') text_rows = list(has_text.index[has_text]) return data.drop(text_rows)
python
def remove_notes(data): """Omit notes from a DataFrame object, where notes are identified as rows with non-numerical entries in the first column. :param data: DataFrame object to remove notes from :type data: Pandas.DataFrame :return: DataFrame object with no notes :rtype: Pandas.DataFrame """ has_text = data.iloc[:, 0].astype(str).str.contains('(?!e-)[a-zA-Z]') text_rows = list(has_text.index[has_text]) return data.drop(text_rows)
Omit notes from a DataFrame object, where notes are identified as rows with non-numerical entries in the first column. :param data: DataFrame object to remove notes from :type data: Pandas.DataFrame :return: DataFrame object with no notes :rtype: Pandas.DataFrame
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/procoda_parser.py#L53-L64
AguaClara/aguaclara
aguaclara/research/procoda_parser.py
day_fraction
def day_fraction(time): """Convert a 24-hour time to a fraction of a day. For example, midnight corresponds to 0.0, and noon to 0.5. :param time: Time in the form of 'HH:MM' (24-hour time) :type time: string :return: A day fraction :rtype: float :Examples: .. code-block:: python day_fraction("18:30") """ hour = int(time.split(":")[0]) minute = int(time.split(":")[1]) return hour/24 + minute/1440
python
def day_fraction(time): """Convert a 24-hour time to a fraction of a day. For example, midnight corresponds to 0.0, and noon to 0.5. :param time: Time in the form of 'HH:MM' (24-hour time) :type time: string :return: A day fraction :rtype: float :Examples: .. code-block:: python day_fraction("18:30") """ hour = int(time.split(":")[0]) minute = int(time.split(":")[1]) return hour/24 + minute/1440
Convert a 24-hour time to a fraction of a day. For example, midnight corresponds to 0.0, and noon to 0.5. :param time: Time in the form of 'HH:MM' (24-hour time) :type time: string :return: A day fraction :rtype: float :Examples: .. code-block:: python day_fraction("18:30")
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/procoda_parser.py#L67-L86
AguaClara/aguaclara
aguaclara/research/procoda_parser.py
time_column_index
def time_column_index(time, time_column): """Return the index of lowest time in the column of times that is greater than or equal to the given time. :param time: the time to index from the column of time; a day fraction :type time: float :param time_column: a list of times (in day fractions), must be increasing and equally spaced :type time_column: float list :return: approximate index of the time from the column of times :rtype: int """ interval = time_column[1]-time_column[0] return int(round((time - time_column[0])/interval + .5))
python
def time_column_index(time, time_column): """Return the index of lowest time in the column of times that is greater than or equal to the given time. :param time: the time to index from the column of time; a day fraction :type time: float :param time_column: a list of times (in day fractions), must be increasing and equally spaced :type time_column: float list :return: approximate index of the time from the column of times :rtype: int """ interval = time_column[1]-time_column[0] return int(round((time - time_column[0])/interval + .5))
Return the index of lowest time in the column of times that is greater than or equal to the given time. :param time: the time to index from the column of time; a day fraction :type time: float :param time_column: a list of times (in day fractions), must be increasing and equally spaced :type time_column: float list :return: approximate index of the time from the column of times :rtype: int
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/procoda_parser.py#L89-L102
AguaClara/aguaclara
aguaclara/research/procoda_parser.py
data_from_dates
def data_from_dates(path, dates): """Return list DataFrames representing the ProCoDA datalogs stored in the given path and recorded on the given dates. :param path: The path to the folder containing the ProCoDA data file(s) :type path: string :param dates: A single date or list of dates for which data was recorded, formatted "M-D-YYYY" :type dates: string or string list :return: a list DataFrame objects representing the ProCoDA datalogs corresponding with the given dates :rtype: pandas.DataFrame list """ if path[-1] != os.path.sep: path += os.path.sep if not isinstance(dates, list): dates = [dates] data = [] for d in dates: filepath = path + 'datalog ' + d + '.xls' data.append(remove_notes(pd.read_csv(filepath, delimiter='\t'))) return data
python
def data_from_dates(path, dates): """Return list DataFrames representing the ProCoDA datalogs stored in the given path and recorded on the given dates. :param path: The path to the folder containing the ProCoDA data file(s) :type path: string :param dates: A single date or list of dates for which data was recorded, formatted "M-D-YYYY" :type dates: string or string list :return: a list DataFrame objects representing the ProCoDA datalogs corresponding with the given dates :rtype: pandas.DataFrame list """ if path[-1] != os.path.sep: path += os.path.sep if not isinstance(dates, list): dates = [dates] data = [] for d in dates: filepath = path + 'datalog ' + d + '.xls' data.append(remove_notes(pd.read_csv(filepath, delimiter='\t'))) return data
Return list DataFrames representing the ProCoDA datalogs stored in the given path and recorded on the given dates. :param path: The path to the folder containing the ProCoDA data file(s) :type path: string :param dates: A single date or list of dates for which data was recorded, formatted "M-D-YYYY" :type dates: string or string list :return: a list DataFrame objects representing the ProCoDA datalogs corresponding with the given dates :rtype: pandas.DataFrame list
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/procoda_parser.py#L105-L128
AguaClara/aguaclara
aguaclara/research/procoda_parser.py
column_start_to_end
def column_start_to_end(data, column, start_idx, end_idx): """Return a list of numeric data entries in the given column from the starting index to the ending index. This can list can be compiled over one or more DataFrames. :param data: a list of DataFrames to extract data in one column from :type data: Pandas.DataFrame list :param column: a column index :type column: int :param start_idx: the index of the starting row :type start_idx: int :param start_idx: the index of the ending row :type start_idx: int :return: a list of data from the given column :rtype: float list """ if len(data) == 1: result = list(pd.to_numeric(data[0].iloc[start_idx:end_idx, column])) else: result = list(pd.to_numeric(data[0].iloc[start_idx:, column])) for i in range(1, len(data)-1): data[i].iloc[0, 0] = 0 result += list(pd.to_numeric(data[i].iloc[:, column]) + (i if column == 0 else 0)) data[-1].iloc[0, 0] = 0 result += list(pd.to_numeric(data[-1].iloc[:end_idx, column]) + (len(data)-1 if column == 0 else 0)) return result
python
def column_start_to_end(data, column, start_idx, end_idx): """Return a list of numeric data entries in the given column from the starting index to the ending index. This can list can be compiled over one or more DataFrames. :param data: a list of DataFrames to extract data in one column from :type data: Pandas.DataFrame list :param column: a column index :type column: int :param start_idx: the index of the starting row :type start_idx: int :param start_idx: the index of the ending row :type start_idx: int :return: a list of data from the given column :rtype: float list """ if len(data) == 1: result = list(pd.to_numeric(data[0].iloc[start_idx:end_idx, column])) else: result = list(pd.to_numeric(data[0].iloc[start_idx:, column])) for i in range(1, len(data)-1): data[i].iloc[0, 0] = 0 result += list(pd.to_numeric(data[i].iloc[:, column]) + (i if column == 0 else 0)) data[-1].iloc[0, 0] = 0 result += list(pd.to_numeric(data[-1].iloc[:end_idx, column]) + (len(data)-1 if column == 0 else 0)) return result
Return a list of numeric data entries in the given column from the starting index to the ending index. This can list can be compiled over one or more DataFrames. :param data: a list of DataFrames to extract data in one column from :type data: Pandas.DataFrame list :param column: a column index :type column: int :param start_idx: the index of the starting row :type start_idx: int :param start_idx: the index of the ending row :type start_idx: int :return: a list of data from the given column :rtype: float list
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/procoda_parser.py#L131-L160
AguaClara/aguaclara
aguaclara/research/procoda_parser.py
get_data_by_state
def get_data_by_state(path, dates, state, column): """Reads a ProCoDA file and extracts the time and data column for each iteration ofthe given state. Note: column 0 is time, the first data column is column 1. :param path: The path to the folder containing the ProCoDA data file(s), defaults to the current directory :type path: string :param dates: A single date or list of dates for which data was recorded, formatted "M-D-YYYY" :type dates: string or string list :param state: The state ID number for which data should be plotted :type state: int :param column: The integer index of the column that you want to extract OR the header of the column that you want to extract :type column: int or string :return: A list of lists of the time and data columns extracted for each iteration of the state. For example, if "data" is the output, data[i][:,0] gives the time column and data[i][:,1] gives the data column for the ith iteration of the given state and column. data[i][0] would give the first [time, data] pair. :type: list of lists of lists :Examples: .. code-block:: python data = get_data_by_state(path='/Users/.../ProCoDA Data/', dates=["6-19-2013", "6-20-2013"], state=1, column=28) """ data_agg = [] day = 0 first_day = True overnight = False extension = ".xls" if path[-1] != '/': path += '/' if not isinstance(dates, list): dates = [dates] for d in dates: state_file = path + "statelog " + d + extension data_file = path + "datalog " + d + extension states = pd.read_csv(state_file, delimiter='\t') data = pd.read_csv(data_file, delimiter='\t') states = np.array(states) data = np.array(data) # get the start and end times for the state state_start_idx = states[:, 1] == state state_start = states[state_start_idx, 0] state_end_idx = np.append([False], state_start_idx[0:-1]) state_end = states[state_end_idx, 0] if overnight: state_start = np.insert(state_start, 0, 0) state_end = np.insert(state_end, 0, states[0, 0]) if state_start_idx[-1]: np.append(state_end, data[0, -1]) # get the corresponding indices in the data array data_start = [] data_end = [] for i in range(np.size(state_start)): add_start = True for j in range(np.size(data[:, 0])): if (data[j, 0] > state_start[i]) and add_start: data_start.append(j) add_start = False if data[j, 0] > state_end[i]: data_end.append(j-1) break if first_day: start_time = data[0, 0] # extract data at those times for i in range(np.size(data_start)): t = data[data_start[i]:data_end[i], 0] + day - start_time if isinstance(column, int): c = data[data_start[i]:data_end[i], column] else: c = data[column][data_start[i]:data_end[i]] if overnight and i == 0: data_agg = np.insert(data_agg[-1], np.size(data_agg[-1][:, 0]), np.vstack((t, c)).T) else: data_agg.append(np.vstack((t, c)).T) day += 1 if first_day: first_day = False if state_start_idx[-1]: overnight = True return data_agg
python
def get_data_by_state(path, dates, state, column): """Reads a ProCoDA file and extracts the time and data column for each iteration ofthe given state. Note: column 0 is time, the first data column is column 1. :param path: The path to the folder containing the ProCoDA data file(s), defaults to the current directory :type path: string :param dates: A single date or list of dates for which data was recorded, formatted "M-D-YYYY" :type dates: string or string list :param state: The state ID number for which data should be plotted :type state: int :param column: The integer index of the column that you want to extract OR the header of the column that you want to extract :type column: int or string :return: A list of lists of the time and data columns extracted for each iteration of the state. For example, if "data" is the output, data[i][:,0] gives the time column and data[i][:,1] gives the data column for the ith iteration of the given state and column. data[i][0] would give the first [time, data] pair. :type: list of lists of lists :Examples: .. code-block:: python data = get_data_by_state(path='/Users/.../ProCoDA Data/', dates=["6-19-2013", "6-20-2013"], state=1, column=28) """ data_agg = [] day = 0 first_day = True overnight = False extension = ".xls" if path[-1] != '/': path += '/' if not isinstance(dates, list): dates = [dates] for d in dates: state_file = path + "statelog " + d + extension data_file = path + "datalog " + d + extension states = pd.read_csv(state_file, delimiter='\t') data = pd.read_csv(data_file, delimiter='\t') states = np.array(states) data = np.array(data) # get the start and end times for the state state_start_idx = states[:, 1] == state state_start = states[state_start_idx, 0] state_end_idx = np.append([False], state_start_idx[0:-1]) state_end = states[state_end_idx, 0] if overnight: state_start = np.insert(state_start, 0, 0) state_end = np.insert(state_end, 0, states[0, 0]) if state_start_idx[-1]: np.append(state_end, data[0, -1]) # get the corresponding indices in the data array data_start = [] data_end = [] for i in range(np.size(state_start)): add_start = True for j in range(np.size(data[:, 0])): if (data[j, 0] > state_start[i]) and add_start: data_start.append(j) add_start = False if data[j, 0] > state_end[i]: data_end.append(j-1) break if first_day: start_time = data[0, 0] # extract data at those times for i in range(np.size(data_start)): t = data[data_start[i]:data_end[i], 0] + day - start_time if isinstance(column, int): c = data[data_start[i]:data_end[i], column] else: c = data[column][data_start[i]:data_end[i]] if overnight and i == 0: data_agg = np.insert(data_agg[-1], np.size(data_agg[-1][:, 0]), np.vstack((t, c)).T) else: data_agg.append(np.vstack((t, c)).T) day += 1 if first_day: first_day = False if state_start_idx[-1]: overnight = True return data_agg
Reads a ProCoDA file and extracts the time and data column for each iteration ofthe given state. Note: column 0 is time, the first data column is column 1. :param path: The path to the folder containing the ProCoDA data file(s), defaults to the current directory :type path: string :param dates: A single date or list of dates for which data was recorded, formatted "M-D-YYYY" :type dates: string or string list :param state: The state ID number for which data should be plotted :type state: int :param column: The integer index of the column that you want to extract OR the header of the column that you want to extract :type column: int or string :return: A list of lists of the time and data columns extracted for each iteration of the state. For example, if "data" is the output, data[i][:,0] gives the time column and data[i][:,1] gives the data column for the ith iteration of the given state and column. data[i][0] would give the first [time, data] pair. :type: list of lists of lists :Examples: .. code-block:: python data = get_data_by_state(path='/Users/.../ProCoDA Data/', dates=["6-19-2013", "6-20-2013"], state=1, column=28)
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/procoda_parser.py#L163-L256
AguaClara/aguaclara
aguaclara/research/procoda_parser.py
column_of_time
def column_of_time(path, start, end=-1): """This function extracts the column of times from a ProCoDA data file. :param path: The file path of the ProCoDA data file. If the file is in the working directory, then the file name is sufficient. :type path: string :param start: Index of first row of data to extract from the data file :type start: int :param end: Index of last row of data to extract from the data. Defaults to last row :type end: int :return: Experimental times starting at 0 day with units of days. :rtype: numpy.array :Examples: .. code-block:: python time = column_of_time("Reactor_data.txt", 0) """ df = pd.read_csv(path, delimiter='\t') start_time = pd.to_numeric(df.iloc[start, 0])*u.day day_times = pd.to_numeric(df.iloc[start:end, 0]) time_data = np.subtract((np.array(day_times)*u.day), start_time) return time_data
python
def column_of_time(path, start, end=-1): """This function extracts the column of times from a ProCoDA data file. :param path: The file path of the ProCoDA data file. If the file is in the working directory, then the file name is sufficient. :type path: string :param start: Index of first row of data to extract from the data file :type start: int :param end: Index of last row of data to extract from the data. Defaults to last row :type end: int :return: Experimental times starting at 0 day with units of days. :rtype: numpy.array :Examples: .. code-block:: python time = column_of_time("Reactor_data.txt", 0) """ df = pd.read_csv(path, delimiter='\t') start_time = pd.to_numeric(df.iloc[start, 0])*u.day day_times = pd.to_numeric(df.iloc[start:end, 0]) time_data = np.subtract((np.array(day_times)*u.day), start_time) return time_data
This function extracts the column of times from a ProCoDA data file. :param path: The file path of the ProCoDA data file. If the file is in the working directory, then the file name is sufficient. :type path: string :param start: Index of first row of data to extract from the data file :type start: int :param end: Index of last row of data to extract from the data. Defaults to last row :type end: int :return: Experimental times starting at 0 day with units of days. :rtype: numpy.array :Examples: .. code-block:: python time = column_of_time("Reactor_data.txt", 0)
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/procoda_parser.py#L259-L282
AguaClara/aguaclara
aguaclara/research/procoda_parser.py
column_of_data
def column_of_data(path, start, column, end="-1", units=""): """This function extracts a column of data from a ProCoDA data file. Note: Column 0 is time. The first data column is column 1. :param path: The file path of the ProCoDA data file. If the file is in the working directory, then the file name is sufficient. :type path: string :param start: Index of first row of data to extract from the data file :type start: int :param end: Index of last row of data to extract from the data. Defaults to last row :type end: int, optional :param column: Index of the column that you want to extract OR name of the column header that you want to extract :type column: int or string :param units: The units you want to apply to the data, e.g. 'mg/L'. Defaults to "" (dimensionless) :type units: string, optional :return: Experimental data with the units applied. :rtype: numpy.array :Examples: .. code-block:: python data = column_of_data("Reactor_data.txt", 0, 1, -1, "mg/L") """ if not isinstance(start, int): start = int(start) if not isinstance(end, int): end = int(end) df = pd.read_csv(path, delimiter='\t') if units == "": if isinstance(column, int): data = np.array(pd.to_numeric(df.iloc[start:end, column])) else: df[column][0:len(df)] else: if isinstance(column, int): data = np.array(pd.to_numeric(df.iloc[start:end, column]))*u(units) else: df[column][0:len(df)]*u(units) return data
python
def column_of_data(path, start, column, end="-1", units=""): """This function extracts a column of data from a ProCoDA data file. Note: Column 0 is time. The first data column is column 1. :param path: The file path of the ProCoDA data file. If the file is in the working directory, then the file name is sufficient. :type path: string :param start: Index of first row of data to extract from the data file :type start: int :param end: Index of last row of data to extract from the data. Defaults to last row :type end: int, optional :param column: Index of the column that you want to extract OR name of the column header that you want to extract :type column: int or string :param units: The units you want to apply to the data, e.g. 'mg/L'. Defaults to "" (dimensionless) :type units: string, optional :return: Experimental data with the units applied. :rtype: numpy.array :Examples: .. code-block:: python data = column_of_data("Reactor_data.txt", 0, 1, -1, "mg/L") """ if not isinstance(start, int): start = int(start) if not isinstance(end, int): end = int(end) df = pd.read_csv(path, delimiter='\t') if units == "": if isinstance(column, int): data = np.array(pd.to_numeric(df.iloc[start:end, column])) else: df[column][0:len(df)] else: if isinstance(column, int): data = np.array(pd.to_numeric(df.iloc[start:end, column]))*u(units) else: df[column][0:len(df)]*u(units) return data
This function extracts a column of data from a ProCoDA data file. Note: Column 0 is time. The first data column is column 1. :param path: The file path of the ProCoDA data file. If the file is in the working directory, then the file name is sufficient. :type path: string :param start: Index of first row of data to extract from the data file :type start: int :param end: Index of last row of data to extract from the data. Defaults to last row :type end: int, optional :param column: Index of the column that you want to extract OR name of the column header that you want to extract :type column: int or string :param units: The units you want to apply to the data, e.g. 'mg/L'. Defaults to "" (dimensionless) :type units: string, optional :return: Experimental data with the units applied. :rtype: numpy.array :Examples: .. code-block:: python data = column_of_data("Reactor_data.txt", 0, 1, -1, "mg/L")
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/procoda_parser.py#L285-L326
AguaClara/aguaclara
aguaclara/research/procoda_parser.py
notes
def notes(path): """This function extracts any experimental notes from a ProCoDA data file. :param path: The file path of the ProCoDA data file. If the file is in the working directory, then the file name is sufficient. :type path: string :return: The rows of the data file that contain text notes inserted during the experiment. Use this to identify the section of the data file that you want to extract. :rtype: pandas.Dataframe """ df = pd.read_csv(path, delimiter='\t') text_row = df.iloc[0:-1, 0].str.contains('[a-z]', '[A-Z]') text_row_index = text_row.index[text_row].tolist() notes = df.loc[text_row_index] return notes
python
def notes(path): """This function extracts any experimental notes from a ProCoDA data file. :param path: The file path of the ProCoDA data file. If the file is in the working directory, then the file name is sufficient. :type path: string :return: The rows of the data file that contain text notes inserted during the experiment. Use this to identify the section of the data file that you want to extract. :rtype: pandas.Dataframe """ df = pd.read_csv(path, delimiter='\t') text_row = df.iloc[0:-1, 0].str.contains('[a-z]', '[A-Z]') text_row_index = text_row.index[text_row].tolist() notes = df.loc[text_row_index] return notes
This function extracts any experimental notes from a ProCoDA data file. :param path: The file path of the ProCoDA data file. If the file is in the working directory, then the file name is sufficient. :type path: string :return: The rows of the data file that contain text notes inserted during the experiment. Use this to identify the section of the data file that you want to extract. :rtype: pandas.Dataframe
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/procoda_parser.py#L329-L342
AguaClara/aguaclara
aguaclara/research/procoda_parser.py
read_state_with_metafile
def read_state_with_metafile(func, state, column, path, metaids=[], extension=".xls", units=""): """Takes in a ProCoDA meta file and performs a function for all data of a certain state in each of the experiments (denoted by file paths in then metafile) Note: Column 0 is time. The first data column is column 1. :param func: A function that will be applied to data from each instance of the state :type func: function :param state: The state ID number for which data should be extracted :type state: int :param column: Index of the column that you want to extract OR header of the column that you want to extract :type column: int or string :param path: The file path of the ProCoDA data file (must be tab-delimited) :type path: string :param metaids: a list of the experiment IDs you'd like to analyze from the metafile :type metaids: string list, optional :param extension: The file extension of the tab delimited file. Defaults to ".xls" if no argument is passed in :type extension: string, optional :param units: The units you want to apply to the data, e.g. 'mg/L'. Defaults to "" (dimensionless) :type units: string, optional :return: ids (string list) - The list of experiment ids given in the metafile :return: outputs (list) - The outputs of the given function for each experiment :Examples: .. code-block:: python def avg_with_units(lst): num = np.size(lst) acc = 0 for i in lst: acc = i + acc return acc / num path = "../tests/data/Test Meta File.txt" ids, answer = read_state_with_metafile(avg_with_units, 1, 28, path, [], ".xls", "mg/L") """ outputs = [] metafile = pd.read_csv(path, delimiter='\t', header=None) metafile = np.array(metafile) ids = metafile[1:, 0] if not isinstance(ids[0], str): ids = list(map(str, ids)) if metaids: paths = [] for i in range(len(ids)): if ids[i] in metaids: paths.append(metafile[i, 4]) else: paths = metafile[1:, 4] basepath = os.path.join(os.path.split(path)[0], metafile[0, 4]) # use a loop to evaluate each experiment in the metafile for i in range(len(paths)): # get the range of dates for experiment i day1 = metafile[i+1, 1] # modify the metafile date so that it works with datetime format if not (day1[2] == "-" or day1[2] == "/"): day1 = "0" + day1 if not (day1[5] == "-" or day1[5] == "/"): day1 = day1[:3] + "0" + day1[3:] if day1[2] == "-": dt = datetime.strptime(day1, "%m-%d-%Y") else: dt = datetime.strptime(day1, "%m/%d/%y") duration = metafile[i+1, 3] if not isinstance(duration, int): duration = int(duration) date_list = [] for j in range(duration): curr_day = dt.strftime("%m-%d-%Y") if curr_day[3] == "0": curr_day = curr_day[:3] + curr_day[4:] if curr_day[0] == "0": curr_day = curr_day[1:] date_list.append(curr_day) dt = dt + timedelta(days=1) path = str(Path(os.path.join(basepath, paths[i]))) + os.sep _, data = read_state(date_list, state, column, units, path, extension) outputs.append(func(data)) return ids, outputs
python
def read_state_with_metafile(func, state, column, path, metaids=[], extension=".xls", units=""): """Takes in a ProCoDA meta file and performs a function for all data of a certain state in each of the experiments (denoted by file paths in then metafile) Note: Column 0 is time. The first data column is column 1. :param func: A function that will be applied to data from each instance of the state :type func: function :param state: The state ID number for which data should be extracted :type state: int :param column: Index of the column that you want to extract OR header of the column that you want to extract :type column: int or string :param path: The file path of the ProCoDA data file (must be tab-delimited) :type path: string :param metaids: a list of the experiment IDs you'd like to analyze from the metafile :type metaids: string list, optional :param extension: The file extension of the tab delimited file. Defaults to ".xls" if no argument is passed in :type extension: string, optional :param units: The units you want to apply to the data, e.g. 'mg/L'. Defaults to "" (dimensionless) :type units: string, optional :return: ids (string list) - The list of experiment ids given in the metafile :return: outputs (list) - The outputs of the given function for each experiment :Examples: .. code-block:: python def avg_with_units(lst): num = np.size(lst) acc = 0 for i in lst: acc = i + acc return acc / num path = "../tests/data/Test Meta File.txt" ids, answer = read_state_with_metafile(avg_with_units, 1, 28, path, [], ".xls", "mg/L") """ outputs = [] metafile = pd.read_csv(path, delimiter='\t', header=None) metafile = np.array(metafile) ids = metafile[1:, 0] if not isinstance(ids[0], str): ids = list(map(str, ids)) if metaids: paths = [] for i in range(len(ids)): if ids[i] in metaids: paths.append(metafile[i, 4]) else: paths = metafile[1:, 4] basepath = os.path.join(os.path.split(path)[0], metafile[0, 4]) # use a loop to evaluate each experiment in the metafile for i in range(len(paths)): # get the range of dates for experiment i day1 = metafile[i+1, 1] # modify the metafile date so that it works with datetime format if not (day1[2] == "-" or day1[2] == "/"): day1 = "0" + day1 if not (day1[5] == "-" or day1[5] == "/"): day1 = day1[:3] + "0" + day1[3:] if day1[2] == "-": dt = datetime.strptime(day1, "%m-%d-%Y") else: dt = datetime.strptime(day1, "%m/%d/%y") duration = metafile[i+1, 3] if not isinstance(duration, int): duration = int(duration) date_list = [] for j in range(duration): curr_day = dt.strftime("%m-%d-%Y") if curr_day[3] == "0": curr_day = curr_day[:3] + curr_day[4:] if curr_day[0] == "0": curr_day = curr_day[1:] date_list.append(curr_day) dt = dt + timedelta(days=1) path = str(Path(os.path.join(basepath, paths[i]))) + os.sep _, data = read_state(date_list, state, column, units, path, extension) outputs.append(func(data)) return ids, outputs
Takes in a ProCoDA meta file and performs a function for all data of a certain state in each of the experiments (denoted by file paths in then metafile) Note: Column 0 is time. The first data column is column 1. :param func: A function that will be applied to data from each instance of the state :type func: function :param state: The state ID number for which data should be extracted :type state: int :param column: Index of the column that you want to extract OR header of the column that you want to extract :type column: int or string :param path: The file path of the ProCoDA data file (must be tab-delimited) :type path: string :param metaids: a list of the experiment IDs you'd like to analyze from the metafile :type metaids: string list, optional :param extension: The file extension of the tab delimited file. Defaults to ".xls" if no argument is passed in :type extension: string, optional :param units: The units you want to apply to the data, e.g. 'mg/L'. Defaults to "" (dimensionless) :type units: string, optional :return: ids (string list) - The list of experiment ids given in the metafile :return: outputs (list) - The outputs of the given function for each experiment :Examples: .. code-block:: python def avg_with_units(lst): num = np.size(lst) acc = 0 for i in lst: acc = i + acc return acc / num path = "../tests/data/Test Meta File.txt" ids, answer = read_state_with_metafile(avg_with_units, 1, 28, path, [], ".xls", "mg/L")
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/procoda_parser.py#L666-L764
AguaClara/aguaclara
aguaclara/research/procoda_parser.py
write_calculations_to_csv
def write_calculations_to_csv(funcs, states, columns, path, headers, out_name, metaids=[], extension=".xls"): """Writes each output of the given functions on the given states and data columns to a new column in the specified output file. Note: Column 0 is time. The first data column is column 1. :param funcs: A function or list of functions which will be applied in order to the data. If only one function is given it is applied to all the states/columns :type funcs: function or function list :param states: The state ID numbers for which data should be extracted. List should be in order of calculation or if only one state is given then it will be used for all the calculations :type states: string or string list :param columns: The index of a column, the header of a column, a list of indexes, OR a list of headers of the column(s) that you want to apply calculations to :type columns: int, string, int list, or string list :param path: Path to your ProCoDA metafile (must be tab-delimited) :type path: string :param headers: List of the desired header for each calculation, in order :type headers: string list :param out_name: Desired name for the output file. Can include a relative path :type out_name: string :param metaids: A list of the experiment IDs you'd like to analyze from the metafile :type metaids: string list, optional :param extension: The file extension of the tab delimited file. Defaults to ".xls" if no argument is passed in :type extension: string, optional :requires: funcs, states, columns, and headers are all of the same length if they are lists. Some being lists and some single values are okay. :return: out_name.csv (CVS file) - A CSV file with the each column being a new calcuation and each row being a new experiment on which the calcuations were performed :return: output (Pandas.DataFrame)- Pandas DataFrame holding the same data that was written to the output file """ if not isinstance(funcs, list): funcs = [funcs] * len(headers) if not isinstance(states, list): states = [states] * len(headers) if not isinstance(columns, list): columns = [columns] * len(headers) data_agg = [] for i in range(len(headers)): ids, data = read_state_with_metafile(funcs[i], states[i], columns[i], path, metaids, extension) data_agg = np.append(data_agg, [data]) output = pd.DataFrame(data=np.vstack((ids, data_agg)).T, columns=["ID"]+headers) output.to_csv(out_name, sep='\t') return output
python
def write_calculations_to_csv(funcs, states, columns, path, headers, out_name, metaids=[], extension=".xls"): """Writes each output of the given functions on the given states and data columns to a new column in the specified output file. Note: Column 0 is time. The first data column is column 1. :param funcs: A function or list of functions which will be applied in order to the data. If only one function is given it is applied to all the states/columns :type funcs: function or function list :param states: The state ID numbers for which data should be extracted. List should be in order of calculation or if only one state is given then it will be used for all the calculations :type states: string or string list :param columns: The index of a column, the header of a column, a list of indexes, OR a list of headers of the column(s) that you want to apply calculations to :type columns: int, string, int list, or string list :param path: Path to your ProCoDA metafile (must be tab-delimited) :type path: string :param headers: List of the desired header for each calculation, in order :type headers: string list :param out_name: Desired name for the output file. Can include a relative path :type out_name: string :param metaids: A list of the experiment IDs you'd like to analyze from the metafile :type metaids: string list, optional :param extension: The file extension of the tab delimited file. Defaults to ".xls" if no argument is passed in :type extension: string, optional :requires: funcs, states, columns, and headers are all of the same length if they are lists. Some being lists and some single values are okay. :return: out_name.csv (CVS file) - A CSV file with the each column being a new calcuation and each row being a new experiment on which the calcuations were performed :return: output (Pandas.DataFrame)- Pandas DataFrame holding the same data that was written to the output file """ if not isinstance(funcs, list): funcs = [funcs] * len(headers) if not isinstance(states, list): states = [states] * len(headers) if not isinstance(columns, list): columns = [columns] * len(headers) data_agg = [] for i in range(len(headers)): ids, data = read_state_with_metafile(funcs[i], states[i], columns[i], path, metaids, extension) data_agg = np.append(data_agg, [data]) output = pd.DataFrame(data=np.vstack((ids, data_agg)).T, columns=["ID"]+headers) output.to_csv(out_name, sep='\t') return output
Writes each output of the given functions on the given states and data columns to a new column in the specified output file. Note: Column 0 is time. The first data column is column 1. :param funcs: A function or list of functions which will be applied in order to the data. If only one function is given it is applied to all the states/columns :type funcs: function or function list :param states: The state ID numbers for which data should be extracted. List should be in order of calculation or if only one state is given then it will be used for all the calculations :type states: string or string list :param columns: The index of a column, the header of a column, a list of indexes, OR a list of headers of the column(s) that you want to apply calculations to :type columns: int, string, int list, or string list :param path: Path to your ProCoDA metafile (must be tab-delimited) :type path: string :param headers: List of the desired header for each calculation, in order :type headers: string list :param out_name: Desired name for the output file. Can include a relative path :type out_name: string :param metaids: A list of the experiment IDs you'd like to analyze from the metafile :type metaids: string list, optional :param extension: The file extension of the tab delimited file. Defaults to ".xls" if no argument is passed in :type extension: string, optional :requires: funcs, states, columns, and headers are all of the same length if they are lists. Some being lists and some single values are okay. :return: out_name.csv (CVS file) - A CSV file with the each column being a new calcuation and each row being a new experiment on which the calcuations were performed :return: output (Pandas.DataFrame)- Pandas DataFrame holding the same data that was written to the output file
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/procoda_parser.py#L767-L815
AguaClara/aguaclara
aguaclara/design/sed_tank.py
n_sed_plates_max
def n_sed_plates_max(sed_inputs=sed_dict): """Return the maximum possible number of plate settlers in a module given plate spacing, thickness, angle, and unsupported length of plate settler. Parameters ---------- S_plate : float Edge to edge distance between plate settlers thickness_plate : float Thickness of PVC sheet used to make plate settlers L_sed_plate_cantilevered : float Maximum length of sed plate sticking out past module pipes without any additional support. The goal is to prevent floppy modules that don't maintain constant distances between the plates angle_plate : float Angle of plate settlers Returns ------- int Maximum number of plates Examples -------- >>> from aide_design.play import* >>> """ B_plate = sed_inputs['plate_settlers']['S'] + sed_inputs['plate_settlers']['thickness'] return math.floor((sed_inputs['plate_settlers']['L_cantilevered'].magnitude / B_plate.magnitude * np.tan(sed_inputs['plate_settlers']['angle'].to(u.rad).magnitude)) + 1)
python
def n_sed_plates_max(sed_inputs=sed_dict): """Return the maximum possible number of plate settlers in a module given plate spacing, thickness, angle, and unsupported length of plate settler. Parameters ---------- S_plate : float Edge to edge distance between plate settlers thickness_plate : float Thickness of PVC sheet used to make plate settlers L_sed_plate_cantilevered : float Maximum length of sed plate sticking out past module pipes without any additional support. The goal is to prevent floppy modules that don't maintain constant distances between the plates angle_plate : float Angle of plate settlers Returns ------- int Maximum number of plates Examples -------- >>> from aide_design.play import* >>> """ B_plate = sed_inputs['plate_settlers']['S'] + sed_inputs['plate_settlers']['thickness'] return math.floor((sed_inputs['plate_settlers']['L_cantilevered'].magnitude / B_plate.magnitude * np.tan(sed_inputs['plate_settlers']['angle'].to(u.rad).magnitude)) + 1)
Return the maximum possible number of plate settlers in a module given plate spacing, thickness, angle, and unsupported length of plate settler. Parameters ---------- S_plate : float Edge to edge distance between plate settlers thickness_plate : float Thickness of PVC sheet used to make plate settlers L_sed_plate_cantilevered : float Maximum length of sed plate sticking out past module pipes without any additional support. The goal is to prevent floppy modules that don't maintain constant distances between the plates angle_plate : float Angle of plate settlers Returns ------- int Maximum number of plates Examples -------- >>> from aide_design.play import* >>>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L291-L317
AguaClara/aguaclara
aguaclara/design/sed_tank.py
w_diffuser_inner_min
def w_diffuser_inner_min(sed_inputs=sed_dict): """Return the minimum inner width of each diffuser in the sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations. Can be found in sed.yaml Returns ------- float Minimum inner width of each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return ((sed_inputs['tank']['vel_up'].to(u.inch/u.s).magnitude / sed_inputs['manifold']['diffuser']['vel_max'].to(u.inch/u.s).magnitude) * sed_inputs['tank']['W'])
python
def w_diffuser_inner_min(sed_inputs=sed_dict): """Return the minimum inner width of each diffuser in the sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations. Can be found in sed.yaml Returns ------- float Minimum inner width of each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return ((sed_inputs['tank']['vel_up'].to(u.inch/u.s).magnitude / sed_inputs['manifold']['diffuser']['vel_max'].to(u.inch/u.s).magnitude) * sed_inputs['tank']['W'])
Return the minimum inner width of each diffuser in the sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations. Can be found in sed.yaml Returns ------- float Minimum inner width of each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L320-L338
AguaClara/aguaclara
aguaclara/design/sed_tank.py
w_diffuser_inner
def w_diffuser_inner(sed_inputs=sed_dict): """Return the inner width of each diffuser in the sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Inner width of each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return ut.ceil_nearest(w_diffuser_inner_min(sed_inputs).magnitude, (np.arange(1/16,1/4,1/16)*u.inch).magnitude)
python
def w_diffuser_inner(sed_inputs=sed_dict): """Return the inner width of each diffuser in the sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Inner width of each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return ut.ceil_nearest(w_diffuser_inner_min(sed_inputs).magnitude, (np.arange(1/16,1/4,1/16)*u.inch).magnitude)
Return the inner width of each diffuser in the sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Inner width of each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L341-L358
AguaClara/aguaclara
aguaclara/design/sed_tank.py
w_diffuser_outer
def w_diffuser_outer(sed_inputs=sed_dict): """Return the outer width of each diffuser in the sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Outer width of each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return (w_diffuser_inner_min(sed_inputs['tank']['W']) + (2 * sed_inputs['manifold']['diffuser']['thickness_wall'])).to(u.m).magnitude
python
def w_diffuser_outer(sed_inputs=sed_dict): """Return the outer width of each diffuser in the sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Outer width of each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return (w_diffuser_inner_min(sed_inputs['tank']['W']) + (2 * sed_inputs['manifold']['diffuser']['thickness_wall'])).to(u.m).magnitude
Return the outer width of each diffuser in the sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Outer width of each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L361-L378
AguaClara/aguaclara
aguaclara/design/sed_tank.py
L_diffuser_outer
def L_diffuser_outer(sed_inputs=sed_dict): """Return the outer length of each diffuser in the sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Outer length of each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return ((sed_inputs['manifold']['diffuser']['A'] / (2 * sed_inputs['manifold']['diffuser']['thickness_wall'])) - w_diffuser_inner(sed_inputs).to(u.inch)).to(u.m).magnitude
python
def L_diffuser_outer(sed_inputs=sed_dict): """Return the outer length of each diffuser in the sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Outer length of each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return ((sed_inputs['manifold']['diffuser']['A'] / (2 * sed_inputs['manifold']['diffuser']['thickness_wall'])) - w_diffuser_inner(sed_inputs).to(u.inch)).to(u.m).magnitude
Return the outer length of each diffuser in the sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Outer length of each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L381-L399
AguaClara/aguaclara
aguaclara/design/sed_tank.py
L_diffuser_inner
def L_diffuser_inner(sed_inputs=sed_dict): """Return the inner length of each diffuser in the sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Inner length of each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return L_diffuser_outer(sed_inputs['tank']['W']) - (2 * (sed_inputs['manifold']['diffuser']['thickness_wall']).to(u.m)).magnitude)
python
def L_diffuser_inner(sed_inputs=sed_dict): """Return the inner length of each diffuser in the sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Inner length of each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return L_diffuser_outer(sed_inputs['tank']['W']) - (2 * (sed_inputs['manifold']['diffuser']['thickness_wall']).to(u.m)).magnitude)
Return the inner length of each diffuser in the sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Inner length of each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L402-L419
AguaClara/aguaclara
aguaclara/design/sed_tank.py
q_diffuser
def q_diffuser(sed_inputs=sed_dict): """Return the flow through each diffuser. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Flow through each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return (sed_inputs['tank']['vel_up'].to(u.m/u.s) * sed_inputs['tank']['W'].to(u.m) * L_diffuser_outer(sed_inputs)).magnitude
python
def q_diffuser(sed_inputs=sed_dict): """Return the flow through each diffuser. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Flow through each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return (sed_inputs['tank']['vel_up'].to(u.m/u.s) * sed_inputs['tank']['W'].to(u.m) * L_diffuser_outer(sed_inputs)).magnitude
Return the flow through each diffuser. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Flow through each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L422-L440
AguaClara/aguaclara
aguaclara/design/sed_tank.py
vel_sed_diffuser
def vel_sed_diffuser(sed_inputs=sed_dict): """Return the velocity through each diffuser. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Flow through each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return (q_diffuser(sed_inputs).magnitude / (w_diffuser_inner(w_tank) * L_diffuser_inner(w_tank)).magnitude)
python
def vel_sed_diffuser(sed_inputs=sed_dict): """Return the velocity through each diffuser. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Flow through each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return (q_diffuser(sed_inputs).magnitude / (w_diffuser_inner(w_tank) * L_diffuser_inner(w_tank)).magnitude)
Return the velocity through each diffuser. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Flow through each diffuser in the sedimentation tank Examples -------- >>> from aide_design.play import* >>>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L443-L460
AguaClara/aguaclara
aguaclara/design/sed_tank.py
q_tank
def q_tank(sed_inputs=sed_dict): """Return the maximum flow through one sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Maximum flow through one sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return (sed_inputs['tank']['L'] * sed_inputs['tank']['vel_up'].to(u.m/u.s) * sed_inputs['tank']['W'].to(u.m)).magnitude
python
def q_tank(sed_inputs=sed_dict): """Return the maximum flow through one sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Maximum flow through one sedimentation tank Examples -------- >>> from aide_design.play import* >>> """ return (sed_inputs['tank']['L'] * sed_inputs['tank']['vel_up'].to(u.m/u.s) * sed_inputs['tank']['W'].to(u.m)).magnitude
Return the maximum flow through one sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Maximum flow through one sedimentation tank Examples -------- >>> from aide_design.play import* >>>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L463-L480
AguaClara/aguaclara
aguaclara/design/sed_tank.py
vel_inlet_man_max
def vel_inlet_man_max(sed_inputs=sed_dict): """Return the maximum velocity through the manifold. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Maximum velocity through the manifold. Examples -------- >>> from aide_design.play import* >>> """ vel_manifold_max = (sed_inputs['diffuser']['vel_max'].to(u.m/u.s).magnitude * sqrt(2*((1-(sed_inputs['manifold']['ratio_Q_man_orifice'])**2)) / (((sed_inputs['manifold']['ratio_Q_man_orifice'])**2)+1))) return vel_manifold_max
python
def vel_inlet_man_max(sed_inputs=sed_dict): """Return the maximum velocity through the manifold. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Maximum velocity through the manifold. Examples -------- >>> from aide_design.play import* >>> """ vel_manifold_max = (sed_inputs['diffuser']['vel_max'].to(u.m/u.s).magnitude * sqrt(2*((1-(sed_inputs['manifold']['ratio_Q_man_orifice'])**2)) / (((sed_inputs['manifold']['ratio_Q_man_orifice'])**2)+1))) return vel_manifold_max
Return the maximum velocity through the manifold. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Maximum velocity through the manifold. Examples -------- >>> from aide_design.play import* >>>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L483-L502
AguaClara/aguaclara
aguaclara/design/sed_tank.py
n_tanks
def n_tanks(Q_plant, sed_inputs=sed_dict): """Return the number of sedimentation tanks required for a given flow rate. Parameters ---------- Q_plant : float Total plant flow rate sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- int Number of sedimentation tanks required for a given flow rate. Examples -------- >>> from aide_design.play import* >>> """ q = q_tank(sed_inputs).magnitude return (int(np.ceil(Q_plant / q)))
python
def n_tanks(Q_plant, sed_inputs=sed_dict): """Return the number of sedimentation tanks required for a given flow rate. Parameters ---------- Q_plant : float Total plant flow rate sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- int Number of sedimentation tanks required for a given flow rate. Examples -------- >>> from aide_design.play import* >>> """ q = q_tank(sed_inputs).magnitude return (int(np.ceil(Q_plant / q)))
Return the number of sedimentation tanks required for a given flow rate. Parameters ---------- Q_plant : float Total plant flow rate sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- int Number of sedimentation tanks required for a given flow rate. Examples -------- >>> from aide_design.play import* >>>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L505-L524
AguaClara/aguaclara
aguaclara/design/sed_tank.py
L_channel
def L_channel(Q_plant, sed_inputs=sed_dict): """Return the length of the inlet and exit channels for the sedimentation tank. Parameters ---------- Q_plant : float Total plant flow rate sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Length of the inlet and exit channels for the sedimentation tank. Examples -------- >>> from aide_design.play import* >>> """ n_tanks = n_tanks(Q_plant, sed_inputs) return ((n_tanks * sed_inputs['tank']['W']) + sed_inputs['thickness_wall'] + ((n_tanks-1) * sed_inputs['thickness_wall']))
python
def L_channel(Q_plant, sed_inputs=sed_dict): """Return the length of the inlet and exit channels for the sedimentation tank. Parameters ---------- Q_plant : float Total plant flow rate sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Length of the inlet and exit channels for the sedimentation tank. Examples -------- >>> from aide_design.play import* >>> """ n_tanks = n_tanks(Q_plant, sed_inputs) return ((n_tanks * sed_inputs['tank']['W']) + sed_inputs['thickness_wall'] + ((n_tanks-1) * sed_inputs['thickness_wall']))
Return the length of the inlet and exit channels for the sedimentation tank. Parameters ---------- Q_plant : float Total plant flow rate sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Length of the inlet and exit channels for the sedimentation tank. Examples -------- >>> from aide_design.play import* >>>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L527-L547
AguaClara/aguaclara
aguaclara/design/sed_tank.py
ID_exit_man
def ID_exit_man(Q_plant, temp, sed_inputs=sed_dict): """Return the inner diameter of the exit manifold by guessing an initial diameter then iterating through pipe flow calculations until the answer converges within 1%% error Parameters ---------- Q_plant : float Total plant flow rate temp : float Design temperature sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Inner diameter of the exit manifold Examples -------- >>> from aide_design.play import* >>> """ #Inputs do not need to be checked here because they are checked by #functions this function calls. nu = pc.viscosity_dynamic(temp) hl = sed_input['manifold']['exit_man']['hl_orifice'].to(u.m) L = sed_ipnut['manifold']['tank']['L'] N_orifices = sed_inputs['manifold']['exit_man']['N_orifices'] K_minor = con.K_MINOR_PIPE_EXIT pipe_rough = mat.PIPE_ROUGH_PVC.to(u.m) D = max(diam_pipemajor(Q_plant, hl, L, nu, pipe_rough).magnitude, diam_pipeminor(Q_plant, hl, K_minor).magnitude) err = 1.00 while err > 0.01: D_prev = D f = pc.fric(Q_plant, D_prev, nu, pipe_rough) D = ((8*Q_plant**2 / pc.GRAVITY.magnitude * np.pi**2 * hl) * (((f*L/D_prev + K_minor) * (1/3 * 1/) * (1/3 + 1/(2 * N_orifices) + 1/(6 * N_orifices**2))) / (1 - sed_inputs['manifold']['ratio_Q_orifice']**2)))**0.25 err = abs(D_prev - D) / ((D + D_prev) / 2) return D
python
def ID_exit_man(Q_plant, temp, sed_inputs=sed_dict): """Return the inner diameter of the exit manifold by guessing an initial diameter then iterating through pipe flow calculations until the answer converges within 1%% error Parameters ---------- Q_plant : float Total plant flow rate temp : float Design temperature sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Inner diameter of the exit manifold Examples -------- >>> from aide_design.play import* >>> """ #Inputs do not need to be checked here because they are checked by #functions this function calls. nu = pc.viscosity_dynamic(temp) hl = sed_input['manifold']['exit_man']['hl_orifice'].to(u.m) L = sed_ipnut['manifold']['tank']['L'] N_orifices = sed_inputs['manifold']['exit_man']['N_orifices'] K_minor = con.K_MINOR_PIPE_EXIT pipe_rough = mat.PIPE_ROUGH_PVC.to(u.m) D = max(diam_pipemajor(Q_plant, hl, L, nu, pipe_rough).magnitude, diam_pipeminor(Q_plant, hl, K_minor).magnitude) err = 1.00 while err > 0.01: D_prev = D f = pc.fric(Q_plant, D_prev, nu, pipe_rough) D = ((8*Q_plant**2 / pc.GRAVITY.magnitude * np.pi**2 * hl) * (((f*L/D_prev + K_minor) * (1/3 * 1/) * (1/3 + 1/(2 * N_orifices) + 1/(6 * N_orifices**2))) / (1 - sed_inputs['manifold']['ratio_Q_orifice']**2)))**0.25 err = abs(D_prev - D) / ((D + D_prev) / 2) return D
Return the inner diameter of the exit manifold by guessing an initial diameter then iterating through pipe flow calculations until the answer converges within 1%% error Parameters ---------- Q_plant : float Total plant flow rate temp : float Design temperature sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Inner diameter of the exit manifold Examples -------- >>> from aide_design.play import* >>>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L551-L593
AguaClara/aguaclara
aguaclara/design/sed_tank.py
D_exit_man_orifice
def D_exit_man_orifice(Q_plant, drill_bits, sed_inputs=sed_dict): """Return the diameter of the orifices in the exit manifold for the sedimentation tank. Parameters ---------- Q_plant : float Total plant flow rate drill_bits : list List of possible drill bit sizes sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Diameter of the orifices in the exit manifold for the sedimentation tank. Examples -------- >>> from aide_design.play import* >>> """ Q_orifice = Q_plant/sed_input['exit_man']['N_orifices'] D_orifice = np.sqrt(Q_orifice**4)/(np.pi * con.RATIO_VC_ORIFICE * np.sqrt(2 * pc.GRAVITY.magnitude * sed_input['exit_man']['hl_orifice'].magnitude)) return ut.ceil_nearest(D_orifice, drill_bits)
python
def D_exit_man_orifice(Q_plant, drill_bits, sed_inputs=sed_dict): """Return the diameter of the orifices in the exit manifold for the sedimentation tank. Parameters ---------- Q_plant : float Total plant flow rate drill_bits : list List of possible drill bit sizes sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Diameter of the orifices in the exit manifold for the sedimentation tank. Examples -------- >>> from aide_design.play import* >>> """ Q_orifice = Q_plant/sed_input['exit_man']['N_orifices'] D_orifice = np.sqrt(Q_orifice**4)/(np.pi * con.RATIO_VC_ORIFICE * np.sqrt(2 * pc.GRAVITY.magnitude * sed_input['exit_man']['hl_orifice'].magnitude)) return ut.ceil_nearest(D_orifice, drill_bits)
Return the diameter of the orifices in the exit manifold for the sedimentation tank. Parameters ---------- Q_plant : float Total plant flow rate drill_bits : list List of possible drill bit sizes sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Diameter of the orifices in the exit manifold for the sedimentation tank. Examples -------- >>> from aide_design.play import* >>>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L596-L618
AguaClara/aguaclara
aguaclara/design/sed_tank.py
L_sed_plate
def L_sed_plate(sed_inputs=sed_dict): """Return the length of a single plate in the plate settler module based on achieving the desired capture velocity Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Length of a single plate Examples -------- >>> from aide_design.play import* >>> """ L_sed_plate = ((sed_input['plate_settlers']['S'] * ((sed_input['tank']['vel_up']/sed_input['plate_settlers']['vel_capture'])-1) + sed_input['plate_settlers']['thickness'] * (sed_input['tank']['vel_up']/sed_input['plate_settlers']['vel_capture'])) / (np.sin(sed_input['plate_settlers']['angle']) * np.cos(sed_input['plate_settlers']['angle'])) ).to(u.m) return L_sed_plate
python
def L_sed_plate(sed_inputs=sed_dict): """Return the length of a single plate in the plate settler module based on achieving the desired capture velocity Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Length of a single plate Examples -------- >>> from aide_design.play import* >>> """ L_sed_plate = ((sed_input['plate_settlers']['S'] * ((sed_input['tank']['vel_up']/sed_input['plate_settlers']['vel_capture'])-1) + sed_input['plate_settlers']['thickness'] * (sed_input['tank']['vel_up']/sed_input['plate_settlers']['vel_capture'])) / (np.sin(sed_input['plate_settlers']['angle']) * np.cos(sed_input['plate_settlers']['angle'])) ).to(u.m) return L_sed_plate
Return the length of a single plate in the plate settler module based on achieving the desired capture velocity Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns ------- float Length of a single plate Examples -------- >>> from aide_design.play import* >>>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/sed_tank.py#L622-L643
AguaClara/aguaclara
aguaclara/core/pipes.py
OD
def OD(ND): """Return a pipe's outer diameter according to its nominal diameter. The pipe schedule is not required here because all of the pipes of a given nominal diameter have the same outer diameter. Steps: 1. Find the index of the closest nominal diameter. (Should this be changed to find the next largest ND?) 2. Take the values of the array, subtract the ND, take the absolute value, find the index of the minimium value. """ index = (np.abs(np.array(pipedb['NDinch']) - (ND))).argmin() return pipedb.iloc[index, 1]
python
def OD(ND): """Return a pipe's outer diameter according to its nominal diameter. The pipe schedule is not required here because all of the pipes of a given nominal diameter have the same outer diameter. Steps: 1. Find the index of the closest nominal diameter. (Should this be changed to find the next largest ND?) 2. Take the values of the array, subtract the ND, take the absolute value, find the index of the minimium value. """ index = (np.abs(np.array(pipedb['NDinch']) - (ND))).argmin() return pipedb.iloc[index, 1]
Return a pipe's outer diameter according to its nominal diameter. The pipe schedule is not required here because all of the pipes of a given nominal diameter have the same outer diameter. Steps: 1. Find the index of the closest nominal diameter. (Should this be changed to find the next largest ND?) 2. Take the values of the array, subtract the ND, take the absolute value, find the index of the minimium value.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/pipes.py#L42-L55
AguaClara/aguaclara
aguaclara/core/pipes.py
ID_sch40
def ID_sch40(ND): """Return the inner diameter for schedule 40 pipes. The wall thickness for these pipes is in the pipedb. Take the values of the array, subtract the ND, take the absolute value, find the index of the minimium value. """ myindex = (np.abs(np.array(pipedb['NDinch']) - (ND))).argmin() return (pipedb.iloc[myindex, 1] - 2*(pipedb.iloc[myindex, 5]))
python
def ID_sch40(ND): """Return the inner diameter for schedule 40 pipes. The wall thickness for these pipes is in the pipedb. Take the values of the array, subtract the ND, take the absolute value, find the index of the minimium value. """ myindex = (np.abs(np.array(pipedb['NDinch']) - (ND))).argmin() return (pipedb.iloc[myindex, 1] - 2*(pipedb.iloc[myindex, 5]))
Return the inner diameter for schedule 40 pipes. The wall thickness for these pipes is in the pipedb. Take the values of the array, subtract the ND, take the absolute value, find the index of the minimium value.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/pipes.py#L67-L76
AguaClara/aguaclara
aguaclara/core/pipes.py
ND_all_available
def ND_all_available(): """Return an array of available nominal diameters. NDs available are those commonly used as based on the 'Used' column in the pipedb. """ ND_all_available = [] for i in range(len(pipedb['NDinch'])): if pipedb.iloc[i, 4] == 1: ND_all_available.append((pipedb['NDinch'][i])) return ND_all_available * u.inch
python
def ND_all_available(): """Return an array of available nominal diameters. NDs available are those commonly used as based on the 'Used' column in the pipedb. """ ND_all_available = [] for i in range(len(pipedb['NDinch'])): if pipedb.iloc[i, 4] == 1: ND_all_available.append((pipedb['NDinch'][i])) return ND_all_available * u.inch
Return an array of available nominal diameters. NDs available are those commonly used as based on the 'Used' column in the pipedb.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/pipes.py#L79-L89
AguaClara/aguaclara
aguaclara/core/pipes.py
ID_SDR_all_available
def ID_SDR_all_available(SDR): """Return an array of inner diameters with a given SDR. IDs available are those commonly used based on the 'Used' column in the pipedb. """ ID = [] ND = ND_all_available() for i in range(len(ND)): ID.append(ID_SDR(ND[i], SDR).magnitude) return ID * u.inch
python
def ID_SDR_all_available(SDR): """Return an array of inner diameters with a given SDR. IDs available are those commonly used based on the 'Used' column in the pipedb. """ ID = [] ND = ND_all_available() for i in range(len(ND)): ID.append(ID_SDR(ND[i], SDR).magnitude) return ID * u.inch
Return an array of inner diameters with a given SDR. IDs available are those commonly used based on the 'Used' column in the pipedb.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/pipes.py#L92-L102
AguaClara/aguaclara
aguaclara/core/pipes.py
ND_SDR_available
def ND_SDR_available(ID, SDR): """ Return an available ND given an ID and a schedule. Takes the values of the array, compares to the ID, and finds the index of the first value greater or equal. """ for i in range(len(np.array(ID_SDR_all_available(SDR)))): if np.array(ID_SDR_all_available(SDR))[i] >= (ID.to(u.inch)).magnitude: return ND_all_available()[i]
python
def ND_SDR_available(ID, SDR): """ Return an available ND given an ID and a schedule. Takes the values of the array, compares to the ID, and finds the index of the first value greater or equal. """ for i in range(len(np.array(ID_SDR_all_available(SDR)))): if np.array(ID_SDR_all_available(SDR))[i] >= (ID.to(u.inch)).magnitude: return ND_all_available()[i]
Return an available ND given an ID and a schedule. Takes the values of the array, compares to the ID, and finds the index of the first value greater or equal.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/pipes.py#L105-L113
AguaClara/aguaclara
aguaclara/core/pipeline.py
flow_pipeline
def flow_pipeline(diameters, lengths, k_minors, target_headloss, nu=con.WATER_NU, pipe_rough=mats.PVC_PIPE_ROUGH): """ This function takes a single pipeline with multiple sections, each potentially with different diameters, lengths and minor loss coefficients and determines the flow rate for a given headloss. :param diameters: list of diameters, where the i_th diameter corresponds to the i_th pipe section :type diameters: numpy.ndarray :param lengths: list of diameters, where the i_th diameter corresponds to the i_th pipe section :type lengths: numpy.ndarray :param k_minors: list of diameters, where the i_th diameter corresponds to the i_th pipe section :type k_minors: numpy.ndarray :param target_headloss: a single headloss describing the total headloss through the system :type target_headloss: float :param nu: The fluid dynamic viscosity of the fluid. Defaults to water at room temperature (1 * 10**-6 * m**2/s) :type nu: float :param pipe_rough: The pipe roughness. Defaults to PVC roughness. :type pipe_rough: float :return: the total flow through the system :rtype: float """ # Ensure all the arguments except total headloss are the same length #TODO # Total number of pipe lengths n = diameters.size # Start with a flow rate guess based on the flow through a single pipe section flow = pc.flow_pipe(diameters[0], target_headloss, lengths[0], nu, pipe_rough, k_minors[0]) err = 1.0 # Add all the pipe length headlosses together to test the error while abs(err) > 0.01 : headloss = sum([pc.headloss(flow, diameters[i], lengths[i], nu, pipe_rough, k_minors[i]).to(u.m).magnitude for i in range(n)]) # Test the error. This is always less than one. err = (target_headloss - headloss) / (target_headloss + headloss) # Adjust the total flow in the direction of the error. If there is more headloss than target headloss, # The flow should be reduced, and vice-versa. flow = flow + err * flow return flow
python
def flow_pipeline(diameters, lengths, k_minors, target_headloss, nu=con.WATER_NU, pipe_rough=mats.PVC_PIPE_ROUGH): """ This function takes a single pipeline with multiple sections, each potentially with different diameters, lengths and minor loss coefficients and determines the flow rate for a given headloss. :param diameters: list of diameters, where the i_th diameter corresponds to the i_th pipe section :type diameters: numpy.ndarray :param lengths: list of diameters, where the i_th diameter corresponds to the i_th pipe section :type lengths: numpy.ndarray :param k_minors: list of diameters, where the i_th diameter corresponds to the i_th pipe section :type k_minors: numpy.ndarray :param target_headloss: a single headloss describing the total headloss through the system :type target_headloss: float :param nu: The fluid dynamic viscosity of the fluid. Defaults to water at room temperature (1 * 10**-6 * m**2/s) :type nu: float :param pipe_rough: The pipe roughness. Defaults to PVC roughness. :type pipe_rough: float :return: the total flow through the system :rtype: float """ # Ensure all the arguments except total headloss are the same length #TODO # Total number of pipe lengths n = diameters.size # Start with a flow rate guess based on the flow through a single pipe section flow = pc.flow_pipe(diameters[0], target_headloss, lengths[0], nu, pipe_rough, k_minors[0]) err = 1.0 # Add all the pipe length headlosses together to test the error while abs(err) > 0.01 : headloss = sum([pc.headloss(flow, diameters[i], lengths[i], nu, pipe_rough, k_minors[i]).to(u.m).magnitude for i in range(n)]) # Test the error. This is always less than one. err = (target_headloss - headloss) / (target_headloss + headloss) # Adjust the total flow in the direction of the error. If there is more headloss than target headloss, # The flow should be reduced, and vice-versa. flow = flow + err * flow return flow
This function takes a single pipeline with multiple sections, each potentially with different diameters, lengths and minor loss coefficients and determines the flow rate for a given headloss. :param diameters: list of diameters, where the i_th diameter corresponds to the i_th pipe section :type diameters: numpy.ndarray :param lengths: list of diameters, where the i_th diameter corresponds to the i_th pipe section :type lengths: numpy.ndarray :param k_minors: list of diameters, where the i_th diameter corresponds to the i_th pipe section :type k_minors: numpy.ndarray :param target_headloss: a single headloss describing the total headloss through the system :type target_headloss: float :param nu: The fluid dynamic viscosity of the fluid. Defaults to water at room temperature (1 * 10**-6 * m**2/s) :type nu: float :param pipe_rough: The pipe roughness. Defaults to PVC roughness. :type pipe_rough: float :return: the total flow through the system :rtype: float
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/pipeline.py#L13-L56
AguaClara/aguaclara
aguaclara/design/lfom.py
LFOM.stout_w_per_flow
def stout_w_per_flow(self, z): """Return the width of a Stout weir at elevation z. More info here. <https://confluence.cornell.edu/display/AGUACLARA/ LFOM+sutro+weir+research> """ w_per_flow = 2 / ((2 * pc.gravity * z) ** (1 / 2) * con.VC_ORIFICE_RATIO * np.pi * self.hl) return w_per_flow.to_base_units()
python
def stout_w_per_flow(self, z): """Return the width of a Stout weir at elevation z. More info here. <https://confluence.cornell.edu/display/AGUACLARA/ LFOM+sutro+weir+research> """ w_per_flow = 2 / ((2 * pc.gravity * z) ** (1 / 2) * con.VC_ORIFICE_RATIO * np.pi * self.hl) return w_per_flow.to_base_units()
Return the width of a Stout weir at elevation z. More info here. <https://confluence.cornell.edu/display/AGUACLARA/ LFOM+sutro+weir+research>
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/lfom.py#L24-L31
AguaClara/aguaclara
aguaclara/design/lfom.py
LFOM.n_rows
def n_rows(self): """This equation states that the open area corresponding to one row can be set equal to two orifices of diameter=row height. If there are more than two orifices per row at the top of the LFOM then there are more orifices than are convenient to drill and more than necessary for good accuracy. Thus this relationship can be used to increase the spacing between the rows and thus increase the diameter of the orifices. This spacing function also sets the lower depth on the high flow rate LFOM with no accurate flows below a depth equal to the first row height. But it might be better to always set then number of rows to 10. The challenge is to figure out a reasonable system of constraints that reliably returns a valid solution. """ N_estimated = (self.hl * np.pi / (2 * self.stout_w_per_flow(self.hl) * self.q)).to(u.dimensionless) variablerow = min(10, max(4, math.trunc(N_estimated.magnitude))) return variablerow
python
def n_rows(self): """This equation states that the open area corresponding to one row can be set equal to two orifices of diameter=row height. If there are more than two orifices per row at the top of the LFOM then there are more orifices than are convenient to drill and more than necessary for good accuracy. Thus this relationship can be used to increase the spacing between the rows and thus increase the diameter of the orifices. This spacing function also sets the lower depth on the high flow rate LFOM with no accurate flows below a depth equal to the first row height. But it might be better to always set then number of rows to 10. The challenge is to figure out a reasonable system of constraints that reliably returns a valid solution. """ N_estimated = (self.hl * np.pi / (2 * self.stout_w_per_flow(self.hl) * self.q)).to(u.dimensionless) variablerow = min(10, max(4, math.trunc(N_estimated.magnitude))) return variablerow
This equation states that the open area corresponding to one row can be set equal to two orifices of diameter=row height. If there are more than two orifices per row at the top of the LFOM then there are more orifices than are convenient to drill and more than necessary for good accuracy. Thus this relationship can be used to increase the spacing between the rows and thus increase the diameter of the orifices. This spacing function also sets the lower depth on the high flow rate LFOM with no accurate flows below a depth equal to the first row height. But it might be better to always set then number of rows to 10. The challenge is to figure out a reasonable system of constraints that reliably returns a valid solution.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/lfom.py#L34-L50
AguaClara/aguaclara
aguaclara/design/lfom.py
LFOM.vel_critical
def vel_critical(self): """The average vertical velocity of the water inside the LFOM pipe at the very bottom of the bottom row of orifices The speed of falling water is 0.841 m/s for all linear flow orifice meters of height 20 cm, independent of total plant flow rate. """ return (4 / (3 * math.pi) * (2 * pc.gravity * self.hl) ** (1 / 2)).to(u.m/u.s)
python
def vel_critical(self): """The average vertical velocity of the water inside the LFOM pipe at the very bottom of the bottom row of orifices The speed of falling water is 0.841 m/s for all linear flow orifice meters of height 20 cm, independent of total plant flow rate. """ return (4 / (3 * math.pi) * (2 * pc.gravity * self.hl) ** (1 / 2)).to(u.m/u.s)
The average vertical velocity of the water inside the LFOM pipe at the very bottom of the bottom row of orifices The speed of falling water is 0.841 m/s for all linear flow orifice meters of height 20 cm, independent of total plant flow rate.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/lfom.py#L59-L64
AguaClara/aguaclara
aguaclara/design/lfom.py
LFOM.area_pipe_min
def area_pipe_min(self): """The minimum cross-sectional area of the LFOM pipe that assures a safety factor.""" return (self.safety_factor * self.q / self.vel_critical).to(u.cm**2)
python
def area_pipe_min(self): """The minimum cross-sectional area of the LFOM pipe that assures a safety factor.""" return (self.safety_factor * self.q / self.vel_critical).to(u.cm**2)
The minimum cross-sectional area of the LFOM pipe that assures a safety factor.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/lfom.py#L67-L70
AguaClara/aguaclara
aguaclara/design/lfom.py
LFOM.nom_diam_pipe
def nom_diam_pipe(self): """The nominal diameter of the LFOM pipe""" ID = pc.diam_circle(self.area_pipe_min) return pipe.ND_SDR_available(ID, self.sdr)
python
def nom_diam_pipe(self): """The nominal diameter of the LFOM pipe""" ID = pc.diam_circle(self.area_pipe_min) return pipe.ND_SDR_available(ID, self.sdr)
The nominal diameter of the LFOM pipe
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/lfom.py#L73-L76
AguaClara/aguaclara
aguaclara/design/lfom.py
LFOM.area_top_orifice
def area_top_orifice(self): """Estimate the orifice area corresponding to the top row of orifices. Another solution method is to use integration to solve this problem. Here we use the width of the stout weir in the center of the top row to estimate the area of the top orifice """ # Calculate the center of the top row: z = self.hl - 0.5 * self.b_rows # Multiply the stout weir width by the height of one row. return self.stout_w_per_flow(z) * self.q * self.b_rows
python
def area_top_orifice(self): """Estimate the orifice area corresponding to the top row of orifices. Another solution method is to use integration to solve this problem. Here we use the width of the stout weir in the center of the top row to estimate the area of the top orifice """ # Calculate the center of the top row: z = self.hl - 0.5 * self.b_rows # Multiply the stout weir width by the height of one row. return self.stout_w_per_flow(z) * self.q * self.b_rows
Estimate the orifice area corresponding to the top row of orifices. Another solution method is to use integration to solve this problem. Here we use the width of the stout weir in the center of the top row to estimate the area of the top orifice
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/lfom.py#L79-L88
AguaClara/aguaclara
aguaclara/design/lfom.py
LFOM.orifice_diameter
def orifice_diameter(self): """The actual orifice diameter. We don't let the diameter extend beyond its row space. """ maxdrill = min(self.b_rows, self.d_orifice_max) return ut.floor_nearest(maxdrill, self.drill_bits)
python
def orifice_diameter(self): """The actual orifice diameter. We don't let the diameter extend beyond its row space. """ maxdrill = min(self.b_rows, self.d_orifice_max) return ut.floor_nearest(maxdrill, self.drill_bits)
The actual orifice diameter. We don't let the diameter extend beyond its row space.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/lfom.py#L96-L100
AguaClara/aguaclara
aguaclara/design/lfom.py
LFOM.n_orifices_per_row_max
def n_orifices_per_row_max(self): """A bound on the number of orifices allowed in each row. The distance between consecutive orifices must be enough to retain structural integrity of the pipe. """ c = math.pi * pipe.ID_SDR(self.nom_diam_pipe, self.sdr) b = self.orifice_diameter + self.s_orifice return math.floor(c/b)
python
def n_orifices_per_row_max(self): """A bound on the number of orifices allowed in each row. The distance between consecutive orifices must be enough to retain structural integrity of the pipe. """ c = math.pi * pipe.ID_SDR(self.nom_diam_pipe, self.sdr) b = self.orifice_diameter + self.s_orifice return math.floor(c/b)
A bound on the number of orifices allowed in each row. The distance between consecutive orifices must be enough to retain structural integrity of the pipe.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/lfom.py#L108-L116
AguaClara/aguaclara
aguaclara/design/lfom.py
LFOM.flow_ramp
def flow_ramp(self): """An equally spaced array representing flow at each row.""" return np.linspace(1 / self.n_rows, 1, self.n_rows)*self.q
python
def flow_ramp(self): """An equally spaced array representing flow at each row.""" return np.linspace(1 / self.n_rows, 1, self.n_rows)*self.q
An equally spaced array representing flow at each row.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/lfom.py#L119-L121
AguaClara/aguaclara
aguaclara/design/lfom.py
LFOM.height_orifices
def height_orifices(self): """Calculates the height of the center of each row of orifices. The bottom of the bottom row orifices is at the zero elevation point of the LFOM so that the flow goes to zero when the water height is at zero. """ return (np.linspace(0, self.n_rows-1, self.n_rows))*self.b_rows + 0.5 * self.orifice_diameter
python
def height_orifices(self): """Calculates the height of the center of each row of orifices. The bottom of the bottom row orifices is at the zero elevation point of the LFOM so that the flow goes to zero when the water height is at zero. """ return (np.linspace(0, self.n_rows-1, self.n_rows))*self.b_rows + 0.5 * self.orifice_diameter
Calculates the height of the center of each row of orifices. The bottom of the bottom row orifices is at the zero elevation point of the LFOM so that the flow goes to zero when the water height is at zero.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/lfom.py#L124-L131
AguaClara/aguaclara
aguaclara/design/lfom.py
LFOM.flow_actual
def flow_actual(self, Row_Index_Submerged, N_LFOM_Orifices): """Calculates the flow for a given number of submerged rows of orifices harray is the distance from the water level to the center of the orifices when the water is at the max level. Parameters ---------- Row_Index_Submerged: int The index of the submerged row. All rows below and including this index are submerged. N_LFOM_Orifices: [int] The number of orifices at each row. Returns -------- The flow through all of the orifices that are submerged. """ flow = 0 for i in range(Row_Index_Submerged + 1): flow = flow + (N_LFOM_Orifices[i] * ( pc.flow_orifice_vert(self.orifice_diameter, self.b_rows*(Row_Index_Submerged + 1) - self.height_orifices[i], con.VC_ORIFICE_RATIO))) return flow
python
def flow_actual(self, Row_Index_Submerged, N_LFOM_Orifices): """Calculates the flow for a given number of submerged rows of orifices harray is the distance from the water level to the center of the orifices when the water is at the max level. Parameters ---------- Row_Index_Submerged: int The index of the submerged row. All rows below and including this index are submerged. N_LFOM_Orifices: [int] The number of orifices at each row. Returns -------- The flow through all of the orifices that are submerged. """ flow = 0 for i in range(Row_Index_Submerged + 1): flow = flow + (N_LFOM_Orifices[i] * ( pc.flow_orifice_vert(self.orifice_diameter, self.b_rows*(Row_Index_Submerged + 1) - self.height_orifices[i], con.VC_ORIFICE_RATIO))) return flow
Calculates the flow for a given number of submerged rows of orifices harray is the distance from the water level to the center of the orifices when the water is at the max level. Parameters ---------- Row_Index_Submerged: int The index of the submerged row. All rows below and including this index are submerged. N_LFOM_Orifices: [int] The number of orifices at each row. Returns -------- The flow through all of the orifices that are submerged.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/lfom.py#L133-L156
AguaClara/aguaclara
aguaclara/design/lfom.py
LFOM.n_orifices_per_row
def n_orifices_per_row(self): """Calculate number of orifices at each level given an orifice diameter. """ # H is distance from the bottom of the next row of orifices to the # center of the current row of orifices H = self.b_rows - 0.5*self.orifice_diameter flow_per_orifice = pc.flow_orifice_vert(self.orifice_diameter, H, con.VC_ORIFICE_RATIO) n = np.zeros(self.n_rows) for i in range(self.n_rows): # calculate the ideal number of orifices at the current row without # constraining to an integer flow_needed = self.flow_ramp[i] - self.flow_actual(i, n) n_orifices_real = (flow_needed / flow_per_orifice).to(u.dimensionless) # constrain number of orifices to be less than the max per row and # greater or equal to 0 n[i] = min((max(0, round(n_orifices_real))), self.n_orifices_per_row_max) return n
python
def n_orifices_per_row(self): """Calculate number of orifices at each level given an orifice diameter. """ # H is distance from the bottom of the next row of orifices to the # center of the current row of orifices H = self.b_rows - 0.5*self.orifice_diameter flow_per_orifice = pc.flow_orifice_vert(self.orifice_diameter, H, con.VC_ORIFICE_RATIO) n = np.zeros(self.n_rows) for i in range(self.n_rows): # calculate the ideal number of orifices at the current row without # constraining to an integer flow_needed = self.flow_ramp[i] - self.flow_actual(i, n) n_orifices_real = (flow_needed / flow_per_orifice).to(u.dimensionless) # constrain number of orifices to be less than the max per row and # greater or equal to 0 n[i] = min((max(0, round(n_orifices_real))), self.n_orifices_per_row_max) return n
Calculate number of orifices at each level given an orifice diameter.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/lfom.py#L159-L176
AguaClara/aguaclara
aguaclara/design/lfom.py
LFOM.error_per_row
def error_per_row(self): """This function calculates the error of the design based on the differences between the predicted flow rate and the actual flow rate through the LFOM.""" FLOW_lfom_error = np.zeros(self.n_rows) for i in range(self.n_rows): actual_flow = self.flow_actual(i, self.n_orifices_per_row) FLOW_lfom_error[i] = (((actual_flow - self.flow_ramp[i]) / self.flow_ramp[i]).to(u.dimensionless)).magnitude return FLOW_lfom_error
python
def error_per_row(self): """This function calculates the error of the design based on the differences between the predicted flow rate and the actual flow rate through the LFOM.""" FLOW_lfom_error = np.zeros(self.n_rows) for i in range(self.n_rows): actual_flow = self.flow_actual(i, self.n_orifices_per_row) FLOW_lfom_error[i] = (((actual_flow - self.flow_ramp[i]) / self.flow_ramp[i]).to(u.dimensionless)).magnitude return FLOW_lfom_error
This function calculates the error of the design based on the differences between the predicted flow rate and the actual flow rate through the LFOM.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/lfom.py#L179-L187
AguaClara/aguaclara
aguaclara/core/drills.py
get_drill_bits_d_imperial
def get_drill_bits_d_imperial(): """Return array of possible drill diameters in imperial.""" step_32nd = np.arange(0.03125, 0.25, 0.03125) step_8th = np.arange(0.25, 1.0, 0.125) step_4th = np.arange(1.0, 2.0, 0.25) maximum = [2.0] return np.concatenate((step_32nd, step_8th, step_4th, maximum)) * u.inch
python
def get_drill_bits_d_imperial(): """Return array of possible drill diameters in imperial.""" step_32nd = np.arange(0.03125, 0.25, 0.03125) step_8th = np.arange(0.25, 1.0, 0.125) step_4th = np.arange(1.0, 2.0, 0.25) maximum = [2.0] return np.concatenate((step_32nd, step_8th, step_4th, maximum)) * u.inch
Return array of possible drill diameters in imperial.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/drills.py#L8-L18
AguaClara/aguaclara
aguaclara/core/drills.py
get_drill_bits_d_metric
def get_drill_bits_d_metric(): """Return array of possible drill diameters in metric.""" return np.concatenate((np.arange(1.0, 10.0, 0.1), np.arange(10.0, 18.0, 0.5), np.arange(18.0, 36.0, 1.0), np.arange(40.0, 55.0, 5.0))) * u.mm
python
def get_drill_bits_d_metric(): """Return array of possible drill diameters in metric.""" return np.concatenate((np.arange(1.0, 10.0, 0.1), np.arange(10.0, 18.0, 0.5), np.arange(18.0, 36.0, 1.0), np.arange(40.0, 55.0, 5.0))) * u.mm
Return array of possible drill diameters in metric.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/drills.py#L21-L26
AguaClara/aguaclara
aguaclara/research/stock_qc.py
Variable_C_Stock.C_stock
def C_stock(self): """Return the required concentration of material in the stock given a reactor's desired system flow rate, system concentration, and stock flow rate. :return: Concentration of material in the stock :rtype: float """ return self._C_sys * (self._Q_sys / self._Q_stock).to(u.dimensionless)
python
def C_stock(self): """Return the required concentration of material in the stock given a reactor's desired system flow rate, system concentration, and stock flow rate. :return: Concentration of material in the stock :rtype: float """ return self._C_sys * (self._Q_sys / self._Q_stock).to(u.dimensionless)
Return the required concentration of material in the stock given a reactor's desired system flow rate, system concentration, and stock flow rate. :return: Concentration of material in the stock :rtype: float
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/stock_qc.py#L77-L85
AguaClara/aguaclara
aguaclara/research/stock_qc.py
Variable_C_Stock.T_stock
def T_stock(self, V_stock): """Return the amount of time at which the stock of materal will be depleted. :param V_stock: Volume of the stock of material :type V_stock: float :return: Time at which the stock will be depleted :rtype: float """ return Stock.T_stock(self, V_stock, self._Q_stock).to(u.hr)
python
def T_stock(self, V_stock): """Return the amount of time at which the stock of materal will be depleted. :param V_stock: Volume of the stock of material :type V_stock: float :return: Time at which the stock will be depleted :rtype: float """ return Stock.T_stock(self, V_stock, self._Q_stock).to(u.hr)
Return the amount of time at which the stock of materal will be depleted. :param V_stock: Volume of the stock of material :type V_stock: float :return: Time at which the stock will be depleted :rtype: float
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/stock_qc.py#L99-L109
AguaClara/aguaclara
aguaclara/research/stock_qc.py
Variable_C_Stock.V_super_stock
def V_super_stock(self, V_stock, C_super_stock): """Return the volume of super (more concentrated) stock that must be diluted for the desired stock volume and required stock concentration. :param V_stock: Volume of the stock of material :type V_stock: float :param C_super_stock: Concentration of the super stock :type C_super_stock: float :return: Volume of super stock to dilute :rtype: float """ return Stock.V_super_stock(self, V_stock, self.C_stock(), C_super_stock)
python
def V_super_stock(self, V_stock, C_super_stock): """Return the volume of super (more concentrated) stock that must be diluted for the desired stock volume and required stock concentration. :param V_stock: Volume of the stock of material :type V_stock: float :param C_super_stock: Concentration of the super stock :type C_super_stock: float :return: Volume of super stock to dilute :rtype: float """ return Stock.V_super_stock(self, V_stock, self.C_stock(), C_super_stock)
Return the volume of super (more concentrated) stock that must be diluted for the desired stock volume and required stock concentration. :param V_stock: Volume of the stock of material :type V_stock: float :param C_super_stock: Concentration of the super stock :type C_super_stock: float :return: Volume of super stock to dilute :rtype: float
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/stock_qc.py#L123-L135
AguaClara/aguaclara
aguaclara/research/stock_qc.py
Variable_Q_Stock.Q_stock
def Q_stock(self): """Return the required flow rate from the stock of material given a reactor's desired system flow rate, system concentration, and stock concentration. :return: Flow rate from the stock of material :rtype: float """ return self._Q_sys * (self._C_sys / self._C_stock).to(u.dimensionless)
python
def Q_stock(self): """Return the required flow rate from the stock of material given a reactor's desired system flow rate, system concentration, and stock concentration. :return: Flow rate from the stock of material :rtype: float """ return self._Q_sys * (self._C_sys / self._C_stock).to(u.dimensionless)
Return the required flow rate from the stock of material given a reactor's desired system flow rate, system concentration, and stock concentration. :return: Flow rate from the stock of material :rtype: float
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/stock_qc.py#L203-L211
AguaClara/aguaclara
aguaclara/research/stock_qc.py
Variable_Q_Stock.rpm
def rpm(self, vol_per_rev): """Return the pump speed required for the reactor's stock of material given the volume of fluid output per revolution by the stock's pump. :param vol_per_rev: Volume of fluid pumped per revolution (dependent on pump and tubing) :type vol_per_rev: float :return: Pump speed for the material stock, in revolutions per minute :rtype: float """ return Stock.rpm(self, vol_per_rev, self.Q_stock()).to(u.rev/u.min)
python
def rpm(self, vol_per_rev): """Return the pump speed required for the reactor's stock of material given the volume of fluid output per revolution by the stock's pump. :param vol_per_rev: Volume of fluid pumped per revolution (dependent on pump and tubing) :type vol_per_rev: float :return: Pump speed for the material stock, in revolutions per minute :rtype: float """ return Stock.rpm(self, vol_per_rev, self.Q_stock()).to(u.rev/u.min)
Return the pump speed required for the reactor's stock of material given the volume of fluid output per revolution by the stock's pump. :param vol_per_rev: Volume of fluid pumped per revolution (dependent on pump and tubing) :type vol_per_rev: float :return: Pump speed for the material stock, in revolutions per minute :rtype: float
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/stock_qc.py#L213-L223
AguaClara/aguaclara
aguaclara/research/stock_qc.py
Variable_Q_Stock.T_stock
def T_stock(self, V_stock): """Return the amount of time at which the stock of materal will be depleted. :param V_stock: Volume of the stock of material :type V_stock: float :return: Time at which the stock will be depleted :rtype: float """ return Stock.T_stock(self, V_stock, self.Q_stock()).to(u.hr)
python
def T_stock(self, V_stock): """Return the amount of time at which the stock of materal will be depleted. :param V_stock: Volume of the stock of material :type V_stock: float :return: Time at which the stock will be depleted :rtype: float """ return Stock.T_stock(self, V_stock, self.Q_stock()).to(u.hr)
Return the amount of time at which the stock of materal will be depleted. :param V_stock: Volume of the stock of material :type V_stock: float :return: Time at which the stock will be depleted :rtype: float
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/stock_qc.py#L225-L235
AguaClara/aguaclara
aguaclara/research/stock_qc.py
Variable_Q_Stock.V_super_stock
def V_super_stock(self, V_stock, C_super_stock): """Return the volume of super (more concentrated) stock that must be diluted for the desired stock volume and stock concentration. :param V_stock: Volume of the stock of material :type V_stock: float :param C_super_stock: Concentration of the super stock :type C_super_stock: float :return: Volume of super stock to dilute :rtype: float """ return Stock.V_super_stock(self, V_stock, self._C_stock, C_super_stock)
python
def V_super_stock(self, V_stock, C_super_stock): """Return the volume of super (more concentrated) stock that must be diluted for the desired stock volume and stock concentration. :param V_stock: Volume of the stock of material :type V_stock: float :param C_super_stock: Concentration of the super stock :type C_super_stock: float :return: Volume of super stock to dilute :rtype: float """ return Stock.V_super_stock(self, V_stock, self._C_stock, C_super_stock)
Return the volume of super (more concentrated) stock that must be diluted for the desired stock volume and stock concentration. :param V_stock: Volume of the stock of material :type V_stock: float :param C_super_stock: Concentration of the super stock :type C_super_stock: float :return: Volume of super stock to dilute :rtype: float
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/stock_qc.py#L249-L261
AguaClara/aguaclara
aguaclara/design/floc.py
Flocculator.vel_grad_avg
def vel_grad_avg(self): """Calculate the average velocity gradient (G-bar) of water flowing through the flocculator. :returns: Average velocity gradient (G-bar) :rtype: float * 1 / second """ return ((u.standard_gravity * self.HL) / (pc.viscosity_kinematic(self.temp) * self.Gt)).to(u.s ** -1)
python
def vel_grad_avg(self): """Calculate the average velocity gradient (G-bar) of water flowing through the flocculator. :returns: Average velocity gradient (G-bar) :rtype: float * 1 / second """ return ((u.standard_gravity * self.HL) / (pc.viscosity_kinematic(self.temp) * self.Gt)).to(u.s ** -1)
Calculate the average velocity gradient (G-bar) of water flowing through the flocculator. :returns: Average velocity gradient (G-bar) :rtype: float * 1 / second
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/floc.py#L103-L110
AguaClara/aguaclara
aguaclara/design/floc.py
Flocculator.W_min_HS_ratio
def W_min_HS_ratio(self): """Calculate the minimum flocculator channel width, given the minimum ratio between expansion height (H) and baffle spacing (S). :returns: Minimum channel width given H_e/S :rtype: float * centimeter """ return ((self.HS_RATIO_MIN * self.Q / self.downstream_H) * (self.BAFFLE_K / (2 * self.downstream_H * pc.viscosity_kinematic(self.temp) * self.vel_grad_avg ** 2)) ** (1/3) ).to(u.cm)
python
def W_min_HS_ratio(self): """Calculate the minimum flocculator channel width, given the minimum ratio between expansion height (H) and baffle spacing (S). :returns: Minimum channel width given H_e/S :rtype: float * centimeter """ return ((self.HS_RATIO_MIN * self.Q / self.downstream_H) * (self.BAFFLE_K / (2 * self.downstream_H * pc.viscosity_kinematic(self.temp) * self.vel_grad_avg ** 2)) ** (1/3) ).to(u.cm)
Calculate the minimum flocculator channel width, given the minimum ratio between expansion height (H) and baffle spacing (S). :returns: Minimum channel width given H_e/S :rtype: float * centimeter
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/floc.py#L129-L138
AguaClara/aguaclara
aguaclara/design/floc.py
Flocculator.channel_n
def channel_n(self): """Calculate the minimum number of channels based on the maximum possible channel width and the maximum length of the channels. Round up to the next even number (factor of 2 shows up twice in equation) The channel width must be greater than the hydraulic width that ensure baffle overlap. Based on the equation for the flocculator volume volume = ([max_L*channel_n] - entrancetank_L)*max_W * downstream_H :returns: number of channels :rtype: float * dimensionless """ min_hydraulic_W =\ np.amax(np.array([1, (self.max_W/self.W_min_HS_ratio).to(u.dimensionless)])) * self.W_min_HS_ratio return 2*np.ceil(((self.vol / (min_hydraulic_W * self.downstream_H) + self.ent_tank_L) / (2 * self.max_L)).to(u.dimensionless))
python
def channel_n(self): """Calculate the minimum number of channels based on the maximum possible channel width and the maximum length of the channels. Round up to the next even number (factor of 2 shows up twice in equation) The channel width must be greater than the hydraulic width that ensure baffle overlap. Based on the equation for the flocculator volume volume = ([max_L*channel_n] - entrancetank_L)*max_W * downstream_H :returns: number of channels :rtype: float * dimensionless """ min_hydraulic_W =\ np.amax(np.array([1, (self.max_W/self.W_min_HS_ratio).to(u.dimensionless)])) * self.W_min_HS_ratio return 2*np.ceil(((self.vol / (min_hydraulic_W * self.downstream_H) + self.ent_tank_L) / (2 * self.max_L)).to(u.dimensionless))
Calculate the minimum number of channels based on the maximum possible channel width and the maximum length of the channels. Round up to the next even number (factor of 2 shows up twice in equation) The channel width must be greater than the hydraulic width that ensure baffle overlap. Based on the equation for the flocculator volume volume = ([max_L*channel_n] - entrancetank_L)*max_W * downstream_H :returns: number of channels :rtype: float * dimensionless
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/floc.py#L141-L154
AguaClara/aguaclara
aguaclara/design/floc.py
Flocculator.channel_W
def channel_W(self): """ The minimum and hence optimal channel width of the flocculator. This The channel must be - wide enough to meet the volume requirement (channel_est_W) - wider than human access for construction - wider than hydraulic requirement to meet H/S ratio Create a dimensionless array of the 3 requirements and then get the maximum :returns: Channel width :rtype: float * meter """ channel_est_W = (self.vol / (self.downstream_H * (self.channel_n * self.max_L - self.ent_tank_L))).to(u.m) # The channel may need to wider than the width that would get the exact required volume. # In that case we will need to shorten the flocculator channel_W = np.amax(np.array([1, (ha.HUMAN_W_MIN/channel_est_W).to(u.dimensionless), (self.W_min_HS_ratio/channel_est_W).to(u.dimensionless)])) * channel_est_W return channel_W
python
def channel_W(self): """ The minimum and hence optimal channel width of the flocculator. This The channel must be - wide enough to meet the volume requirement (channel_est_W) - wider than human access for construction - wider than hydraulic requirement to meet H/S ratio Create a dimensionless array of the 3 requirements and then get the maximum :returns: Channel width :rtype: float * meter """ channel_est_W = (self.vol / (self.downstream_H * (self.channel_n * self.max_L - self.ent_tank_L))).to(u.m) # The channel may need to wider than the width that would get the exact required volume. # In that case we will need to shorten the flocculator channel_W = np.amax(np.array([1, (ha.HUMAN_W_MIN/channel_est_W).to(u.dimensionless), (self.W_min_HS_ratio/channel_est_W).to(u.dimensionless)])) * channel_est_W return channel_W
The minimum and hence optimal channel width of the flocculator. This The channel must be - wide enough to meet the volume requirement (channel_est_W) - wider than human access for construction - wider than hydraulic requirement to meet H/S ratio Create a dimensionless array of the 3 requirements and then get the maximum :returns: Channel width :rtype: float * meter
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/floc.py#L157-L175
AguaClara/aguaclara
aguaclara/design/floc.py
Flocculator.channel_L
def channel_L(self): """ The channel length of the flocculator. If ha.HUMAN_W_MIN or W_min_HS_ratio is the defining constraint for the flocculator width, then the flocculator volume will be greater than necessary. Bring the volume back to the design volume by shortening the flocculator in this case. This design approach will produce flocculators that are the same length as the max_L that was specified in many cases. The flocculator will be less than the specified length especially for cases with only one or two sed tanks. channel_L = (vol/(channel_W * downstream_H) + entrancetank_L)/channel_n :returns: Channel length :rtype: float * meter """ channel_L = ((self.vol / (self.channel_W * self.downstream_H) + self.ent_tank_L) / self.channel_n).to(u.m) return channel_L
python
def channel_L(self): """ The channel length of the flocculator. If ha.HUMAN_W_MIN or W_min_HS_ratio is the defining constraint for the flocculator width, then the flocculator volume will be greater than necessary. Bring the volume back to the design volume by shortening the flocculator in this case. This design approach will produce flocculators that are the same length as the max_L that was specified in many cases. The flocculator will be less than the specified length especially for cases with only one or two sed tanks. channel_L = (vol/(channel_W * downstream_H) + entrancetank_L)/channel_n :returns: Channel length :rtype: float * meter """ channel_L = ((self.vol / (self.channel_W * self.downstream_H) + self.ent_tank_L) / self.channel_n).to(u.m) return channel_L
The channel length of the flocculator. If ha.HUMAN_W_MIN or W_min_HS_ratio is the defining constraint for the flocculator width, then the flocculator volume will be greater than necessary. Bring the volume back to the design volume by shortening the flocculator in this case. This design approach will produce flocculators that are the same length as the max_L that was specified in many cases. The flocculator will be less than the specified length especially for cases with only one or two sed tanks. channel_L = (vol/(channel_W * downstream_H) + entrancetank_L)/channel_n :returns: Channel length :rtype: float * meter
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/floc.py#L178-L192
AguaClara/aguaclara
aguaclara/design/floc.py
Flocculator.expansion_max_H
def expansion_max_H(self): """"Return the maximum distance between expansions for the largest allowable H/S ratio. :returns: Maximum expansion distance :rtype: float * meter Examples -------- exp_dist_max(20*u.L/u.s, 40*u.cm, 37000, 25*u.degC, 2*u.m) 0.375 meter """ return (((self.BAFFLE_K / (2 * pc.viscosity_kinematic(self.temp) * (self.vel_grad_avg ** 2))) * (self.Q * self.RATIO_MAX_HS / self.channel_W) ** 3) ** (1/4)).to(u.m)
python
def expansion_max_H(self): """"Return the maximum distance between expansions for the largest allowable H/S ratio. :returns: Maximum expansion distance :rtype: float * meter Examples -------- exp_dist_max(20*u.L/u.s, 40*u.cm, 37000, 25*u.degC, 2*u.m) 0.375 meter """ return (((self.BAFFLE_K / (2 * pc.viscosity_kinematic(self.temp) * (self.vel_grad_avg ** 2))) * (self.Q * self.RATIO_MAX_HS / self.channel_W) ** 3) ** (1/4)).to(u.m)
Return the maximum distance between expansions for the largest allowable H/S ratio. :returns: Maximum expansion distance :rtype: float * meter Examples -------- exp_dist_max(20*u.L/u.s, 40*u.cm, 37000, 25*u.degC, 2*u.m) 0.375 meter
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/floc.py#L195-L206
AguaClara/aguaclara
aguaclara/design/floc.py
Flocculator.baffle_S
def baffle_S(self): """Return the spacing between baffles. :returns: Spacing between baffles :rtype: int """ return ((self.BAFFLE_K / ((2 * self.expansion_H * (self.vel_grad_avg ** 2) * pc.viscosity_kinematic(self.temp))).to_base_units()) ** (1/3) * self.Q / self.channel_W).to(u.cm)
python
def baffle_S(self): """Return the spacing between baffles. :returns: Spacing between baffles :rtype: int """ return ((self.BAFFLE_K / ((2 * self.expansion_H * (self.vel_grad_avg ** 2) * pc.viscosity_kinematic(self.temp))).to_base_units()) ** (1/3) * self.Q / self.channel_W).to(u.cm)
Return the spacing between baffles. :returns: Spacing between baffles :rtype: int
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/floc.py#L225-L233
AguaClara/aguaclara
aguaclara/design/floc.py
Flocculator.drain_K
def drain_K(self): """ Return the minor loss coefficient of the drain pipe. :returns: Minor Loss Coefficient :return: float """ drain_K = minorloss.PIPE_ENTRANCE_K_MINOR + minorloss.PIPE_ENTRANCE_K_MINOR + minorloss.PIPE_EXIT_K_MINOR return drain_K
python
def drain_K(self): """ Return the minor loss coefficient of the drain pipe. :returns: Minor Loss Coefficient :return: float """ drain_K = minorloss.PIPE_ENTRANCE_K_MINOR + minorloss.PIPE_ENTRANCE_K_MINOR + minorloss.PIPE_EXIT_K_MINOR return drain_K
Return the minor loss coefficient of the drain pipe. :returns: Minor Loss Coefficient :return: float
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/floc.py#L244-L250
AguaClara/aguaclara
aguaclara/design/floc.py
Flocculator.drain_D
def drain_D(self): """ Returns depth of drain pipe. :returns: Depth :return: float """ tank_A = 2 * self.channel_L * self.channel_W drain_D = (np.sqrt(8 * tank_A / (np.pi * self.drain_t) * np.sqrt( self.downstream_H * self.drain_K / (2 * u.standard_gravity)))).to_base_units() return drain_D
python
def drain_D(self): """ Returns depth of drain pipe. :returns: Depth :return: float """ tank_A = 2 * self.channel_L * self.channel_W drain_D = (np.sqrt(8 * tank_A / (np.pi * self.drain_t) * np.sqrt( self.downstream_H * self.drain_K / (2 * u.standard_gravity)))).to_base_units() return drain_D
Returns depth of drain pipe. :returns: Depth :return: float
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/floc.py#L253-L261
AguaClara/aguaclara
aguaclara/design/floc.py
Flocculator.drain_ND
def drain_ND(self): """Returns the diameter of the drain pipe. Each drain pipe will drain two channels because channels are connected by a port at the far end and the first channel can't have a drain because of the entrance tank. Need to review the design to see if this is a good assumption. D_{Pipe} = \sqrt{ \frac{8 A_{Tank}}{\pi t_{Drain}} \sqrt{ \frac{h_0 \sum K}{2g} } } :returns: list of designed values :rtype: float * centimeter """ drain_ND = pipes.ND_SDR_available(self.drain_D, self.SDR) return drain_ND
python
def drain_ND(self): """Returns the diameter of the drain pipe. Each drain pipe will drain two channels because channels are connected by a port at the far end and the first channel can't have a drain because of the entrance tank. Need to review the design to see if this is a good assumption. D_{Pipe} = \sqrt{ \frac{8 A_{Tank}}{\pi t_{Drain}} \sqrt{ \frac{h_0 \sum K}{2g} } } :returns: list of designed values :rtype: float * centimeter """ drain_ND = pipes.ND_SDR_available(self.drain_D, self.SDR) return drain_ND
Returns the diameter of the drain pipe. Each drain pipe will drain two channels because channels are connected by a port at the far end and the first channel can't have a drain because of the entrance tank. Need to review the design to see if this is a good assumption. D_{Pipe} = \sqrt{ \frac{8 A_{Tank}}{\pi t_{Drain}} \sqrt{ \frac{h_0 \sum K}{2g} } } :returns: list of designed values :rtype: float * centimeter
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/floc.py#L264-L275
AguaClara/aguaclara
aguaclara/design/floc.py
Flocculator.design
def design(self): """Returns the designed values. :returns: list of designed values (G, t, channel_W, obstacle_n) :rtype: int """ floc_dict = {'channel_n': self.channel_n, 'channel_L': self.channel_L, 'channel_W': self.channel_W, 'baffle_S': self.baffle_S, 'obstacle_n': self.obstacle_n, 'G': self.vel_grad_avg, 't': self.retention_time, 'expansion_max_H': self.expansion_max_H, 'drain_ND': self.drain_ND} return floc_dict
python
def design(self): """Returns the designed values. :returns: list of designed values (G, t, channel_W, obstacle_n) :rtype: int """ floc_dict = {'channel_n': self.channel_n, 'channel_L': self.channel_L, 'channel_W': self.channel_W, 'baffle_S': self.baffle_S, 'obstacle_n': self.obstacle_n, 'G': self.vel_grad_avg, 't': self.retention_time, 'expansion_max_H': self.expansion_max_H, 'drain_ND': self.drain_ND} return floc_dict
Returns the designed values. :returns: list of designed values (G, t, channel_W, obstacle_n) :rtype: int
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/floc.py#L278-L292
AguaClara/aguaclara
aguaclara/design/floc.py
Flocculator.draw
def draw(self): """Draw the Onshape flocculator model based off of this object.""" from onshapepy import Part CAD = Part( 'https://cad.onshape.com/documents/b4cfd328713460beeb3125ac/w/3928b5c91bb0a0be7858d99e/e/6f2eeada21e494cebb49515f' ) CAD.params = { 'channel_L': self.channel_L, 'channel_W': self.channel_W, 'channel_H': self.downstream_H, 'channel_pairs': self.channel_n/2, 'baffle_S': self.baffle_S, }
python
def draw(self): """Draw the Onshape flocculator model based off of this object.""" from onshapepy import Part CAD = Part( 'https://cad.onshape.com/documents/b4cfd328713460beeb3125ac/w/3928b5c91bb0a0be7858d99e/e/6f2eeada21e494cebb49515f' ) CAD.params = { 'channel_L': self.channel_L, 'channel_W': self.channel_W, 'channel_H': self.downstream_H, 'channel_pairs': self.channel_n/2, 'baffle_S': self.baffle_S, }
Draw the Onshape flocculator model based off of this object.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/floc.py#L294-L306
AguaClara/aguaclara
aguaclara/design/cdc.py
viscosity_kinematic_alum
def viscosity_kinematic_alum(conc_alum, temp): """Return the dynamic viscosity of water at a given temperature. If given units, the function will automatically convert to Kelvin. If not given units, the function will assume Kelvin. This function assumes that the temperature dependence can be explained based on the effect on water and that there is no confounding effect from the coagulant. """ nu = (1 + (4.255 * 10**-6) * conc_alum**2.289) * pc.viscosity_kinematic(temp).magnitude return nu
python
def viscosity_kinematic_alum(conc_alum, temp): """Return the dynamic viscosity of water at a given temperature. If given units, the function will automatically convert to Kelvin. If not given units, the function will assume Kelvin. This function assumes that the temperature dependence can be explained based on the effect on water and that there is no confounding effect from the coagulant. """ nu = (1 + (4.255 * 10**-6) * conc_alum**2.289) * pc.viscosity_kinematic(temp).magnitude return nu
Return the dynamic viscosity of water at a given temperature. If given units, the function will automatically convert to Kelvin. If not given units, the function will assume Kelvin. This function assumes that the temperature dependence can be explained based on the effect on water and that there is no confounding effect from the coagulant.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/cdc.py#L33-L43
AguaClara/aguaclara
aguaclara/design/cdc.py
viscosity_kinematic_pacl
def viscosity_kinematic_pacl(conc_pacl, temp): """Return the dynamic viscosity of water at a given temperature. If given units, the function will automatically convert to Kelvin. If not given units, the function will assume Kelvin. This function assumes that the temperature dependence can be explained based on the effect on water and that there is no confounding effect from the coagulant. """ nu = (1 + (2.383 * 10**-5) * conc_pacl**1.893) * pc.viscosity_kinematic(temp).magnitude return nu
python
def viscosity_kinematic_pacl(conc_pacl, temp): """Return the dynamic viscosity of water at a given temperature. If given units, the function will automatically convert to Kelvin. If not given units, the function will assume Kelvin. This function assumes that the temperature dependence can be explained based on the effect on water and that there is no confounding effect from the coagulant. """ nu = (1 + (2.383 * 10**-5) * conc_pacl**1.893) * pc.viscosity_kinematic(temp).magnitude return nu
Return the dynamic viscosity of water at a given temperature. If given units, the function will automatically convert to Kelvin. If not given units, the function will assume Kelvin. This function assumes that the temperature dependence can be explained based on the effect on water and that there is no confounding effect from the coagulant.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/cdc.py#L47-L57
AguaClara/aguaclara
aguaclara/design/cdc.py
viscosity_kinematic_chem
def viscosity_kinematic_chem(conc_chem, temp, en_chem): """Return the dynamic viscosity of water at a given temperature. If given units, the function will automatically convert to Kelvin. If not given units, the function will assume Kelvin. """ if en_chem == 0: nu = viscosity_kinematic_alum(conc_chem, temp).magnitude if en_chem == 1: nu = viscosity_kinematic_pacl(conc_chem, temp).magnitude if en_chem not in [0,1]: nu = pc.viscosity_kinematic(temp).magnitude return nu
python
def viscosity_kinematic_chem(conc_chem, temp, en_chem): """Return the dynamic viscosity of water at a given temperature. If given units, the function will automatically convert to Kelvin. If not given units, the function will assume Kelvin. """ if en_chem == 0: nu = viscosity_kinematic_alum(conc_chem, temp).magnitude if en_chem == 1: nu = viscosity_kinematic_pacl(conc_chem, temp).magnitude if en_chem not in [0,1]: nu = pc.viscosity_kinematic(temp).magnitude return nu
Return the dynamic viscosity of water at a given temperature. If given units, the function will automatically convert to Kelvin. If not given units, the function will assume Kelvin.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/cdc.py#L61-L73
AguaClara/aguaclara
aguaclara/design/cdc.py
max_linear_flow
def max_linear_flow(Diam, HeadlossCDC, Ratio_Error, KMinor): """Return the maximum flow that will meet the linear requirement. Maximum flow that can be put through a tube of a given diameter without exceeding the allowable deviation from linear head loss behavior """ flow = (pc.area_circle(Diam)).magnitude * np.sqrt((2 * Ratio_Error * HeadlossCDC * pc.gravity)/ KMinor) return flow.magnitude
python
def max_linear_flow(Diam, HeadlossCDC, Ratio_Error, KMinor): """Return the maximum flow that will meet the linear requirement. Maximum flow that can be put through a tube of a given diameter without exceeding the allowable deviation from linear head loss behavior """ flow = (pc.area_circle(Diam)).magnitude * np.sqrt((2 * Ratio_Error * HeadlossCDC * pc.gravity)/ KMinor) return flow.magnitude
Return the maximum flow that will meet the linear requirement. Maximum flow that can be put through a tube of a given diameter without exceeding the allowable deviation from linear head loss behavior
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/cdc.py#L84-L90
AguaClara/aguaclara
aguaclara/design/cdc.py
_len_tube
def _len_tube(Flow, Diam, HeadLoss, conc_chem, temp, en_chem, KMinor): """Length of tube required to get desired head loss at maximum flow based on the Hagen-Poiseuille equation.""" num1 = pc.gravity.magnitude * HeadLoss * np.pi * (Diam**4) denom1 = 128 * viscosity_kinematic_chem(conc_chem, temp, en_chem) * Flow num2 = Flow * KMinor denom2 = 16 * np.pi * viscosity_kinematic_chem(conc_chem, temp, en_chem) len = ((num1/denom1) - (num2/denom2)) return len.magnitude
python
def _len_tube(Flow, Diam, HeadLoss, conc_chem, temp, en_chem, KMinor): """Length of tube required to get desired head loss at maximum flow based on the Hagen-Poiseuille equation.""" num1 = pc.gravity.magnitude * HeadLoss * np.pi * (Diam**4) denom1 = 128 * viscosity_kinematic_chem(conc_chem, temp, en_chem) * Flow num2 = Flow * KMinor denom2 = 16 * np.pi * viscosity_kinematic_chem(conc_chem, temp, en_chem) len = ((num1/denom1) - (num2/denom2)) return len.magnitude
Length of tube required to get desired head loss at maximum flow based on the Hagen-Poiseuille equation.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/cdc.py#L102-L110
AguaClara/aguaclara
aguaclara/design/cdc.py
_length_cdc_tube_array
def _length_cdc_tube_array(FlowPlant, ConcDoseMax, ConcStock, DiamTubeAvail, HeadlossCDC, temp, en_chem, KMinor): """Calculate the length of each diameter tube given the corresponding flow rate and coagulant. Choose the tube that is shorter than the maximum length tube.""" Flow = _flow_cdc_tube(FlowPlant, ConcDoseMax, ConcStock, DiamTubeAvail, HeadlossCDC,Ratio_Error, KMinor).magnitude return _len_tube(Flow, DiamTubeAvail, HeadlossCDC, ConcStock, temp, en_chem, KMinor).magnitude
python
def _length_cdc_tube_array(FlowPlant, ConcDoseMax, ConcStock, DiamTubeAvail, HeadlossCDC, temp, en_chem, KMinor): """Calculate the length of each diameter tube given the corresponding flow rate and coagulant. Choose the tube that is shorter than the maximum length tube.""" Flow = _flow_cdc_tube(FlowPlant, ConcDoseMax, ConcStock, DiamTubeAvail, HeadlossCDC,Ratio_Error, KMinor).magnitude return _len_tube(Flow, DiamTubeAvail, HeadlossCDC, ConcStock, temp, en_chem, KMinor).magnitude
Calculate the length of each diameter tube given the corresponding flow rate and coagulant. Choose the tube that is shorter than the maximum length tube.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/cdc.py#L148-L156
AguaClara/aguaclara
aguaclara/design/cdc.py
len_cdc_tube
def len_cdc_tube(FlowPlant, ConcDoseMax, ConcStock, DiamTubeAvail, HeadlossCDC, LenCDCTubeMax, temp, en_chem, KMinor): """The length of tubing may be longer than the max specified if the stock concentration is too high to give a viable solution with the specified length of tubing.""" index = i_cdc(FlowPlant, ConcDoseMax, ConcStock, DiamTubeAvail, HeadlossCDC, LenCDCTubeMax, temp, en_chem, KMinor) len_cdc_tube = (_length_cdc_tube_array(FlowPlant, ConcDoseMax, ConcStock, DiamTubeAvail, HeadlossCDC, temp, en_chem, KMinor))[index].magnitude return len_cdc_tube
python
def len_cdc_tube(FlowPlant, ConcDoseMax, ConcStock, DiamTubeAvail, HeadlossCDC, LenCDCTubeMax, temp, en_chem, KMinor): """The length of tubing may be longer than the max specified if the stock concentration is too high to give a viable solution with the specified length of tubing.""" index = i_cdc(FlowPlant, ConcDoseMax, ConcStock, DiamTubeAvail, HeadlossCDC, LenCDCTubeMax, temp, en_chem, KMinor) len_cdc_tube = (_length_cdc_tube_array(FlowPlant, ConcDoseMax, ConcStock, DiamTubeAvail, HeadlossCDC, temp, en_chem, KMinor))[index].magnitude return len_cdc_tube
The length of tubing may be longer than the max specified if the stock concentration is too high to give a viable solution with the specified length of tubing.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/cdc.py#L186-L199
AguaClara/aguaclara
aguaclara/research/floc_model.py
dens_alum_nanocluster
def dens_alum_nanocluster(coag): """Return the density of the aluminum in the nanocluster. This is useful for determining the volume of nanoclusters given a concentration of aluminum. """ density = (coag.PrecipDensity * MOLEC_WEIGHT_ALUMINUM * coag.PrecipAluminumMPM / coag.PrecipMolecWeight) return density
python
def dens_alum_nanocluster(coag): """Return the density of the aluminum in the nanocluster. This is useful for determining the volume of nanoclusters given a concentration of aluminum. """ density = (coag.PrecipDensity * MOLEC_WEIGHT_ALUMINUM * coag.PrecipAluminumMPM / coag.PrecipMolecWeight) return density
Return the density of the aluminum in the nanocluster. This is useful for determining the volume of nanoclusters given a concentration of aluminum.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L128-L136
AguaClara/aguaclara
aguaclara/research/floc_model.py
dens_pacl_solution
def dens_pacl_solution(ConcAluminum, temp): """Return the density of the PACl solution. From Stock Tank Mixing report Fall 2013: https://confluence.cornell.edu/download/attachments/137953883/20131213_Research_Report.pdf """ return ((0.492 * ConcAluminum * PACl.MolecWeight / (PACl.AluminumMPM * MOLEC_WEIGHT_ALUMINUM) ) + pc.density_water(temp).magnitude )
python
def dens_pacl_solution(ConcAluminum, temp): """Return the density of the PACl solution. From Stock Tank Mixing report Fall 2013: https://confluence.cornell.edu/download/attachments/137953883/20131213_Research_Report.pdf """ return ((0.492 * ConcAluminum * PACl.MolecWeight / (PACl.AluminumMPM * MOLEC_WEIGHT_ALUMINUM) ) + pc.density_water(temp).magnitude )
Return the density of the PACl solution. From Stock Tank Mixing report Fall 2013: https://confluence.cornell.edu/download/attachments/137953883/20131213_Research_Report.pdf
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L140-L149
AguaClara/aguaclara
aguaclara/research/floc_model.py
particle_number_concentration
def particle_number_concentration(ConcMat, material): """Return the number of particles in suspension. :param ConcMat: Concentration of the material :type ConcMat: float :param material: The material in solution :type material: floc_model.Material """ return ConcMat.to(material.Density.units) / ((material.Density * np.pi * material.Diameter**3) / 6)
python
def particle_number_concentration(ConcMat, material): """Return the number of particles in suspension. :param ConcMat: Concentration of the material :type ConcMat: float :param material: The material in solution :type material: floc_model.Material """ return ConcMat.to(material.Density.units) / ((material.Density * np.pi * material.Diameter**3) / 6)
Return the number of particles in suspension. :param ConcMat: Concentration of the material :type ConcMat: float :param material: The material in solution :type material: floc_model.Material
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L194-L202
AguaClara/aguaclara
aguaclara/research/floc_model.py
sep_dist_clay
def sep_dist_clay(ConcClay, material): """Return the separation distance between clay particles.""" return ((material.Density/ConcClay)*((np.pi * material.Diameter ** 3)/6))**(1/3)
python
def sep_dist_clay(ConcClay, material): """Return the separation distance between clay particles.""" return ((material.Density/ConcClay)*((np.pi * material.Diameter ** 3)/6))**(1/3)
Return the separation distance between clay particles.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L206-L209
AguaClara/aguaclara
aguaclara/research/floc_model.py
num_nanoclusters
def num_nanoclusters(ConcAluminum, coag): """Return the number of Aluminum nanoclusters.""" return (ConcAluminum / (dens_alum_nanocluster(coag).magnitude * np.pi * coag.Diameter**3))
python
def num_nanoclusters(ConcAluminum, coag): """Return the number of Aluminum nanoclusters.""" return (ConcAluminum / (dens_alum_nanocluster(coag).magnitude * np.pi * coag.Diameter**3))
Return the number of Aluminum nanoclusters.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L213-L216
AguaClara/aguaclara
aguaclara/research/floc_model.py
frac_vol_floc_initial
def frac_vol_floc_initial(ConcAluminum, ConcClay, coag, material): """Return the volume fraction of flocs initially present, accounting for both suspended particles and coagulant precipitates. :param ConcAluminum: Concentration of aluminum in solution :type ConcAluminum: float :param ConcClay: Concentration of particle in suspension :type ConcClay: float :param coag: Type of coagulant in solution :type coag: float :param material: Type of particles in suspension, e.g. floc_model.Clay :type material: floc_model.Material :return: Volume fraction of particles initially present :rtype: float """ return ((conc_precipitate(ConcAluminum, coag).magnitude/coag.PrecipDensity) + (ConcClay / material.Density))
python
def frac_vol_floc_initial(ConcAluminum, ConcClay, coag, material): """Return the volume fraction of flocs initially present, accounting for both suspended particles and coagulant precipitates. :param ConcAluminum: Concentration of aluminum in solution :type ConcAluminum: float :param ConcClay: Concentration of particle in suspension :type ConcClay: float :param coag: Type of coagulant in solution :type coag: float :param material: Type of particles in suspension, e.g. floc_model.Clay :type material: floc_model.Material :return: Volume fraction of particles initially present :rtype: float """ return ((conc_precipitate(ConcAluminum, coag).magnitude/coag.PrecipDensity) + (ConcClay / material.Density))
Return the volume fraction of flocs initially present, accounting for both suspended particles and coagulant precipitates. :param ConcAluminum: Concentration of aluminum in solution :type ConcAluminum: float :param ConcClay: Concentration of particle in suspension :type ConcClay: float :param coag: Type of coagulant in solution :type coag: float :param material: Type of particles in suspension, e.g. floc_model.Clay :type material: floc_model.Material :return: Volume fraction of particles initially present :rtype: float
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L219-L235