repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
AguaClara/aguaclara
aguaclara/research/floc_model.py
num_coll_reqd
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. """ return DIM_FRACTAL * np.log2(DiamTarget/material.Diameter)
python
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. """ return DIM_FRACTAL * np.log2(DiamTarget/material.Diameter)
Return the number of doubling collisions required. Calculates the number of doubling collisions required to produce a floc of diameter DiamTarget.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L255-L261
AguaClara/aguaclara
aguaclara/research/floc_model.py
sep_dist_floc
def sep_dist_floc(ConcAluminum, ConcClay, coag, material, DIM_FRACTAL, DiamTarget): """Return separation distance as a function of floc size.""" return (material.Diameter * (np.pi/(6 * frac_vol_floc_initial(ConcAluminum, ConcClay, coag, material) ))**(1/3) * (DiamTarget / material.Diameter)**(DIM_FRACTAL / 3) )
python
def sep_dist_floc(ConcAluminum, ConcClay, coag, material, DIM_FRACTAL, DiamTarget): """Return separation distance as a function of floc size.""" return (material.Diameter * (np.pi/(6 * frac_vol_floc_initial(ConcAluminum, ConcClay, coag, material) ))**(1/3) * (DiamTarget / material.Diameter)**(DIM_FRACTAL / 3) )
Return separation distance as a function of floc size.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L266-L275
AguaClara/aguaclara
aguaclara/research/floc_model.py
frac_vol_floc
def frac_vol_floc(ConcAluminum, ConcClay, coag, DIM_FRACTAL, material, DiamTarget): """Return the floc volume fraction.""" return (frac_vol_floc_initial(ConcAluminum, ConcClay, coag, material) * (DiamTarget / material.Diameter)**(3-DIM_FRACTAL) )
python
def frac_vol_floc(ConcAluminum, ConcClay, coag, DIM_FRACTAL, material, DiamTarget): """Return the floc volume fraction.""" return (frac_vol_floc_initial(ConcAluminum, ConcClay, coag, material) * (DiamTarget / material.Diameter)**(3-DIM_FRACTAL) )
Return the floc volume fraction.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L280-L285
AguaClara/aguaclara
aguaclara/research/floc_model.py
dens_floc_init
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. """ return (conc_floc(ConcAluminum, ConcClay, coag).magnitude / frac_vol_floc_initial(ConcAluminum, ConcClay, coag, material) )
python
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. """ return (conc_floc(ConcAluminum, ConcClay, coag).magnitude / frac_vol_floc_initial(ConcAluminum, ConcClay, coag, material) )
Return the density of the initial floc. Initial floc is made primarily of the primary colloid and nanoglobs.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L289-L296
AguaClara/aguaclara
aguaclara/research/floc_model.py
ratio_area_clay_total
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 """ return (1 / (1 + (2 * material.Diameter / (3 * DiamTube * ratio_clay_sphere(RatioHeightDiameter) * (ConcClay / material.Density) ) ) ) )
python
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 """ return (1 / (1 + (2 * material.Diameter / (3 * DiamTube * ratio_clay_sphere(RatioHeightDiameter) * (ConcClay / material.Density) ) ) ) )
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
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L309-L336
AguaClara/aguaclara
aguaclara/research/floc_model.py
gamma_coag
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 """ 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)) ))
python
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 """ 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)) ))
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
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L339-L373
AguaClara/aguaclara
aguaclara/research/floc_model.py
gamma_humic_acid_to_coag
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 """ return min(((ConcNatOrgMat / conc_precipitate(ConcAl, coag).magnitude) * (coag.Density / NatOrgMat.Density) * (coag.Diameter / (4 * NatOrgMat.Diameter)) ), 1)
python
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 """ return min(((ConcNatOrgMat / conc_precipitate(ConcAl, coag).magnitude) * (coag.Density / NatOrgMat.Density) * (coag.Diameter / (4 * NatOrgMat.Diameter)) ), 1)
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
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L377-L396
AguaClara/aguaclara
aguaclara/research/floc_model.py
pacl_term
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 """ return (gamma_coag(ConcClay, ConcAl, coag, material, DiamTube, RatioHeightDiameter) * (1 - gamma_humic_acid_to_coag(ConcAl, ConcNatOrgMat, NatOrgMat, coag)) )
python
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 """ return (gamma_coag(ConcClay, ConcAl, coag, material, DiamTube, RatioHeightDiameter) * (1 - gamma_humic_acid_to_coag(ConcAl, ConcNatOrgMat, NatOrgMat, coag)) )
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
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L401-L430
AguaClara/aguaclara
aguaclara/research/floc_model.py
dens_floc
def dens_floc(ConcAl, ConcClay, DIM_FRACTAL, DiamTarget, coag, material, Temp): """Calculate floc density as a function of size.""" WaterDensity = pc.density_water(Temp).magnitude return ((dens_floc_init(ConcAl, ConcClay, coag, material).magnitude - WaterDensity ) * (material.Diameter / DiamTarget)**(3 - DIM_FRACTAL) + WaterDensity )
python
def dens_floc(ConcAl, ConcClay, DIM_FRACTAL, DiamTarget, coag, material, Temp): """Calculate floc density as a function of size.""" WaterDensity = pc.density_water(Temp).magnitude return ((dens_floc_init(ConcAl, ConcClay, coag, material).magnitude - WaterDensity ) * (material.Diameter / DiamTarget)**(3 - DIM_FRACTAL) + WaterDensity )
Calculate floc density as a function of size.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L505-L513
AguaClara/aguaclara
aguaclara/research/floc_model.py
vel_term_floc
def vel_term_floc(ConcAl, ConcClay, coag, material, DIM_FRACTAL, DiamTarget, Temp): """Calculate floc terminal velocity.""" 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) )
python
def vel_term_floc(ConcAl, ConcClay, coag, material, DIM_FRACTAL, DiamTarget, Temp): """Calculate floc terminal velocity.""" 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) )
Calculate floc terminal velocity.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L518-L531
AguaClara/aguaclara
aguaclara/research/floc_model.py
diam_floc_vel_term
def diam_floc_vel_term(ConcAl, ConcClay, coag, material, DIM_FRACTAL, VelTerm, Temp): """Calculate floc diamter as a function of terminal velocity.""" 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)) )
python
def diam_floc_vel_term(ConcAl, ConcClay, coag, material, DIM_FRACTAL, VelTerm, Temp): """Calculate floc diamter as a function of terminal velocity.""" 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)) )
Calculate floc diamter as a function of terminal velocity.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L536-L552
AguaClara/aguaclara
aguaclara/research/floc_model.py
time_col_laminar
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. """ 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 )
python
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. """ 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 )
Calculate single collision time for laminar flow mediated collisions. Calculated as a function of floc size.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L558-L572
AguaClara/aguaclara
aguaclara/research/floc_model.py
time_col_turbulent
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. """ 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) )
python
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. """ 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) )
Calculate single collision time for turbulent flow mediated collisions. Calculated as a function of floc size.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L577-L586
AguaClara/aguaclara
aguaclara/research/floc_model.py
diam_kolmogorov
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. """ 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) )
python
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. """ 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) )
Return the size of the floc with separation distances equal to the Kolmogorov length and the inner viscous length scale.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L602-L613
AguaClara/aguaclara
aguaclara/research/floc_model.py
dean_number
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. """ return (reynolds_rapid_mix(PlantFlow, IDTube, Temp) * (IDTube / (2 * RadiusCoil))**(1/2) )
python
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. """ return (reynolds_rapid_mix(PlantFlow, IDTube, Temp) * (IDTube / (2 * RadiusCoil))**(1/2) )
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.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L669-L679
AguaClara/aguaclara
aguaclara/research/floc_model.py
g_coil
def g_coil(FlowPlant, IDTube, RadiusCoil, Temp): """We need a reference for this. Karen's thesis likely has this equation and the reference. """ return (g_straight(FlowPlant, IDTube).magnitude * (1 + 0.033 * np.log10(dean_number(FlowPlant, IDTube, RadiusCoil, Temp) ) ** 4 ) ** (1/2) )
python
def g_coil(FlowPlant, IDTube, RadiusCoil, Temp): """We need a reference for this. Karen's thesis likely has this equation and the reference. """ return (g_straight(FlowPlant, IDTube).magnitude * (1 + 0.033 * np.log10(dean_number(FlowPlant, IDTube, RadiusCoil, Temp) ) ** 4 ) ** (1/2) )
We need a reference for this. Karen's thesis likely has this equation and the reference.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L683-L693
AguaClara/aguaclara
aguaclara/research/floc_model.py
g_time_res
def g_time_res(FlowPlant, IDTube, RadiusCoil, LengthTube, Temp): """G Residence Time calculated for a coiled tube flocculator.""" return (g_coil(FlowPlant, IDTube, RadiusCoil, Temp).magnitude * time_res_tube(IDTube, LengthTube, FlowPlant).magnitude )
python
def g_time_res(FlowPlant, IDTube, RadiusCoil, LengthTube, Temp): """G Residence Time calculated for a coiled tube flocculator.""" return (g_coil(FlowPlant, IDTube, RadiusCoil, Temp).magnitude * time_res_tube(IDTube, LengthTube, FlowPlant).magnitude )
G Residence Time calculated for a coiled tube flocculator.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L703-L707
AguaClara/aguaclara
aguaclara/research/floc_model.py
Chemical.define_Precip
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: """ self.PrecipDiameter = diameter self.PrecipDensity = density self.PrecipMolecWeight = molecweight self.PrecipAluminumMPM = alumMPM
python
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: """ self.PrecipDiameter = diameter self.PrecipDensity = density self.PrecipMolecWeight = molecweight self.PrecipAluminumMPM = 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:
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/research/floc_model.py#L59-L73
AguaClara/aguaclara
aguaclara/design/plant.py
Plant.ent_tank_a
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 """ # 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
python
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 """ # 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
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
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/design/plant.py#L24-L47
AguaClara/aguaclara
aguaclara/unit_process_design/lfom.py
n_lfom_rows
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. """ 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
python
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. """ 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
This equation states that the open area corresponding to one row can be set equal to two orifices of diameter=row height. If there are more than two orifices per row at the top of the LFOM then there are more orifices than are convenient to drill and more than necessary for good accuracy. Thus this relationship can be used to increase the spacing between the rows and thus increase the diameter of the orifices. This spacing function also sets the lower depth on the high flow rate LFOM with no accurate flows below a depth equal to the first row height. But it might be better to always set then number of rows to 10. The challenge is to figure out a reasonable system of constraints that reliably returns a valid solution.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/unit_process_design/lfom.py#L26-L51
AguaClara/aguaclara
aguaclara/unit_process_design/lfom.py
area_lfom_orifices_top
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 """ 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))
python
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 """ 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))
Estimate the orifice area corresponding to the top row of orifices. Another solution method is to use integration to solve this problem. Here we use the width of the stout weir in the center of the top row to estimate the area of the top orifice
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/unit_process_design/lfom.py#L76-L83
AguaClara/aguaclara
aguaclara/unit_process_design/lfom.py
n_lfom_orifices_per_row_max
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. """ 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))
python
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. """ 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))
A bound on the number of orifices allowed in each row. The distance between consecutive orifices must be enough to retain structural integrity of the pipe.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/unit_process_design/lfom.py#L99-L107
AguaClara/aguaclara
aguaclara/unit_process_design/lfom.py
height_lfom_orifices
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. """ return (np.arange((orifice_diameter(FLOW,HL_LFOM,drill_bits)*0.5), HL_LFOM, (dist_center_lfom_rows(FLOW,HL_LFOM))))
python
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. """ return (np.arange((orifice_diameter(FLOW,HL_LFOM,drill_bits)*0.5), HL_LFOM, (dist_center_lfom_rows(FLOW,HL_LFOM))))
Calculates the height of the center of each row of orifices. The bottom of the bottom row orifices is at the zero elevation point of the LFOM so that the flow goes to zero when the water height is at zero.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/unit_process_design/lfom.py#L115-L123
AguaClara/aguaclara
aguaclara/unit_process_design/lfom.py
flow_lfom_actual
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 """ 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
python
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 """ 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
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
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/unit_process_design/lfom.py#L126-L139
AguaClara/aguaclara
aguaclara/core/utility.py
round_sf
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 """ 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
python
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 """ 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
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
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/utility.py#L12-L37
AguaClara/aguaclara
aguaclara/core/utility.py
stepceil_with_units
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. """ counter = 0 * unit while counter < param.to(unit): counter += step * unit return counter
python
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. """ counter = 0 * unit while counter < param.to(unit): counter += step * unit return counter
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.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/utility.py#L40-L49
AguaClara/aguaclara
aguaclara/core/utility.py
list_handler
def list_handler(HandlerResult="nparray"): """Wraps a function to handle list inputs.""" def decorate(func): def wrapper(*args, **kwargs): """Run through the wrapped function once for each array element. :param HandlerResult: output type. Defaults to numpy arrays. """ 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
python
def list_handler(HandlerResult="nparray"): """Wraps a function to handle list inputs.""" def decorate(func): def wrapper(*args, **kwargs): """Run through the wrapped function once for each array element. :param HandlerResult: output type. Defaults to numpy arrays. """ 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
Wraps a function to handle list inputs.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/utility.py#L64-L132
AguaClara/aguaclara
aguaclara/core/utility.py
check_range
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. """ 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]))
python
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. """ 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]))
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.
https://github.com/AguaClara/aguaclara/blob/8dd4e734768b166a7fc2b60388a24df2f93783fc/aguaclara/core/utility.py#L135-L198
fracpete/python-weka-wrapper3
python/weka/clusterers.py
main
def main(): """ Runs a clusterer from the command-line. Calls JVM start/stop automatically. Use -h to see all options. """ 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()
python
def main(): """ Runs a clusterer from the command-line. Calls JVM start/stop automatically. Use -h to see all options. """ 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()
Runs a clusterer from the command-line. Calls JVM start/stop automatically. Use -h to see all options.
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/clusterers.py#L383-L439
fracpete/python-weka-wrapper3
python/weka/clusterers.py
Clusterer.update_clusterer
def update_clusterer(self, inst): """ Updates the clusterer with the instance. :param inst: the Instance to update the clusterer with :type inst: Instance """ 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!")
python
def update_clusterer(self, inst): """ Updates the clusterer with the instance. :param inst: the Instance to update the clusterer with :type inst: Instance """ 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!")
Updates the clusterer with the instance. :param inst: the Instance to update the clusterer with :type inst: Instance
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/clusterers.py#L78-L88
fracpete/python-weka-wrapper3
python/weka/clusterers.py
Clusterer.update_finished
def update_finished(self): """ Signals the clusterer that updating with new data has finished. """ if self.is_updateable: javabridge.call(self.jobject, "updateFinished", "()V") else: logger.critical(classes.get_classname(self.jobject) + " is not updateable!")
python
def update_finished(self): """ Signals the clusterer that updating with new data has finished. """ if self.is_updateable: javabridge.call(self.jobject, "updateFinished", "()V") else: logger.critical(classes.get_classname(self.jobject) + " is not updateable!")
Signals the clusterer that updating with new data has finished.
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/clusterers.py#L90-L97
fracpete/python-weka-wrapper3
python/weka/clusterers.py
Clusterer.distribution_for_instance
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[] """ pred = self.__distribution(inst.jobject) return javabridge.get_env().get_double_array_elements(pred)
python
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[] """ pred = self.__distribution(inst.jobject) return javabridge.get_env().get_double_array_elements(pred)
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[]
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/clusterers.py#L110-L120
fracpete/python-weka-wrapper3
python/weka/clusterers.py
ClusterEvaluation.cluster_assignments
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 """ array = javabridge.call(self.jobject, "getClusterAssignments", "()[D") if array is None: return None else: return javabridge.get_env().get_double_array_elements(array)
python
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 """ array = javabridge.call(self.jobject, "getClusterAssignments", "()[D") if array is None: return None else: return javabridge.get_env().get_double_array_elements(array)
Return an array of cluster assignments corresponding to the most recent set of instances clustered. :return: the cluster assignments :rtype: ndarray
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/clusterers.py#L297-L308
fracpete/python-weka-wrapper3
python/weka/clusterers.py
ClusterEvaluation.classes_to_clusters
def classes_to_clusters(self): """ Return the array (ordered by cluster number) of minimum error class to cluster mappings. :return: the mappings :rtype: ndarray """ array = javabridge.call(self.jobject, "getClassesToClusters", "()[I") if array is None: return None else: return javabridge.get_env().get_int_array_elements(array)
python
def classes_to_clusters(self): """ Return the array (ordered by cluster number) of minimum error class to cluster mappings. :return: the mappings :rtype: ndarray """ array = javabridge.call(self.jobject, "getClassesToClusters", "()[I") if array is None: return None else: return javabridge.get_env().get_int_array_elements(array)
Return the array (ordered by cluster number) of minimum error class to cluster mappings. :return: the mappings :rtype: ndarray
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/clusterers.py#L331-L342
fracpete/python-weka-wrapper3
python/weka/clusterers.py
ClusterEvaluation.crossvalidate_model
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 """ 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)
python
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 """ 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)
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/clusterers.py#L362-L380
fracpete/python-weka-wrapper3
python/weka/core/serialization.py
deepcopy
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 """ 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
python
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 """ 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
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/serialization.py#L27-L50
fracpete/python-weka-wrapper3
python/weka/core/serialization.py
read_all
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 """ 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)
python
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 """ 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)
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/serialization.py#L68-L84
fracpete/python-weka-wrapper3
python/weka/core/serialization.py
write
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 """ if isinstance(jobject, JavaObject): jobject = jobject.jobject javabridge.static_call( "Lweka/core/SerializationHelper;", "write", "(Ljava/lang/String;Ljava/lang/Object;)V", filename, jobject)
python
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 """ if isinstance(jobject, JavaObject): jobject = jobject.jobject javabridge.static_call( "Lweka/core/SerializationHelper;", "write", "(Ljava/lang/String;Ljava/lang/Object;)V", 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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/serialization.py#L87-L101
fracpete/python-weka-wrapper3
python/weka/associations.py
Item.decrease_frequency
def decrease_frequency(self, frequency=None): """ Decreases the frequency. :param frequency: the frequency to decrease by, 1 if None :type frequency: int """ if frequency is None: javabridge.call(self.jobject, "decreaseFrequency", "()V") else: javabridge.call(self.jobject, "decreaseFrequency", "(I)V", frequency)
python
def decrease_frequency(self, frequency=None): """ Decreases the frequency. :param frequency: the frequency to decrease by, 1 if None :type frequency: int """ if frequency is None: javabridge.call(self.jobject, "decreaseFrequency", "()V") else: javabridge.call(self.jobject, "decreaseFrequency", "(I)V", frequency)
Decreases the frequency. :param frequency: the frequency to decrease by, 1 if None :type frequency: int
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/associations.py#L84-L94
fracpete/python-weka-wrapper3
python/weka/associations.py
Item.increase_frequency
def increase_frequency(self, frequency=None): """ Increases the frequency. :param frequency: the frequency to increase by, 1 if None :type frequency: int """ if frequency is None: javabridge.call(self.jobject, "increaseFrequency", "()V") else: javabridge.call(self.jobject, "increaseFrequency", "(I)V", frequency)
python
def increase_frequency(self, frequency=None): """ Increases the frequency. :param frequency: the frequency to increase by, 1 if None :type frequency: int """ if frequency is None: javabridge.call(self.jobject, "increaseFrequency", "()V") else: javabridge.call(self.jobject, "increaseFrequency", "(I)V", frequency)
Increases the frequency. :param frequency: the frequency to increase by, 1 if None :type frequency: int
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/associations.py#L96-L106
fracpete/python-weka-wrapper3
python/weka/associations.py
AssociationRule.consequence
def consequence(self): """ Get the the consequence. :return: the consequence, list of Item objects :rtype: list """ items = javabridge.get_collection_wrapper( javabridge.call(self.jobject, "getConsequence", "()Ljava/util/Collection;")) result = [] for item in items: result.append(Item(item)) return result
python
def consequence(self): """ Get the the consequence. :return: the consequence, list of Item objects :rtype: list """ items = javabridge.get_collection_wrapper( javabridge.call(self.jobject, "getConsequence", "()Ljava/util/Collection;")) result = [] for item in items: result.append(Item(item)) return result
Get the the consequence. :return: the consequence, list of Item objects :rtype: list
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/associations.py#L275-L287
fracpete/python-weka-wrapper3
python/weka/associations.py
Associator.can_produce_rules
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 """ if not self.check_type(self.jobject, "weka.associations.AssociationRulesProducer"): return False return javabridge.call(self.jobject, "canProduceRules", "()Z")
python
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 """ if not self.check_type(self.jobject, "weka.associations.AssociationRulesProducer"): return False return javabridge.call(self.jobject, "canProduceRules", "()Z")
Checks whether association rules can be generated. :return: whether scheme implements AssociationRulesProducer interface and association rules can be generated :rtype: bool
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/associations.py#L552-L562
fracpete/python-weka-wrapper3
python/weka/associations.py
Associator.association_rules
def association_rules(self): """ Returns association rules that were generated. Only if implements AssociationRulesProducer. :return: the association rules that were generated :rtype: AssociationRules """ if not self.check_type(self.jobject, "weka.associations.AssociationRulesProducer"): return None return AssociationRules( javabridge.call(self.jobject, "getAssociationRules", "()Lweka/associations/AssociationRules;"))
python
def association_rules(self): """ Returns association rules that were generated. Only if implements AssociationRulesProducer. :return: the association rules that were generated :rtype: AssociationRules """ if not self.check_type(self.jobject, "weka.associations.AssociationRulesProducer"): return None return AssociationRules( javabridge.call(self.jobject, "getAssociationRules", "()Lweka/associations/AssociationRules;"))
Returns association rules that were generated. Only if implements AssociationRulesProducer. :return: the association rules that were generated :rtype: AssociationRules
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/associations.py#L564-L574
fracpete/python-weka-wrapper3
python/weka/associations.py
Associator.rule_metric_names
def rule_metric_names(self): """ Returns the rule metric names of the association rules. Only if implements AssociationRulesProducer. :return: the metric names :rtype: list """ 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;"))
python
def rule_metric_names(self): """ Returns the rule metric names of the association rules. Only if implements AssociationRulesProducer. :return: the metric names :rtype: list """ 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;"))
Returns the rule metric names of the association rules. Only if implements AssociationRulesProducer. :return: the metric names :rtype: list
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/associations.py#L577-L587
fracpete/python-weka-wrapper3
python/weka/core/converters.py
loader_for_file
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 """ 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)
python
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 """ 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)
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/converters.py#L228-L243
fracpete/python-weka-wrapper3
python/weka/core/converters.py
saver_for_file
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 """ 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)
python
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 """ 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)
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/converters.py#L262-L277
fracpete/python-weka-wrapper3
python/weka/core/converters.py
save_any_file
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 """ saver = saver_for_file(filename) if saver is None: return False else: saver.save_file(data, filename) return True
python
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 """ saver = saver_for_file(filename) if saver is None: return False else: saver.save_file(data, filename) return True
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/converters.py#L280-L296
fracpete/python-weka-wrapper3
python/weka/core/converters.py
ndarray_to_instances
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 """ 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
python
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 """ 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
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/converters.py#L299-L340
fracpete/python-weka-wrapper3
python/weka/core/converters.py
Loader.load_file
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 """ 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;"))
python
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 """ 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;"))
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/converters.py#L60-L88
fracpete/python-weka-wrapper3
python/weka/core/converters.py
Loader.load_url
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 """ 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;"))
python
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 """ 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;"))
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/converters.py#L90-L110
fracpete/python-weka-wrapper3
python/weka/core/converters.py
TextDirectoryLoader.load
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 """ javabridge.call(self.jobject, "reset", "()V") return Instances(javabridge.call(self.jobject, "getDataSet", "()Lweka/core/Instances;"))
python
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 """ javabridge.call(self.jobject, "reset", "()V") return Instances(javabridge.call(self.jobject, "getDataSet", "()Lweka/core/Instances;"))
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/converters.py#L168-L177
fracpete/python-weka-wrapper3
python/weka/core/converters.py
Saver.save_file
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 """ 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")
python
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 """ 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")
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/converters.py#L210-L225
fracpete/python-weka-wrapper3
python/weka/core/typeconv.py
string_array_to_list
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 """ 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
python
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 """ 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
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/typeconv.py#L25-L39
fracpete/python-weka-wrapper3
python/weka/core/typeconv.py
string_list_to_array
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 """ 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
python
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 """ 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
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/typeconv.py#L42-L54
fracpete/python-weka-wrapper3
python/weka/core/typeconv.py
double_matrix_to_ndarray
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 """ 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
python
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 """ 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
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/typeconv.py#L57-L78
fracpete/python-weka-wrapper3
python/weka/core/typeconv.py
enumeration_to_list
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 """ result = [] while javabridge.call(enm, "hasMoreElements", "()Z"): result.append(javabridge.call(enm, "nextElement", "()Ljava/lang/Object;")) return result
python
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 """ result = [] while javabridge.call(enm, "hasMoreElements", "()Z"): result.append(javabridge.call(enm, "nextElement", "()Ljava/lang/Object;")) return result
Turns the java.util.Enumeration into a list. :param enm: the enumeration to convert :type enm: JB_Object :return: the list :rtype: list
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/typeconv.py#L81-L93
fracpete/python-weka-wrapper3
python/weka/attribute_selection.py
main
def main(): """ Runs attribute selection from the command-line. Calls JVM start/stop automatically. Use -h to see all options. """ 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()
python
def main(): """ Runs attribute selection from the command-line. Calls JVM start/stop automatically. Use -h to see all options. """ 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()
Runs attribute selection from the command-line. Calls JVM start/stop automatically. Use -h to see all options.
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/attribute_selection.py#L310-L354
fracpete/python-weka-wrapper3
python/weka/attribute_selection.py
ASSearch.search
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 """ 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)
python
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 """ 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)
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/attribute_selection.py#L54-L71
fracpete/python-weka-wrapper3
python/weka/attribute_selection.py
ASEvaluation.post_process
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 """ 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)
python
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 """ 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)
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/attribute_selection.py#L114-L127
fracpete/python-weka-wrapper3
python/weka/attribute_selection.py
AttributeSelection.selected_attributes
def selected_attributes(self): """ Returns the selected attributes from the last run. :return: the Numpy array of 0-based indices :rtype: ndarray """ array = javabridge.call(self.jobject, "selectedAttributes", "()[I") if array is None: return None else: return javabridge.get_env().get_int_array_elements(array)
python
def selected_attributes(self): """ Returns the selected attributes from the last run. :return: the Numpy array of 0-based indices :rtype: ndarray """ array = javabridge.call(self.jobject, "selectedAttributes", "()[I") if array is None: return None else: return javabridge.get_env().get_int_array_elements(array)
Returns the selected attributes from the last run. :return: the Numpy array of 0-based indices :rtype: ndarray
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/attribute_selection.py#L215-L226
fracpete/python-weka-wrapper3
python/weka/attribute_selection.py
AttributeSelection.ranked_attributes
def ranked_attributes(self): """ Returns the matrix of ranked attributes from the last run. :return: the Numpy matrix :rtype: ndarray """ matrix = javabridge.call(self.jobject, "rankedAttributes", "()[[D") if matrix is None: return None else: return typeconv.double_matrix_to_ndarray(matrix)
python
def ranked_attributes(self): """ Returns the matrix of ranked attributes from the last run. :return: the Numpy matrix :rtype: ndarray """ matrix = javabridge.call(self.jobject, "rankedAttributes", "()[[D") if matrix is None: return None else: return typeconv.double_matrix_to_ndarray(matrix)
Returns the matrix of ranked attributes from the last run. :return: the Numpy matrix :rtype: ndarray
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/attribute_selection.py#L259-L270
fracpete/python-weka-wrapper3
python/weka/attribute_selection.py
AttributeSelection.reduce_dimensionality
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 """ 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))
python
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 """ 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))
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/attribute_selection.py#L272-L290
fracpete/python-weka-wrapper3
python/weka/plot/classifiers.py
generate_thresholdcurve_data
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 """ 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
python
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 """ 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
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/plot/classifiers.py#L101-L116
fracpete/python-weka-wrapper3
python/weka/plot/classifiers.py
get_thresholdcurve_data
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 """ 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
python
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 """ 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
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/plot/classifiers.py#L119-L141
fracpete/python-weka-wrapper3
python/weka/plot/classifiers.py
plot_roc
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 """ 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()
python
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 """ 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()
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/plot/classifiers.py#L170-L219
fracpete/python-weka-wrapper3
python/weka/plot/classifiers.py
plot_learning_curve
def plot_learning_curve(classifiers, train, test=None, increments=100, metric="percent_correct", title="Learning curve", label_template="[#] @ $", key_loc="lower right", outfile=None, wait=True): """ Plots a learning curve. :param classifiers: list of Classifier template objects :type classifiers: list of Classifier :param train: dataset to use for the building the classifier, used for evaluating it test set None :type train: Instances :param test: optional dataset (or list of datasets) to use for the testing the built classifiers :type test: list or Instances :param increments: the increments (>= 1: # of instances, <1: percentage of dataset) :type increments: float :param metric: the name of the numeric metric to plot (Evaluation.<metric>) :type metric: str :param title: the title for the plot :type title: str :param label_template: the template for the label in the plot (#: 1-based index of classifier, @: full classname, !: simple classname, $: options, *: 1-based index of test set) :type label_template: str :param key_loc: the location 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 """ if not plot.matplotlib_available: logger.error("Matplotlib is not installed, plotting unavailable!") return if not train.has_class(): logger.error("Training set has no class attribute set!") return if increments >= 1: inc = increments else: inc = round(train.num_instances * increments) if test is None: tst = [train] elif isinstance(test, list): tst = test elif isinstance(test, Instances): tst = [test] else: logger.error("Expected list or Instances object, instead: " + type(test)) return for t in tst: if train.equal_headers(t) is not None: logger.error("Training and test set are not compatible: " + train.equal_headers(t)) return steps = [] cls = [] evls = {} for classifier in classifiers: cl = Classifier.make_copy(classifier) cls.append(cl) evls[cl] = {} for t in tst: evls[cl][t] = [] for i in range(train.num_instances): if (i > 0) and (i % inc == 0): steps.append(i+1) for cl in cls: # train if cl.is_updateable: if i == 0: tr = Instances.copy_instances(train, 0, 1) cl.build_classifier(tr) else: cl.update_classifier(train.get_instance(i)) else: if (i > 0) and (i % inc == 0): tr = Instances.copy_instances(train, 0, i + 1) cl.build_classifier(tr) # evaluate if (i > 0) and (i % inc == 0): for t in tst: evl = Evaluation(t) evl.test_model(cl, t) evls[cl][t].append(getattr(evl, metric)) fig, ax = plt.subplots() ax.set_xlabel("# of instances") ax.set_ylabel(metric) ax.set_title(title) fig.canvas.set_window_title(title) ax.grid(True) i = 0 for cl in cls: evlpertest = evls[cl] i += 1 n = 0 for t in tst: evl = evlpertest[t] n += 1 plot_label = label_template.\ replace("#", str(i)).\ replace("*", str(n)).\ replace("@", cl.classname).\ replace("!", cl.classname[cl.classname.rfind(".") + 1:]).\ replace("$", join_options(cl.config)) ax.plot(steps, evl, label=plot_label) plt.draw() plt.legend(loc=key_loc, shadow=True) if outfile is not None: plt.savefig(outfile) if wait: plt.show()
python
def plot_learning_curve(classifiers, train, test=None, increments=100, metric="percent_correct", title="Learning curve", label_template="[#] @ $", key_loc="lower right", outfile=None, wait=True): """ Plots a learning curve. :param classifiers: list of Classifier template objects :type classifiers: list of Classifier :param train: dataset to use for the building the classifier, used for evaluating it test set None :type train: Instances :param test: optional dataset (or list of datasets) to use for the testing the built classifiers :type test: list or Instances :param increments: the increments (>= 1: # of instances, <1: percentage of dataset) :type increments: float :param metric: the name of the numeric metric to plot (Evaluation.<metric>) :type metric: str :param title: the title for the plot :type title: str :param label_template: the template for the label in the plot (#: 1-based index of classifier, @: full classname, !: simple classname, $: options, *: 1-based index of test set) :type label_template: str :param key_loc: the location 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 """ if not plot.matplotlib_available: logger.error("Matplotlib is not installed, plotting unavailable!") return if not train.has_class(): logger.error("Training set has no class attribute set!") return if increments >= 1: inc = increments else: inc = round(train.num_instances * increments) if test is None: tst = [train] elif isinstance(test, list): tst = test elif isinstance(test, Instances): tst = [test] else: logger.error("Expected list or Instances object, instead: " + type(test)) return for t in tst: if train.equal_headers(t) is not None: logger.error("Training and test set are not compatible: " + train.equal_headers(t)) return steps = [] cls = [] evls = {} for classifier in classifiers: cl = Classifier.make_copy(classifier) cls.append(cl) evls[cl] = {} for t in tst: evls[cl][t] = [] for i in range(train.num_instances): if (i > 0) and (i % inc == 0): steps.append(i+1) for cl in cls: # train if cl.is_updateable: if i == 0: tr = Instances.copy_instances(train, 0, 1) cl.build_classifier(tr) else: cl.update_classifier(train.get_instance(i)) else: if (i > 0) and (i % inc == 0): tr = Instances.copy_instances(train, 0, i + 1) cl.build_classifier(tr) # evaluate if (i > 0) and (i % inc == 0): for t in tst: evl = Evaluation(t) evl.test_model(cl, t) evls[cl][t].append(getattr(evl, metric)) fig, ax = plt.subplots() ax.set_xlabel("# of instances") ax.set_ylabel(metric) ax.set_title(title) fig.canvas.set_window_title(title) ax.grid(True) i = 0 for cl in cls: evlpertest = evls[cl] i += 1 n = 0 for t in tst: evl = evlpertest[t] n += 1 plot_label = label_template.\ replace("#", str(i)).\ replace("*", str(n)).\ replace("@", cl.classname).\ replace("!", cl.classname[cl.classname.rfind(".") + 1:]).\ replace("$", join_options(cl.config)) ax.plot(steps, evl, label=plot_label) plt.draw() plt.legend(loc=key_loc, shadow=True) if outfile is not None: plt.savefig(outfile) if wait: plt.show()
Plots a learning curve. :param classifiers: list of Classifier template objects :type classifiers: list of Classifier :param train: dataset to use for the building the classifier, used for evaluating it test set None :type train: Instances :param test: optional dataset (or list of datasets) to use for the testing the built classifiers :type test: list or Instances :param increments: the increments (>= 1: # of instances, <1: percentage of dataset) :type increments: float :param metric: the name of the numeric metric to plot (Evaluation.<metric>) :type metric: str :param title: the title for the plot :type title: str :param label_template: the template for the label in the plot (#: 1-based index of classifier, @: full classname, !: simple classname, $: options, *: 1-based index of test set) :type label_template: str :param key_loc: the location 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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/plot/classifiers.py#L274-L388
fracpete/python-weka-wrapper3
python/weka/core/packages.py
all_packages
def all_packages(): """ Returns a list of all packages. :return: the list of packages :rtype: list """ 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
python
def all_packages(): """ Returns a list of all packages. :return: the list of packages :rtype: list """ 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
Returns a list of all packages. :return: the list of packages :rtype: list
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/packages.py#L228-L242
fracpete/python-weka-wrapper3
python/weka/core/packages.py
install_package
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 """ 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, [])
python
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 """ 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, [])
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/packages.py#L279-L304
fracpete/python-weka-wrapper3
python/weka/core/packages.py
is_installed
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 """ pkgs = installed_packages() for pkge in pkgs: if pkge.name == name: return True return False
python
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 """ pkgs = installed_packages() for pkge in pkgs: if pkge.name == name: return True return False
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/packages.py#L322-L335
fracpete/python-weka-wrapper3
python/weka/core/packages.py
Package.dependencies
def dependencies(self): """ Returns the dependencies of the package. :return: the list of Dependency objects :rtype: list of Dependency """ result = [] dependencies = javabridge.get_collection_wrapper( javabridge.call(self.jobject, "getDependencies", "()Ljava/util/List;")) for dependency in dependencies: result.append(Dependency(dependency)) return result
python
def dependencies(self): """ Returns the dependencies of the package. :return: the list of Dependency objects :rtype: list of Dependency """ result = [] dependencies = javabridge.get_collection_wrapper( javabridge.call(self.jobject, "getDependencies", "()Ljava/util/List;")) for dependency in dependencies: result.append(Dependency(dependency)) return result
Returns the dependencies of the package. :return: the list of Dependency objects :rtype: list of Dependency
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/packages.py#L58-L70
fracpete/python-weka-wrapper3
python/weka/core/packages.py
PackageConstraint.check_constraint
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 """ 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!")
python
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 """ 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!")
Checks the constraints. :param pkge: the package to check :type pkge: Package :param constr: the package constraint to check :type constr: PackageConstraint
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/packages.py#L133-L148
fracpete/python-weka-wrapper3
python/weka/core/database.py
InstanceQuery.custom_properties
def custom_properties(self, props): """ Sets the custom properties file to use. :param props: the props file :type props: str """ fprops = javabridge.make_instance("java/io/File", "(Ljava/lang/String;)V", props) javabridge.call(self.jobject, "setCustomPropsFile", "(Ljava/io/File;)V", fprops)
python
def custom_properties(self, props): """ Sets the custom properties file to use. :param props: the props file :type props: str """ fprops = javabridge.make_instance("java/io/File", "(Ljava/lang/String;)V", props) javabridge.call(self.jobject, "setCustomPropsFile", "(Ljava/io/File;)V", fprops)
Sets the custom properties file to use. :param props: the props file :type props: str
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/database.py#L132-L140
fracpete/python-weka-wrapper3
python/weka/core/database.py
InstanceQuery.retrieve_instances
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 """ 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)
python
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 """ 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)
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
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/database.py#L182-L195
fracpete/python-weka-wrapper3
python/weka/core/capabilities.py
Capabilities.owner
def owner(self): """ Returns the owner of these capabilities, if any. :return: the owner, can be None :rtype: JavaObject """ obj = javabridge.call(self.jobject, "getOwner", "()Lweka/core/CapabilitiesHandler;") if obj is None: return None else: return JavaObject(jobject=obj)
python
def owner(self): """ Returns the owner of these capabilities, if any. :return: the owner, can be None :rtype: JavaObject """ obj = javabridge.call(self.jobject, "getOwner", "()Lweka/core/CapabilitiesHandler;") if obj is None: return None else: return JavaObject(jobject=obj)
Returns the owner of these capabilities, if any. :return: the owner, can be None :rtype: JavaObject
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/capabilities.py#L113-L124
fracpete/python-weka-wrapper3
python/weka/core/capabilities.py
Capabilities.dependencies
def dependencies(self): """ Returns all the dependencies. :return: the dependency list :rtype: list """ result = [] iterator = javabridge.iterate_java(javabridge.call(self.jobject, "dependencies", "()Ljava/util/Iterator;")) for c in iterator: result.append(Capability(c)) return result
python
def dependencies(self): """ Returns all the dependencies. :return: the dependency list :rtype: list """ result = [] iterator = javabridge.iterate_java(javabridge.call(self.jobject, "dependencies", "()Ljava/util/Iterator;")) for c in iterator: result.append(Capability(c)) return result
Returns all the dependencies. :return: the dependency list :rtype: list
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/capabilities.py#L181-L192
fracpete/python-weka-wrapper3
python/weka/core/capabilities.py
Capabilities.for_instances
def for_instances(cls, data, multi=None): """ returns a Capabilities object specific for this data. The minimum number of instances is not set, the check for multi-instance data is optional. :param data: the data to generate the capabilities for :type data: Instances :param multi: whether to check the structure, too :type multi: bool :return: the generated capabilities :rtype: Capabilities """ if multi is None: return Capabilities(javabridge.static_call( "weka/core/Capabilities", "forInstances", "(Lweka/core/Instances;)Lweka/core/Capabilities;", data.jobject)) else: return Capabilities(javabridge.static_call( "weka/core/Capabilities", "forInstances", "(Lweka/core/Instances;Z)Lweka/core/Capabilities;", data.jobject, multi))
python
def for_instances(cls, data, multi=None): """ returns a Capabilities object specific for this data. The minimum number of instances is not set, the check for multi-instance data is optional. :param data: the data to generate the capabilities for :type data: Instances :param multi: whether to check the structure, too :type multi: bool :return: the generated capabilities :rtype: Capabilities """ if multi is None: return Capabilities(javabridge.static_call( "weka/core/Capabilities", "forInstances", "(Lweka/core/Instances;)Lweka/core/Capabilities;", data.jobject)) else: return Capabilities(javabridge.static_call( "weka/core/Capabilities", "forInstances", "(Lweka/core/Instances;Z)Lweka/core/Capabilities;", data.jobject, multi))
returns a Capabilities object specific for this data. The minimum number of instances is not set, the check for multi-instance data is optional. :param data: the data to generate the capabilities for :type data: Instances :param multi: whether to check the structure, too :type multi: bool :return: the generated capabilities :rtype: Capabilities
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/capabilities.py#L428-L447
fracpete/python-weka-wrapper3
python/weka/plot/dataset.py
scatter_plot
def scatter_plot(data, index_x, index_y, percent=100.0, seed=1, size=50, title=None, outfile=None, wait=True): """ Plots two attributes against each other. TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html :param data: the dataset :type data: Instances :param index_x: the 0-based index of the attribute on the x axis :type index_x: int :param index_y: the 0-based index of the attribute on the y axis :type index_y: int :param percent: the percentage of the dataset to use for plotting :type percent: float :param seed: the seed value to use for subsampling :type seed: int :param size: the size of the circles in point :type size: int :param title: an optional title :type title: str :param outfile: the (optional) file to save the generated plot to. The extension determines the file format. :type outfile: str :param wait: whether to wait for the user to close the plot :type wait: bool """ if not plot.matplotlib_available: logger.error("Matplotlib is not installed, plotting unavailable!") return # create subsample data = plot.create_subsample(data, percent=percent, seed=seed) # collect data x = [] y = [] if data.class_index == -1: c = None else: c = [] for i in range(data.num_instances): inst = data.get_instance(i) x.append(inst.get_value(index_x)) y.append(inst.get_value(index_y)) if c is not None: c.append(inst.get_value(inst.class_index)) # plot data fig, ax = plt.subplots() if c is None: ax.scatter(x, y, s=size, alpha=0.5) else: ax.scatter(x, y, c=c, s=size, alpha=0.5) ax.set_xlabel(data.attribute(index_x).name) ax.set_ylabel(data.attribute(index_y).name) if title is None: title = "Attribute scatter plot" if percent != 100: title += " (%0.1f%%)" % percent ax.set_title(title) ax.plot(ax.get_xlim(), ax.get_ylim(), ls="--", c="0.3") ax.grid(True) fig.canvas.set_window_title(data.relationname) plt.draw() if outfile is not None: plt.savefig(outfile) if wait: plt.show()
python
def scatter_plot(data, index_x, index_y, percent=100.0, seed=1, size=50, title=None, outfile=None, wait=True): """ Plots two attributes against each other. TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html :param data: the dataset :type data: Instances :param index_x: the 0-based index of the attribute on the x axis :type index_x: int :param index_y: the 0-based index of the attribute on the y axis :type index_y: int :param percent: the percentage of the dataset to use for plotting :type percent: float :param seed: the seed value to use for subsampling :type seed: int :param size: the size of the circles in point :type size: int :param title: an optional title :type title: str :param outfile: the (optional) file to save the generated plot to. The extension determines the file format. :type outfile: str :param wait: whether to wait for the user to close the plot :type wait: bool """ if not plot.matplotlib_available: logger.error("Matplotlib is not installed, plotting unavailable!") return # create subsample data = plot.create_subsample(data, percent=percent, seed=seed) # collect data x = [] y = [] if data.class_index == -1: c = None else: c = [] for i in range(data.num_instances): inst = data.get_instance(i) x.append(inst.get_value(index_x)) y.append(inst.get_value(index_y)) if c is not None: c.append(inst.get_value(inst.class_index)) # plot data fig, ax = plt.subplots() if c is None: ax.scatter(x, y, s=size, alpha=0.5) else: ax.scatter(x, y, c=c, s=size, alpha=0.5) ax.set_xlabel(data.attribute(index_x).name) ax.set_ylabel(data.attribute(index_y).name) if title is None: title = "Attribute scatter plot" if percent != 100: title += " (%0.1f%%)" % percent ax.set_title(title) ax.plot(ax.get_xlim(), ax.get_ylim(), ls="--", c="0.3") ax.grid(True) fig.canvas.set_window_title(data.relationname) plt.draw() if outfile is not None: plt.savefig(outfile) if wait: plt.show()
Plots two attributes against each other. TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html :param data: the dataset :type data: Instances :param index_x: the 0-based index of the attribute on the x axis :type index_x: int :param index_y: the 0-based index of the attribute on the y axis :type index_y: int :param percent: the percentage of the dataset to use for plotting :type percent: float :param seed: the seed value to use for subsampling :type seed: int :param size: the size of the circles in point :type size: int :param title: an optional title :type title: str :param outfile: the (optional) file to save the generated plot to. The extension determines the file format. :type outfile: str :param wait: whether to wait for the user to close the plot :type wait: bool
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/plot/dataset.py#L27-L93
fracpete/python-weka-wrapper3
python/weka/plot/dataset.py
line_plot
def line_plot(data, atts=None, percent=100.0, seed=1, title=None, outfile=None, wait=True): """ Uses the internal format to plot the dataset, one line per instance. :param data: the dataset :type data: Instances :param atts: the list of 0-based attribute indices of attributes to plot :type atts: list :param percent: the percentage of the dataset to use for plotting :type percent: float :param seed: the seed value to use for subsampling :type seed: int :param title: an optional title :type title: str :param outfile: the (optional) file to save the generated plot to. The extension determines the file format. :type outfile: str :param wait: whether to wait for the user to close the plot :type wait: bool """ if not plot.matplotlib_available: logger.error("Matplotlib is not installed, plotting unavailable!") return # create subsample data = plot.create_subsample(data, percent=percent, seed=seed) fig = plt.figure() if atts is None: x = [] for i in range(data.num_attributes): x.append(i) else: x = atts ax = fig.add_subplot(111) ax.set_xlabel("attributes") ax.set_ylabel("value") ax.grid(True) for index_y in range(data.num_instances): y = [] for index_x in x: y.append(data.get_instance(index_y).get_value(index_x)) ax.plot(x, y, "o-", alpha=0.5) if title is None: title = data.relationname if percent != 100: title += " (%0.1f%%)" % percent fig.canvas.set_window_title(title) plt.draw() if outfile is not None: plt.savefig(outfile) if wait: plt.show()
python
def line_plot(data, atts=None, percent=100.0, seed=1, title=None, outfile=None, wait=True): """ Uses the internal format to plot the dataset, one line per instance. :param data: the dataset :type data: Instances :param atts: the list of 0-based attribute indices of attributes to plot :type atts: list :param percent: the percentage of the dataset to use for plotting :type percent: float :param seed: the seed value to use for subsampling :type seed: int :param title: an optional title :type title: str :param outfile: the (optional) file to save the generated plot to. The extension determines the file format. :type outfile: str :param wait: whether to wait for the user to close the plot :type wait: bool """ if not plot.matplotlib_available: logger.error("Matplotlib is not installed, plotting unavailable!") return # create subsample data = plot.create_subsample(data, percent=percent, seed=seed) fig = plt.figure() if atts is None: x = [] for i in range(data.num_attributes): x.append(i) else: x = atts ax = fig.add_subplot(111) ax.set_xlabel("attributes") ax.set_ylabel("value") ax.grid(True) for index_y in range(data.num_instances): y = [] for index_x in x: y.append(data.get_instance(index_y).get_value(index_x)) ax.plot(x, y, "o-", alpha=0.5) if title is None: title = data.relationname if percent != 100: title += " (%0.1f%%)" % percent fig.canvas.set_window_title(title) plt.draw() if outfile is not None: plt.savefig(outfile) if wait: plt.show()
Uses the internal format to plot the dataset, one line per instance. :param data: the dataset :type data: Instances :param atts: the list of 0-based attribute indices of attributes to plot :type atts: list :param percent: the percentage of the dataset to use for plotting :type percent: float :param seed: the seed value to use for subsampling :type seed: int :param title: an optional title :type title: str :param outfile: the (optional) file to save the generated plot to. The extension determines the file format. :type outfile: str :param wait: whether to wait for the user to close the plot :type wait: bool
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/plot/dataset.py#L168-L221
fracpete/python-weka-wrapper3
python/weka/filters.py
Filter.filter
def filter(self, data): """ Filters the dataset(s). When providing a list, this can be used to create compatible train/test sets, since the filter only gets initialized with the first dataset and all subsequent datasets get transformed using the same setup. NB: inputformat(Instances) must have been called beforehand. :param data: the Instances to filter :type data: Instances or list of Instances :return: the filtered Instances object(s) :rtype: Instances or list of Instances """ if isinstance(data, list): result = [] for d in data: result.append(Instances(javabridge.static_call( "Lweka/filters/Filter;", "useFilter", "(Lweka/core/Instances;Lweka/filters/Filter;)Lweka/core/Instances;", d.jobject, self.jobject))) return result else: return Instances(javabridge.static_call( "Lweka/filters/Filter;", "useFilter", "(Lweka/core/Instances;Lweka/filters/Filter;)Lweka/core/Instances;", data.jobject, self.jobject))
python
def filter(self, data): """ Filters the dataset(s). When providing a list, this can be used to create compatible train/test sets, since the filter only gets initialized with the first dataset and all subsequent datasets get transformed using the same setup. NB: inputformat(Instances) must have been called beforehand. :param data: the Instances to filter :type data: Instances or list of Instances :return: the filtered Instances object(s) :rtype: Instances or list of Instances """ if isinstance(data, list): result = [] for d in data: result.append(Instances(javabridge.static_call( "Lweka/filters/Filter;", "useFilter", "(Lweka/core/Instances;Lweka/filters/Filter;)Lweka/core/Instances;", d.jobject, self.jobject))) return result else: return Instances(javabridge.static_call( "Lweka/filters/Filter;", "useFilter", "(Lweka/core/Instances;Lweka/filters/Filter;)Lweka/core/Instances;", data.jobject, self.jobject))
Filters the dataset(s). When providing a list, this can be used to create compatible train/test sets, since the filter only gets initialized with the first dataset and all subsequent datasets get transformed using the same setup. NB: inputformat(Instances) must have been called beforehand. :param data: the Instances to filter :type data: Instances or list of Instances :return: the filtered Instances object(s) :rtype: Instances or list of Instances
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/filters.py#L122-L147
fracpete/python-weka-wrapper3
python/weka/filters.py
MultiFilter.filters
def filters(self): """ Returns the list of base filters. :return: the filter list :rtype: list """ objects = javabridge.get_env().get_object_array_elements( javabridge.call(self.jobject, "getFilters", "()[Lweka/filters/Filter;")) result = [] for obj in objects: result.append(Filter(jobject=obj)) return result
python
def filters(self): """ Returns the list of base filters. :return: the filter list :rtype: list """ objects = javabridge.get_env().get_object_array_elements( javabridge.call(self.jobject, "getFilters", "()[Lweka/filters/Filter;")) result = [] for obj in objects: result.append(Filter(jobject=obj)) return result
Returns the list of base filters. :return: the filter list :rtype: list
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/filters.py#L201-L213
fracpete/python-weka-wrapper3
python/weka/filters.py
MultiFilter.filters
def filters(self, filters): """ Sets the base filters. :param filters: the list of base filters to use :type filters: list """ obj = [] for fltr in filters: obj.append(fltr.jobject) javabridge.call(self.jobject, "setFilters", "([Lweka/filters/Filter;)V", obj)
python
def filters(self, filters): """ Sets the base filters. :param filters: the list of base filters to use :type filters: list """ obj = [] for fltr in filters: obj.append(fltr.jobject) javabridge.call(self.jobject, "setFilters", "([Lweka/filters/Filter;)V", obj)
Sets the base filters. :param filters: the list of base filters to use :type filters: list
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/filters.py#L216-L226
fracpete/python-weka-wrapper3
python/weka/flow/container.py
Container.generate_help
def generate_help(self): """ Generates a help string for this container. :return: the help string :rtype: str """ result = [] result.append(self.__class__.__name__) result.append(re.sub(r'.', '=', self.__class__.__name__)) result.append("") result.append("Supported value names:") for a in self.allowed: result.append(a) return '\n'.join(result)
python
def generate_help(self): """ Generates a help string for this container. :return: the help string :rtype: str """ result = [] result.append(self.__class__.__name__) result.append(re.sub(r'.', '=', self.__class__.__name__)) result.append("") result.append("Supported value names:") for a in self.allowed: result.append(a) return '\n'.join(result)
Generates a help string for this container. :return: the help string :rtype: str
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/container.py#L84-L98
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
Transformer.post_execute
def post_execute(self): """ Gets executed after the actual execution. :return: None if successful, otherwise error message :rtype: str """ result = super(Transformer, self).post_execute() if result is None: self._input = None return result
python
def post_execute(self): """ Gets executed after the actual execution. :return: None if successful, otherwise error message :rtype: str """ result = super(Transformer, self).post_execute() if result is None: self._input = None return result
Gets executed after the actual execution. :return: None if successful, otherwise error message :rtype: str
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L55-L65
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
LoadDataset.quickinfo
def quickinfo(self): """ Returns a short string describing some of the options of the actor. :return: the info, None if not available :rtype: str """ return "incremental: " + str(self.config["incremental"]) \ + ", custom: " + str(self.config["use_custom_loader"]) \ + ", loader: " + base.to_commandline(self.config["custom_loader"])
python
def quickinfo(self): """ Returns a short string describing some of the options of the actor. :return: the info, None if not available :rtype: str """ return "incremental: " + str(self.config["incremental"]) \ + ", custom: " + str(self.config["use_custom_loader"]) \ + ", loader: " + base.to_commandline(self.config["custom_loader"])
Returns a short string describing some of the options of the actor. :return: the info, None if not available :rtype: str
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L131-L140
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
LoadDataset.fix_config
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ opt = "incremental" if opt not in options: options[opt] = False if opt not in self.help: self.help[opt] = "Whether to load the dataset incrementally (bool)." opt = "use_custom_loader" if opt not in options: options[opt] = False if opt not in self.help: self.help[opt] = "Whether to use a custom loader." opt = "custom_loader" if opt not in options: options[opt] = converters.Loader(classname="weka.core.converters.ArffLoader") if opt not in self.help: self.help[opt] = "The custom loader to use (Loader)." return super(LoadDataset, self).fix_config(options)
python
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ opt = "incremental" if opt not in options: options[opt] = False if opt not in self.help: self.help[opt] = "Whether to load the dataset incrementally (bool)." opt = "use_custom_loader" if opt not in options: options[opt] = False if opt not in self.help: self.help[opt] = "Whether to use a custom loader." opt = "custom_loader" if opt not in options: options[opt] = converters.Loader(classname="weka.core.converters.ArffLoader") if opt not in self.help: self.help[opt] = "The custom loader to use (Loader)." return super(LoadDataset, self).fix_config(options)
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L142-L169
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
LoadDataset.check_input
def check_input(self, token): """ Performs checks on the input token. Raises an exception if unsupported. :param token: the token to check :type token: Token """ if token is None: raise Exception(self.full_name + ": No token provided!") if isinstance(token.payload, str): return raise Exception(self.full_name + ": Unhandled class: " + classes.get_classname(token.payload))
python
def check_input(self, token): """ Performs checks on the input token. Raises an exception if unsupported. :param token: the token to check :type token: Token """ if token is None: raise Exception(self.full_name + ": No token provided!") if isinstance(token.payload, str): return raise Exception(self.full_name + ": Unhandled class: " + classes.get_classname(token.payload))
Performs checks on the input token. Raises an exception if unsupported. :param token: the token to check :type token: Token
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L171-L182
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
LoadDataset.do_execute
def do_execute(self): """ The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str """ fname = str(self.input.payload) if not os.path.exists(fname): return "File '" + fname + "' does not exist!" if not os.path.isfile(fname): return "Location '" + fname + "' is not a file!" if self.resolve_option("use_custom_loader"): self._loader = self.resolve_option("custom_loader") else: self._loader = converters.loader_for_file(fname) dataset = self._loader.load_file(fname, incremental=bool(self.resolve_option("incremental"))) if not self.resolve_option("incremental"): self._output.append(Token(dataset)) else: self._iterator = self._loader.__iter__() return None
python
def do_execute(self): """ The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str """ fname = str(self.input.payload) if not os.path.exists(fname): return "File '" + fname + "' does not exist!" if not os.path.isfile(fname): return "Location '" + fname + "' is not a file!" if self.resolve_option("use_custom_loader"): self._loader = self.resolve_option("custom_loader") else: self._loader = converters.loader_for_file(fname) dataset = self._loader.load_file(fname, incremental=bool(self.resolve_option("incremental"))) if not self.resolve_option("incremental"): self._output.append(Token(dataset)) else: self._iterator = self._loader.__iter__() return None
The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L184-L205
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
LoadDataset.output
def output(self): """ Returns the next available output token. :return: the next token, None if none available :rtype: Token """ if self._iterator is not None: try: inst = self._iterator.next() result = Token(inst) except Exception as e: self._iterator = None result = None else: result = super(LoadDataset, self).output() return result
python
def output(self): """ Returns the next available output token. :return: the next token, None if none available :rtype: Token """ if self._iterator is not None: try: inst = self._iterator.next() result = Token(inst) except Exception as e: self._iterator = None result = None else: result = super(LoadDataset, self).output() return result
Returns the next available output token. :return: the next token, None if none available :rtype: Token
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L216-L232
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
LoadDataset.stop_execution
def stop_execution(self): """ Triggers the stopping of the object. """ super(LoadDataset, self).stop_execution() self._loader = None self._iterator = None
python
def stop_execution(self): """ Triggers the stopping of the object. """ super(LoadDataset, self).stop_execution() self._loader = None self._iterator = None
Triggers the stopping of the object.
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L234-L240
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
LoadDataset.wrapup
def wrapup(self): """ Finishes up after execution finishes, does not remove any graphical output. """ self._loader = None self._iterator = None super(LoadDataset, self).wrapup()
python
def wrapup(self): """ Finishes up after execution finishes, does not remove any graphical output. """ self._loader = None self._iterator = None super(LoadDataset, self).wrapup()
Finishes up after execution finishes, does not remove any graphical output.
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L242-L248
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
SetStorageValue.fix_config
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(SetStorageValue, self).fix_config(options) opt = "storage_name" if opt not in options: options[opt] = "unknown" if opt not in self.help: self.help[opt] = "The storage value name for storing the payload under (string)." return options
python
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(SetStorageValue, self).fix_config(options) opt = "storage_name" if opt not in options: options[opt] = "unknown" if opt not in self.help: self.help[opt] = "The storage value name for storing the payload under (string)." return options
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L286-L303
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
SetStorageValue.do_execute
def do_execute(self): """ The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str """ if self.storagehandler is None: return "No storage handler available!" self.storagehandler.storage[self.resolve_option("storage_name")] = self.input.payload self._output.append(self.input) return None
python
def do_execute(self): """ The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str """ if self.storagehandler is None: return "No storage handler available!" self.storagehandler.storage[self.resolve_option("storage_name")] = self.input.payload self._output.append(self.input) return None
The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L305-L316
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
DeleteStorageValue.fix_config
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(DeleteStorageValue, self).fix_config(options) opt = "storage_name" if opt not in options: options[opt] = "unknown" if opt not in self.help: self.help[opt] = "The name of the storage value to delete (string)." return options
python
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(DeleteStorageValue, self).fix_config(options) opt = "storage_name" if opt not in options: options[opt] = "unknown" if opt not in self.help: self.help[opt] = "The name of the storage value to delete (string)." return options
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L354-L371
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
InitStorageValue.fix_config
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(InitStorageValue, self).fix_config(options) opt = "storage_name" if opt not in options: options[opt] = "unknown" if opt not in self.help: self.help[opt] = "The name of the storage value to delete (string)." opt = "value" if opt not in options: options[opt] = "1" if opt not in self.help: self.help[opt] = "The initial value (string)." return options
python
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(InitStorageValue, self).fix_config(options) opt = "storage_name" if opt not in options: options[opt] = "unknown" if opt not in self.help: self.help[opt] = "The name of the storage value to delete (string)." opt = "value" if opt not in options: options[opt] = "1" if opt not in self.help: self.help[opt] = "The initial value (string)." return options
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L422-L445
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
InitStorageValue.do_execute
def do_execute(self): """ The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str """ if self.storagehandler is None: return "No storage handler available!" self.storagehandler.storage[self.resolve_option("storage_name")] = eval(str(self.resolve_option("value"))) self._output.append(self.input) return None
python
def do_execute(self): """ The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str """ if self.storagehandler is None: return "No storage handler available!" self.storagehandler.storage[self.resolve_option("storage_name")] = eval(str(self.resolve_option("value"))) self._output.append(self.input) return None
The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L447-L458
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
UpdateStorageValue.fix_config
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(UpdateStorageValue, self).fix_config(options) opt = "storage_name" if opt not in options: options[opt] = "unknown" if opt not in self.help: self.help[opt] = "The name of the storage value to update (string)." opt = "expression" if opt not in options: options[opt] = "int({X} + 1)" if opt not in self.help: self.help[opt] = "The expression for updating the storage value; use {X} for current value (string)." return options
python
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(UpdateStorageValue, self).fix_config(options) opt = "storage_name" if opt not in options: options[opt] = "unknown" if opt not in self.help: self.help[opt] = "The name of the storage value to update (string)." opt = "expression" if opt not in options: options[opt] = "int({X} + 1)" if opt not in self.help: self.help[opt] = "The expression for updating the storage value; use {X} for current value (string)." return options
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L499-L522
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
UpdateStorageValue.do_execute
def do_execute(self): """ The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str """ if self.storagehandler is None: return "No storage handler available!" expr = str(self.resolve_option("expression")).replace( "{X}", str(self.storagehandler.storage[str(self.resolve_option("storage_name"))])) expr = self.storagehandler.expand(expr) self.storagehandler.storage[self.resolve_option("storage_name")] = eval(expr) self._output.append(self.input) return None
python
def do_execute(self): """ The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str """ if self.storagehandler is None: return "No storage handler available!" expr = str(self.resolve_option("expression")).replace( "{X}", str(self.storagehandler.storage[str(self.resolve_option("storage_name"))])) expr = self.storagehandler.expand(expr) self.storagehandler.storage[self.resolve_option("storage_name")] = eval(expr) self._output.append(self.input) return None
The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L524-L538
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
MathExpression.fix_config
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(MathExpression, self).fix_config(options) opt = "expression" if opt not in options: options[opt] = "{X}" if opt not in self.help: self.help[opt] = "The mathematical expression to evaluate (string)." return options
python
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(MathExpression, self).fix_config(options) opt = "expression" if opt not in options: options[opt] = "{X}" if opt not in self.help: self.help[opt] = "The mathematical expression to evaluate (string)." return options
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L581-L598
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
MathExpression.do_execute
def do_execute(self): """ The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str """ expr = str(self.resolve_option("expression")) expr = expr.replace("{X}", str(self.input.payload)) self._output.append(Token(eval(expr))) return None
python
def do_execute(self): """ The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str """ expr = str(self.resolve_option("expression")) expr = expr.replace("{X}", str(self.input.payload)) self._output.append(Token(eval(expr))) return None
The actual execution of the actor. :return: None if successful, otherwise error message :rtype: str
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L600-L610
fracpete/python-weka-wrapper3
python/weka/flow/transformer.py
ClassSelector.fix_config
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(ClassSelector, self).fix_config(options) opt = "index" if opt not in options: options[opt] = "last" if opt not in self.help: self.help[opt] = "The class index (1-based number); 'first' and 'last' are accepted as well (string)." opt = "unset" if opt not in options: options[opt] = False if opt not in self.help: self.help[opt] = "Whether to unset the class index (bool)." return options
python
def fix_config(self, options): """ Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict """ options = super(ClassSelector, self).fix_config(options) opt = "index" if opt not in options: options[opt] = "last" if opt not in self.help: self.help[opt] = "The class index (1-based number); 'first' and 'last' are accepted as well (string)." opt = "unset" if opt not in options: options[opt] = False if opt not in self.help: self.help[opt] = "Whether to unset the class index (bool)." return options
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary. :param options: the options to fix :type options: dict :return: the (potentially) fixed options :rtype: dict
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/flow/transformer.py#L649-L672