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' ] if unit == 'kelvin' : temp = t if unit == 'celsius' : temp = temputils . kelvin_to_celsius ( t ) if unit == 'fahrenheit' : temp = temputils . kelvin_to_fahrenheit ( t ) result . append ( ( tstamp , temp ) ) return result | 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_data | 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_URL , self . _API_key , None ) _ , json_data = self . _client . cacheable_get_json ( uri , params = params ) return json_data | 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 ( { tuple ( np . eye ( poly . dim ) [ idx ] ) : np . array ( 1 ) } ) x0 . append ( poly_ ) x1 . append ( arg ) args [ idx ] = np . nan if x0 : poly = call ( poly , args ) return substitute ( poly , x0 , x1 ) masks = np . zeros ( len ( args ) , dtype = bool ) for idx , arg in enumerate ( args ) : if np . ma . is_masked ( arg ) or np . any ( np . isnan ( arg ) ) : masks [ idx ] = True args [ idx ] = 0 shape = np . array ( args [ np . argmax ( [ np . prod ( np . array ( arg ) . shape ) for arg in args ] ) ] ) . shape args = np . array ( [ np . ones ( shape , dtype = int ) * arg for arg in args ] ) A = { } for key in poly . keys : key_ = np . array ( key ) * ( 1 - masks ) val = np . outer ( poly . A [ key ] , np . prod ( ( args . T ** key_ ) . T , axis = 0 ) ) val = np . reshape ( val , poly . shape + tuple ( shape ) ) val = np . where ( val != val , 0 , val ) mkey = tuple ( np . array ( key ) * ( masks ) ) if not mkey in A : A [ mkey ] = val else : A [ mkey ] = A [ mkey ] + val out = Poly ( A , poly . dim , None , None ) if out . keys and not np . sum ( out . keys ) : out = out . A [ out . keys [ 0 ] ] elif not out . keys : out = np . zeros ( out . shape , dtype = out . dtype ) return out | 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 : x0 = [ x for x in x0 ] else : x0 = [ x0 ] if x1 . shape : x1 = [ x for x in x1 ] else : x1 = [ x1 ] valid = False C = [ x . keys [ 0 ] . index ( 1 ) for x in x0 ] for key in P . keys : if np . any ( [ key [ c ] for c in C ] ) : valid = True break if not valid : return P dims = [ tuple ( np . array ( x . keys [ 0 ] ) != 0 ) . index ( True ) for x in x0 ] dec = is_decomposed ( P ) if not dec : P = decompose ( P ) P = chaospy . poly . dimension . dimsplit ( P ) shape = P . shape P = [ p for p in chaospy . poly . shaping . flatten ( P ) ] for i in range ( len ( P ) ) : for j in range ( len ( dims ) ) : if P [ i ] . keys and P [ i ] . keys [ 0 ] [ dims [ j ] ] : P [ i ] = x1 [ j ] . __pow__ ( P [ i ] . keys [ 0 ] [ dims [ j ] ] ) break P = Poly ( P , dim , None , dtype ) P = chaospy . poly . shaping . reshape ( P , shape ) P = chaospy . poly . collection . prod ( P , 0 ) if not dec : P = chaospy . poly . collection . sum ( P , 0 ) return P | 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 ) : return 1. def cache_key ( distribution ) : return ( tuple ( k_data ) , distribution ) if cache is None : cache = { } else : if cache_key ( distribution ) in cache : return cache [ cache_key ( distribution ) ] from . . import baseclass try : parameters = load_parameters ( distribution , "_mom" , parameters , cache , cache_key ) out = distribution . _mom ( k_data , ** parameters ) except baseclass . StochasticallyDependentError : logger . warning ( "Distribution %s has stochastic dependencies; " "Approximating moments with quadrature." , distribution ) from . . import approximation out = approximation . approximate_moment ( distribution , k_data ) if isinstance ( out , numpy . ndarray ) : out = out . item ( ) cache [ cache_key ( distribution ) ] = out return out | 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 ) not in edges : edges . append ( ( dist , value ) ) if value not in nodes : nodes . append ( value ) pool . append ( value ) permanent_marks = set ( ) temporary_marks = set ( ) def visit ( node ) : if node in permanent_marks : return if node in temporary_marks : raise DependencyError ( "cycles in dependency structure." ) nodes . remove ( node ) temporary_marks . add ( node ) for node1 , node2 in edges : if node1 is node : visit ( node2 ) temporary_marks . remove ( node ) permanent_marks . add ( node ) pool . append ( node ) while nodes : node = nodes [ 0 ] visit ( node ) if not reverse : pool = list ( reversed ( pool ) ) return pool | 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 . extend ( [ dist for dist in dist1 if dist in dist2 ] ) return sorted ( dependencies ) | 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 ) : polynomials [ idx ] = poly / numpy . sqrt ( norms [ : , idx ] ) norms = norms ** 0 dim = len ( dist ) if dim > 1 : mv_polynomials = [ ] mv_norms = [ ] indices = chaospy . bertran . bindex ( start = 0 , stop = order , dim = dim , sort = sort , cross_truncation = cross_truncation , ) for index in indices : poly = polynomials [ index [ 0 ] ] [ 0 ] for idx in range ( 1 , dim ) : poly = poly * polynomials [ index [ idx ] ] [ idx ] mv_polynomials . append ( poly ) if retall : for index in indices : mv_norms . append ( numpy . prod ( [ norms [ idx , index [ idx ] ] for idx in range ( dim ) ] ) ) else : mv_norms = norms [ 0 ] mv_polynomials = polynomials polynomials = chaospy . poly . flatten ( chaospy . poly . Poly ( mv_polynomials ) ) if retall : return polynomials , numpy . array ( mv_norms ) return polynomials | 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_scaler , numpy . float64 : _identify_scaler , chaospy . poly . base . Poly : _identify_poly , dict : _identify_dict , numpy . ndarray : _identify_iterable , list : _identify_iterable , tuple : _identify_iterable , } . items ( ) : if isinstance ( core , datatype ) : return identifier ( core ) raise TypeError ( "Poly arg: 'core' is not a valid type " + repr ( core ) ) | 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 _ in core ] ) dims = numpy . array ( [ a . dim for a in core ] ) dim = numpy . max ( dims ) if dim != numpy . min ( dims ) : core = [ chaospy . poly . dimension . setdim ( a , dim ) for a in core ] out = { } for idx , core_ in enumerate ( core ) : for key in core_ . keys : if not key in out : out [ key ] = numpy . zeros ( shape , dtype = dtype ) out [ key ] [ idx ] = core_ . A [ key ] return out , dim , shape , dtype | 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 . where ( vvar > 0 , cov / vvar , 0 ) | 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 * q / a , 2 * ( 1 - q ) / ( 1 - a ) ) from chaospy . poly import variable x = variable ( ) orth = [ x * 0 , x ** 0 ] inner = numpy . sum ( q * w , - 1 ) norms = [ 1. , 1. ] A , B = [ ] , [ ] for n in range ( k ) : A . append ( inner / norms [ - 1 ] ) B . append ( norms [ - 1 ] / norms [ - 2 ] ) orth . append ( ( x - A [ - 1 ] ) * orth [ - 1 ] - orth [ - 2 ] * B [ - 1 ] ) y = orth [ - 1 ] ( * q ) ** 2 * w inner = numpy . sum ( q * y , - 1 ) norms . append ( numpy . sum ( y , - 1 ) ) A , B = numpy . array ( A ) . T [ 0 ] , numpy . array ( B ) . T return A [ - 1 ] , B [ - 1 ] | 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 . flatten ( poly ) m1 = E ( poly , dist ) m2 = E ( poly ** 2 , dist ) m3 = E ( poly ** 3 , dist ) out = ( m3 - 3 * m2 * m1 + 2 * m1 ** 3 ) / ( m2 - m1 ** 2 ) ** 1.5 out = numpy . reshape ( out , shape ) return out | 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 = cache if cache is not None else { } parameters = load_parameters ( distribution , "_cdf" , parameters = parameters , cache = cache ) cache [ distribution ] = x_data out = numpy . zeros ( x_data . shape ) out [ : ] = distribution . _cdf ( x_data , ** parameters ) return out | 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 . flatten ( poly ) keys = poly . keys N = len ( keys ) A = poly . A keys1 = numpy . array ( keys ) . T if dim == 1 : keys1 = keys1 [ 0 ] keys2 = sum ( numpy . meshgrid ( keys , keys ) ) else : keys2 = numpy . empty ( ( dim , N , N ) ) for i in range ( N ) : for j in range ( N ) : keys2 [ : , i , j ] = keys1 [ : , i ] + keys1 [ : , j ] m1 = numpy . outer ( * [ dist . mom ( keys1 , ** kws ) ] * 2 ) m2 = dist . mom ( keys2 , ** kws ) mom = m2 - m1 out = numpy . zeros ( poly . shape ) for i in range ( N ) : a = A [ keys [ i ] ] out += a * a * mom [ i , i ] for j in range ( i + 1 , N ) : b = A [ keys [ j ] ] out += 2 * a * b * mom [ i , j ] out = out . reshape ( shape ) return out | 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 . Dist ) : dist , poly = poly , polynomials . variable ( len ( poly ) ) if not poly . keys : return numpy . zeros ( poly . shape , dtype = int ) if isinstance ( poly , ( list , tuple , numpy . ndarray ) ) : return [ E ( _ , dist , ** kws ) for _ in poly ] if poly . dim < len ( dist ) : poly = polynomials . setdim ( poly , len ( dist ) ) shape = poly . shape poly = polynomials . flatten ( poly ) keys = poly . keys mom = dist . mom ( numpy . array ( keys ) . T , ** kws ) A = poly . A if len ( dist ) == 1 : mom = mom [ 0 ] out = numpy . zeros ( poly . shape ) for i in range ( len ( keys ) ) : out += A [ keys [ i ] ] * mom [ i ] out = numpy . reshape ( out , shape ) return out | 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 . descriptives . Cov ( basis , dist ) ) cholmat_inv = numpy . linalg . inv ( cholmat . T ) . T if not normed : diag_mesh = numpy . repeat ( numpy . diag ( cholmat_inv ) , len ( cholmat_inv ) ) cholmat_inv /= diag_mesh . reshape ( cholmat_inv . shape ) coefs = numpy . empty ( ( length + 1 , length + 1 ) ) coefs [ 1 : , 1 : ] = cholmat_inv coefs [ 0 , 0 ] = 1 coefs [ 0 , 1 : ] = 0 expected = - numpy . sum ( cholmat_inv * chaospy . descriptives . E ( basis , dist , ** kws ) , - 1 ) coefs [ 1 : , 0 ] = expected coefs = coefs . T out = { } out [ ( 0 , ) * dim ] = coefs [ 0 ] for idx in range ( length ) : index = basis [ idx ] . keys [ 0 ] out [ index ] = coefs [ idx + 1 ] polynomials = chaospy . poly . Poly ( out , dim , coefs . shape [ 1 : ] , float ) return polynomials | 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 , dtype = int ) for lkey in P . keys : if not sum ( lkey [ ldim - 1 : ] ) or not sum ( lkey ) : P . A [ lkey [ : dim ] ] = P . A . pop ( lkey ) else : del P . A [ lkey ] P . keys = sorted ( P . A . keys ( ) , key = sort_key ) return P | 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_ , 1.0 ) if size == 1 : beta = numpy . sqrt ( max ( gamma , eps ) ) else : beta = numpy . sqrt ( max ( gamma , xi_ / numpy . sqrt ( size * size - 1.0 ) , eps ) ) mat_a = 1.0 * mat mat_r = 0.0 * mat perm = numpy . eye ( size , dtype = int ) for idx in range ( size ) : idz = idx for idy in range ( idx + 1 , size ) : if abs ( mat_a [ idy , idy ] ) >= abs ( mat_a [ idz , idz ] ) : idz = idy if idz != idx : mat_a , mat_r , perm = swap_across ( idz , idx , mat_a , mat_r , perm ) theta_j = 0.0 if idx < size - 1 : for idy in range ( idx + 1 , size ) : theta_j = max ( theta_j , abs ( mat_a [ idx , idy ] ) ) a_pred = max ( abs ( mat_a [ idx , idx ] ) , ( theta_j / beta ) ** 2 , delta ) mat_r [ idx , idx ] = numpy . sqrt ( a_pred ) for idy in range ( idx + 1 , size ) : mat_r [ idx , idy ] = mat_a [ idx , idy ] / mat_r [ idx , idx ] for idz in range ( idx + 1 , idy + 1 ) : mat_a [ idy , idz ] = mat_a [ idz , idy ] = mat_a [ idz , idy ] - mat_r [ idx , idy ] * mat_r [ idx , idz ] return perm , mat_r . T | 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 mat_a = numpy . dot ( perm_new , numpy . dot ( mat_a , perm_new ) ) mat_r = numpy . dot ( mat_r , perm_new ) return mat_a , mat_r , perm | 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 : burnin = max ( primes ) out = numpy . empty ( ( dim , order ) ) indices = [ idx + burnin for idx in range ( order ) ] for dim_ in range ( dim ) : out [ dim_ ] = create_van_der_corput_samples ( indices , number_base = primes [ dim_ ] ) return out | 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 self . _range ( x_data , { } ) else : x_data = numpy . asfarray ( x_data ) shape = x_data . shape x_data = x_data . reshape ( len ( self ) , - 1 ) q_data = evaluation . evaluate_bound ( self , x_data ) q_data = q_data . reshape ( ( 2 , ) + shape ) return q_data | 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 >= lower ) q_data [ indices ] = numpy . clip ( evaluation . evaluate_forward ( self , x_data ) , a_min = 0 , a_max = 1 ) [ indices ] q_data = q_data . reshape ( shape ) return q_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 ) lower , upper = evaluation . evaluate_bound ( self , x_data ) x_data = numpy . clip ( x_data , a_min = lower , a_max = upper ) x_data = x_data . reshape ( shape ) return x_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 = sampler . generator . generate_samples ( order = size_ , domain = self , rule = rule , antithetic = antithetic ) try : out = out . reshape ( shape ) except : if len ( self ) == 1 : out = out . flatten ( ) else : out = out . reshape ( dim , int ( out . size / dim ) ) return out | 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 ( out ) return out . reshape ( shape ) | 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 ( ( 2 , ) + shape ) | 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 , 6 , 200 ) ) contourf ( s , t , Q . pdf ( [ s , t ] ) , 50 ) xlabel ( "$q_1$" ) ylabel ( "$q_2$" ) subplot ( 122 ) Qr = Q . sample ( 500 ) scatter ( * Qr , s = 10 , c = "k" , marker = "s" ) xlabel ( "$Q_1$" ) ylabel ( "$Q_2$" ) axis ( [ 0 , 5 , - 6 , 6 ] ) savefig ( "multivariate.png" ) clf ( ) Q2 = cp . Gamma ( 1 ) Q1 = cp . Normal ( Q2 ** 2 , Q2 + 1 ) Q = cp . J ( Q1 , Q2 ) subplot ( 121 ) s , t = meshgrid ( linspace ( - 4 , 7 , 200 ) , linspace ( 0 , 3 , 200 ) ) contourf ( s , t , Q . pdf ( [ s , t ] ) , 30 ) xlabel ( "$q_1$" ) ylabel ( "$q_2$" ) subplot ( 122 ) Qr = Q . sample ( 500 ) scatter ( * Qr ) xlabel ( "$Q_1$" ) ylabel ( "$Q_2$" ) axis ( [ - 4 , 7 , 0 , 3 ] ) savefig ( "multivariate2.png" ) clf ( ) | 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 dims = len ( samples ) if not len ( axes ) : axes = ( True , ) axes = numpy . asarray ( axes , dtype = bool ) . flatten ( ) indices = { tuple ( axes * idx ) for idx in numpy . ndindex ( ( 2 , ) * dims ) } indices = sorted ( indices , reverse = True ) indices = sorted ( indices , key = lambda idx : sum ( idx ) ) out = [ numpy . where ( idx , inverse_samples . T , samples . T ) . T for idx in indices ] out = numpy . dstack ( out ) . reshape ( dims , - 1 ) return out | 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 = chaospy . poly . constructor . ensure_dim ( core , dim , dim_ ) for key in list ( core . keys ( ) ) : if np . all ( core [ key ] == 0 ) : del core [ key ] assert isinstance ( dim , int ) , "not recognised type for dim: '%s'" % repr ( type ( dim ) ) assert isinstance ( shape , tuple ) , str ( shape ) assert dtype is not None , str ( dtype ) if not core : core = { ( 0 , ) * dim : np . zeros ( shape , dtype = dtype ) } else : core = { key : np . asarray ( value , dtype ) for key , value in core . items ( ) } return core , dim , shape , dtype | 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 ) : m , n = float ( parts [ i ] ) , float ( orders [ i ] ) l = len ( arg ) args [ i ] = arg [ int ( m / n * l ) : int ( ( m + 1 ) / n * l ) ] shapes = [ arg . shape for arg in args ] size = numpy . prod ( shapes , 0 ) [ 0 ] * numpy . sum ( shapes , 0 ) [ 1 ] if size > 10 ** 9 : raise MemoryError ( "Too large sets" ) if len ( args ) == 1 : out = args [ 0 ] elif len ( args ) == 2 : out = combine_two ( * args ) else : arg1 = combine_two ( * args [ : 2 ] ) out = combine ( [ arg1 , ] + args [ 2 : ] ) return out | 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 return ( int ( idxn - idxm ) , ) + _rec ( idx , dim - 1 ) return _rec ( idx , dim ) | 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 ( stop ) , - 1 , - 1 ) , ) * dim ] total = numpy . array ( total ) . reshape ( dim , - 1 ) if start . size > 1 : for idx , start_ in enumerate ( start ) : total = total [ : , total [ idx ] >= start_ ] else : total = total [ : , total . sum ( 0 ) >= start ] if stop . size > 1 : for idx , stop_ in enumerate ( stop ) : total = total [ : , total [ idx ] <= stop_ ] total = total . T . tolist ( ) if "G" in sort : total = sorted ( total , key = sum ) else : def cmp_ ( idxi , idxj ) : if not numpy . any ( idxi ) : return 0 if idxi [ 0 ] == idxj [ 0 ] : return cmp ( idxi [ : - 1 ] , idxj [ : - 1 ] ) return ( idxi [ - 1 ] > idxj [ - 1 ] ) - ( idxi [ - 1 ] < idxj [ - 1 ] ) key = functools . cmp_to_key ( cmp_ ) total = sorted ( total , key = key ) if "I" in sort : total = total [ : : - 1 ] if "R" in sort : total = [ idx [ : : - 1 ] for idx in total ] for pos , idx in reversed ( list ( enumerate ( total ) ) ) : idx = numpy . array ( idx ) cross_truncation = numpy . asfarray ( cross_truncation ) try : if numpy . any ( numpy . sum ( idx ** ( 1. / cross_truncation ) ) > numpy . max ( stop ) ** ( 1. / cross_truncation ) ) : del total [ pos ] except ( OverflowError , ZeroDivisionError ) : pass return total | 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 , axis ) < idx : idxi += 1 return idxi , axis out = numpy . array ( idxm ) - 1 * ( numpy . eye ( dim ) [ axis ] ) return single_index ( out ) , axis | 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 return core , shape | 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 . poly . typing . asfloat , } . items ( ) : if dtype == key : converter = val break else : raise ValueError ( "dtype not recognised (%s)" % str ( dtype ) ) for key , val in core . items ( ) : core [ key ] = converter ( val ) return core , dtype | 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_ = key_convert ( key ) if key_ in new_core : new_core [ key_ ] += val else : new_core [ key_ ] = val return new_core , int ( dim ) | 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 ) lo = dataset . min ( ) up = dataset . max ( ) qoi_dist = distributions . SampleDist ( dataset , lo , up ) qoi_dists . append ( qoi_dist ) qoi_dists = numpy . array ( qoi_dists , distributions . Dist ) qoi_dists = qoi_dists . reshape ( shape ) if not shape : qoi_dists = qoi_dists . item ( ) return qoi_dists | 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 , dtype = int ) * order lower = numpy . ones ( dim ) * lower upper = numpy . ones ( dim ) * upper if composite is None : composite = numpy . array ( 0 ) composite = numpy . asarray ( composite ) if not composite . size : composite = numpy . array ( [ numpy . linspace ( 0 , 1 , composite + 1 ) ] * dim ) else : composite = numpy . array ( composite ) if len ( composite . shape ) <= 1 : composite = numpy . transpose ( [ composite ] ) composite = ( ( composite . T - lower ) / ( upper - lower ) ) . T results = [ _gauss_legendre ( order [ i ] , composite [ i ] ) for i in range ( dim ) ] abscis = numpy . array ( [ _ [ 0 ] for _ in results ] ) weights = numpy . array ( [ _ [ 1 ] for _ in results ] ) abscis = chaospy . quad . combine ( abscis ) weights = chaospy . quad . combine ( weights ) abscis = ( upper - lower ) * abscis + lower weights = numpy . prod ( weights * ( upper - lower ) , 1 ) return abscis . T , weights | 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 ) vals , vecs = numpy . linalg . eig ( banded ) abscis , weight = vals . real , vecs [ 0 , : ] ** 2 indices = numpy . argsort ( abscis ) abscis , weight = abscis [ indices ] , weight [ indices ] n_abscis = len ( abscis ) composite = numpy . array ( composite ) . flatten ( ) composite = list ( set ( composite ) ) composite = [ comp for comp in composite if ( comp < 1 ) and ( comp > 0 ) ] composite . sort ( ) composite = [ 0 ] + composite + [ 1 ] abscissas = numpy . empty ( n_abscis * ( len ( composite ) - 1 ) ) weights = numpy . empty ( n_abscis * ( len ( composite ) - 1 ) ) for dim in range ( len ( composite ) - 1 ) : abscissas [ dim * n_abscis : ( dim + 1 ) * n_abscis ] = abscis * ( composite [ dim + 1 ] - composite [ dim ] ) + composite [ dim ] weights [ dim * n_abscis : ( dim + 1 ) * n_abscis ] = weight * ( composite [ dim + 1 ] - composite [ dim ] ) return abscissas , weights | 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 = [ _ [ 1 ] for _ in values ] abscissas = chaospy . quad . combine ( abscissas ) . T weights = numpy . prod ( chaospy . quad . combine ( weights ) , - 1 ) return abscissas , weights order = sorted ( PATTERSON_VALUES . keys ( ) ) [ order ] abscissas , weights = PATTERSON_VALUES [ order ] lower , upper = dist . range ( ) abscissas = .5 * ( abscissas * ( upper - lower ) + upper + lower ) abscissas = abscissas . reshape ( 1 , abscissas . size ) weights /= numpy . sum ( weights ) return abscissas , 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 [ 0 ] ) . size rule = rule . lower ( ) if len ( rule ) == 1 : rule = collection . QUAD_SHORT_NAMES [ rule ] quad_function = collection . get_function ( rule , domain , normalize , growth = growth , composite = composite , accuracy = accuracy , ) if sparse : order = np . ones ( len ( domain ) , dtype = int ) * order abscissas , weights = sparse_grid . sparse_grid ( quad_function , order , dim ) else : abscissas , weights = quad_function ( order ) assert len ( weights ) == abscissas . shape [ 1 ] assert len ( abscissas . shape ) == 2 return abscissas , weights | 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." . format ( instance . __class__ . __name__ ) ) return instance return caller | 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 = list ( freeze . A . values ( ) ) [ 0 ] else : freeze = numpy . array ( keys ) freeze = freeze . reshape ( int ( freeze . size / len ( dist ) ) , len ( dist ) ) shape = poly . shape poly = polynomials . flatten ( poly ) kmax = numpy . max ( poly . keys , 0 ) + 1 keys = [ range ( k ) for k in kmax ] A = poly . A . copy ( ) keys = poly . keys out = { } zeros = [ 0 ] * poly . dim for i in range ( len ( keys ) ) : key = list ( keys [ i ] ) a = A [ tuple ( key ) ] for d in range ( poly . dim ) : for j in range ( len ( freeze ) ) : if freeze [ j , d ] : key [ d ] , zeros [ d ] = zeros [ d ] , key [ d ] break tmp = a * dist . mom ( tuple ( key ) ) if tuple ( zeros ) in out : out [ tuple ( zeros ) ] = out [ tuple ( zeros ) ] + tmp else : out [ tuple ( zeros ) ] = tmp for d in range ( poly . dim ) : for j in range ( len ( freeze ) ) : if freeze [ j , d ] : key [ d ] , zeros [ d ] = zeros [ d ] , key [ d ] break out = polynomials . Poly ( out , poly . dim , poly . shape , float ) out = polynomials . reshape ( out , shape ) return out | 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 , ( tuple , list , numpy . ndarray ) ) : domain = numpy . asfarray ( domain ) if len ( domain . shape ) < 2 : dim = 1 else : dim = len ( domain [ 0 ] ) trans = lambda x_data : ( ( domain [ 1 ] - domain [ 0 ] ) * x_data . T + domain [ 0 ] ) . T else : dist = domain dim = len ( dist ) trans = dist . inv if antithetic is not None : from . antithetic import create_antithetic_variates antithetic = numpy . array ( antithetic , dtype = bool ) . flatten ( ) if antithetic . size == 1 and dim > 1 : antithetic = numpy . repeat ( antithetic , dim ) size = numpy . sum ( 1 * numpy . array ( antithetic ) ) order_saved = order order = int ( numpy . log ( order - dim ) ) order = order if order > 1 else 1 while order ** dim < order_saved : order += 1 trans_ = trans trans = lambda x_data : trans_ ( create_antithetic_variates ( x_data , antithetic ) [ : , : order_saved ] ) assert rule in SAMPLERS , "rule not recognised" sampler = SAMPLERS [ rule ] x_data = trans ( sampler ( order = order , dim = dim ) ) logger . debug ( "order: %d, dim: %d -> shape: %s" , order , dim , x_data . shape ) return x_data | 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 . array ( chaospy . bertran . bindex ( 0 , order - 1 , dim , sort ) [ : size ] ) idx , idy = numpy . mgrid [ : size , : size ] matrix = numpy . prod ( abscissas . T [ idx ] ** indices [ idy ] , - 1 ) det = numpy . linalg . det ( matrix ) if det == 0 : raise numpy . linalg . LinAlgError ( "invertible matrix required" ) vec = chaospy . poly . basis ( 0 , order - 1 , dim , sort ) [ : size ] coeffs = numpy . zeros ( ( size , size ) ) if size == 1 : out = chaospy . poly . basis ( 0 , 0 , dim , sort ) * abscissas . item ( ) elif size == 2 : coeffs = numpy . linalg . inv ( matrix ) out = chaospy . poly . sum ( vec * ( coeffs . T ) , 1 ) else : for i in range ( size ) : for j in range ( size ) : coeffs [ i , j ] += numpy . linalg . det ( matrix [ 1 : , 1 : ] ) matrix = numpy . roll ( matrix , - 1 , axis = 0 ) matrix = numpy . roll ( matrix , - 1 , axis = 1 ) coeffs /= det out = chaospy . poly . sum ( vec * ( coeffs . T ) , 1 ) return out | 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 ) return dist | 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 ( numpy . diag ( mat [ idx : , idx : ] ) ) + idx if mat [ idx_max , idx_max ] <= numpy . abs ( diag_max * eps ) : if not idx : raise ValueError ( "Purly negative definite" ) for j in range ( idx , size ) : hitri [ j , j ] = hitri [ j - 1 , j - 1 ] / float ( j ) break tmp = mat [ : , idx ] . copy ( ) mat [ : , idx ] = mat [ : , idx_max ] mat [ : , idx_max ] = tmp tmp = hitri [ : , idx ] . copy ( ) hitri [ : , idx ] = hitri [ : , idx_max ] hitri [ : , idx_max ] = tmp tmp = mat [ idx , : ] . copy ( ) mat [ idx , : ] = mat [ idx_max , : ] mat [ idx_max , : ] = tmp piv [ idx ] , piv [ idx_max ] = piv [ idx_max ] , piv [ idx ] hitri [ idx , idx ] = numpy . sqrt ( mat [ idx , idx ] ) rval = mat [ idx , idx + 1 : ] / hitri [ idx , idx ] hitri [ idx , idx + 1 : ] = rval mat [ idx + 1 : , idx + 1 : ] -= numpy . outer ( rval , rval ) perm = numpy . zeros ( ( size , size ) , dtype = int ) for idx in range ( size ) : perm [ idx , piv [ idx ] ] = 1 return perm , hitri . T | 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_cond ( poly , zero , dist , ** kws ) , dist , ** kws ) ) / ( V + ( V == 0 ) ) ** ( V != 0 ) ) zero [ i ] = 1 return out | 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 ) assert "cdf" in kwargs , "cdf function must be defined" assert "bnd" in kwargs , "bnd function must be defined" if "str" in kwargs and isinstance ( kwargs [ "str" ] , str ) : string = kwargs . pop ( "str" ) kwargs [ "str" ] = lambda * args , ** kwargs : string defaults = defaults if defaults else { } for key in defaults : assert key in LEGAL_ATTRS , "invalid default value {}" . format ( key ) def custom_distribution ( ** kws ) : prm = defaults . copy ( ) prm . update ( kws ) dist = Dist ( ** prm ) for key , function in kwargs . items ( ) : attr_name = LEGAL_ATTRS [ key ] setattr ( dist , attr_name , types . MethodType ( function , dist ) ) return dist if "doc" in kwargs : custom_distribution . __doc__ = kwargs [ "doc" ] return custom_distribution | 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 ) shape = solves . shape solves = solves . reshape ( weights . size , int ( solves . size / weights . size ) ) ovals = orth ( * nodes ) vals1 = [ ( val * solves . T * weights ) . T for val in ovals ] if norms is None : norms = numpy . sum ( ovals ** 2 * weights , - 1 ) else : norms = numpy . array ( norms ) . flatten ( ) assert len ( norms ) == len ( orth ) coefs = ( numpy . sum ( vals1 , 1 ) . T / norms ) . T coefs = coefs . reshape ( len ( coefs ) , * shape [ 1 : ] ) approx_model = chaospy . poly . transpose ( chaospy . poly . sum ( orth * coefs . T , - 1 ) ) if retall : return approx_model , coefs return approx_model | 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 , weights = [ ] , [ ] bindex = chaospy . bertran . bindex ( order - dim + 1 , order , dim ) if skew is None : skew = numpy . zeros ( dim , dtype = int ) else : skew = numpy . array ( skew , dtype = int ) assert len ( skew ) == dim for idx in range ( chaospy . bertran . terms ( order , dim ) - chaospy . bertran . terms ( order - dim , dim ) ) : idb = bindex [ idx ] abscissa , weight = func ( skew + idb ) weight *= ( - 1 ) ** ( order - sum ( idb ) ) * comb ( dim - 1 , order - sum ( idb ) ) abscissas . append ( abscissa ) weights . append ( weight ) abscissas = numpy . concatenate ( abscissas , 1 ) weights = numpy . concatenate ( weights , 0 ) abscissas = numpy . around ( abscissas , 15 ) order = numpy . lexsort ( tuple ( abscissas ) ) abscissas = abscissas . T [ order ] . T weights = weights [ order ] diff = numpy . diff ( abscissas . T , axis = 0 ) unique = numpy . ones ( len ( abscissas . T ) , bool ) unique [ 1 : ] = ( diff != 0 ) . any ( axis = 1 ) length = len ( weights ) idx = 1 while idx < length : while idx < length and unique [ idx ] : idx += 1 idy = idx + 1 while idy < length and not unique [ idy ] : idy += 1 if idy - idx > 1 : weights [ idx - 1 ] = numpy . sum ( weights [ idx - 1 : idy ] ) idx = idy + 1 abscissas = abscissas [ : , unique ] weights = weights [ unique ] return abscissas , weights | 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 . zeros ( ( 2 , ) + x_data . shape ) lower , upper = distribution . _bnd ( x_data . copy ( ) , ** parameters ) out . T [ : , : , 0 ] = numpy . asfarray ( lower ) . T out . T [ : , : , 1 ] = numpy . asfarray ( upper ) . T cache [ distribution ] = out return out | 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 = numpy . array ( part2 ) shape = part1 . shape + part2 . shape return numpy . outer ( chaospy . poly . shaping . flatten ( part1 ) , chaospy . poly . shaping . flatten ( part2 ) , ) if dtype == Poly : if isinstance ( part1 , Poly ) and isinstance ( part2 , Poly ) : if ( 1 , ) in ( part1 . shape , part2 . shape ) : return part1 * part2 shape = part1 . shape + part2 . shape out = [ ] for _ in chaospy . poly . shaping . flatten ( part1 ) : out . append ( part2 * _ ) return chaospy . poly . shaping . reshape ( Poly ( out ) , shape ) if isinstance ( part1 , ( int , float , list , tuple ) ) : part2 , part1 = numpy . array ( part1 ) , part2 else : part2 = numpy . array ( part2 ) core_old = part1 . A core_new = { } for key in part1 . keys : core_new [ key ] = outer ( core_old [ key ] , part2 ) shape = part1 . shape + part2 . shape dtype = chaospy . poly . typing . dtyping ( part1 . dtype , part2 . dtype ) return Poly ( core_new , part1 . dim , shape , dtype ) raise NotImplementedError | 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 . sum ( poly , 0 ) | 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_truncation = cross_truncation ) else : basis = order basis = list ( basis ) polynomials = [ basis [ 0 ] ] if normed : for idx in range ( 1 , len ( basis ) ) : for idy in range ( idx ) : orth = chaospy . descriptives . E ( basis [ idx ] * polynomials [ idy ] , dist , ** kws ) basis [ idx ] = basis [ idx ] - polynomials [ idy ] * orth norms = chaospy . descriptives . E ( polynomials [ - 1 ] ** 2 , dist , ** kws ) if norms <= 0 : logger . warning ( "Warning: Polynomial cutoff at term %d" , idx ) break basis [ idx ] = basis [ idx ] / numpy . sqrt ( norms ) polynomials . append ( basis [ idx ] ) else : norms = [ 1. ] for idx in range ( 1 , len ( basis ) ) : for idy in range ( idx ) : orth = chaospy . descriptives . E ( basis [ idx ] * polynomials [ idy ] , dist , ** kws ) basis [ idx ] = basis [ idx ] - polynomials [ idy ] * orth / norms [ idy ] norms . append ( chaospy . descriptives . E ( polynomials [ - 1 ] ** 2 , dist , ** kws ) ) if norms [ - 1 ] <= 0 : logger . warning ( "Warning: Polynomial cutoff at term %d" , idx ) break polynomials . append ( basis [ idx ] ) return chaospy . poly . Poly ( polynomials , dim = dim , shape = ( len ( polynomials ) , ) ) | 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 = parameters_ if contains_call_signature ( getattr ( distribution , method_name ) , "cache" ) : parameters [ "cache" ] = cache else : for key , value in parameters . items ( ) : if isinstance ( value , baseclass . Dist ) : value = cache_key ( value ) if value in cache : parameters [ key ] = cache [ value ] else : raise baseclass . StochasticallyDependentError ( "evaluating under-defined distribution {}." . format ( distribution ) ) return parameters | 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 : if type_ in args : return type_ raise ValueError ( "dtypes not recognised " + str ( [ str ( _ ) for _ in args ] ) ) | 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 numpy . all ( core [ key ] [ i ] == 0 ) : out [ i ] [ key ] = core [ key ] [ i ] for i in range ( numpy . prod ( shape ) ) : out [ i ] = Poly ( out [ i ] , vari . dim , ( ) , vari . dtype ) out = out . reshape ( shape ) return out return numpy . asarray ( vari ) | 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 . shape return lower , upper | 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.