idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
18,100 | def cumprod ( vari , axis = None ) : if isinstance ( vari , Poly ) : if np . prod ( vari . shape ) == 1 : return vari . copy ( ) if axis is None : vari = chaospy . poly . shaping . flatten ( vari ) axis = 0 vari = chaospy . poly . shaping . rollaxis ( vari , axis ) out = [ vari [ 0 ] ] for poly in vari [ 1 : ] : out . append ( out [ - 1 ] * poly ) return Poly ( out , vari . dim , vari . shape , vari . dtype ) return np . cumprod ( vari , axis ) | Perform the cumulative product of a shapeable quantity over a given axis . |
18,101 | def quad_leja ( order , dist ) : from chaospy . distributions import evaluation if len ( dist ) > 1 and evaluation . get_dependencies ( * list ( dist ) ) : raise evaluation . DependencyError ( "Leja quadrature do not supper distribution with dependencies." ) if len ( dist ) > 1 : if isinstance ( order , int ) : out = [ quad_leja ( order , _ ) for _ in dist ] else : out = [ quad_leja ( order [ _ ] , dist [ _ ] ) for _ in range ( len ( dist ) ) ] abscissas = [ _ [ 0 ] [ 0 ] for _ in out ] weights = [ _ [ 1 ] for _ in out ] abscissas = chaospy . quad . combine ( abscissas ) . T weights = chaospy . quad . combine ( weights ) weights = numpy . prod ( weights , - 1 ) return abscissas , weights lower , upper = dist . range ( ) abscissas = [ lower , dist . mom ( 1 ) , upper ] for _ in range ( int ( order ) ) : obj = create_objective ( dist , abscissas ) opts , vals = zip ( * [ fminbound ( obj , abscissas [ idx ] , abscissas [ idx + 1 ] , full_output = 1 ) [ : 2 ] for idx in range ( len ( abscissas ) - 1 ) ] ) index = numpy . argmin ( vals ) abscissas . insert ( index + 1 , opts [ index ] ) abscissas = numpy . asfarray ( abscissas ) . flatten ( ) [ 1 : - 1 ] weights = create_weights ( abscissas , dist ) abscissas = abscissas . reshape ( 1 , abscissas . size ) return numpy . array ( abscissas ) , numpy . array ( weights ) | Generate Leja quadrature node . |
18,102 | def create_objective ( dist , abscissas ) : abscissas_ = numpy . array ( abscissas [ 1 : - 1 ] ) def obj ( absisa ) : out = - numpy . sqrt ( dist . pdf ( absisa ) ) out *= numpy . prod ( numpy . abs ( abscissas_ - absisa ) ) return out return obj | Create objective function . |
18,103 | def create_weights ( nodes , dist ) : poly = chaospy . quad . generate_stieltjes ( dist , len ( nodes ) - 1 , retall = True ) [ 0 ] poly = chaospy . poly . flatten ( chaospy . poly . Poly ( poly ) ) weights_inverse = poly ( nodes ) weights = numpy . linalg . inv ( weights_inverse ) return weights [ : , 0 ] | Create weights for the Laja method . |
18,104 | def gill_king ( mat , eps = 1e-16 ) : if not scipy . sparse . issparse ( mat ) : mat = numpy . asfarray ( mat ) assert numpy . allclose ( mat , mat . T ) size = mat . shape [ 0 ] mat_diag = mat . diagonal ( ) gamma = abs ( mat_diag ) . max ( ) off_diag = abs ( mat - numpy . diag ( mat_diag ) ) . max ( ) delta = eps * max ( gamma + off_diag , 1 ) beta = numpy . sqrt ( max ( gamma , off_diag / size , eps ) ) lowtri = _gill_king ( mat , beta , delta ) return lowtri | Gill - King algorithm for modified cholesky decomposition . |
18,105 | def _gill_king ( mat , beta , delta ) : size = mat . shape [ 0 ] if scipy . sparse . issparse ( mat ) : lowtri = scipy . sparse . eye ( * mat . shape ) else : lowtri = numpy . eye ( size ) d_vec = numpy . zeros ( size , dtype = float ) for idx in range ( size ) : if idx == 0 : idz = [ ] else : idz = numpy . s_ [ : idx ] djtemp = mat [ idx , idx ] - numpy . dot ( lowtri [ idx , idz ] , d_vec [ idz ] * lowtri [ idx , idz ] . T ) if idx < size - 1 : idy = numpy . s_ [ idx + 1 : size ] ccol = mat [ idy , idx ] - numpy . dot ( lowtri [ idy , idz ] , d_vec [ idz ] * lowtri [ idx , idz ] . T ) theta = abs ( ccol ) . max ( ) d_vec [ idx ] = max ( abs ( djtemp ) , ( theta / beta ) ** 2 , delta ) lowtri [ idy , idx ] = ccol / d_vec [ idx ] else : d_vec [ idx ] = max ( abs ( djtemp ) , delta ) for idx in range ( size ) : lowtri [ : , idx ] = lowtri [ : , idx ] * numpy . sqrt ( d_vec [ idx ] ) return lowtri | Backend function for the Gill - King algorithm . |
18,106 | def approximate_moment ( dist , K , retall = False , control_var = None , rule = "F" , order = 1000 , ** kws ) : dim = len ( dist ) shape = K . shape size = int ( K . size / dim ) K = K . reshape ( dim , size ) if dim > 1 : shape = shape [ 1 : ] X , W = quad . generate_quadrature ( order , dist , rule = rule , normalize = True , ** kws ) grid = numpy . mgrid [ : len ( X [ 0 ] ) , : size ] X = X . T [ grid [ 0 ] ] . T K = K . T [ grid [ 1 ] ] . T out = numpy . prod ( X ** K , 0 ) * W if control_var is not None : Y = control_var . ppf ( dist . fwd ( X ) ) mu = control_var . mom ( numpy . eye ( len ( control_var ) ) ) if ( mu . size == 1 ) and ( dim > 1 ) : mu = mu . repeat ( dim ) for d in range ( dim ) : alpha = numpy . cov ( out , Y [ d ] ) [ 0 , 1 ] / numpy . var ( Y [ d ] ) out -= alpha * ( Y [ d ] - mu ) out = numpy . sum ( out , - 1 ) return out | Approximation method for estimation of raw statistical moments . |
18,107 | def approximate_density ( dist , xloc , parameters = None , cache = None , eps = 1.e-7 ) : if parameters is None : parameters = dist . prm . copy ( ) if cache is None : cache = { } xloc = numpy . asfarray ( xloc ) lo , up = numpy . min ( xloc ) , numpy . max ( xloc ) mu = .5 * ( lo + up ) eps = numpy . where ( xloc < mu , eps , - eps ) * xloc floc = evaluation . evaluate_forward ( dist , xloc , parameters = parameters . copy ( ) , cache = cache . copy ( ) ) for d in range ( len ( dist ) ) : xloc [ d ] += eps [ d ] tmp = evaluation . evaluate_forward ( dist , xloc , parameters = parameters . copy ( ) , cache = cache . copy ( ) ) floc [ d ] -= tmp [ d ] xloc [ d ] -= eps [ d ] floc = numpy . abs ( floc / eps ) return floc | Approximate the probability density function . |
18,108 | def create_van_der_corput_samples ( idx , number_base = 2 ) : assert number_base > 1 idx = numpy . asarray ( idx ) . flatten ( ) + 1 out = numpy . zeros ( len ( idx ) , dtype = float ) base = float ( number_base ) active = numpy . ones ( len ( idx ) , dtype = bool ) while numpy . any ( active ) : out [ active ] += ( idx [ active ] % number_base ) / base idx //= number_base base *= number_base active = idx > 0 return out | Van der Corput samples . |
18,109 | def add ( * args ) : if len ( args ) > 2 : return add ( args [ 0 ] , add ( args [ 1 ] , args [ 1 : ] ) ) if len ( args ) == 1 : return args [ 0 ] part1 , part2 = args if isinstance ( part2 , Poly ) : if part2 . dim > part1 . dim : part1 = chaospy . dimension . setdim ( part1 , part2 . dim ) elif part2 . dim < part1 . dim : part2 = chaospy . dimension . setdim ( part2 , part1 . dim ) dtype = chaospy . poly . typing . dtyping ( part1 . dtype , part2 . dtype ) core1 = part1 . A . copy ( ) core2 = part2 . A . copy ( ) if np . prod ( part2 . shape ) > np . prod ( part1 . shape ) : shape = part2 . shape ones = np . ones ( shape , dtype = int ) for key in core1 : core1 [ key ] = core1 [ key ] * ones else : shape = part1 . shape ones = np . ones ( shape , dtype = int ) for key in core2 : core2 [ key ] = core2 [ key ] * ones for idx in core1 : if idx in core2 : core2 [ idx ] = core2 [ idx ] + core1 [ idx ] else : core2 [ idx ] = core1 [ idx ] out = core2 return Poly ( out , part1 . dim , shape , dtype ) part2 = np . asarray ( part2 ) core = part1 . A . copy ( ) dtype = chaospy . poly . typing . dtyping ( part1 . dtype , part2 . dtype ) zero = ( 0 , ) * part1 . dim if zero not in core : core [ zero ] = np . zeros ( part1 . shape , dtype = int ) core [ zero ] = core [ zero ] + part2 if np . prod ( part2 . shape ) > np . prod ( part1 . shape ) : ones = np . ones ( part2 . shape , dtype = dtype ) for key in core : core [ key ] = core [ key ] * ones return Poly ( core , part1 . dim , None , dtype ) | Polynomial addition . |
18,110 | def mul ( * args ) : if len ( args ) > 2 : return add ( args [ 0 ] , add ( args [ 1 ] , args [ 1 : ] ) ) if len ( args ) == 1 : return args [ 0 ] part1 , part2 = args if not isinstance ( part2 , Poly ) : if isinstance ( part2 , ( float , int ) ) : part2 = np . asarray ( part2 ) if not part2 . shape : core = part1 . A . copy ( ) dtype = chaospy . poly . typing . dtyping ( part1 . dtype , part2 . dtype ) for key in part1 . keys : core [ key ] = np . asarray ( core [ key ] * part2 , dtype ) return Poly ( core , part1 . dim , part1 . shape , dtype ) part2 = Poly ( part2 ) if part2 . dim > part1 . dim : part1 = chaospy . dimension . setdim ( part1 , part2 . dim ) elif part2 . dim < part1 . dim : part2 = chaospy . dimension . setdim ( part2 , part1 . dim ) if np . prod ( part1 . shape ) >= np . prod ( part2 . shape ) : shape = part1 . shape else : shape = part2 . shape dtype = chaospy . poly . typing . dtyping ( part1 . dtype , part2 . dtype ) if part1 . dtype != part2 . dtype : if part1 . dtype == dtype : part2 = chaospy . poly . typing . asfloat ( part2 ) else : part1 = chaospy . poly . typing . asfloat ( part1 ) core = { } for idx1 in part2 . A : for idx2 in part1 . A : key = tuple ( np . array ( idx1 ) + np . array ( idx2 ) ) core [ key ] = np . asarray ( core . get ( key , 0 ) + part2 . A [ idx1 ] * part1 . A [ idx2 ] ) core = { key : value for key , value in core . items ( ) if np . any ( value ) } out = Poly ( core , part1 . dim , shape , dtype ) return out | Polynomial multiplication . |
18,111 | def plot ( self , resolution_constant_regions = 20 , resolution_smooth_regions = 200 ) : if self . eps == 0 : x = [ ] y = [ ] for I , value in zip ( self . _indicator_functions , self . _values ) : x . append ( I . L ) y . append ( value ) x . append ( I . R ) y . append ( value ) return x , y else : n = float ( resolution_smooth_regions ) / self . eps if len ( self . data ) == 1 : return [ self . L , self . R ] , [ self . _values [ 0 ] , self . _values [ 0 ] ] else : x = [ np . linspace ( self . data [ 0 ] [ 0 ] , self . data [ 1 ] [ 0 ] - self . eps , resolution_constant_regions + 1 ) ] for I in self . _indicator_functions [ 1 : ] : x . append ( np . linspace ( I . L - self . eps , I . L + self . eps , resolution_smooth_regions + 1 ) ) x . append ( np . linspace ( I . L + self . eps , I . R - self . eps , resolution_constant_regions + 1 ) ) x . append ( np . linspace ( I . R - self . eps , I . R , 3 ) ) x = np . concatenate ( x ) y = self ( x ) return x , y | Return arrays x y for plotting the piecewise constant function . Just the minimum number of straight lines are returned if eps = 0 otherwise resolution_constant_regions plotting intervals are insed in the constant regions with resolution_smooth_regions plotting intervals in the smoothed regions . |
18,112 | def gradient ( poly ) : return differential ( poly , chaospy . poly . collection . basis ( 1 , 1 , poly . dim ) ) | Gradient of a polynomial . |
18,113 | def create_korobov_samples ( order , dim , base = 17797 ) : values = numpy . empty ( dim ) values [ 0 ] = 1 for idx in range ( 1 , dim ) : values [ idx ] = base * values [ idx - 1 ] % ( order + 1 ) grid = numpy . mgrid [ : dim , : order + 1 ] out = values [ grid [ 0 ] ] * ( grid [ 1 ] + 1 ) / ( order + 1. ) % 1. return out [ : , : order ] | Create Korobov lattice samples . |
18,114 | def quad_genz_keister ( order , dist , rule = 24 ) : assert isinstance ( rule , int ) if len ( dist ) > 1 : if isinstance ( order , int ) : values = [ quad_genz_keister ( order , d , rule ) for d in dist ] else : values = [ quad_genz_keister ( order [ i ] , dist [ i ] , rule ) for i in range ( len ( dist ) ) ] abscissas = [ _ [ 0 ] [ 0 ] for _ in values ] abscissas = chaospy . quad . combine ( abscissas ) . T weights = [ _ [ 1 ] for _ in values ] weights = np . prod ( chaospy . quad . combine ( weights ) , - 1 ) return abscissas , weights foo = chaospy . quad . genz_keister . COLLECTION [ rule ] abscissas , weights = foo ( order ) abscissas = dist . inv ( scipy . special . ndtr ( abscissas ) ) abscissas = abscissas . reshape ( 1 , abscissas . size ) return abscissas , weights | Genz - Keister quadrature rule . |
18,115 | def Perc ( poly , q , dist , sample = 10000 , ** kws ) : shape = poly . shape poly = polynomials . flatten ( poly ) q = numpy . array ( q ) / 100. dim = len ( dist ) Z = dist . sample ( sample , ** kws ) if dim == 1 : Z = ( Z , ) q = numpy . array ( [ q ] ) poly1 = poly ( * Z ) mi , ma = dist . range ( ) . reshape ( 2 , dim ) ext = numpy . mgrid [ ( slice ( 0 , 2 , 1 ) , ) * dim ] . reshape ( dim , 2 ** dim ) . T ext = numpy . where ( ext , mi , ma ) . T poly2 = poly ( * ext ) poly2 = numpy . array ( [ _ for _ in poly2 . T if not numpy . any ( numpy . isnan ( _ ) ) ] ) . T if poly2 . shape : poly1 = numpy . concatenate ( [ poly1 , poly2 ] , - 1 ) samples = poly1 . shape [ - 1 ] poly1 . sort ( ) out = poly1 . T [ numpy . asarray ( q * ( samples - 1 ) , dtype = int ) ] out = out . reshape ( q . shape + shape ) return out | Percentile function . |
18,116 | def probabilistic_collocation ( order , dist , subset = .1 ) : abscissas , weights = chaospy . quad . collection . golub_welsch ( order , dist ) likelihood = dist . pdf ( abscissas ) alpha = numpy . random . random ( len ( weights ) ) alpha = likelihood > alpha * subset * numpy . max ( likelihood ) abscissas = abscissas . T [ alpha ] . T weights = weights [ alpha ] return abscissas , weights | Probabilistic collocation method . |
18,117 | def get_function ( rule , domain , normalize , ** parameters ) : from . . . distributions . baseclass import Dist if isinstance ( domain , Dist ) : lower , upper = domain . range ( ) parameters [ "dist" ] = domain else : lower , upper = numpy . array ( domain ) parameters [ "lower" ] = lower parameters [ "upper" ] = upper quad_function = QUAD_FUNCTIONS [ rule ] parameters_spec = inspect . getargspec ( quad_function ) [ 0 ] parameters_spec = { key : None for key in parameters_spec } del parameters_spec [ "order" ] for key in parameters_spec : if key in parameters : parameters_spec [ key ] = parameters [ key ] def _quad_function ( order , * args , ** kws ) : params = parameters_spec . copy ( ) params . update ( kws ) abscissas , weights = quad_function ( order , * args , ** params ) if rule in UNORMALIZED_QUADRATURE_RULES and normalize : if isinstance ( domain , Dist ) : if len ( domain ) == 1 : weights *= domain . pdf ( abscissas ) . flatten ( ) else : weights *= domain . pdf ( abscissas ) weights /= numpy . sum ( weights ) return abscissas , weights return _quad_function | Create a quadrature function and set default parameter values . |
18,118 | def fit_regression ( polynomials , abscissas , evals , rule = "LS" , retall = False , order = 0 , alpha = - 1 , ) : abscissas = numpy . asarray ( abscissas ) if len ( abscissas . shape ) == 1 : abscissas = abscissas . reshape ( 1 , * abscissas . shape ) evals = numpy . array ( evals ) poly_evals = polynomials ( * abscissas ) . T shape = evals . shape [ 1 : ] evals = evals . reshape ( evals . shape [ 0 ] , int ( numpy . prod ( evals . shape [ 1 : ] ) ) ) if isinstance ( rule , str ) : rule = rule . upper ( ) if rule == "LS" : uhat = linalg . lstsq ( poly_evals , evals ) [ 0 ] elif rule == "T" : uhat = rlstsq ( poly_evals , evals , order = order , alpha = alpha , cross = False ) elif rule == "TC" : uhat = rlstsq ( poly_evals , evals , order = order , alpha = alpha , cross = True ) else : from sklearn . linear_model . base import LinearModel assert isinstance ( rule , LinearModel ) uhat = rule . fit ( poly_evals , evals ) . coef_ . T evals = evals . reshape ( evals . shape [ 0 ] , * shape ) approx_model = chaospy . poly . sum ( ( polynomials * uhat . T ) , - 1 ) approx_model = chaospy . poly . reshape ( approx_model , shape ) if retall == 1 : return approx_model , uhat elif retall == 2 : return approx_model , uhat , poly_evals return approx_model | Fit a polynomial chaos expansion using linear regression . |
18,119 | def quad_genz_keister_24 ( order ) : order = sorted ( GENZ_KEISTER_24 . keys ( ) ) [ order ] abscissas , weights = GENZ_KEISTER_24 [ order ] abscissas = numpy . array ( abscissas ) weights = numpy . array ( weights ) weights /= numpy . sum ( weights ) abscissas *= numpy . sqrt ( 2 ) return abscissas , weights | Hermite Genz - Keister 24 rule . |
18,120 | def contains_call_signature ( caller , key ) : try : args = inspect . signature ( caller ) . parameters except AttributeError : args = inspect . getargspec ( caller ) . args return key in args | Check if a function or method call signature contains a specific argument . |
18,121 | def Sens_m_sample ( poly , dist , samples , rule = "R" ) : dim = len ( dist ) generator = Saltelli ( dist , samples , poly , rule = rule ) zeros = [ 0 ] * dim ones = [ 1 ] * dim index = [ 0 ] * dim variance = numpy . var ( generator [ zeros ] , - 1 ) matrix_0 = generator [ zeros ] matrix_1 = generator [ ones ] mean = .5 * ( numpy . mean ( matrix_1 ) + numpy . mean ( matrix_0 ) ) matrix_0 -= mean matrix_1 -= mean out = [ numpy . mean ( matrix_1 * ( ( generator [ index ] - mean ) - matrix_0 ) , - 1 ) / numpy . where ( variance , variance , 1 ) for index in numpy . eye ( dim , dtype = bool ) ] return numpy . array ( out ) | First order sensitivity indices estimated using Saltelli s method . |
18,122 | def Sens_m2_sample ( poly , dist , samples , rule = "R" ) : dim = len ( dist ) generator = Saltelli ( dist , samples , poly , rule = rule ) zeros = [ 0 ] * dim ones = [ 1 ] * dim index = [ 0 ] * dim variance = numpy . var ( generator [ zeros ] , - 1 ) matrix_0 = generator [ zeros ] matrix_1 = generator [ ones ] mean = .5 * ( numpy . mean ( matrix_1 ) + numpy . mean ( matrix_0 ) ) matrix_0 -= mean matrix_1 -= mean out = numpy . empty ( ( dim , dim ) + poly . shape ) for dim1 in range ( dim ) : index [ dim1 ] = 1 matrix = generator [ index ] - mean out [ dim1 , dim1 ] = numpy . mean ( matrix_1 * ( matrix - matrix_0 ) , - 1 , ) / numpy . where ( variance , variance , 1 ) for dim2 in range ( dim1 + 1 , dim ) : index [ dim2 ] = 1 matrix = generator [ index ] - mean out [ dim1 , dim2 ] = out [ dim2 , dim1 ] = numpy . mean ( matrix_1 * ( matrix - matrix_0 ) , - 1 , ) / numpy . where ( variance , variance , 1 ) index [ dim2 ] = 0 index [ dim1 ] = 0 return out | Second order sensitivity indices estimated using Saltelli s method . |
18,123 | def Sens_t_sample ( poly , dist , samples , rule = "R" ) : generator = Saltelli ( dist , samples , poly , rule = rule ) dim = len ( dist ) zeros = [ 0 ] * dim variance = numpy . var ( generator [ zeros ] , - 1 ) return numpy . array ( [ 1 - numpy . mean ( ( generator [ ~ index ] - generator [ zeros ] ) ** 2 , - 1 , ) / ( 2 * numpy . where ( variance , variance , 1 ) ) for index in numpy . eye ( dim , dtype = bool ) ] ) | Total order sensitivity indices estimated using Saltelli s method . |
18,124 | def get_matrix ( self , indices ) : new = numpy . empty ( self . samples1 . shape ) for idx in range ( len ( indices ) ) : if indices [ idx ] : new [ idx ] = self . samples1 [ idx ] else : new [ idx ] = self . samples2 [ idx ] if self . poly : new = self . poly ( * new ) return new | Retrieve Saltelli matrix . |
18,125 | def generate_stieltjes ( dist , order , accuracy = 100 , normed = False , retall = False , ** kws ) : from . . import distributions assert not distributions . evaluation . get_dependencies ( dist ) if len ( dist ) > 1 : orth , norms , coeff1 , coeff2 = zip ( * [ generate_stieltjes ( _ , order , accuracy , normed , retall = True , ** kws ) for _ in dist ] ) orth = [ [ chaospy . setdim ( _ , len ( orth ) ) for _ in poly ] for poly in orth ] orth = [ [ chaospy . rolldim ( _ , len ( dist ) - idx ) for _ in poly ] for idx , poly in enumerate ( orth ) ] orth = [ chaospy . poly . base . Poly ( _ ) for _ in zip ( * orth ) ] if not retall : return orth norms = numpy . vstack ( norms ) coeff1 = numpy . vstack ( coeff1 ) coeff2 = numpy . vstack ( coeff2 ) return orth , norms , coeff1 , coeff2 try : orth , norms , coeff1 , coeff2 = _stieltjes_analytical ( dist , order , normed ) except NotImplementedError : orth , norms , coeff1 , coeff2 = _stieltjes_approx ( dist , order , accuracy , normed , ** kws ) if retall : assert not numpy . any ( numpy . isnan ( coeff1 ) ) assert not numpy . any ( numpy . isnan ( coeff2 ) ) return orth , norms , coeff1 , coeff2 return orth | Discretized Stieltjes method . |
18,126 | def _stieltjes_analytical ( dist , order , normed ) : dimensions = len ( dist ) mom_order = numpy . arange ( order + 1 ) . repeat ( dimensions ) mom_order = mom_order . reshape ( order + 1 , dimensions ) . T coeff1 , coeff2 = dist . ttr ( mom_order ) coeff2 [ : , 0 ] = 1. poly = chaospy . poly . collection . core . variable ( dimensions ) if normed : orth = [ poly ** 0 * numpy . ones ( dimensions ) , ( poly - coeff1 [ : , 0 ] ) / numpy . sqrt ( coeff2 [ : , 1 ] ) , ] for order_ in range ( 1 , order ) : orth . append ( ( orth [ - 1 ] * ( poly - coeff1 [ : , order_ ] ) - orth [ - 2 ] * numpy . sqrt ( coeff2 [ : , order_ ] ) ) / numpy . sqrt ( coeff2 [ : , order_ + 1 ] ) ) norms = numpy . ones ( coeff2 . shape ) else : orth = [ poly - poly , poly ** 0 * numpy . ones ( dimensions ) ] for order_ in range ( order ) : orth . append ( orth [ - 1 ] * ( poly - coeff1 [ : , order_ ] ) - orth [ - 2 ] * coeff2 [ : , order_ ] ) orth = orth [ 1 : ] norms = numpy . cumprod ( coeff2 , 1 ) return orth , norms , coeff1 , coeff2 | Stieltjes method with analytical recurrence coefficients . |
18,127 | def _stieltjes_approx ( dist , order , accuracy , normed , ** kws ) : kws [ "rule" ] = kws . get ( "rule" , "C" ) assert kws [ "rule" ] . upper ( ) != "G" absisas , weights = chaospy . quad . generate_quadrature ( accuracy , dist . range ( ) , ** kws ) weights = weights * dist . pdf ( absisas ) poly = chaospy . poly . variable ( len ( dist ) ) orth = [ poly * 0 , poly ** 0 ] inner = numpy . sum ( absisas * weights , - 1 ) norms = [ numpy . ones ( len ( dist ) ) , numpy . ones ( len ( dist ) ) ] coeff1 = [ ] coeff2 = [ ] for _ in range ( order ) : coeff1 . append ( inner / norms [ - 1 ] ) coeff2 . append ( norms [ - 1 ] / norms [ - 2 ] ) orth . append ( ( poly - coeff1 [ - 1 ] ) * orth [ - 1 ] - orth [ - 2 ] * coeff2 [ - 1 ] ) raw_nodes = orth [ - 1 ] ( * absisas ) ** 2 * weights inner = numpy . sum ( absisas * raw_nodes , - 1 ) norms . append ( numpy . sum ( raw_nodes , - 1 ) ) if normed : orth [ - 1 ] = orth [ - 1 ] / numpy . sqrt ( norms [ - 1 ] ) coeff1 . append ( inner / norms [ - 1 ] ) coeff2 . append ( norms [ - 1 ] / norms [ - 2 ] ) coeff1 = numpy . transpose ( coeff1 ) coeff2 = numpy . transpose ( coeff2 ) norms = numpy . array ( norms [ 1 : ] ) . T orth = orth [ 1 : ] return orth , norms , coeff1 , coeff2 | Stieltjes method with approximative recurrence coefficients . |
18,128 | def set_state ( seed_value = None , step = None ) : global RANDOM_SEED if seed_value is not None : RANDOM_SEED = seed_value if step is not None : RANDOM_SEED += step | Set random seed . |
18,129 | def rule_generator ( * funcs ) : dim = len ( funcs ) tensprod_rule = create_tensorprod_function ( funcs ) assert hasattr ( tensprod_rule , "__call__" ) mv_rule = create_mv_rule ( tensprod_rule , dim ) assert hasattr ( mv_rule , "__call__" ) return mv_rule | Constructor for creating multivariate quadrature generator . |
18,130 | def create_tensorprod_function ( funcs ) : dim = len ( funcs ) def tensprod_rule ( order , part = None ) : order = order * numpy . ones ( dim , int ) values = [ funcs [ idx ] ( order [ idx ] ) for idx in range ( dim ) ] abscissas = [ numpy . array ( _ [ 0 ] ) . flatten ( ) for _ in values ] abscissas = chaospy . quad . combine ( abscissas , part = part ) . T weights = [ numpy . array ( _ [ 1 ] ) . flatten ( ) for _ in values ] weights = numpy . prod ( chaospy . quad . combine ( weights , part = part ) , - 1 ) return abscissas , weights return tensprod_rule | Combine 1 - D rules into multivariate rule using tensor product . |
18,131 | def create_mv_rule ( tensorprod_rule , dim ) : def mv_rule ( order , sparse = False , part = None ) : if sparse : order = numpy . ones ( dim , dtype = int ) * order tensorprod_rule_ = lambda order , part = part : tensorprod_rule ( order , part = part ) return chaospy . quad . sparse_grid ( tensorprod_rule_ , order ) return tensorprod_rule ( order , part = part ) return mv_rule | Convert tensor product rule into a multivariate quadrature generator . |
18,132 | def quad_fejer ( order , lower = 0 , upper = 1 , growth = False , part = None ) : order = numpy . asarray ( order , dtype = int ) . flatten ( ) lower = numpy . asarray ( lower ) . flatten ( ) upper = numpy . asarray ( upper ) . flatten ( ) dim = max ( lower . size , upper . size , order . size ) order = numpy . ones ( dim , dtype = int ) * order lower = numpy . ones ( dim ) * lower upper = numpy . ones ( dim ) * upper composite = numpy . array ( [ numpy . arange ( 2 ) ] * dim ) if growth : results = [ _fejer ( numpy . where ( order [ i ] == 0 , 0 , 2. ** ( order [ i ] + 1 ) - 2 ) ) for i in range ( dim ) ] else : results = [ _fejer ( order [ i ] , composite [ i ] ) for i in range ( dim ) ] abscis = [ _ [ 0 ] for _ in results ] weight = [ _ [ 1 ] for _ in results ] abscis = chaospy . quad . combine ( abscis , part = part ) . T weight = chaospy . quad . combine ( weight , part = part ) abscis = ( ( upper - lower ) * abscis . T + lower ) . T weight = numpy . prod ( weight * ( upper - lower ) , - 1 ) assert len ( abscis ) == dim assert len ( weight ) == len ( abscis . T ) return abscis , weight | Generate the quadrature abscissas and weights in Fejer quadrature . |
18,133 | def _fejer ( order , composite = None ) : r order = int ( order ) if order == 0 : return numpy . array ( [ .5 ] ) , numpy . array ( [ 1. ] ) order += 2 theta = ( order - numpy . arange ( order + 1 ) ) * numpy . pi / order abscisas = 0.5 * numpy . cos ( theta ) + 0.5 N , K = numpy . mgrid [ : order + 1 , : order // 2 ] weights = 2 * numpy . cos ( 2 * ( K + 1 ) * theta [ N ] ) / ( 4 * K * ( K + 2 ) + 3 ) if order % 2 == 0 : weights [ : , - 1 ] *= 0.5 weights = ( 1 - numpy . sum ( weights , - 1 ) ) / order return abscisas [ 1 : - 1 ] , weights [ 1 : - 1 ] | r Backend method . |
18,134 | def create_latin_hypercube_samples ( order , dim = 1 ) : randoms = numpy . random . random ( order * dim ) . reshape ( ( dim , order ) ) for dim_ in range ( dim ) : perm = numpy . random . permutation ( order ) randoms [ dim_ ] = ( perm + randoms [ dim_ ] ) / order return randoms | Latin Hypercube sampling . |
18,135 | def create_hammersley_samples ( order , dim = 1 , burnin = - 1 , primes = ( ) ) : if dim == 1 : return create_halton_samples ( order = order , dim = 1 , burnin = burnin , primes = primes ) out = numpy . empty ( ( dim , order ) , dtype = float ) out [ : dim - 1 ] = create_halton_samples ( order = order , dim = dim - 1 , burnin = burnin , primes = primes ) out [ dim - 1 ] = numpy . linspace ( 0 , 1 , order + 2 ) [ 1 : - 1 ] return out | Create samples from the Hammersley set . |
18,136 | def create_primes ( threshold ) : if threshold == 2 : return [ 2 ] elif threshold < 2 : return [ ] numbers = list ( range ( 3 , threshold + 1 , 2 ) ) root_of_threshold = threshold ** 0.5 half = int ( ( threshold + 1 ) / 2 - 1 ) idx = 0 counter = 3 while counter <= root_of_threshold : if numbers [ idx ] : idy = int ( ( counter * counter - 3 ) / 2 ) numbers [ idy ] = 0 while idy < half : numbers [ idy ] = 0 idy += counter idx += 1 counter = 2 * idx + 3 return [ 2 ] + [ number for number in numbers if number ] | Generate prime values using sieve of Eratosthenes method . |
18,137 | def evaluate_inverse ( distribution , u_data , cache = None , parameters = None ) : if cache is None : cache = { } out = numpy . zeros ( u_data . shape ) if hasattr ( distribution , "_ppf" ) : parameters = load_parameters ( distribution , "_ppf" , parameters = parameters , cache = cache ) out [ : ] = distribution . _ppf ( u_data . copy ( ) , ** parameters ) else : from . . import approximation parameters = load_parameters ( distribution , "_cdf" , parameters = parameters , cache = cache ) out [ : ] = approximation . approximate_inverse ( distribution , u_data . copy ( ) , cache = cache . copy ( ) , parameters = parameters ) cache [ distribution ] = out return out | Evaluate inverse Rosenblatt transformation . |
18,138 | def mom_recurse ( self , idxi , idxj , idxk ) : rank_ = min ( chaospy . bertran . rank ( idxi , self . dim ) , chaospy . bertran . rank ( idxj , self . dim ) , chaospy . bertran . rank ( idxk , self . dim ) ) par , axis0 = chaospy . bertran . parent ( idxk , self . dim ) gpar , _ = chaospy . bertran . parent ( par , self . dim , axis0 ) idxi_child = chaospy . bertran . child ( idxi , self . dim , axis0 ) oneup = chaospy . bertran . child ( 0 , self . dim , axis0 ) out1 = self . mom_111 ( idxi_child , idxj , par ) out2 = self . mom_111 ( chaospy . bertran . child ( oneup , self . dim , axis0 ) , par , par ) for k in range ( gpar , idxk ) : if chaospy . bertran . rank ( k , self . dim ) >= rank_ : out1 -= self . mom_111 ( oneup , k , par ) * self . mom_111 ( idxi , idxj , k ) out2 -= self . mom_111 ( oneup , par , k ) * self ( oneup , k , par ) return out1 / out2 | Backend mement main loop . |
18,139 | def Sens_m_nataf ( order , dist , samples , vals , ** kws ) : assert dist . __class__ . __name__ == "Copula" trans = dist . prm [ "trans" ] assert trans . __class__ . __name__ == "nataf" vals = numpy . array ( vals ) cov = trans . prm [ "C" ] cov = numpy . dot ( cov , cov . T ) marginal = dist . prm [ "dist" ] dim = len ( dist ) orth = chaospy . orthogonal . orth_ttr ( order , marginal , sort = "GR" ) r = range ( dim ) index = [ 1 ] + [ 0 ] * ( dim - 1 ) nataf = chaospy . dist . Nataf ( marginal , cov , r ) samples_ = marginal . inv ( nataf . fwd ( samples ) ) poly , coeffs = chaospy . collocation . fit_regression ( orth , samples_ , vals , retall = 1 ) V = Var ( poly , marginal , ** kws ) out = numpy . zeros ( ( dim , ) + poly . shape ) out [ 0 ] = Var ( E_cond ( poly , index , marginal , ** kws ) , marginal , ** kws ) / ( V + ( V == 0 ) ) * ( V != 0 ) for i in range ( 1 , dim ) : r = r [ 1 : ] + r [ : 1 ] index = index [ - 1 : ] + index [ : - 1 ] nataf = chaospy . dist . Nataf ( marginal , cov , r ) samples_ = marginal . inv ( nataf . fwd ( samples ) ) poly , coeffs = chaospy . collocation . fit_regression ( orth , samples_ , vals , retall = 1 ) out [ i ] = Var ( E_cond ( poly , index , marginal , ** kws ) , marginal , ** kws ) / ( V + ( V == 0 ) ) * ( V != 0 ) return out | Variance - based decomposition through the Nataf distribution . |
18,140 | def quad_golub_welsch ( order , dist , accuracy = 100 , ** kws ) : order = numpy . array ( order ) * numpy . ones ( len ( dist ) , dtype = int ) + 1 _ , _ , coeff1 , coeff2 = chaospy . quad . generate_stieltjes ( dist , numpy . max ( order ) , accuracy = accuracy , retall = True , ** kws ) dimensions = len ( dist ) abscisas , weights = _golbub_welsch ( order , coeff1 , coeff2 ) if dimensions == 1 : abscisa = numpy . reshape ( abscisas , ( 1 , order [ 0 ] ) ) weight = numpy . reshape ( weights , ( order [ 0 ] , ) ) else : abscisa = chaospy . quad . combine ( abscisas ) . T weight = numpy . prod ( chaospy . quad . combine ( weights ) , - 1 ) assert len ( abscisa ) == dimensions assert len ( weight ) == len ( abscisa . T ) return abscisa , weight | Golub - Welsch algorithm for creating quadrature nodes and weights . |
18,141 | def _golbub_welsch ( orders , coeff1 , coeff2 ) : abscisas , weights = [ ] , [ ] for dim , order in enumerate ( orders ) : if order : bands = numpy . zeros ( ( 2 , order ) ) bands [ 0 ] = coeff1 [ dim , : order ] bands [ 1 , : - 1 ] = numpy . sqrt ( coeff2 [ dim , 1 : order ] ) vals , vecs = scipy . linalg . eig_banded ( bands , lower = True ) abscisa , weight = vals . real , vecs [ 0 , : ] ** 2 indices = numpy . argsort ( abscisa ) abscisa , weight = abscisa [ indices ] , weight [ indices ] else : abscisa , weight = numpy . array ( [ coeff1 [ dim , 0 ] ] ) , numpy . array ( [ 1. ] ) abscisas . append ( abscisa ) weights . append ( weight ) return abscisas , weights | Recurrence coefficients to abscisas and weights . |
18,142 | def Kurt ( poly , dist = None , fisher = True , ** kws ) : if isinstance ( poly , distributions . Dist ) : x = polynomials . variable ( len ( poly ) ) poly , dist = x , poly else : poly = polynomials . Poly ( poly ) if fisher : adjust = 3 else : adjust = 0 shape = poly . shape poly = polynomials . flatten ( poly ) m1 = E ( poly , dist ) m2 = E ( poly ** 2 , dist ) m3 = E ( poly ** 3 , dist ) m4 = E ( poly ** 4 , dist ) out = ( m4 - 4 * m3 * m1 + 6 * m2 * m1 ** 2 - 3 * m1 ** 4 ) / ( m2 ** 2 - 2 * m2 * m1 ** 2 + m1 ** 4 ) - adjust out = numpy . reshape ( out , shape ) return out | Kurtosis operator . |
18,143 | def basis ( start , stop = None , dim = 1 , sort = "G" , cross_truncation = 1. ) : if stop is None : start , stop = numpy . array ( 0 ) , start start = numpy . array ( start , dtype = int ) stop = numpy . array ( stop , dtype = int ) dim = max ( start . size , stop . size , dim ) indices = numpy . array ( chaospy . bertran . bindex ( numpy . min ( start ) , 2 * numpy . max ( stop ) , dim , sort , cross_truncation ) ) if start . size == 1 : bellow = numpy . sum ( indices , - 1 ) >= start else : start = numpy . ones ( dim , dtype = int ) * start bellow = numpy . all ( indices - start >= 0 , - 1 ) if stop . size == 1 : above = numpy . sum ( indices , - 1 ) <= stop . item ( ) else : stop = numpy . ones ( dim , dtype = int ) * stop above = numpy . all ( stop - indices >= 0 , - 1 ) pool = list ( indices [ above * bellow ] ) arg = numpy . zeros ( len ( pool ) , dtype = int ) arg [ 0 ] = 1 poly = { } for idx in pool : idx = tuple ( idx ) poly [ idx ] = arg arg = numpy . roll ( arg , 1 ) x = numpy . zeros ( len ( pool ) , dtype = int ) x [ 0 ] = 1 A = { } for I in pool : I = tuple ( I ) A [ I ] = x x = numpy . roll ( x , 1 ) return Poly ( A , dim ) | Create an N - dimensional unit polynomial basis . |
18,144 | def cutoff ( poly , * args ) : if len ( args ) == 1 : low , high = 0 , args [ 0 ] else : low , high = args [ : 2 ] core_old = poly . A core_new = { } for key in poly . keys : if low <= numpy . sum ( key ) < high : core_new [ key ] = core_old [ key ] return Poly ( core_new , poly . dim , poly . shape , poly . dtype ) | Remove polynomial components with order outside a given interval . |
18,145 | def prange ( N = 1 , dim = 1 ) : A = { } r = numpy . arange ( N , dtype = int ) key = numpy . zeros ( dim , dtype = int ) for i in range ( N ) : key [ - 1 ] = i A [ tuple ( key ) ] = 1 * ( r == i ) return Poly ( A , dim , ( N , ) , int ) | Constructor to create a range of polynomials where the exponent vary . |
18,146 | def rolldim ( P , n = 1 ) : dim = P . dim shape = P . shape dtype = P . dtype A = dict ( ( ( key [ n : ] + key [ : n ] , P . A [ key ] ) for key in P . keys ) ) return Poly ( A , dim , shape , dtype ) | Roll the axes . |
18,147 | def swapdim ( P , dim1 = 1 , dim2 = 0 ) : if not isinstance ( P , Poly ) : return numpy . swapaxes ( P , dim1 , dim2 ) dim = P . dim shape = P . shape dtype = P . dtype if dim1 == dim2 : return P m = max ( dim1 , dim2 ) if P . dim <= m : P = chaospy . poly . dimension . setdim ( P , m + 1 ) dim = m + 1 A = { } for key in P . keys : val = P . A [ key ] key = list ( key ) key [ dim1 ] , key [ dim2 ] = key [ dim2 ] , key [ dim1 ] A [ tuple ( key ) ] = val return Poly ( A , dim , shape , dtype ) | Swap the dim between two variables . |
18,148 | def tril ( P , k = 0 ) : A = P . A . copy ( ) for key in P . keys : A [ key ] = numpy . tril ( P . A [ key ] ) return Poly ( A , dim = P . dim , shape = P . shape ) | Lower triangle of coefficients . |
18,149 | def tricu ( P , k = 0 ) : tri = numpy . sum ( numpy . mgrid [ [ slice ( 0 , _ , 1 ) for _ in P . shape ] ] , 0 ) tri = tri < len ( tri ) + k if isinstance ( P , Poly ) : A = P . A . copy ( ) B = { } for key in P . keys : B [ key ] = A [ key ] * tri return Poly ( B , shape = P . shape , dim = P . dim , dtype = P . dtype ) out = P * tri return out | Cross - diagonal upper triangle . |
18,150 | def variable ( dims = 1 ) : if dims == 1 : return Poly ( { ( 1 , ) : 1 } , dim = 1 , shape = ( ) ) return Poly ( { tuple ( indices ) : indices for indices in numpy . eye ( dims , dtype = int ) } , dim = dims , shape = ( dims , ) ) | Simple constructor to create single variables to create polynomials . |
18,151 | def all ( A , ax = None ) : if isinstance ( A , Poly ) : out = numpy . zeros ( A . shape , dtype = bool ) B = A . A for key in A . keys : out += all ( B [ key ] , ax ) return out return numpy . all ( A , ax ) | Test if all values in A evaluate to True |
18,152 | def around ( A , decimals = 0 ) : if isinstance ( A , Poly ) : B = A . A . copy ( ) for key in A . keys : B [ key ] = around ( B [ key ] , decimals ) return Poly ( B , A . dim , A . shape , A . dtype ) return numpy . around ( A , decimals ) | Evenly round to the given number of decimals . |
18,153 | def diag ( A , k = 0 ) : if isinstance ( A , Poly ) : core , core_new = A . A , { } for key in A . keys : core_new [ key ] = numpy . diag ( core [ key ] , k ) return Poly ( core_new , A . dim , None , A . dtype ) return numpy . diag ( A , k ) | Extract or construct a diagonal polynomial array . |
18,154 | def prune ( A , threshold ) : if isinstance ( A , Poly ) : B = A . A . copy ( ) for key in A . keys : values = B [ key ] . copy ( ) values [ numpy . abs ( values ) < threshold ] = 0. B [ key ] = values return Poly ( B , A . dim , A . shape , A . dtype ) A = A . copy ( ) A [ numpy . abs ( A ) < threshold ] = 0. return A | Remove coefficients that is not larger than a given threshold . |
18,155 | def _range ( self , xloc , cache ) : uloc = numpy . zeros ( ( 2 , len ( self ) ) ) for dist in evaluation . sorted_dependencies ( self , reverse = True ) : if dist not in self . inverse_map : continue idx = self . inverse_map [ dist ] xloc_ = xloc [ idx ] . reshape ( 1 , - 1 ) uloc [ : , idx ] = evaluation . evaluate_bound ( dist , xloc_ , cache = cache ) . flatten ( ) return uloc | Special handle for finding bounds on constrained dists . |
18,156 | def Spearman ( poly , dist , sample = 10000 , retall = False , ** kws ) : samples = dist . sample ( sample , ** kws ) poly = polynomials . flatten ( poly ) Y = poly ( * samples ) if retall : return spearmanr ( Y . T ) return spearmanr ( Y . T ) [ 0 ] | Calculate Spearman s rank - order correlation coefficient . |
18,157 | def _diff ( self , x , th , eps ) : foo = lambda y : self . igen ( numpy . sum ( self . gen ( y , th ) , 0 ) , th ) out1 = out2 = 0. sign = 1 - 2 * ( x > .5 ) . T for I in numpy . ndindex ( * ( ( 2 , ) * ( len ( x ) - 1 ) + ( 1 , ) ) ) : eps_ = numpy . array ( I ) * eps x_ = ( x . T + sign * eps_ ) . T out1 += ( - 1 ) ** sum ( I ) * foo ( x_ ) x_ [ - 1 ] = 1 out2 += ( - 1 ) ** sum ( I ) * foo ( x_ ) out = out1 / out2 return out | Differentiation function . |
18,158 | def available_services ( ) : all_datas = ( ) data = ( ) for class_path in settings . TH_SERVICES : class_name = class_path . rsplit ( '.' , 1 ) [ 1 ] data = ( class_name , class_name . rsplit ( 'Service' , 1 ) [ 1 ] ) all_datas = ( data , ) + all_datas return all_datas | get the available services to be activated |
18,159 | def handle ( self , * args , ** options ) : trigger_id = options . get ( 'trigger_id' ) trigger = TriggerService . objects . filter ( id = int ( trigger_id ) , status = True , user__is_active = True , provider_failed__lt = settings . DJANGO_TH . get ( 'failed_tries' , 10 ) , consumer_failed__lt = settings . DJANGO_TH . get ( 'failed_tries' , 10 ) ) . select_related ( 'consumer__name' , 'provider__name' ) try : with Pool ( processes = 1 ) as pool : r = Read ( ) result = pool . map_async ( r . reading , trigger ) result . get ( timeout = 360 ) p = Pub ( ) result = pool . map_async ( p . publishing , trigger ) result . get ( timeout = 360 ) cache . delete ( 'django_th' + '_fire_trigger_' + str ( trigger_id ) ) except TimeoutError as e : logger . warning ( e ) | get the trigger to fire |
18,160 | def read_data ( self , ** kwargs ) : trigger_id = kwargs . get ( 'trigger_id' ) trigger = Pushbullet . objects . get ( trigger_id = trigger_id ) date_triggered = kwargs . get ( 'date_triggered' ) data = list ( ) pushes = self . pushb . get_pushes ( ) for p in pushes : title = 'From Pushbullet' created = arrow . get ( p . get ( 'created' ) ) if created > date_triggered and p . get ( 'type' ) == trigger . type and ( p . get ( 'sender_email' ) == p . get ( 'receiver_email' ) or p . get ( 'sender_email' ) is None ) : title = title + ' Channel' if p . get ( 'channel_iden' ) and p . get ( 'title' ) is None else title body = p . get ( 'body' ) data . append ( { 'title' : title , 'content' : body } ) self . send_digest_event ( trigger_id , title , '' ) cache . set ( 'th_pushbullet_' + str ( trigger_id ) , data ) return data | get the data from the service as the pushbullet service does not have any date in its API linked to the note add the triggered date to the dict data thus the service will be triggered when data will be found |
18,161 | def html_entity_decode_char ( self , m , defs = htmlentities . entitydefs ) : try : char = defs [ m . group ( 1 ) ] return "&{char};" . format ( char = char ) except ValueError : return m . group ( 0 ) except KeyError : return m . group ( 0 ) | decode html entity into one of the html char |
18,162 | def html_entity_decode_codepoint ( self , m , defs = htmlentities . codepoint2name ) : try : char = defs [ m . group ( 1 ) ] return "&{char};" . format ( char = char ) except ValueError : return m . group ( 0 ) except KeyError : return m . group ( 0 ) | decode html entity into one of the codepoint2name |
18,163 | def html_entity_decode ( self ) : pattern = re . compile ( r"&#(\w+?);" ) string = pattern . sub ( self . html_entity_decode_char , self . my_string ) return pattern . sub ( self . html_entity_decode_codepoint , string ) | entry point of this set of tools to decode html entities |
18,164 | def read_data ( self , ** kwargs ) : trigger_id = kwargs . get ( 'trigger_id' ) date_triggered = kwargs . get ( 'date_triggered' ) data = list ( ) since = arrow . get ( date_triggered ) . timestamp if self . token is not None : pockets = self . pocket . get ( since = since , state = "unread" ) content = '' if pockets is not None and len ( pockets [ 0 ] [ 'list' ] ) > 0 : for my_pocket in pockets [ 0 ] [ 'list' ] . values ( ) : if my_pocket . get ( 'excerpt' ) : content = my_pocket [ 'excerpt' ] elif my_pocket . get ( 'given_title' ) : content = my_pocket [ 'given_title' ] my_date = arrow . get ( str ( date_triggered ) , 'YYYY-MM-DD HH:mm:ss' ) . to ( settings . TIME_ZONE ) data . append ( { 'my_date' : str ( my_date ) , 'tag' : '' , 'link' : my_pocket [ 'given_url' ] , 'title' : my_pocket [ 'given_title' ] , 'content' : content , 'tweet_id' : 0 } ) self . send_digest_event ( trigger_id , my_pocket [ 'given_title' ] , my_pocket [ 'given_url' ] ) cache . set ( 'th_pocket_' + str ( trigger_id ) , data ) return data | get the data from the service As the pocket service does not have any date in its API linked to the note add the triggered date to the dict data thus the service will be triggered when data will be found |
18,165 | def remove_prohibited_element ( tag_name , document_element ) : elements = document_element . getElementsByTagName ( tag_name ) for element in elements : p = element . parentNode p . removeChild ( element ) | To fit the Evernote DTD need drop this tag name |
18,166 | def _get_content ( data , which_content ) : content = '' if data . get ( which_content ) : if isinstance ( data . get ( which_content ) , feedparser . FeedParserDict ) : content = data . get ( which_content ) [ 'value' ] elif not isinstance ( data . get ( which_content ) , str ) : if 'value' in data . get ( which_content ) [ 0 ] : content = data . get ( which_content ) [ 0 ] . value else : content = data . get ( which_content ) return content | get the content that could be hidden in the middle of content or summary detail from the data of the provider |
18,167 | def get_request_token ( self , request ) : if self . oauth == 'oauth1' : oauth = OAuth1Session ( self . consumer_key , client_secret = self . consumer_secret ) request_token = oauth . fetch_request_token ( self . REQ_TOKEN ) request . session [ 'oauth_token' ] = request_token [ 'oauth_token' ] request . session [ 'oauth_token_secret' ] = request_token [ 'oauth_token_secret' ] return request_token else : callback_url = self . callback_url ( request ) oauth = OAuth2Session ( client_id = self . consumer_key , redirect_uri = callback_url , scope = self . scope ) authorization_url , state = oauth . authorization_url ( self . AUTH_URL ) return authorization_url | request the token to the external service |
18,168 | def save_data ( self , trigger_id , ** data ) : title , content = super ( ServiceEvernote , self ) . save_data ( trigger_id , ** data ) trigger = Evernote . objects . get ( trigger_id = trigger_id ) note_store = self . _notestore ( trigger_id , data ) if isinstance ( note_store , evernote . api . client . Store ) : note = self . _notebook ( trigger , note_store ) note = self . _attributes ( note , data ) content = self . _footer ( trigger , data , content ) note . title = limit_content ( title , 255 ) note = self . _content ( note , content ) return EvernoteMgr . create_note ( note_store , note , trigger_id , data ) else : return note_store | let s save the data don t want to handle empty title nor content otherwise this will produce an Exception by the Evernote s API |
18,169 | def get_evernote_client ( self , token = None ) : if token : return EvernoteClient ( token = token , sandbox = self . sandbox ) else : return EvernoteClient ( consumer_key = self . consumer_key , consumer_secret = self . consumer_secret , sandbox = self . sandbox ) | get the token from evernote |
18,170 | def auth ( self , request ) : client = self . get_evernote_client ( ) request_token = client . get_request_token ( self . callback_url ( request ) ) request . session [ 'oauth_token' ] = request_token [ 'oauth_token' ] request . session [ 'oauth_token_secret' ] = request_token [ 'oauth_token_secret' ] return client . get_authorize_url ( request_token ) | let s auth the user to the Service |
18,171 | def get_context_data ( self , ** kwargs ) : triggers_enabled = triggers_disabled = services_activated = ( ) context = super ( TriggerListView , self ) . get_context_data ( ** kwargs ) if self . kwargs . get ( 'trigger_filtered_by' ) : page_link = reverse ( 'trigger_filter_by' , kwargs = { 'trigger_filtered_by' : self . kwargs . get ( 'trigger_filtered_by' ) } ) elif self . kwargs . get ( 'trigger_ordered_by' ) : page_link = reverse ( 'trigger_order_by' , kwargs = { 'trigger_ordered_by' : self . kwargs . get ( 'trigger_ordered_by' ) } ) else : page_link = reverse ( 'home' ) if self . request . user . is_authenticated : triggers_enabled = TriggerService . objects . filter ( user = self . request . user , status = 1 ) . count ( ) triggers_disabled = TriggerService . objects . filter ( user = self . request . user , status = 0 ) . count ( ) user_service = UserService . objects . filter ( user = self . request . user ) context [ 'trigger_filter_by' ] = user_service services_activated = user_service . count ( ) context [ 'nb_triggers' ] = { 'enabled' : triggers_enabled , 'disabled' : triggers_disabled } context [ 'nb_services' ] = services_activated context [ 'page_link' ] = page_link context [ 'fire' ] = settings . DJANGO_TH . get ( 'fire' , False ) return context | get the data of the view |
18,172 | def datas ( self ) : data = feedparser . parse ( self . URL_TO_PARSE , agent = self . USER_AGENT ) if data . bozo == 1 : data . entries = '' return data | read the data from a given URL or path to a local file |
18,173 | def finalcallback ( request , ** kwargs ) : default_provider . load_services ( ) service_name = kwargs . get ( 'service_name' ) service_object = default_provider . get_service ( service_name ) lets_callback = getattr ( service_object , 'callback' ) return render_to_response ( lets_callback ( request ) ) | let s do the callback of the related service after the auth request from UserServiceCreateView |
18,174 | def filter_that ( self , criteria , data ) : import re prog = re . compile ( criteria ) return True if prog . match ( data ) else False | this method just use the module re to check if the data contain the string to find |
18,175 | def load_services ( self , services = settings . TH_SERVICES ) : kwargs = { } for class_path in services : module_name , class_name = class_path . rsplit ( '.' , 1 ) klass = import_from_path ( class_path ) service = klass ( None , ** kwargs ) self . register ( class_name , service ) | get the service from the settings |
18,176 | def recycle ( ) : for service in cache . iter_keys ( 'th_*' ) : try : service_value = cache . get ( service , version = 2 ) cache . set ( service , service_value ) cache . delete_pattern ( service , version = 2 ) except ValueError : pass logger . info ( 'recycle of cache done!' ) | the purpose of this tasks is to recycle the data from the cache with version = 2 in the main cache |
18,177 | def handle ( self , * args , ** options ) : now = arrow . utcnow ( ) . to ( settings . TIME_ZONE ) now = now . date ( ) digest = Digest . objects . filter ( date_end = str ( now ) ) . order_by ( 'user' , 'date_end' ) users = digest . distinct ( 'user' ) subject = 'Your digester' msg_plain = render_to_string ( 'digest/email.txt' , { 'digest' : digest , 'subject' : subject } ) msg_html = render_to_string ( 'digest/email.html' , { 'digest' : digest , 'subject' : subject } ) message = msg_plain from_email = settings . ADMINS recipient_list = ( ) for user in users : recipient_list += ( user . user . email , ) send_mail ( subject , message , from_email , recipient_list , html_message = msg_html ) | get all the digest data to send to each user |
18,178 | def get_notebook ( note_store , my_notebook ) : notebook_id = 0 notebooks = note_store . listNotebooks ( ) for notebook in notebooks : if notebook . name . lower ( ) == my_notebook . lower ( ) : notebook_id = notebook . guid break return notebook_id | get the notebook from its name |
18,179 | def set_notebook ( note_store , my_notebook , notebook_id ) : if notebook_id == 0 : new_notebook = Types . Notebook ( ) new_notebook . name = my_notebook new_notebook . defaultNotebook = False notebook_id = note_store . createNotebook ( new_notebook ) . guid return notebook_id | create a notebook |
18,180 | def set_note_attribute ( data ) : na = False if data . get ( 'link' ) : na = Types . NoteAttributes ( ) na . sourceURL = data . get ( 'link' ) return na | add the link of the source in the note |
18,181 | def is_primitive ( val ) : return isinstance ( val , ( str , bool , float , complex , bytes , six . text_type ) + six . string_types + six . integer_types ) | Checks if the passed value is a primitive type . |
18,182 | def split_every ( parts , iterable ) : return takewhile ( bool , ( list ( islice ( iterable , parts ) ) for _ in count ( ) ) ) | Split an iterable into parts of length parts |
18,183 | def compute_partition_size ( result , processes ) : try : return max ( math . ceil ( len ( result ) / processes ) , 1 ) except TypeError : return 1 | Attempts to compute the partition size to evenly distribute work across processes . Defaults to 1 if the length of result cannot be determined . |
18,184 | def evaluate ( self , sequence ) : last_cache_index = self . cache_scan ( ) transformations = self . transformations [ last_cache_index : ] return self . engine . evaluate ( sequence , transformations ) | Compute the lineage on the sequence . |
18,185 | def _wrap ( value ) : if is_primitive ( value ) : return value if isinstance ( value , ( dict , set ) ) or is_namedtuple ( value ) : return value elif isinstance ( value , collections . Iterable ) : try : if type ( value ) . __name__ == 'DataFrame' : import pandas if isinstance ( value , pandas . DataFrame ) : return Sequence ( value . values ) except ImportError : pass return Sequence ( value ) else : return value | Wraps the passed value in a Sequence if it is not a primitive . If it is a string argument it is expanded to a list of characters . |
18,186 | def cartesian ( self , * iterables , ** kwargs ) : return self . _transform ( transformations . cartesian_t ( iterables , kwargs . get ( 'repeat' , 1 ) ) ) | Returns the cartesian product of the passed iterables with the specified number of repetitions . |
18,187 | def drop ( self , n ) : if n <= 0 : return self . _transform ( transformations . drop_t ( 0 ) ) else : return self . _transform ( transformations . drop_t ( n ) ) | Drop the first n elements of the sequence . |
18,188 | def drop_right ( self , n ) : return self . _transform ( transformations . CACHE_T , transformations . drop_right_t ( n ) ) | Drops the last n elements of the sequence . |
18,189 | def take ( self , n ) : if n <= 0 : return self . _transform ( transformations . take_t ( 0 ) ) else : return self . _transform ( transformations . take_t ( n ) ) | Take the first n elements of the sequence . |
18,190 | def count ( self , func ) : n = 0 for element in self : if func ( element ) : n += 1 return n | Counts the number of elements in the sequence which satisfy the predicate func . |
18,191 | def reduce ( self , func , * initial ) : if len ( initial ) == 0 : return _wrap ( reduce ( func , self ) ) elif len ( initial ) == 1 : return _wrap ( reduce ( func , self , initial [ 0 ] ) ) else : raise ValueError ( 'reduce takes exactly one optional parameter for initial value' ) | Reduce sequence of elements using func . API mirrors functools . reduce |
18,192 | def product ( self , projection = None ) : if self . empty ( ) : if projection : return projection ( 1 ) else : return 1 if self . size ( ) == 1 : if projection : return projection ( self . first ( ) ) else : return self . first ( ) if projection : return self . map ( projection ) . reduce ( mul ) else : return self . reduce ( mul ) | Takes product of elements in sequence . |
18,193 | def sum ( self , projection = None ) : if projection : return sum ( self . map ( projection ) ) else : return sum ( self ) | Takes sum of elements in sequence . |
18,194 | def average ( self , projection = None ) : length = self . size ( ) if projection : return sum ( self . map ( projection ) ) / length else : return sum ( self ) / length | Takes the average of elements in the sequence |
18,195 | def sliding ( self , size , step = 1 ) : return self . _transform ( transformations . sliding_t ( _wrap , size , step ) ) | Groups elements in fixed size blocks by passing a sliding window over them . |
18,196 | def sorted ( self , key = None , reverse = False ) : return self . _transform ( transformations . sorted_t ( key = key , reverse = reverse ) ) | Uses python sort and its passed arguments to sort the input . |
18,197 | def slice ( self , start , until ) : return self . _transform ( transformations . slice_t ( start , until ) ) | Takes a slice of the sequence starting at start and until but not including until . |
18,198 | def to_list ( self , n = None ) : if n is None : self . cache ( ) return self . _base_sequence else : return self . cache ( ) . take ( n ) . list ( ) | Converts sequence to list of elements . |
18,199 | def to_jsonl ( self , path , mode = 'wb' , compression = None ) : with universal_write_open ( path , mode = mode , compression = compression ) as output : output . write ( ( self . map ( json . dumps ) . make_string ( '\n' ) + '\n' ) . encode ( 'utf-8' ) ) | Saves the sequence to a jsonl file . Each element is mapped using json . dumps then written with a newline separating each element . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.