code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
return Stock.rpm(self, vol_per_rev, self.Q_stock()).to(u.rev/u.min)
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
11.557933
12.460698
0.927551
return Stock.T_stock(self, V_stock, self.Q_stock()).to(u.hr)
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
11.370621
12.717057
0.894124
return Stock.V_super_stock(self, V_stock, self._C_stock, C_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
5.144579
6.641779
0.774578
return ((u.standard_gravity * self.HL) / (pc.viscosity_kinematic(self.temp) * self.Gt)).to(u.s ** -1)
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
21.814817
23.107433
0.944061
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)
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
11.519226
12.145734
0.948417
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))
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
9.131337
5.732103
1.593017
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
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
11.056553
7.722013
1.431823
channel_L = ((self.vol / (self.channel_W * self.downstream_H) + self.ent_tank_L) / self.channel_n).to(u.m) return 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
12.930279
2.972412
4.350096
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)
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
14.938127
15.959483
0.936003
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)
def baffle_S(self)
Return the spacing between baffles. :returns: Spacing between baffles :rtype: int
15.457935
17.538086
0.881392
drain_K = minorloss.PIPE_ENTRANCE_K_MINOR + minorloss.PIPE_ENTRANCE_K_MINOR + minorloss.PIPE_EXIT_K_MINOR return drain_K
def drain_K(self)
Return the minor loss coefficient of the drain pipe. :returns: Minor Loss Coefficient :return: float
9.476676
7.088959
1.336822
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
def drain_D(self)
Returns depth of drain pipe. :returns: Depth :return: float
8.917594
9.005336
0.990257
drain_ND = pipes.ND_SDR_available(self.drain_D, self.SDR) return 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
20.272203
21.813007
0.929363
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
def design(self)
Returns the designed values. :returns: list of designed values (G, t, channel_W, obstacle_n) :rtype: int
5.434901
4.2711
1.272483
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, }
def draw(self)
Draw the Onshape flocculator model based off of this object.
11.987846
10.704058
1.119935
nu = (1 + (4.255 * 10**-6) * conc_alum**2.289) * pc.viscosity_kinematic(temp).magnitude return nu
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.
7.755434
9.855481
0.786916
nu = (1 + (2.383 * 10**-5) * conc_pacl**1.893) * pc.viscosity_kinematic(temp).magnitude return nu
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.
7.250491
9.24917
0.783907
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
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.
4.41934
4.794164
0.921817
flow = (pc.area_circle(Diam)).magnitude * np.sqrt((2 * Ratio_Error * HeadlossCDC * pc.gravity)/ KMinor) return flow.magnitude
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
11.65261
12.095588
0.963377
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
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.
5.013378
4.789925
1.046651
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
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.
4.772772
4.929663
0.968174
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
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.
2.944462
2.998587
0.98195
density = (coag.PrecipDensity * MOLEC_WEIGHT_ALUMINUM * coag.PrecipAluminumMPM / coag.PrecipMolecWeight) return density
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.
16.052748
15.794744
1.016335
return ((0.492 * ConcAluminum * PACl.MolecWeight / (PACl.AluminumMPM * MOLEC_WEIGHT_ALUMINUM) ) + pc.density_water(temp).magnitude )
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
15.243657
16.122492
0.94549
return ConcMat.to(material.Density.units) / ((material.Density * np.pi * material.Diameter**3) / 6)
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
7.639214
8.809831
0.867124
return ((material.Density/ConcClay)*((np.pi * material.Diameter ** 3)/6))**(1/3)
def sep_dist_clay(ConcClay, material)
Return the separation distance between clay particles.
11.404124
11.055161
1.031566
return (ConcAluminum / (dens_alum_nanocluster(coag).magnitude * np.pi * coag.Diameter**3))
def num_nanoclusters(ConcAluminum, coag)
Return the number of Aluminum nanoclusters.
12.669578
12.250621
1.034199
return ((conc_precipitate(ConcAluminum, coag).magnitude/coag.PrecipDensity) + (ConcClay / material.Density))
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
10.922625
15.761553
0.692992
return DIM_FRACTAL * np.log2(DiamTarget/material.Diameter)
def num_coll_reqd(DIM_FRACTAL, material, DiamTarget)
Return the number of doubling collisions required. Calculates the number of doubling collisions required to produce a floc of diameter DiamTarget.
4.431891
6.102498
0.726242
return (material.Diameter * (np.pi/(6 * frac_vol_floc_initial(ConcAluminum, ConcClay, coag, material) ))**(1/3) * (DiamTarget / material.Diameter)**(DIM_FRACTAL / 3) )
def sep_dist_floc(ConcAluminum, ConcClay, coag, material, DIM_FRACTAL, DiamTarget)
Return separation distance as a function of floc size.
6.00072
5.966343
1.005762
return (frac_vol_floc_initial(ConcAluminum, ConcClay, coag, material) * (DiamTarget / material.Diameter)**(3-DIM_FRACTAL) )
def frac_vol_floc(ConcAluminum, ConcClay, coag, DIM_FRACTAL, material, DiamTarget)
Return the floc volume fraction.
4.381062
4.156791
1.053953
return (conc_floc(ConcAluminum, ConcClay, coag).magnitude / frac_vol_floc_initial(ConcAluminum, ConcClay, coag, material) )
def dens_floc_init(ConcAluminum, ConcClay, coag, material)
Return the density of the initial floc. Initial floc is made primarily of the primary colloid and nanoglobs.
4.361605
5.331515
0.81808
return (1 / (1 + (2 * material.Diameter / (3 * DiamTube * ratio_clay_sphere(RatioHeightDiameter) * (ConcClay / material.Density) ) ) ) )
def ratio_area_clay_total(ConcClay, material, DiamTube, RatioHeightDiameter)
Return the surface area of clay normalized by total surface area. Total surface area is a combination of clay and reactor wall surface areas. This function is used to estimate how much coagulant actually goes to the clay. :param ConcClay: Concentration of clay in suspension :type ConcClay: float :param material: Type of clay in suspension, e.g. floc_model.Clay :type material: floc_model.Material :param DiamTube: Diameter of flocculator tube (assumes tube flocculator for calculation of reactor surface area) :type DiamTube: float :param RatioHeightDiameter: Dimensionless ratio describing ratio of clay height to clay diameter :type RatioHeightDiameter: float :return: The ratio of clay surface area to total available surface area (accounting for reactor walls) :rtype: float
6.96534
8.867582
0.785484
return (1 - np.exp(( (-frac_vol_floc_initial(ConcAluminum, 0*u.kg/u.m**3, coag, material) * material.Diameter) / (frac_vol_floc_initial(0*u.kg/u.m**3, ConcClay, coag, material) * coag.Diameter)) * (1 / np.pi) * (ratio_area_clay_total(ConcClay, material, DiamTube, RatioHeightDiameter) / ratio_clay_sphere(RatioHeightDiameter)) ))
def gamma_coag(ConcClay, ConcAluminum, coag, material, DiamTube, RatioHeightDiameter)
Return the coverage of clay with nanoglobs. This function accounts for loss to the tube flocculator walls and a poisson distribution on the clay given random hits by the nanoglobs. The poisson distribution results in the coverage only gradually approaching full coverage as coagulant dose increases. :param ConcClay: Concentration of clay in suspension :type ConcClay: float :param ConcAluminum: Concentration of aluminum in solution :type ConcAluminum: float :param coag: Type of coagulant in solution, e.g. floc_model.PACl :type coag: floc_model.Material :param material: Type of clay in suspension, e.g. floc_model.Clay :type material: floc_model.Material :param DiamTube: Diameter of flocculator tube (assumes tube flocculator for calculation of reactor surface area) :type DiamTube: float :param RatioHeightDiameter: Dimensionless ratio of clay height to clay diameter :type RatioHeightDiameter: float :return: Fraction of the clay surface area that is coated with coagulant precipitates :rtype: float
5.452086
4.907194
1.111039
return min(((ConcNatOrgMat / conc_precipitate(ConcAl, coag).magnitude) * (coag.Density / NatOrgMat.Density) * (coag.Diameter / (4 * NatOrgMat.Diameter)) ), 1)
def gamma_humic_acid_to_coag(ConcAl, ConcNatOrgMat, NatOrgMat, coag)
Return the fraction of the coagulant that is coated with humic acid. :param ConcAl: Concentration of alumninum in solution :type ConcAl: float :param ConcNatOrgMat: Concentration of natural organic matter in solution :type ConcNatOrgMat: float :param NatOrgMat: type of natural organic matter, e.g. floc_model.HumicAcid :type NatOrgMat: floc_model.Material :param coag: Type of coagulant in solution, e.g. floc_model.PACl :type coag: floc_model.Material :return: fraction of the coagulant that is coated with humic acid :rtype: float
7.432879
8.126472
0.91465
return (gamma_coag(ConcClay, ConcAl, coag, material, DiamTube, RatioHeightDiameter) * (1 - gamma_humic_acid_to_coag(ConcAl, ConcNatOrgMat, NatOrgMat, coag)) )
def pacl_term(DiamTube, ConcClay, ConcAl, ConcNatOrgMat, NatOrgMat, coag, material, RatioHeightDiameter)
Return the fraction of the surface area that is covered with coagulant that is not covered with humic acid. :param DiamTube: Diameter of the dosing tube :type Diamtube: float :param ConcClay: Concentration of clay in solution :type ConcClay: float :param ConcAl: Concentration of alumninum in solution :type ConcAl: float :param ConcNatOrgMat: Concentration of natural organic matter in solution :type ConcNatOrgMat: float :param NatOrgMat: type of natural organic matter, e.g. floc_model.HumicAcid :type NatOrgMat: floc_model.Material :param coag: Type of coagulant in solution, e.g. floc_model.PACl :type coag: floc_model.Material :param material: Type of clay in suspension, e.g. floc_model.Clay :type material: floc_model.Material :param RatioHeightDiameter: Dimensionless ratio of clay height to clay diameter :type RatioHeightDiameter: float :return: fraction of the surface area that is covered with coagulant that is not covered with humic acid :rtype: float
4.484685
3.99402
1.12285
WaterDensity = pc.density_water(Temp).magnitude return ((dens_floc_init(ConcAl, ConcClay, coag, material).magnitude - WaterDensity ) * (material.Diameter / DiamTarget)**(3 - DIM_FRACTAL) + WaterDensity )
def dens_floc(ConcAl, ConcClay, DIM_FRACTAL, DiamTarget, coag, material, Temp)
Calculate floc density as a function of size.
7.875885
8.298686
0.949052
WaterDensity = pc.density_water(Temp).magnitude return (((pc.gravity.magnitude * material.Diameter**2) / (18 * PHI_FLOC * pc.viscosity_kinematic(Temp).magnitude) ) * ((dens_floc_init(ConcAl, ConcClay, coag, material).magnitude - WaterDensity ) / WaterDensity ) * (DiamTarget / material.Diameter) ** (DIM_FRACTAL - 1) )
def vel_term_floc(ConcAl, ConcClay, coag, material, DIM_FRACTAL, DiamTarget, Temp)
Calculate floc terminal velocity.
7.053957
7.095473
0.994149
WaterDensity = pc.density_water(Temp).magnitude return (material.Diameter * (((18 * VelTerm * PHI_FLOC * pc.viscosity_kinematic(Temp).magnitude ) / (pc.gravity.magnitude * material.Diameter**2) ) * (WaterDensity / (dens_floc_init(ConcAl, ConcClay, coag, material).magnitude - WaterDensity ) ) ) ** (1 / (DIM_FRACTAL - 1)) )
def diam_floc_vel_term(ConcAl, ConcClay, coag, material, DIM_FRACTAL, VelTerm, Temp)
Calculate floc diamter as a function of terminal velocity.
7.963755
8.151768
0.976936
return (((1/6) * ((6/np.pi)**(1/3)) * frac_vol_floc_initial(ConcAl, ConcClay, coag, material) ** (-2/3) * (pc.viscosity_kinematic(Temp).magnitude / EnergyDis) ** (1 / 2) * (DiamTarget / material.Diameter) ** (2*DIM_FRACTAL/3 - 2) ) # End of the numerator / (gamma_coag(ConcClay, ConcAl, coag, material, DiamTube, RatioHeightDiameter) ) # End of the denominator )
def time_col_laminar(EnergyDis, Temp, ConcAl, ConcClay, coag, material, DiamTarget, DiamTube, DIM_FRACTAL, RatioHeightDiameter)
Calculate single collision time for laminar flow mediated collisions. Calculated as a function of floc size.
6.850116
7.175105
0.954706
return((1/6) * (6/np.pi)**(1/9) * EnergyDis**(-1/3) * DiamTarget**(2/3) * frac_vol_floc_initial(ConcAl, ConcClay, coag, material)**(-8/9) * (DiamTarget / material.Diameter)**((8*(DIM_FRACTAL-3)) / 9) )
def time_col_turbulent(EnergyDis, ConcAl, ConcClay, coag, material, DiamTarget, DIM_FRACTAL)
Calculate single collision time for turbulent flow mediated collisions. Calculated as a function of floc size.
6.677848
6.67734
1.000076
return (material.Diameter * ((eta_kolmogorov(EnergyDis, Temp).magnitude / material.Diameter) * ((6 * frac_vol_floc_initial(ConcAl, ConcClay, coag, material)) / np.pi )**(1/3) )**(3 / DIM_FRACTAL) )
def diam_kolmogorov(EnergyDis, Temp, ConcAl, ConcClay, coag, material, DIM_FRACTAL)
Return the size of the floc with separation distances equal to the Kolmogorov length and the inner viscous length scale.
9.606214
8.839561
1.08673
return (reynolds_rapid_mix(PlantFlow, IDTube, Temp) * (IDTube / (2 * RadiusCoil))**(1/2) )
def dean_number(PlantFlow, IDTube, RadiusCoil, Temp)
Return the Dean Number. The Dean Number is a dimensionless parameter that is the unfortunate combination of Reynolds and tube curvature. It would have been better to keep the Reynolds number and define a simple dimensionless geometric parameter.
8.233503
8.849821
0.930358
return (g_straight(FlowPlant, IDTube).magnitude * (1 + 0.033 * np.log10(dean_number(FlowPlant, IDTube, RadiusCoil, Temp) ) ** 4 ) ** (1/2) )
def g_coil(FlowPlant, IDTube, RadiusCoil, Temp)
We need a reference for this. Karen's thesis likely has this equation and the reference.
7.729716
7.854514
0.984111
return (g_coil(FlowPlant, IDTube, RadiusCoil, Temp).magnitude * time_res_tube(IDTube, LengthTube, FlowPlant).magnitude )
def g_time_res(FlowPlant, IDTube, RadiusCoil, LengthTube, Temp)
G Residence Time calculated for a coiled tube flocculator.
6.053633
6.030203
1.003885
self.PrecipDiameter = diameter self.PrecipDensity = density self.PrecipMolecWeight = molecweight self.PrecipAluminumMPM = alumMPM
def define_Precip(self, diameter, density, molecweight, alumMPM)
Define a precipitate for the chemical. :param diameter: Diameter of the precipitate in particulate form :type diameter: float :param density: Density of the material (mass/volume) :type density: float :param molecWeight: Molecular weight of the material (mass/mole) :type molecWeight: float :param alumMPM:
1.98509
2.65017
0.749043
# first guess planview area a_new = 1 * u.m**2 a_ratio = 2 # set to >1+tolerance to start while loop tolerance = 0.01 a_floc_pv = ( self.floc.vol / (self.floc.downstream_H + (self.floc.HL / 2)) ) while a_ratio > (1 + tolerance): a_et_pv = a_new a_etf_pv = a_et_pv + a_floc_pv w_tot = a_etf_pv / self.floc.max_L w_chan = w_tot / self.floc.channel_n a_new = self.floc.max_L * w_chan a_ratio = a_new / a_et_pv return a_new
def ent_tank_a(self)
Calculate the planview area of the entrance tank, given the volume of the flocculator. :returns: The planview area of the entrance tank. :rtype: float * u.m ** 2
7.023065
5.630156
1.247401
N_estimated = (HL_LFOM*np.pi/(2*width_stout(HL_LFOM,HL_LFOM)*FLOW)) variablerow = min(10,max(4,math.trunc(N_estimated.magnitude))) # Forcing the LFOM to either have 4 or 8 rows, for design purposes # If the hydraulic calculation finds that there should be 4 rows, then there # will be 4 rows. If anything other besides 4 rows is found, then assign 8 # rows. # This can be improved in the future. if variablerow == 4: variablerow = 4 else: variablerow = 8 return variablerow
def n_lfom_rows(FLOW,HL_LFOM)
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.
8.184051
8.294937
0.986632
return ((FLOW*width_stout(HL_LFOM*u.m,HL_LFOM*u.m-0.5*dist_center_lfom_rows(FLOW,HL_LFOM)).magnitude * dist_center_lfom_rows(FLOW,HL_LFOM).magnitude))
def area_lfom_orifices_top(FLOW,HL_LFOM)
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
7.718022
5.555651
1.38922
return math.floor(math.pi * (pipe.ID_SDR( nom_diam_lfom_pipe(FLOW, HL_LFOM), design.lfom.SDR_LFOM).magnitude) / (orifice_diameter(FLOW, HL_LFOM, drill_bits).magnitude + aguaclara.design.lfom.ORIFICE_S.magnitude))
def n_lfom_orifices_per_row_max(FLOW,HL_LFOM,drill_bits)
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.
13.060267
13.34365
0.978763
return (np.arange((orifice_diameter(FLOW,HL_LFOM,drill_bits)*0.5), HL_LFOM, (dist_center_lfom_rows(FLOW,HL_LFOM))))
def height_lfom_orifices(FLOW,HL_LFOM,drill_bits)
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.
9.106602
8.657986
1.051815
D_LFOM_Orifices=orifice_diameter(FLOW, HL_LFOM, drill_bits).magnitude row_height=dist_center_lfom_rows(FLOW, HL_LFOM).magnitude harray = (np.linspace(row_height, HL_LFOM, n_lfom_rows(FLOW, HL_LFOM))) - 0.5 * D_LFOM_Orifices FLOW_new = 0 for i in range(Row_Index_Submerged+1): FLOW_new = FLOW_new + (N_LFOM_Orifices[i] * ( pc.flow_orifice_vert(D_LFOM_Orifices, harray[Row_Index_Submerged-i], con.VC_ORIFICE_RATIO).magnitude)) return FLOW_new
def flow_lfom_actual(FLOW,HL_LFOM,drill_bits,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
4.970537
4.651702
1.068542
units = None try: num = number.magnitude units = number.units except AttributeError: num = number try: if (units != None): rounded_num = round(num, digits - int(floor(log10(abs(num)))) - 1) * units else: rounded_num = round(num, digits - int(floor(log10(abs(num)))) - 1) return rounded_num except ValueError: # Prevents an error with log10(0) if (units != None): return 0 * units else: return 0
def round_sf(number, digits)
Returns inputted value rounded to number of significant figures desired. :param number: Value to be rounded :type number: float :param digits: number of significant digits to be rounded to. :type digits: int
2.732183
2.667835
1.02412
counter = 0 * unit while counter < param.to(unit): counter += step * unit return counter
def stepceil_with_units(param, step, unit)
This function returns the smallest multiple of 'step' greater than or equal to 'param' and outputs the result in Pint units. This function is unit-aware and functions without requiring translation so long as 'param' and 'unit' are of the same dimensionality.
7.235271
7.490294
0.965953
def decorate(func): def wrapper(*args, **kwargs): sequences = [] enumsUnitCheck = enumerate(args) argsList = list(args) #This for loop identifies pint unit objects and strips them #of their units. for num, arg in enumsUnitCheck: if type(arg) == type(1 * u.m): argsList[num] = arg.to_base_units().magnitude enumsUnitless = enumerate(argsList) #This for loop identifies arguments that are sequences and #adds their index location to the list 'sequences'. for num, arg in enumsUnitless: if isinstance(arg, (list, tuple, np.ndarray)): sequences.append(num) #If there are no sequences to iterate through, simply return #the function. if len(sequences) == 0: result = func(*args, **kwargs) else: #iterant keeps track of how many times we've iterated and #limiter stops the loop once we've iterated as many times #as there are list elements. Without this check, a few #erroneous runs will occur, appending the last couple values #to the end of the list multiple times. # #We only care about the length of sequences[0] because this #function is recursive, and sequences[0] is always the relevant #sequences for any given run. limiter = len(argsList[sequences[0]]) iterant = 0 result = [] for num in sequences: for arg in argsList[num]: if iterant >= limiter: break #We can safely replace the entire list argument #with a single element from it because of the looping #we're doing. We redefine the object, but that #definition remains within this namespace and does #not penetrate further up the function. argsList[num] = arg #Here we dive down the rabbit hole. This ends up #creating a multi-dimensional array shaped by the #sizes and shapes of the lists passed. result.append(wrapper(*argsList, HandlerResult=HandlerResult, **kwargs)) iterant += 1 #HandlerResult allows the user to specify what type to #return the generated sequence as. It defaults to numpy #arrays because functions tend to handle them better, but if #the user does not wish to import numpy the base Python options #are available to them. if HandlerResult == "nparray": result = np.array(result) elif HandlerResult == "tuple": result = tuple(result) elif HandlerResult == "list": result == list(result) return result return wrapper return decorate
def list_handler(HandlerResult="nparray")
Wraps a function to handle list inputs.
5.729973
5.657709
1.012773
knownChecks = ('>0', '>=0', '0-1', '<0', '<=0', 'int', 'boolean') for arg in args: #Converts arg to a mutable list arg = [*arg] if len(arg) == 1: #arg[1] details what range the parameter should fall within; if #len(arg) is 1 that means a validity was not specified and the #parameter should not have been passed in its current form raise TypeError("No range-validity parameter provided.") elif len(arg) == 2: #Appending 'Input" to the end allows us to give more descriptive #error messages that do not fail if no description was supplied. arg.append("Input") #This ensures that all whitespace is removed before checking if the #request is understood arg[1] = "".join(arg[1].lower().split()) #This block checks that each range request is understood. #If the request is a compound one, it must be separated into individual #requests for validity comprehension for i in arg[1].split(","): if i not in knownChecks: raise RuntimeError("Unknown parameter validation " "request: {0}.".format(i)) if not isinstance(arg[0], (list, tuple, np.ndarray)): arg[0] = [arg[0]] for i in arg[0]: if '>0' in arg[1] and i <= 0: raise ValueError("{1} is {0} but must be greater than " "0.".format(i, arg[2])) if '>=0' in arg[1] and i <0: raise ValueError("{1} is {0} but must be 0 or " "greater.".format(i, arg[2])) if '0-1' in arg[1] and not 0 <= i <= 1: raise ValueError("{1} is {0} but must be between 0 and " "1.".format(i, arg[2])) if '<0' in arg[1] and i >= 0: raise ValueError("{1} is {0} but must be less than " "0.".format(i, arg[2])) if '<=0' in arg[1] and i >0: raise ValueError("{1} is {0} but must be 0 or " "less.".format(i, arg[2])) if 'int' in arg[1] and int(i) != i: raise TypeError("{1} is {0} but must be a numeric " "integer.".format(i, arg[2])) if 'boolean' in arg[1] and type(i) != bool: raise TypeError("{1} is {0} but must be a " "boolean.".format(i, arg[2]))
def check_range(*args)
Check whether passed paramters fall within approved ranges. Does not return anything, but will raise an error if a parameter falls outside of its defined range. Input should be passed as an array of sequences, with each sequence having three elements: [0] is the value being checked, [1] is the range parameter(s) within which the value should fall, and [2] is the name of the parameter, for better error messages. If [2] is not supplied, "Input" will be appended as a generic name. Range requests that this function understands are listed in the knownChecks sequence.
3.242354
2.913134
1.113012
parser = argparse.ArgumentParser( description='Performs clustering from the command-line. Calls JVM start/stop automatically.') parser.add_argument("-j", metavar="classpath", dest="classpath", help="additional classpath, jars/directories") parser.add_argument("-X", metavar="heap", dest="heap", help="max heap size for jvm, e.g., 512m") parser.add_argument("-t", metavar="train", dest="train", required=True, help="training set file") parser.add_argument("-T", metavar="test", dest="test", help="test set file") parser.add_argument("-d", metavar="outmodel", dest="outmodel", help="model output file name") parser.add_argument("-l", metavar="inmodel", dest="inmodel", help="model input file name") parser.add_argument("-p", metavar="attributes", dest="attributes", help="attribute range") parser.add_argument("-x", metavar="num folds", dest="numfolds", help="number of folds") parser.add_argument("-s", metavar="seed", dest="seed", help="seed value for randomization") parser.add_argument("-c", metavar="class index", dest="classindex", help="1-based class attribute index") parser.add_argument("-g", metavar="graph", dest="graph", help="graph output file (if supported)") parser.add_argument("clusterer", help="clusterer classname, e.g., weka.clusterers.SimpleKMeans") parser.add_argument("option", nargs=argparse.REMAINDER, help="additional clusterer options") parsed = parser.parse_args() jars = [] if parsed.classpath is not None: jars = parsed.classpath.split(os.pathsep) params = [] if parsed.train is not None: params.extend(["-t", parsed.train]) if parsed.test is not None: params.extend(["-T", parsed.test]) if parsed.outmodel is not None: params.extend(["-d", parsed.outmodel]) if parsed.inmodel is not None: params.extend(["-l", parsed.inmodel]) if parsed.attributes is not None: params.extend(["-p", parsed.attributes]) if parsed.numfolds is not None: params.extend(["-x", parsed.numfolds]) if parsed.seed is not None: params.extend(["-s", parsed.seed]) if parsed.classindex is not None: params.extend(["-c", parsed.classindex]) if parsed.graph is not None: params.extend(["-g", parsed.graph]) jvm.start(jars, max_heap_size=parsed.heap, packages=True) logger.debug("Commandline: " + join_options(sys.argv[1:])) try: clusterer = Clusterer(classname=parsed.clusterer) if len(parsed.option) > 0: clusterer.options = parsed.option print(ClusterEvaluation.evaluate_clusterer(clusterer, params)) except Exception as e: print(e) finally: jvm.stop()
def main()
Runs a clusterer from the command-line. Calls JVM start/stop automatically. Use -h to see all options.
2.161992
2.012322
1.074377
if self.is_updateable: javabridge.call(self.jobject, "updateClusterer", "(Lweka/core/Instance;)V", inst.jobject) else: logger.critical(classes.get_classname(self.jobject) + " is not updateable!")
def update_clusterer(self, inst)
Updates the clusterer with the instance. :param inst: the Instance to update the clusterer with :type inst: Instance
4.886677
4.517365
1.081754
if self.is_updateable: javabridge.call(self.jobject, "updateFinished", "()V") else: logger.critical(classes.get_classname(self.jobject) + " is not updateable!")
def update_finished(self)
Signals the clusterer that updating with new data has finished.
6.043714
5.404118
1.118354
pred = self.__distribution(inst.jobject) return javabridge.get_env().get_double_array_elements(pred)
def distribution_for_instance(self, inst)
Peforms a prediction, returning the cluster distribution. :param inst: the Instance to get the cluster distribution for :type inst: Instance :return: the cluster distribution :rtype: float[]
11.546791
10.676485
1.081516
array = javabridge.call(self.jobject, "getClusterAssignments", "()[D") if array is None: return None else: return javabridge.get_env().get_double_array_elements(array)
def cluster_assignments(self)
Return an array of cluster assignments corresponding to the most recent set of instances clustered. :return: the cluster assignments :rtype: ndarray
4.138634
4.051095
1.021609
array = javabridge.call(self.jobject, "getClassesToClusters", "()[I") if array is None: return None else: return javabridge.get_env().get_int_array_elements(array)
def classes_to_clusters(self)
Return the array (ordered by cluster number) of minimum error class to cluster mappings. :return: the mappings :rtype: ndarray
4.020981
4.120139
0.975933
return javabridge.static_call( "Lweka/clusterers/ClusterEvaluation;", "crossValidateModel", "(Lweka/clusterers/DensityBasedClusterer;Lweka/core/Instances;ILjava/util/Random;)D", clusterer.jobject, data.jobject, num_folds, rnd.jobject)
def crossvalidate_model(cls, clusterer, data, num_folds, rnd)
Cross-validates the clusterer and returns the loglikelihood. :param clusterer: the clusterer instance to evaluate :type clusterer: Clusterer :param data: the data to evaluate on :type data: Instances :param num_folds: the number of folds :type num_folds: int :param rnd: the random number generator to use :type rnd: Random :return: the cross-validated loglikelihood :rtype: float
3.934661
2.958925
1.32976
if isinstance(obj, JavaObject): wrapped = True jobject = obj.jobject else: wrapped = False jobject = obj try: serialized = javabridge.make_instance("weka/core/SerializedObject", "(Ljava/lang/Object;)V", jobject) jcopy = javabridge.call(serialized, "getObject", "()Ljava/lang/Object;") if wrapped: jcopy = obj.__class__(jobject=jcopy) return jcopy except JavaException as e: print("Failed to create copy of " + classes.get_classname(obj) + ": " + str(e)) return None
def deepcopy(obj)
Creates a deep copy of the JavaObject (or derived class) or JB_Object. :param obj: the object to create a copy of :type obj: object :return: the copy, None if failed to copy :rtype: object
3.610815
3.454623
1.045212
array = javabridge.static_call( "Lweka/core/SerializationHelper;", "readAll", "(Ljava/lang/String;)[Ljava/lang/Object;", filename) if array is None: return None else: return javabridge.get_env().get_object_array_elements(array)
def read_all(filename)
Reads the serialized objects from disk. Caller must wrap objects in appropriate Python wrapper classes. :param filename: the file with the serialized objects :type filename: str :return: the list of JB_OBjects :rtype: list
3.591676
3.660666
0.981154
if isinstance(jobject, JavaObject): jobject = jobject.jobject javabridge.static_call( "Lweka/core/SerializationHelper;", "write", "(Ljava/lang/String;Ljava/lang/Object;)V", filename, jobject)
def write(filename, jobject)
Serializes the object to disk. JavaObject instances get automatically unwrapped. :param filename: the file to serialize the object to :type filename: str :param jobject: the object to serialize :type jobject: JB_Object or JavaObject
3.169639
3.132028
1.012009
if frequency is None: javabridge.call(self.jobject, "decreaseFrequency", "()V") else: javabridge.call(self.jobject, "decreaseFrequency", "(I)V", frequency)
def decrease_frequency(self, frequency=None)
Decreases the frequency. :param frequency: the frequency to decrease by, 1 if None :type frequency: int
2.609063
2.565946
1.016803
if frequency is None: javabridge.call(self.jobject, "increaseFrequency", "()V") else: javabridge.call(self.jobject, "increaseFrequency", "(I)V", frequency)
def increase_frequency(self, frequency=None)
Increases the frequency. :param frequency: the frequency to increase by, 1 if None :type frequency: int
2.596512
2.543765
1.020736
items = javabridge.get_collection_wrapper( javabridge.call(self.jobject, "getConsequence", "()Ljava/util/Collection;")) result = [] for item in items: result.append(Item(item)) return result
def consequence(self)
Get the the consequence. :return: the consequence, list of Item objects :rtype: list
4.369678
3.784773
1.154542
if not self.check_type(self.jobject, "weka.associations.AssociationRulesProducer"): return False return javabridge.call(self.jobject, "canProduceRules", "()Z")
def can_produce_rules(self)
Checks whether association rules can be generated. :return: whether scheme implements AssociationRulesProducer interface and association rules can be generated :rtype: bool
6.839058
4.65934
1.467817
if not self.check_type(self.jobject, "weka.associations.AssociationRulesProducer"): return None return AssociationRules( javabridge.call(self.jobject, "getAssociationRules", "()Lweka/associations/AssociationRules;"))
def association_rules(self)
Returns association rules that were generated. Only if implements AssociationRulesProducer. :return: the association rules that were generated :rtype: AssociationRules
5.357657
4.189545
1.278816
if not self.check_type(self.jobject, "weka.associations.AssociationRulesProducer"): return None return string_array_to_list( javabridge.call(self.jobject, "getRuleMetricNames", "()[Ljava/lang/String;"))
def rule_metric_names(self)
Returns the rule metric names of the association rules. Only if implements AssociationRulesProducer. :return: the metric names :rtype: list
6.464643
4.758483
1.358551
loader = javabridge.static_call( "weka/core/converters/ConverterUtils", "getLoaderForFile", "(Ljava/lang/String;)Lweka/core/converters/AbstractFileLoader;", filename) if loader is None: return None else: return Loader(jobject=loader)
def loader_for_file(filename)
Returns a Loader that can load the specified file, based on the file extension. None if failed to determine. :param filename: the filename to get the loader for :type filename: str :return: the assoicated loader instance or None if none found :rtype: Loader
3.181476
3.802883
0.836596
saver = javabridge.static_call( "weka/core/converters/ConverterUtils", "getSaverForFile", "(Ljava/lang/String;)Lweka/core/converters/AbstractFileSaver;", filename) if saver is None: return None else: return Saver(jobject=saver)
def saver_for_file(filename)
Returns a Saver that can load the specified file, based on the file extension. None if failed to determine. :param filename: the filename to get the saver for :type filename: str :return: the associated saver instance or None if none found :rtype: Saver
3.291119
3.364998
0.978045
saver = saver_for_file(filename) if saver is None: return False else: saver.save_file(data, filename) return True
def save_any_file(data, filename)
Determines a Saver based on the the file extension. Returns whether successfully saved. :param filename: the name of the file to save :type filename: str :param data: the data to save :type data: Instances :return: whether successfully saved :rtype: bool
3.677748
3.271902
1.12404
if len(numpy.shape(array)) != 2: raise Exception("Number of array dimensions must be 2!") rows, cols = numpy.shape(array) # header atts = [] if att_list is not None: if len(att_list) != cols: raise Exception( "Number columns and provided attribute names differ: " + str(cols) + " != " + len(att_list)) for name in att_list: att = Attribute.create_numeric(name) atts.append(att) else: for i in range(cols): name = att_template.replace("#", str(i+1)).replace("!", str(i)).replace("@", relation) att = Attribute.create_numeric(name) atts.append(att) result = Instances.create_instances(relation, atts, rows) # data for i in range(rows): inst = Instance.create_instance(array[i]) result.add_instance(inst) return result
def ndarray_to_instances(array, relation, att_template="Att-#", att_list=None)
Converts the numpy matrix into an Instances object and returns it. :param array: the numpy ndarray to convert :type array: numpy.darray :param relation: the name of the dataset :type relation: str :param att_template: the prefix to use for the attribute names, "#" is the 1-based index, "!" is the 0-based index, "@" the relation name :type att_template: str :param att_list: the list of attribute names to use :type att_list: list :return: the generated instances object :rtype: Instances
2.642879
2.450334
1.078579
self.enforce_type(self.jobject, "weka.core.converters.FileSourcedConverter") self.incremental = incremental if not javabridge.is_instance_of(dfile, "Ljava/io/File;"): dfile = javabridge.make_instance( "Ljava/io/File;", "(Ljava/lang/String;)V", javabridge.get_env().new_string_utf(str(dfile))) javabridge.call(self.jobject, "reset", "()V") # check whether file exists, otherwise previously set file gets loaded again sfile = javabridge.to_string(dfile) if not os.path.exists(sfile): raise Exception("Dataset file does not exist: " + str(sfile)) javabridge.call(self.jobject, "setFile", "(Ljava/io/File;)V", dfile) if incremental: self.structure = Instances(javabridge.call(self.jobject, "getStructure", "()Lweka/core/Instances;")) return self.structure else: return Instances(javabridge.call(self.jobject, "getDataSet", "()Lweka/core/Instances;"))
def load_file(self, dfile, incremental=False)
Loads the specified file and returns the Instances object. In case of incremental loading, only the structure. :param dfile: the file to load :type dfile: str :param incremental: whether to load the dataset incrementally :type incremental: bool :return: the full dataset or the header (if incremental) :rtype: Instances :raises Exception: if the file does not exist
2.625852
2.561681
1.02505
self.enforce_type(self.jobject, "weka.core.converters.URLSourcedLoader") self.incremental = incremental javabridge.call(self.jobject, "reset", "()V") javabridge.call(self.jobject, "setURL", "(Ljava/lang/String;)V", str(url)) if incremental: self.structure = Instances(javabridge.call(self.jobject, "getStructure", "()Lweka/core/Instances;")) return self.structure else: return Instances(javabridge.call(self.jobject, "getDataSet", "()Lweka/core/Instances;"))
def load_url(self, url, incremental=False)
Loads the specified URL and returns the Instances object. In case of incremental loading, only the structure. :param url: the URL to load the data from :type url: str :param incremental: whether to load the dataset incrementally :type incremental: bool :return: the full dataset or the header (if incremental) :rtype: Instances
2.945854
2.766885
1.064682
javabridge.call(self.jobject, "reset", "()V") return Instances(javabridge.call(self.jobject, "getDataSet", "()Lweka/core/Instances;"))
def load(self)
Loads the text files from the specified directory and returns the Instances object. In case of incremental loading, only the structure. :return: the full dataset or the header (if incremental) :rtype: Instances
5.015283
3.72322
1.347028
self.enforce_type(self.jobject, "weka.core.converters.FileSourcedConverter") if not javabridge.is_instance_of(dfile, "Ljava/io/File;"): dfile = javabridge.make_instance( "Ljava/io/File;", "(Ljava/lang/String;)V", javabridge.get_env().new_string_utf(str(dfile))) javabridge.call(self.jobject, "setFile", "(Ljava/io/File;)V", dfile) javabridge.call(self.jobject, "setInstances", "(Lweka/core/Instances;)V", data.jobject) javabridge.call(self.jobject, "writeBatch", "()V")
def save_file(self, data, dfile)
Saves the Instances object in the specified file. :param data: the data to save :type data: Instances :param dfile: the file to save the data to :type dfile: str
2.479714
2.352765
1.053957
result = [] length = javabridge.get_env().get_array_length(a) wrapped = javabridge.get_env().get_object_array_elements(a) for i in range(length): result.append(javabridge.get_env().get_string(wrapped[i])) return result
def string_array_to_list(a)
Turns the Java string array into Python unicode string list. :param a: the string array to convert :type a: JB_Object :return: the string list :rtype: list
2.216352
2.324892
0.953314
result = javabridge.get_env().make_object_array(len(l), javabridge.get_env().find_class("java/lang/String")) for i in range(len(l)): javabridge.get_env().set_object_array_element(result, i, javabridge.get_env().new_string_utf(l[i])) return result
def string_list_to_array(l)
Turns a Python unicode string list into a Java String array. :param l: the string list :type: list :rtype: java string array :return: JB_Object
2.207961
2.279599
0.968574
rows = javabridge.get_env().get_object_array_elements(m) num_rows = len(rows) num_cols = javabridge.get_env().get_array_length(rows[0]) result = numpy.zeros(num_rows * num_cols).reshape((num_rows, num_cols)) i = 0 for row in rows: elements = javabridge.get_env().get_double_array_elements(row) n = 0 for element in elements: result[i][n] = element n += 1 i += 1 return result
def double_matrix_to_ndarray(m)
Turns the Java matrix (2-dim array) of doubles into a numpy 2-dim array. :param m: the double matrix :type: JB_Object :return: Numpy array :rtype: numpy.darray
2.00009
2.049842
0.975729
result = [] while javabridge.call(enm, "hasMoreElements", "()Z"): result.append(javabridge.call(enm, "nextElement", "()Ljava/lang/Object;")) return result
def enumeration_to_list(enm)
Turns the java.util.Enumeration into a list. :param enm: the enumeration to convert :type enm: JB_Object :return: the list :rtype: list
2.623407
2.541761
1.032122
parser = argparse.ArgumentParser( description='Performs attribute selection from the command-line. Calls JVM start/stop automatically.') parser.add_argument("-j", metavar="classpath", dest="classpath", help="additional classpath, jars/directories") parser.add_argument("-X", metavar="heap", dest="heap", help="max heap size for jvm, e.g., 512m") parser.add_argument("-i", metavar="input", dest="input", required=True, help="input file") parser.add_argument("-c", metavar="class index", dest="classindex", help="1-based class attribute index") parser.add_argument("-s", metavar="search", dest="search", help="search method, classname and options") parser.add_argument("-x", metavar="num folds", dest="numfolds", help="number of folds") parser.add_argument("-n", metavar="seed", dest="seed", help="the seed value for randomization") parser.add_argument("evaluator", help="evaluator classname, e.g., weka.attributeSelection.CfsSubsetEval") parser.add_argument("option", nargs=argparse.REMAINDER, help="additional evaluator options") parsed = parser.parse_args() jars = [] if parsed.classpath is not None: jars = parsed.classpath.split(os.pathsep) params = [] if parsed.input is not None: params.extend(["-i", parsed.input]) if parsed.classindex is not None: params.extend(["-c", parsed.classindex]) if parsed.search is not None: params.extend(["-s", parsed.search]) if parsed.numfolds is not None: params.extend(["-x", parsed.numfolds]) if parsed.seed is not None: params.extend(["-n", parsed.seed]) jvm.start(jars, max_heap_size=parsed.heap, packages=True) logger.debug("Commandline: " + join_options(sys.argv[1:])) try: evaluation = ASEvaluation(classname=parsed.evaluator) if len(parsed.option) > 0: evaluation.options = parsed.option print(AttributeSelection.attribute_selection(evaluation, params)) except Exception as e: print(e) finally: jvm.stop()
def main()
Runs attribute selection from the command-line. Calls JVM start/stop automatically. Use -h to see all options.
2.67456
2.354527
1.135923
array = javabridge.call( self.jobject, "search", "(Lweka/attributeSelection/ASEvaluation;Lweka/core/Instances;)[I", evaluation.jobject, data.jobject) if array is None: return None else: javabridge.get_env().get_int_array_elements(array)
def search(self, evaluation, data)
Performs the search and returns the indices of the selected attributes. :param evaluation: the evaluation algorithm to use :type evaluation: ASEvaluation :param data: the data to use :type data: Instances :return: the selected attributes (0-based indices) :rtype: ndarray
3.655902
3.387234
1.079318
array = javabridge.call(self.jobject, "postProcess", "([I)[I", indices) if array is None: return None else: return javabridge.get_env().get_int_array_elements(array)
def post_process(self, indices)
Post-processes the evaluator with the selected attribute indices. :param indices: the attribute indices list to use :type indices: ndarray :return: the processed indices :rtype: ndarray
3.497163
3.656271
0.956483
array = javabridge.call(self.jobject, "selectedAttributes", "()[I") if array is None: return None else: return javabridge.get_env().get_int_array_elements(array)
def selected_attributes(self)
Returns the selected attributes from the last run. :return: the Numpy array of 0-based indices :rtype: ndarray
3.711607
3.610392
1.028034
matrix = javabridge.call(self.jobject, "rankedAttributes", "()[[D") if matrix is None: return None else: return typeconv.double_matrix_to_ndarray(matrix)
def ranked_attributes(self)
Returns the matrix of ranked attributes from the last run. :return: the Numpy matrix :rtype: ndarray
6.651474
5.965341
1.11502
if type(data) is Instance: return Instance( javabridge.call( self.jobject, "reduceDimensionality", "(Lweka/core/Instance;)Lweka/core/Instance;", data.jobject)) else: return Instances( javabridge.call( self.jobject, "reduceDimensionality", "(Lweka/core/Instances;)Lweka/core/Instances;", data.jobject))
def reduce_dimensionality(self, data)
Reduces the dimensionality of the provided Instance or Instances object. :param data: the data to process :type data: Instances :return: the reduced dataset :rtype: Instances
2.311366
2.114228
1.093243
jtc = JavaObject.new_instance("weka.classifiers.evaluation.ThresholdCurve") pred = javabridge.call(evaluation.jobject, "predictions", "()Ljava/util/ArrayList;") result = Instances( javabridge.call(jtc, "getCurve", "(Ljava/util/ArrayList;I)Lweka/core/Instances;", pred, class_index)) return result
def generate_thresholdcurve_data(evaluation, class_index)
Generates the threshold curve data from the evaluation object's predictions. :param evaluation: the evaluation to obtain the predictions from :type evaluation: Evaluation :param class_index: the 0-based index of the class-label to create the plot for :type class_index: int :return: the generated threshold curve data :rtype: Instances
4.677663
4.49756
1.040045
xi = data.attribute_by_name(xname).index yi = data.attribute_by_name(yname).index x = [] y = [] for i in range(data.num_instances): inst = data.get_instance(i) x.append(inst.get_value(xi)) y.append(inst.get_value(yi)) return x, y
def get_thresholdcurve_data(data, xname, yname)
Retrieves x and y columns from of the data generated by the weka.classifiers.evaluation.ThresholdCurve class. :param data: the threshold curve data :type data: Instances :param xname: the name of the X column :type xname: str :param yname: the name of the Y column :type yname: str :return: tuple of x and y arrays :rtype: tuple
2.363429
2.272805
1.039873
if not plot.matplotlib_available: logger.error("Matplotlib is not installed, plotting unavailable!") return if class_index is None: class_index = [0] ax = None for cindex in class_index: data = generate_thresholdcurve_data(evaluation, cindex) head = evaluation.header area = get_auc(data) x, y = get_thresholdcurve_data(data, "False Positive Rate", "True Positive Rate") if ax is None: fig, ax = plt.subplots() ax.set_xlabel("False Positive Rate") ax.set_ylabel("True Positive Rate") if title is None: title = "ROC" ax.set_title(title) ax.grid(True) fig.canvas.set_window_title(title) plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plot_label = head.class_attribute.value(cindex) + " (AUC: %0.4f)" % area ax.plot(x, y, label=plot_label) ax.plot(ax.get_xlim(), ax.get_ylim(), ls="--", c="0.3") plt.draw() plt.legend(loc=key_loc, shadow=True) if outfile is not None: plt.savefig(outfile) if wait: plt.show()
def plot_roc(evaluation, class_index=None, title=None, key_loc="lower right", outfile=None, wait=True)
Plots the ROC (receiver operator characteristics) curve for the given predictions. TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html :param evaluation: the evaluation to obtain the predictions from :type evaluation: Evaluation :param class_index: the list of 0-based indices of the class-labels to create the plot for :type class_index: list :param title: an optional title :type title: str :param key_loc: the position string for the key :type key_loc: str :param outfile: the output file, ignored if None :type outfile: str :param wait: whether to wait for the user to close the plot :type wait: bool
2.622579
2.647205
0.990697
establish_cache() result = [] pkgs = javabridge.get_collection_wrapper( javabridge.static_call( "weka/core/WekaPackageManager", "getAllPackages", "()Ljava/util/List;")) for pkge in pkgs: result.append(Package(pkge)) return result
def all_packages()
Returns a list of all packages. :return: the list of packages :rtype: list
5.55659
6.113994
0.908832
establish_cache() if pkge.startswith("http://") or pkge.startswith("https://"): url = javabridge.make_instance( "java/net/URL", "(Ljava/lang/String;)V", javabridge.get_env().new_string_utf(pkge)) return not javabridge.static_call( "weka/core/WekaPackageManager", "installPackageFromURL", "(Ljava/net/URL;[Ljava/io/PrintStream;)Ljava/lang/String;", url, []) is None elif pkge.lower().endswith(".zip"): return not javabridge.static_call( "weka/core/WekaPackageManager", "installPackageFromArchive", "(Ljava/lang/String;[Ljava/io/PrintStream;)Ljava/lang/String;", pkge, []) is None else: return javabridge.static_call( "weka/core/WekaPackageManager", "installPackageFromRepository", "(Ljava/lang/String;Ljava/lang/String;[Ljava/io/PrintStream;)Z", pkge, version, [])
def install_package(pkge, version="Latest")
The list of packages to install. :param pkge: the name of the repository package, a URL (http/https) or a zip file :type pkge: str :param version: in case of the repository packages, the version :type version: str :return: whether successfully installed :rtype: bool
2.529957
2.398971
1.054601
pkgs = installed_packages() for pkge in pkgs: if pkge.name == name: return True return False
def is_installed(name)
Checks whether a package with the name is already installed. :param name: the name of the package :type name: str :return: whether the package is installed :rtype: bool
4.248734
4.760885
0.892425
result = [] dependencies = javabridge.get_collection_wrapper( javabridge.call(self.jobject, "getDependencies", "()Ljava/util/List;")) for dependency in dependencies: result.append(Dependency(dependency)) return result
def dependencies(self)
Returns the dependencies of the package. :return: the list of Dependency objects :rtype: list of Dependency
4.298514
3.966645
1.083665
if not pkge is None: return javabridge.call( self.jobject, "checkConstraint", "(Lweka/core/packageManagement/Package;)Z", pkge.jobject) if not constr is None: return javabridge.call( self.jobject, "checkConstraint", "(Lweka/core/packageManagement/PackageConstraint;)Z", pkge.jobject) raise Exception("Either package or package constraing must be provided!")
def check_constraint(self, pkge=None, constr=None)
Checks the constraints. :param pkge: the package to check :type pkge: Package :param constr: the package constraint to check :type constr: PackageConstraint
3.150675
3.067735
1.027036
fprops = javabridge.make_instance("java/io/File", "(Ljava/lang/String;)V", props) javabridge.call(self.jobject, "setCustomPropsFile", "(Ljava/io/File;)V", fprops)
def custom_properties(self, props)
Sets the custom properties file to use. :param props: the props file :type props: str
3.842639
3.376563
1.138033
if query is None: data = javabridge.call(self.jobject, "retrieveInstances", "()Lweka/core/Instances;") else: data = javabridge.call(self.jobject, "retrieveInstances", "(Ljava/lang/String;)Lweka/core/Instances;") return Instances(data)
def retrieve_instances(self, query=None)
Executes either the supplied query or the one set via options (or the 'query' property). :param query: query to execute if not the currently set one :type query: str :return: the generated dataq :rtype: Instances
2.383595
2.44609
0.974451