idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
28,500
def pdf ( self , X ) : return invwishart . pdf ( X , df = self . v , scale = self . Psi )
PDF for Inverse Wishart prior
28,501
def neg_loglik ( self , beta ) : Z = np . zeros ( 2 ) Z [ 0 ] = 1 states = np . zeros ( [ self . state_no , self . data . shape [ 0 ] ] ) states [ 0 , : ] = beta [ self . z_no : self . z_no + self . data . shape [ 0 ] ] states [ 1 , : ] = beta [ self . z_no + self . data . shape [ 0 ] : ] parm = np . array ( [ self . l...
Creates negative loglikelihood of the model
28,502
def state_likelihood_markov_blanket ( self , beta , alpha , col_no ) : _ , _ , _ , Q = self . _ss_matrices ( beta ) blanket = np . append ( 0 , ss . norm . logpdf ( alpha [ col_no ] [ 1 : ] - alpha [ col_no ] [ : - 1 ] , loc = 0 , scale = np . sqrt ( Q [ col_no ] [ col_no ] ) ) ) blanket [ : - 1 ] = blanket [ : - 1 ] +...
Returns Markov blanket of the states given the variance latent variables
28,503
def markov_blanket ( self , beta , alpha ) : likelihood_blanket = self . likelihood_markov_blanket ( beta ) state_blanket = self . state_likelihood_markov_blanket ( beta , alpha , 0 ) for i in range ( self . state_no - 1 ) : likelihood_blanket = np . append ( likelihood_blanket , self . likelihood_markov_blanket ( beta...
Creates total Markov blanket for states
28,504
def _general_approximating_model ( self , beta , T , Z , R , Q , h_approx ) : H = np . ones ( self . data_length ) * h_approx mu = np . zeros ( self . data_length ) return H , mu
Creates simplest kind of approximating Gaussian model
28,505
def fit ( self , optimizer = 'RMSProp' , iterations = 1000 , print_progress = True , start_diffuse = False , ** kwargs ) : return self . _bbvi_fit ( optimizer = optimizer , print_progress = print_progress , start_diffuse = start_diffuse , iterations = iterations , ** kwargs )
Fits the model
28,506
def create_design_matrix_2 ( Z , data , Y_len , lag_no ) : row_count = 1 for lag in range ( 1 , lag_no + 1 ) : for reg in range ( Y_len ) : Z [ row_count , : ] = data [ reg ] [ ( lag_no - lag ) : - lag ] row_count += 1 return Z
For Python 2 . 7 - cythonized version only works for 3 . 5
28,507
def _create_B ( self , Y ) : Z = self . _create_Z ( Y ) return np . dot ( np . dot ( Y , np . transpose ( Z ) ) , np . linalg . inv ( np . dot ( Z , np . transpose ( Z ) ) ) )
Creates OLS coefficient matrix
28,508
def _create_Z ( self , Y ) : Z = np . ones ( ( ( self . ylen * self . lags + 1 ) , Y [ 0 ] . shape [ 0 ] ) ) return self . create_design_matrix ( Z , self . data , Y . shape [ 0 ] , self . lags )
Creates design matrix holding the lagged variables
28,509
def _forecast_mean ( self , h , t_params , Y , shock_type = None , shock_index = 0 , shock_value = None , shock_dir = 'positive' , irf_intervals = False ) : random = self . _shock_create ( h , shock_type , shock_index , shock_value , shock_dir , irf_intervals ) exp = [ Y [ variable ] for variable in range ( 0 , self . ...
Function allows for mean prediction ; also allows shock specification for simulations or impulse response effects
28,510
def _shock_create ( self , h , shock_type , shock_index , shock_value , shock_dir , irf_intervals ) : if shock_type is None : random = [ np . zeros ( self . ylen ) for i in range ( 0 , h ) ] elif shock_type == 'IRF' : if self . use_ols_covariance is False : cov = self . custom_covariance ( self . latent_variables . get...
Function creates shocks based on desired specification
28,511
def estimator_cov ( self , method ) : Y = np . array ( [ reg [ self . lags : ] for reg in self . data ] ) Z = self . _create_Z ( Y ) if method == 'OLS' : sigma = self . ols_covariance ( ) else : sigma = self . custom_covariance ( self . latent_variables . get_z_values ( ) ) return np . kron ( np . linalg . inv ( np . d...
Creates covariance matrix for the estimators
28,512
def ols_covariance ( self ) : Y = np . array ( [ reg [ self . lags : reg . shape [ 0 ] ] for reg in self . data ] ) return ( 1.0 / ( Y [ 0 ] . shape [ 0 ] ) ) * np . dot ( self . residuals ( Y ) , np . transpose ( self . residuals ( Y ) ) )
Creates OLS estimate of the covariance matrix
28,513
def residuals ( self , Y ) : return ( Y - np . dot ( self . _create_B ( Y ) , self . _create_Z ( Y ) ) )
Creates the model residuals
28,514
def construct_wishart ( self , v , X ) : self . adjust_prior ( list ( range ( int ( ( len ( self . latent_variables . z_list ) - self . ylen - ( self . ylen ** 2 - self . ylen ) / 2 ) ) , int ( len ( self . latent_variables . z_list ) ) ) ) , fam . InverseWishart ( v , X ) )
Constructs a Wishart prior for the covariance matrix
28,515
def simulation_smoother ( self , beta ) : T , Z , R , Q , H = self . _ss_matrices ( beta ) rnd_h = np . random . normal ( 0 , np . sqrt ( H ) , self . data . shape [ 0 ] + 1 ) q_dist = ss . multivariate_normal ( [ 0.0 ] , Q ) rnd_q = q_dist . rvs ( self . data . shape [ 0 ] + 1 ) a_plus = np . zeros ( ( T . shape [ 0 ]...
Koopman s simulation smoother - simulates from states given model latent variables and observations
28,516
def smoothed_state ( self , data , beta ) : T , Z , R , Q , H = self . _ss_matrices ( beta ) alpha , V = univariate_KFS ( data , Z , H , T , Q , R , 0.0 ) return alpha , V
Creates the negative log marginal likelihood of the model
28,517
def _laplace_fit ( self , obj_type ) : y = self . fit ( method = 'PML' , printer = False ) if y . ihessian is None : raise Exception ( "No Hessian information - Laplace approximation cannot be performed" ) else : self . latent_variables . estimation_method = 'Laplace' theta , Y , scores , states , states_var , X_names ...
Performs a Laplace approximation to the posterior
28,518
def _optimize_fit ( self , obj_type = None , ** kwargs ) : preopt_search = kwargs . get ( 'preopt_search' , True ) if obj_type == self . neg_loglik : method = 'MLE' else : method = 'PML' if preopt_search is True : try : phi = self . _preoptimize_model ( self . latent_variables . get_z_starting_values ( ) , method ) pre...
This function fits models using Maximum Likelihood or Penalized Maximum Likelihood
28,519
def multivariate_neg_logposterior ( self , beta ) : post = self . neg_loglik ( beta ) for k in range ( 0 , self . z_no ) : if self . latent_variables . z_list [ k ] . prior . covariance_prior is True : post += - self . latent_variables . z_list [ k ] . prior . logpdf ( self . custom_covariance ( beta ) ) break else : p...
Returns negative log posterior for a model with a covariance matrix
28,520
def shift_dates ( self , h ) : date_index = copy . deepcopy ( self . index ) date_index = date_index [ self . max_lag : len ( date_index ) ] if self . is_pandas is True : if isinstance ( date_index , pd . core . indexes . datetimes . DatetimeIndex ) : if pd . infer_freq ( date_index ) in [ 'H' , 'M' , 'S' ] : for t in ...
Auxiliary function for creating dates for forecasts
28,521
def plot_z ( self , indices = None , figsize = ( 15 , 5 ) , ** kwargs ) : self . latent_variables . plot_z ( indices = indices , figsize = figsize , ** kwargs )
Plots latent variables by calling latent parameters object
28,522
def evo_blanket ( self , beta , alpha ) : evo_blanket = np . zeros ( self . state_no ) for i in range ( evo_blanket . shape [ 0 ] ) : evo_blanket [ i ] = self . state_likelihood_markov_blanket ( beta , alpha , i ) . sum ( ) if self . family_z_no > 0 : evo_blanket = np . append ( [ self . likelihood_markov_blanket ( bet...
Creates Markov blanket for the variance latent variables
28,523
def log_p_blanket ( self , beta ) : states = np . zeros ( [ self . state_no , self . data . shape [ 0 ] ] ) for state_i in range ( self . state_no ) : states [ state_i , : ] = beta [ ( self . z_no + ( self . data . shape [ 0 ] * state_i ) ) : ( self . z_no + ( self . data . shape [ 0 ] * ( state_i + 1 ) ) ) ] return np...
Creates complete Markov blanket for latent variables
28,524
def logpdf ( self , mu ) : if self . transform is not None : mu = self . transform ( mu ) return ss . expon . logpdf ( mu , self . lmd0 )
Log PDF for Exponential prior
28,525
def markov_blanket ( y , mean , scale , shape , skewness ) : return ss . expon . logpdf ( x = y , scale = 1 / mean )
Markov blanket for the Exponential distribution
28,526
def pdf ( self , mu ) : if self . transform is not None : mu = self . transform ( mu ) return ss . expon . pdf ( mu , self . lmd0 )
PDF for Exponential prior
28,527
def change_parameters ( self , params ) : no_of_params = 0 for core_param in range ( len ( self . q ) ) : for approx_param in range ( self . q [ core_param ] . param_no ) : self . q [ core_param ] . vi_change_param ( approx_param , params [ no_of_params ] ) no_of_params += 1
Utility function for changing the approximate distribution parameters
28,528
def current_parameters ( self ) : current = [ ] for core_param in range ( len ( self . q ) ) : for approx_param in range ( self . q [ core_param ] . param_no ) : current . append ( self . q [ core_param ] . vi_return_param ( approx_param ) ) return np . array ( current )
Obtains an array with the current parameters
28,529
def cv_gradient ( self , z ) : gradient = np . zeros ( np . sum ( self . approx_param_no ) ) z_t = z . T log_q = self . normal_log_q ( z . T ) log_p = self . log_p ( z . T ) grad_log_q = self . grad_log_q ( z ) gradient = grad_log_q * ( log_p - log_q ) alpha0 = alpha_recursion ( np . zeros ( np . sum ( self . approx_pa...
The control variate augmented Monte Carlo gradient estimate
28,530
def draw_variables ( self ) : z = self . q [ 0 ] . draw_variable_local ( self . sims ) for i in range ( 1 , len ( self . q ) ) : z = np . vstack ( ( z , self . q [ i ] . draw_variable_local ( self . sims ) ) ) return z
Draw parameters from the approximating distributions
28,531
def grad_log_q ( self , z ) : param_count = 0 grad = np . zeros ( ( np . sum ( self . approx_param_no ) , self . sims ) ) for core_param in range ( len ( self . q ) ) : for approx_param in range ( self . q [ core_param ] . param_no ) : grad [ param_count ] = self . q [ core_param ] . vi_score ( z [ core_param ] , appro...
The gradients of the approximating distributions
28,532
def print_progress ( self , i , current_params ) : for split in range ( 1 , 11 ) : if i == ( round ( self . iterations / 10 * split ) - 1 ) : post = - self . full_neg_posterior ( current_params ) approx = self . create_normal_logq ( current_params ) diff = post - approx if not self . quiet_progress : print ( str ( spli...
Prints the current ELBO at every decile of total iterations
28,533
def run ( self ) : z = self . draw_normal_initial ( ) gradient = self . cv_gradient_initial ( z ) gradient [ np . isnan ( gradient ) ] = 0 variance = np . power ( gradient , 2 ) final_parameters = self . current_parameters ( ) final_samples = 1 if self . optimizer == 'ADAM' : self . optim = ADAM ( final_parameters , va...
The core BBVI routine - draws Monte Carlo gradients and uses a stochastic optimizer .
28,534
def logpdf ( x , shape , loc = 0.0 , scale = 1.0 , skewness = 1.0 ) : m1 = ( np . sqrt ( shape ) * sp . gamma ( ( shape - 1.0 ) / 2.0 ) ) / ( np . sqrt ( np . pi ) * sp . gamma ( shape / 2.0 ) ) loc = loc + ( skewness - ( 1.0 / skewness ) ) * scale * m1 result = np . zeros ( x . shape [ 0 ] ) result [ x - loc < 0 ] = n...
Log PDF for the Skew - t distribution
28,535
def approximating_model_reg ( self , beta , T , Z , R , Q , h_approx , data , X , state_no ) : H = np . ones ( data . shape [ 0 ] ) mu = np . zeros ( data . shape [ 0 ] ) alpha = np . zeros ( [ state_no , data . shape [ 0 ] ] ) tol = 100.0 it = 0 while tol > 10 ** - 7 and it < 5 : old_alpha = np . sum ( X * alpha . T ,...
Creates approximating Gaussian model for Poisson measurement density - dynamic regression model
28,536
def logpdf ( self , mu ) : if self . transform is not None : mu = self . transform ( mu ) return ss . poisson . logpmf ( mu , self . lmd0 )
Log PDF for Poisson prior
28,537
def setup ( ) : name = "Poisson" link = np . exp scale = False shape = False skewness = False mean_transform = np . log cythonized = True return name , link , scale , shape , skewness , mean_transform , cythonized
Returns the attributes of this family
28,538
def pdf ( self , mu ) : if self . transform is not None : mu = self . transform ( mu ) return ss . poisson . pmf ( mu , self . lmd0 )
PDF for Poisson prior
28,539
def reg_score_function ( X , y , mean , scale , shape , skewness ) : return X * ( y - mean )
GAS Poisson Regression Update term using gradient only - native Python function
28,540
def second_order_score ( y , mean , scale , shape , skewness ) : return ( y - mean ) / float ( mean )
GAS Poisson Update term potentially using second - order information - native Python function
28,541
def logpdf ( self , x ) : if self . transform is not None : x = self . transform ( x ) return ( - self . alpha - 1 ) * np . log ( x ) - ( self . beta / float ( x ) )
Log PDF for Inverse Gamma prior
28,542
def pdf ( self , x ) : if self . transform is not None : x = self . transform ( x ) return ( x ** ( - self . alpha - 1 ) ) * np . exp ( - ( self . beta / float ( x ) ) )
PDF for Inverse Gamma prior
28,543
def logpdf ( self , mu ) : if self . transform is not None : mu = self . transform ( mu ) return ss . cauchy . logpdf ( mu , self . loc0 , self . scale0 )
Log PDF for Cauchy prior
28,544
def pdf ( self , mu ) : return ss . cauchy . pdf ( mu , self . loc0 , self . scale0 )
PDF for Cauchy prior
28,545
def markov_blanket ( y , mean , scale , shape , skewness ) : return ss . cauchy . logpdf ( y , loc = mean , scale = scale )
Markov blanket for each likelihood term - used for state space models
28,546
def setup ( ) : name = "Cauchy" link = np . array scale = True shape = False skewness = False mean_transform = np . array cythonized = True return name , link , scale , shape , skewness , mean_transform , cythonized
Returns the attributes of this family if using in a probabilistic model
28,547
def neg_loglikelihood ( y , mean , scale , shape , skewness ) : return - np . sum ( ss . cauchy . logpdf ( y , loc = mean , scale = scale ) )
Negative loglikelihood function for this distribution
28,548
def reg_score_function ( X , y , mean , scale , shape , skewness ) : return 2.0 * ( ( y - mean ) * X ) / ( np . power ( scale , 2 ) + np . power ( ( y - mean ) , 2 ) )
GAS Cauchy Regression Update term using gradient only - native Python function
28,549
def general_neg_loglik ( self , beta ) : mu , Y = self . _model ( beta ) parm = np . array ( [ self . latent_variables . z_list [ k ] . prior . transform ( beta [ k ] ) for k in range ( beta . shape [ 0 ] ) ] ) model_scale , model_shape , model_skewness = self . _get_scale_and_shape ( parm ) return self . family . neg_...
Calculates the negative log - likelihood of the model
28,550
def plot_fit ( self , ** kwargs ) : import matplotlib . pyplot as plt import seaborn as sns figsize = kwargs . get ( 'figsize' , ( 10 , 7 ) ) plt . figure ( figsize = figsize ) date_index = self . index [ self . ar : self . data . shape [ 0 ] ] mu , Y = self . _model ( self . latent_variables . get_z_values ( ) ) plt ....
Plots the fit of the model against the data
28,551
def predict_is ( self , h = 5 , fit_once = True , fit_method = 'MLE' , intervals = False , ** kwargs ) : predictions = [ ] for t in range ( 0 , h ) : x = NNAR ( ar = self . ar , units = self . units , layers = self . layers , data = self . data_original [ : - h + t ] , family = self . family ) if fit_once is False : x ...
Makes dynamic out - of - sample predictions with the estimated model on in - sample data
28,552
def likelihood_markov_blanket ( self , beta ) : states = beta [ self . z_no : self . z_no + self . data_length ] parm = np . array ( [ self . latent_variables . z_list [ k ] . prior . transform ( beta [ k ] ) for k in range ( self . z_no ) ] ) scale , shape , skewness = self . _get_scale_and_shape ( parm ) return self ...
Creates likelihood markov blanket of the model
28,553
def _animate_bbvi ( self , stored_latent_variables , stored_predictive_likelihood ) : from matplotlib . animation import FuncAnimation , writers import matplotlib . pyplot as plt import seaborn as sns fig = plt . figure ( ) ax = fig . add_subplot ( 1 , 1 , 1 ) ud = BBVINLLMAnimate ( ax , self . data , stored_latent_var...
Produces animated plot of BBVI optimization
28,554
def initialize_approx_dist ( self , phi , start_diffuse , gaussian_latents ) : for i in range ( len ( self . latent_variables . z_list ) ) : approx_dist = self . latent_variables . z_list [ i ] . q if isinstance ( approx_dist , fam . Normal ) : self . latent_variables . z_list [ i ] . q . mu0 = phi [ i ] self . latent_...
Initializes the appoximate distibution for the model
28,555
def logpdf ( self , mu ) : if self . transform is not None : mu = self . transform ( mu ) return ss . t . logpdf ( mu , df = self . df0 , loc = self . loc0 , scale = self . scale0 )
Log PDF for t prior
28,556
def second_order_score ( y , mean , scale , shape , skewness ) : return ( ( shape + 1 ) / shape ) * ( y - mean ) / ( np . power ( scale , 2 ) + ( np . power ( y - mean , 2 ) / shape ) ) / ( ( shape + 1 ) * ( ( np . power ( scale , 2 ) * shape ) - np . power ( y - mean , 2 ) ) / np . power ( ( np . power ( scale , 2 ) *...
GAS t Update term potentially using second - order information - native Python function
28,557
def load_hashes ( filename ) : hashes = { } try : with open ( filename , 'r' ) as cython_hash_file : for hash_record in cython_hash_file : ( filename , header_hash , cython_hash , gen_file_hash ) = hash_record . split ( ) hashes [ filename ] = ( header_hash , cython_hash , gen_file_hash ) except ( KeyError , ValueError...
Load the hashes dict from the hashfile
28,558
def save_hashes ( hashes , filename ) : with open ( filename , 'w' ) as cython_hash_file : for key , value in hashes . items ( ) : cython_hash_file . write ( "%s %s %s %s\n" % ( key , value [ 0 ] , value [ 1 ] , value [ 2 ] ) )
Save the hashes dict to the hashfile
28,559
def clean_path ( path ) : path = path . replace ( os . sep , '/' ) if path . startswith ( './' ) : path = path [ 2 : ] return path
Clean the path
28,560
def get_hash_tuple ( header_path , cython_path , gen_file_path ) : header_hash = ( sha1_of_file ( header_path ) if os . path . exists ( header_path ) else 'NA' ) from_hash = sha1_of_file ( cython_path ) to_hash = ( sha1_of_file ( gen_file_path ) if os . path . exists ( gen_file_path ) else 'NA' ) return header_hash , f...
Get the hashes from the given files
28,561
def logpdf ( self , mu ) : if self . transform is not None : mu = self . transform ( mu ) if mu < self . lower and self . lower is not None : return - 10.0 ** 6 elif mu > self . upper and self . upper is not None : return - 10.0 ** 6 else : return - np . log ( float ( self . sigma0 ) ) - ( 0.5 * ( mu - self . mu0 ) ** ...
Log PDF for Truncated Normal prior
28,562
def pdf ( self , mu ) : if self . transform is not None : mu = self . transform ( mu ) if mu < self . lower and self . lower is not None : return 0.0 elif mu > self . upper and self . upper is not None : return 0.0 else : return ( 1 / float ( self . sigma0 ) ) * np . exp ( - ( 0.5 * ( mu - self . mu0 ) ** 2 ) / float (...
PDF for Truncated Normal prior
28,563
def tune_scale ( acceptance , scale ) : if acceptance > 0.8 : scale *= 2.0 elif acceptance <= 0.8 and acceptance > 0.4 : scale *= 1.3 elif acceptance < 0.234 and acceptance > 0.1 : scale *= ( 1 / 1.3 ) elif acceptance <= 0.1 and acceptance > 0.05 : scale *= 0.4 elif acceptance <= 0.05 and acceptance > 0.01 : scale *= 0...
Tunes scale for M - H algorithm
28,564
def draw_variable_local ( self , size ) : return ss . norm . rvs ( loc = self . mu0 , scale = self . sigma0 , size = size )
Simulate from the Normal distribution using instance values
28,565
def first_order_score ( y , mean , scale , shape , skewness ) : return ( y - mean ) / np . power ( scale , 2 )
GAS Normal Update term using gradient only - native Python function
28,566
def logpdf ( self , mu ) : if self . transform is not None : mu = self . transform ( mu ) return - np . log ( float ( self . sigma0 ) ) - ( 0.5 * ( mu - self . mu0 ) ** 2 ) / float ( self . sigma0 ** 2 )
Log PDF for Normal prior
28,567
def pdf ( self , mu ) : if self . transform is not None : mu = self . transform ( mu ) return ( 1.0 / float ( self . sigma0 ) ) * np . exp ( - ( 0.5 * ( mu - self . mu0 ) ** 2 ) / float ( self . sigma0 ** 2 ) )
PDF for Normal prior
28,568
def vi_change_param ( self , index , value ) : if index == 0 : self . mu0 = value elif index == 1 : self . sigma0 = np . exp ( value )
Wrapper function for changing latent variables - variational inference
28,569
def vi_return_param ( self , index ) : if index == 0 : return self . mu0 elif index == 1 : return np . log ( self . sigma0 )
Wrapper function for selecting appropriate latent variable for variational inference
28,570
def vi_score ( self , x , index ) : if index == 0 : return self . vi_loc_score ( x ) elif index == 1 : return self . vi_scale_score ( x )
Wrapper function for selecting appropriate score
28,571
def first_order_score ( y , mean , scale , shape , skewness ) : return ( y - mean ) / float ( scale * np . abs ( y - mean ) )
GAS Laplace Update term using gradient only - native Python function
28,572
def logpdf ( self , mu ) : if self . transform is not None : mu = self . transform ( mu ) return ss . laplace . logpdf ( mu , loc = self . loc0 , scale = self . scale0 )
Log PDF for Laplace prior
28,573
def pdf ( self , mu ) : if self . transform is not None : mu = self . transform ( mu ) return ss . laplace . pdf ( mu , self . loc0 , self . scale0 )
PDF for Laplace prior
28,574
def second_order_score ( y , mean , scale , shape , skewness ) : return ( ( y - mean ) / float ( scale * np . abs ( y - mean ) ) ) / ( - ( np . power ( y - mean , 2 ) - np . power ( np . abs ( mean - y ) , 2 ) ) / ( scale * np . power ( np . abs ( mean - y ) , 3 ) ) )
GAS Laplace Update term potentially using second - order information - native Python function
28,575
def data_check ( data , target ) : if isinstance ( data , pd . DataFrame ) or isinstance ( data , pd . core . frame . DataFrame ) : data_index = data . index if target is None : transformed_data = data . ix [ : , 0 ] . values data_name = str ( data . columns . values [ 0 ] ) else : transformed_data = data [ target ] . ...
Checks data type
28,576
def add_z ( self , name , prior , q , index = True ) : self . z_list . append ( LatentVariable ( name , len ( self . z_list ) , prior , q ) ) if index is True : self . z_indices [ name ] = { 'start' : len ( self . z_list ) - 1 , 'end' : len ( self . z_list ) - 1 }
Adds latent variable
28,577
def create ( self , name , dim , prior , q ) : def rec ( dim , prev = [ ] ) : if len ( dim ) > 0 : return [ rec ( dim [ 1 : ] , prev + [ i ] ) for i in range ( dim [ 0 ] ) ] else : return "(" + "," . join ( [ str ( j ) for j in prev ] ) + ")" indices = rec ( dim ) for f_dim in range ( 1 , len ( dim ) ) : indices = sum ...
Creates multiple latent variables
28,578
def build_latent_variables ( self ) : lvs_to_build = [ ] lvs_to_build . append ( [ 'Noise Sigma^2' , fam . Flat ( transform = 'exp' ) , fam . Normal ( 0 , 3 ) , - 1.0 ] ) for lag in range ( self . X . shape [ 1 ] ) : lvs_to_build . append ( [ 'l lag' + str ( lag + 1 ) , fam . FLat ( transform = 'exp' ) , fam . Normal (...
Builds latent variables for this kernel
28,579
def _ar_matrix ( self ) : Y = np . array ( self . data [ self . max_lag : self . data . shape [ 0 ] ] ) X = self . data [ ( self . max_lag - 1 ) : - 1 ] if self . ar != 0 : for i in range ( 1 , self . ar ) : X = np . vstack ( ( X , self . data [ ( self . max_lag - i - 1 ) : - i - 1 ] ) ) return X
Creates Autoregressive matrix
28,580
def predict_is ( self , h ) : result = pd . DataFrame ( [ self . run ( h = h ) [ 2 ] ] ) . T result . index = self . index [ - h : ] return result
Outputs predictions for the Aggregate algorithm on the in - sample data
28,581
def summary ( self , h ) : _ , losses , _ = self . run ( h = h ) df = pd . DataFrame ( losses ) df . index = [ 'Ensemble' ] + self . model_names df . columns = [ self . loss_name ] return df
Summarize the results for each model for h steps of the algorithm
28,582
def extract_geometry ( self ) : gf = vtk . vtkCompositeDataGeometryFilter ( ) gf . SetInputData ( self ) gf . Update ( ) return wrap ( gf . GetOutputDataObject ( 0 ) )
Combines the geomertry of all blocks into a single PolyData object . Place this filter at the end of a pipeline before a polydata consumer such as a polydata mapper to extract geometry from all blocks and append them to one polydata object .
28,583
def combine ( self , merge_points = False ) : alg = vtk . vtkAppendFilter ( ) for block in self : alg . AddInputData ( block ) alg . SetMergePoints ( merge_points ) alg . Update ( ) return wrap ( alg . GetOutputDataObject ( 0 ) )
Appends all blocks into a single unstructured grid .
28,584
def save ( self , filename , binary = True ) : filename = os . path . abspath ( os . path . expanduser ( filename ) ) ext = vtki . get_ext ( filename ) if ext in [ '.vtm' , '.vtmb' ] : writer = vtk . vtkXMLMultiBlockDataWriter ( ) else : raise Exception ( 'File extension must be either "vtm" or "vtmb"' ) writer . SetFi...
Writes a MultiBlock dataset to disk .
28,585
def get_index_by_name ( self , name ) : for i in range ( self . n_blocks ) : if self . get_block_name ( i ) == name : return i raise KeyError ( 'Block name ({}) not found' . format ( name ) )
Find the index number by block name
28,586
def append ( self , data ) : index = self . n_blocks self [ index ] = data self . refs . append ( data )
Add a data set to the next block index
28,587
def set_block_name ( self , index , name ) : if name is None : return self . GetMetaData ( index ) . Set ( vtk . vtkCompositeDataSet . NAME ( ) , name ) self . Modified ( )
Set a block s string name at the specified index
28,588
def get_block_name ( self , index ) : meta = self . GetMetaData ( index ) if meta is not None : return meta . Get ( vtk . vtkCompositeDataSet . NAME ( ) ) return None
Returns the string name of the block at the given index
28,589
def keys ( self ) : names = [ ] for i in range ( self . n_blocks ) : names . append ( self . get_block_name ( i ) ) return names
Get all the block names in the dataset
28,590
def next ( self ) : if self . _iter_n < self . n_blocks : result = self [ self . _iter_n ] self . _iter_n += 1 return result else : raise StopIteration
Get the next block from the iterator
28,591
def _repr_html_ ( self ) : fmt = "" fmt += "<table>" fmt += "<tr><th>Information</th><th>Blocks</th></tr>" fmt += "<tr><td>" fmt += "\n" fmt += "<table>\n" fmt += "<tr><th>{}</th><th>Values</th></tr>\n" . format ( type ( self ) . __name__ ) row = "<tr><td>{}</td><td>{}</td></tr>\n" for attr in self . _get_attrs ( ) : t...
A pretty representation for Jupyter notebooks
28,592
def translate ( surf , center , direction ) : normx = np . array ( direction ) / np . linalg . norm ( direction ) normz = np . cross ( normx , [ 0 , 1.0 , 0.0000001 ] ) normz /= np . linalg . norm ( normz ) normy = np . cross ( normz , normx ) trans = np . zeros ( ( 4 , 4 ) ) trans [ : 3 , 0 ] = normx trans [ : 3 , 1 ]...
Translates and orientates a mesh centered at the origin and facing in the x direction to a new center and direction
28,593
def Cylinder ( center = ( 0. , 0. , 0. ) , direction = ( 1. , 0. , 0. ) , radius = 0.5 , height = 1.0 , resolution = 100 , ** kwargs ) : capping = kwargs . get ( 'capping' , kwargs . get ( 'cap_ends' , True ) ) cylinderSource = vtk . vtkCylinderSource ( ) cylinderSource . SetRadius ( radius ) cylinderSource . SetHeight...
Create the surface of a cylinder .
28,594
def Arrow ( start = ( 0. , 0. , 0. ) , direction = ( 1. , 0. , 0. ) , tip_length = 0.25 , tip_radius = 0.1 , shaft_radius = 0.05 , shaft_resolution = 20 ) : arrow = vtk . vtkArrowSource ( ) arrow . SetTipLength ( tip_length ) arrow . SetTipRadius ( tip_radius ) arrow . SetShaftRadius ( shaft_radius ) arrow . SetShaftRe...
Create a vtk Arrow
28,595
def Sphere ( radius = 0.5 , center = ( 0 , 0 , 0 ) , direction = ( 0 , 0 , 1 ) , theta_resolution = 30 , phi_resolution = 30 , start_theta = 0 , end_theta = 360 , start_phi = 0 , end_phi = 180 ) : sphere = vtk . vtkSphereSource ( ) sphere . SetRadius ( radius ) sphere . SetThetaResolution ( theta_resolution ) sphere . ...
Create a vtk Sphere
28,596
def Plane ( center = ( 0 , 0 , 0 ) , direction = ( 0 , 0 , 1 ) , i_size = 1 , j_size = 1 , i_resolution = 10 , j_resolution = 10 ) : planeSource = vtk . vtkPlaneSource ( ) planeSource . SetXResolution ( i_resolution ) planeSource . SetYResolution ( j_resolution ) planeSource . Update ( ) surf = PolyData ( planeSource ....
Create a plane
28,597
def Line ( pointa = ( - 0.5 , 0. , 0. ) , pointb = ( 0.5 , 0. , 0. ) , resolution = 1 ) : if np . array ( pointa ) . size != 3 : raise TypeError ( 'Point A must be a length three tuple of floats.' ) if np . array ( pointb ) . size != 3 : raise TypeError ( 'Point B must be a length three tuple of floats.' ) src = vtk . ...
Create a line
28,598
def Cube ( center = ( 0. , 0. , 0. ) , x_length = 1.0 , y_length = 1.0 , z_length = 1.0 , bounds = None ) : src = vtk . vtkCubeSource ( ) if bounds is not None : if np . array ( bounds ) . size != 6 : raise TypeError ( 'Bounds must be given as length 6 tuple: (xMin,xMax, yMin,yMax, zMin,zMax)' ) src . SetBounds ( bound...
Create a cube by either specifying the center and side lengths or just the bounds of the cube . If bounds are given all other arguments are ignored .
28,599
def standard_reader_routine ( reader , filename , attrs = None ) : if attrs is None : attrs = { } if not isinstance ( attrs , dict ) : raise TypeError ( 'Attributes must be a dictionary of name and arguments.' ) reader . SetFileName ( filename ) for name , args in attrs . items ( ) : attr = getattr ( reader , name ) if...
Use a given reader from the READERS mapping in the common VTK reading pipeline routine .