idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
18,000
def persist ( self , path_to_file ) : with open ( path_to_file , 'wb' ) as f : f . write ( self . data )
Saves the image to disk on a file
18,001
def load ( cls , path_to_file ) : import mimetypes mimetypes . init ( ) mime = mimetypes . guess_type ( 'file://%s' % path_to_file ) [ 0 ] img_type = ImageTypeEnum . lookup_by_mime_type ( mime ) with open ( path_to_file , 'rb' ) as f : data = f . read ( ) return Image ( data , image_type = img_type )
Loads the image data from a file on disk and tries to guess the image MIME type
18,002
def timeformat ( timeobject , timeformat ) : if timeformat == "unix" : return to_UNIXtime ( timeobject ) elif timeformat == "iso" : return to_ISO8601 ( timeobject ) elif timeformat == "date" : return to_date ( timeobject ) else : raise ValueError ( "Invalid value for timeformat parameter" )
Formats the specified time object to the target format type .
18,003
def temperature_series ( self , unit = 'kelvin' ) : if unit not in ( 'kelvin' , 'celsius' , 'fahrenheit' ) : raise ValueError ( "Invalid value for parameter 'unit'" ) result = [ ] for tstamp in self . _station_history . get_measurements ( ) : t = self . _station_history . get_measurements ( ) [ tstamp ] [ 'temperature'...
Returns the temperature time series relative to the meteostation in the form of a list of tuples each one containing the couple timestamp - value
18,004
def humidity_series ( self ) : return [ ( tstamp , self . _station_history . get_measurements ( ) [ tstamp ] [ 'humidity' ] ) for tstamp in self . _station_history . get_measurements ( ) ]
Returns the humidity time series relative to the meteostation in the form of a list of tuples each one containing the couple timestamp - value
18,005
def pressure_series ( self ) : return [ ( tstamp , self . _station_history . get_measurements ( ) [ tstamp ] [ 'pressure' ] ) for tstamp in self . _station_history . get_measurements ( ) ]
Returns the atmospheric pressure time series relative to the meteostation in the form of a list of tuples each one containing the couple timestamp - value
18,006
def rain_series ( self ) : return [ ( tstamp , self . _station_history . get_measurements ( ) [ tstamp ] [ 'rain' ] ) for tstamp in self . _station_history . get_measurements ( ) ]
Returns the precipitation time series relative to the meteostation in the form of a list of tuples each one containing the couple timestamp - value
18,007
def wind_series ( self ) : return [ ( timestamp , self . _station_history . get_measurements ( ) [ timestamp ] [ 'wind' ] ) for timestamp in self . _station_history . get_measurements ( ) ]
Returns the wind speed time series relative to the meteostation in the form of a list of tuples each one containing the couple timestamp - value
18,008
def max_rain ( self ) : return max ( self . _purge_none_samples ( self . rain_series ( ) ) , key = lambda item : item [ 1 ] )
Returns a tuple containing the max value in the rain series preceeded by its timestamp
18,009
def get_uvi ( self , params_dict ) : lat = str ( params_dict [ 'lat' ] ) lon = str ( params_dict [ 'lon' ] ) params = dict ( lat = lat , lon = lon ) uri = http_client . HttpClient . to_url ( UV_INDEX_URL , self . _API_key , None ) _ , json_data = self . _client . cacheable_get_json ( uri , params = params ) return json...
Invokes the UV Index endpoint
18,010
def get_uvi_history ( self , params_dict ) : lat = str ( params_dict [ 'lat' ] ) lon = str ( params_dict [ 'lon' ] ) start = str ( params_dict [ 'start' ] ) end = str ( params_dict [ 'end' ] ) params = dict ( lat = lat , lon = lon , start = start , end = end ) uri = http_client . HttpClient . to_url ( UV_INDEX_HISTORY_...
Invokes the UV Index History endpoint
18,011
def call ( poly , args ) : args = list ( args ) if len ( args ) < poly . dim : args = args + [ np . nan ] * ( poly . dim - len ( args ) ) elif len ( args ) > poly . dim : raise ValueError ( "too many arguments" ) x0 , x1 = [ ] , [ ] for idx , arg in enumerate ( args ) : if isinstance ( arg , Poly ) : poly_ = Poly ( { t...
Evaluate a polynomial along specified axes .
18,012
def substitute ( P , x0 , x1 , V = 0 ) : x0 , x1 = map ( Poly , [ x0 , x1 ] ) dim = np . max ( [ p . dim for p in [ P , x0 , x1 ] ] ) dtype = chaospy . poly . typing . dtyping ( P . dtype , x0 . dtype , x1 . dtype ) P , x0 , x1 = [ chaospy . poly . dimension . setdim ( p , dim ) for p in [ P , x0 , x1 ] ] if x0 . shape...
Substitute a variable in a polynomial array .
18,013
def decompose ( P ) : P = P . copy ( ) if not P : return P out = [ Poly ( { key : P . A [ key ] } ) for key in P . keys ] return Poly ( out , None , None , None )
Decompose a polynomial to component form .
18,014
def evaluate_moment ( distribution , k_data , parameters = None , cache = None , ) : logger = logging . getLogger ( __name__ ) assert len ( k_data ) == len ( distribution ) , ( "distribution %s is not of length %d" % ( distribution , len ( k_data ) ) ) assert len ( k_data . shape ) == 1 if numpy . all ( k_data == 0 ) :...
Evaluate raw statistical moments .
18,015
def mul ( left , right ) : from . mv_mul import MvMul length = max ( left , right ) if length == 1 : return Mul ( left , right ) return MvMul ( left , right )
Distribution multiplication .
18,016
def sorted_dependencies ( dist , reverse = False ) : from . . import baseclass collection = [ dist ] nodes = [ dist ] edges = [ ] pool = [ dist ] while pool : dist = pool . pop ( ) for key in sorted ( dist . prm ) : value = dist . prm [ key ] if not isinstance ( value , baseclass . Dist ) : continue if ( dist , value )...
Extract all underlying dependencies from a distribution sorted topologically .
18,017
def get_dependencies ( * distributions ) : from . . import baseclass distributions = [ sorted_dependencies ( dist ) for dist in distributions if isinstance ( dist , baseclass . Dist ) ] dependencies = list ( ) for idx , dist1 in enumerate ( distributions ) : for dist2 in distributions [ idx + 1 : ] : dependencies . ext...
Get underlying dependencies that are shared between distributions .
18,018
def orth_ttr ( order , dist , normed = False , sort = "GR" , retall = False , cross_truncation = 1. , ** kws ) : polynomials , norms , _ , _ = chaospy . quad . generate_stieltjes ( dist = dist , order = numpy . max ( order ) , retall = True , ** kws ) if normed : for idx , poly in enumerate ( polynomials ) : polynomial...
Create orthogonal polynomial expansion from three terms recursion formula .
18,019
def quad_genz_keister_22 ( order ) : order = sorted ( GENZ_KEISTER_22 . keys ( ) ) [ order ] abscissas , weights = GENZ_KEISTER_22 [ order ] abscissas = numpy . array ( abscissas ) weights = numpy . array ( weights ) weights /= numpy . sum ( weights ) abscissas *= numpy . sqrt ( 2 ) return abscissas , weights
Hermite Genz - Keister 22 rule .
18,020
def identify_core ( core ) : for datatype , identifier in { int : _identify_scaler , numpy . int8 : _identify_scaler , numpy . int16 : _identify_scaler , numpy . int32 : _identify_scaler , numpy . int64 : _identify_scaler , float : _identify_scaler , numpy . float16 : _identify_scaler , numpy . float32 : _identify_scal...
Identify the polynomial argument .
18,021
def _identify_poly ( core ) : return core . A , core . dim , core . shape , core . dtype
Specification for a polynomial .
18,022
def _identify_dict ( core ) : if not core : return { } , 1 , ( ) , int core = core . copy ( ) key = sorted ( core . keys ( ) , key = chaospy . poly . base . sort_key ) [ 0 ] shape = numpy . array ( core [ key ] ) . shape dtype = numpy . array ( core [ key ] ) . dtype dim = len ( key ) return core , dim , shape , dtype
Specification for a dictionary .
18,023
def _identify_iterable ( core ) : if isinstance ( core , numpy . ndarray ) and not core . shape : return { ( 0 , ) : core } , 1 , ( ) , core . dtype core = [ chaospy . poly . base . Poly ( a ) for a in core ] shape = ( len ( core ) , ) + core [ 0 ] . shape dtype = chaospy . poly . typing . dtyping ( * [ _ . dtype for _...
Specification for a list tuple numpy . ndarray .
18,024
def Corr ( poly , dist = None , ** kws ) : if isinstance ( poly , distributions . Dist ) : poly , dist = polynomials . variable ( len ( poly ) ) , poly else : poly = polynomials . Poly ( poly ) cov = Cov ( poly , dist , ** kws ) var = numpy . diag ( cov ) vvar = numpy . sqrt ( numpy . outer ( var , var ) ) return numpy...
Correlation matrix of a distribution or polynomial .
18,025
def tri_ttr ( k , a ) : from . . . quad import quad_clenshaw_curtis q1 , w1 = quad_clenshaw_curtis ( int ( 10 ** 3 * a ) , 0 , a ) q2 , w2 = quad_clenshaw_curtis ( int ( 10 ** 3 * ( 1 - a ) ) , a , 1 ) q = numpy . concatenate ( [ q1 , q2 ] , 1 ) w = numpy . concatenate ( [ w1 , w2 ] ) w = w * numpy . where ( q < a , 2 ...
Custom TTR function .
18,026
def Skew ( poly , dist = None , ** kws ) : if isinstance ( poly , distributions . Dist ) : x = polynomials . variable ( len ( poly ) ) poly , dist = x , poly else : poly = polynomials . Poly ( poly ) if poly . dim < len ( dist ) : polynomials . setdim ( poly , len ( dist ) ) shape = poly . shape poly = polynomials . fl...
Skewness operator .
18,027
def evaluate_forward ( distribution , x_data , parameters = None , cache = None , ) : assert len ( x_data ) == len ( distribution ) , ( "distribution %s is not of length %d" % ( distribution , len ( x_data ) ) ) assert hasattr ( distribution , "_cdf" ) , ( "distribution require the `_cdf` method to function." ) cache =...
Evaluate forward Rosenblatt transformation .
18,028
def Var ( poly , dist = None , ** kws ) : if isinstance ( poly , distributions . Dist ) : x = polynomials . variable ( len ( poly ) ) poly , dist = x , poly else : poly = polynomials . Poly ( poly ) dim = len ( dist ) if poly . dim < dim : polynomials . setdim ( poly , dim ) shape = poly . shape poly = polynomials . fl...
Element by element 2nd order statistics .
18,029
def E ( poly , dist = None , ** kws ) : if not isinstance ( poly , ( distributions . Dist , polynomials . Poly ) ) : print ( type ( poly ) ) print ( "Approximating expected value..." ) out = quadrature . quad ( poly , dist , veceval = True , ** kws ) print ( "done" ) return out if isinstance ( poly , distributions . Di...
Expected value operator .
18,030
def create_chebyshev_samples ( order , dim = 1 ) : x_data = .5 * numpy . cos ( numpy . arange ( order , 0 , - 1 ) * numpy . pi / ( order + 1 ) ) + .5 x_data = chaospy . quad . combine ( [ x_data ] * dim ) return x_data . T
Chebyshev sampling function .
18,031
def orth_chol ( order , dist , normed = True , sort = "GR" , cross_truncation = 1. , ** kws ) : dim = len ( dist ) basis = chaospy . poly . basis ( start = 1 , stop = order , dim = dim , sort = sort , cross_truncation = cross_truncation , ) length = len ( basis ) cholmat = chaospy . chol . gill_king ( chaospy . descrip...
Create orthogonal polynomial expansion from Cholesky decomposition .
18,032
def setdim ( P , dim = None ) : P = P . copy ( ) ldim = P . dim if not dim : dim = ldim + 1 if dim == ldim : return P P . dim = dim if dim > ldim : key = numpy . zeros ( dim , dtype = int ) for lkey in P . keys : key [ : ldim ] = lkey P . A [ tuple ( key ) ] = P . A . pop ( lkey ) else : key = numpy . zeros ( dim , dty...
Adjust the dimensions of a polynomial .
18,033
def gill_murray_wright ( mat , eps = 1e-16 ) : mat = numpy . asfarray ( mat ) size = mat . shape [ 0 ] gamma = 0.0 xi_ = 0.0 for idy in range ( size ) : gamma = max ( abs ( mat [ idy , idy ] ) , gamma ) for idx in range ( idy + 1 , size ) : xi_ = max ( abs ( mat [ idy , idx ] ) , xi_ ) delta = eps * max ( gamma + xi_ ,...
Gill - Murray - Wright algorithm for pivoting modified Cholesky decomposition .
18,034
def swap_across ( idx , idy , mat_a , mat_r , perm ) : size = mat_a . shape [ 0 ] perm_new = numpy . eye ( size , dtype = int ) perm_row = 1.0 * perm [ : , idx ] perm [ : , idx ] = perm [ : , idy ] perm [ : , idy ] = perm_row row_p = 1.0 * perm_new [ idx ] perm_new [ idx ] = perm_new [ idy ] perm_new [ idy ] = row_p ma...
Interchange row and column idy and idx .
18,035
def create_halton_samples ( order , dim = 1 , burnin = - 1 , primes = ( ) ) : primes = list ( primes ) if not primes : prime_order = 10 * dim while len ( primes ) < dim : primes = create_primes ( prime_order ) prime_order *= 2 primes = primes [ : dim ] assert len ( primes ) == dim , "not enough primes" if burnin < 0 : ...
Create Halton sequence .
18,036
def range ( self , x_data = None ) : if x_data is None : try : x_data = evaluation . evaluate_inverse ( self , numpy . array ( [ [ 0.5 ] ] * len ( self ) ) ) except StochasticallyDependentError : x_data = approximation . find_interior_point ( self ) shape = ( len ( self ) , ) if hasattr ( self , "_range" ) : return sel...
Generate the upper and lower bounds of a distribution .
18,037
def fwd ( self , x_data ) : x_data = numpy . asfarray ( x_data ) shape = x_data . shape x_data = x_data . reshape ( len ( self ) , - 1 ) lower , upper = evaluation . evaluate_bound ( self , x_data ) q_data = numpy . zeros ( x_data . shape ) indices = x_data > upper q_data [ indices ] = 1 indices = ~ indices & ( x_data ...
Forward Rosenblatt transformation .
18,038
def inv ( self , q_data , max_iterations = 100 , tollerance = 1e-5 ) : q_data = numpy . asfarray ( q_data ) assert numpy . all ( ( q_data >= 0 ) & ( q_data <= 1 ) ) , "sanitize your inputs!" shape = q_data . shape q_data = q_data . reshape ( len ( self ) , - 1 ) x_data = evaluation . evaluate_inverse ( self , q_data ) ...
Inverse Rosenblatt transformation .
18,039
def sample ( self , size = ( ) , rule = "R" , antithetic = None ) : size_ = numpy . prod ( size , dtype = int ) dim = len ( self ) if dim > 1 : if isinstance ( size , ( tuple , list , numpy . ndarray ) ) : shape = ( dim , ) + tuple ( size ) else : shape = ( dim , size ) else : shape = size from . import sampler out = s...
Create pseudo - random generated samples .
18,040
def mom ( self , K , ** kws ) : K = numpy . asarray ( K , dtype = int ) shape = K . shape dim = len ( self ) if dim > 1 : shape = shape [ 1 : ] size = int ( K . size / dim ) K = K . reshape ( dim , size ) cache = { } out = [ evaluation . evaluate_moment ( self , kdata , cache ) for kdata in K . T ] out = numpy . array ...
Raw statistical moments .
18,041
def ttr ( self , kloc , acc = 10 ** 3 , verbose = 1 ) : kloc = numpy . asarray ( kloc , dtype = int ) shape = kloc . shape kloc = kloc . reshape ( len ( self ) , - 1 ) cache = { } out = [ evaluation . evaluate_recurrence_coefficients ( self , k ) for k in kloc . T ] out = numpy . array ( out ) . T return out . reshape ...
Three terms relation s coefficient generator
18,042
def Acf ( poly , dist , N = None , ** kws ) : if N is None : N = len ( poly ) / 2 + 1 corr = Corr ( poly , dist , ** kws ) out = numpy . empty ( N ) for n in range ( N ) : out [ n ] = numpy . mean ( corr . diagonal ( n ) , 0 ) return out
Auto - correlation function .
18,043
def plot_figures ( ) : rc ( "figure" , figsize = [ 8. , 4. ] ) rc ( "figure.subplot" , left = .08 , top = .95 , right = .98 ) rc ( "image" , cmap = "gray" ) seed ( 1000 ) Q1 = cp . Gamma ( 2 ) Q2 = cp . Normal ( 0 , Q1 ) Q = cp . J ( Q1 , Q2 ) subplot ( 121 ) s , t = meshgrid ( linspace ( 0 , 5 , 200 ) , linspace ( - 6...
Plot figures for multivariate distribution section .
18,044
def flatten ( vari ) : if isinstance ( vari , Poly ) : shape = int ( numpy . prod ( vari . shape ) ) return reshape ( vari , ( shape , ) ) return numpy . array ( vari ) . flatten ( )
Flatten a shapeable quantity .
18,045
def reshape ( vari , shape ) : if isinstance ( vari , Poly ) : core = vari . A . copy ( ) for key in vari . keys : core [ key ] = reshape ( core [ key ] , shape ) out = Poly ( core , vari . dim , shape , vari . dtype ) return out return numpy . asarray ( vari ) . reshape ( shape )
Reshape the shape of a shapeable quantity .
18,046
def rollaxis ( vari , axis , start = 0 ) : if isinstance ( vari , Poly ) : core_old = vari . A . copy ( ) core_new = { } for key in vari . keys : core_new [ key ] = rollaxis ( core_old [ key ] , axis , start ) return Poly ( core_new , vari . dim , None , vari . dtype ) return numpy . rollaxis ( vari , axis , start )
Roll the specified axis backwards until it lies in a given position .
18,047
def swapaxes ( vari , ax1 , ax2 ) : if isinstance ( vari , Poly ) : core = vari . A . copy ( ) for key in vari . keys : core [ key ] = swapaxes ( core [ key ] , ax1 , ax2 ) return Poly ( core , vari . dim , None , vari . dtype ) return numpy . swapaxes ( vari , ax1 , ax2 )
Interchange two axes of a polynomial .
18,048
def roll ( vari , shift , axis = None ) : if isinstance ( vari , Poly ) : core = vari . A . copy ( ) for key in vari . keys : core [ key ] = roll ( core [ key ] , shift , axis ) return Poly ( core , vari . dim , None , vari . dtype ) return numpy . roll ( vari , shift , axis )
Roll array elements along a given axis .
18,049
def transpose ( vari ) : if isinstance ( vari , Poly ) : core = vari . A . copy ( ) for key in vari . keys : core [ key ] = transpose ( core [ key ] ) return Poly ( core , vari . dim , vari . shape [ : : - 1 ] , vari . dtype ) return numpy . transpose ( vari )
Transpose a shapeable quantety .
18,050
def create_antithetic_variates ( samples , axes = ( ) ) : samples = numpy . asfarray ( samples ) assert numpy . all ( samples <= 1 ) and numpy . all ( samples >= 0 ) , ( "all samples assumed on interval [0, 1]." ) if len ( samples . shape ) == 1 : samples = samples . reshape ( 1 , - 1 ) inverse_samples = 1 - samples di...
Generate antithetic variables .
18,051
def preprocess ( core , dim , shape , dtype ) : core , dim_ , shape_ , dtype_ = chaospy . poly . constructor . identify_core ( core ) core , shape = chaospy . poly . constructor . ensure_shape ( core , shape , shape_ ) core , dtype = chaospy . poly . constructor . ensure_dtype ( core , dtype , dtype_ ) core , dim = cha...
Constructor function for the Poly class .
18,052
def combine ( args , part = None ) : args = [ cleanup ( arg ) for arg in args ] if part is not None : parts , orders = part if numpy . array ( orders ) . size == 1 : orders = [ int ( numpy . array ( orders ) . item ( ) ) ] * len ( args ) parts = numpy . array ( parts ) . flatten ( ) for i , arg in enumerate ( args ) : ...
All linear combination of a list of list .
18,053
def cleanup ( arg ) : arg = numpy . asarray ( arg ) if len ( arg . shape ) <= 1 : arg = arg . reshape ( arg . size , 1 ) elif len ( arg . shape ) > 2 : raise ValueError ( "shapes must be smaller than 3" ) return arg
Clean up the input variable .
18,054
def create_grid_samples ( order , dim = 1 ) : x_data = numpy . arange ( 1 , order + 1 ) / ( order + 1. ) x_data = chaospy . quad . combine ( [ x_data ] * dim ) return x_data . T
Create samples from a regular grid .
18,055
def add ( idxi , idxj , dim ) : idxm = numpy . array ( multi_index ( idxi , dim ) ) idxn = numpy . array ( multi_index ( idxj , dim ) ) out = single_index ( idxm + idxn ) return out
Bertran addition .
18,056
def terms ( order , dim ) : return int ( scipy . special . comb ( order + dim , dim , 1 ) )
Count the number of polynomials in an expansion .
18,057
def multi_index ( idx , dim ) : def _rec ( idx , dim ) : idxn = idxm = 0 if not dim : return ( ) if idx == 0 : return ( 0 , ) * dim while terms ( idxn , dim ) <= idx : idxn += 1 idx -= terms ( idxn - 1 , dim ) if idx == 0 : return ( idxn , ) + ( 0 , ) * ( dim - 1 ) while terms ( idxm , dim - 1 ) <= idx : idxm += 1 retu...
Single to multi - index using graded reverse lexicographical notation .
18,058
def bindex ( start , stop = None , dim = 1 , sort = "G" , cross_truncation = 1. ) : if stop is None : start , stop = 0 , start start = numpy . array ( start , dtype = int ) . flatten ( ) stop = numpy . array ( stop , dtype = int ) . flatten ( ) sort = sort . upper ( ) total = numpy . mgrid [ ( slice ( numpy . max ( sto...
Generator for creating multi - indices .
18,059
def single_index ( idxm ) : if - 1 in idxm : return 0 order = int ( sum ( idxm ) ) dim = len ( idxm ) if order == 0 : return 0 return terms ( order - 1 , dim ) + single_index ( idxm [ 1 : ] )
Multi - index to single integer notation .
18,060
def rank ( idx , dim ) : idxm = multi_index ( idx , dim ) out = 0 while idxm [ - 1 : ] == ( 0 , ) : out += 1 idxm = idxm [ : - 1 ] return out
Calculate the index rank according to Bertran s notation .
18,061
def parent ( idx , dim , axis = None ) : idxm = multi_index ( idx , dim ) if axis is None : axis = dim - numpy . argmin ( 1 * ( numpy . array ( idxm ) [ : : - 1 ] == 0 ) ) - 1 if not idx : return idx , axis if idxm [ axis ] == 0 : idxi = parent ( parent ( idx , dim ) [ 0 ] , dim ) [ 0 ] while child ( idxi + 1 , dim , a...
Parent node according to Bertran s notation .
18,062
def child ( idx , dim , axis ) : idxm = multi_index ( idx , dim ) out = numpy . array ( idxm ) + 1 * ( numpy . eye ( len ( idxm ) ) [ axis ] ) return single_index ( out )
Child node according to Bertran s notation .
18,063
def ensure_shape ( core , shape , shape_ ) : core = core . copy ( ) if shape is None : shape = shape_ elif isinstance ( shape , int ) : shape = ( shape , ) if tuple ( shape ) == tuple ( shape_ ) : return core , shape ones = np . ones ( shape , dtype = int ) for key , val in core . items ( ) : core [ key ] = val * ones ...
Ensure shape is correct .
18,064
def ensure_dtype ( core , dtype , dtype_ ) : core = core . copy ( ) if dtype is None : dtype = dtype_ if dtype_ == dtype : return core , dtype for key , val in { int : chaospy . poly . typing . asint , float : chaospy . poly . typing . asfloat , np . float32 : chaospy . poly . typing . asfloat , np . float64 : chaospy ...
Ensure dtype is correct .
18,065
def ensure_dim ( core , dim , dim_ ) : if dim is None : dim = dim_ if not dim : return core , 1 if dim_ == dim : return core , int ( dim ) if dim > dim_ : key_convert = lambda vari : vari [ : dim_ ] else : key_convert = lambda vari : vari + ( 0 , ) * ( dim - dim_ ) new_core = { } for key , val in core . items ( ) : key...
Ensure that dim is correct .
18,066
def sort_key ( val ) : return numpy . sum ( ( max ( val ) + 1 ) ** numpy . arange ( len ( val ) - 1 , - 1 , - 1 ) * val )
Sort key for sorting keys in grevlex order .
18,067
def copy ( self ) : return Poly ( self . A . copy ( ) , self . dim , self . shape , self . dtype )
Return a copy of the polynomial .
18,068
def coefficients ( self ) : out = numpy . array ( [ self . A [ key ] for key in self . keys ] ) out = numpy . rollaxis ( out , - 1 ) return out
Polynomial coefficients .
18,069
def QoI_Dist ( poly , dist , sample = 10000 , ** kws ) : shape = poly . shape poly = polynomials . flatten ( poly ) dim = len ( dist ) samples = dist . sample ( sample , ** kws ) qoi_dists = [ ] for i in range ( 0 , len ( poly ) ) : if dim == 1 : dataset = poly [ i ] ( samples ) else : dataset = poly [ i ] ( * samples ...
Constructs distributions for the quantity of interests .
18,070
def quad_gauss_legendre ( order , lower = 0 , upper = 1 , composite = 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...
Generate the quadrature nodes and weights in Gauss - Legendre quadrature .
18,071
def _gauss_legendre ( order , composite = 1 ) : inner = numpy . ones ( order + 1 ) * 0.5 outer = numpy . arange ( order + 1 ) ** 2 outer = outer / ( 16 * outer - 4. ) banded = numpy . diag ( numpy . sqrt ( outer [ 1 : ] ) , k = - 1 ) + numpy . diag ( inner ) + numpy . diag ( numpy . sqrt ( outer [ 1 : ] ) , k = 1 ) val...
Backend function .
18,072
def quad_gauss_patterson ( order , dist ) : if len ( dist ) > 1 : if isinstance ( order , int ) : values = [ quad_gauss_patterson ( order , d ) for d in dist ] else : values = [ quad_gauss_patterson ( order [ i ] , dist [ i ] ) for i in range ( len ( dist ) ) ] abscissas = [ _ [ 0 ] [ 0 ] for _ in values ] weights = [ ...
Generate sets abscissas and weights for Gauss - Patterson quadrature .
18,073
def generate_quadrature ( order , domain , accuracy = 100 , sparse = False , rule = "C" , composite = 1 , growth = None , part = None , normalize = False , ** kws ) : from . . distributions . baseclass import Dist isdist = isinstance ( domain , Dist ) if isdist : dim = len ( domain ) else : dim = np . array ( domain [ ...
Numerical quadrature node and weight generator .
18,074
def deprecation_warning ( func , name ) : @ wraps ( func ) def caller ( * args , ** kwargs ) : logger = logging . getLogger ( __name__ ) instance = func ( * args , ** kwargs ) logger . warning ( "Distribution `chaospy.{}` has been renamed to " . format ( name ) + "`chaospy.{}` and will be deprecated next release." . fo...
Add a deprecation warning do each distribution .
18,075
def E_cond ( poly , freeze , dist , ** kws ) : if poly . dim < len ( dist ) : poly = polynomials . setdim ( poly , len ( dist ) ) freeze = polynomials . Poly ( freeze ) freeze = polynomials . setdim ( freeze , len ( dist ) ) keys = freeze . keys if len ( keys ) == 1 and keys [ 0 ] == ( 0 , ) * len ( dist ) : freeze = l...
Conditional expected value operator .
18,076
def generate_samples ( order , domain = 1 , rule = "R" , antithetic = None ) : logger = logging . getLogger ( __name__ ) logger . debug ( "generating random samples using rule %s" , rule ) rule = rule . upper ( ) if isinstance ( domain , int ) : dim = domain trans = lambda x_data : x_data elif isinstance ( domain , ( t...
Sample generator .
18,077
def sparse_segment ( cords ) : r cords = np . array ( cords ) + 1 slices = [ ] for cord in cords : slices . append ( slice ( 1 , 2 ** cord + 1 , 2 ) ) grid = np . mgrid [ slices ] indices = grid . reshape ( len ( cords ) , np . prod ( grid . shape [ 1 : ] ) ) . T sgrid = indices * 2. ** - cords return sgrid
r Create a segment of a sparse grid .
18,078
def lagrange_polynomial ( abscissas , sort = "GR" ) : abscissas = numpy . asfarray ( abscissas ) if len ( abscissas . shape ) == 1 : abscissas = abscissas . reshape ( 1 , abscissas . size ) dim , size = abscissas . shape order = 1 while chaospy . bertran . terms ( order , dim ) <= size : order += 1 indices = numpy . ar...
Create Lagrange polynomials .
18,079
def SampleDist ( samples , lo = None , up = None ) : samples = numpy . asarray ( samples ) if lo is None : lo = samples . min ( ) if up is None : up = samples . max ( ) try : dist = sample_dist ( samples , lo , up ) except numpy . linalg . LinAlgError : dist = Uniform ( lower = - numpy . inf , upper = numpy . inf ) ret...
Distribution based on samples .
18,080
def bastos_ohagen ( mat , eps = 1e-16 ) : mat_ref = numpy . asfarray ( mat ) mat = mat_ref . copy ( ) diag_max = numpy . diag ( mat ) . max ( ) assert len ( mat . shape ) == 2 size = len ( mat ) hitri = numpy . zeros ( ( size , size ) ) piv = numpy . arange ( size ) for idx in range ( size ) : idx_max = numpy . argmax ...
Bastos - O Hagen algorithm for modified Cholesky decomposition .
18,081
def Sens_t ( poly , dist , ** kws ) : dim = len ( dist ) if poly . dim < dim : poly = chaospy . poly . setdim ( poly , len ( dist ) ) zero = [ 1 ] * dim out = numpy . zeros ( ( dim , ) + poly . shape , dtype = float ) V = Var ( poly , dist , ** kws ) for i in range ( dim ) : zero [ i ] = 0 out [ i ] = ( ( V - Var ( E_c...
Variance - based decomposition AKA Sobol indices
18,082
def construct ( parent = None , defaults = None , ** kwargs ) : for key in kwargs : assert key in LEGAL_ATTRS , "{} is not legal input" . format ( key ) if parent is not None : for key , value in LEGAL_ATTRS . items ( ) : if key not in kwargs and hasattr ( parent , value ) : kwargs [ key ] = getattr ( parent , value ) ...
Random variable constructor .
18,083
def fit_quadrature ( orth , nodes , weights , solves , retall = False , norms = None , ** kws ) : orth = chaospy . poly . Poly ( orth ) nodes = numpy . asfarray ( nodes ) weights = numpy . asfarray ( weights ) if callable ( solves ) : solves = [ solves ( node ) for node in nodes . T ] solves = numpy . asfarray ( solves...
Using spectral projection to create a polynomial approximation over distribution space .
18,084
def sparse_grid ( func , order , dim = None , skew = None ) : if not isinstance ( order , int ) : orders = numpy . array ( order ) . flatten ( ) dim = orders . size m_order = int ( numpy . min ( orders ) ) skew = [ order - m_order for order in orders ] return sparse_grid ( func , m_order , dim , skew ) abscissas , weig...
Smolyak sparse grid constructor .
18,085
def evaluate_bound ( distribution , x_data , parameters = None , cache = None , ) : assert len ( x_data ) == len ( distribution ) assert len ( x_data . shape ) == 2 cache = cache if cache is not None else { } parameters = load_parameters ( distribution , "_bnd" , parameters = parameters , cache = cache ) out = numpy . ...
Evaluate lower and upper bounds .
18,086
def inner ( * args ) : haspoly = sum ( [ isinstance ( arg , Poly ) for arg in args ] ) if not haspoly : return numpy . sum ( numpy . prod ( args , 0 ) , 0 ) out = args [ 0 ] for arg in args [ 1 : ] : out = out * arg return sum ( out )
Inner product of a polynomial set .
18,087
def outer ( * args ) : if len ( args ) > 2 : part1 = args [ 0 ] part2 = outer ( * args [ 1 : ] ) elif len ( args ) == 2 : part1 , part2 = args else : return args [ 0 ] dtype = chaospy . poly . typing . dtyping ( part1 , part2 ) if dtype in ( list , tuple , numpy . ndarray ) : part1 = numpy . array ( part1 ) part2 = num...
Polynomial outer product .
18,088
def dot ( poly1 , poly2 ) : if not isinstance ( poly1 , Poly ) and not isinstance ( poly2 , Poly ) : return numpy . dot ( poly1 , poly2 ) poly1 = Poly ( poly1 ) poly2 = Poly ( poly2 ) poly = poly1 * poly2 if numpy . prod ( poly1 . shape ) <= 1 or numpy . prod ( poly2 . shape ) <= 1 : return poly return chaospy . poly ....
Dot product of polynomial vectors .
18,089
def quad_genz_keister_16 ( order ) : order = sorted ( GENZ_KEISTER_16 . keys ( ) ) [ order ] abscissas , weights = GENZ_KEISTER_16 [ order ] abscissas = numpy . array ( abscissas ) weights = numpy . array ( weights ) weights /= numpy . sum ( weights ) abscissas *= numpy . sqrt ( 2 ) return abscissas , weights
Hermite Genz - Keister 16 rule .
18,090
def orth_gs ( order , dist , normed = False , sort = "GR" , cross_truncation = 1. , ** kws ) : logger = logging . getLogger ( __name__ ) dim = len ( dist ) if isinstance ( order , int ) : if order == 0 : return chaospy . poly . Poly ( 1 , dim = dim ) basis = chaospy . poly . basis ( 0 , order , dim , sort , cross_trunc...
Gram - Schmidt process for generating orthogonal polynomials .
18,091
def load_parameters ( distribution , method_name , parameters = None , cache = None , cache_key = lambda x : x , ) : from . . import baseclass if cache is None : cache = { } if parameters is None : parameters = { } parameters_ = distribution . prm . copy ( ) parameters_ . update ( ** parameters ) parameters = parameter...
Load parameter values by filling them in from cache .
18,092
def quad_genz_keister_18 ( order ) : order = sorted ( GENZ_KEISTER_18 . keys ( ) ) [ order ] abscissas , weights = GENZ_KEISTER_18 [ order ] abscissas = numpy . array ( abscissas ) weights = numpy . array ( weights ) weights /= numpy . sum ( weights ) abscissas *= numpy . sqrt ( 2 ) return abscissas , weights
Hermite Genz - Keister 18 rule .
18,093
def dtyping ( * args ) : args = list ( args ) for idx , arg in enumerate ( args ) : if isinstance ( arg , Poly ) : args [ idx ] = Poly elif isinstance ( arg , numpy . generic ) : args [ idx ] = numpy . asarray ( arg ) . dtype elif isinstance ( arg , ( float , int ) ) : args [ idx ] = type ( arg ) for type_ in DATATYPES...
Find least common denominator dtype .
18,094
def toarray ( vari ) : if isinstance ( vari , Poly ) : shape = vari . shape out = numpy . asarray ( [ { } for _ in range ( numpy . prod ( shape ) ) ] , dtype = object ) core = vari . A . copy ( ) for key in core . keys ( ) : core [ key ] = core [ key ] . flatten ( ) for i in range ( numpy . prod ( shape ) ) : if not nu...
Convert polynomial array into a numpy . asarray of polynomials .
18,095
def _bnd ( self , xloc , dist , length , cache ) : lower , upper = evaluation . evaluate_bound ( dist , xloc . reshape ( 1 , - 1 ) ) lower = lower . reshape ( length , - 1 ) upper = upper . reshape ( length , - 1 ) assert lower . shape == xloc . shape , ( lower . shape , xloc . shape ) assert upper . shape == xloc . sh...
boundary function .
18,096
def _mom ( self , k , dist , length , cache ) : return numpy . prod ( dist . mom ( k ) , 0 )
Moment generating function .
18,097
def sum ( vari , axis = None ) : if isinstance ( vari , Poly ) : core = vari . A . copy ( ) for key in vari . keys : core [ key ] = sum ( core [ key ] , axis ) return Poly ( core , vari . dim , None , vari . dtype ) return np . sum ( vari , axis )
Sum the components of a shapeable quantity along a given axis .
18,098
def cumsum ( vari , axis = None ) : if isinstance ( vari , Poly ) : core = vari . A . copy ( ) for key , val in core . items ( ) : core [ key ] = cumsum ( val , axis ) return Poly ( core , vari . dim , None , vari . dtype ) return np . cumsum ( vari , axis )
Cumulative sum the components of a shapeable quantity along a given axis .
18,099
def prod ( vari , axis = None ) : if isinstance ( vari , Poly ) : 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 = out * poly return out return np . prod ( vari , axis )
Product of the components of a shapeable quantity along a given axis .