func_code_string
stringlengths
52
1.94M
func_documentation_string
stringlengths
1
47.2k
def _k_value_square_reduction(ent_pipe_id, exit_pipe_id, re, f): 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.
def _k_value_tapered_reduction(ent_pipe_id, exit_pipe_id, fitting_angle, re, f): 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...
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.
def drain_OD(q_plant, T, depth_end, SDR): 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 ...
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: flo...
def num_plates_ET(q_plant, W_chan): 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_p...
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 -------- >>> f...
def L_plate_ET(q_plant, W_chan): 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.PLA...
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) ...
def alpha0_carbonate(pH): 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 ...
def alpha1_carbonate(pH): 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 >>>...
def alpha2_carbonate(pH): 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 >>> rou...
def ANC_closed(pH, total_carbonates): 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 ...
def aeration_data(DO_column, dirpath): #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 th...
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...
def O2_sat(P_air, temp): 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: ...
def Gran(data_file_path): 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...
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 ...
def CMFR(t, C_initial, C_influent): 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: f...
def E_CMFR_N(t, N): 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 nump...
def E_Advective_Dispersion(t, Pe): # 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.arr...
def Tracer_CMFR_N(t_seconds, t_bar, C_bar, N): 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 tim...
def Solver_CMFR_N(t_data, C_data, theta_guess, C_bar_guess): 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.magn...
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 tim...
def Tracer_AD_Pe(t_seconds, t_bar, C_bar, Pe): 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...
def Solver_AD_Pe(t_data, C_data, theta_guess, C_bar_guess): #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 ...
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 tim...
def set_sig_figs(n=4): 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.
def get_data_by_time(path, columns, dates, start_time='00:00', end_time='23:59'): 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...
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 o...
def remove_notes(data): 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
def day_fraction(time): 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")
def time_column_index(time, time_column): 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_c...
def data_from_dates(path, dates): 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 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" ...
def column_start_to_end(data, column, start_idx, end_idx): 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...
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 ...
def get_data_by_state(path, dates, state, column): 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 ...
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 ...
def column_of_time(path, start, end=-1): 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...
def column_of_data(path, start, column, end="-1", units=""): 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_num...
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 r...
def notes(path): 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 experime...
def read_state_with_metafile(func, state, column, path, metaids=[], extension=".xls", units=""): 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 = ...
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 :...
def write_calculations_to_csv(funcs, states, columns, path, headers, out_name, metaids=[], extension=".xls"): if not isinstance(funcs, list): funcs = [funcs] * len(headers) if not isinstance(states, list): states = [states] * len(headers) if not isinstance(...
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...
def n_sed_plates_max(sed_inputs=sed_dict): 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).m...
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 m...
def w_diffuser_inner_min(sed_inputs=sed_dict): 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 ...
def w_diffuser_inner(sed_inputs=sed_dict): 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 ...
def w_diffuser_outer(sed_inputs=sed_dict): 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 ...
def L_diffuser_outer(sed_inputs=sed_dict): 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 i...
def L_diffuser_inner(sed_inputs=sed_dict): 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 i...
def q_diffuser(sed_inputs=sed_dict): 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 Exa...
def vel_sed_diffuser(sed_inputs=sed_dict): 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 ...
def q_tank(sed_inputs=sed_dict): 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...
def vel_inlet_man_max(sed_inputs=sed_dict): 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. Exampl...
def n_tanks(Q_plant, sed_inputs=sed_dict): 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 --...
def L_channel(Q_plant, sed_inputs=sed_dict): 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 ...
def ID_exit_man(Q_plant, temp, sed_inputs=sed_dict): #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_orifi...
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 : di...
def D_exit_man_orifice(Q_plant, drill_bits, sed_inputs=sed_dict): 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...
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 sediment...
def L_sed_plate(sed_inputs=sed_dict): 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'])) ...
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 ------- ...
def OD(ND): 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 ...
def ID_sch40(ND): 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.
def ND_all_available(): 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.
def ID_SDR_all_available(SDR): 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.
def ND_SDR_available(ID, SDR): 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.
def flow_pipeline(diameters, lengths, k_minors, target_headloss, nu=con.WATER_NU, pipe_rough=mats.PVC_PIPE_ROUGH): # 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 ...
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: ...
def stout_w_per_flow(self, z): 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>
def n_rows(self): 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...
def vel_critical(self): 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.
def area_pipe_min(self): 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.
def nom_diam_pipe(self): ID = pc.diam_circle(self.area_pipe_min) return pipe.ND_SDR_available(ID, self.sdr)
The nominal diameter of the LFOM pipe
def area_top_orifice(self): # 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
def orifice_diameter(self): 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.
def n_orifices_per_row_max(self): 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.
def flow_ramp(self): return np.linspace(1 / self.n_rows, 1, self.n_rows)*self.q
An equally spaced array representing flow at each row.
def height_orifices(self): 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.
def flow_actual(self, Row_Index_Submerged, N_LFOM_Orifices): 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) ...
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 bel...
def n_orifices_per_row(self): # 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 ...
Calculate number of orifices at each level given an orifice diameter.
def error_per_row(self): 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 r...
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.
def get_drill_bits_d_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, ...
Return array of possible drill diameters in imperial.
def get_drill_bits_d_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.
def C_stock(self): 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
def T_stock(self, V_stock): 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
def V_super_stock(self, V_stock, C_super_stock): 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_stoc...
def Q_stock(self): 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
def rpm(self, vol_per_rev): 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...
def T_stock(self, V_stock): 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
def V_super_stock(self, V_stock, C_super_stock): 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 ...
def vel_grad_avg(self): 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
def W_min_HS_ratio(self): 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
def channel_n(self): 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.dimen...
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. Ba...
def channel_W(self): 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...
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 arr...
def channel_L(self): 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...
def expansion_max_H(self): 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
def baffle_S(self): 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
def drain_K(self): 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
def drain_D(self): 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
def drain_ND(self): 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} =...
def design(self): 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...
Returns the designed values. :returns: list of designed values (G, t, channel_W, obstacle_n) :rtype: int
def draw(self): 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...
Draw the Onshape flocculator model based off of this object.
def viscosity_kinematic_alum(conc_alum, temp): 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 ...
def viscosity_kinematic_pacl(conc_pacl, temp): 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 ...
def viscosity_kinematic_chem(conc_chem, temp, en_chem): 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).magnitu...
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.
def max_linear_flow(Diam, HeadlossCDC, Ratio_Error, KMinor): 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
def _len_tube(Flow, Diam, HeadLoss, conc_chem, temp, en_chem, KMinor): 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) ...
Length of tube required to get desired head loss at maximum flow based on the Hagen-Poiseuille equation.
def _length_cdc_tube_array(FlowPlant, ConcDoseMax, ConcStock, DiamTubeAvail, HeadlossCDC, temp, en_chem, KMinor): Flow = _flow_cdc_tube(FlowPlant, ConcDoseMax, ConcStock, DiamTubeAvail, HeadlossCDC,Ratio_Error, KMinor).magnitude return _len_tube(Flow, DiamTubeAvail, HeadlossCDC,...
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.
def len_cdc_tube(FlowPlant, ConcDoseMax, ConcStock, DiamTubeAvail, HeadlossCDC, LenCDCTubeMax, temp, en_chem, KMinor): index = i_cdc(FlowPlant, ConcDoseMax, ConcStock, DiamTubeAvail, HeadlossCDC, LenCDCTubeMax, temp, en_chem, KMinor) len_cdc_tu...
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.
def dens_alum_nanocluster(coag): 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.
def dens_pacl_solution(ConcAluminum, temp): 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
def particle_number_concentration(ConcMat, 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
def sep_dist_clay(ConcClay, material): return ((material.Density/ConcClay)*((np.pi * material.Diameter ** 3)/6))**(1/3)
Return the separation distance between clay particles.
def num_nanoclusters(ConcAluminum, coag): return (ConcAluminum / (dens_alum_nanocluster(coag).magnitude * np.pi * coag.Diameter**3))
Return the number of Aluminum nanoclusters.
def frac_vol_floc_initial(ConcAluminum, ConcClay, coag, material): 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:...