idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
32,400
def _diffsigma ( self , Ep , Egamma ) : Tp = Ep - self . _m_p diffsigma = self . _Amax ( Tp ) * self . _F ( Tp , Egamma ) if self . nuclear_enhancement : diffsigma *= self . _nuclear_factor ( Tp ) return diffsigma
Differential cross section
32,401
def _nuclear_factor ( self , Tp ) : sigmaRpp = 10 * np . pi * 1e-27 sigmainel = self . _sigma_inel ( Tp ) sigmainel0 = self . _sigma_inel ( 1e3 ) f = sigmainel / sigmainel0 f2 = np . where ( f > 1 , f , 1.0 ) G = 1.0 + np . log ( f2 ) epsC = 1.37 eps1 = 0.29 eps2 = 0.1 epstotal = np . where ( Tp > self . _Tth , epsC + ...
Compute nuclear enhancement factor
32,402
def _Fgamma ( self , x , Ep ) : L = np . log ( Ep ) B = 1.30 + 0.14 * L + 0.011 * L ** 2 beta = ( 1.79 + 0.11 * L + 0.008 * L ** 2 ) ** - 1 k = ( 0.801 + 0.049 * L + 0.014 * L ** 2 ) ** - 1 xb = x ** beta F1 = B * ( np . log ( x ) / x ) * ( ( 1 - xb ) / ( 1 + k * xb * ( 1 - xb ) ) ) ** 4 F2 = ( 1.0 / np . log ( x ) - (...
KAB06 Eq . 58
32,403
def _sigma_inel ( self , Ep ) : L = np . log ( Ep ) sigma = 34.3 + 1.88 * L + 0.25 * L ** 2 if Ep <= 0.1 : Eth = 1.22e-3 sigma *= ( 1 - ( Eth / Ep ) ** 4 ) ** 2 * heaviside ( Ep - Eth ) return sigma * 1e-27
Inelastic cross - section for p - p interaction . KAB06 Eq . 73 79
32,404
def _photon_integrand ( self , x , Egamma ) : try : return ( self . _sigma_inel ( Egamma / x ) * self . _particle_distribution ( ( Egamma / x ) ) * self . _Fgamma ( x , Egamma / x ) / x ) except ZeroDivisionError : return np . nan
Integrand of Eq . 72
32,405
def _calc_specpp_hiE ( self , Egamma ) : from scipy . integrate import quad Egamma = Egamma . to ( "TeV" ) . value specpp = ( c . cgs . value * quad ( self . _photon_integrand , 0.0 , 1.0 , args = Egamma , epsrel = 1e-3 , epsabs = 0 , ) [ 0 ] ) return specpp * u . Unit ( "1/(s TeV)" )
Spectrum computed as in Eq . 42 for Egamma > = 0 . 1 TeV
32,406
def _calc_specpp_loE ( self , Egamma ) : from scipy . integrate import quad Egamma = Egamma . to ( "TeV" ) . value Epimin = Egamma + self . _m_pi ** 2 / ( 4 * Egamma ) result = ( 2 * quad ( self . _delta_integrand , Epimin , np . inf , epsrel = 1e-3 , epsabs = 0 ) [ 0 ] ) return result * u . Unit ( "1/(s TeV)" )
Delta - functional approximation for low energies Egamma < 0 . 1 TeV
32,407
def get_config_path ( appdirs = DEFAULT_APPDIRS , file_name = DEFAULT_CONFIG_FILENAME ) : return os . path . join ( appdirs . user_config_dir , file_name )
Return the path where the config file is stored .
32,408
def write_config_file ( config_instance , appdirs = DEFAULT_APPDIRS , file_name = DEFAULT_CONFIG_FILENAME ) : path = get_config_path ( appdirs , file_name ) with open ( path , 'w' ) as fobj : config_instance . write ( fobj ) return config_instance
Write a ConfigParser instance to file at the correct location .
32,409
def load_config_file ( appdirs = DEFAULT_APPDIRS , file_name = DEFAULT_CONFIG_FILENAME , fallback_config_instance = None ) : if not fallback_config_instance : fallback_config_instance = backend_config_to_configparser ( get_default_backend_config ( appdirs ) ) config = SafeConfigParser ( ) path = get_config_path ( appdi...
Retrieve config information from file at default location .
32,410
def get_default_backend_config ( appdirs ) : return { 'store' : 'sqlalchemy' , 'day_start' : datetime . time ( 5 , 30 , 0 ) , 'fact_min_delta' : 1 , 'tmpfile_path' : os . path . join ( appdirs . user_data_dir , '{}.tmp' . format ( appdirs . appname ) ) , 'db_engine' : 'sqlite' , 'db_path' : os . path . join ( appdirs ....
Return a default config dictionary .
32,411
def backend_config_to_configparser ( config ) : def get_store ( ) : return config . get ( 'store' ) def get_day_start ( ) : day_start = config . get ( 'day_start' ) if day_start : day_start = day_start . strftime ( '%H:%M:%S' ) return day_start def get_fact_min_delta ( ) : return text_type ( config . get ( 'fact_min_de...
Return a ConfigParser instance representing a given backend config dictionary .
32,412
def configparser_to_backend_config ( cp_instance ) : def get_store ( ) : store = cp_instance . get ( 'Backend' , 'store' ) if store not in hamster_lib . REGISTERED_BACKENDS . keys ( ) : raise ValueError ( _ ( "Unrecognized store option." ) ) return store def get_day_start ( ) : try : day_start = datetime . datetime . s...
Return a config dict generated from a configparser instance .
32,413
def user_data_dir ( self ) : directory = appdirs . user_data_dir ( self . appname , self . appauthor , version = self . version , roaming = self . roaming ) if self . create : self . _ensure_directory_exists ( directory ) return directory
Return user_data_dir .
32,414
def site_config_dir ( self ) : directory = appdirs . site_config_dir ( self . appname , self . appauthor , version = self . version , multipath = self . multipath ) if self . create : self . _ensure_directory_exists ( directory ) return directory
Return site_config_dir .
32,415
def user_cache_dir ( self ) : directory = appdirs . user_cache_dir ( self . appname , self . appauthor , version = self . version ) if self . create : self . _ensure_directory_exists ( directory ) return directory
Return user_cache_dir .
32,416
def _ensure_directory_exists ( self , directory ) : if not os . path . lexists ( directory ) : os . makedirs ( directory ) return directory
Ensure that the passed path exists .
32,417
def _load_tmp_fact ( filepath ) : from hamster_lib import Fact try : with open ( filepath , 'rb' ) as fobj : fact = pickle . load ( fobj ) except IOError : fact = False else : if not isinstance ( fact , Fact ) : raise TypeError ( _ ( "Something went wrong. It seems our pickled file does not contain" " valid Fact instan...
Load an ongoing fact from a given location .
32,418
def parse_raw_fact ( raw_fact ) : def at_split ( string ) : result = string . split ( '@' , 1 ) length = len ( result ) if length == 1 : front , back = result [ 0 ] . strip ( ) , None else : front , back = result front , back = front . strip ( ) , back . strip ( ) return ( front , back ) def comma_split ( string ) : re...
Extract semantically meaningful sub - components from a raw fact text .
32,419
def read_run ( filename , modelfn = None ) : result = _result ( ) result . modelfn = modelfn result . run_info = { } f = h5py . File ( filename , "r" ) result . chain = np . array ( f [ "sampler/chain" ] ) result . lnprobability = np . array ( f [ "sampler/lnprobability" ] ) result . blobs = [ ] shape = result . chain ...
Read chain from a hdf5 saved with save_run .
32,420
def ElectronIC ( pars , data ) : ECPL = ExponentialCutoffPowerLaw ( pars [ 0 ] / u . eV , 10.0 * u . TeV , pars [ 1 ] , 10 ** pars [ 2 ] * u . TeV ) IC = InverseCompton ( ECPL , seed_photon_fields = [ "CMB" ] ) return IC . flux ( data , distance = 1.0 * u . kpc )
Define particle distribution model radiative model and return model flux at data energy values
32,421
def _pdist ( p ) : index , ref , ampl , cutoff , beta = p [ : 5 ] if cutoff == 0.0 : pdist = models . PowerLaw ( ampl * 1e30 * u . Unit ( "1/eV" ) , ref * u . TeV , index ) else : pdist = models . ExponentialCutoffPowerLaw ( ampl * 1e30 * u . Unit ( "1/eV" ) , ref * u . TeV , index , cutoff * u . TeV , beta = beta , ) ...
Return PL or ECPL instance based on parameters p
32,422
def plot_chain ( sampler , p = None , ** kwargs ) : if p is None : npars = sampler . chain . shape [ - 1 ] for pp in six . moves . range ( npars ) : _plot_chain_func ( sampler , pp , ** kwargs ) fig = None else : fig = _plot_chain_func ( sampler , p , ** kwargs ) return fig
Generate a diagnostic plot of the sampler chains .
32,423
def _read_or_calc_samples ( sampler , modelidx = 0 , n_samples = 100 , last_step = False , e_range = None , e_npoints = 100 , threads = None , ) : if not e_range : modelx , model = _process_blob ( sampler , modelidx , last_step = last_step ) else : e_range = validate_array ( "e_range" , u . Quantity ( e_range ) , physi...
Get samples from blob or compute them from chain and sampler . modelfn
32,424
def _calc_ML ( sampler , modelidx = 0 , e_range = None , e_npoints = 100 ) : ML , MLp , MLerr , ML_model = find_ML ( sampler , modelidx ) if e_range is not None : e_range = validate_array ( "e_range" , u . Quantity ( e_range ) , physical_type = "energy" ) e_unit = e_range . unit energy = ( np . logspace ( np . log10 ( ...
Get ML model from blob or compute them from chain and sampler . modelfn
32,425
def _plot_MLmodel ( ax , sampler , modelidx , e_range , e_npoints , e_unit , sed ) : ML , MLp , MLerr , ML_model = _calc_ML ( sampler , modelidx , e_range = e_range , e_npoints = e_npoints ) f_unit , sedf = sed_conversion ( ML_model [ 0 ] , ML_model [ 1 ] . unit , sed ) ax . loglog ( ML_model [ 0 ] . to ( e_unit ) . va...
compute and plot ML model
32,426
def plot_CI ( ax , sampler , modelidx = 0 , sed = True , confs = [ 3 , 1 , 0.5 ] , e_unit = u . eV , label = None , e_range = None , e_npoints = 100 , threads = None , last_step = False , ) : confs . sort ( reverse = True ) modelx , CI = _calc_CI ( sampler , modelidx = modelidx , confs = confs , e_range = e_range , e_n...
Plot confidence interval .
32,427
def plot_samples ( ax , sampler , modelidx = 0 , sed = True , n_samples = 100 , e_unit = u . eV , e_range = None , e_npoints = 100 , threads = None , label = None , last_step = False , ) : modelx , model = _read_or_calc_samples ( sampler , modelidx , last_step = last_step , e_range = e_range , e_npoints = e_npoints , t...
Plot a number of samples from the sampler chain .
32,428
def find_ML ( sampler , modelidx ) : index = np . unravel_index ( np . argmax ( sampler . lnprobability ) , sampler . lnprobability . shape ) MLp = sampler . chain [ index ] if modelidx is not None and hasattr ( sampler , "blobs" ) : blob = sampler . blobs [ index [ 1 ] ] [ index [ 0 ] ] [ modelidx ] if isinstance ( bl...
Find Maximum Likelihood parameters as those in the chain with a highest log probability .
32,429
def plot_blob ( sampler , blobidx = 0 , label = None , last_step = False , figure = None , ** kwargs ) : modelx , model = _process_blob ( sampler , blobidx , last_step ) if label is None : label = "Model output {0}" . format ( blobidx ) if modelx is None : f = plot_distribution ( model , label , figure = figure ) else ...
Plot a metadata blob as a fit to spectral data or value distribution
32,430
def _plot_ulims ( ax , x , y , xerr , color , capsize = 5 , height_fraction = 0.25 , elinewidth = 2 ) : ax . errorbar ( x , y , xerr = xerr , ls = "" , color = color , elinewidth = elinewidth , capsize = 0 ) from distutils . version import LooseVersion import matplotlib mpl_version = LooseVersion ( matplotlib . __versi...
Plot upper limits as arrows with cap at value of upper limit .
32,431
def plot_data ( input_data , xlabel = None , ylabel = None , sed = True , figure = None , e_unit = None , ulim_opts = { } , errorbar_opts = { } , ) : import matplotlib . pyplot as plt try : data = validate_data_table ( input_data ) except TypeError as exc : if hasattr ( input_data , "data" ) : data = input_data . data ...
Plot spectral data .
32,432
def plot_distribution ( samples , label , figure = None ) : from scipy import stats import matplotlib . pyplot as plt quant = [ 16 , 50 , 84 ] quantiles = dict ( six . moves . zip ( quant , np . percentile ( samples , quant ) ) ) std = np . std ( samples ) if isinstance ( samples [ 0 ] , u . Quantity ) : unit = samples...
Plot a distribution and print statistics about it
32,433
def plot_corner ( sampler , show_ML = True , ** kwargs ) : import matplotlib . pyplot as plt oldlw = plt . rcParams [ "lines.linewidth" ] plt . rcParams [ "lines.linewidth" ] = 0.7 try : from corner import corner if show_ML : _ , MLp , _ , _ = find_ML ( sampler , 0 ) else : MLp = None corner_opts = { "labels" : sampler...
A plot that summarizes the parameter samples by showing them as individual histograms and 2D histograms against each other . The maximum likelihood parameter vector is indicated by a cross .
32,434
def predict_given_context ( self , x , c , c_dims ) : assert len ( c ) == len ( c_dims ) _ , index = self . dataset . nn_dims ( x , c , range ( self . dim_x ) , list ( np . array ( c_dims ) + self . dim_x ) , k = 1 ) return self . dataset . get_y ( index [ 0 ] )
Provide a prediction of x with context c on dimensions c_dims in the output space being S - c_dims
32,435
def gen_front_term ( self , x , dmp_num ) : if isinstance ( x , np . ndarray ) : return np . ones ( x . shape ) return 1
Generates the front term on the forcing term . For rhythmic DMPs it s non - diminishing so this function is just a placeholder to return 1 .
32,436
def predict_y ( self , xq , sigma = None , k = None ) : assert len ( xq ) == self . dataset . dim_x sigma_sq = self . sigma_sq if sigma is None else sigma * sigma k = k or self . k dists , index = self . dataset . nn_x ( xq , k = k ) w = self . _weights ( dists , index , sigma_sq ) Xq = np . array ( np . append ( [ 1.0...
Provide a prediction of xq in the output space
32,437
def predict_dims ( self , q , dims_x , dims_y , dims_out , sigma = None , k = None ) : assert len ( q ) == len ( dims_x ) + len ( dims_y ) sigma_sq = self . sigma_sq if sigma is None else sigma * sigma k = k or self . k dists , index = self . dataset . nn_dims ( q [ : len ( dims_x ) ] , q [ len ( dims_x ) : ] , dims_x ...
Provide a prediction of q in the output space
32,438
def scatter_plot ( self , ax , topic_dims , t = None , ms_limits = True , ** kwargs_plot ) : plot_specs = { 'marker' : 'o' , 'linestyle' : 'None' } plot_specs . update ( kwargs_plot ) data = self . data_t ( topic_dims , t ) ax . plot ( * ( data . T ) , ** plot_specs ) if ms_limits : ax . axis ( self . axes_limits ( top...
2D or 3D scatter plot .
32,439
def get_nodes ( self ) : return self . fold_up ( lambda n , fl , fg : [ n ] + fl + fg , lambda leaf : [ leaf ] )
Get the list of all nodes .
32,440
def get_leaves ( self ) : return self . fold_up ( lambda n , fl , fg : fl + fg , lambda leaf : [ leaf ] )
Get the list of all leaves .
32,441
def pt2leaf ( self , x ) : if self . leafnode : return self else : if x [ self . split_dim ] < self . split_value : return self . lower . pt2leaf ( x ) else : return self . greater . pt2leaf ( x )
Get the leaf which domain contains x .
32,442
def sample_random ( self ) : if self . sampling_mode [ 'volume' ] : if self . leafnode : return self . sample_bounds ( ) else : split_ratio = ( ( self . split_value - self . bounds_x [ 0 , self . split_dim ] ) / ( self . bounds_x [ 1 , self . split_dim ] - self . bounds_x [ 0 , self . split_dim ] ) ) if split_ratio > n...
Sample a point in a random leaf .
32,443
def sample_greedy ( self ) : if self . leafnode : return self . sample_bounds ( ) else : lp = self . lower . max_leaf_progress gp = self . greater . max_leaf_progress maxp = max ( lp , gp ) if self . sampling_mode [ 'multiscale' ] : tp = self . progress if tp > maxp : return self . sample_bounds ( ) if gp == maxp : sam...
Sample a point in the leaf with the max progress .
32,444
def progress_all ( self ) : return self . progress_idxs ( range ( np . shape ( self . get_data_x ( ) ) [ 0 ] - self . progress_win_size , np . shape ( self . get_data_x ( ) ) [ 0 ] ) )
Competence progress of the overall tree .
32,445
def progress_idxs ( self , idxs ) : if self . progress_measure == 'abs_deriv_cov' : if len ( idxs ) <= 1 : return 0 else : idxs = sorted ( idxs ) [ - self . progress_win_size : ] return abs ( np . cov ( zip ( range ( len ( idxs ) ) , self . get_data_c ( ) [ idxs ] ) , rowvar = 0 ) [ 0 , 1 ] ) elif self . progress_measu...
Competence progress on points of given indexes .
32,446
def fold_up ( self , f_inter , f_leaf ) : return f_leaf ( self ) if self . leafnode else f_inter ( self , self . lower . fold_up ( f_inter , f_leaf ) , self . greater . fold_up ( f_inter , f_leaf ) )
Apply recursively the function f_inter from leaves to root begining with function f_leaf on leaves .
32,447
def f ( self , m ) : M = reshape ( m , self . input_dim ) n = M . shape [ 0 ] if M . shape [ 1 ] != self . input_dim : return 'Wrong input dimension' else : S = self . environment . update ( M ) m = M [ 0 ] s = S [ 0 ] self . pointsList . append ( ( m , s ) ) return self . dist_array ( S )
Function to minimize
32,448
def from_forward ( cls , fmodel , ** kwargs ) : im = cls ( fmodel . dim_x , fmodel . dim_y , ** kwargs ) im . fmodel = fmodel return im
Construst an inverse model from a forward model and constraints .
32,449
def _random_x ( self ) : return ( tuple ( random . random ( ) for _ in range ( self . fmodel . dim_x ) ) , )
If the database is empty generate a random vector .
32,450
def config ( self ) : return ", " . join ( '%s:%s' % ( key , value ) for key , value in self . conf . items ( ) )
Return a string with the configuration
32,451
def run ( self , n_iter = - 1 , bg = False ) : if n_iter == - 1 : if not self . eval_at : raise ValueError ( 'Set n_iter or define evaluate_at.' ) n_iter = self . eval_at [ - 1 ] + 1 self . _running . set ( ) if bg : self . _t = threading . Thread ( target = lambda : self . _run ( n_iter ) ) self . _t . start ( ) else ...
Run the experiment .
32,452
def evaluate_at ( self , eval_at , testcases , mode = None ) : self . eval_at = eval_at self . log . eval_at = eval_at if mode is None : if self . context_mode is None or ( self . context_mode . has_key ( 'choose_m' ) and self . context_mode [ 'choose_m' ] ) : mode = 'inverse' else : mode = self . context_mode [ "mode"...
Sets the evaluation interation indices .
32,453
def rollout ( self , ** kwargs ) : if kwargs . has_key ( 'tau' ) : timesteps = int ( self . timesteps / kwargs [ 'tau' ] ) else : timesteps = self . timesteps self . x_track = np . zeros ( timesteps ) self . reset_state ( ) for t in range ( timesteps ) : self . x_track [ t ] = self . x self . step ( ** kwargs ) return ...
Generate x for open loop movements .
32,454
def discrete_random_draw ( data , nb = 1 ) : data = np . array ( data ) if not data . any ( ) : data = np . ones_like ( data ) data = data / data . sum ( ) xk = np . arange ( len ( data ) ) custm = stats . rv_discrete ( name = 'custm' , values = ( xk , data ) ) return custm . rvs ( size = nb )
Code from Steve Nguyen
32,455
def from_dataset ( cls , dataset , constraints = ( ) , ** kwargs ) : fm = LWLRForwardModel ( dataset . dim_x , dataset . dim_y , ** kwargs ) fm . dataset = dataset im = cls . from_forward ( fm , constraints = constraints , ** kwargs ) return im
Construct a optimized inverse model from an existing dataset . A LWLR forward model is constructed by default .
32,456
def _setuplimits ( self , constraints ) : self . constraints = tuple ( constraints ) assert len ( self . constraints ) == self . fmodel . dim_x self . goal = None
Setup the limits for every initialiser .
32,457
def _error ( self , x ) : y_pred = self . fmodel . predict_y ( x ) err_v = y_pred - self . goal error = sum ( e * e for e in err_v ) return error
Error function . Once self . y_desired has been defined compute the error of input x using the forward model .
32,458
def _error_dm ( self , m , dm , s ) : pred = self . fmodel . predict_given_context ( np . hstack ( ( m , dm ) ) , s , range ( len ( s ) ) ) err_v = pred - self . goal error = sum ( e * e for e in err_v ) return error
Error function . Once self . goal has been defined compute the error of input using the generalized forward model .
32,459
def generate ( self , number = None ) : if number is None : return numpy . random . multivariate_normal ( self . mu , self . sigma ) else : return numpy . random . multivariate_normal ( self . mu , self . sigma , number )
Generates vectors from the Gaussian .
32,460
def log_normal ( self , x ) : d = self . mu . shape [ 0 ] xc = x - self . mu if len ( x . shape ) == 1 : exp_term = numpy . sum ( numpy . multiply ( xc , numpy . dot ( self . inv , xc ) ) ) else : exp_term = numpy . sum ( numpy . multiply ( xc , numpy . dot ( xc , self . inv ) ) , axis = 1 ) return - .5 * ( d * numpy ....
Returns the log density of probability of x or the one dimensional array of all log probabilities if many vectors are given .
32,461
def cond_gaussian ( self , dims , v ) : ( d , c , b , a ) = numpy . split_matrix ( self . sigma , dims ) ( mu2 , mu1 ) = numpy . split_vector ( self . mu , dims ) d_inv = numpy . linalg . inv ( d ) mu = mu1 + numpy . dot ( numpy . dot ( b , d_inv ) , v - mu2 ) sigma = a - numpy . dot ( b , numpy . dot ( d_inv , c ) ) r...
Returns mean and variance of the conditional probability defined by a set of dimension and at a given vector .
32,462
def from_configuration ( cls , env_name , config_name = 'default' ) : env_cls , env_configs , _ = environments [ env_name ] return env_cls ( ** env_configs [ config_name ] )
Environment factory from name and configuration strings .
32,463
def update ( self , m_ag , reset = True , log = True ) : if reset : self . reset ( ) if len ( array ( m_ag ) . shape ) == 1 : s = self . one_update ( m_ag , log ) else : s = [ ] for m in m_ag : s . append ( self . one_update ( m , log ) ) s = array ( s ) return s
Computes sensorimotor values from motor orders .
32,464
def reset ( self ) : self . data = [ ] self . size = 0 self . kdtree = None self . nn_ready = False
Reset the dataset to zero elements .
32,465
def _build_tree ( self ) : if not self . nn_ready : self . kdtree = scipy . spatial . cKDTree ( self . data ) self . nn_ready = True
Build the KDTree for the observed data
32,466
def from_data ( cls , data ) : if len ( data ) == 0 : raise ValueError ( "data array is empty." ) dim_x , dim_y = len ( data [ 0 ] [ 0 ] ) , len ( data [ 0 ] [ 1 ] ) dataset = cls ( dim_x , dim_y ) for x , y in data : assert len ( x ) == dim_x and len ( y ) == dim_y dataset . add_xy ( x , y ) return dataset
Create a dataset from an array of data infering the dimension from the datapoint
32,467
def from_xy ( cls , x_array , y_array ) : if len ( x_array ) == 0 : raise ValueError ( "data array is empty." ) dim_x , dim_y = len ( x_array [ 0 ] ) , len ( y_array [ 0 ] ) dataset = cls ( dim_x , dim_y ) for x , y in zip ( x_array , y_array ) : assert len ( x ) == dim_x and len ( y ) == dim_y dataset . add_xy ( x , y...
Create a dataset from two arrays of data .
32,468
def nn_x ( self , x , k = 1 , radius = np . inf , eps = 0.0 , p = 2 ) : assert len ( x ) == self . dim_x k_x = min ( k , self . size ) return self . _nn ( DATA_X , x , k = k_x , radius = radius , eps = eps , p = p )
Find the k nearest neighbors of x in the observed input data
32,469
def from_classes ( cls , im_model_cls , im_model_config , expl_dims , sm_model_cls , sm_model_config , inf_dims , m_mins , m_maxs , s_mins , s_maxs , n_bootstrap = 0 , context_mode = None ) : conf = make_configuration ( m_mins , m_maxs , s_mins , s_maxs ) sm_model = sm_model_cls ( conf , ** sm_model_config ) im_model =...
Initialize agent class
32,470
def choose ( self , context_ms = None ) : try : if self . context_mode is None : x = self . interest_model . sample ( ) else : if self . context_mode [ "mode" ] == 'mdmsds' : if self . expl_dims == self . conf . s_dims : x = np . hstack ( ( context_ms [ self . conf . m_ndims // 2 : ] , self . interest_model . sample_gi...
Returns a point chosen by the interest model
32,471
def infer ( self , expl_dims , inf_dims , x ) : try : if self . n_bootstrap > 0 : self . n_bootstrap -= 1 raise ExplautoBootstrapError y = self . sensorimotor_model . infer ( expl_dims , inf_dims , x . flatten ( ) ) except ExplautoBootstrapError : logger . warning ( 'Sensorimotor model not bootstrapped yet' ) y = rand_...
Use the sensorimotor model to compute the expected value on inf_dims given that the value on expl_dims is x .
32,472
def compute_motor_command ( self , m_ag ) : m_env = bounds_min_max ( m_ag , self . conf . m_mins , self . conf . m_maxs ) return m_env
Compute the motor command by restricting it to the bounds .
32,473
def compute_sensori_effect ( self , m_env ) : pos = { m . name : pos for m , pos in zip ( self . motors , m_env ) } self . robot . goto_position ( pos , self . move_duration , wait = True ) if self . tracker is not None : return self . tracker . get_object_position ( self . tracked_obj )
Move the robot motors and retrieve the tracked object position .
32,474
def infer_order ( self , goal , ** kwargs ) : x = self . imodel . infer_x ( np . array ( self . _pre_y ( goal ) ) , ** kwargs ) [ 0 ] return self . _post_x ( x , goal )
Infer an order in order to obtain an effect close to goal given the observation data of the model .
32,475
def predict_effect ( self , order , ** kwargs ) : y = self . imodel . fmodel . predict_y ( np . array ( self . _pre_x ( order ) ) , ** kwargs ) return self . _post_y ( y , order )
Predict the effect of a goal .
32,476
def _enforce_bounds ( self , x ) : assert len ( x ) == len ( self . bounds ) x_enforced = [ ] for x_i , ( lb , ub ) in zip ( x , self . bounds ) : if x_i < lb : if x_i > lb - ( ub - lb ) / 1e10 : x_enforced . append ( lb ) else : x_enforced . append ( x_i ) elif x_i > ub : if x_i < ub + ( ub - lb ) / 1e10 : x_enforced ...
Enforce the bounds on x if only infinitesimal violations occurs
32,477
def fit ( self , counts_df , val_set = None ) : if self . stop_crit == 'val-llk' : if val_set is None : raise ValueError ( "If 'stop_crit' is set to 'val-llk', must provide a validation set." ) if self . verbose : self . _print_st_msg ( ) self . _process_data ( counts_df ) if self . verbose : self . _print_data_info ( ...
Fit Hierarchical Poisson Model to sparse count data
32,478
def predict_factors ( self , counts_df , maxiter = 10 , ncores = 1 , random_seed = 1 , stop_thr = 1e-3 , return_all = False ) : ncores , random_seed , stop_thr , maxiter = self . _check_input_predict_factors ( ncores , random_seed , stop_thr , maxiter ) counts_df = self . _process_data_single ( counts_df ) Theta = np ....
Gets latent factors for a user given her item counts
32,479
def infer_x ( self , y_desired , ** kwargs ) : sigma = kwargs . get ( 'sigma' , self . sigma ) k = kwargs . get ( 'k' , self . k ) xq = self . _guess_x ( y_desired , k = k , sigma = sigma , ** kwargs ) [ 0 ] dists , index = self . fmodel . dataset . nn_x ( xq , k = k ) w = self . fmodel . _weights ( dists , sigma * sig...
Provide an inversion of yq in the input space
32,480
def from_settings_product ( cls , environments , babblings , interest_models , sensorimotor_models , evaluate_at , testcases = None , same_testcases = False ) : l = itertools . product ( environments , babblings , interest_models , sensorimotor_models ) settings = [ make_settings ( env , bab , im , sm , env_conf , im_c...
Creates a ExperimentPool with the product of all the given settings .
32,481
def compute_sensori_effect ( self , m ) : if self . use_basis_functions : func = simulation . step ( m , 1000 * self . dt ) else : traj = self . bf . trajectory ( m ) . flatten ( ) func = lambda t : traj [ int ( 1000 * self . dt * t ) ] states = simulation . simulate ( self . n , self . x0 , self . dt , func ) last_sta...
This function generates the end effector position at the end of the movement .
32,482
def animate_pendulum ( self , m , path = "anim_npendulum" ) : if os . path . exists ( path ) : shutil . rmtree ( path ) os . makedirs ( path ) for t in range ( 0 , 1000 , 32 ) : ax = axes ( ) self . plot_npendulum ( ax , m , t ) savefig ( os . path . join ( path , "{}.png" . format ( t ) ) ) clf ( )
This function generates few images at different instants in order to animate the pendulum .
32,483
def _fileToMatrix ( file_name ) : if 1 < 3 : lres = [ ] for line in open ( file_name , 'r' ) . readlines ( ) : if len ( line ) > 0 and line [ 0 ] not in ( '%' , '#' ) : lres . append ( list ( map ( float , line . split ( ) ) ) ) res = lres while res != [ ] and res [ 0 ] == [ ] : del res [ 0 ] return res print ( 'could ...
rudimentary method to read in data from a file
32,484
def pprint ( to_be_printed ) : try : import pprint as pp pp . pprint ( to_be_printed ) except ImportError : if isinstance ( to_be_printed , dict ) : print ( '{' ) for k , v in to_be_printed . items ( ) : print ( "'" + k + "'" if isinstance ( k , basestring ) else k , ': ' , "'" + v + "'" if isinstance ( k , basestring ...
nicely formated print
32,485
def felli ( x ) : return sum ( 1e6 ** ( np . arange ( len ( x ) ) / ( len ( x ) - 1 ) ) * ( np . array ( x , copy = False ) ) ** 2 )
unbound test function needed to test multiprocessor
32,486
def update ( self , arx , xarchive = None , arf = None , evals = None ) : if isinstance ( arx , BestSolution ) : if self . evalsall is None : self . evalsall = arx . evalsall elif arx . evalsall is not None : self . evalsall = max ( ( self . evalsall , arx . evalsall ) ) if arx . f is not None and arx . f < np . inf : ...
checks for better solutions in list arx .
32,487
def repair ( self , x , copy_if_changed = True , copy_always = False ) : if copy_always : x = array ( x , copy = True ) copy = False else : copy = copy_if_changed if self . bounds is None : return x for ib in [ 0 , 1 ] : if self . bounds [ ib ] is None : continue for i in rglen ( x ) : idx = min ( [ i , len ( self . bo...
projects infeasible values on the domain bound might be overwritten by derived class
32,488
def has_bounds ( self ) : bounds = self . bounds if bounds in ( None , [ None , None ] ) : return False for ib , bound in enumerate ( bounds ) : if bound is not None : sign_ = 2 * ib - 1 for bound_i in bound : if bound_i is not None and sign_ * bound_i < np . inf : return True return False
return True if any variable is bounded
32,489
def is_in_bounds ( self , x ) : if self . bounds is None : return True for ib in [ 0 , 1 ] : if self . bounds [ ib ] is None : continue for i in rglen ( x ) : idx = min ( [ i , len ( self . bounds [ ib ] ) - 1 ] ) if self . bounds [ ib ] [ idx ] is not None and ( - 1 ) ** ib * x [ i ] < ( - 1 ) ** ib * self . bounds [ ...
not yet tested
32,490
def repair ( self , x , copy_if_changed = True , copy_always = False ) : copy = copy_if_changed if copy_always : x = array ( x , copy = True ) copy = False if self . bounds is None or ( self . bounds [ 0 ] is None and self . bounds [ 1 ] is None ) : return x return self . bounds_tf ( x , copy )
transforms x into the bounded domain .
32,491
def repair ( self , x , copy_if_changed = True , copy_always = False ) : copy = copy_if_changed if copy_always : x = array ( x , copy = True ) bounds = self . bounds if bounds not in ( None , [ None , None ] , ( None , None ) ) : x = array ( x , copy = True ) if copy and not copy_always else x if bounds [ 0 ] is not No...
sets out - of - bounds components of x on the bounds .
32,492
def update ( self , function_values , es ) : if self . bounds is None or ( self . bounds [ 0 ] is None and self . bounds [ 1 ] is None ) : return self N = es . N varis = es . sigma ** 2 * array ( N * [ es . C ] if isscalar ( es . C ) else ( es . C if isscalar ( es . C [ 0 ] ) else [ es . C [ i ] [ i ] for i in xrange (...
updates the weights for computing a boundary penalty .
32,493
def initialize ( self ) : self . _lb = [ b [ 0 ] for b in self . bounds ] self . _ub = [ b [ 1 ] for b in self . bounds ]
initialize in base class
32,494
def is_feasible_i ( self , x , i ) : lb = self . _lb [ self . _index ( i ) ] ub = self . _ub [ self . _index ( i ) ] al = self . _al [ self . _index ( i ) ] au = self . _au [ self . _index ( i ) ] return lb - al < x < ub + au
return True if value x is in the invertible domain of variable i
32,495
def _transform_i ( self , x , i ) : x = self . _shift_or_mirror_into_invertible_i ( x , i ) lb = self . _lb [ self . _index ( i ) ] ub = self . _ub [ self . _index ( i ) ] al = self . _al [ self . _index ( i ) ] au = self . _au [ self . _index ( i ) ] if x < lb + al : return lb + ( x - ( lb - al ) ) ** 2 / 4 / al elif ...
return transform of x in component i
32,496
def _inverse_i ( self , y , i ) : lb = self . _lb [ self . _index ( i ) ] ub = self . _ub [ self . _index ( i ) ] al = self . _al [ self . _index ( i ) ] au = self . _au [ self . _index ( i ) ] if 1 < 3 : if not lb <= y <= ub : raise ValueError ( 'argument of inverse must be within the given bounds' ) if y < lb + al : ...
return inverse of y in component i
32,497
def pheno ( self , x , into_bounds = None , copy = True , copy_always = False , archive = None , iteration = None ) : input_type = type ( x ) if into_bounds is None : into_bounds = ( lambda x , copy = False : x if not copy else array ( x , copy = copy ) ) if copy_always and not copy : raise ValueError ( 'arguments copy...
maps the genotypic input argument into the phenotypic space see help for class GenoPheno
32,498
def geno ( self , y , from_bounds = None , copy_if_changed = True , copy_always = False , repair = None , archive = None ) : if from_bounds is None : from_bounds = lambda x , copy = False : x if archive is not None : try : x = archive [ y ] [ 'geno' ] except ( KeyError , TypeError ) : x = None if x is not None : if arc...
maps the phenotypic input argument into the genotypic space that is computes essentially the inverse of pheno .
32,499
def optimize ( self , objective_fct , iterations = None , min_iterations = 1 , args = ( ) , verb_disp = None , logger = None , call_back = None ) : assert iterations is None or min_iterations <= iterations if not hasattr ( self , 'logger' ) : self . logger = logger logger = self . logger = logger or self . logger if no...
find minimizer of objective_fct .