id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
242,000
SheffieldML/GPyOpt
GPyOpt/acquisitions/LP.py
AcquisitionLP.d_acquisition_function
def d_acquisition_function(self, x): """ Returns the gradient of the acquisition function at x. """ x = np.atleast_2d(x) if self.transform=='softplus': fval = -self.acq.acquisition_function(x)[:,0] scale = 1./(np.log1p(np.exp(fval))*(1.+np.exp(-fval))) ...
python
def d_acquisition_function(self, x): x = np.atleast_2d(x) if self.transform=='softplus': fval = -self.acq.acquisition_function(x)[:,0] scale = 1./(np.log1p(np.exp(fval))*(1.+np.exp(-fval))) elif self.transform=='none': fval = -self.acq.acquisition_function(x)...
[ "def", "d_acquisition_function", "(", "self", ",", "x", ")", ":", "x", "=", "np", ".", "atleast_2d", "(", "x", ")", "if", "self", ".", "transform", "==", "'softplus'", ":", "fval", "=", "-", "self", ".", "acq", ".", "acquisition_function", "(", "x", ...
Returns the gradient of the acquisition function at x.
[ "Returns", "the", "gradient", "of", "the", "acquisition", "function", "at", "x", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LP.py#L112-L132
242,001
SheffieldML/GPyOpt
GPyOpt/acquisitions/LP.py
AcquisitionLP.acquisition_function_withGradients
def acquisition_function_withGradients(self, x): """ Returns the acquisition function and its its gradient at x. """ aqu_x = self.acquisition_function(x) aqu_x_grad = self.d_acquisition_function(x) return aqu_x, aqu_x_grad
python
def acquisition_function_withGradients(self, x): aqu_x = self.acquisition_function(x) aqu_x_grad = self.d_acquisition_function(x) return aqu_x, aqu_x_grad
[ "def", "acquisition_function_withGradients", "(", "self", ",", "x", ")", ":", "aqu_x", "=", "self", ".", "acquisition_function", "(", "x", ")", "aqu_x_grad", "=", "self", ".", "d_acquisition_function", "(", "x", ")", "return", "aqu_x", ",", "aqu_x_grad" ]
Returns the acquisition function and its its gradient at x.
[ "Returns", "the", "acquisition", "function", "and", "its", "its", "gradient", "at", "x", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LP.py#L134-L140
242,002
SheffieldML/GPyOpt
GPyOpt/acquisitions/base.py
AcquisitionBase.acquisition_function
def acquisition_function(self,x): """ Takes an acquisition and weights it so the domain and cost are taken into account. """ f_acqu = self._compute_acq(x) cost_x, _ = self.cost_withGradients(x) return -(f_acqu*self.space.indicator_constraints(x))/cost_x
python
def acquisition_function(self,x): f_acqu = self._compute_acq(x) cost_x, _ = self.cost_withGradients(x) return -(f_acqu*self.space.indicator_constraints(x))/cost_x
[ "def", "acquisition_function", "(", "self", ",", "x", ")", ":", "f_acqu", "=", "self", ".", "_compute_acq", "(", "x", ")", "cost_x", ",", "_", "=", "self", ".", "cost_withGradients", "(", "x", ")", "return", "-", "(", "f_acqu", "*", "self", ".", "spa...
Takes an acquisition and weights it so the domain and cost are taken into account.
[ "Takes", "an", "acquisition", "and", "weights", "it", "so", "the", "domain", "and", "cost", "are", "taken", "into", "account", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/base.py#L33-L39
242,003
SheffieldML/GPyOpt
GPyOpt/acquisitions/base.py
AcquisitionBase.acquisition_function_withGradients
def acquisition_function_withGradients(self, x): """ Takes an acquisition and it gradient and weights it so the domain and cost are taken into account. """ f_acqu,df_acqu = self._compute_acq_withGradients(x) cost_x, cost_grad_x = self.cost_withGradients(x) f_acq_cost = f_...
python
def acquisition_function_withGradients(self, x): f_acqu,df_acqu = self._compute_acq_withGradients(x) cost_x, cost_grad_x = self.cost_withGradients(x) f_acq_cost = f_acqu/cost_x df_acq_cost = (df_acqu*cost_x - f_acqu*cost_grad_x)/(cost_x**2) return -f_acq_cost*self.space.indicator...
[ "def", "acquisition_function_withGradients", "(", "self", ",", "x", ")", ":", "f_acqu", ",", "df_acqu", "=", "self", ".", "_compute_acq_withGradients", "(", "x", ")", "cost_x", ",", "cost_grad_x", "=", "self", ".", "cost_withGradients", "(", "x", ")", "f_acq_c...
Takes an acquisition and it gradient and weights it so the domain and cost are taken into account.
[ "Takes", "an", "acquisition", "and", "it", "gradient", "and", "weights", "it", "so", "the", "domain", "and", "cost", "are", "taken", "into", "account", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/base.py#L42-L50
242,004
SheffieldML/GPyOpt
GPyOpt/util/general.py
reshape
def reshape(x,input_dim): ''' Reshapes x into a matrix with input_dim columns ''' x = np.array(x) if x.size ==input_dim: x = x.reshape((1,input_dim)) return x
python
def reshape(x,input_dim): ''' Reshapes x into a matrix with input_dim columns ''' x = np.array(x) if x.size ==input_dim: x = x.reshape((1,input_dim)) return x
[ "def", "reshape", "(", "x", ",", "input_dim", ")", ":", "x", "=", "np", ".", "array", "(", "x", ")", "if", "x", ".", "size", "==", "input_dim", ":", "x", "=", "x", ".", "reshape", "(", "(", "1", ",", "input_dim", ")", ")", "return", "x" ]
Reshapes x into a matrix with input_dim columns
[ "Reshapes", "x", "into", "a", "matrix", "with", "input_dim", "columns" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/general.py#L76-L84
242,005
SheffieldML/GPyOpt
GPyOpt/util/general.py
spawn
def spawn(f): ''' Function for parallel evaluation of the acquisition function ''' def fun(pipe,x): pipe.send(f(x)) pipe.close() return fun
python
def spawn(f): ''' Function for parallel evaluation of the acquisition function ''' def fun(pipe,x): pipe.send(f(x)) pipe.close() return fun
[ "def", "spawn", "(", "f", ")", ":", "def", "fun", "(", "pipe", ",", "x", ")", ":", "pipe", ".", "send", "(", "f", "(", "x", ")", ")", "pipe", ".", "close", "(", ")", "return", "fun" ]
Function for parallel evaluation of the acquisition function
[ "Function", "for", "parallel", "evaluation", "of", "the", "acquisition", "function" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/general.py#L144-L151
242,006
SheffieldML/GPyOpt
GPyOpt/util/general.py
values_to_array
def values_to_array(input_values): ''' Transforms a values of int, float and tuples to a column vector numpy array ''' if type(input_values)==tuple: values = np.array(input_values).reshape(-1,1) elif type(input_values) == np.ndarray: values = np.atleast_2d(input_values) elif type...
python
def values_to_array(input_values): ''' Transforms a values of int, float and tuples to a column vector numpy array ''' if type(input_values)==tuple: values = np.array(input_values).reshape(-1,1) elif type(input_values) == np.ndarray: values = np.atleast_2d(input_values) elif type...
[ "def", "values_to_array", "(", "input_values", ")", ":", "if", "type", "(", "input_values", ")", "==", "tuple", ":", "values", "=", "np", ".", "array", "(", "input_values", ")", ".", "reshape", "(", "-", "1", ",", "1", ")", "elif", "type", "(", "inpu...
Transforms a values of int, float and tuples to a column vector numpy array
[ "Transforms", "a", "values", "of", "int", "float", "and", "tuples", "to", "a", "column", "vector", "numpy", "array" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/general.py#L168-L180
242,007
SheffieldML/GPyOpt
GPyOpt/util/general.py
merge_values
def merge_values(values1,values2): ''' Merges two numpy arrays by calculating all possible combinations of rows ''' array1 = values_to_array(values1) array2 = values_to_array(values2) if array1.size == 0: return array2 if array2.size == 0: return array1 merged_array = [...
python
def merge_values(values1,values2): ''' Merges two numpy arrays by calculating all possible combinations of rows ''' array1 = values_to_array(values1) array2 = values_to_array(values2) if array1.size == 0: return array2 if array2.size == 0: return array1 merged_array = [...
[ "def", "merge_values", "(", "values1", ",", "values2", ")", ":", "array1", "=", "values_to_array", "(", "values1", ")", "array2", "=", "values_to_array", "(", "values2", ")", "if", "array1", ".", "size", "==", "0", ":", "return", "array2", "if", "array2", ...
Merges two numpy arrays by calculating all possible combinations of rows
[ "Merges", "two", "numpy", "arrays", "by", "calculating", "all", "possible", "combinations", "of", "rows" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/general.py#L183-L200
242,008
SheffieldML/GPyOpt
GPyOpt/util/general.py
normalize
def normalize(Y, normalization_type='stats'): """Normalize the vector Y using statistics or its range. :param Y: Row or column vector that you want to normalize. :param normalization_type: String specifying the kind of normalization to use. Options are 'stats' to use mean and standard deviation, or...
python
def normalize(Y, normalization_type='stats'): Y = np.asarray(Y, dtype=float) if np.max(Y.shape) != Y.size: raise NotImplementedError('Only 1-dimensional arrays are supported.') # Only normalize with non null sdev (divide by zero). For only one # data point both std and ptp return 0. if nor...
[ "def", "normalize", "(", "Y", ",", "normalization_type", "=", "'stats'", ")", ":", "Y", "=", "np", ".", "asarray", "(", "Y", ",", "dtype", "=", "float", ")", "if", "np", ".", "max", "(", "Y", ".", "shape", ")", "!=", "Y", ".", "size", ":", "rai...
Normalize the vector Y using statistics or its range. :param Y: Row or column vector that you want to normalize. :param normalization_type: String specifying the kind of normalization to use. Options are 'stats' to use mean and standard deviation, or 'maxmin' to use the range of function values. :r...
[ "Normalize", "the", "vector", "Y", "using", "statistics", "or", "its", "range", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/general.py#L203-L234
242,009
SheffieldML/GPyOpt
GPyOpt/experiment_design/grid_design.py
GridDesign.get_samples
def get_samples(self, init_points_count): """ This method may return less points than requested. The total number of generated points is the smallest closest integer of n^d to the selected amount of points. """ init_points_count = self._adjust_init_points_count(init_points_count...
python
def get_samples(self, init_points_count): init_points_count = self._adjust_init_points_count(init_points_count) samples = np.empty((init_points_count, self.space.dimensionality)) # Use random design to fill non-continuous variables random_design = RandomDesign(self.space) random...
[ "def", "get_samples", "(", "self", ",", "init_points_count", ")", ":", "init_points_count", "=", "self", ".", "_adjust_init_points_count", "(", "init_points_count", ")", "samples", "=", "np", ".", "empty", "(", "(", "init_points_count", ",", "self", ".", "space"...
This method may return less points than requested. The total number of generated points is the smallest closest integer of n^d to the selected amount of points.
[ "This", "method", "may", "return", "less", "points", "than", "requested", ".", "The", "total", "number", "of", "generated", "points", "is", "the", "smallest", "closest", "integer", "of", "n^d", "to", "the", "selected", "amount", "of", "points", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/experiment_design/grid_design.py#L26-L43
242,010
SheffieldML/GPyOpt
GPyOpt/experiment_design/random_design.py
RandomDesign.get_samples_with_constraints
def get_samples_with_constraints(self, init_points_count): """ Draw random samples and only save those that satisfy constraints Finish when required number of samples is generated """ samples = np.empty((0, self.space.dimensionality)) while samples.shape[0] < init_points...
python
def get_samples_with_constraints(self, init_points_count): samples = np.empty((0, self.space.dimensionality)) while samples.shape[0] < init_points_count: domain_samples = self.get_samples_without_constraints(init_points_count) valid_indices = (self.space.indicator_constraints(do...
[ "def", "get_samples_with_constraints", "(", "self", ",", "init_points_count", ")", ":", "samples", "=", "np", ".", "empty", "(", "(", "0", ",", "self", ".", "space", ".", "dimensionality", ")", ")", "while", "samples", ".", "shape", "[", "0", "]", "<", ...
Draw random samples and only save those that satisfy constraints Finish when required number of samples is generated
[ "Draw", "random", "samples", "and", "only", "save", "those", "that", "satisfy", "constraints", "Finish", "when", "required", "number", "of", "samples", "is", "generated" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/experiment_design/random_design.py#L21-L35
242,011
SheffieldML/GPyOpt
GPyOpt/experiment_design/random_design.py
RandomDesign.fill_noncontinous_variables
def fill_noncontinous_variables(self, samples): """ Fill sample values to non-continuous variables in place """ init_points_count = samples.shape[0] for (idx, var) in enumerate(self.space.space_expanded): if isinstance(var, DiscreteVariable) or isinstance(var, Catego...
python
def fill_noncontinous_variables(self, samples): init_points_count = samples.shape[0] for (idx, var) in enumerate(self.space.space_expanded): if isinstance(var, DiscreteVariable) or isinstance(var, CategoricalVariable) : sample_var = np.atleast_2d(np.random.choice(var.domain,...
[ "def", "fill_noncontinous_variables", "(", "self", ",", "samples", ")", ":", "init_points_count", "=", "samples", ".", "shape", "[", "0", "]", "for", "(", "idx", ",", "var", ")", "in", "enumerate", "(", "self", ".", "space", ".", "space_expanded", ")", "...
Fill sample values to non-continuous variables in place
[ "Fill", "sample", "values", "to", "non", "-", "continuous", "variables", "in", "place" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/experiment_design/random_design.py#L37-L53
242,012
SheffieldML/GPyOpt
GPyOpt/interface/driver.py
BODriver._get_obj
def _get_obj(self,space): """ Imports the acquisition function. """ obj_func = self.obj_func from ..core.task import SingleObjective return SingleObjective(obj_func, self.config['resources']['cores'], space=space, unfold_args=True)
python
def _get_obj(self,space): obj_func = self.obj_func from ..core.task import SingleObjective return SingleObjective(obj_func, self.config['resources']['cores'], space=space, unfold_args=True)
[ "def", "_get_obj", "(", "self", ",", "space", ")", ":", "obj_func", "=", "self", ".", "obj_func", "from", ".", ".", "core", ".", "task", "import", "SingleObjective", "return", "SingleObjective", "(", "obj_func", ",", "self", ".", "config", "[", "'resources...
Imports the acquisition function.
[ "Imports", "the", "acquisition", "function", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L24-L32
242,013
SheffieldML/GPyOpt
GPyOpt/interface/driver.py
BODriver._get_space
def _get_space(self): """ Imports the domain. """ assert 'space' in self.config, 'The search space is NOT configured!' space_config = self.config['space'] constraint_config = self.config['constraints'] from ..core.task.space import Design_space re...
python
def _get_space(self): assert 'space' in self.config, 'The search space is NOT configured!' space_config = self.config['space'] constraint_config = self.config['constraints'] from ..core.task.space import Design_space return Design_space.fromConfig(space_config, constrain...
[ "def", "_get_space", "(", "self", ")", ":", "assert", "'space'", "in", "self", ".", "config", ",", "'The search space is NOT configured!'", "space_config", "=", "self", ".", "config", "[", "'space'", "]", "constraint_config", "=", "self", ".", "config", "[", "...
Imports the domain.
[ "Imports", "the", "domain", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L34-L43
242,014
SheffieldML/GPyOpt
GPyOpt/interface/driver.py
BODriver._get_model
def _get_model(self): """ Imports the model. """ from copy import deepcopy model_args = deepcopy(self.config['model']) del model_args['type'] from ..models import select_model return select_model(self.config['model']['type']).fromConfig(model_arg...
python
def _get_model(self): from copy import deepcopy model_args = deepcopy(self.config['model']) del model_args['type'] from ..models import select_model return select_model(self.config['model']['type']).fromConfig(model_args)
[ "def", "_get_model", "(", "self", ")", ":", "from", "copy", "import", "deepcopy", "model_args", "=", "deepcopy", "(", "self", ".", "config", "[", "'model'", "]", ")", "del", "model_args", "[", "'type'", "]", "from", ".", ".", "models", "import", "select_...
Imports the model.
[ "Imports", "the", "model", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L45-L55
242,015
SheffieldML/GPyOpt
GPyOpt/interface/driver.py
BODriver._get_acquisition
def _get_acquisition(self, model, space): """ Imports the acquisition """ from copy import deepcopy acqOpt_config = deepcopy(self.config['acquisition']['optimizer']) acqOpt_name = acqOpt_config['name'] del acqOpt_config['name'] from ..opt...
python
def _get_acquisition(self, model, space): from copy import deepcopy acqOpt_config = deepcopy(self.config['acquisition']['optimizer']) acqOpt_name = acqOpt_config['name'] del acqOpt_config['name'] from ..optimization import AcquisitionOptimizer acqOpt = Ac...
[ "def", "_get_acquisition", "(", "self", ",", "model", ",", "space", ")", ":", "from", "copy", "import", "deepcopy", "acqOpt_config", "=", "deepcopy", "(", "self", ".", "config", "[", "'acquisition'", "]", "[", "'optimizer'", "]", ")", "acqOpt_name", "=", "...
Imports the acquisition
[ "Imports", "the", "acquisition" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L58-L71
242,016
SheffieldML/GPyOpt
GPyOpt/interface/driver.py
BODriver._get_acq_evaluator
def _get_acq_evaluator(self, acq): """ Imports the evaluator """ from ..core.evaluators import select_evaluator from copy import deepcopy eval_args = deepcopy(self.config['acquisition']['evaluator']) del eval_args['type'] return select_evaluator(self.conf...
python
def _get_acq_evaluator(self, acq): from ..core.evaluators import select_evaluator from copy import deepcopy eval_args = deepcopy(self.config['acquisition']['evaluator']) del eval_args['type'] return select_evaluator(self.config['acquisition']['evaluator']['type'])(acq, **eval_arg...
[ "def", "_get_acq_evaluator", "(", "self", ",", "acq", ")", ":", "from", ".", ".", "core", ".", "evaluators", "import", "select_evaluator", "from", "copy", "import", "deepcopy", "eval_args", "=", "deepcopy", "(", "self", ".", "config", "[", "'acquisition'", "...
Imports the evaluator
[ "Imports", "the", "evaluator" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L73-L82
242,017
SheffieldML/GPyOpt
GPyOpt/interface/driver.py
BODriver._check_stop
def _check_stop(self, iters, elapsed_time, converged): """ Defines the stopping criterion. """ r_c = self.config['resources'] stop = False if converged==0: stop=True if r_c['maximum-iterations'] !='NA' and iters>= r_c['maximum-iterations']: ...
python
def _check_stop(self, iters, elapsed_time, converged): r_c = self.config['resources'] stop = False if converged==0: stop=True if r_c['maximum-iterations'] !='NA' and iters>= r_c['maximum-iterations']: stop = True if r_c['max-run-time'] != 'NA' and...
[ "def", "_check_stop", "(", "self", ",", "iters", ",", "elapsed_time", ",", "converged", ")", ":", "r_c", "=", "self", ".", "config", "[", "'resources'", "]", "stop", "=", "False", "if", "converged", "==", "0", ":", "stop", "=", "True", "if", "r_c", "...
Defines the stopping criterion.
[ "Defines", "the", "stopping", "criterion", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L84-L98
242,018
SheffieldML/GPyOpt
GPyOpt/interface/driver.py
BODriver.run
def run(self): """ Runs the optimization using the previously loaded elements. """ space = self._get_space() obj_func = self._get_obj(space) model = self._get_model() acq = self._get_acquisition(model, space) acq_eval = self._get_acq_evaluator(acq) ...
python
def run(self): space = self._get_space() obj_func = self._get_obj(space) model = self._get_model() acq = self._get_acquisition(model, space) acq_eval = self._get_acq_evaluator(acq) from ..experiment_design import initial_design X_init = initial_de...
[ "def", "run", "(", "self", ")", ":", "space", "=", "self", ".", "_get_space", "(", ")", "obj_func", "=", "self", ".", "_get_obj", "(", "space", ")", "model", "=", "self", ".", "_get_model", "(", ")", "acq", "=", "self", ".", "_get_acquisition", "(", ...
Runs the optimization using the previously loaded elements.
[ "Runs", "the", "optimization", "using", "the", "previously", "loaded", "elements", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/driver.py#L100-L119
242,019
SheffieldML/GPyOpt
GPyOpt/optimization/optimizer.py
choose_optimizer
def choose_optimizer(optimizer_name, bounds): """ Selects the type of local optimizer """ if optimizer_name == 'lbfgs': optimizer = OptLbfgs(bounds) elif optimizer_name == 'DIRECT': optimizer = OptDirect(bounds) elif optimizer_name == 'CMA': ...
python
def choose_optimizer(optimizer_name, bounds): if optimizer_name == 'lbfgs': optimizer = OptLbfgs(bounds) elif optimizer_name == 'DIRECT': optimizer = OptDirect(bounds) elif optimizer_name == 'CMA': optimizer = OptCma(bounds) else: raise I...
[ "def", "choose_optimizer", "(", "optimizer_name", ",", "bounds", ")", ":", "if", "optimizer_name", "==", "'lbfgs'", ":", "optimizer", "=", "OptLbfgs", "(", "bounds", ")", "elif", "optimizer_name", "==", "'DIRECT'", ":", "optimizer", "=", "OptDirect", "(", "bou...
Selects the type of local optimizer
[ "Selects", "the", "type", "of", "local", "optimizer" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/optimization/optimizer.py#L238-L253
242,020
SheffieldML/GPyOpt
GPyOpt/util/arguments_manager.py
ArgumentsManager.evaluator_creator
def evaluator_creator(self, evaluator_type, acquisition, batch_size, model_type, model, space, acquisition_optimizer): """ Acquisition chooser from the available options. Guide the optimization through sequential or parallel evalutions of the objective. """ acquisition_transformation = s...
python
def evaluator_creator(self, evaluator_type, acquisition, batch_size, model_type, model, space, acquisition_optimizer): acquisition_transformation = self.kwargs.get('acquisition_transformation','none') if batch_size == 1 or evaluator_type == 'sequential': return Sequential(acquisition) ...
[ "def", "evaluator_creator", "(", "self", ",", "evaluator_type", ",", "acquisition", ",", "batch_size", ",", "model_type", ",", "model", ",", "space", ",", "acquisition_optimizer", ")", ":", "acquisition_transformation", "=", "self", ".", "kwargs", ".", "get", "(...
Acquisition chooser from the available options. Guide the optimization through sequential or parallel evalutions of the objective.
[ "Acquisition", "chooser", "from", "the", "available", "options", ".", "Guide", "the", "optimization", "through", "sequential", "or", "parallel", "evalutions", "of", "the", "objective", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/arguments_manager.py#L17-L38
242,021
SheffieldML/GPyOpt
GPyOpt/acquisitions/LCB.py
AcquisitionLCB._compute_acq
def _compute_acq(self, x): """ Computes the GP-Lower Confidence Bound """ m, s = self.model.predict(x) f_acqu = -m + self.exploration_weight * s return f_acqu
python
def _compute_acq(self, x): m, s = self.model.predict(x) f_acqu = -m + self.exploration_weight * s return f_acqu
[ "def", "_compute_acq", "(", "self", ",", "x", ")", ":", "m", ",", "s", "=", "self", ".", "model", ".", "predict", "(", "x", ")", "f_acqu", "=", "-", "m", "+", "self", ".", "exploration_weight", "*", "s", "return", "f_acqu" ]
Computes the GP-Lower Confidence Bound
[ "Computes", "the", "GP", "-", "Lower", "Confidence", "Bound" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LCB.py#L31-L37
242,022
SheffieldML/GPyOpt
GPyOpt/acquisitions/LCB.py
AcquisitionLCB._compute_acq_withGradients
def _compute_acq_withGradients(self, x): """ Computes the GP-Lower Confidence Bound and its derivative """ m, s, dmdx, dsdx = self.model.predict_withGradients(x) f_acqu = -m + self.exploration_weight * s df_acqu = -dmdx + self.exploration_weight * dsdx ret...
python
def _compute_acq_withGradients(self, x): m, s, dmdx, dsdx = self.model.predict_withGradients(x) f_acqu = -m + self.exploration_weight * s df_acqu = -dmdx + self.exploration_weight * dsdx return f_acqu, df_acqu
[ "def", "_compute_acq_withGradients", "(", "self", ",", "x", ")", ":", "m", ",", "s", ",", "dmdx", ",", "dsdx", "=", "self", ".", "model", ".", "predict_withGradients", "(", "x", ")", "f_acqu", "=", "-", "m", "+", "self", ".", "exploration_weight", "*",...
Computes the GP-Lower Confidence Bound and its derivative
[ "Computes", "the", "GP", "-", "Lower", "Confidence", "Bound", "and", "its", "derivative" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LCB.py#L39-L46
242,023
SheffieldML/GPyOpt
GPyOpt/core/task/variables.py
create_variable
def create_variable(descriptor): """ Creates a variable from a dictionary descriptor """ if descriptor['type'] == 'continuous': return ContinuousVariable(descriptor['name'], descriptor['domain'], descriptor.get('dimensionality', 1)) elif descriptor['type'] == 'bandit': return BanditV...
python
def create_variable(descriptor): if descriptor['type'] == 'continuous': return ContinuousVariable(descriptor['name'], descriptor['domain'], descriptor.get('dimensionality', 1)) elif descriptor['type'] == 'bandit': return BanditVariable(descriptor['name'], descriptor['domain'], descriptor.get('di...
[ "def", "create_variable", "(", "descriptor", ")", ":", "if", "descriptor", "[", "'type'", "]", "==", "'continuous'", ":", "return", "ContinuousVariable", "(", "descriptor", "[", "'name'", "]", ",", "descriptor", "[", "'domain'", "]", ",", "descriptor", ".", ...
Creates a variable from a dictionary descriptor
[ "Creates", "a", "variable", "from", "a", "dictionary", "descriptor" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/variables.py#L230-L243
242,024
SheffieldML/GPyOpt
GPyOpt/core/task/variables.py
Variable.expand
def expand(self): """ Builds a list of single dimensional variables representing current variable. Examples: For single dimensional variable, it is returned as is discrete of (0,2,4) -> discrete of (0,2,4) For multi dimensional variable, a list of variables is returned, ...
python
def expand(self): expanded_variables = [] for i in range(self.dimensionality): one_d_variable = deepcopy(self) one_d_variable.dimensionality = 1 if self.dimensionality > 1: one_d_variable.name = '{}_{}'.format(self.name, i+1) else: ...
[ "def", "expand", "(", "self", ")", ":", "expanded_variables", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "dimensionality", ")", ":", "one_d_variable", "=", "deepcopy", "(", "self", ")", "one_d_variable", ".", "dimensionality", "=", "1", ...
Builds a list of single dimensional variables representing current variable. Examples: For single dimensional variable, it is returned as is discrete of (0,2,4) -> discrete of (0,2,4) For multi dimensional variable, a list of variables is returned, each representing a single dimension ...
[ "Builds", "a", "list", "of", "single", "dimensional", "variables", "representing", "current", "variable", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/variables.py#L16-L36
242,025
SheffieldML/GPyOpt
GPyOpt/core/task/variables.py
ContinuousVariable.round
def round(self, value_array): """ If value falls within bounds, just return it otherwise return min or max, whichever is closer to the value Assumes an 1d array with a single element as an input. """ min_value = self.domain[0] max_value = self.domain[1] ...
python
def round(self, value_array): min_value = self.domain[0] max_value = self.domain[1] rounded_value = value_array[0] if rounded_value < min_value: rounded_value = min_value elif rounded_value > max_value: rounded_value = max_value return [rounded_v...
[ "def", "round", "(", "self", ",", "value_array", ")", ":", "min_value", "=", "self", ".", "domain", "[", "0", "]", "max_value", "=", "self", ".", "domain", "[", "1", "]", "rounded_value", "=", "value_array", "[", "0", "]", "if", "rounded_value", "<", ...
If value falls within bounds, just return it otherwise return min or max, whichever is closer to the value Assumes an 1d array with a single element as an input.
[ "If", "value", "falls", "within", "bounds", "just", "return", "it", "otherwise", "return", "min", "or", "max", "whichever", "is", "closer", "to", "the", "value", "Assumes", "an", "1d", "array", "with", "a", "single", "element", "as", "an", "input", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/variables.py#L100-L116
242,026
SheffieldML/GPyOpt
GPyOpt/core/task/variables.py
BanditVariable.round
def round(self, value_array): """ Rounds a bandit variable by selecting the closest point in the domain Closest here is defined by euclidian distance Assumes an 1d array of the same length as the single variable value """ distances = np.linalg.norm(np.array(self.domain) -...
python
def round(self, value_array): distances = np.linalg.norm(np.array(self.domain) - value_array, axis=1) idx = np.argmin(distances) return [self.domain[idx]]
[ "def", "round", "(", "self", ",", "value_array", ")", ":", "distances", "=", "np", ".", "linalg", ".", "norm", "(", "np", ".", "array", "(", "self", ".", "domain", ")", "-", "value_array", ",", "axis", "=", "1", ")", "idx", "=", "np", ".", "argmi...
Rounds a bandit variable by selecting the closest point in the domain Closest here is defined by euclidian distance Assumes an 1d array of the same length as the single variable value
[ "Rounds", "a", "bandit", "variable", "by", "selecting", "the", "closest", "point", "in", "the", "domain", "Closest", "here", "is", "defined", "by", "euclidian", "distance", "Assumes", "an", "1d", "array", "of", "the", "same", "length", "as", "the", "single",...
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/variables.py#L151-L159
242,027
SheffieldML/GPyOpt
GPyOpt/core/task/variables.py
DiscreteVariable.round
def round(self, value_array): """ Rounds a discrete variable by selecting the closest point in the domain Assumes an 1d array with a single element as an input. """ value = value_array[0] rounded_value = self.domain[0] for domain_value in self.domain: ...
python
def round(self, value_array): value = value_array[0] rounded_value = self.domain[0] for domain_value in self.domain: if np.abs(domain_value - value) < np.abs(rounded_value - value): rounded_value = domain_value return [rounded_value]
[ "def", "round", "(", "self", ",", "value_array", ")", ":", "value", "=", "value_array", "[", "0", "]", "rounded_value", "=", "self", ".", "domain", "[", "0", "]", "for", "domain_value", "in", "self", ".", "domain", ":", "if", "np", ".", "abs", "(", ...
Rounds a discrete variable by selecting the closest point in the domain Assumes an 1d array with a single element as an input.
[ "Rounds", "a", "discrete", "variable", "by", "selecting", "the", "closest", "point", "in", "the", "domain", "Assumes", "an", "1d", "array", "with", "a", "single", "element", "as", "an", "input", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/variables.py#L175-L187
242,028
SheffieldML/GPyOpt
GPyOpt/optimization/acquisition_optimizer.py
AcquisitionOptimizer.optimize
def optimize(self, f=None, df=None, f_df=None, duplicate_manager=None): """ Optimizes the input function. :param f: function to optimize. :param df: gradient of the function to optimize. :param f_df: returns both the function to optimize and its gradient. """ se...
python
def optimize(self, f=None, df=None, f_df=None, duplicate_manager=None): self.f = f self.df = df self.f_df = f_df ## --- Update the optimizer, in case context has beee passed. self.optimizer = choose_optimizer(self.optimizer_name, self.context_manager.noncontext_bounds) ...
[ "def", "optimize", "(", "self", ",", "f", "=", "None", ",", "df", "=", "None", ",", "f_df", "=", "None", ",", "duplicate_manager", "=", "None", ")", ":", "self", ".", "f", "=", "f", "self", ".", "df", "=", "df", "self", ".", "f_df", "=", "f_df"...
Optimizes the input function. :param f: function to optimize. :param df: gradient of the function to optimize. :param f_df: returns both the function to optimize and its gradient.
[ "Optimizes", "the", "input", "function", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/optimization/acquisition_optimizer.py#L46-L77
242,029
SheffieldML/GPyOpt
GPyOpt/core/task/objective.py
SingleObjective.evaluate
def evaluate(self, x): """ Performs the evaluation of the objective at x. """ if self.n_procs == 1: f_evals, cost_evals = self._eval_func(x) else: try: f_evals, cost_evals = self._syncronous_batch_evaluation(x) except: ...
python
def evaluate(self, x): if self.n_procs == 1: f_evals, cost_evals = self._eval_func(x) else: try: f_evals, cost_evals = self._syncronous_batch_evaluation(x) except: if not hasattr(self, 'parallel_error'): print('Error...
[ "def", "evaluate", "(", "self", ",", "x", ")", ":", "if", "self", ".", "n_procs", "==", "1", ":", "f_evals", ",", "cost_evals", "=", "self", ".", "_eval_func", "(", "x", ")", "else", ":", "try", ":", "f_evals", ",", "cost_evals", "=", "self", ".", ...
Performs the evaluation of the objective at x.
[ "Performs", "the", "evaluation", "of", "the", "objective", "at", "x", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/objective.py#L44-L61
242,030
SheffieldML/GPyOpt
GPyOpt/core/task/objective.py
SingleObjective._syncronous_batch_evaluation
def _syncronous_batch_evaluation(self,x): """ Evaluates the function a x, where x can be a single location or a batch. The evaluation is performed in parallel according to the number of accessible cores. """ from multiprocessing import Process, Pipe # --- parallel evalua...
python
def _syncronous_batch_evaluation(self,x): from multiprocessing import Process, Pipe # --- parallel evaluation of the function divided_samples = [x[i::self.n_procs] for i in range(self.n_procs)] pipe = [Pipe() for i in range(self.n_procs)] proc = [Process(target=spawn(self._eval_...
[ "def", "_syncronous_batch_evaluation", "(", "self", ",", "x", ")", ":", "from", "multiprocessing", "import", "Process", ",", "Pipe", "# --- parallel evaluation of the function", "divided_samples", "=", "[", "x", "[", "i", ":", ":", "self", ".", "n_procs", "]", "...
Evaluates the function a x, where x can be a single location or a batch. The evaluation is performed in parallel according to the number of accessible cores.
[ "Evaluates", "the", "function", "a", "x", "where", "x", "can", "be", "a", "single", "location", "or", "a", "batch", ".", "The", "evaluation", "is", "performed", "in", "parallel", "according", "to", "the", "number", "of", "accessible", "cores", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/objective.py#L80-L101
242,031
SheffieldML/GPyOpt
GPyOpt/core/evaluators/sequential.py
Sequential.compute_batch
def compute_batch(self, duplicate_manager=None,context_manager=None): """ Selects the new location to evaluate the objective. """ x, _ = self.acquisition.optimize(duplicate_manager=duplicate_manager) return x
python
def compute_batch(self, duplicate_manager=None,context_manager=None): x, _ = self.acquisition.optimize(duplicate_manager=duplicate_manager) return x
[ "def", "compute_batch", "(", "self", ",", "duplicate_manager", "=", "None", ",", "context_manager", "=", "None", ")", ":", "x", ",", "_", "=", "self", ".", "acquisition", ".", "optimize", "(", "duplicate_manager", "=", "duplicate_manager", ")", "return", "x"...
Selects the new location to evaluate the objective.
[ "Selects", "the", "new", "location", "to", "evaluate", "the", "objective", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/evaluators/sequential.py#L18-L23
242,032
SheffieldML/GPyOpt
GPyOpt/acquisitions/LCB_mcmc.py
AcquisitionLCB_MCMC._compute_acq
def _compute_acq(self,x): """ Integrated GP-Lower Confidence Bound """ means, stds = self.model.predict(x) f_acqu = 0 for m,s in zip(means, stds): f_acqu += -m + self.exploration_weight * s return f_acqu/(len(means))
python
def _compute_acq(self,x): means, stds = self.model.predict(x) f_acqu = 0 for m,s in zip(means, stds): f_acqu += -m + self.exploration_weight * s return f_acqu/(len(means))
[ "def", "_compute_acq", "(", "self", ",", "x", ")", ":", "means", ",", "stds", "=", "self", ".", "model", ".", "predict", "(", "x", ")", "f_acqu", "=", "0", "for", "m", ",", "s", "in", "zip", "(", "means", ",", "stds", ")", ":", "f_acqu", "+=", ...
Integrated GP-Lower Confidence Bound
[ "Integrated", "GP", "-", "Lower", "Confidence", "Bound" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LCB_mcmc.py#L26-L34
242,033
SheffieldML/GPyOpt
GPyOpt/acquisitions/LCB_mcmc.py
AcquisitionLCB_MCMC._compute_acq_withGradients
def _compute_acq_withGradients(self, x): """ Integrated GP-Lower Confidence Bound and its derivative """ means, stds, dmdxs, dsdxs = self.model.predict_withGradients(x) f_acqu = None df_acqu = None for m, s, dmdx, dsdx in zip(means, stds, dmdxs, dsdxs): ...
python
def _compute_acq_withGradients(self, x): means, stds, dmdxs, dsdxs = self.model.predict_withGradients(x) f_acqu = None df_acqu = None for m, s, dmdx, dsdx in zip(means, stds, dmdxs, dsdxs): f = -m + self.exploration_weight * s df = -dmdx + self.explorati...
[ "def", "_compute_acq_withGradients", "(", "self", ",", "x", ")", ":", "means", ",", "stds", ",", "dmdxs", ",", "dsdxs", "=", "self", ".", "model", ".", "predict_withGradients", "(", "x", ")", "f_acqu", "=", "None", "df_acqu", "=", "None", "for", "m", "...
Integrated GP-Lower Confidence Bound and its derivative
[ "Integrated", "GP", "-", "Lower", "Confidence", "Bound", "and", "its", "derivative" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/LCB_mcmc.py#L36-L52
242,034
SheffieldML/GPyOpt
GPyOpt/core/task/space.py
Design_space._expand_config_space
def _expand_config_space(self): """ Expands the config input space into a list of diccionaries, one for each variable_dic in which the dimensionality is always one. Example: It would transform config_space =[ {'name': 'var_1', 'type': 'continuous', 'domain':(-1,1), 'dimensionali...
python
def _expand_config_space(self): self.config_space_expanded = [] for variable in self.config_space: variable_dic = variable.copy() if 'dimensionality' in variable_dic.keys(): dimensionality = variable_dic['dimensionality'] variable_dic['dimensional...
[ "def", "_expand_config_space", "(", "self", ")", ":", "self", ".", "config_space_expanded", "=", "[", "]", "for", "variable", "in", "self", ".", "config_space", ":", "variable_dic", "=", "variable", ".", "copy", "(", ")", "if", "'dimensionality'", "in", "var...
Expands the config input space into a list of diccionaries, one for each variable_dic in which the dimensionality is always one. Example: It would transform config_space =[ {'name': 'var_1', 'type': 'continuous', 'domain':(-1,1), 'dimensionality':1}, {'name': 'var_2', 't...
[ "Expands", "the", "config", "input", "space", "into", "a", "list", "of", "diccionaries", "one", "for", "each", "variable_dic", "in", "which", "the", "dimensionality", "is", "always", "one", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L101-L131
242,035
SheffieldML/GPyOpt
GPyOpt/core/task/space.py
Design_space._create_variables_dic
def _create_variables_dic(self): """ Returns the variable by passing its name """ self.name_to_variable = {} for variable in self.space_expanded: self.name_to_variable[variable.name] = variable
python
def _create_variables_dic(self): self.name_to_variable = {} for variable in self.space_expanded: self.name_to_variable[variable.name] = variable
[ "def", "_create_variables_dic", "(", "self", ")", ":", "self", ".", "name_to_variable", "=", "{", "}", "for", "variable", "in", "self", ".", "space_expanded", ":", "self", ".", "name_to_variable", "[", "variable", ".", "name", "]", "=", "variable" ]
Returns the variable by passing its name
[ "Returns", "the", "variable", "by", "passing", "its", "name" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L162-L168
242,036
SheffieldML/GPyOpt
GPyOpt/core/task/space.py
Design_space._translate_space
def _translate_space(self, space): """ Translates a list of dictionaries into internal list of variables """ self.space = [] self.dimensionality = 0 self.has_types = d = {t: False for t in self.supported_types} for i, d in enumerate(space): descriptor...
python
def _translate_space(self, space): self.space = [] self.dimensionality = 0 self.has_types = d = {t: False for t in self.supported_types} for i, d in enumerate(space): descriptor = deepcopy(d) descriptor['name'] = descriptor.get('name', 'var_' + str(i)) ...
[ "def", "_translate_space", "(", "self", ",", "space", ")", ":", "self", ".", "space", "=", "[", "]", "self", ".", "dimensionality", "=", "0", "self", ".", "has_types", "=", "d", "=", "{", "t", ":", "False", "for", "t", "in", "self", ".", "supported...
Translates a list of dictionaries into internal list of variables
[ "Translates", "a", "list", "of", "dictionaries", "into", "internal", "list", "of", "variables" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L170-L191
242,037
SheffieldML/GPyOpt
GPyOpt/core/task/space.py
Design_space._expand_space
def _expand_space(self): """ Creates an internal list where the variables with dimensionality larger than one are expanded. This list is the one that is used internally to do the optimization. """ ## --- Expand the config space self._expand_config_space() ## ---...
python
def _expand_space(self): ## --- Expand the config space self._expand_config_space() ## --- Expand the space self.space_expanded = [] for variable in self.space: self.space_expanded += variable.expand()
[ "def", "_expand_space", "(", "self", ")", ":", "## --- Expand the config space", "self", ".", "_expand_config_space", "(", ")", "## --- Expand the space", "self", ".", "space_expanded", "=", "[", "]", "for", "variable", "in", "self", ".", "space", ":", "self", "...
Creates an internal list where the variables with dimensionality larger than one are expanded. This list is the one that is used internally to do the optimization.
[ "Creates", "an", "internal", "list", "where", "the", "variables", "with", "dimensionality", "larger", "than", "one", "are", "expanded", ".", "This", "list", "is", "the", "one", "that", "is", "used", "internally", "to", "do", "the", "optimization", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L193-L205
242,038
SheffieldML/GPyOpt
GPyOpt/core/task/space.py
Design_space.objective_to_model
def objective_to_model(self, x_objective): ''' This function serves as interface between objective input vectors and model input vectors''' x_model = [] for k in range(self.objective_dimensionality): variable = self.space_expanded[k] new_entry = variable.objecti...
python
def objective_to_model(self, x_objective): ''' This function serves as interface between objective input vectors and model input vectors''' x_model = [] for k in range(self.objective_dimensionality): variable = self.space_expanded[k] new_entry = variable.objecti...
[ "def", "objective_to_model", "(", "self", ",", "x_objective", ")", ":", "x_model", "=", "[", "]", "for", "k", "in", "range", "(", "self", ".", "objective_dimensionality", ")", ":", "variable", "=", "self", ".", "space_expanded", "[", "k", "]", "new_entry",...
This function serves as interface between objective input vectors and model input vectors
[ "This", "function", "serves", "as", "interface", "between", "objective", "input", "vectors", "and", "model", "input", "vectors" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L207-L218
242,039
SheffieldML/GPyOpt
GPyOpt/core/task/space.py
Design_space.model_to_objective
def model_to_objective(self, x_model): ''' This function serves as interface between model input vectors and objective input vectors ''' idx_model = 0 x_objective = [] for idx_obj in range(self.objective_dimensionality): variable = self.space_expanded[idx...
python
def model_to_objective(self, x_model): ''' This function serves as interface between model input vectors and objective input vectors ''' idx_model = 0 x_objective = [] for idx_obj in range(self.objective_dimensionality): variable = self.space_expanded[idx...
[ "def", "model_to_objective", "(", "self", ",", "x_model", ")", ":", "idx_model", "=", "0", "x_objective", "=", "[", "]", "for", "idx_obj", "in", "range", "(", "self", ".", "objective_dimensionality", ")", ":", "variable", "=", "self", ".", "space_expanded", ...
This function serves as interface between model input vectors and objective input vectors
[ "This", "function", "serves", "as", "interface", "between", "model", "input", "vectors", "and", "objective", "input", "vectors" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L238-L251
242,040
SheffieldML/GPyOpt
GPyOpt/core/task/space.py
Design_space.get_subspace
def get_subspace(self, dims): ''' Extracts subspace from the reference of a list of variables in the inputs of the model. ''' subspace = [] k = 0 for variable in self.space_expanded: if k in dims: subspace.append(variable) k...
python
def get_subspace(self, dims): ''' Extracts subspace from the reference of a list of variables in the inputs of the model. ''' subspace = [] k = 0 for variable in self.space_expanded: if k in dims: subspace.append(variable) k...
[ "def", "get_subspace", "(", "self", ",", "dims", ")", ":", "subspace", "=", "[", "]", "k", "=", "0", "for", "variable", "in", "self", ".", "space_expanded", ":", "if", "k", "in", "dims", ":", "subspace", ".", "append", "(", "variable", ")", "k", "+...
Extracts subspace from the reference of a list of variables in the inputs of the model.
[ "Extracts", "subspace", "from", "the", "reference", "of", "a", "list", "of", "variables", "in", "the", "inputs", "of", "the", "model", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L283-L294
242,041
SheffieldML/GPyOpt
GPyOpt/core/task/space.py
Design_space.indicator_constraints
def indicator_constraints(self,x): """ Returns array of ones and zeros indicating if x is within the constraints """ x = np.atleast_2d(x) I_x = np.ones((x.shape[0],1)) if self.constraints is not None: for d in self.constraints: try: ...
python
def indicator_constraints(self,x): x = np.atleast_2d(x) I_x = np.ones((x.shape[0],1)) if self.constraints is not None: for d in self.constraints: try: exec('constraint = lambda x:' + d['constraint'], globals()) ind_x = (constrai...
[ "def", "indicator_constraints", "(", "self", ",", "x", ")", ":", "x", "=", "np", ".", "atleast_2d", "(", "x", ")", "I_x", "=", "np", ".", "ones", "(", "(", "x", ".", "shape", "[", "0", "]", ",", "1", ")", ")", "if", "self", ".", "constraints", ...
Returns array of ones and zeros indicating if x is within the constraints
[ "Returns", "array", "of", "ones", "and", "zeros", "indicating", "if", "x", "is", "within", "the", "constraints" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L297-L312
242,042
SheffieldML/GPyOpt
GPyOpt/core/task/space.py
Design_space.input_dim
def input_dim(self): """ Extracts the input dimension of the domain. """ n_cont = len(self.get_continuous_dims()) n_disc = len(self.get_discrete_dims()) return n_cont + n_disc
python
def input_dim(self): n_cont = len(self.get_continuous_dims()) n_disc = len(self.get_discrete_dims()) return n_cont + n_disc
[ "def", "input_dim", "(", "self", ")", ":", "n_cont", "=", "len", "(", "self", ".", "get_continuous_dims", "(", ")", ")", "n_disc", "=", "len", "(", "self", ".", "get_discrete_dims", "(", ")", ")", "return", "n_cont", "+", "n_disc" ]
Extracts the input dimension of the domain.
[ "Extracts", "the", "input", "dimension", "of", "the", "domain", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L314-L320
242,043
SheffieldML/GPyOpt
GPyOpt/core/task/space.py
Design_space.round_optimum
def round_optimum(self, x): """ Rounds some value x to a feasible value in the design space. x is expected to be a vector or an array with a single row """ x = np.array(x) if not ((x.ndim == 1) or (x.ndim == 2 and x.shape[0] == 1)): raise ValueError("Unexpecte...
python
def round_optimum(self, x): x = np.array(x) if not ((x.ndim == 1) or (x.ndim == 2 and x.shape[0] == 1)): raise ValueError("Unexpected dimentionality of x. Got {}, expected (1, N) or (N,)".format(x.ndim)) if x.ndim == 2: x = x[0] x_rounded = [] value_inde...
[ "def", "round_optimum", "(", "self", ",", "x", ")", ":", "x", "=", "np", ".", "array", "(", "x", ")", "if", "not", "(", "(", "x", ".", "ndim", "==", "1", ")", "or", "(", "x", ".", "ndim", "==", "2", "and", "x", ".", "shape", "[", "0", "]"...
Rounds some value x to a feasible value in the design space. x is expected to be a vector or an array with a single row
[ "Rounds", "some", "value", "x", "to", "a", "feasible", "value", "in", "the", "design", "space", ".", "x", "is", "expected", "to", "be", "a", "vector", "or", "an", "array", "with", "a", "single", "row" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L322-L343
242,044
SheffieldML/GPyOpt
GPyOpt/core/task/space.py
Design_space.get_continuous_bounds
def get_continuous_bounds(self): """ Extracts the bounds of the continuous variables. """ bounds = [] for d in self.space: if d.type == 'continuous': bounds.extend([d.domain]*d.dimensionality) return bounds
python
def get_continuous_bounds(self): bounds = [] for d in self.space: if d.type == 'continuous': bounds.extend([d.domain]*d.dimensionality) return bounds
[ "def", "get_continuous_bounds", "(", "self", ")", ":", "bounds", "=", "[", "]", "for", "d", "in", "self", ".", "space", ":", "if", "d", ".", "type", "==", "'continuous'", ":", "bounds", ".", "extend", "(", "[", "d", ".", "domain", "]", "*", "d", ...
Extracts the bounds of the continuous variables.
[ "Extracts", "the", "bounds", "of", "the", "continuous", "variables", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L353-L361
242,045
SheffieldML/GPyOpt
GPyOpt/core/task/space.py
Design_space.get_continuous_dims
def get_continuous_dims(self): """ Returns the dimension of the continuous components of the domain. """ continuous_dims = [] for i in range(self.dimensionality): if self.space_expanded[i].type == 'continuous': continuous_dims += [i] return con...
python
def get_continuous_dims(self): continuous_dims = [] for i in range(self.dimensionality): if self.space_expanded[i].type == 'continuous': continuous_dims += [i] return continuous_dims
[ "def", "get_continuous_dims", "(", "self", ")", ":", "continuous_dims", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "dimensionality", ")", ":", "if", "self", ".", "space_expanded", "[", "i", "]", ".", "type", "==", "'continuous'", ":", ...
Returns the dimension of the continuous components of the domain.
[ "Returns", "the", "dimension", "of", "the", "continuous", "components", "of", "the", "domain", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L364-L372
242,046
SheffieldML/GPyOpt
GPyOpt/core/task/space.py
Design_space.get_discrete_grid
def get_discrete_grid(self): """ Computes a Numpy array with the grid of points that results after crossing the possible outputs of the discrete variables """ sets_grid = [] for d in self.space: if d.type == 'discrete': sets_grid.extend([d.doma...
python
def get_discrete_grid(self): sets_grid = [] for d in self.space: if d.type == 'discrete': sets_grid.extend([d.domain]*d.dimensionality) return np.array(list(itertools.product(*sets_grid)))
[ "def", "get_discrete_grid", "(", "self", ")", ":", "sets_grid", "=", "[", "]", "for", "d", "in", "self", ".", "space", ":", "if", "d", ".", "type", "==", "'discrete'", ":", "sets_grid", ".", "extend", "(", "[", "d", ".", "domain", "]", "*", "d", ...
Computes a Numpy array with the grid of points that results after crossing the possible outputs of the discrete variables
[ "Computes", "a", "Numpy", "array", "with", "the", "grid", "of", "points", "that", "results", "after", "crossing", "the", "possible", "outputs", "of", "the", "discrete", "variables" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L387-L396
242,047
SheffieldML/GPyOpt
GPyOpt/core/task/space.py
Design_space.get_discrete_dims
def get_discrete_dims(self): """ Returns the dimension of the discrete components of the domain. """ discrete_dims = [] for i in range(self.dimensionality): if self.space_expanded[i].type == 'discrete': discrete_dims += [i] return discrete_dims
python
def get_discrete_dims(self): discrete_dims = [] for i in range(self.dimensionality): if self.space_expanded[i].type == 'discrete': discrete_dims += [i] return discrete_dims
[ "def", "get_discrete_dims", "(", "self", ")", ":", "discrete_dims", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "dimensionality", ")", ":", "if", "self", ".", "space_expanded", "[", "i", "]", ".", "type", "==", "'discrete'", ":", "discr...
Returns the dimension of the discrete components of the domain.
[ "Returns", "the", "dimension", "of", "the", "discrete", "components", "of", "the", "domain", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L399-L407
242,048
SheffieldML/GPyOpt
GPyOpt/core/task/space.py
Design_space.get_bandit
def get_bandit(self): """ Extracts the arms of the bandit if any. """ arms_bandit = [] for d in self.space: if d.type == 'bandit': arms_bandit += tuple(map(tuple, d.domain)) return np.asarray(arms_bandit)
python
def get_bandit(self): arms_bandit = [] for d in self.space: if d.type == 'bandit': arms_bandit += tuple(map(tuple, d.domain)) return np.asarray(arms_bandit)
[ "def", "get_bandit", "(", "self", ")", ":", "arms_bandit", "=", "[", "]", "for", "d", "in", "self", ".", "space", ":", "if", "d", ".", "type", "==", "'bandit'", ":", "arms_bandit", "+=", "tuple", "(", "map", "(", "tuple", ",", "d", ".", "domain", ...
Extracts the arms of the bandit if any.
[ "Extracts", "the", "arms", "of", "the", "bandit", "if", "any", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/task/space.py#L422-L430
242,049
SheffieldML/GPyOpt
GPyOpt/models/rfmodel.py
RFModel.predict
def predict(self, X): """ Predictions with the model. Returns posterior means and standard deviations at X. """ X = np.atleast_2d(X) m = np.empty(shape=(0,1)) s = np.empty(shape=(0,1)) for k in range(X.shape[0]): preds = [] for pred in sel...
python
def predict(self, X): X = np.atleast_2d(X) m = np.empty(shape=(0,1)) s = np.empty(shape=(0,1)) for k in range(X.shape[0]): preds = [] for pred in self.model.estimators_: preds.append(pred.predict(X[k,:])[0]) m = np.vstack((m ,np.array(...
[ "def", "predict", "(", "self", ",", "X", ")", ":", "X", "=", "np", ".", "atleast_2d", "(", "X", ")", "m", "=", "np", ".", "empty", "(", "shape", "=", "(", "0", ",", "1", ")", ")", "s", "=", "np", ".", "empty", "(", "shape", "=", "(", "0",...
Predictions with the model. Returns posterior means and standard deviations at X.
[ "Predictions", "with", "the", "model", ".", "Returns", "posterior", "means", "and", "standard", "deviations", "at", "X", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/models/rfmodel.py#L79-L93
242,050
SheffieldML/GPyOpt
GPyOpt/acquisitions/MPI_mcmc.py
AcquisitionMPI_MCMC._compute_acq
def _compute_acq(self,x): """ Integrated Expected Improvement """ means, stds = self.model.predict(x) fmins = self.model.get_fmin() f_acqu = 0 for m,s,fmin in zip(means, stds, fmins): _, Phi, _ = get_quantiles(self.jitter, fmin, m, s) f_acq...
python
def _compute_acq(self,x): means, stds = self.model.predict(x) fmins = self.model.get_fmin() f_acqu = 0 for m,s,fmin in zip(means, stds, fmins): _, Phi, _ = get_quantiles(self.jitter, fmin, m, s) f_acqu += Phi return f_acqu/len(means)
[ "def", "_compute_acq", "(", "self", ",", "x", ")", ":", "means", ",", "stds", "=", "self", ".", "model", ".", "predict", "(", "x", ")", "fmins", "=", "self", ".", "model", ".", "get_fmin", "(", ")", "f_acqu", "=", "0", "for", "m", ",", "s", ","...
Integrated Expected Improvement
[ "Integrated", "Expected", "Improvement" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/MPI_mcmc.py#L29-L39
242,051
SheffieldML/GPyOpt
GPyOpt/acquisitions/MPI_mcmc.py
AcquisitionMPI_MCMC._compute_acq_withGradients
def _compute_acq_withGradients(self, x): """ Integrated Expected Improvement and its derivative """ means, stds, dmdxs, dsdxs = self.model.predict_withGradients(x) fmins = self.model.get_fmin() f_acqu = None df_acqu = None for m, s, fmin, dmdx, dsdx in zip...
python
def _compute_acq_withGradients(self, x): means, stds, dmdxs, dsdxs = self.model.predict_withGradients(x) fmins = self.model.get_fmin() f_acqu = None df_acqu = None for m, s, fmin, dmdx, dsdx in zip(means, stds, fmins, dmdxs, dsdxs): phi, Phi, u = get_quantiles(self.ji...
[ "def", "_compute_acq_withGradients", "(", "self", ",", "x", ")", ":", "means", ",", "stds", ",", "dmdxs", ",", "dsdxs", "=", "self", ".", "model", ".", "predict_withGradients", "(", "x", ")", "fmins", "=", "self", ".", "model", ".", "get_fmin", "(", ")...
Integrated Expected Improvement and its derivative
[ "Integrated", "Expected", "Improvement", "and", "its", "derivative" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/MPI_mcmc.py#L41-L59
242,052
SheffieldML/GPyOpt
GPyOpt/plotting/plots_bo.py
plot_convergence
def plot_convergence(Xdata,best_Y, filename = None): ''' Plots to evaluate the convergence of standard Bayesian optimization algorithms ''' n = Xdata.shape[0] aux = (Xdata[1:n,:]-Xdata[0:n-1,:])**2 distances = np.sqrt(aux.sum(axis=1)) ## Distances between consecutive x's plt.figure(figs...
python
def plot_convergence(Xdata,best_Y, filename = None): ''' Plots to evaluate the convergence of standard Bayesian optimization algorithms ''' n = Xdata.shape[0] aux = (Xdata[1:n,:]-Xdata[0:n-1,:])**2 distances = np.sqrt(aux.sum(axis=1)) ## Distances between consecutive x's plt.figure(figs...
[ "def", "plot_convergence", "(", "Xdata", ",", "best_Y", ",", "filename", "=", "None", ")", ":", "n", "=", "Xdata", ".", "shape", "[", "0", "]", "aux", "=", "(", "Xdata", "[", "1", ":", "n", ",", ":", "]", "-", "Xdata", "[", "0", ":", "n", "-"...
Plots to evaluate the convergence of standard Bayesian optimization algorithms
[ "Plots", "to", "evaluate", "the", "convergence", "of", "standard", "Bayesian", "optimization", "algorithms" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/plotting/plots_bo.py#L122-L150
242,053
SheffieldML/GPyOpt
GPyOpt/core/evaluators/batch_local_penalization.py
LocalPenalization.compute_batch
def compute_batch(self, duplicate_manager=None, context_manager=None): """ Computes the elements of the batch sequentially by penalizing the acquisition. """ from ...acquisitions import AcquisitionLP assert isinstance(self.acquisition, AcquisitionLP) self.acquisition.upd...
python
def compute_batch(self, duplicate_manager=None, context_manager=None): from ...acquisitions import AcquisitionLP assert isinstance(self.acquisition, AcquisitionLP) self.acquisition.update_batches(None,None,None) # --- GET first element in the batch X_batch = self.acquisition.op...
[ "def", "compute_batch", "(", "self", ",", "duplicate_manager", "=", "None", ",", "context_manager", "=", "None", ")", ":", "from", ".", ".", ".", "acquisitions", "import", "AcquisitionLP", "assert", "isinstance", "(", "self", ".", "acquisition", ",", "Acquisit...
Computes the elements of the batch sequentially by penalizing the acquisition.
[ "Computes", "the", "elements", "of", "the", "batch", "sequentially", "by", "penalizing", "the", "acquisition", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/evaluators/batch_local_penalization.py#L22-L49
242,054
SheffieldML/GPyOpt
manual/notebooks_check.py
check_notebooks_for_errors
def check_notebooks_for_errors(notebooks_directory): ''' Evaluates all notebooks in given directory and prints errors, if any ''' print("Checking notebooks in directory {} for errors".format(notebooks_directory)) failed_notebooks_count = 0 for file in os.listdir(notebooks_directory): if file.en...
python
def check_notebooks_for_errors(notebooks_directory): ''' Evaluates all notebooks in given directory and prints errors, if any ''' print("Checking notebooks in directory {} for errors".format(notebooks_directory)) failed_notebooks_count = 0 for file in os.listdir(notebooks_directory): if file.en...
[ "def", "check_notebooks_for_errors", "(", "notebooks_directory", ")", ":", "print", "(", "\"Checking notebooks in directory {} for errors\"", ".", "format", "(", "notebooks_directory", ")", ")", "failed_notebooks_count", "=", "0", "for", "file", "in", "os", ".", "listdi...
Evaluates all notebooks in given directory and prints errors, if any
[ "Evaluates", "all", "notebooks", "in", "given", "directory", "and", "prints", "errors", "if", "any" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/manual/notebooks_check.py#L8-L24
242,055
SheffieldML/GPyOpt
GPyOpt/models/gpmodel.py
GPModel.predict
def predict(self, X, with_noise=True): """ Predictions with the model. Returns posterior means and standard deviations at X. Note that this is different in GPy where the variances are given. Parameters: X (np.ndarray) - points to run the prediction for. with_noise (bool)...
python
def predict(self, X, with_noise=True): m, v = self._predict(X, False, with_noise) # We can take the square root because v is just a diagonal matrix of variances return m, np.sqrt(v)
[ "def", "predict", "(", "self", ",", "X", ",", "with_noise", "=", "True", ")", ":", "m", ",", "v", "=", "self", ".", "_predict", "(", "X", ",", "False", ",", "with_noise", ")", "# We can take the square root because v is just a diagonal matrix of variances", "ret...
Predictions with the model. Returns posterior means and standard deviations at X. Note that this is different in GPy where the variances are given. Parameters: X (np.ndarray) - points to run the prediction for. with_noise (bool) - whether to add noise to the prediction. Default is True.
[ "Predictions", "with", "the", "model", ".", "Returns", "posterior", "means", "and", "standard", "deviations", "at", "X", ".", "Note", "that", "this", "is", "different", "in", "GPy", "where", "the", "variances", "are", "given", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/models/gpmodel.py#L100-L110
242,056
SheffieldML/GPyOpt
GPyOpt/models/gpmodel.py
GPModel.predict_covariance
def predict_covariance(self, X, with_noise=True): """ Predicts the covariance matric for points in X. Parameters: X (np.ndarray) - points to run the prediction for. with_noise (bool) - whether to add noise to the prediction. Default is True. """ _, v = se...
python
def predict_covariance(self, X, with_noise=True): _, v = self._predict(X, True, with_noise) return v
[ "def", "predict_covariance", "(", "self", ",", "X", ",", "with_noise", "=", "True", ")", ":", "_", ",", "v", "=", "self", ".", "_predict", "(", "X", ",", "True", ",", "with_noise", ")", "return", "v" ]
Predicts the covariance matric for points in X. Parameters: X (np.ndarray) - points to run the prediction for. with_noise (bool) - whether to add noise to the prediction. Default is True.
[ "Predicts", "the", "covariance", "matric", "for", "points", "in", "X", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/models/gpmodel.py#L112-L121
242,057
SheffieldML/GPyOpt
GPyOpt/models/gpmodel.py
GPModel.predict_withGradients
def predict_withGradients(self, X): """ Returns the mean, standard deviation, mean gradient and standard deviation gradient at X. """ if X.ndim==1: X = X[None,:] m, v = self.model.predict(X) v = np.clip(v, 1e-10, np.inf) dmdx, dvdx = self.model.predictive_gradient...
python
def predict_withGradients(self, X): if X.ndim==1: X = X[None,:] m, v = self.model.predict(X) v = np.clip(v, 1e-10, np.inf) dmdx, dvdx = self.model.predictive_gradients(X) dmdx = dmdx[:,:,0] dsdx = dvdx / (2*np.sqrt(v)) return m, np.sqrt(v), dmdx, dsdx
[ "def", "predict_withGradients", "(", "self", ",", "X", ")", ":", "if", "X", ".", "ndim", "==", "1", ":", "X", "=", "X", "[", "None", ",", ":", "]", "m", ",", "v", "=", "self", ".", "model", ".", "predict", "(", "X", ")", "v", "=", "np", "."...
Returns the mean, standard deviation, mean gradient and standard deviation gradient at X.
[ "Returns", "the", "mean", "standard", "deviation", "mean", "gradient", "and", "standard", "deviation", "gradient", "at", "X", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/models/gpmodel.py#L129-L140
242,058
SheffieldML/GPyOpt
GPyOpt/models/gpmodel.py
GPModel_MCMC.predict
def predict(self, X): """ Predictions with the model for all the MCMC samples. Returns posterior means and standard deviations at X. Note that this is different in GPy where the variances are given. """ if X.ndim==1: X = X[None,:] ps = self.model.param_array.copy() means...
python
def predict(self, X): if X.ndim==1: X = X[None,:] ps = self.model.param_array.copy() means = [] stds = [] for s in self.hmc_samples: if self.model._fixes_ is None: self.model[:] = s else: self.model[self.model._fixes_] = s ...
[ "def", "predict", "(", "self", ",", "X", ")", ":", "if", "X", ".", "ndim", "==", "1", ":", "X", "=", "X", "[", "None", ",", ":", "]", "ps", "=", "self", ".", "model", ".", "param_array", ".", "copy", "(", ")", "means", "=", "[", "]", "stds"...
Predictions with the model for all the MCMC samples. Returns posterior means and standard deviations at X. Note that this is different in GPy where the variances are given.
[ "Predictions", "with", "the", "model", "for", "all", "the", "MCMC", "samples", ".", "Returns", "posterior", "means", "and", "standard", "deviations", "at", "X", ".", "Note", "that", "this", "is", "different", "in", "GPy", "where", "the", "variances", "are", ...
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/models/gpmodel.py#L255-L275
242,059
SheffieldML/GPyOpt
GPyOpt/models/gpmodel.py
GPModel_MCMC.get_fmin
def get_fmin(self): """ Returns the location where the posterior mean is takes its minimal value. """ ps = self.model.param_array.copy() fmins = [] for s in self.hmc_samples: if self.model._fixes_ is None: self.model[:] = s else: ...
python
def get_fmin(self): ps = self.model.param_array.copy() fmins = [] for s in self.hmc_samples: if self.model._fixes_ is None: self.model[:] = s else: self.model[self.model._fixes_] = s self.model._trigger_params_changed() ...
[ "def", "get_fmin", "(", "self", ")", ":", "ps", "=", "self", ".", "model", ".", "param_array", ".", "copy", "(", ")", "fmins", "=", "[", "]", "for", "s", "in", "self", ".", "hmc_samples", ":", "if", "self", ".", "model", ".", "_fixes_", "is", "No...
Returns the location where the posterior mean is takes its minimal value.
[ "Returns", "the", "location", "where", "the", "posterior", "mean", "is", "takes", "its", "minimal", "value", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/models/gpmodel.py#L277-L293
242,060
SheffieldML/GPyOpt
GPyOpt/models/gpmodel.py
GPModel_MCMC.predict_withGradients
def predict_withGradients(self, X): """ Returns the mean, standard deviation, mean gradient and standard deviation gradient at X for all the MCMC samples. """ if X.ndim==1: X = X[None,:] ps = self.model.param_array.copy() means = [] stds = [] dmdxs = [] ...
python
def predict_withGradients(self, X): if X.ndim==1: X = X[None,:] ps = self.model.param_array.copy() means = [] stds = [] dmdxs = [] dsdxs = [] for s in self.hmc_samples: if self.model._fixes_ is None: self.model[:] = s else: ...
[ "def", "predict_withGradients", "(", "self", ",", "X", ")", ":", "if", "X", ".", "ndim", "==", "1", ":", "X", "=", "X", "[", "None", ",", ":", "]", "ps", "=", "self", ".", "model", ".", "param_array", ".", "copy", "(", ")", "means", "=", "[", ...
Returns the mean, standard deviation, mean gradient and standard deviation gradient at X for all the MCMC samples.
[ "Returns", "the", "mean", "standard", "deviation", "mean", "gradient", "and", "standard", "deviation", "gradient", "at", "X", "for", "all", "the", "MCMC", "samples", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/models/gpmodel.py#L295-L322
242,061
SheffieldML/GPyOpt
GPyOpt/interface/func_loader.py
load_objective
def load_objective(config): """ Loads the objective function from a .json file. """ assert 'prjpath' in config assert 'main-file' in config, "The problem file ('main-file') is missing!" os.chdir(config['prjpath']) if config['language'].lower()=='python': assert config['main-fil...
python
def load_objective(config): assert 'prjpath' in config assert 'main-file' in config, "The problem file ('main-file') is missing!" os.chdir(config['prjpath']) if config['language'].lower()=='python': assert config['main-file'].endswith('.py'), 'The python problem file has to end with .py!' ...
[ "def", "load_objective", "(", "config", ")", ":", "assert", "'prjpath'", "in", "config", "assert", "'main-file'", "in", "config", ",", "\"The problem file ('main-file') is missing!\"", "os", ".", "chdir", "(", "config", "[", "'prjpath'", "]", ")", "if", "config", ...
Loads the objective function from a .json file.
[ "Loads", "the", "objective", "function", "from", "a", ".", "json", "file", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/func_loader.py#L7-L21
242,062
SheffieldML/GPyOpt
GPyOpt/acquisitions/EI.py
AcquisitionEI._compute_acq
def _compute_acq(self, x): """ Computes the Expected Improvement per unit of cost """ m, s = self.model.predict(x) fmin = self.model.get_fmin() phi, Phi, u = get_quantiles(self.jitter, fmin, m, s) f_acqu = s * (u * Phi + phi) return f_acqu
python
def _compute_acq(self, x): m, s = self.model.predict(x) fmin = self.model.get_fmin() phi, Phi, u = get_quantiles(self.jitter, fmin, m, s) f_acqu = s * (u * Phi + phi) return f_acqu
[ "def", "_compute_acq", "(", "self", ",", "x", ")", ":", "m", ",", "s", "=", "self", ".", "model", ".", "predict", "(", "x", ")", "fmin", "=", "self", ".", "model", ".", "get_fmin", "(", ")", "phi", ",", "Phi", ",", "u", "=", "get_quantiles", "(...
Computes the Expected Improvement per unit of cost
[ "Computes", "the", "Expected", "Improvement", "per", "unit", "of", "cost" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/acquisitions/EI.py#L32-L40
242,063
SheffieldML/GPyOpt
GPyOpt/interface/config_parser.py
update_config
def update_config(config_new, config_default): ''' Updates the loaded method configuration with default values. ''' if any([isinstance(v, dict) for v in list(config_new.values())]): for k,v in list(config_new.items()): if isinstance(v,dict) and k in config_default: u...
python
def update_config(config_new, config_default): ''' Updates the loaded method configuration with default values. ''' if any([isinstance(v, dict) for v in list(config_new.values())]): for k,v in list(config_new.items()): if isinstance(v,dict) and k in config_default: u...
[ "def", "update_config", "(", "config_new", ",", "config_default", ")", ":", "if", "any", "(", "[", "isinstance", "(", "v", ",", "dict", ")", "for", "v", "in", "list", "(", "config_new", ".", "values", "(", ")", ")", "]", ")", ":", "for", "k", ",", ...
Updates the loaded method configuration with default values.
[ "Updates", "the", "loaded", "method", "configuration", "with", "default", "values", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/config_parser.py#L62-L75
242,064
SheffieldML/GPyOpt
GPyOpt/interface/config_parser.py
parser
def parser(input_file_path='config.json'): ''' Parser for the .json file containing the configuration of the method. ''' # --- Read .json file try: with open(input_file_path, 'r') as config_file: config_new = json.load(config_file) config_file.close() except: ...
python
def parser(input_file_path='config.json'): ''' Parser for the .json file containing the configuration of the method. ''' # --- Read .json file try: with open(input_file_path, 'r') as config_file: config_new = json.load(config_file) config_file.close() except: ...
[ "def", "parser", "(", "input_file_path", "=", "'config.json'", ")", ":", "# --- Read .json file", "try", ":", "with", "open", "(", "input_file_path", ",", "'r'", ")", "as", "config_file", ":", "config_new", "=", "json", ".", "load", "(", "config_file", ")", ...
Parser for the .json file containing the configuration of the method.
[ "Parser", "for", "the", ".", "json", "file", "containing", "the", "configuration", "of", "the", "method", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/interface/config_parser.py#L78-L94
242,065
SheffieldML/GPyOpt
GPyOpt/util/mcmc_sampler.py
AffineInvariantEnsembleSampler.get_samples
def get_samples(self, n_samples, log_p_function, burn_in_steps=50): """ Generates samples. Parameters: n_samples - number of samples to generate log_p_function - a function that returns log density for a specific sample burn_in_steps - number of burn-in steps...
python
def get_samples(self, n_samples, log_p_function, burn_in_steps=50): restarts = initial_design('random', self.space, n_samples) sampler = emcee.EnsembleSampler(n_samples, self.space.input_dim(), log_p_function) samples, samples_log, _ = sampler.run_mcmc(restarts, burn_in_steps) # make su...
[ "def", "get_samples", "(", "self", ",", "n_samples", ",", "log_p_function", ",", "burn_in_steps", "=", "50", ")", ":", "restarts", "=", "initial_design", "(", "'random'", ",", "self", ".", "space", ",", "n_samples", ")", "sampler", "=", "emcee", ".", "Ense...
Generates samples. Parameters: n_samples - number of samples to generate log_p_function - a function that returns log density for a specific sample burn_in_steps - number of burn-in steps for sampling Returns a tuple of two array: (samples, log_p_function values for...
[ "Generates", "samples", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/util/mcmc_sampler.py#L39-L59
242,066
SheffieldML/GPyOpt
GPyOpt/core/bo.py
BO.suggest_next_locations
def suggest_next_locations(self, context = None, pending_X = None, ignored_X = None): """ Run a single optimization step and return the next locations to evaluate the objective. Number of suggested locations equals to batch_size. :param context: fixes specified variables to a particular...
python
def suggest_next_locations(self, context = None, pending_X = None, ignored_X = None): self.model_parameters_iterations = None self.num_acquisitions = 0 self.context = context self._update_model(self.normalization_type) suggested_locations = self._compute_next_evaluations(pending...
[ "def", "suggest_next_locations", "(", "self", ",", "context", "=", "None", ",", "pending_X", "=", "None", ",", "ignored_X", "=", "None", ")", ":", "self", ".", "model_parameters_iterations", "=", "None", "self", ".", "num_acquisitions", "=", "0", "self", "."...
Run a single optimization step and return the next locations to evaluate the objective. Number of suggested locations equals to batch_size. :param context: fixes specified variables to a particular context (values) for the optimization run (default, None). :param pending_X: matrix of input conf...
[ "Run", "a", "single", "optimization", "step", "and", "return", "the", "next", "locations", "to", "evaluate", "the", "objective", ".", "Number", "of", "suggested", "locations", "equals", "to", "batch_size", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/bo.py#L55-L71
242,067
SheffieldML/GPyOpt
GPyOpt/core/bo.py
BO._print_convergence
def _print_convergence(self): """ Prints the reason why the optimization stopped. """ if self.verbosity: if (self.num_acquisitions == self.max_iter) and (not self.initial_iter): print(' ** Maximum number of iterations reached **') return 1 ...
python
def _print_convergence(self): if self.verbosity: if (self.num_acquisitions == self.max_iter) and (not self.initial_iter): print(' ** Maximum number of iterations reached **') return 1 elif (self._distance_last_evaluations() < self.eps) and (not self.init...
[ "def", "_print_convergence", "(", "self", ")", ":", "if", "self", ".", "verbosity", ":", "if", "(", "self", ".", "num_acquisitions", "==", "self", ".", "max_iter", ")", "and", "(", "not", "self", ".", "initial_iter", ")", ":", "print", "(", "' ** Maxim...
Prints the reason why the optimization stopped.
[ "Prints", "the", "reason", "why", "the", "optimization", "stopped", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/bo.py#L172-L190
242,068
SheffieldML/GPyOpt
GPyOpt/core/bo.py
BO.evaluate_objective
def evaluate_objective(self): """ Evaluates the objective """ self.Y_new, cost_new = self.objective.evaluate(self.suggested_sample) self.cost.update_cost_model(self.suggested_sample, cost_new) self.Y = np.vstack((self.Y,self.Y_new))
python
def evaluate_objective(self): self.Y_new, cost_new = self.objective.evaluate(self.suggested_sample) self.cost.update_cost_model(self.suggested_sample, cost_new) self.Y = np.vstack((self.Y,self.Y_new))
[ "def", "evaluate_objective", "(", "self", ")", ":", "self", ".", "Y_new", ",", "cost_new", "=", "self", ".", "objective", ".", "evaluate", "(", "self", ".", "suggested_sample", ")", "self", ".", "cost", ".", "update_cost_model", "(", "self", ".", "suggeste...
Evaluates the objective
[ "Evaluates", "the", "objective" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/bo.py#L193-L199
242,069
SheffieldML/GPyOpt
GPyOpt/core/bo.py
BO._compute_results
def _compute_results(self): """ Computes the optimum and its value. """ self.Y_best = best_value(self.Y) self.x_opt = self.X[np.argmin(self.Y),:] self.fx_opt = np.min(self.Y)
python
def _compute_results(self): self.Y_best = best_value(self.Y) self.x_opt = self.X[np.argmin(self.Y),:] self.fx_opt = np.min(self.Y)
[ "def", "_compute_results", "(", "self", ")", ":", "self", ".", "Y_best", "=", "best_value", "(", "self", ".", "Y", ")", "self", ".", "x_opt", "=", "self", ".", "X", "[", "np", ".", "argmin", "(", "self", ".", "Y", ")", ",", ":", "]", "self", "....
Computes the optimum and its value.
[ "Computes", "the", "optimum", "and", "its", "value", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/bo.py#L201-L207
242,070
SheffieldML/GPyOpt
GPyOpt/core/bo.py
BO._distance_last_evaluations
def _distance_last_evaluations(self): """ Computes the distance between the last two evaluations. """ if self.X.shape[0] < 2: # less than 2 evaluations return np.inf return np.sqrt(np.sum((self.X[-1, :] - self.X[-2, :]) ** 2))
python
def _distance_last_evaluations(self): if self.X.shape[0] < 2: # less than 2 evaluations return np.inf return np.sqrt(np.sum((self.X[-1, :] - self.X[-2, :]) ** 2))
[ "def", "_distance_last_evaluations", "(", "self", ")", ":", "if", "self", ".", "X", ".", "shape", "[", "0", "]", "<", "2", ":", "# less than 2 evaluations", "return", "np", ".", "inf", "return", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "(", "se...
Computes the distance between the last two evaluations.
[ "Computes", "the", "distance", "between", "the", "last", "two", "evaluations", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/bo.py#L209-L216
242,071
SheffieldML/GPyOpt
GPyOpt/core/bo.py
BO.save_evaluations
def save_evaluations(self, evaluations_file = None): """ Saves evaluations at each iteration of the optimization :param evaluations_file: name of the file in which the results are saved. """ iterations = np.array(range(1, self.Y.shape[0] + 1))[:, None] results = np.hsta...
python
def save_evaluations(self, evaluations_file = None): iterations = np.array(range(1, self.Y.shape[0] + 1))[:, None] results = np.hstack((iterations, self.Y, self.X)) header = ['Iteration', 'Y'] + ['var_' + str(k) for k in range(1, self.X.shape[1] + 1)] data = [header] + results.tolist() ...
[ "def", "save_evaluations", "(", "self", ",", "evaluations_file", "=", "None", ")", ":", "iterations", "=", "np", ".", "array", "(", "range", "(", "1", ",", "self", ".", "Y", ".", "shape", "[", "0", "]", "+", "1", ")", ")", "[", ":", ",", "None", ...
Saves evaluations at each iteration of the optimization :param evaluations_file: name of the file in which the results are saved.
[ "Saves", "evaluations", "at", "each", "iteration", "of", "the", "optimization" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/bo.py#L367-L378
242,072
SheffieldML/GPyOpt
GPyOpt/core/bo.py
BO.save_models
def save_models(self, models_file): """ Saves model parameters at each iteration of the optimization :param models_file: name of the file or a file buffer, in which the results are saved. """ if self.model_parameters_iterations is None: raise ValueError("No iteration...
python
def save_models(self, models_file): if self.model_parameters_iterations is None: raise ValueError("No iterations have been carried out yet and hence no iterations of the BO can be saved") iterations = np.array(range(1,self.model_parameters_iterations.shape[0]+1))[:,None] results = n...
[ "def", "save_models", "(", "self", ",", "models_file", ")", ":", "if", "self", ".", "model_parameters_iterations", "is", "None", ":", "raise", "ValueError", "(", "\"No iterations have been carried out yet and hence no iterations of the BO can be saved\"", ")", "iterations", ...
Saves model parameters at each iteration of the optimization :param models_file: name of the file or a file buffer, in which the results are saved.
[ "Saves", "model", "parameters", "at", "each", "iteration", "of", "the", "optimization" ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/core/bo.py#L380-L394
242,073
SheffieldML/GPyOpt
GPyOpt/methods/bayesian_optimization.py
BayesianOptimization._init_design_chooser
def _init_design_chooser(self): """ Initializes the choice of X and Y based on the selected initial design and number of points selected. """ # If objective function was not provided, we require some initial sample data if self.f is None and (self.X is None or self.Y is None): ...
python
def _init_design_chooser(self): # If objective function was not provided, we require some initial sample data if self.f is None and (self.X is None or self.Y is None): raise InvalidConfigError("Initial data for both X and Y is required when objective function is not provided") # Cas...
[ "def", "_init_design_chooser", "(", "self", ")", ":", "# If objective function was not provided, we require some initial sample data", "if", "self", ".", "f", "is", "None", "and", "(", "self", ".", "X", "is", "None", "or", "self", ".", "Y", "is", "None", ")", ":...
Initializes the choice of X and Y based on the selected initial design and number of points selected.
[ "Initializes", "the", "choice", "of", "X", "and", "Y", "based", "on", "the", "selected", "initial", "design", "and", "number", "of", "points", "selected", "." ]
255539dc5927819ca701e44fe3d76cd4864222fa
https://github.com/SheffieldML/GPyOpt/blob/255539dc5927819ca701e44fe3d76cd4864222fa/GPyOpt/methods/bayesian_optimization.py#L183-L198
242,074
coleifer/huey
huey/api.py
crontab
def crontab(minute='*', hour='*', day='*', month='*', day_of_week='*'): """ Convert a "crontab"-style set of parameters into a test function that will return True when the given datetime matches the parameters set forth in the crontab. For day-of-week, 0=Sunday and 6=Saturday. Acceptable input...
python
def crontab(minute='*', hour='*', day='*', month='*', day_of_week='*'): validation = ( ('m', month, range(1, 13)), ('d', day, range(1, 32)), ('w', day_of_week, range(8)), # 0-6, but also 7 for Sunday. ('H', hour, range(24)), ('M', minute, range(60)) ) cron_settings = ...
[ "def", "crontab", "(", "minute", "=", "'*'", ",", "hour", "=", "'*'", ",", "day", "=", "'*'", ",", "month", "=", "'*'", ",", "day_of_week", "=", "'*'", ")", ":", "validation", "=", "(", "(", "'m'", ",", "month", ",", "range", "(", "1", ",", "13...
Convert a "crontab"-style set of parameters into a test function that will return True when the given datetime matches the parameters set forth in the crontab. For day-of-week, 0=Sunday and 6=Saturday. Acceptable inputs: * = every distinct value */n = run every "n" times, i.e. hours='*/4' == 0...
[ "Convert", "a", "crontab", "-", "style", "set", "of", "parameters", "into", "a", "test", "function", "that", "will", "return", "True", "when", "the", "given", "datetime", "matches", "the", "parameters", "set", "forth", "in", "the", "crontab", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/api.py#L913-L990
242,075
coleifer/huey
huey/storage.py
BaseStorage.put_if_empty
def put_if_empty(self, key, value): """ Atomically write data only if the key is not already set. :param bytes key: Key to check/set. :param bytes value: Arbitrary data. :return: Boolean whether key/value was set. """ if self.has_data_for_key(key): re...
python
def put_if_empty(self, key, value): if self.has_data_for_key(key): return False self.put_data(key, value) return True
[ "def", "put_if_empty", "(", "self", ",", "key", ",", "value", ")", ":", "if", "self", ".", "has_data_for_key", "(", "key", ")", ":", "return", "False", "self", ".", "put_data", "(", "key", ",", "value", ")", "return", "True" ]
Atomically write data only if the key is not already set. :param bytes key: Key to check/set. :param bytes value: Arbitrary data. :return: Boolean whether key/value was set.
[ "Atomically", "write", "data", "only", "if", "the", "key", "is", "not", "already", "set", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/storage.py#L190-L201
242,076
coleifer/huey
huey/utils.py
make_naive
def make_naive(dt): """ Makes an aware datetime.datetime naive in local time zone. """ tt = dt.utctimetuple() ts = calendar.timegm(tt) local_tt = time.localtime(ts) return datetime.datetime(*local_tt[:6])
python
def make_naive(dt): tt = dt.utctimetuple() ts = calendar.timegm(tt) local_tt = time.localtime(ts) return datetime.datetime(*local_tt[:6])
[ "def", "make_naive", "(", "dt", ")", ":", "tt", "=", "dt", ".", "utctimetuple", "(", ")", "ts", "=", "calendar", ".", "timegm", "(", "tt", ")", "local_tt", "=", "time", ".", "localtime", "(", "ts", ")", "return", "datetime", ".", "datetime", "(", "...
Makes an aware datetime.datetime naive in local time zone.
[ "Makes", "an", "aware", "datetime", ".", "datetime", "naive", "in", "local", "time", "zone", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/utils.py#L48-L55
242,077
coleifer/huey
huey/consumer.py
BaseProcess.sleep_for_interval
def sleep_for_interval(self, start_ts, nseconds): """ Sleep for a given interval with respect to the start timestamp. So, if the start timestamp is 1337 and nseconds is 10, the method will actually sleep for nseconds - (current_timestamp - start_timestamp). So if the current tim...
python
def sleep_for_interval(self, start_ts, nseconds): sleep_time = nseconds - (time.time() - start_ts) if sleep_time <= 0: return self._logger.debug('Sleeping for %s', sleep_time) # Recompute time to sleep to improve accuracy in case the process was # pre-empted by the ke...
[ "def", "sleep_for_interval", "(", "self", ",", "start_ts", ",", "nseconds", ")", ":", "sleep_time", "=", "nseconds", "-", "(", "time", ".", "time", "(", ")", "-", "start_ts", ")", "if", "sleep_time", "<=", "0", ":", "return", "self", ".", "_logger", "....
Sleep for a given interval with respect to the start timestamp. So, if the start timestamp is 1337 and nseconds is 10, the method will actually sleep for nseconds - (current_timestamp - start_timestamp). So if the current timestamp is 1340, we'll only sleep for 7 seconds (the goal being...
[ "Sleep", "for", "a", "given", "interval", "with", "respect", "to", "the", "start", "timestamp", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/consumer.py#L39-L56
242,078
coleifer/huey
huey/consumer.py
Consumer.start
def start(self): """ Start all consumer processes and register signal handlers. """ if self.huey.immediate: raise ConfigurationError( 'Consumer cannot be run with Huey instances where immediate ' 'is enabled. Please check your configuration and...
python
def start(self): if self.huey.immediate: raise ConfigurationError( 'Consumer cannot be run with Huey instances where immediate ' 'is enabled. Please check your configuration and ensure that ' '"huey.immediate = False".') # Log startup message. ...
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "huey", ".", "immediate", ":", "raise", "ConfigurationError", "(", "'Consumer cannot be run with Huey instances where immediate '", "'is enabled. Please check your configuration and ensure that '", "'\"huey.immediate = Fal...
Start all consumer processes and register signal handlers.
[ "Start", "all", "consumer", "processes", "and", "register", "signal", "handlers", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/consumer.py#L344-L383
242,079
coleifer/huey
huey/consumer.py
Consumer.stop
def stop(self, graceful=False): """ Set the stop-flag. If `graceful=True`, this method blocks until the workers to finish executing any tasks they might be currently working on. """ self.stop_flag.set() if graceful: self._logger.info('Shutting down gr...
python
def stop(self, graceful=False): self.stop_flag.set() if graceful: self._logger.info('Shutting down gracefully...') try: for _, worker_process in self.worker_threads: worker_process.join() except KeyboardInterrupt: se...
[ "def", "stop", "(", "self", ",", "graceful", "=", "False", ")", ":", "self", ".", "stop_flag", ".", "set", "(", ")", "if", "graceful", ":", "self", ".", "_logger", ".", "info", "(", "'Shutting down gracefully...'", ")", "try", ":", "for", "_", ",", "...
Set the stop-flag. If `graceful=True`, this method blocks until the workers to finish executing any tasks they might be currently working on.
[ "Set", "the", "stop", "-", "flag", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/consumer.py#L385-L403
242,080
coleifer/huey
huey/consumer.py
Consumer.run
def run(self): """ Run the consumer. """ self.start() timeout = self._stop_flag_timeout health_check_ts = time.time() while True: try: self.stop_flag.wait(timeout=timeout) except KeyboardInterrupt: self._log...
python
def run(self): self.start() timeout = self._stop_flag_timeout health_check_ts = time.time() while True: try: self.stop_flag.wait(timeout=timeout) except KeyboardInterrupt: self._logger.info('Received SIGINT') self.s...
[ "def", "run", "(", "self", ")", ":", "self", ".", "start", "(", ")", "timeout", "=", "self", ".", "_stop_flag_timeout", "health_check_ts", "=", "time", ".", "time", "(", ")", "while", "True", ":", "try", ":", "self", ".", "stop_flag", ".", "wait", "(...
Run the consumer.
[ "Run", "the", "consumer", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/consumer.py#L405-L440
242,081
coleifer/huey
huey/consumer.py
Consumer.check_worker_health
def check_worker_health(self): """ Check the health of the worker processes. Workers that have died will be replaced with new workers. """ self._logger.debug('Checking worker health.') workers = [] restart_occurred = False for i, (worker, worker_t) in enum...
python
def check_worker_health(self): self._logger.debug('Checking worker health.') workers = [] restart_occurred = False for i, (worker, worker_t) in enumerate(self.worker_threads): if not self.environment.is_alive(worker_t): self._logger.warning('Worker %d died, re...
[ "def", "check_worker_health", "(", "self", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'Checking worker health.'", ")", "workers", "=", "[", "]", "restart_occurred", "=", "False", "for", "i", ",", "(", "worker", ",", "worker_t", ")", "in", "enume...
Check the health of the worker processes. Workers that have died will be replaced with new workers.
[ "Check", "the", "health", "of", "the", "worker", "processes", ".", "Workers", "that", "have", "died", "will", "be", "replaced", "with", "new", "workers", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/consumer.py#L442-L472
242,082
coleifer/huey
huey/contrib/djhuey/__init__.py
close_db
def close_db(fn): """Decorator to be used with tasks that may operate on the database.""" @wraps(fn) def inner(*args, **kwargs): try: return fn(*args, **kwargs) finally: if not HUEY.immediate: close_old_connections() return inner
python
def close_db(fn): @wraps(fn) def inner(*args, **kwargs): try: return fn(*args, **kwargs) finally: if not HUEY.immediate: close_old_connections() return inner
[ "def", "close_db", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "finally", ":", "if", "not"...
Decorator to be used with tasks that may operate on the database.
[ "Decorator", "to", "be", "used", "with", "tasks", "that", "may", "operate", "on", "the", "database", "." ]
416e8da1ca18442c08431a91bce373de7d2d200f
https://github.com/coleifer/huey/blob/416e8da1ca18442c08431a91bce373de7d2d200f/huey/contrib/djhuey/__init__.py#L123-L132
242,083
johnwheeler/flask-ask
samples/purchase/model.py
Product.list
def list(self): """ return list of purchasable and not entitled products""" mylist = [] for prod in self.product_list: if self.purchasable(prod) and not self.entitled(prod): mylist.append(prod) return mylist
python
def list(self): mylist = [] for prod in self.product_list: if self.purchasable(prod) and not self.entitled(prod): mylist.append(prod) return mylist
[ "def", "list", "(", "self", ")", ":", "mylist", "=", "[", "]", "for", "prod", "in", "self", ".", "product_list", ":", "if", "self", ".", "purchasable", "(", "prod", ")", "and", "not", "self", ".", "entitled", "(", "prod", ")", ":", "mylist", ".", ...
return list of purchasable and not entitled products
[ "return", "list", "of", "purchasable", "and", "not", "entitled", "products" ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/samples/purchase/model.py#L51-L57
242,084
johnwheeler/flask-ask
samples/tidepooler/tidepooler.py
_find_tide_info
def _find_tide_info(predictions): """ Algorithm to find the 2 high tides for the day, the first of which is smaller and occurs mid-day, the second of which is larger and typically in the evening. """ last_prediction = None first_high_tide = None second_high_tide = None low_tide = None...
python
def _find_tide_info(predictions): last_prediction = None first_high_tide = None second_high_tide = None low_tide = None first_tide_done = False for prediction in predictions: if last_prediction is None: last_prediction = prediction continue if last_predict...
[ "def", "_find_tide_info", "(", "predictions", ")", ":", "last_prediction", "=", "None", "first_high_tide", "=", "None", "second_high_tide", "=", "None", "low_tide", "=", "None", "first_tide_done", "=", "False", "for", "prediction", "in", "predictions", ":", "if", ...
Algorithm to find the 2 high tides for the day, the first of which is smaller and occurs mid-day, the second of which is larger and typically in the evening.
[ "Algorithm", "to", "find", "the", "2", "high", "tides", "for", "the", "day", "the", "first", "of", "which", "is", "smaller", "and", "occurs", "mid", "-", "day", "the", "second", "of", "which", "is", "larger", "and", "typically", "in", "the", "evening", ...
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/samples/tidepooler/tidepooler.py#L252-L290
242,085
johnwheeler/flask-ask
flask_ask/models.py
audio.enqueue
def enqueue(self, stream_url, offset=0, opaque_token=None): """Adds stream to the queue. Does not impact the currently playing stream.""" directive = self._play_directive('ENQUEUE') audio_item = self._audio_item(stream_url=stream_url, offset=offset, ...
python
def enqueue(self, stream_url, offset=0, opaque_token=None): directive = self._play_directive('ENQUEUE') audio_item = self._audio_item(stream_url=stream_url, offset=offset, push_buffer=False, ...
[ "def", "enqueue", "(", "self", ",", "stream_url", ",", "offset", "=", "0", ",", "opaque_token", "=", "None", ")", ":", "directive", "=", "self", ".", "_play_directive", "(", "'ENQUEUE'", ")", "audio_item", "=", "self", ".", "_audio_item", "(", "stream_url"...
Adds stream to the queue. Does not impact the currently playing stream.
[ "Adds", "stream", "to", "the", "queue", ".", "Does", "not", "impact", "the", "currently", "playing", "stream", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/models.py#L364-L375
242,086
johnwheeler/flask-ask
flask_ask/models.py
audio.play_next
def play_next(self, stream_url=None, offset=0, opaque_token=None): """Replace all streams in the queue but does not impact the currently playing stream.""" directive = self._play_directive('REPLACE_ENQUEUED') directive['audioItem'] = self._audio_item(stream_url=stream_url, offset=offset, opaque...
python
def play_next(self, stream_url=None, offset=0, opaque_token=None): directive = self._play_directive('REPLACE_ENQUEUED') directive['audioItem'] = self._audio_item(stream_url=stream_url, offset=offset, opaque_token=opaque_token) self._response['directives'].append(directive) return self
[ "def", "play_next", "(", "self", ",", "stream_url", "=", "None", ",", "offset", "=", "0", ",", "opaque_token", "=", "None", ")", ":", "directive", "=", "self", ".", "_play_directive", "(", "'REPLACE_ENQUEUED'", ")", "directive", "[", "'audioItem'", "]", "=...
Replace all streams in the queue but does not impact the currently playing stream.
[ "Replace", "all", "streams", "in", "the", "queue", "but", "does", "not", "impact", "the", "currently", "playing", "stream", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/models.py#L377-L383
242,087
johnwheeler/flask-ask
flask_ask/models.py
audio.resume
def resume(self): """Sends Play Directive to resume playback at the paused offset""" directive = self._play_directive('REPLACE_ALL') directive['audioItem'] = self._audio_item() self._response['directives'].append(directive) return self
python
def resume(self): directive = self._play_directive('REPLACE_ALL') directive['audioItem'] = self._audio_item() self._response['directives'].append(directive) return self
[ "def", "resume", "(", "self", ")", ":", "directive", "=", "self", ".", "_play_directive", "(", "'REPLACE_ALL'", ")", "directive", "[", "'audioItem'", "]", "=", "self", ".", "_audio_item", "(", ")", "self", ".", "_response", "[", "'directives'", "]", ".", ...
Sends Play Directive to resume playback at the paused offset
[ "Sends", "Play", "Directive", "to", "resume", "playback", "at", "the", "paused", "offset" ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/models.py#L385-L390
242,088
johnwheeler/flask-ask
flask_ask/models.py
audio._audio_item
def _audio_item(self, stream_url=None, offset=0, push_buffer=True, opaque_token=None): """Builds an AudioPlayer Directive's audioItem and updates current_stream""" audio_item = {'stream': {}} stream = audio_item['stream'] # existing stream if not stream_url: # stream...
python
def _audio_item(self, stream_url=None, offset=0, push_buffer=True, opaque_token=None): audio_item = {'stream': {}} stream = audio_item['stream'] # existing stream if not stream_url: # stream.update(current_stream.__dict__) stream['url'] = current_stream.url ...
[ "def", "_audio_item", "(", "self", ",", "stream_url", "=", "None", ",", "offset", "=", "0", ",", "push_buffer", "=", "True", ",", "opaque_token", "=", "None", ")", ":", "audio_item", "=", "{", "'stream'", ":", "{", "}", "}", "stream", "=", "audio_item"...
Builds an AudioPlayer Directive's audioItem and updates current_stream
[ "Builds", "an", "AudioPlayer", "Directive", "s", "audioItem", "and", "updates", "current_stream" ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/models.py#L398-L418
242,089
johnwheeler/flask-ask
flask_ask/models.py
audio.clear_queue
def clear_queue(self, stop=False): """Clears queued streams and optionally stops current stream. Keyword Arguments: stop {bool} set True to stop current current stream and clear queued streams. set False to clear queued streams and allow current stream to finish ...
python
def clear_queue(self, stop=False): directive = {} directive['type'] = 'AudioPlayer.ClearQueue' if stop: directive['clearBehavior'] = 'CLEAR_ALL' else: directive['clearBehavior'] = 'CLEAR_ENQUEUED' self._response['directives'].append(directive) ret...
[ "def", "clear_queue", "(", "self", ",", "stop", "=", "False", ")", ":", "directive", "=", "{", "}", "directive", "[", "'type'", "]", "=", "'AudioPlayer.ClearQueue'", "if", "stop", ":", "directive", "[", "'clearBehavior'", "]", "=", "'CLEAR_ALL'", "else", "...
Clears queued streams and optionally stops current stream. Keyword Arguments: stop {bool} set True to stop current current stream and clear queued streams. set False to clear queued streams and allow current stream to finish default: {False}
[ "Clears", "queued", "streams", "and", "optionally", "stops", "current", "stream", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/models.py#L425-L442
242,090
johnwheeler/flask-ask
flask_ask/core.py
find_ask
def find_ask(): """ Find our instance of Ask, navigating Local's and possible blueprints. Note: This only supports returning a reference to the first instance of Ask found. """ if hasattr(current_app, 'ask'): return getattr(current_app, 'ask') else: if hasattr(current_app, '...
python
def find_ask(): if hasattr(current_app, 'ask'): return getattr(current_app, 'ask') else: if hasattr(current_app, 'blueprints'): blueprints = getattr(current_app, 'blueprints') for blueprint_name in blueprints: if hasattr(blueprints[blueprint_name], 'ask'):...
[ "def", "find_ask", "(", ")", ":", "if", "hasattr", "(", "current_app", ",", "'ask'", ")", ":", "return", "getattr", "(", "current_app", ",", "'ask'", ")", "else", ":", "if", "hasattr", "(", "current_app", ",", "'blueprints'", ")", ":", "blueprints", "=",...
Find our instance of Ask, navigating Local's and possible blueprints. Note: This only supports returning a reference to the first instance of Ask found.
[ "Find", "our", "instance", "of", "Ask", "navigating", "Local", "s", "and", "possible", "blueprints", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L21-L35
242,091
johnwheeler/flask-ask
flask_ask/core.py
Ask.init_app
def init_app(self, app, path='templates.yaml'): """Initializes Ask app by setting configuration variables, loading templates, and maps Ask route to a flask view. The Ask instance is given the following configuration variables by calling on Flask's configuration: `ASK_APPLICATION_ID`: ...
python
def init_app(self, app, path='templates.yaml'): if self._route is None: raise TypeError("route is a required argument when app is not None") self.app = app app.ask = self app.add_url_rule(self._route, view_func=self._flask_view_func, methods=['POST']) app.j...
[ "def", "init_app", "(", "self", ",", "app", ",", "path", "=", "'templates.yaml'", ")", ":", "if", "self", ".", "_route", "is", "None", ":", "raise", "TypeError", "(", "\"route is a required argument when app is not None\"", ")", "self", ".", "app", "=", "app",...
Initializes Ask app by setting configuration variables, loading templates, and maps Ask route to a flask view. The Ask instance is given the following configuration variables by calling on Flask's configuration: `ASK_APPLICATION_ID`: Turn on application ID verification by setting this var...
[ "Initializes", "Ask", "app", "by", "setting", "configuration", "variables", "loading", "templates", "and", "maps", "Ask", "route", "to", "a", "flask", "view", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L101-L142
242,092
johnwheeler/flask-ask
flask_ask/core.py
Ask.launch
def launch(self, f): """Decorator maps a view function as the endpoint for an Alexa LaunchRequest and starts the skill. @ask.launch def launched(): return question('Welcome to Foo') The wrapped function is registered as the launch view function and renders the response ...
python
def launch(self, f): self._launch_view_func = f @wraps(f) def wrapper(*args, **kw): self._flask_view_func(*args, **kw) return f
[ "def", "launch", "(", "self", ",", "f", ")", ":", "self", ".", "_launch_view_func", "=", "f", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "self", ".", "_flask_view_func", "(", "*", "args", ",", ...
Decorator maps a view function as the endpoint for an Alexa LaunchRequest and starts the skill. @ask.launch def launched(): return question('Welcome to Foo') The wrapped function is registered as the launch view function and renders the response for requests to the Launch U...
[ "Decorator", "maps", "a", "view", "function", "as", "the", "endpoint", "for", "an", "Alexa", "LaunchRequest", "and", "starts", "the", "skill", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L192-L212
242,093
johnwheeler/flask-ask
flask_ask/core.py
Ask.session_ended
def session_ended(self, f): """Decorator routes Alexa SessionEndedRequest to the wrapped view function to end the skill. @ask.session_ended def session_ended(): return "{}", 200 The wrapped function is registered as the session_ended view function and renders the re...
python
def session_ended(self, f): self._session_ended_view_func = f @wraps(f) def wrapper(*args, **kw): self._flask_view_func(*args, **kw) return f
[ "def", "session_ended", "(", "self", ",", "f", ")", ":", "self", ".", "_session_ended_view_func", "=", "f", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "self", ".", "_flask_view_func", "(", "*", "...
Decorator routes Alexa SessionEndedRequest to the wrapped view function to end the skill. @ask.session_ended def session_ended(): return "{}", 200 The wrapped function is registered as the session_ended view function and renders the response for requests to the end of the s...
[ "Decorator", "routes", "Alexa", "SessionEndedRequest", "to", "the", "wrapped", "view", "function", "to", "end", "the", "skill", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L214-L232
242,094
johnwheeler/flask-ask
flask_ask/core.py
Ask.intent
def intent(self, intent_name, mapping={}, convert={}, default={}): """Decorator routes an Alexa IntentRequest and provides the slot parameters to the wrapped function. Functions decorated as an intent are registered as the view function for the Intent's URL, and provide the backend responses to...
python
def intent(self, intent_name, mapping={}, convert={}, default={}): def decorator(f): self._intent_view_funcs[intent_name] = f self._intent_mappings[intent_name] = mapping self._intent_converts[intent_name] = convert self._intent_defaults[intent_name] = default ...
[ "def", "intent", "(", "self", ",", "intent_name", ",", "mapping", "=", "{", "}", ",", "convert", "=", "{", "}", ",", "default", "=", "{", "}", ")", ":", "def", "decorator", "(", "f", ")", ":", "self", ".", "_intent_view_funcs", "[", "intent_name", ...
Decorator routes an Alexa IntentRequest and provides the slot parameters to the wrapped function. Functions decorated as an intent are registered as the view function for the Intent's URL, and provide the backend responses to give your Skill its functionality. @ask.intent('WeatherIntent', mapp...
[ "Decorator", "routes", "an", "Alexa", "IntentRequest", "and", "provides", "the", "slot", "parameters", "to", "the", "wrapped", "function", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L234-L268
242,095
johnwheeler/flask-ask
flask_ask/core.py
Ask.default_intent
def default_intent(self, f): """Decorator routes any Alexa IntentRequest that is not matched by any existing @ask.intent routing.""" self._default_intent_view_func = f @wraps(f) def wrapper(*args, **kw): self._flask_view_func(*args, **kw) return f
python
def default_intent(self, f): self._default_intent_view_func = f @wraps(f) def wrapper(*args, **kw): self._flask_view_func(*args, **kw) return f
[ "def", "default_intent", "(", "self", ",", "f", ")", ":", "self", ".", "_default_intent_view_func", "=", "f", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "self", ".", "_flask_view_func", "(", "*", ...
Decorator routes any Alexa IntentRequest that is not matched by any existing @ask.intent routing.
[ "Decorator", "routes", "any", "Alexa", "IntentRequest", "that", "is", "not", "matched", "by", "any", "existing" ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L270-L277
242,096
johnwheeler/flask-ask
flask_ask/core.py
Ask.display_element_selected
def display_element_selected(self, f): """Decorator routes Alexa Display.ElementSelected request to the wrapped view function. @ask.display_element_selected def eval_element(): return "", 200 The wrapped function is registered as the display_element_selected view function ...
python
def display_element_selected(self, f): self._display_element_selected_func = f @wraps(f) def wrapper(*args, **kw): self._flask_view_func(*args, **kw) return f
[ "def", "display_element_selected", "(", "self", ",", "f", ")", ":", "self", ".", "_display_element_selected_func", "=", "f", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "self", ".", "_flask_view_func", ...
Decorator routes Alexa Display.ElementSelected request to the wrapped view function. @ask.display_element_selected def eval_element(): return "", 200 The wrapped function is registered as the display_element_selected view function and renders the response for requests. ...
[ "Decorator", "routes", "Alexa", "Display", ".", "ElementSelected", "request", "to", "the", "wrapped", "view", "function", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L279-L297
242,097
johnwheeler/flask-ask
flask_ask/core.py
Ask.on_purchase_completed
def on_purchase_completed(self, mapping={'payload': 'payload','name':'name','status':'status','token':'token'}, convert={}, default={}): """Decorator routes an Connections.Response to the wrapped function. Request is sent when Alexa completes the purchase flow. See https://developer.amazon.co...
python
def on_purchase_completed(self, mapping={'payload': 'payload','name':'name','status':'status','token':'token'}, convert={}, default={}): def decorator(f): self._intent_view_funcs['Connections.Response'] = f self._intent_mappings['Connections.Response'] = mapping self._intent_...
[ "def", "on_purchase_completed", "(", "self", ",", "mapping", "=", "{", "'payload'", ":", "'payload'", ",", "'name'", ":", "'name'", ",", "'status'", ":", "'status'", ",", "'token'", ":", "'token'", "}", ",", "convert", "=", "{", "}", ",", "default", "=",...
Decorator routes an Connections.Response to the wrapped function. Request is sent when Alexa completes the purchase flow. See https://developer.amazon.com/docs/in-skill-purchase/add-isps-to-a-skill.html#handle-results The wrapped view function may accept parameters from the Request. ...
[ "Decorator", "routes", "an", "Connections", ".", "Response", "to", "the", "wrapped", "function", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L300-L328
242,098
johnwheeler/flask-ask
flask_ask/core.py
Ask.run_aws_lambda
def run_aws_lambda(self, event): """Invoke the Flask Ask application from an AWS Lambda function handler. Use this method to service AWS Lambda requests from a custom Alexa skill. This method will invoke your Flask application providing a WSGI-compatible environment that wraps the origi...
python
def run_aws_lambda(self, event): # We are guaranteed to be called by AWS as a Lambda function does not # expose a public facing interface. self.app.config['ASK_VERIFY_REQUESTS'] = False # Convert an environment variable to a WSGI "bytes-as-unicode" string enc, esc = sys.getfiles...
[ "def", "run_aws_lambda", "(", "self", ",", "event", ")", ":", "# We are guaranteed to be called by AWS as a Lambda function does not", "# expose a public facing interface.", "self", ".", "app", ".", "config", "[", "'ASK_VERIFY_REQUESTS'", "]", "=", "False", "# Convert an envi...
Invoke the Flask Ask application from an AWS Lambda function handler. Use this method to service AWS Lambda requests from a custom Alexa skill. This method will invoke your Flask application providing a WSGI-compatible environment that wraps the original Alexa event provided to the AWS ...
[ "Invoke", "the", "Flask", "Ask", "application", "from", "an", "AWS", "Lambda", "function", "handler", "." ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L585-L683
242,099
johnwheeler/flask-ask
flask_ask/core.py
Ask._parse_timestamp
def _parse_timestamp(timestamp): """ Parse a given timestamp value, raising ValueError if None or Flasey """ if timestamp: try: return aniso8601.parse_datetime(timestamp) except AttributeError: # raised by aniso8601 if raw_timestamp...
python
def _parse_timestamp(timestamp): if timestamp: try: return aniso8601.parse_datetime(timestamp) except AttributeError: # raised by aniso8601 if raw_timestamp is not valid string # in ISO8601 format try: re...
[ "def", "_parse_timestamp", "(", "timestamp", ")", ":", "if", "timestamp", ":", "try", ":", "return", "aniso8601", ".", "parse_datetime", "(", "timestamp", ")", "except", "AttributeError", ":", "# raised by aniso8601 if raw_timestamp is not valid string", "# in ISO8601 for...
Parse a given timestamp value, raising ValueError if None or Flasey
[ "Parse", "a", "given", "timestamp", "value", "raising", "ValueError", "if", "None", "or", "Flasey" ]
fe407646ae404a8c90b363c86d5c4c201b6a5580
https://github.com/johnwheeler/flask-ask/blob/fe407646ae404a8c90b363c86d5c4c201b6a5580/flask_ask/core.py#L724-L740