language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
Python | def calc_K(self, r):
r"""
Calculate kernel as a function of distance
This method implements the kernel function as a function of distance. Given an array
of distances, this function evaluates the kernel function of those values, returning
an array of the same shape. Note that this is not implemented for the base class, as
this must be defined for a specific kernel.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel evaluations, with the same shape as the input ``r``
:rtype: ndarray
"""
raise NotImplementedError("base Kernel class does not implement a kernel function") | def calc_K(self, r):
r"""
Calculate kernel as a function of distance
This method implements the kernel function as a function of distance. Given an array
of distances, this function evaluates the kernel function of those values, returning
an array of the same shape. Note that this is not implemented for the base class, as
this must be defined for a specific kernel.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel evaluations, with the same shape as the input ``r``
:rtype: ndarray
"""
raise NotImplementedError("base Kernel class does not implement a kernel function") |
Python | def calc_dKdr(self, r):
r"""
Calculate first derivative of kernel as a function of distance
This method implements the first derivative of the kernel function as a function of
distance. Given an array of distances, this function evaluates the derivative
function of those values, returning an array of the same shape. Note that this is
not implemented for the base class, as this must be defined for a specific kernel.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel derivatives, with the same shape as the input ``r``
:rtype: ndarray
"""
raise NotImplementedError("base Kernel class does not implement a kernel derivative function") | def calc_dKdr(self, r):
r"""
Calculate first derivative of kernel as a function of distance
This method implements the first derivative of the kernel function as a function of
distance. Given an array of distances, this function evaluates the derivative
function of those values, returning an array of the same shape. Note that this is
not implemented for the base class, as this must be defined for a specific kernel.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel derivatives, with the same shape as the input ``r``
:rtype: ndarray
"""
raise NotImplementedError("base Kernel class does not implement a kernel derivative function") |
Python | def calc_d2Kdr2(self, r):
r"""
Calculate second derivative of kernel as a function of distance
This method implements the second derivative of the kernel function as a function of
distance. Given an array of distances, this function evaluates the second derivative
function of those values, returning an array of the same shape. Note that this is
not implemented for the base class, as this must be defined for a specific kernel.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel second derivatives, with the same shape as the input ``r``
:rtype: ndarray
"""
raise NotImplementedError("base Kernel class does not implement kernel derivatives") | def calc_d2Kdr2(self, r):
r"""
Calculate second derivative of kernel as a function of distance
This method implements the second derivative of the kernel function as a function of
distance. Given an array of distances, this function evaluates the second derivative
function of those values, returning an array of the same shape. Note that this is
not implemented for the base class, as this must be defined for a specific kernel.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel second derivatives, with the same shape as the input ``r``
:rtype: ndarray
"""
raise NotImplementedError("base Kernel class does not implement kernel derivatives") |
Python | def calc_K(self, r):
r"""
Compute K(r) for the squared exponential kernel
This method implements the squared exponential kernel function as a function of distance.
Given an array of distances, this function evaluates the kernel function of those values,
returning an array of the same shape.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel evaluations, with the same shape as the input ``r``
:rtype: ndarray
"""
assert np.all(r >= 0.), "kernel distances must be positive"
r = np.array(r)
return np.exp(-0.5*r**2) | def calc_K(self, r):
r"""
Compute K(r) for the squared exponential kernel
This method implements the squared exponential kernel function as a function of distance.
Given an array of distances, this function evaluates the kernel function of those values,
returning an array of the same shape.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel evaluations, with the same shape as the input ``r``
:rtype: ndarray
"""
assert np.all(r >= 0.), "kernel distances must be positive"
r = np.array(r)
return np.exp(-0.5*r**2) |
Python | def calc_dKdr(self, r):
r"""
Calculate first derivative of the squared exponential kernel as a function of distance
This method implements the first derivative of the squared exponential kernel function
as a function of distance. Given an array of distances, this function evaluates the derivative
function of those values, returning an array of the same shape.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel derivatives, with the same shape as the input ``r``
:rtype: ndarray
"""
assert np.all(r >= 0.), "kernel distances must be positive"
r = np.array(r)
return -r*np.exp(-0.5*r**2) | def calc_dKdr(self, r):
r"""
Calculate first derivative of the squared exponential kernel as a function of distance
This method implements the first derivative of the squared exponential kernel function
as a function of distance. Given an array of distances, this function evaluates the derivative
function of those values, returning an array of the same shape.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel derivatives, with the same shape as the input ``r``
:rtype: ndarray
"""
assert np.all(r >= 0.), "kernel distances must be positive"
r = np.array(r)
return -r*np.exp(-0.5*r**2) |
Python | def calc_d2Kdr2(self, r):
r"""
Calculate second derivative of the squared exponential kernel as a function of distance
This method implements the second derivative of the squared exponential kernel function
as a function of distance. Given an array of distances, this function evaluates the
second derivative function of those values, returning an array of the same shape.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel second derivatives, with the same shape as the input ``r``
:rtype: ndarray
"""
assert np.all(r >= 0.), "kernel distances must be positive"
r = np.array(r)
return (r**2 - 1.)*np.exp(-0.5*r**2) | def calc_d2Kdr2(self, r):
r"""
Calculate second derivative of the squared exponential kernel as a function of distance
This method implements the second derivative of the squared exponential kernel function
as a function of distance. Given an array of distances, this function evaluates the
second derivative function of those values, returning an array of the same shape.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel second derivatives, with the same shape as the input ``r``
:rtype: ndarray
"""
assert np.all(r >= 0.), "kernel distances must be positive"
r = np.array(r)
return (r**2 - 1.)*np.exp(-0.5*r**2) |
Python | def calc_K(self, r):
r"""
Compute K(r) for the Matern 5/2 kernel
This method implements the Matern 5/2 kernel function as a function of distance.
Given an array of distances, this function evaluates the kernel function of those values,
returning an array of the same shape.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel evaluations, with the same shape as the input ``r``
:rtype: ndarray
"""
assert np.all(r >= 0.), "kernel distances must be positive"
r = np.array(r)
return (1.+np.sqrt(5.)*r+5./3.*r**2)*np.exp(-np.sqrt(5.)*r) | def calc_K(self, r):
r"""
Compute K(r) for the Matern 5/2 kernel
This method implements the Matern 5/2 kernel function as a function of distance.
Given an array of distances, this function evaluates the kernel function of those values,
returning an array of the same shape.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel evaluations, with the same shape as the input ``r``
:rtype: ndarray
"""
assert np.all(r >= 0.), "kernel distances must be positive"
r = np.array(r)
return (1.+np.sqrt(5.)*r+5./3.*r**2)*np.exp(-np.sqrt(5.)*r) |
Python | def calc_dKdr(self, r):
r"""
Calculate first derivative of the Matern 5/2 kernel as a function of distance
This method implements the first derivative of the Matern 5/2 kernel function
as a function of distance. Given an array of distances, this function evaluates the derivative
function of those values, returning an array of the same shape.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel derivatives, with the same shape as the input ``r``
:rtype: ndarray
"""
assert np.all(r >= 0.), "kernel distances must be positive"
r = np.array(r)
return -5./3.*r*(1.+np.sqrt(5.)*r)*np.exp(-np.sqrt(5.)*r) | def calc_dKdr(self, r):
r"""
Calculate first derivative of the Matern 5/2 kernel as a function of distance
This method implements the first derivative of the Matern 5/2 kernel function
as a function of distance. Given an array of distances, this function evaluates the derivative
function of those values, returning an array of the same shape.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel derivatives, with the same shape as the input ``r``
:rtype: ndarray
"""
assert np.all(r >= 0.), "kernel distances must be positive"
r = np.array(r)
return -5./3.*r*(1.+np.sqrt(5.)*r)*np.exp(-np.sqrt(5.)*r) |
Python | def calc_d2Kdr2(self, r):
r"""
Calculate second derivative of the squared exponential kernel as a function of distance
This method implements the second derivative of the squared exponential kernel function
as a function of distance. Given an array of distances, this function evaluates the
second derivative function of those values, returning an array of the same shape.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel second derivatives, with the same shape as the input ``r``
:rtype: ndarray
"""
assert np.all(r >= 0.), "kernel distances must be positive"
r = np.array(r)
return 5./3.*(5.*r**2-np.sqrt(5.)*r-1.)*np.exp(-np.sqrt(5.)*r) | def calc_d2Kdr2(self, r):
r"""
Calculate second derivative of the squared exponential kernel as a function of distance
This method implements the second derivative of the squared exponential kernel function
as a function of distance. Given an array of distances, this function evaluates the
second derivative function of those values, returning an array of the same shape.
:param r: Array holding distances between all points. All values in this array must be
non-negative.
:type r: array-like
:returns: Array holding kernel second derivatives, with the same shape as the input ``r``
:rtype: ndarray
"""
assert np.all(r >= 0.), "kernel distances must be positive"
r = np.array(r)
return 5./3.*(5.*r**2-np.sqrt(5.)*r-1.)*np.exp(-np.sqrt(5.)*r) |
Python | def n(self):
"""
Returns number of training examples for the emulator
:returns: Number of training examples for the emulator object
:rtype: int
"""
return self.inputs.shape[0] | def n(self):
"""
Returns number of training examples for the emulator
:returns: Number of training examples for the emulator object
:rtype: int
"""
return self.inputs.shape[0] |
Python | def D(self):
"""
Returns number of inputs for the emulator
:returns: Number of inputs for the emulator object
:rtype: int
"""
return self.inputs.shape[1] | def D(self):
"""
Returns number of inputs for the emulator
:returns: Number of inputs for the emulator object
:rtype: int
"""
return self.inputs.shape[1] |
Python | def n_params(self):
"""Returns number of hyperparameters
Returns the number of hyperparameters for the emulator. The
number depends on the choice of mean function, covariance
function, and nugget strategy, and possibly the number of
inputs for certain choices of the mean function.
:returns: Number of hyperparameters
:rtype: int
"""
return self.mean.get_n_params(self.inputs) + self.D + 2 | def n_params(self):
"""Returns number of hyperparameters
Returns the number of hyperparameters for the emulator. The
number depends on the choice of mean function, covariance
function, and nugget strategy, and possibly the number of
inputs for certain choices of the mean function.
:returns: Number of hyperparameters
:rtype: int
"""
return self.mean.get_n_params(self.inputs) + self.D + 2 |
Python | def nugget(self):
"""Returns emulator nugget parameter
Returns current value of the nugget parameter. If the nugget
is to be selected adaptively, by pivoting, or by fitting the
emulator and the nugget has not been fit, returns ``None``.
:returns: Current nugget value, either a float or ``None``
:rtype: float or None
The ``nugget`` parameter controls how noise is added to the
covariance matrix in order to stabilize the inversion or
smooth the emulator predictions. If ``nugget`` is a
non-negative float, then that particular value is used for the
nugget. Note that setting this parameter to be zero enforces
that the emulator strictly interpolates between
points. Alternatively, a string can be provided. A value of
``"fit"`` means that the nugget is treated as a
hyperparameter, and is the last entry in the ``theta``
array. Alternatively, if ``nugget`` is set to be
``"adaptive"``, the fitting routine will adaptively make the
noise parameter as large as is needed to ensure that the
emulator can be fit. Finally, pivoting can be selected by
setting to ``"pivot"``, which will ignore any collinear rows
in the covariance matrix.
Internally, this modifies both the way the nugget is chosen
(which can be determined via the ``nugget_type`` property) and
the value itself (the ``nugget`` property)
:param nugget: Noise to be added to the diagonal, specified as
a string or a float. A non-negative float
specifies the noise level explicitly, while a
string indicates that the nugget will be found
via fitting, either as ``"adaptive"``,
``"pivot"``, or ``"fit"`` (see above for a
description).
:type nugget: float or str
:returns: None
:rtype: None
"""
return self._nugget | def nugget(self):
"""Returns emulator nugget parameter
Returns current value of the nugget parameter. If the nugget
is to be selected adaptively, by pivoting, or by fitting the
emulator and the nugget has not been fit, returns ``None``.
:returns: Current nugget value, either a float or ``None``
:rtype: float or None
The ``nugget`` parameter controls how noise is added to the
covariance matrix in order to stabilize the inversion or
smooth the emulator predictions. If ``nugget`` is a
non-negative float, then that particular value is used for the
nugget. Note that setting this parameter to be zero enforces
that the emulator strictly interpolates between
points. Alternatively, a string can be provided. A value of
``"fit"`` means that the nugget is treated as a
hyperparameter, and is the last entry in the ``theta``
array. Alternatively, if ``nugget`` is set to be
``"adaptive"``, the fitting routine will adaptively make the
noise parameter as large as is needed to ensure that the
emulator can be fit. Finally, pivoting can be selected by
setting to ``"pivot"``, which will ignore any collinear rows
in the covariance matrix.
Internally, this modifies both the way the nugget is chosen
(which can be determined via the ``nugget_type`` property) and
the value itself (the ``nugget`` property)
:param nugget: Noise to be added to the diagonal, specified as
a string or a float. A non-negative float
specifies the noise level explicitly, while a
string indicates that the nugget will be found
via fitting, either as ``"adaptive"``,
``"pivot"``, or ``"fit"`` (see above for a
description).
:type nugget: float or str
:returns: None
:rtype: None
"""
return self._nugget |
Python | def nugget(self, nugget):
"""Set the nugget parameter for the emulator
Method for changing the ``nugget`` parameter for the
emulator. When a new emulator is initilized, this is set to
None.
The ``nugget`` parameter controls how noise is added to the
covariance matrix in order to stabilize the inversion or
smooth the emulator predictions. If ``nugget`` is a
non-negative float, then that particular value is used for the
nugget. Note that setting this parameter to be zero enforces
that the emulator strictly interpolates between
points. Alternatively, a string can be provided. A value of
``"fit"`` means that the nugget is treated as a
hyperparameter, and is the last entry in the ``theta``
array. Alternatively, if ``nugget`` is set to be
``"adaptive"``, the fitting routine will adaptively make the
noise parameter as large as is needed to ensure that the
emulator can be fit. Finally, pivoting can be selected by
setting to ``"pivot"``, which will ignore any collinear rows
in the covariance matrix.
Internally, this modifies both the way the nugget is chosen
(which can be determined via the ``nugget_type`` property) and
the value itself (the ``nugget`` property)
:param nugget: Noise to be added to the diagonal, specified as
a string or a float. A non-negative float
specifies the noise level explicitly, while a
string indicates that the nugget will be found
via fitting, either as ``"adaptive"``,
``"pivot"``, or ``"fit"`` (see above for a
description).
:type nugget: float or str
:returns: None
:rtype: None
"""
if not isinstance(nugget, (str, float)):
try:
nugget = float(nugget)
except TypeError:
raise TypeError("nugget parameter must be a string or a non-negative float")
if isinstance(nugget, str):
if nugget == "adaptive":
self._nugget_type = "adaptive"
elif nugget == "fit":
self._nugget_type = "fit"
elif nugget == "pivot":
self._nugget_type = "pivot"
else:
raise ValueError("bad value of nugget, must be a float or 'adaptive', 'pivot', or 'fit'")
self._nugget = None
else:
if nugget < 0.:
raise ValueError("nugget parameter must be non-negative")
self._nugget_type = "fixed"
self._nugget = float(nugget) | def nugget(self, nugget):
"""Set the nugget parameter for the emulator
Method for changing the ``nugget`` parameter for the
emulator. When a new emulator is initilized, this is set to
None.
The ``nugget`` parameter controls how noise is added to the
covariance matrix in order to stabilize the inversion or
smooth the emulator predictions. If ``nugget`` is a
non-negative float, then that particular value is used for the
nugget. Note that setting this parameter to be zero enforces
that the emulator strictly interpolates between
points. Alternatively, a string can be provided. A value of
``"fit"`` means that the nugget is treated as a
hyperparameter, and is the last entry in the ``theta``
array. Alternatively, if ``nugget`` is set to be
``"adaptive"``, the fitting routine will adaptively make the
noise parameter as large as is needed to ensure that the
emulator can be fit. Finally, pivoting can be selected by
setting to ``"pivot"``, which will ignore any collinear rows
in the covariance matrix.
Internally, this modifies both the way the nugget is chosen
(which can be determined via the ``nugget_type`` property) and
the value itself (the ``nugget`` property)
:param nugget: Noise to be added to the diagonal, specified as
a string or a float. A non-negative float
specifies the noise level explicitly, while a
string indicates that the nugget will be found
via fitting, either as ``"adaptive"``,
``"pivot"``, or ``"fit"`` (see above for a
description).
:type nugget: float or str
:returns: None
:rtype: None
"""
if not isinstance(nugget, (str, float)):
try:
nugget = float(nugget)
except TypeError:
raise TypeError("nugget parameter must be a string or a non-negative float")
if isinstance(nugget, str):
if nugget == "adaptive":
self._nugget_type = "adaptive"
elif nugget == "fit":
self._nugget_type = "fit"
elif nugget == "pivot":
self._nugget_type = "pivot"
else:
raise ValueError("bad value of nugget, must be a float or 'adaptive', 'pivot', or 'fit'")
self._nugget = None
else:
if nugget < 0.:
raise ValueError("nugget parameter must be non-negative")
self._nugget_type = "fixed"
self._nugget = float(nugget) |
Python | def theta(self, theta):
"""Fits the emulator and sets the parameters (property-based setter alias for ``fit``)
Pre-calculates the matrices needed to compute the
log-likelihood and its derivatives and make subsequent
predictions. This is called any time the hyperparameter values
are changed in order to ensure that all the information is
needed to evaluate the log-likelihood and its derivatives,
which are needed when fitting the optimal hyperparameters.
The method computes the mean function and covariance matrix
and inverts the covariance matrix using the method specified
by the value of ``nugget``. The factorized matrix and the
product of the inverse with the difference between the targets
and the mean are cached for later use, and the negative
marginal log-likelihood is also cached. This method has no
return value, but it does modify the state of the object.
:param theta: Values of the hyperparameters to use in
fitting. Must be a numpy array with length
``n_params``
:type theta: ndarray
:returns: None
"""
if theta is None:
self._theta = None
self.current_logpost = None
else:
self.fit(theta) | def theta(self, theta):
"""Fits the emulator and sets the parameters (property-based setter alias for ``fit``)
Pre-calculates the matrices needed to compute the
log-likelihood and its derivatives and make subsequent
predictions. This is called any time the hyperparameter values
are changed in order to ensure that all the information is
needed to evaluate the log-likelihood and its derivatives,
which are needed when fitting the optimal hyperparameters.
The method computes the mean function and covariance matrix
and inverts the covariance matrix using the method specified
by the value of ``nugget``. The factorized matrix and the
product of the inverse with the difference between the targets
and the mean are cached for later use, and the negative
marginal log-likelihood is also cached. This method has no
return value, but it does modify the state of the object.
:param theta: Values of the hyperparameters to use in
fitting. Must be a numpy array with length
``n_params``
:type theta: ndarray
:returns: None
"""
if theta is None:
self._theta = None
self.current_logpost = None
else:
self.fit(theta) |
Python | def priors(self):
"""The current list priors used in computing the log posterior
To set the priors, must be a list or ``None``. Entries can be
``None`` or a subclass of ``Prior``. ``None`` indicates weak
prior information. An empty list or ``None`` means all
uninformative priors. Otherwise list should have the same
length as the number of hyperparameters, or alternatively can
be one shorter than the number of hyperparameters if
``nugget_type`` is ``"adaptive"``, ``"pivot"`` or ``"fixed"``
meaning that the nugget hyperparameter is not fit but is
instead fixed or found adaptively. If the nugget
hyperparameter is not fit, the prior for the nugget will
automatically be set to ``None`` even if a distribution is
provided.
"""
return self._priors | def priors(self):
"""The current list priors used in computing the log posterior
To set the priors, must be a list or ``None``. Entries can be
``None`` or a subclass of ``Prior``. ``None`` indicates weak
prior information. An empty list or ``None`` means all
uninformative priors. Otherwise list should have the same
length as the number of hyperparameters, or alternatively can
be one shorter than the number of hyperparameters if
``nugget_type`` is ``"adaptive"``, ``"pivot"`` or ``"fixed"``
meaning that the nugget hyperparameter is not fit but is
instead fixed or found adaptively. If the nugget
hyperparameter is not fit, the prior for the nugget will
automatically be set to ``None`` even if a distribution is
provided.
"""
return self._priors |
Python | def fit(self, theta):
"""Fits the emulator and sets the parameters
Pre-calculates the matrices needed to compute the
log-likelihood and its derivatives and make subsequent
predictions. This is called any time the hyperparameter values
are changed in order to ensure that all the information is
needed to evaluate the log-likelihood and its derivatives,
which are needed when fitting the optimal hyperparameters.
The method computes the mean function and covariance matrix
and inverts the covariance matrix using the method specified
by the value of ``nugget_type``. The factorized matrix and the
product of the inverse with the difference between the targets
and the mean are cached for later use, and the negative
marginal log-likelihood is also cached. This method has no
return value, but it does modify the state of the object.
:param theta: Values of the hyperparameters to use in
fitting. Must be a numpy array with length
``n_params``
:type theta: ndarray
:returns: None
"""
theta = np.array(theta)
assert theta.shape == (self.n_params,), "bad shape for hyperparameters"
self._theta = theta
switch = self.mean.get_n_params(self.inputs)
m = self.mean.mean_f(self.inputs, self.theta[:switch])
Q = self.kernel.kernel_f(self.inputs, self.inputs, self.theta[switch:-1])
if self.nugget_type == "adaptive":
self.L, self._nugget = jit_cholesky(Q)
self.P = np.arange(0, self.n)
elif self.nugget_type == "pivot":
self.L, self.P = pivot_cholesky(Q)
self._nugget = 0.
else:
if self.nugget_type == "fit":
self._nugget = np.exp(self.theta[-1])
Q += self._nugget*np.eye(self.n)
self.L = linalg.cholesky(Q, lower=True)
self.P = np.arange(0, self.n)
self.invQt = pivot_cho_solve(self.L, self.P, self.targets - m)
self.current_logpost = 0.5*(2.0*np.sum(np.log(np.diag(self.L))) +
np.dot(self.targets - m, self.invQt) +
self.n*np.log(2. * np.pi))
for i in range(self.n_params):
if not self._priors[i] is None:
self.current_logpost -= self._priors[i].logp(self.theta[i]) | def fit(self, theta):
"""Fits the emulator and sets the parameters
Pre-calculates the matrices needed to compute the
log-likelihood and its derivatives and make subsequent
predictions. This is called any time the hyperparameter values
are changed in order to ensure that all the information is
needed to evaluate the log-likelihood and its derivatives,
which are needed when fitting the optimal hyperparameters.
The method computes the mean function and covariance matrix
and inverts the covariance matrix using the method specified
by the value of ``nugget_type``. The factorized matrix and the
product of the inverse with the difference between the targets
and the mean are cached for later use, and the negative
marginal log-likelihood is also cached. This method has no
return value, but it does modify the state of the object.
:param theta: Values of the hyperparameters to use in
fitting. Must be a numpy array with length
``n_params``
:type theta: ndarray
:returns: None
"""
theta = np.array(theta)
assert theta.shape == (self.n_params,), "bad shape for hyperparameters"
self._theta = theta
switch = self.mean.get_n_params(self.inputs)
m = self.mean.mean_f(self.inputs, self.theta[:switch])
Q = self.kernel.kernel_f(self.inputs, self.inputs, self.theta[switch:-1])
if self.nugget_type == "adaptive":
self.L, self._nugget = jit_cholesky(Q)
self.P = np.arange(0, self.n)
elif self.nugget_type == "pivot":
self.L, self.P = pivot_cholesky(Q)
self._nugget = 0.
else:
if self.nugget_type == "fit":
self._nugget = np.exp(self.theta[-1])
Q += self._nugget*np.eye(self.n)
self.L = linalg.cholesky(Q, lower=True)
self.P = np.arange(0, self.n)
self.invQt = pivot_cho_solve(self.L, self.P, self.targets - m)
self.current_logpost = 0.5*(2.0*np.sum(np.log(np.diag(self.L))) +
np.dot(self.targets - m, self.invQt) +
self.n*np.log(2. * np.pi))
for i in range(self.n_params):
if not self._priors[i] is None:
self.current_logpost -= self._priors[i].logp(self.theta[i]) |
Python | def logposterior(self, theta):
"""Calculate the negative log-posterior at a particular value of the hyperparameters
Calculate the negative log-posterior for the given set of
parameters. Calling this method sets the parameter values and
computes the needed inverse matrices in order to evaluate the
log-posterior and its derivatives. In addition to returning
the log-posterior value, it stores the current value of the
hyperparameters and log-posterior in attributes of the object.
:param theta: Value of the hyperparameters. Must be array-like
with shape ``(n_params,)``
:type theta: ndarray
:returns: negative log-posterior
:rtype: float
"""
if self.theta is None or not np.allclose(theta, self.theta, rtol=1.e-10, atol=1.e-15):
self.fit(theta)
return self.current_logpost | def logposterior(self, theta):
"""Calculate the negative log-posterior at a particular value of the hyperparameters
Calculate the negative log-posterior for the given set of
parameters. Calling this method sets the parameter values and
computes the needed inverse matrices in order to evaluate the
log-posterior and its derivatives. In addition to returning
the log-posterior value, it stores the current value of the
hyperparameters and log-posterior in attributes of the object.
:param theta: Value of the hyperparameters. Must be array-like
with shape ``(n_params,)``
:type theta: ndarray
:returns: negative log-posterior
:rtype: float
"""
if self.theta is None or not np.allclose(theta, self.theta, rtol=1.e-10, atol=1.e-15):
self.fit(theta)
return self.current_logpost |
Python | def logpost_deriv(self, theta):
"""Calculate the partial derivatives of the negative log-posterior
Calculate the partial derivatives of the negative
log-posterior with respect to the hyperparameters. Note that
this function is normally used only when fitting the
hyperparameters, and it is not needed to make predictions.
During normal use, the ``logpost_deriv`` method is called
after evaluating the ``logposterior`` method. The
implementation takes advantage of this by reusing cached
results, as the factorized covariance matrix is expensive to
compute and is used by the ``logposterior``,
``logpost_deriv``, and ``logpost_hessian`` methods. If the
function is evaluated with a different set of parameters than
was previously used to set the log-posterior, the method calls
``fit`` (and subsequently resets the cached information).
:param theta: Value of the hyperparameters. Must be array-like
with shape ``(n_params,)``
:type theta: ndarray
:returns: partial derivatives of the negative log-posterior
with respect to the hyperparameters (array with
shape ``(n_params,)``)
:rtype: ndarray
"""
theta = np.array(theta)
assert theta.shape == (self.n_params,), "bad shape for new parameters"
if self.theta is None or not np.allclose(theta, self.theta, rtol=1.e-10, atol=1.e-15):
self.fit(theta)
partials = np.zeros(self.n_params)
switch = self.mean.get_n_params(self.inputs)
dmdtheta = self.mean.mean_deriv(self.inputs, self.theta[:switch])
dKdtheta = self.kernel.kernel_deriv(self.inputs, self.inputs, self.theta[switch:-1])
partials[:switch] = -np.dot(dmdtheta, self.invQt)
for d in range(self.D + 1):
invQ_dot_dKdtheta_trace = np.trace(pivot_cho_solve(self.L, self.P, dKdtheta[d]))
partials[switch + d] = -0.5*(np.dot(self.invQt, np.dot(dKdtheta[d], self.invQt)) -
invQ_dot_dKdtheta_trace)
if self.nugget_type == "fit":
nugget = np.exp(self.theta[-1])
partials[-1] = 0.5*nugget*(np.trace(pivot_cho_solve(self.L, self.P, np.eye(self.n))) -
np.dot(self.invQt, self.invQt))
for i in range(self.n_params):
if not self._priors[i] is None:
partials[i] -= self._priors[i].dlogpdtheta(self.theta[i])
return partials | def logpost_deriv(self, theta):
"""Calculate the partial derivatives of the negative log-posterior
Calculate the partial derivatives of the negative
log-posterior with respect to the hyperparameters. Note that
this function is normally used only when fitting the
hyperparameters, and it is not needed to make predictions.
During normal use, the ``logpost_deriv`` method is called
after evaluating the ``logposterior`` method. The
implementation takes advantage of this by reusing cached
results, as the factorized covariance matrix is expensive to
compute and is used by the ``logposterior``,
``logpost_deriv``, and ``logpost_hessian`` methods. If the
function is evaluated with a different set of parameters than
was previously used to set the log-posterior, the method calls
``fit`` (and subsequently resets the cached information).
:param theta: Value of the hyperparameters. Must be array-like
with shape ``(n_params,)``
:type theta: ndarray
:returns: partial derivatives of the negative log-posterior
with respect to the hyperparameters (array with
shape ``(n_params,)``)
:rtype: ndarray
"""
theta = np.array(theta)
assert theta.shape == (self.n_params,), "bad shape for new parameters"
if self.theta is None or not np.allclose(theta, self.theta, rtol=1.e-10, atol=1.e-15):
self.fit(theta)
partials = np.zeros(self.n_params)
switch = self.mean.get_n_params(self.inputs)
dmdtheta = self.mean.mean_deriv(self.inputs, self.theta[:switch])
dKdtheta = self.kernel.kernel_deriv(self.inputs, self.inputs, self.theta[switch:-1])
partials[:switch] = -np.dot(dmdtheta, self.invQt)
for d in range(self.D + 1):
invQ_dot_dKdtheta_trace = np.trace(pivot_cho_solve(self.L, self.P, dKdtheta[d]))
partials[switch + d] = -0.5*(np.dot(self.invQt, np.dot(dKdtheta[d], self.invQt)) -
invQ_dot_dKdtheta_trace)
if self.nugget_type == "fit":
nugget = np.exp(self.theta[-1])
partials[-1] = 0.5*nugget*(np.trace(pivot_cho_solve(self.L, self.P, np.eye(self.n))) -
np.dot(self.invQt, self.invQt))
for i in range(self.n_params):
if not self._priors[i] is None:
partials[i] -= self._priors[i].dlogpdtheta(self.theta[i])
return partials |
Python | def logpost_hessian(self, theta):
"""Calculate the Hessian of the negative log-posterior
Calculate the Hessian of the negative log-posterior with
respect to the hyperparameters. Note that this function is
normally used only when fitting the hyperparameters, and it is
not needed to make predictions. It is also used to estimate an
appropriate step size when fitting hyperparameters using the
lognormal approximation or MCMC sampling.
When used in an optimization routine, the ``logpost_hessian``
method is called after evaluating the ``logposterior``
method. The implementation takes advantage of this by storing
the inverse of the covariance matrix, which is expensive to
compute and is used by the ``logposterior`` and
``logpost_deriv`` methods as well. If the function is
evaluated with a different set of parameters than was
previously used to set the log-posterior, the method calls
``fit`` to compute the needed information and changes the
cached values.
:param theta: Value of the hyperparameters. Must be array-like
with shape ``(n_params,)``
:type theta: ndarray
:returns: Hessian of the negative log-posterior (array with
shape ``(n_params, n_params)``)
:rtype: ndarray
"""
assert theta.shape == (self.n_params,), "Parameter vector must have length number of inputs + 1"
if self.theta is None or not np.allclose(theta, self.theta, rtol=1.e-10, atol=1.e-15):
self.fit(theta)
hessian = np.zeros((self.n_params, self.n_params))
switch = self.mean.get_n_params(self.inputs)
dmdtheta = self.mean.mean_deriv(self.inputs, self.theta[:switch])
d2mdtheta2 = self.mean.mean_hessian(self.inputs, self.theta[:switch])
dKdtheta = self.kernel.kernel_deriv(self.inputs, self.inputs, self.theta[switch:-1])
d2Kdtheta2 = self.kernel.kernel_hessian(self.inputs, self.inputs, self.theta[switch:-1])
hessian[:switch, :switch] = -(np.dot(d2mdtheta2, self.invQt) -
np.dot(dmdtheta, pivot_cho_solve(self.L, self.P,
np.transpose(dmdtheta))))
hessian[:switch, switch:-1] = np.dot(dmdtheta,
pivot_cho_solve(self.L, self.P,
np.transpose(np.dot(dKdtheta, self.invQt))))
hessian[switch:-1, :switch] = np.transpose(hessian[:switch, switch:-1])
for d1 in range(self.D + 1):
invQ_dot_d1 = pivot_cho_solve(self.L, self.P, dKdtheta[d1])
for d2 in range(self.D + 1):
invQ_dot_d2 = pivot_cho_solve(self.L, self.P, dKdtheta[d2])
invQ_dot_d1d2 = pivot_cho_solve(self.L, self.P, d2Kdtheta2[d1, d2])
term_1 = np.linalg.multi_dot([self.invQt,
2.*np.dot(dKdtheta[d1], invQ_dot_d2) - d2Kdtheta2[d1, d2],
self.invQt])
term_2 = np.trace(np.dot(invQ_dot_d1, invQ_dot_d2) - invQ_dot_d1d2)
hessian[switch + d1, switch + d2] = 0.5*(term_1 - term_2)
if self.nugget_type == "fit":
nugget = np.exp(self.theta[-1])
invQinvQt = pivot_cho_solve(self.L, self.P, self.invQt)
hessian[:switch, -1] = nugget*np.dot(dmdtheta, invQinvQt)
for d in range(self.D + 1):
hessian[switch + d, -1] = nugget*(np.linalg.multi_dot([self.invQt, dKdtheta[d], invQinvQt]) -
0.5*np.trace(pivot_cho_solve(self.L, self.P,
np.dot(dKdtheta[d],
pivot_cho_solve(self.L, self.P,
np.eye(self.n))))))
hessian[-1, -1] = 0.5*nugget*(np.trace(pivot_cho_solve(self.L, self.P, np.eye(self.n))) -
np.dot(self.invQt, self.invQt))
hessian[-1, -1] += nugget**2*(np.dot(self.invQt, invQinvQt) -
0.5*np.trace(pivot_cho_solve(self.L, self.P,
pivot_cho_solve(self.L, self.P,
np.eye(self.n)))))
hessian[-1, :-1] = np.transpose(hessian[:-1, -1])
for i in range(self.n_params):
if not self._priors[i] is None:
hessian[i, i] -= self._priors[i].d2logpdtheta2(self.theta[i])
return hessian | def logpost_hessian(self, theta):
"""Calculate the Hessian of the negative log-posterior
Calculate the Hessian of the negative log-posterior with
respect to the hyperparameters. Note that this function is
normally used only when fitting the hyperparameters, and it is
not needed to make predictions. It is also used to estimate an
appropriate step size when fitting hyperparameters using the
lognormal approximation or MCMC sampling.
When used in an optimization routine, the ``logpost_hessian``
method is called after evaluating the ``logposterior``
method. The implementation takes advantage of this by storing
the inverse of the covariance matrix, which is expensive to
compute and is used by the ``logposterior`` and
``logpost_deriv`` methods as well. If the function is
evaluated with a different set of parameters than was
previously used to set the log-posterior, the method calls
``fit`` to compute the needed information and changes the
cached values.
:param theta: Value of the hyperparameters. Must be array-like
with shape ``(n_params,)``
:type theta: ndarray
:returns: Hessian of the negative log-posterior (array with
shape ``(n_params, n_params)``)
:rtype: ndarray
"""
assert theta.shape == (self.n_params,), "Parameter vector must have length number of inputs + 1"
if self.theta is None or not np.allclose(theta, self.theta, rtol=1.e-10, atol=1.e-15):
self.fit(theta)
hessian = np.zeros((self.n_params, self.n_params))
switch = self.mean.get_n_params(self.inputs)
dmdtheta = self.mean.mean_deriv(self.inputs, self.theta[:switch])
d2mdtheta2 = self.mean.mean_hessian(self.inputs, self.theta[:switch])
dKdtheta = self.kernel.kernel_deriv(self.inputs, self.inputs, self.theta[switch:-1])
d2Kdtheta2 = self.kernel.kernel_hessian(self.inputs, self.inputs, self.theta[switch:-1])
hessian[:switch, :switch] = -(np.dot(d2mdtheta2, self.invQt) -
np.dot(dmdtheta, pivot_cho_solve(self.L, self.P,
np.transpose(dmdtheta))))
hessian[:switch, switch:-1] = np.dot(dmdtheta,
pivot_cho_solve(self.L, self.P,
np.transpose(np.dot(dKdtheta, self.invQt))))
hessian[switch:-1, :switch] = np.transpose(hessian[:switch, switch:-1])
for d1 in range(self.D + 1):
invQ_dot_d1 = pivot_cho_solve(self.L, self.P, dKdtheta[d1])
for d2 in range(self.D + 1):
invQ_dot_d2 = pivot_cho_solve(self.L, self.P, dKdtheta[d2])
invQ_dot_d1d2 = pivot_cho_solve(self.L, self.P, d2Kdtheta2[d1, d2])
term_1 = np.linalg.multi_dot([self.invQt,
2.*np.dot(dKdtheta[d1], invQ_dot_d2) - d2Kdtheta2[d1, d2],
self.invQt])
term_2 = np.trace(np.dot(invQ_dot_d1, invQ_dot_d2) - invQ_dot_d1d2)
hessian[switch + d1, switch + d2] = 0.5*(term_1 - term_2)
if self.nugget_type == "fit":
nugget = np.exp(self.theta[-1])
invQinvQt = pivot_cho_solve(self.L, self.P, self.invQt)
hessian[:switch, -1] = nugget*np.dot(dmdtheta, invQinvQt)
for d in range(self.D + 1):
hessian[switch + d, -1] = nugget*(np.linalg.multi_dot([self.invQt, dKdtheta[d], invQinvQt]) -
0.5*np.trace(pivot_cho_solve(self.L, self.P,
np.dot(dKdtheta[d],
pivot_cho_solve(self.L, self.P,
np.eye(self.n))))))
hessian[-1, -1] = 0.5*nugget*(np.trace(pivot_cho_solve(self.L, self.P, np.eye(self.n))) -
np.dot(self.invQt, self.invQt))
hessian[-1, -1] += nugget**2*(np.dot(self.invQt, invQinvQt) -
0.5*np.trace(pivot_cho_solve(self.L, self.P,
pivot_cho_solve(self.L, self.P,
np.eye(self.n)))))
hessian[-1, :-1] = np.transpose(hessian[:-1, -1])
for i in range(self.n_params):
if not self._priors[i] is None:
hessian[i, i] -= self._priors[i].d2logpdtheta2(self.theta[i])
return hessian |
Python | def predict(self, testing, unc=True, deriv=True, include_nugget=True):
"""Make a prediction for a set of input vectors for a single set of hyperparameters
Makes predictions for the emulator on a given set of input
vectors. The input vectors must be passed as a ``(n_predict,
D)``, ``(n_predict,)`` or ``(D,)`` shaped array-like object,
where ``n_predict`` is the number of different prediction
points under consideration and ``D`` is the number of inputs
to the emulator. If the prediction inputs array is 1D and ``D
== 1`` for the GP instance, then the 1D array must have shape
``(n_predict,)``. Otherwise, if the array is 1D it must have
shape ``(D,)``, and the method assumes ``n_predict == 1``. The
prediction is returned as an ``(n_predict, )`` shaped numpy
array as the first return value from the method.
Optionally, the emulator can also calculate the variances in
the predictions and the derivatives with respect to each input
parameter. If the uncertainties are computed, they are
returned as the second output from the method as an
``(n_predict,)`` shaped numpy array. If the derivatives are
computed, they are returned as the third output from the
method as an ``(n_predict, D)`` shaped numpy array.
The final input to the method determines if the predictive
variance should include the nugget or not. For situations
where the nugget represents observational error and
predictions are estimating the true underlying function, this
should be set to ``False``. However, most other cases should
probably include the nugget, as the emulator is using it to
represent some of the uncertainty in the underlying simulator,
so the default value is ``True``.
:param testing: Array-like object holding the points where
predictions will be made. Must have shape
``(n_predict, D)`` or ``(D,)`` (for a single
prediction)
:type testing: ndarray
:param unc: (optional) Flag indicating if the uncertainties
are to be computed. If ``False`` the method
returns ``None`` in place of the uncertainty
array. Default value is ``True``.
:type unc: bool
:param deriv: (optional) Flag indicating if the derivatives
are to be computed. If ``False`` the method
returns ``None`` in place of the derivative
array. Default value is ``True``.
:type deriv: bool
:param include_nugget: (optional) Flag indicating if the
nugget should be included in the
predictive variance. Only relevant if
``unc = True``. Default is ``True``.
:type include_nugget: bool
:returns: Tuple of numpy arrays holding the predictions,
uncertainties, and derivatives,
respectively. Predictions and uncertainties have
shape ``(n_predict,)`` while the derivatives have
shape ``(n_predict, D)``. If the ``unc`` or
``deriv`` flags are set to ``False``, then those
arrays are replaced by ``None``.
:rtype: tuple
"""
if self.theta is None:
raise ValueError("hyperparameters have not been fit for this Gaussian Process")
testing = np.array(testing)
if self.D == 1 and testing.ndim == 1:
testing = np.reshape(testing, (-1, 1))
elif testing.ndim == 1:
testing = np.reshape(testing, (1, len(testing)))
assert testing.ndim == 2, "testing must be a 2D array"
n_testing, D = np.shape(testing)
assert D == self.D, "second dimension of testing must be the same as the number of input parameters"
switch = self.mean.get_n_params(testing)
mtest = self.mean.mean_f(testing, self.theta[:switch])
Ktest = self.kernel.kernel_f(self.inputs, testing, self.theta[switch:-1])
mu = mtest + np.dot(Ktest.T, self.invQt)
var = None
if unc:
sigma_2 = np.exp(self.theta[-2])
if include_nugget:
sigma_2 += self._nugget
var = np.maximum(sigma_2 - np.sum(Ktest*pivot_cho_solve(self.L, self.P, Ktest), axis=0),
0.)
inputderiv = None
if deriv:
inputderiv = np.zeros((n_testing, self.D))
mean_deriv = self.mean.mean_inputderiv(testing, self.theta[:switch])
kern_deriv = self.kernel.kernel_inputderiv(testing, self.inputs, self.theta[switch:-1])
inputderiv = np.transpose(mean_deriv + np.dot(kern_deriv, self.invQt))
return PredictResult(mean=mu, unc=var, deriv=inputderiv) | def predict(self, testing, unc=True, deriv=True, include_nugget=True):
"""Make a prediction for a set of input vectors for a single set of hyperparameters
Makes predictions for the emulator on a given set of input
vectors. The input vectors must be passed as a ``(n_predict,
D)``, ``(n_predict,)`` or ``(D,)`` shaped array-like object,
where ``n_predict`` is the number of different prediction
points under consideration and ``D`` is the number of inputs
to the emulator. If the prediction inputs array is 1D and ``D
== 1`` for the GP instance, then the 1D array must have shape
``(n_predict,)``. Otherwise, if the array is 1D it must have
shape ``(D,)``, and the method assumes ``n_predict == 1``. The
prediction is returned as an ``(n_predict, )`` shaped numpy
array as the first return value from the method.
Optionally, the emulator can also calculate the variances in
the predictions and the derivatives with respect to each input
parameter. If the uncertainties are computed, they are
returned as the second output from the method as an
``(n_predict,)`` shaped numpy array. If the derivatives are
computed, they are returned as the third output from the
method as an ``(n_predict, D)`` shaped numpy array.
The final input to the method determines if the predictive
variance should include the nugget or not. For situations
where the nugget represents observational error and
predictions are estimating the true underlying function, this
should be set to ``False``. However, most other cases should
probably include the nugget, as the emulator is using it to
represent some of the uncertainty in the underlying simulator,
so the default value is ``True``.
:param testing: Array-like object holding the points where
predictions will be made. Must have shape
``(n_predict, D)`` or ``(D,)`` (for a single
prediction)
:type testing: ndarray
:param unc: (optional) Flag indicating if the uncertainties
are to be computed. If ``False`` the method
returns ``None`` in place of the uncertainty
array. Default value is ``True``.
:type unc: bool
:param deriv: (optional) Flag indicating if the derivatives
are to be computed. If ``False`` the method
returns ``None`` in place of the derivative
array. Default value is ``True``.
:type deriv: bool
:param include_nugget: (optional) Flag indicating if the
nugget should be included in the
predictive variance. Only relevant if
``unc = True``. Default is ``True``.
:type include_nugget: bool
:returns: Tuple of numpy arrays holding the predictions,
uncertainties, and derivatives,
respectively. Predictions and uncertainties have
shape ``(n_predict,)`` while the derivatives have
shape ``(n_predict, D)``. If the ``unc`` or
``deriv`` flags are set to ``False``, then those
arrays are replaced by ``None``.
:rtype: tuple
"""
if self.theta is None:
raise ValueError("hyperparameters have not been fit for this Gaussian Process")
testing = np.array(testing)
if self.D == 1 and testing.ndim == 1:
testing = np.reshape(testing, (-1, 1))
elif testing.ndim == 1:
testing = np.reshape(testing, (1, len(testing)))
assert testing.ndim == 2, "testing must be a 2D array"
n_testing, D = np.shape(testing)
assert D == self.D, "second dimension of testing must be the same as the number of input parameters"
switch = self.mean.get_n_params(testing)
mtest = self.mean.mean_f(testing, self.theta[:switch])
Ktest = self.kernel.kernel_f(self.inputs, testing, self.theta[switch:-1])
mu = mtest + np.dot(Ktest.T, self.invQt)
var = None
if unc:
sigma_2 = np.exp(self.theta[-2])
if include_nugget:
sigma_2 += self._nugget
var = np.maximum(sigma_2 - np.sum(Ktest*pivot_cho_solve(self.L, self.P, Ktest), axis=0),
0.)
inputderiv = None
if deriv:
inputderiv = np.zeros((n_testing, self.D))
mean_deriv = self.mean.mean_inputderiv(testing, self.theta[:switch])
kern_deriv = self.kernel.kernel_inputderiv(testing, self.inputs, self.theta[switch:-1])
inputderiv = np.transpose(mean_deriv + np.dot(kern_deriv, self.invQt))
return PredictResult(mean=mu, unc=var, deriv=inputderiv) |
Python | def predict(self, testing, unc=True, deriv=True, include_nugget=True,
allow_not_fit=False, processes=None):
"""Make a prediction for a set of input vectors
Makes predictions for each of the emulators on a given set of
input vectors. The input vectors must be passed as a
``(n_predict, D)`` or ``(D,)`` shaped array-like object, where
``n_predict`` is the number of different prediction points
under consideration and ``D`` is the number of inputs to the
emulator. If the prediction inputs array has shape ``(D,)``,
then the method assumes ``n_predict == 1``. The prediction
points are passed to each emulator and the predictions are
collected into an ``(n_emulators, n_predict)`` shaped numpy
array as the first return value from the method.
Optionally, the emulator can also calculate the uncertainties
in the predictions (as a variance) and the derivatives with
respect to each input parameter. If the uncertainties are
computed, they are returned as the second output from the
method as an ``(n_emulators, n_predict)`` shaped numpy
array. If the derivatives are computed, they are returned as
the third output from the method as an ``(n_emulators,
n_predict, D)`` shaped numpy array. Finally, if uncertainties
are computed, the ``include_nugget`` flag determines if the
uncertainties should include the nugget. By default, this is
set to ``True``.
The ``allow_not_fit`` flag determines how the object handles
any emulators that do not have fit hyperparameter values
(because fitting presumably failed). By default,
``allow_not_fit=False`` and the method will raise an error
if any emulators are not fit. Passing ``allow_not_fit=True``
will override this and ``NaN`` will be returned from any
emulators that have not been fit.
As with the fitting, this computation can be done
independently for each emulator and thus can be done in
parallel.
:param testing: Array-like object holding the points where
predictions will be made. Must have shape
``(n_predict, D)`` or ``(D,)`` (for a single
prediction)
:type testing: ndarray
:param unc: (optional) Flag indicating if the uncertainties
are to be computed. If ``False`` the method
returns ``None`` in place of the uncertainty
array. Default value is ``True``.
:type unc: bool
:param deriv: (optional) Flag indicating if the derivatives
are to be computed. If ``False`` the method
returns ``None`` in place of the derivative
array. Default value is ``True``.
:type deriv: bool
:param include_nugget: (optional) Flag indicating if the
nugget should be included in the
predictive variance. Only relevant if
``unc = True``. Default is ``True``.
:type include_nugget: bool
:param allow_not_fit: (optional) Flag that allows predictions
to be made even if not all emulators have
been fit. Default is ``False`` which
will raise an error if any unfitted
emulators are present.
:type allow_not_fit: bool
:param processes: (optional) Number of processes to use when
making the predictions. Must be a positive
integer or ``None`` to use the number of
processors on the computer (default is
``None``)
:type processes: int or None
:returns: ``PredictResult`` object holding numpy arrays
containing the predictions, uncertainties, and
derivatives, respectively. Predictions and
uncertainties have shape ``(n_emulators,
n_predict)`` while the derivatives have shape
``(n_emulators, n_predict, D)``. If the ``do_unc``
or ``do_deriv`` flags are set to ``False``, then
those arrays are replaced by ``None``.
:rtype: PredictResult
"""
testing = np.array(testing)
if self.D == 1 and testing.ndim == 1:
testing = np.reshape(testing, (-1, 1))
elif testing.ndim == 1:
testing = np.reshape(testing, (1, len(testing)))
assert testing.ndim == 2, "testing must be a 2D array"
n_testing, D = np.shape(testing)
assert D == self.D, "second dimension of testing must be the same as the number of input parameters"
if not processes is None:
processes = int(processes)
assert processes > 0, "number of processes must be a positive integer"
if allow_not_fit:
predict_method = _gp_predict_default_NaN
else:
predict_method = self.GPClass.predict
if platform.system() == "Windows" or self.use_gpu:
predict_vals = [predict_method(gp, testing, unc, deriv, include_nugget)
for gp in self.emulators]
else:
with Pool(processes) as p:
predict_vals = p.starmap(predict_method,
[(gp, testing, unc, deriv, include_nugget)
for gp in self.emulators])
# repackage predictions into numpy arrays
predict_unpacked, unc_unpacked, deriv_unpacked = [np.array(t) for t in zip(*predict_vals)]
if not unc:
unc_unpacked = None
if not deriv:
deriv_unpacked = None
return PredictResult(mean=predict_unpacked, unc=unc_unpacked, deriv=deriv_unpacked) | def predict(self, testing, unc=True, deriv=True, include_nugget=True,
allow_not_fit=False, processes=None):
"""Make a prediction for a set of input vectors
Makes predictions for each of the emulators on a given set of
input vectors. The input vectors must be passed as a
``(n_predict, D)`` or ``(D,)`` shaped array-like object, where
``n_predict`` is the number of different prediction points
under consideration and ``D`` is the number of inputs to the
emulator. If the prediction inputs array has shape ``(D,)``,
then the method assumes ``n_predict == 1``. The prediction
points are passed to each emulator and the predictions are
collected into an ``(n_emulators, n_predict)`` shaped numpy
array as the first return value from the method.
Optionally, the emulator can also calculate the uncertainties
in the predictions (as a variance) and the derivatives with
respect to each input parameter. If the uncertainties are
computed, they are returned as the second output from the
method as an ``(n_emulators, n_predict)`` shaped numpy
array. If the derivatives are computed, they are returned as
the third output from the method as an ``(n_emulators,
n_predict, D)`` shaped numpy array. Finally, if uncertainties
are computed, the ``include_nugget`` flag determines if the
uncertainties should include the nugget. By default, this is
set to ``True``.
The ``allow_not_fit`` flag determines how the object handles
any emulators that do not have fit hyperparameter values
(because fitting presumably failed). By default,
``allow_not_fit=False`` and the method will raise an error
if any emulators are not fit. Passing ``allow_not_fit=True``
will override this and ``NaN`` will be returned from any
emulators that have not been fit.
As with the fitting, this computation can be done
independently for each emulator and thus can be done in
parallel.
:param testing: Array-like object holding the points where
predictions will be made. Must have shape
``(n_predict, D)`` or ``(D,)`` (for a single
prediction)
:type testing: ndarray
:param unc: (optional) Flag indicating if the uncertainties
are to be computed. If ``False`` the method
returns ``None`` in place of the uncertainty
array. Default value is ``True``.
:type unc: bool
:param deriv: (optional) Flag indicating if the derivatives
are to be computed. If ``False`` the method
returns ``None`` in place of the derivative
array. Default value is ``True``.
:type deriv: bool
:param include_nugget: (optional) Flag indicating if the
nugget should be included in the
predictive variance. Only relevant if
``unc = True``. Default is ``True``.
:type include_nugget: bool
:param allow_not_fit: (optional) Flag that allows predictions
to be made even if not all emulators have
been fit. Default is ``False`` which
will raise an error if any unfitted
emulators are present.
:type allow_not_fit: bool
:param processes: (optional) Number of processes to use when
making the predictions. Must be a positive
integer or ``None`` to use the number of
processors on the computer (default is
``None``)
:type processes: int or None
:returns: ``PredictResult`` object holding numpy arrays
containing the predictions, uncertainties, and
derivatives, respectively. Predictions and
uncertainties have shape ``(n_emulators,
n_predict)`` while the derivatives have shape
``(n_emulators, n_predict, D)``. If the ``do_unc``
or ``do_deriv`` flags are set to ``False``, then
those arrays are replaced by ``None``.
:rtype: PredictResult
"""
testing = np.array(testing)
if self.D == 1 and testing.ndim == 1:
testing = np.reshape(testing, (-1, 1))
elif testing.ndim == 1:
testing = np.reshape(testing, (1, len(testing)))
assert testing.ndim == 2, "testing must be a 2D array"
n_testing, D = np.shape(testing)
assert D == self.D, "second dimension of testing must be the same as the number of input parameters"
if not processes is None:
processes = int(processes)
assert processes > 0, "number of processes must be a positive integer"
if allow_not_fit:
predict_method = _gp_predict_default_NaN
else:
predict_method = self.GPClass.predict
if platform.system() == "Windows" or self.use_gpu:
predict_vals = [predict_method(gp, testing, unc, deriv, include_nugget)
for gp in self.emulators]
else:
with Pool(processes) as p:
predict_vals = p.starmap(predict_method,
[(gp, testing, unc, deriv, include_nugget)
for gp in self.emulators])
# repackage predictions into numpy arrays
predict_unpacked, unc_unpacked, deriv_unpacked = [np.array(t) for t in zip(*predict_vals)]
if not unc:
unc_unpacked = None
if not deriv:
deriv_unpacked = None
return PredictResult(mean=predict_unpacked, unc=unc_unpacked, deriv=deriv_unpacked) |
Python | def _gp_predict_default_NaN(gp, testing, unc, deriv, include_nugget):
"""Prediction method for GPs that defaults to NaN for unfit GPs
Wrapper function for the ``GaussianProcess`` predict method that
returns NaN if the GP is not fit. Allows ``MultiOutputGP`` objects
that do not have all emulators fit to still return predictions
with unfit emulator predictions replaced with NaN.
The first argument to this function is the GP that will be used
for prediction. All other arguments are the same as the
arguments for the ``predict`` method of ``GaussianProcess``.
:param gp: The ``GaussianProcess`` object (or related class) for
which predictions will be made.
:type gp: GaussianProcess
:param testing: Array-like object holding the points where
predictions will be made. Must have shape
``(n_predict, D)`` or ``(D,)`` (for a single
prediction)
:type testing: ndarray
:param unc: (optional) Flag indicating if the uncertainties
are to be computed. If ``False`` the method
returns ``None`` in place of the uncertainty
array. Default value is ``True``.
:type unc: bool
:param deriv: (optional) Flag indicating if the derivatives
are to be computed. If ``False`` the method
returns ``None`` in place of the derivative
array. Default value is ``True``.
:type deriv: bool
:param include_nugget: (optional) Flag indicating if the
nugget should be included in the
predictive variance. Only relevant if
``unc = True``. Default is ``True``.
:type include_nugget: bool
:returns: Tuple of numpy arrays holding the predictions,
uncertainties, and derivatives,
respectively. Predictions and uncertainties have
shape ``(n_predict,)`` while the derivatives have
shape ``(n_predict, D)``. If the ``unc`` or
``deriv`` flags are set to ``False``, then those
arrays are replaced by ``None``.
:rtype: tuple
"""
assert isinstance(gp, GaussianProcessBase)
try:
return gp.predict(testing, unc, deriv, include_nugget)
except ValueError:
n_predict = testing.shape[0]
if unc:
unc_array = np.array([np.nan]*n_predict)
else:
unc_array = None
if deriv:
deriv_array = np.reshape(np.array([np.nan]*n_predict*gp.D),
(n_predict, gp.D))
else:
deriv_array = None
return PredictResult(mean =np.array([np.nan]*n_predict),
unc=unc_array, deriv=deriv_array) | def _gp_predict_default_NaN(gp, testing, unc, deriv, include_nugget):
"""Prediction method for GPs that defaults to NaN for unfit GPs
Wrapper function for the ``GaussianProcess`` predict method that
returns NaN if the GP is not fit. Allows ``MultiOutputGP`` objects
that do not have all emulators fit to still return predictions
with unfit emulator predictions replaced with NaN.
The first argument to this function is the GP that will be used
for prediction. All other arguments are the same as the
arguments for the ``predict`` method of ``GaussianProcess``.
:param gp: The ``GaussianProcess`` object (or related class) for
which predictions will be made.
:type gp: GaussianProcess
:param testing: Array-like object holding the points where
predictions will be made. Must have shape
``(n_predict, D)`` or ``(D,)`` (for a single
prediction)
:type testing: ndarray
:param unc: (optional) Flag indicating if the uncertainties
are to be computed. If ``False`` the method
returns ``None`` in place of the uncertainty
array. Default value is ``True``.
:type unc: bool
:param deriv: (optional) Flag indicating if the derivatives
are to be computed. If ``False`` the method
returns ``None`` in place of the derivative
array. Default value is ``True``.
:type deriv: bool
:param include_nugget: (optional) Flag indicating if the
nugget should be included in the
predictive variance. Only relevant if
``unc = True``. Default is ``True``.
:type include_nugget: bool
:returns: Tuple of numpy arrays holding the predictions,
uncertainties, and derivatives,
respectively. Predictions and uncertainties have
shape ``(n_predict,)`` while the derivatives have
shape ``(n_predict, D)``. If the ``unc`` or
``deriv`` flags are set to ``False``, then those
arrays are replaced by ``None``.
:rtype: tuple
"""
assert isinstance(gp, GaussianProcessBase)
try:
return gp.predict(testing, unc, deriv, include_nugget)
except ValueError:
n_predict = testing.shape[0]
if unc:
unc_array = np.array([np.nan]*n_predict)
else:
unc_array = None
if deriv:
deriv_array = np.reshape(np.array([np.nan]*n_predict*gp.D),
(n_predict, gp.D))
else:
deriv_array = None
return PredictResult(mean =np.array([np.nan]*n_predict),
unc=unc_array, deriv=deriv_array) |
Python | def ndarray_coerce_type_and_flags(arr):
"""
Helper function for the GaussianProcessGPU methods that call
CUDA/C++ functions (those wrapped by _dense_gpgpu) and that take
numpy arrays as arguments. Ensures that an array is of the
correct type for this purpose.
Takes an array or array-like.
Returns an ndarray with the same data, that has:
- dtype of float64
- flags.writable
- flags.c_contiguous
The array returned may reference the original array, be a copy of
it, or be newly constructed from the argument.
"""
arr = np.array(arr, copy=False)
# cast into float64, just in case we were given integers and ensure contiguous (C type)
arr_contiguous_float64 = np.ascontiguousarray(arr.astype(np.float64, copy=False))
if not arr_contiguous_float64.flags['WRITEABLE']:
return np.copy(arr_contiguous_float64)
else:
return arr_contiguous_float64 | def ndarray_coerce_type_and_flags(arr):
"""
Helper function for the GaussianProcessGPU methods that call
CUDA/C++ functions (those wrapped by _dense_gpgpu) and that take
numpy arrays as arguments. Ensures that an array is of the
correct type for this purpose.
Takes an array or array-like.
Returns an ndarray with the same data, that has:
- dtype of float64
- flags.writable
- flags.c_contiguous
The array returned may reference the original array, be a copy of
it, or be newly constructed from the argument.
"""
arr = np.array(arr, copy=False)
# cast into float64, just in case we were given integers and ensure contiguous (C type)
arr_contiguous_float64 = np.ascontiguousarray(arr.astype(np.float64, copy=False))
if not arr_contiguous_float64.flags['WRITEABLE']:
return np.copy(arr_contiguous_float64)
else:
return arr_contiguous_float64 |
Python | def parse_meanfunc_formula(formula):
"""
Assuming the formula has already been parsed by the Python MeanFunction interface,
we expect it to be in a standard form, with parameters denoted by 'c' and variables
denoted by 'x[dim_index]' where dim_index < D.
:param formula: string representing the desired mean function formula
:type formula: str
:returns: Instance of LibGPGPU.ConstMeanFunc or LibGPGPU.PolyMeanFunc implementing formula,
or None if the formula could not be parsed, or is not currently implemented in C++ code.
:rtype: LibGPGPU.ConstMeanFunc or LibGPGPU.PolyMeanFun or None
"""
if formula == "c":
return LibGPGPU.ConstMeanFunc()
else:
# see if the formula is a string representation of a number
try:
m = float(formula)
return LibGPGPU.FixedMeanFunc(m)
except:
pass
# if we got here, we hopefully have a parse-able formula
terms = formula.split("+")
def find_index_and_power(term):
variables = re.findall("x\[[\d+]\]",term)
if len(variables) == 0:
# didn't find a non-const term
return None
indices = [int(re.search("\[([\d+])\]", v).groups()[0]) for v in variables]
if indices.count(indices[0]) != len(indices):
raise NotImplementedError("Cross terms, e.g. x[0]*x[1] not implemented in GPU version.")
# first guess at the power to which the index is raised is how many times it appears
# e.g. if written as x[0]*x[0]
power = len(indices)
# however, it's also possible to write 'x[0]^2' or even, 'x[0]*x[0]^2' or even 'x[0]^2*x[0]^2'
# so look at all the numbers appearing after a '^'.
more_powers = re.findall("\^[\d]+",term)
more_powers = [int(re.search("\^([\d]+)",p).groups()[0]) for p in more_powers]
# now add these on to the original power number
# (subtracting one each time, as we already have x^1 implicitly)
for p in more_powers:
power += p - 1
return [indices[0], power]
indices_powers = []
for term in terms:
ip = find_index_and_power(term)
if ip:
indices_powers.append(ip)
if len(indices_powers) > 0:
return LibGPGPU.PolyMeanFunc(indices_powers)
else:
return None | def parse_meanfunc_formula(formula):
"""
Assuming the formula has already been parsed by the Python MeanFunction interface,
we expect it to be in a standard form, with parameters denoted by 'c' and variables
denoted by 'x[dim_index]' where dim_index < D.
:param formula: string representing the desired mean function formula
:type formula: str
:returns: Instance of LibGPGPU.ConstMeanFunc or LibGPGPU.PolyMeanFunc implementing formula,
or None if the formula could not be parsed, or is not currently implemented in C++ code.
:rtype: LibGPGPU.ConstMeanFunc or LibGPGPU.PolyMeanFun or None
"""
if formula == "c":
return LibGPGPU.ConstMeanFunc()
else:
# see if the formula is a string representation of a number
try:
m = float(formula)
return LibGPGPU.FixedMeanFunc(m)
except:
pass
# if we got here, we hopefully have a parse-able formula
terms = formula.split("+")
def find_index_and_power(term):
variables = re.findall("x\[[\d+]\]",term)
if len(variables) == 0:
# didn't find a non-const term
return None
indices = [int(re.search("\[([\d+])\]", v).groups()[0]) for v in variables]
if indices.count(indices[0]) != len(indices):
raise NotImplementedError("Cross terms, e.g. x[0]*x[1] not implemented in GPU version.")
# first guess at the power to which the index is raised is how many times it appears
# e.g. if written as x[0]*x[0]
power = len(indices)
# however, it's also possible to write 'x[0]^2' or even, 'x[0]*x[0]^2' or even 'x[0]^2*x[0]^2'
# so look at all the numbers appearing after a '^'.
more_powers = re.findall("\^[\d]+",term)
more_powers = [int(re.search("\^([\d]+)",p).groups()[0]) for p in more_powers]
# now add these on to the original power number
# (subtracting one each time, as we already have x^1 implicitly)
for p in more_powers:
power += p - 1
return [indices[0], power]
indices_powers = []
for term in terms:
ip = find_index_and_power(term)
if ip:
indices_powers.append(ip)
if len(indices_powers) > 0:
return LibGPGPU.PolyMeanFunc(indices_powers)
else:
return None |
Python | def inputs(self):
"""
Returns inputs for the emulator as a numpy array
:returns: Emulator inputs, 2D array with shape ``(n, D)``
:rtype: ndarray
"""
return self._densegp_gpu.inputs() | def inputs(self):
"""
Returns inputs for the emulator as a numpy array
:returns: Emulator inputs, 2D array with shape ``(n, D)``
:rtype: ndarray
"""
return self._densegp_gpu.inputs() |
Python | def targets(self):
"""
Returns targets for the emulator as a numpy array
:returns: Emulator targets, 1D array with shape ``(n,)``
:rtype: ndarray
"""
return self._densegp_gpu.targets() | def targets(self):
"""
Returns targets for the emulator as a numpy array
:returns: Emulator targets, 1D array with shape ``(n,)``
:rtype: ndarray
"""
return self._densegp_gpu.targets() |
Python | def n(self):
"""
Returns number of training examples for the emulator
:returns: Number of training examples for the emulator object
:rtype: int
"""
return self._densegp_gpu.n() | def n(self):
"""
Returns number of training examples for the emulator
:returns: Number of training examples for the emulator object
:rtype: int
"""
return self._densegp_gpu.n() |
Python | def D(self):
"""
Returns number of inputs (dimensions) for the emulator
:returns: Number of inputs for the emulator object
:rtype: int
"""
return self._densegp_gpu.D() | def D(self):
"""
Returns number of inputs (dimensions) for the emulator
:returns: Number of inputs for the emulator object
:rtype: int
"""
return self._densegp_gpu.D() |
Python | def n_params(self):
"""
Returns number of hyperparameters
Returns the number of hyperparameters for the emulator. The number depends on the
choice of mean function, covariance function, and nugget strategy, and possibly the
number of inputs for certain choices of the mean function.
:returns: Number of hyperparameters
:rtype: int
"""
return self._densegp_gpu.n_params()+ self.mean.get_n_params(self.inputs) | def n_params(self):
"""
Returns number of hyperparameters
Returns the number of hyperparameters for the emulator. The number depends on the
choice of mean function, covariance function, and nugget strategy, and possibly the
number of inputs for certain choices of the mean function.
:returns: Number of hyperparameters
:rtype: int
"""
return self._densegp_gpu.n_params()+ self.mean.get_n_params(self.inputs) |
Python | def L(self):
"""
Return the lower triangular Cholesky factor.
:returns: np.array
"""
result = np.zeros((self.n, self.n))
self._densegp_gpu.get_cholesky_lower(result)
return np.tril(result.transpose()) | def L(self):
"""
Return the lower triangular Cholesky factor.
:returns: np.array
"""
result = np.zeros((self.n, self.n))
self._densegp_gpu.get_cholesky_lower(result)
return np.tril(result.transpose()) |
Python | def fit(self, theta):
"""
Fits the emulator and sets the parameters.
Implements the same interface as
:func:`mogp_emulator.GaussianProcess.GaussianProcess.fit`
"""
theta = ndarray_coerce_type_and_flags(theta)
nugget_size = self.nugget if self.nugget_type == "fixed" else 0.
self._densegp_gpu.fit(theta, self._nugget_type, nugget_size)
if self.nugget_type == "adaptive" or self.nugget_type == "fit":
self._nugget = self._densegp_gpu.get_jitter()
invQt_result = np.zeros(self.n)
self._densegp_gpu.get_invQt(invQt_result)
self.invQt = invQt_result
self.current_logpost = self.logposterior(theta) | def fit(self, theta):
"""
Fits the emulator and sets the parameters.
Implements the same interface as
:func:`mogp_emulator.GaussianProcess.GaussianProcess.fit`
"""
theta = ndarray_coerce_type_and_flags(theta)
nugget_size = self.nugget if self.nugget_type == "fixed" else 0.
self._densegp_gpu.fit(theta, self._nugget_type, nugget_size)
if self.nugget_type == "adaptive" or self.nugget_type == "fit":
self._nugget = self._densegp_gpu.get_jitter()
invQt_result = np.zeros(self.n)
self._densegp_gpu.get_invQt(invQt_result)
self.invQt = invQt_result
self.current_logpost = self.logposterior(theta) |
Python | def logposterior(self, theta):
"""
Calculate the negative log-posterior at a particular value of the hyperparameters
See :func:`mogp_emulator.GaussianProcess.GaussianProcess.logposterior`
:param theta: Value of the hyperparameters. Must be array-like with shape ``(n_params,)``
:type theta: ndarray
:returns: negative log-posterior
:rtype: float
"""
if self.theta is None or not np.allclose(theta, self.theta, rtol=1.e-10, atol=1.e-15):
self.fit(theta)
return self._densegp_gpu.get_logpost() | def logposterior(self, theta):
"""
Calculate the negative log-posterior at a particular value of the hyperparameters
See :func:`mogp_emulator.GaussianProcess.GaussianProcess.logposterior`
:param theta: Value of the hyperparameters. Must be array-like with shape ``(n_params,)``
:type theta: ndarray
:returns: negative log-posterior
:rtype: float
"""
if self.theta is None or not np.allclose(theta, self.theta, rtol=1.e-10, atol=1.e-15):
self.fit(theta)
return self._densegp_gpu.get_logpost() |
Python | def predict(self, testing, unc=True, deriv=True, include_nugget=True):
"""
Make a prediction for a set of input vectors for a single set of hyperparameters.
This method implements the same interface as
:func:`mogp_emulator.GaussianProcess.GaussianProcess.predict`
"""
if self.theta is None:
raise ValueError("hyperparameters have not been fit for this Gaussian Process")
testing = ndarray_coerce_type_and_flags(testing)
if self.D == 1 and testing.ndim == 1:
testing = np.reshape(testing, (-1, 1))
elif testing.ndim == 1:
testing = np.reshape(testing, (1, len(testing)))
assert testing.ndim == 2
n_testing, D = np.shape(testing)
assert D == self.D
means = np.zeros(n_testing)
if unc:
variances = np.zeros(n_testing)
for i in range(0, n_testing, self._max_batch_size):
self._densegp_gpu.predict_variance_batch(
testing[i:i+self._max_batch_size],
means[i:i+self._max_batch_size],
variances[i:i+self._max_batch_size])
if include_nugget:
variances += self._nugget
else:
for i in range(0, n_testing, self._max_batch_size):
self._densegp_gpu.predict_batch(
testing[i:i+self._max_batch_size],
means[i:i+self._max_batch_size])
variances = None
if deriv:
deriv_result = np.zeros((n_testing,self.D))
for i in range(0, n_testing, self._max_batch_size):
self._densegp_gpu.predict_deriv(
testing[i:i+self._max_batch_size],
deriv_result[i:i+self._max_batch_size])
else:
deriv_result = None
return PredictResult(mean=means, unc=variances, deriv=deriv_result) | def predict(self, testing, unc=True, deriv=True, include_nugget=True):
"""
Make a prediction for a set of input vectors for a single set of hyperparameters.
This method implements the same interface as
:func:`mogp_emulator.GaussianProcess.GaussianProcess.predict`
"""
if self.theta is None:
raise ValueError("hyperparameters have not been fit for this Gaussian Process")
testing = ndarray_coerce_type_and_flags(testing)
if self.D == 1 and testing.ndim == 1:
testing = np.reshape(testing, (-1, 1))
elif testing.ndim == 1:
testing = np.reshape(testing, (1, len(testing)))
assert testing.ndim == 2
n_testing, D = np.shape(testing)
assert D == self.D
means = np.zeros(n_testing)
if unc:
variances = np.zeros(n_testing)
for i in range(0, n_testing, self._max_batch_size):
self._densegp_gpu.predict_variance_batch(
testing[i:i+self._max_batch_size],
means[i:i+self._max_batch_size],
variances[i:i+self._max_batch_size])
if include_nugget:
variances += self._nugget
else:
for i in range(0, n_testing, self._max_batch_size):
self._densegp_gpu.predict_batch(
testing[i:i+self._max_batch_size],
means[i:i+self._max_batch_size])
variances = None
if deriv:
deriv_result = np.zeros((n_testing,self.D))
for i in range(0, n_testing, self._max_batch_size):
self._densegp_gpu.predict_deriv(
testing[i:i+self._max_batch_size],
deriv_result[i:i+self._max_batch_size])
else:
deriv_result = None
return PredictResult(mean=means, unc=variances, deriv=deriv_result) |
Python | def fit_GP_MAP(*args, n_tries=15, theta0=None, method="L-BFGS-B",
skip_failures=True, refit=False, **kwargs):
"""Fit one or more Gaussian Processes by attempting to minimize the
negative log-posterior
Fits the hyperparameters of one or more Gaussian Processes by
attempting to minimize the negative log-posterior multiple times
from a given starting location and using a particular minimization
method. The best result found among all of the attempts is
returned, unless all attempts to fit the parameters result in an
error (see below).
The arguments to the method can either be an existing
``GaussianProcess`` or ``MultiOutputGP`` instance, or a list of
arguments to be passed to the ``__init__`` method of
``GaussianProcess`` or ``MultiOutputGP`` if more than one output
is detected. Keyword arguments for creating a new
``GaussianProcess`` or ``MultiOutputGP`` object can either be
passed as part of the ``*args`` list or as keywords (if present in
``**kwargs``, they will be extracted and passed separately to the
``__init__`` method).
If the method encounters an overflow (this can result because the
parameter values stored are the logarithm of the actual
hyperparameters to enforce positivity) or a linear algebra error
(occurs when the covariance matrix cannot be inverted, even with
additional noise added along the diagonal if adaptive noise was
selected), the iteration is skipped. If all attempts to find
optimal hyperparameters result in an error, then the emulator is
skipped and the parameters are reset to ``None``. By default, a
warning will be printed to the console if this occurs for
``MultiOutputGP`` fitting, while an error will be raise for
``GaussianProcess`` fitting. This behavior can be changed to raise
an error for ``MultiOutputGP`` fitting by passing the kwarg
``skip_failures=False``. This default behavior is chosen because
``MultiOutputGP`` fitting is often done in a situation where human
review of all fit emulators is not possible, so the fitting
routine skips over failures and then flags those that failed for
further review.
For ``MultiOutputGP`` fitting, by default the routine assumes that
only GPs that currently do not have hyperparameters fit need to be
fit. This behavior is controlled by the ``refit`` keyword, which
is ``False`` by default. To fit all emulators regardless of their
current fitting status, pass ``refit=True``. The ``refit``
argument has no effect on fitting of single ``GaussianProcess``
objects -- standard ``GaussianProcess`` objects will be fit
regardless of the current value of the hyperparameters.
The ``theta0`` parameter is the point at which the first iteration
will start. If more than one attempt is made, subsequent attempts
will use random starting points. If you are fitting Multiple
Outputs, then this argument can take any of the following forms:
(1) None (random start points for all emulators), (2) a list of
numpy arrays or ``NoneTypes`` with length ``n_emulators``, (3) a
numpy array of shape ``(n_params,)`` or ``(n_emulators,
n_params)`` which with either use the same start point for all
emulators or the specified start point for all emulators. Note
that if you us a numpy array, all emulators must have the same
number of parameters, while using a list allows more flexibility.
The user can specify the details of the minimization method, using
any of the gradient-based optimizers available in
``scipy.optimize.minimize``. Any additional parameters beyond the
method specification can be passed as keyword arguments.
The function returns a fit ``GaussianProcess`` or
``MultiOutputGP`` instance, either the original one passed to the
function, or the new one created from the included arguments.
:param ``*args``: Either a single ``GaussianProcess`` or
``MultiOutputGP`` instance, or arguments to be
passed to the ``__init__`` method when creating
a new ``GaussianProcess`` or ``MultiOutputGP``
instance.
:param n_tries: Number of attempts to minimize the negative
log-posterior function. Must be a positive
integer (optional, default is 15)
:type n_tries: int
:param theta0: Initial starting point for the first iteration. If
present, must be array-like with shape
``(n_params,)`` based on the specific
``GaussianProcess`` being fit. If a
``MultiOutputGP`` is being fit it must be a list of
length ``n_emulators`` with each entry as either
``None`` or a numpy array of shape ``(n_params,)``,
or a numpy array with shape ``(n_emulators,
n_params)`` (note that if the various emulators
have different numbers of parameters, the numpy
array option will not work). If ``None`` is given,
then a random value is chosen. (Default is
``None``)
:type theta0: None or ndarray
:param method: Minimization method to be used. Can be any
gradient-based optimization method available in
``scipy.optimize.minimize``. (Default is
``'L-BFGS-B'``)
:type method: str
:param skip_failures: Boolean controlling how to handle failures
in ``MultiOutputGP`` fitting. If set to
``True``, emulator fits will fail silently
without raising an error and provide
information on the emulators that failed
and the end of fitting. If ``False``, any
failed fit will raise a ``RuntimeError``.
Has no effect on fitting a single
``GaussianProcess``, which will always
raise an error. Optional, default is
``True``.
:type skip_failures: bool
:param refit: Boolean indicating if previously fit emulators
for ``MultiOutputGP`` objects should be fit again.
Optional, default is ``False``. Has no effect on
``GaussianProcess`` fitting, which will be fit
irrespective of the current hyperparameter values.
:type refit: bool
:param ``**kwargs``: Additional keyword arguments to be passed to
``GaussianProcess.__init__``,
``MultiOutputGP.__init__``, or the
minimization routine. Relevant parameters for
the GP classes are automatically split out
from those used in the minimization
function. See available parameters in the
corresponding functions for details.
:returns: Fit GP or Multi-Output GP instance
:rtype: GaussianProcess or MultiOutputGP
"""
if len(args) == 1:
gp = args[0]
if isinstance(gp, MultiOutputGP):
gp = _fit_MOGP_MAP(gp, n_tries, theta0, method, refit, **kwargs)
elif isinstance(gp, GaussianProcessBase):
gp = _fit_single_GP_MAP(gp, n_tries, theta0, method, **kwargs)
else:
raise TypeError("single arg to fit_GP_MAP must be a GaussianProcess or MultiOutputGP instance")
elif len(args) < 2:
raise TypeError("missing required inputs/targets arrays to GaussianProcess")
else:
gp_kwargs = {}
for key in ["mean", "kernel", "priors", "nugget", "inputdict", "use_patsy"]:
if key in kwargs:
gp_kwargs[key] = kwargs[key]
del kwargs[key]
try:
gp = GaussianProcess(*args, **gp_kwargs)
gp = _fit_single_GP_MAP(gp, n_tries, theta0, method, **kwargs)
except AssertionError:
try:
gp = MultiOutputGP(*args, **gp_kwargs)
gp = _fit_MOGP_MAP(gp, n_tries, theta0, method, **kwargs)
except AssertionError:
raise ValueError("Bad values for *args in fit_GP_MAP")
if isinstance(gp, GaussianProcessBase):
if gp.theta is None:
raise RuntimeError("GP fitting failed")
else:
if len(gp.get_indices_not_fit()) > 0:
failure_string = "Fitting failed for emulators {}".format(
gp.get_indices_not_fit())
if skip_failures:
print(failure_string)
else:
raise RuntimeError(failure_string)
return gp | def fit_GP_MAP(*args, n_tries=15, theta0=None, method="L-BFGS-B",
skip_failures=True, refit=False, **kwargs):
"""Fit one or more Gaussian Processes by attempting to minimize the
negative log-posterior
Fits the hyperparameters of one or more Gaussian Processes by
attempting to minimize the negative log-posterior multiple times
from a given starting location and using a particular minimization
method. The best result found among all of the attempts is
returned, unless all attempts to fit the parameters result in an
error (see below).
The arguments to the method can either be an existing
``GaussianProcess`` or ``MultiOutputGP`` instance, or a list of
arguments to be passed to the ``__init__`` method of
``GaussianProcess`` or ``MultiOutputGP`` if more than one output
is detected. Keyword arguments for creating a new
``GaussianProcess`` or ``MultiOutputGP`` object can either be
passed as part of the ``*args`` list or as keywords (if present in
``**kwargs``, they will be extracted and passed separately to the
``__init__`` method).
If the method encounters an overflow (this can result because the
parameter values stored are the logarithm of the actual
hyperparameters to enforce positivity) or a linear algebra error
(occurs when the covariance matrix cannot be inverted, even with
additional noise added along the diagonal if adaptive noise was
selected), the iteration is skipped. If all attempts to find
optimal hyperparameters result in an error, then the emulator is
skipped and the parameters are reset to ``None``. By default, a
warning will be printed to the console if this occurs for
``MultiOutputGP`` fitting, while an error will be raise for
``GaussianProcess`` fitting. This behavior can be changed to raise
an error for ``MultiOutputGP`` fitting by passing the kwarg
``skip_failures=False``. This default behavior is chosen because
``MultiOutputGP`` fitting is often done in a situation where human
review of all fit emulators is not possible, so the fitting
routine skips over failures and then flags those that failed for
further review.
For ``MultiOutputGP`` fitting, by default the routine assumes that
only GPs that currently do not have hyperparameters fit need to be
fit. This behavior is controlled by the ``refit`` keyword, which
is ``False`` by default. To fit all emulators regardless of their
current fitting status, pass ``refit=True``. The ``refit``
argument has no effect on fitting of single ``GaussianProcess``
objects -- standard ``GaussianProcess`` objects will be fit
regardless of the current value of the hyperparameters.
The ``theta0`` parameter is the point at which the first iteration
will start. If more than one attempt is made, subsequent attempts
will use random starting points. If you are fitting Multiple
Outputs, then this argument can take any of the following forms:
(1) None (random start points for all emulators), (2) a list of
numpy arrays or ``NoneTypes`` with length ``n_emulators``, (3) a
numpy array of shape ``(n_params,)`` or ``(n_emulators,
n_params)`` which with either use the same start point for all
emulators or the specified start point for all emulators. Note
that if you us a numpy array, all emulators must have the same
number of parameters, while using a list allows more flexibility.
The user can specify the details of the minimization method, using
any of the gradient-based optimizers available in
``scipy.optimize.minimize``. Any additional parameters beyond the
method specification can be passed as keyword arguments.
The function returns a fit ``GaussianProcess`` or
``MultiOutputGP`` instance, either the original one passed to the
function, or the new one created from the included arguments.
:param ``*args``: Either a single ``GaussianProcess`` or
``MultiOutputGP`` instance, or arguments to be
passed to the ``__init__`` method when creating
a new ``GaussianProcess`` or ``MultiOutputGP``
instance.
:param n_tries: Number of attempts to minimize the negative
log-posterior function. Must be a positive
integer (optional, default is 15)
:type n_tries: int
:param theta0: Initial starting point for the first iteration. If
present, must be array-like with shape
``(n_params,)`` based on the specific
``GaussianProcess`` being fit. If a
``MultiOutputGP`` is being fit it must be a list of
length ``n_emulators`` with each entry as either
``None`` or a numpy array of shape ``(n_params,)``,
or a numpy array with shape ``(n_emulators,
n_params)`` (note that if the various emulators
have different numbers of parameters, the numpy
array option will not work). If ``None`` is given,
then a random value is chosen. (Default is
``None``)
:type theta0: None or ndarray
:param method: Minimization method to be used. Can be any
gradient-based optimization method available in
``scipy.optimize.minimize``. (Default is
``'L-BFGS-B'``)
:type method: str
:param skip_failures: Boolean controlling how to handle failures
in ``MultiOutputGP`` fitting. If set to
``True``, emulator fits will fail silently
without raising an error and provide
information on the emulators that failed
and the end of fitting. If ``False``, any
failed fit will raise a ``RuntimeError``.
Has no effect on fitting a single
``GaussianProcess``, which will always
raise an error. Optional, default is
``True``.
:type skip_failures: bool
:param refit: Boolean indicating if previously fit emulators
for ``MultiOutputGP`` objects should be fit again.
Optional, default is ``False``. Has no effect on
``GaussianProcess`` fitting, which will be fit
irrespective of the current hyperparameter values.
:type refit: bool
:param ``**kwargs``: Additional keyword arguments to be passed to
``GaussianProcess.__init__``,
``MultiOutputGP.__init__``, or the
minimization routine. Relevant parameters for
the GP classes are automatically split out
from those used in the minimization
function. See available parameters in the
corresponding functions for details.
:returns: Fit GP or Multi-Output GP instance
:rtype: GaussianProcess or MultiOutputGP
"""
if len(args) == 1:
gp = args[0]
if isinstance(gp, MultiOutputGP):
gp = _fit_MOGP_MAP(gp, n_tries, theta0, method, refit, **kwargs)
elif isinstance(gp, GaussianProcessBase):
gp = _fit_single_GP_MAP(gp, n_tries, theta0, method, **kwargs)
else:
raise TypeError("single arg to fit_GP_MAP must be a GaussianProcess or MultiOutputGP instance")
elif len(args) < 2:
raise TypeError("missing required inputs/targets arrays to GaussianProcess")
else:
gp_kwargs = {}
for key in ["mean", "kernel", "priors", "nugget", "inputdict", "use_patsy"]:
if key in kwargs:
gp_kwargs[key] = kwargs[key]
del kwargs[key]
try:
gp = GaussianProcess(*args, **gp_kwargs)
gp = _fit_single_GP_MAP(gp, n_tries, theta0, method, **kwargs)
except AssertionError:
try:
gp = MultiOutputGP(*args, **gp_kwargs)
gp = _fit_MOGP_MAP(gp, n_tries, theta0, method, **kwargs)
except AssertionError:
raise ValueError("Bad values for *args in fit_GP_MAP")
if isinstance(gp, GaussianProcessBase):
if gp.theta is None:
raise RuntimeError("GP fitting failed")
else:
if len(gp.get_indices_not_fit()) > 0:
failure_string = "Fitting failed for emulators {}".format(
gp.get_indices_not_fit())
if skip_failures:
print(failure_string)
else:
raise RuntimeError(failure_string)
return gp |
Python | def _fit_single_GP_MAP(gp, n_tries=15, theta0=None, method='L-BFGS-B', **kwargs):
"""Fit hyperparameters using MAP for a single GP
Returns a single GP object that has its hyperparameters fit to the
MAP value. Accepts keyword arguments passed to scipy's
minimization routine.
"""
assert isinstance(gp, GaussianProcessBase)
n_tries = int(n_tries)
assert n_tries > 0, "number of attempts must be positive"
np.seterr(divide = 'raise', over = 'raise', invalid = 'raise')
logpost_values = []
theta_values = []
theta_startvals = 5.*(np.random.rand(n_tries, gp.n_params) - 0.5)
if not theta0 is None:
theta0 = np.array(theta0)
assert theta0.shape == (gp.n_params,), "theta0 must be a 1D array with length n_params"
theta_startvals[0,:] = theta0
for theta in theta_startvals:
try:
min_dict = minimize(gp.logposterior, theta, method = method,
jac = gp.logpost_deriv, options = kwargs)
min_theta = min_dict['x']
min_logpost = min_dict['fun']
logpost_values.append(min_logpost)
theta_values.append(min_theta)
except LinAlgError:
print("Matrix not positive definite, skipping this iteration")
except FloatingPointError:
print("Floating point error in optimization routine, skipping this iteration")
if len(logpost_values) == 0:
print("Minimization routine failed to return a value")
gp.theta = None
else:
logpost_values = np.array(logpost_values)
idx = np.argmin(logpost_values)
gp.fit(theta_values[idx])
return gp | def _fit_single_GP_MAP(gp, n_tries=15, theta0=None, method='L-BFGS-B', **kwargs):
"""Fit hyperparameters using MAP for a single GP
Returns a single GP object that has its hyperparameters fit to the
MAP value. Accepts keyword arguments passed to scipy's
minimization routine.
"""
assert isinstance(gp, GaussianProcessBase)
n_tries = int(n_tries)
assert n_tries > 0, "number of attempts must be positive"
np.seterr(divide = 'raise', over = 'raise', invalid = 'raise')
logpost_values = []
theta_values = []
theta_startvals = 5.*(np.random.rand(n_tries, gp.n_params) - 0.5)
if not theta0 is None:
theta0 = np.array(theta0)
assert theta0.shape == (gp.n_params,), "theta0 must be a 1D array with length n_params"
theta_startvals[0,:] = theta0
for theta in theta_startvals:
try:
min_dict = minimize(gp.logposterior, theta, method = method,
jac = gp.logpost_deriv, options = kwargs)
min_theta = min_dict['x']
min_logpost = min_dict['fun']
logpost_values.append(min_logpost)
theta_values.append(min_theta)
except LinAlgError:
print("Matrix not positive definite, skipping this iteration")
except FloatingPointError:
print("Floating point error in optimization routine, skipping this iteration")
if len(logpost_values) == 0:
print("Minimization routine failed to return a value")
gp.theta = None
else:
logpost_values = np.array(logpost_values)
idx = np.argmin(logpost_values)
gp.fit(theta_values[idx])
return gp |
Python | def _fit_MOGP_MAP(gp, n_tries=15, theta0=None, method='L-BFGS-B',
refit=False, **kwargs):
"""Fit hyperparameters using MAP for multiple GPs in parallel
Uses Python Multiprocessing to fit GPs in parallel by calling the
above routine for a single GP for each of the emulators in the
MOGP class. Returns a MultiOutputGP object where all emulators
have been fit to the MAP value.
Routine only fits GPs that have not previously been fit (indicated
by the hyperparameters being set to ``None`` by default. This can
be overridden by passing ``refit=True``.
Accepts a ``processes`` argument (integer or None) as a keyword to
control the number of subprocesses used to fit the individual GPs
in parallel. Must be positive. Default is ``None``.
"""
assert isinstance(gp, MultiOutputGP)
try:
processes = kwargs['processes']
del kwargs['processes']
except KeyError:
processes = None
assert int(n_tries) > 0, "n_tries must be a positive integer"
if theta0 is None:
theta0 = [ None ]*gp.n_emulators
else:
if isinstance(theta0, np.ndarray):
if theta0.ndim == 1:
theta0 = [theta0]*gp.n_emulators
else:
assert theta0.ndim == 2, "theta0 must be a 1D or 2D array"
assert theta0.shape[0] == gp.n_emulators, "bad shape for fitting starting points"
elif isinstance(theta0, list):
assert len(theta0) == gp.n_emulators, "theta0 must be a list of length n_emulators"
if not processes is None:
processes = int(processes)
assert processes > 0, "number of processes must be positive"
n_tries = int(n_tries)
if refit:
emulators_to_fit = gp.emulators
indices_to_fit = list(range(len(gp.emulators)))
thetavals = theta0
else:
indices_to_fit = gp.get_indices_not_fit()
emulators_to_fit = gp.get_emulators_not_fit()
thetavals = [ theta0[idx] for idx in indices_to_fit]
if platform.system() == "Windows" or gp.use_gpu:
fit_MOGP = [fit_GP_MAP(emulator, n_tries=n_tries, theta0=t0, method=method, **kwargs)
for (emulator, t0) in zip(emulators_to_fit, thetavals)]
else:
with Pool(processes) as p:
fit_MOGP = p.starmap(partial(_fit_single_GP_MAP_bound, n_tries=n_tries, method=method, **kwargs),
[(emulator, t0) for (emulator, t0) in zip(emulators_to_fit, thetavals)])
for (idx, em) in zip(indices_to_fit, fit_MOGP):
gp.emulators[idx] = em
return gp | def _fit_MOGP_MAP(gp, n_tries=15, theta0=None, method='L-BFGS-B',
refit=False, **kwargs):
"""Fit hyperparameters using MAP for multiple GPs in parallel
Uses Python Multiprocessing to fit GPs in parallel by calling the
above routine for a single GP for each of the emulators in the
MOGP class. Returns a MultiOutputGP object where all emulators
have been fit to the MAP value.
Routine only fits GPs that have not previously been fit (indicated
by the hyperparameters being set to ``None`` by default. This can
be overridden by passing ``refit=True``.
Accepts a ``processes`` argument (integer or None) as a keyword to
control the number of subprocesses used to fit the individual GPs
in parallel. Must be positive. Default is ``None``.
"""
assert isinstance(gp, MultiOutputGP)
try:
processes = kwargs['processes']
del kwargs['processes']
except KeyError:
processes = None
assert int(n_tries) > 0, "n_tries must be a positive integer"
if theta0 is None:
theta0 = [ None ]*gp.n_emulators
else:
if isinstance(theta0, np.ndarray):
if theta0.ndim == 1:
theta0 = [theta0]*gp.n_emulators
else:
assert theta0.ndim == 2, "theta0 must be a 1D or 2D array"
assert theta0.shape[0] == gp.n_emulators, "bad shape for fitting starting points"
elif isinstance(theta0, list):
assert len(theta0) == gp.n_emulators, "theta0 must be a list of length n_emulators"
if not processes is None:
processes = int(processes)
assert processes > 0, "number of processes must be positive"
n_tries = int(n_tries)
if refit:
emulators_to_fit = gp.emulators
indices_to_fit = list(range(len(gp.emulators)))
thetavals = theta0
else:
indices_to_fit = gp.get_indices_not_fit()
emulators_to_fit = gp.get_emulators_not_fit()
thetavals = [ theta0[idx] for idx in indices_to_fit]
if platform.system() == "Windows" or gp.use_gpu:
fit_MOGP = [fit_GP_MAP(emulator, n_tries=n_tries, theta0=t0, method=method, **kwargs)
for (emulator, t0) in zip(emulators_to_fit, thetavals)]
else:
with Pool(processes) as p:
fit_MOGP = p.starmap(partial(_fit_single_GP_MAP_bound, n_tries=n_tries, method=method, **kwargs),
[(emulator, t0) for (emulator, t0) in zip(emulators_to_fit, thetavals)])
for (idx, em) in zip(indices_to_fit, fit_MOGP):
gp.emulators[idx] = em
return gp |
Python | def _check_cholesky_inputs(A):
"""
Check inputs to cholesky routines
This function is used by both specialized Cholesky routines to check inputs. It verifies
that the input is a 2D square matrix and that all diagonal elements are positive (a
necessary but not sufficient condition for positive definiteness). If these checks pass,
it returns the input as a numpy array.
:param A: The matrix to be inverted as an array of shape ``(n,n)``. Must be a symmetric positive
definite matrix.
:type A: ndarray or similar
:returns: The matrix to be inverted as an array of shape ``(n,n)``. Must be a symmetric positive
definite matrix.
:rtype: ndarray
"""
A = np.array(A)
assert A.ndim == 2, "A must have shape (n,n)"
assert A.shape[0] == A.shape[1], "A must have shape (n,n)"
np.testing.assert_allclose(A.T, A)
diagA = np.diag(A)
if np.any(diagA <= 0.):
raise linalg.LinAlgError("not pd: non-positive diagonal elements")
return A | def _check_cholesky_inputs(A):
"""
Check inputs to cholesky routines
This function is used by both specialized Cholesky routines to check inputs. It verifies
that the input is a 2D square matrix and that all diagonal elements are positive (a
necessary but not sufficient condition for positive definiteness). If these checks pass,
it returns the input as a numpy array.
:param A: The matrix to be inverted as an array of shape ``(n,n)``. Must be a symmetric positive
definite matrix.
:type A: ndarray or similar
:returns: The matrix to be inverted as an array of shape ``(n,n)``. Must be a symmetric positive
definite matrix.
:rtype: ndarray
"""
A = np.array(A)
assert A.ndim == 2, "A must have shape (n,n)"
assert A.shape[0] == A.shape[1], "A must have shape (n,n)"
np.testing.assert_allclose(A.T, A)
diagA = np.diag(A)
if np.any(diagA <= 0.):
raise linalg.LinAlgError("not pd: non-positive diagonal elements")
return A |
Python | def jit_cholesky(A, maxtries = 5):
"""
Performs Jittered Cholesky Decomposition
Performs a Jittered Cholesky decomposition, adding noise to the diagonal of the matrix as needed
in order to ensure that the matrix can be inverted. Adapted from code in GPy.
On occasion, the matrix that needs to be inverted in fitting a GP is nearly singular. This arises
when the training samples are very close to one another, and can be averted by adding a noise term
to the diagonal of the matrix. This routine performs an exact Cholesky decomposition if it can
be done, and if it cannot it successively adds noise to the diagonal (starting with 1.e-6 times
the mean of the diagonal and incrementing by a factor of 10 each time) until the matrix can be
decomposed or the algorithm reaches ``maxtries`` attempts. The routine returns the lower
triangular matrix and the amount of noise necessary to stabilize the decomposition.
:param A: The matrix to be inverted as an array of shape ``(n,n)``. Must be a symmetric positive
definite matrix.
:type A: ndarray
:param maxtries: (optional) Maximum allowable number of attempts to stabilize the Cholesky
Decomposition. Must be a positive integer (default = 5)
:type maxtries: int
:returns: Lower-triangular factored matrix (shape ``(n,n)`` and the noise that was added to
the diagonal to achieve that result.
:rtype: tuple containing an ndarray and a float
"""
A = _check_cholesky_inputs(A)
assert int(maxtries) > 0, "maxtries must be a positive integer"
A = np.ascontiguousarray(A)
L, info = lapack.dpotrf(A, lower = 1)
if info == 0:
return L, 0.
else:
diagA = np.diag(A)
jitter = diagA.mean() * 1e-6
num_tries = 1
while num_tries <= maxtries and np.isfinite(jitter):
try:
L = linalg.cholesky(A + np.eye(A.shape[0]) * jitter, lower=True)
return L, jitter
except:
jitter *= 10
finally:
num_tries += 1
raise linalg.LinAlgError("not positive definite, even with jitter.")
return L, jitter | def jit_cholesky(A, maxtries = 5):
"""
Performs Jittered Cholesky Decomposition
Performs a Jittered Cholesky decomposition, adding noise to the diagonal of the matrix as needed
in order to ensure that the matrix can be inverted. Adapted from code in GPy.
On occasion, the matrix that needs to be inverted in fitting a GP is nearly singular. This arises
when the training samples are very close to one another, and can be averted by adding a noise term
to the diagonal of the matrix. This routine performs an exact Cholesky decomposition if it can
be done, and if it cannot it successively adds noise to the diagonal (starting with 1.e-6 times
the mean of the diagonal and incrementing by a factor of 10 each time) until the matrix can be
decomposed or the algorithm reaches ``maxtries`` attempts. The routine returns the lower
triangular matrix and the amount of noise necessary to stabilize the decomposition.
:param A: The matrix to be inverted as an array of shape ``(n,n)``. Must be a symmetric positive
definite matrix.
:type A: ndarray
:param maxtries: (optional) Maximum allowable number of attempts to stabilize the Cholesky
Decomposition. Must be a positive integer (default = 5)
:type maxtries: int
:returns: Lower-triangular factored matrix (shape ``(n,n)`` and the noise that was added to
the diagonal to achieve that result.
:rtype: tuple containing an ndarray and a float
"""
A = _check_cholesky_inputs(A)
assert int(maxtries) > 0, "maxtries must be a positive integer"
A = np.ascontiguousarray(A)
L, info = lapack.dpotrf(A, lower = 1)
if info == 0:
return L, 0.
else:
diagA = np.diag(A)
jitter = diagA.mean() * 1e-6
num_tries = 1
while num_tries <= maxtries and np.isfinite(jitter):
try:
L = linalg.cholesky(A + np.eye(A.shape[0]) * jitter, lower=True)
return L, jitter
except:
jitter *= 10
finally:
num_tries += 1
raise linalg.LinAlgError("not positive definite, even with jitter.")
return L, jitter |
Python | def pivot_cholesky(A):
"""
Pivoted cholesky decomposition routine
Performs a pivoted Cholesky decomposition on a square, potentially
singular (i.e. can have collinear rows) covariance matrix. Rows
and columns are interchanged such that the diagonal entries of the
factorized matrix decrease from the first entry to the last entry.
Any collinear rows are skipped, and the diagonal entries for those
rows are instead replaced by a decreasing entry. This allows the
factorized matrix to still be used to compute the log determinant
in the same way, which is required to compute the marginal log
likelihood/posterior in the GP fitting.
Returns the factorized matrix, and an ordered array of integer
indices indicating the pivoting order. Raises an error if the
decomposition fails.
:param A: The matrix to be inverted as an array of shape ``(n,n)``.
Must be a symmetric matrix (though can be singular).
:type A: ndarray
:returns: Lower-triangular factored matrix (shape ``(n,n)`` an an array of
integers indicating the pivoting order needed to produce the
factorization.
:rtype: tuple containing an ndarray of shape `(n,n)` of floats and a
ndarray of shape `(n,)` of integers.
"""
A = _check_cholesky_inputs(A)
A = np.ascontiguousarray(A)
L, P, rank, info = lapack.dpstrf(A, lower = 1)
L = np.tril(L)
if info < 0:
raise linalg.LinAlgError("Illegal value in covariance matrix")
n = A.shape[0]
idx = np.arange(rank, n)
divs = np.cumprod(np.arange(rank+1, n+1, dtype=np.float64))
L[idx, idx] = L[rank-1, rank-1]/divs
return L, P-1 | def pivot_cholesky(A):
"""
Pivoted cholesky decomposition routine
Performs a pivoted Cholesky decomposition on a square, potentially
singular (i.e. can have collinear rows) covariance matrix. Rows
and columns are interchanged such that the diagonal entries of the
factorized matrix decrease from the first entry to the last entry.
Any collinear rows are skipped, and the diagonal entries for those
rows are instead replaced by a decreasing entry. This allows the
factorized matrix to still be used to compute the log determinant
in the same way, which is required to compute the marginal log
likelihood/posterior in the GP fitting.
Returns the factorized matrix, and an ordered array of integer
indices indicating the pivoting order. Raises an error if the
decomposition fails.
:param A: The matrix to be inverted as an array of shape ``(n,n)``.
Must be a symmetric matrix (though can be singular).
:type A: ndarray
:returns: Lower-triangular factored matrix (shape ``(n,n)`` an an array of
integers indicating the pivoting order needed to produce the
factorization.
:rtype: tuple containing an ndarray of shape `(n,n)` of floats and a
ndarray of shape `(n,)` of integers.
"""
A = _check_cholesky_inputs(A)
A = np.ascontiguousarray(A)
L, P, rank, info = lapack.dpstrf(A, lower = 1)
L = np.tril(L)
if info < 0:
raise linalg.LinAlgError("Illegal value in covariance matrix")
n = A.shape[0]
idx = np.arange(rank, n)
divs = np.cumprod(np.arange(rank+1, n+1, dtype=np.float64))
L[idx, idx] = L[rank-1, rank-1]/divs
return L, P-1 |
Python | def _pivot_transpose(P):
"""
Invert a pivot matrix by taking its transpose
Inverts the pivot matrix by taking its transpose. Since the pivot
matrix is represented by an array of integers(to make swapping the
rows more simple by using numpy indexing), this is done by
creating the equivalent array of integers representing the
transpose. Input must be a list of non-negative integers, where
each integer up to the length of the array appears exactly
once. Otherwise this function will raise an exception.
:param P: Input pivot matrix, represented as an array of non-negative
integers.
:type P: ndarray containing integers
:returns: Transpose of the pivot matrix, represented as an array of
non-negative integers.
:rtype: ndarray containing integers.
"""
assert np.array(P).ndim == 1, "pivot matrix must be a list of integers"
try:
return np.array([np.where(P == idx)[0][0] for idx in range(len(P))], dtype=np.int32)
except IndexError:
raise ValueError("Bad values for pivot matrix input to pivot_transpose") | def _pivot_transpose(P):
"""
Invert a pivot matrix by taking its transpose
Inverts the pivot matrix by taking its transpose. Since the pivot
matrix is represented by an array of integers(to make swapping the
rows more simple by using numpy indexing), this is done by
creating the equivalent array of integers representing the
transpose. Input must be a list of non-negative integers, where
each integer up to the length of the array appears exactly
once. Otherwise this function will raise an exception.
:param P: Input pivot matrix, represented as an array of non-negative
integers.
:type P: ndarray containing integers
:returns: Transpose of the pivot matrix, represented as an array of
non-negative integers.
:rtype: ndarray containing integers.
"""
assert np.array(P).ndim == 1, "pivot matrix must be a list of integers"
try:
return np.array([np.where(P == idx)[0][0] for idx in range(len(P))], dtype=np.int32)
except IndexError:
raise ValueError("Bad values for pivot matrix input to pivot_transpose") |
Python | def pivot_cho_solve(L, P, b):
"""Solve a Linear System factorized using Pivoted Cholesky Decomposition
Solve a system :math:`{Ax = b}` where the matrix has been factorized using the
`pivot_cholesky` function. Can also solve a system which has been
factorized using the regular Cholesky decomposition routine if
`P` is the set of integers from 0 to the length of the linear system.
The routine rearranges the order of the RHS based on the pivoting
order that was used, and then rearranges back to the original
ordering of the RHS when returning the array.
:param L: Factorized :math:`{A}` square matrix using
pivoting. Assumes lower triangular factorization is
used.
:type L: ndarray
:param P: Pivot matrix, expressed as a list or 1D array of
integers that is the same length as `L`. Must contain
only nonzero integers as entries, with each number up to
the length of the array appearing exactly once.
:type P: list or ndarray
:param b: Right hand side to be solved. Can be any array that
satisfies the rules of the scipy `cho_solve` routine.
:type b: ndarray
:returns: Solution to the appropriate linear system as a ndarray.
:rtype: ndarray
"""
assert len(P) == L.shape[0], "Length of pivot matrix must match linear system"
try:
return cho_solve((L, True), b[P])[_pivot_transpose(P)]
except (IndexError, ValueError):
raise ValueError("Bad values for pivot matrix in pivot_cho_solve") | def pivot_cho_solve(L, P, b):
"""Solve a Linear System factorized using Pivoted Cholesky Decomposition
Solve a system :math:`{Ax = b}` where the matrix has been factorized using the
`pivot_cholesky` function. Can also solve a system which has been
factorized using the regular Cholesky decomposition routine if
`P` is the set of integers from 0 to the length of the linear system.
The routine rearranges the order of the RHS based on the pivoting
order that was used, and then rearranges back to the original
ordering of the RHS when returning the array.
:param L: Factorized :math:`{A}` square matrix using
pivoting. Assumes lower triangular factorization is
used.
:type L: ndarray
:param P: Pivot matrix, expressed as a list or 1D array of
integers that is the same length as `L`. Must contain
only nonzero integers as entries, with each number up to
the length of the array appearing exactly once.
:type P: list or ndarray
:param b: Right hand side to be solved. Can be any array that
satisfies the rules of the scipy `cho_solve` routine.
:type b: ndarray
:returns: Solution to the appropriate linear system as a ndarray.
:rtype: ndarray
"""
assert len(P) == L.shape[0], "Length of pivot matrix must match linear system"
try:
return cho_solve((L, True), b[P])[_pivot_transpose(P)]
except (IndexError, ValueError):
raise ValueError("Bad values for pivot matrix in pivot_cho_solve") |
Python | def recursive_var_search(v, variable_list):
""" Add all variables to var_list, recursively.
v is the json variable that will be searched recursively.
each element in variable_list will be a 3-tuple consisting of:
* full_name
* name
* value
"""
if isinstance(v['value'], list):
for v2 in v['value']:
# print("val:", json.dumps(val, indent=2))
recursive_var_search(v2, variable_list)
# var_names_to_tokens[val['full_name']] = val['value']
else:
try:
variable_list.append((v['full_name'], v['name'], v['value']))
except BaseException:
assert False, "Json parsing error for variable %s" % (
json.dumps(v, indent=2)) | def recursive_var_search(v, variable_list):
""" Add all variables to var_list, recursively.
v is the json variable that will be searched recursively.
each element in variable_list will be a 3-tuple consisting of:
* full_name
* name
* value
"""
if isinstance(v['value'], list):
for v2 in v['value']:
# print("val:", json.dumps(val, indent=2))
recursive_var_search(v2, variable_list)
# var_names_to_tokens[val['full_name']] = val['value']
else:
try:
variable_list.append((v['full_name'], v['name'], v['value']))
except BaseException:
assert False, "Json parsing error for variable %s" % (
json.dumps(v, indent=2)) |
Python | def convert_dialog_json_to_ner_tagged_examples(d, dialog_id, api_endpoints=[
"find_place", "places_nearby"], param_name="query", do_predict=False):
''' Converts a json to [possibly] multiple ner-tagged examples.
Args:
d - json representing a single dialog context
dialog_id - string identifier for the dialog
Example ner-tagged example format:
-DOCSTART-log_518.json:::::hawker
[INITIAL] 0
[VAR_TYPE] 0
source address 0
[VAR_VALUE] 0
150 North Bridge Road, Singapore 179100 0
[VAR_TYPE] 0
source latitude 0
[VAR_VALUE] 0
1.293076 0
[VAR_TYPE] 0
source longitude 0
[VAR_VALUE] 0
103.85206770000002 0
[USER] 0
Hi 0
, 0
is 0
there 0
a 0
hawker 0
centre 0
nearby 0
? 0
[USER] 0
Hi 0
, 0
is 0
there 0
a 0
nearby 0
hawker 1
center 0
? 0
[AGENT] 0
Sure, give me a moment. 0
[API] 0
places nearby 0
[API_PARAM_NAME] 0
query 0
'''
output_examples = list()
all_tokens_and_labels = list()
var_name_to_token_index = dict()
var_names_to_tokens = dict()
# Add initial variables
initial_variables = d['initial_variables']['variables'] if isinstance(
d['initial_variables'], dict) else d['initial_variables']
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS['initial_variables'], NOCLICK_LABEL])
for var in initial_variables:
var_names_to_tokens[var['full_name']] = str(var['value'])
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS["var_type"], NOCLICK_LABEL])
all_tokens_and_labels.append(
[remove_underscore(var['full_name']), NOCLICK_LABEL])
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS["var_value"], NOCLICK_LABEL])
# Make token index to relabel correspond to the [VAR_VALUE] token
var_name_to_token_index[var['full_name']] = len(
all_tokens_and_labels) - 1
all_tokens_and_labels.append([var['value'], NOCLICK_LABEL])
for e in d["events"]:
if e['event_type'] == "user_utterance":
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS['user_utterance'], NOCLICK_LABEL])
# For user utterances, do not add user variable names (e.g. u1_2)
# as tokens.
for var in e['variables']:
all_tokens_and_labels.append([var['value'], NOCLICK_LABEL])
var_name_to_token_index[var['full_name']] = len(
all_tokens_and_labels) - 1
var_names_to_tokens[var['full_name']] = var['value']
elif e['event_type'] == "agent_utterance":
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS['agent_utterance'], NOCLICK_LABEL])
all_tokens_and_labels.append([e['utterance'], NOCLICK_LABEL])
elif e['event_type'] == "api_call":
# First, COPY all tokens and labels,
# and output an example if the endpoint and input parameter match.
if e['endpoint'] in api_endpoints:
found_matching_param = False
gold_params = None
gold_value = "__DUMMY__"
copy_all_tokens_and_labels = deepcopy(all_tokens_and_labels)
# Append something like:
# [API] 0
# find_place 0
copy_all_tokens_and_labels.extend([
[SPECIAL_SEPARATORS['api_call'], NOCLICK_LABEL],
[remove_underscore(e['endpoint']), NOCLICK_LABEL]
])
# Append something like:
# [API_PARAM_NAME] 0
# query 0
# OR if not target param
# [API_PARAM_NAME] 0
# src latitude 0
# [API_PARAM_VALUE]
# -118.71 0
for p in e['params']:
copy_all_tokens_and_labels.append(
[SPECIAL_SEPARATORS["api_param_name"], NOCLICK_LABEL])
copy_all_tokens_and_labels.append(
[remove_underscore(p["param"]), NOCLICK_LABEL])
if p["param"] == param_name:
found_matching_param = True
if not do_predict:
gold_params = p['variable_name']
gold_value = p['value']
break
copy_all_tokens_and_labels.append(
[SPECIAL_SEPARATORS["api_param_value"], NOCLICK_LABEL])
copy_all_tokens_and_labels.append(
[p["value"], NOCLICK_LABEL])
if found_matching_param:
if not do_predict:
# If we found our target API and parameter, re-label their NER NOCLICK tags with CLICK tags,
# and write the example to file.
assert gold_params is not None
gold_params = split_utterance_var(gold_params)
for var in gold_params:
index = var_name_to_token_index[var]
copy_all_tokens_and_labels[index][1] = CLICK_LABEL
new_example = [
"%s%s:::::%s" %
(DOCSTART, dialog_id, gold_value)]
for token, label in copy_all_tokens_and_labels:
new_example.append(str(token) + " " + label)
output_examples.append(new_example)
# Unrelated to gold-params, add all API stuff
# Append something like:
# [API] 0
# find_place 0
# [API_PARAM_NAME] 0
# query 0
# [API_PARAM_NAME] 0
# src latitude 0
# [API_PARAM_VALUE]
# -118.71 0
# ...
all_tokens_and_labels.extend([
[SPECIAL_SEPARATORS['api_call'], NOCLICK_LABEL],
[remove_underscore(e['endpoint']), NOCLICK_LABEL]
])
for p in e['params']:
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS["api_param_name"], NOCLICK_LABEL])
all_tokens_and_labels.append([p["param"], NOCLICK_LABEL])
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS["api_param_value"], NOCLICK_LABEL])
all_tokens_and_labels.append([p["value"], NOCLICK_LABEL])
# Append api's returned variables in something like
# [VAR_TYPE] address
# [VAR_VALUE] 1234 5th street
# ....
# Also index variable tokens and lines by full name
returned_variables = list()
for v in e['variables']:
recursive_var_search(v, returned_variables)
for full_name, name, value in returned_variables:
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS["var_type"], NOCLICK_LABEL])
all_tokens_and_labels.append([name, NOCLICK_LABEL])
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS["var_value"], NOCLICK_LABEL])
# Make token index to relabel correspond to the [VAR_VALUE]
# token
var_name_to_token_index[full_name] = len(
all_tokens_and_labels) - 1
all_tokens_and_labels.append([value, NOCLICK_LABEL])
var_names_to_tokens[full_name] = value
return output_examples | def convert_dialog_json_to_ner_tagged_examples(d, dialog_id, api_endpoints=[
"find_place", "places_nearby"], param_name="query", do_predict=False):
''' Converts a json to [possibly] multiple ner-tagged examples.
Args:
d - json representing a single dialog context
dialog_id - string identifier for the dialog
Example ner-tagged example format:
-DOCSTART-log_518.json:::::hawker
[INITIAL] 0
[VAR_TYPE] 0
source address 0
[VAR_VALUE] 0
150 North Bridge Road, Singapore 179100 0
[VAR_TYPE] 0
source latitude 0
[VAR_VALUE] 0
1.293076 0
[VAR_TYPE] 0
source longitude 0
[VAR_VALUE] 0
103.85206770000002 0
[USER] 0
Hi 0
, 0
is 0
there 0
a 0
hawker 0
centre 0
nearby 0
? 0
[USER] 0
Hi 0
, 0
is 0
there 0
a 0
nearby 0
hawker 1
center 0
? 0
[AGENT] 0
Sure, give me a moment. 0
[API] 0
places nearby 0
[API_PARAM_NAME] 0
query 0
'''
output_examples = list()
all_tokens_and_labels = list()
var_name_to_token_index = dict()
var_names_to_tokens = dict()
# Add initial variables
initial_variables = d['initial_variables']['variables'] if isinstance(
d['initial_variables'], dict) else d['initial_variables']
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS['initial_variables'], NOCLICK_LABEL])
for var in initial_variables:
var_names_to_tokens[var['full_name']] = str(var['value'])
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS["var_type"], NOCLICK_LABEL])
all_tokens_and_labels.append(
[remove_underscore(var['full_name']), NOCLICK_LABEL])
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS["var_value"], NOCLICK_LABEL])
# Make token index to relabel correspond to the [VAR_VALUE] token
var_name_to_token_index[var['full_name']] = len(
all_tokens_and_labels) - 1
all_tokens_and_labels.append([var['value'], NOCLICK_LABEL])
for e in d["events"]:
if e['event_type'] == "user_utterance":
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS['user_utterance'], NOCLICK_LABEL])
# For user utterances, do not add user variable names (e.g. u1_2)
# as tokens.
for var in e['variables']:
all_tokens_and_labels.append([var['value'], NOCLICK_LABEL])
var_name_to_token_index[var['full_name']] = len(
all_tokens_and_labels) - 1
var_names_to_tokens[var['full_name']] = var['value']
elif e['event_type'] == "agent_utterance":
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS['agent_utterance'], NOCLICK_LABEL])
all_tokens_and_labels.append([e['utterance'], NOCLICK_LABEL])
elif e['event_type'] == "api_call":
# First, COPY all tokens and labels,
# and output an example if the endpoint and input parameter match.
if e['endpoint'] in api_endpoints:
found_matching_param = False
gold_params = None
gold_value = "__DUMMY__"
copy_all_tokens_and_labels = deepcopy(all_tokens_and_labels)
# Append something like:
# [API] 0
# find_place 0
copy_all_tokens_and_labels.extend([
[SPECIAL_SEPARATORS['api_call'], NOCLICK_LABEL],
[remove_underscore(e['endpoint']), NOCLICK_LABEL]
])
# Append something like:
# [API_PARAM_NAME] 0
# query 0
# OR if not target param
# [API_PARAM_NAME] 0
# src latitude 0
# [API_PARAM_VALUE]
# -118.71 0
for p in e['params']:
copy_all_tokens_and_labels.append(
[SPECIAL_SEPARATORS["api_param_name"], NOCLICK_LABEL])
copy_all_tokens_and_labels.append(
[remove_underscore(p["param"]), NOCLICK_LABEL])
if p["param"] == param_name:
found_matching_param = True
if not do_predict:
gold_params = p['variable_name']
gold_value = p['value']
break
copy_all_tokens_and_labels.append(
[SPECIAL_SEPARATORS["api_param_value"], NOCLICK_LABEL])
copy_all_tokens_and_labels.append(
[p["value"], NOCLICK_LABEL])
if found_matching_param:
if not do_predict:
# If we found our target API and parameter, re-label their NER NOCLICK tags with CLICK tags,
# and write the example to file.
assert gold_params is not None
gold_params = split_utterance_var(gold_params)
for var in gold_params:
index = var_name_to_token_index[var]
copy_all_tokens_and_labels[index][1] = CLICK_LABEL
new_example = [
"%s%s:::::%s" %
(DOCSTART, dialog_id, gold_value)]
for token, label in copy_all_tokens_and_labels:
new_example.append(str(token) + " " + label)
output_examples.append(new_example)
# Unrelated to gold-params, add all API stuff
# Append something like:
# [API] 0
# find_place 0
# [API_PARAM_NAME] 0
# query 0
# [API_PARAM_NAME] 0
# src latitude 0
# [API_PARAM_VALUE]
# -118.71 0
# ...
all_tokens_and_labels.extend([
[SPECIAL_SEPARATORS['api_call'], NOCLICK_LABEL],
[remove_underscore(e['endpoint']), NOCLICK_LABEL]
])
for p in e['params']:
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS["api_param_name"], NOCLICK_LABEL])
all_tokens_and_labels.append([p["param"], NOCLICK_LABEL])
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS["api_param_value"], NOCLICK_LABEL])
all_tokens_and_labels.append([p["value"], NOCLICK_LABEL])
# Append api's returned variables in something like
# [VAR_TYPE] address
# [VAR_VALUE] 1234 5th street
# ....
# Also index variable tokens and lines by full name
returned_variables = list()
for v in e['variables']:
recursive_var_search(v, returned_variables)
for full_name, name, value in returned_variables:
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS["var_type"], NOCLICK_LABEL])
all_tokens_and_labels.append([name, NOCLICK_LABEL])
all_tokens_and_labels.append(
[SPECIAL_SEPARATORS["var_value"], NOCLICK_LABEL])
# Make token index to relabel correspond to the [VAR_VALUE]
# token
var_name_to_token_index[full_name] = len(
all_tokens_and_labels) - 1
all_tokens_and_labels.append([value, NOCLICK_LABEL])
var_names_to_tokens[full_name] = value
return output_examples |
Python | def find_latlon(self, query, latlon):
'''Just get the latitude and longitude of a place
and some administrative details to make sure it's the right one.
(Venice, CA, USA vs Venice, Italy)
'''
api_res = self.gmaps.find_place(
input=query,
input_type='textquery',
fields=[
'formatted_address',
'name',
'geometry',
'place_id'],
location_bias="point:" +
latlon)
if api_res['status'] == 'ZERO_RESULTS':
return []
v = []
place = api_res['candidates'][0]
add_variable_if_exists(v, place, 'name', ('name',))
add_variable_if_exists(v, place, 'name', ('formatted_address',))
v.append({
'name': 'latlon',
'value': str(place['geometry']['location']['lat']) + ',' + str(place['geometry']['location']['lng']),
})
place_id = place['place_id']
# do a place_details call to get a more concise version of the address
api_res = self.gmaps.place(
place_id=place_id,
fields=['address_component'])
place = api_res['result']
for component in place['address_components']:
if 'political' in component['types']:
v.append({
'name': ' '.join(component for component in component['types'] if component != 'political'),
'value': component['long_name'],
})
return v | def find_latlon(self, query, latlon):
'''Just get the latitude and longitude of a place
and some administrative details to make sure it's the right one.
(Venice, CA, USA vs Venice, Italy)
'''
api_res = self.gmaps.find_place(
input=query,
input_type='textquery',
fields=[
'formatted_address',
'name',
'geometry',
'place_id'],
location_bias="point:" +
latlon)
if api_res['status'] == 'ZERO_RESULTS':
return []
v = []
place = api_res['candidates'][0]
add_variable_if_exists(v, place, 'name', ('name',))
add_variable_if_exists(v, place, 'name', ('formatted_address',))
v.append({
'name': 'latlon',
'value': str(place['geometry']['location']['lat']) + ',' + str(place['geometry']['location']['lng']),
})
place_id = place['place_id']
# do a place_details call to get a more concise version of the address
api_res = self.gmaps.place(
place_id=place_id,
fields=['address_component'])
place = api_res['result']
for component in place['address_components']:
if 'political' in component['types']:
v.append({
'name': ' '.join(component for component in component['types'] if component != 'political'),
'value': component['long_name'],
})
return v |
Python | def _execute_command(self, command):
''' Executes a complete template command and returns the reward and user message '''
message = []
reward = 0
action, params = command[0], command[1:]
if action in self.domain.user_templates_list:
message = {
'body': action.format(*[p['value'] for p in params]),
'template': action,
'variables': []
}
self.room.agent.state.passenger_partial_command = []
else:
assert False, "Invalid action: '%s'" % action
# self.dones = {'__all__': self.state.is_done()}
return reward, message | def _execute_command(self, command):
''' Executes a complete template command and returns the reward and user message '''
message = []
reward = 0
action, params = command[0], command[1:]
if action in self.domain.user_templates_list:
message = {
'body': action.format(*[p['value'] for p in params]),
'template': action,
'variables': []
}
self.room.agent.state.passenger_partial_command = []
else:
assert False, "Invalid action: '%s'" % action
# self.dones = {'__all__': self.state.is_done()}
return reward, message |
Python | def _get_valid_actions_mask(self):
'''
Return indicator mask of valid actions
'''
mask = [0] * len(self.user_shared_state["action_space_partitions"])
assert len(mask) == self.room.agent.state.passenger_max_actions, \
"%d != %d" % (len(mask) == len(self.room.agent.state.passenger_max_actions))
empty_command = len(self.room.agent.state.passenger_partial_command) == 0
for index, action_type_and_sub_index in self.user_shared_state["action_space_partitions"].items():
action_type, sub_index = action_type_and_sub_index
if (action_type == ActionType.TEMPLATE and empty_command) or \
(action_type == ActionType.VARIABLE and not empty_command and \
sub_index < len(self.room.agent.state.passenger_variables)):
# TODO ADD (action_type == ActionType.NO_ACTION and empty_command) or \
mask[index] = 1
return mask | def _get_valid_actions_mask(self):
'''
Return indicator mask of valid actions
'''
mask = [0] * len(self.user_shared_state["action_space_partitions"])
assert len(mask) == self.room.agent.state.passenger_max_actions, \
"%d != %d" % (len(mask) == len(self.room.agent.state.passenger_max_actions))
empty_command = len(self.room.agent.state.passenger_partial_command) == 0
for index, action_type_and_sub_index in self.user_shared_state["action_space_partitions"].items():
action_type, sub_index = action_type_and_sub_index
if (action_type == ActionType.TEMPLATE and empty_command) or \
(action_type == ActionType.VARIABLE and not empty_command and \
sub_index < len(self.room.agent.state.passenger_variables)):
# TODO ADD (action_type == ActionType.NO_ACTION and empty_command) or \
mask[index] = 1
return mask |
Python | def init_policy_server(config):
''' Start the policy serve r that receives (state, action, reward) batches
and computes gradients for RL '''
# By default, Ray will parallelize its workload. However, if you need to debug your Ray program,
# it may be easier to do everything on a single process. You can force all Ray functions to occur
# on a single process with local_mode=True.
memory_limit = 1024 * 1024 * 1024 * 10 # GB
ray.init(local_mode=config["debug_mode"], object_store_memory=memory_limit)
trainer_config = config["trainer_config"]
assert torch.cuda.device_count() >= trainer_config["num_gpus"]
trainer_config["input"] = lambda ioctx: PolicyServerInput(ioctx, config["policy_server_host"], int(config["policy_server_port"]))
custom_model = config.get("custom_model", None)
if custom_model:
register_custom_model(custom_model)
trainer_config["model"]["custom_model"] = custom_model
agent_obs_space, agent_action_space = \
make_observation_space_and_action_space(config, True)
if config["multiagent"]:
user_obs_space, user_action_space = \
make_observation_space_and_action_space(config, False)
trainer_config["multiagent"] = {
"policies": {
# the first tuple value is None -> uses default policy
"agent": (None, agent_obs_space, agent_action_space, {}),
"user": (None, user_obs_space, user_action_space, {})
},
"policy_mapping_fn": lambda agent_id: agent_id
}
from ray.rllib.examples.env.random_env import RandomMultiAgentEnv
# Create a fake env for the server. This env will never be used (neither
# for sampling, nor for evaluation) and its obs/action Spaces do not
# matter either (multi-agent config above defines Spaces per Policy).
register_env("custom_env", lambda c: RandomMultiAgentEnv(c))
else:
def custom_env(env_config):
''' Create an env stub for policy training. Only the
action_space and observation_space attributes need to be defined,
no other env functions are needed (e.g. step(), reset(), etc). '''
env = gym.Env()
env.action_space = agent_action_space
env.observation_space = agent_obs_space
return env
register_env("custom_env", custom_env)
trainer = SUPPORTED_TRAINER_CLASSES[config["trainer_class"]](
env="custom_env", config=trainer_config)
os.makedirs(config["model_checkpoint_dir"], exist_ok=True)
# Attempt to restore from checkpoint if possible.
latest_checkpoint = os.path.join(
config["model_checkpoint_dir"], "latest_ckpt")
if os.path.exists(latest_checkpoint):
latest_checkpoint = open(latest_checkpoint).read()
print("Restoring from checkpoint", latest_checkpoint)
trainer.restore(latest_checkpoint)
# Serving and training loop
print("######## Training loop begins... ########")
count = 0
while True:
train_log = trainer.train()
# print(pretty_print(train_log))
count += 1
if count % config["checkpoint_freq"] == 0:
checkpoint = trainer.save()
print("#### Writing checkpoint for train iteration", count, "####")
with open(latest_checkpoint, "w") as f:
f.write(checkpoint) | def init_policy_server(config):
''' Start the policy serve r that receives (state, action, reward) batches
and computes gradients for RL '''
# By default, Ray will parallelize its workload. However, if you need to debug your Ray program,
# it may be easier to do everything on a single process. You can force all Ray functions to occur
# on a single process with local_mode=True.
memory_limit = 1024 * 1024 * 1024 * 10 # GB
ray.init(local_mode=config["debug_mode"], object_store_memory=memory_limit)
trainer_config = config["trainer_config"]
assert torch.cuda.device_count() >= trainer_config["num_gpus"]
trainer_config["input"] = lambda ioctx: PolicyServerInput(ioctx, config["policy_server_host"], int(config["policy_server_port"]))
custom_model = config.get("custom_model", None)
if custom_model:
register_custom_model(custom_model)
trainer_config["model"]["custom_model"] = custom_model
agent_obs_space, agent_action_space = \
make_observation_space_and_action_space(config, True)
if config["multiagent"]:
user_obs_space, user_action_space = \
make_observation_space_and_action_space(config, False)
trainer_config["multiagent"] = {
"policies": {
# the first tuple value is None -> uses default policy
"agent": (None, agent_obs_space, agent_action_space, {}),
"user": (None, user_obs_space, user_action_space, {})
},
"policy_mapping_fn": lambda agent_id: agent_id
}
from ray.rllib.examples.env.random_env import RandomMultiAgentEnv
# Create a fake env for the server. This env will never be used (neither
# for sampling, nor for evaluation) and its obs/action Spaces do not
# matter either (multi-agent config above defines Spaces per Policy).
register_env("custom_env", lambda c: RandomMultiAgentEnv(c))
else:
def custom_env(env_config):
''' Create an env stub for policy training. Only the
action_space and observation_space attributes need to be defined,
no other env functions are needed (e.g. step(), reset(), etc). '''
env = gym.Env()
env.action_space = agent_action_space
env.observation_space = agent_obs_space
return env
register_env("custom_env", custom_env)
trainer = SUPPORTED_TRAINER_CLASSES[config["trainer_class"]](
env="custom_env", config=trainer_config)
os.makedirs(config["model_checkpoint_dir"], exist_ok=True)
# Attempt to restore from checkpoint if possible.
latest_checkpoint = os.path.join(
config["model_checkpoint_dir"], "latest_ckpt")
if os.path.exists(latest_checkpoint):
latest_checkpoint = open(latest_checkpoint).read()
print("Restoring from checkpoint", latest_checkpoint)
trainer.restore(latest_checkpoint)
# Serving and training loop
print("######## Training loop begins... ########")
count = 0
while True:
train_log = trainer.train()
# print(pretty_print(train_log))
count += 1
if count % config["checkpoint_freq"] == 0:
checkpoint = trainer.save()
print("#### Writing checkpoint for train iteration", count, "####")
with open(latest_checkpoint, "w") as f:
f.write(checkpoint) |
Python | def custom_env(env_config):
''' Create an env stub for policy training. Only the
action_space and observation_space attributes need to be defined,
no other env functions are needed (e.g. step(), reset(), etc). '''
env = gym.Env()
env.action_space = agent_action_space
env.observation_space = agent_obs_space
return env | def custom_env(env_config):
''' Create an env stub for policy training. Only the
action_space and observation_space attributes need to be defined,
no other env functions are needed (e.g. step(), reset(), etc). '''
env = gym.Env()
env.action_space = agent_action_space
env.observation_space = agent_obs_space
return env |
Python | def action_space_partitions(domain, max_variables, for_agent):
''' Returns a dictionary that maps an action_index to
an ActionType and its subindex
args:
domain - Domain object from domain.py
max_variables - max number of variables to choose from
for_agent - If set to True, computes action space partitions
for the agent. If False, computes partitions for
the user.
'''
index = 0
partitions = {}
partitions[index] = (ActionType.NO_ACTION, None)
if for_agent:
for i in range(len(domain.api_functions)):
index += 1
partitions[index] = (ActionType.API, i)
index += 1
partitions[index] = (ActionType.END_DIALOG_API, None)
for i in range(len(domain.agent_templates_list if for_agent else \
domain.user_templates_list)):
index += 1
partitions[index] = (ActionType.TEMPLATE, i)
for i in range(max_variables):
index += 1
partitions[index] = (ActionType.VARIABLE, i)
return partitions | def action_space_partitions(domain, max_variables, for_agent):
''' Returns a dictionary that maps an action_index to
an ActionType and its subindex
args:
domain - Domain object from domain.py
max_variables - max number of variables to choose from
for_agent - If set to True, computes action space partitions
for the agent. If False, computes partitions for
the user.
'''
index = 0
partitions = {}
partitions[index] = (ActionType.NO_ACTION, None)
if for_agent:
for i in range(len(domain.api_functions)):
index += 1
partitions[index] = (ActionType.API, i)
index += 1
partitions[index] = (ActionType.END_DIALOG_API, None)
for i in range(len(domain.agent_templates_list if for_agent else \
domain.user_templates_list)):
index += 1
partitions[index] = (ActionType.TEMPLATE, i)
for i in range(max_variables):
index += 1
partitions[index] = (ActionType.VARIABLE, i)
return partitions |
Python | def _query_matches(self, query: str, place: Place) -> bool:
'''Test if query matches place.'''
return (fuzz.partial_ratio(query, place.name.lower()) > 80
or any(fuzz.token_sort_ratio(query, type_) > 80 for type_ in place.types)
) | def _query_matches(self, query: str, place: Place) -> bool:
'''Test if query matches place.'''
return (fuzz.partial_ratio(query, place.name.lower()) > 80
or any(fuzz.token_sort_ratio(query, type_) > 80 for type_ in place.types)
) |
Python | def _place_to_response(p: Place, src_lat: str, src_lng: str):
'''convert a Place, `p`, to the format expected by the api'''
dist = MicroworldMapProvider._dist(src_lat, src_lng, p.lat, p.lng)
if int(p.lat) <= 5 and int(p.lng) <= 5:
city = 'Marina del Rey'
elif int(p.lat) <= 5 and int(p.lng) > 5:
city = 'Santa Monica'
elif int(p.lat) > 5 and int(p.lng) <= 5:
city = 'Culver City'
elif int(p.lat) > 5 and int(p.lng) > 5:
city = 'Sawtelle'
else:
city = 'Los Angeles'
street_names = [
'First',
'Second',
'Third',
'Fourth',
'Fifth',
'Sixth',
'Seventh',
'Eighth',
'Ninth',
'Tenth']
return [
{'name': 'name', 'value': p.name},
{'name': 'address_simple',
'value': street_names[min(len(street_names) - 1, int(p.lng) - 1)] + ' Street'},
{'name': 'latitude', 'value': p.lat},
{'name': 'longitude', 'value': p.lng},
{'name': 'types', 'value': [
{'name': i, 'value': type_} for i, type_ in enumerate(p.types)
]},
{'name': 'rating', 'value': p.rating},
{'name': 'price', 'value': p.price},
{'name': 'distance', 'value': '{} mi'.format(dist)},
{'name': 'duration', 'value': '{} mins'.format(dist)},
{'name': 'neighborhood', 'value': city},
] | def _place_to_response(p: Place, src_lat: str, src_lng: str):
'''convert a Place, `p`, to the format expected by the api'''
dist = MicroworldMapProvider._dist(src_lat, src_lng, p.lat, p.lng)
if int(p.lat) <= 5 and int(p.lng) <= 5:
city = 'Marina del Rey'
elif int(p.lat) <= 5 and int(p.lng) > 5:
city = 'Santa Monica'
elif int(p.lat) > 5 and int(p.lng) <= 5:
city = 'Culver City'
elif int(p.lat) > 5 and int(p.lng) > 5:
city = 'Sawtelle'
else:
city = 'Los Angeles'
street_names = [
'First',
'Second',
'Third',
'Fourth',
'Fifth',
'Sixth',
'Seventh',
'Eighth',
'Ninth',
'Tenth']
return [
{'name': 'name', 'value': p.name},
{'name': 'address_simple',
'value': street_names[min(len(street_names) - 1, int(p.lng) - 1)] + ' Street'},
{'name': 'latitude', 'value': p.lat},
{'name': 'longitude', 'value': p.lng},
{'name': 'types', 'value': [
{'name': i, 'value': type_} for i, type_ in enumerate(p.types)
]},
{'name': 'rating', 'value': p.rating},
{'name': 'price', 'value': p.price},
{'name': 'distance', 'value': '{} mi'.format(dist)},
{'name': 'duration', 'value': '{} mins'.format(dist)},
{'name': 'neighborhood', 'value': city},
] |
Python | def find_place(self, query, latitude, longitude):
'''
Return the place that contains query and is closest to latitude longitude
Google maps does something more complicated to find the best (but not always closest) match
'''
query = query.strip().lower()
matching_places = self.get_matching_places(query)
if matching_places:
closest_place = min(matching_places,
key=lambda place: self._dist(latitude, longitude, place.lat, place.lng))
return self._place_to_response(closest_place, latitude, longitude)
else:
# no matching places
raise ValueError(
'No places could be found matching {}. See {} for a list of places'.format(query, self.places_path)) | def find_place(self, query, latitude, longitude):
'''
Return the place that contains query and is closest to latitude longitude
Google maps does something more complicated to find the best (but not always closest) match
'''
query = query.strip().lower()
matching_places = self.get_matching_places(query)
if matching_places:
closest_place = min(matching_places,
key=lambda place: self._dist(latitude, longitude, place.lat, place.lng))
return self._place_to_response(closest_place, latitude, longitude)
else:
# no matching places
raise ValueError(
'No places could be found matching {}. See {} for a list of places'.format(query, self.places_path)) |
Python | def _place_to_response(p: Place, src_lat: str, src_lng: str):
'''convert a Place, `p`, to the format expected by the api'''
dist = MicroworldMapProvider2._dist(src_lat, src_lng, p.lat, p.lng)
if float(p.lat) <= 5 and float(p.lng) <= 5:
city = 'Marina del Rey'
elif float(p.lat) <= 5 and float(p.lng) > 5:
city = 'Santa Monica'
elif float(p.lat) > 5 and float(p.lng) <= 5:
city = 'Culver City'
elif float(p.lat) > 5 and float(p.lng) > 5:
city = 'Sawtelle'
else:
city = 'Los Angeles'
street_names = [
'First',
'Second',
'Third',
'Fourth',
'Fifth',
'Sixth',
'Seventh',
'Eighth',
'Ninth',
'Tenth']
try:
streetname = street_names[int(p.lng) - 1] + ' Street'
address = p.lat + ' ' + streetname
except ValueError:
streetname = ''
address = ''
result = [
{'name': 'name', 'value': p.name},
{'name': 'address_simple', 'value': address},
{'name': 'streetname', 'value': streetname},
{'name': 'latitude', 'value': p.lat},
{'name': 'longitude', 'value': p.lng},
{'name': 'types', 'value': [
{'name': i, 'value': type_} for i, type_ in enumerate(p.types)
]},
{'name': 'rating', 'value': p.rating},
{'name': 'price', 'value': p.price},
{'name': 'distance', 'value': '{} mi'.format(dist)},
{'name': 'duration', 'value': '{} mins'.format(dist)},
{'name': 'neighborhood', 'value': city},
]
# remove blank values
result = [variable for variable in result if variable['value']]
return result | def _place_to_response(p: Place, src_lat: str, src_lng: str):
'''convert a Place, `p`, to the format expected by the api'''
dist = MicroworldMapProvider2._dist(src_lat, src_lng, p.lat, p.lng)
if float(p.lat) <= 5 and float(p.lng) <= 5:
city = 'Marina del Rey'
elif float(p.lat) <= 5 and float(p.lng) > 5:
city = 'Santa Monica'
elif float(p.lat) > 5 and float(p.lng) <= 5:
city = 'Culver City'
elif float(p.lat) > 5 and float(p.lng) > 5:
city = 'Sawtelle'
else:
city = 'Los Angeles'
street_names = [
'First',
'Second',
'Third',
'Fourth',
'Fifth',
'Sixth',
'Seventh',
'Eighth',
'Ninth',
'Tenth']
try:
streetname = street_names[int(p.lng) - 1] + ' Street'
address = p.lat + ' ' + streetname
except ValueError:
streetname = ''
address = ''
result = [
{'name': 'name', 'value': p.name},
{'name': 'address_simple', 'value': address},
{'name': 'streetname', 'value': streetname},
{'name': 'latitude', 'value': p.lat},
{'name': 'longitude', 'value': p.lng},
{'name': 'types', 'value': [
{'name': i, 'value': type_} for i, type_ in enumerate(p.types)
]},
{'name': 'rating', 'value': p.rating},
{'name': 'price', 'value': p.price},
{'name': 'distance', 'value': '{} mi'.format(dist)},
{'name': 'duration', 'value': '{} mins'.format(dist)},
{'name': 'neighborhood', 'value': city},
]
# remove blank values
result = [variable for variable in result if variable['value']]
return result |
Python | def parse_action(text):
'''
Extract the action from a prediction
'''
text = text[:text.find('[PARAM]')] if '[PARAM]' in text else text
return text[len('[ACTION]'):].strip() | def parse_action(text):
'''
Extract the action from a prediction
'''
text = text[:text.find('[PARAM]')] if '[PARAM]' in text else text
return text[len('[ACTION]'):].strip() |
Python | def parse_params(text):
'''
Extract the parameters from a prediction
'''
return text.partition('[PARAM]')[2].strip().split(
' [PARAM] ') if '[PARAM]' in text else [] | def parse_params(text):
'''
Extract the parameters from a prediction
'''
return text.partition('[PARAM]')[2].strip().split(
' [PARAM] ') if '[PARAM]' in text else [] |
Python | def preprocess_context(context_lines):
'''
Preprocess the context to split on underscores
'''
context_lines = [line.replace('_', ' ') for line in context_lines]
# return new_lines
variable_replaced_lines = []
variable_dict = {}
for line in context_lines:
match = re.match('(.*) = (.*)', line)
if match is not None:
variable_dict[match.group(2)] = match.group(1)
if line.startswith('PREDICT'):
params = parse_params(line.strip())
if 'find place' in line or 'places nearby' in line:
params = params[1:]
for param in params:
line = line.replace(param, variable_dict.get(param, param))
variable_replaced_lines.append(line)
return variable_replaced_lines | def preprocess_context(context_lines):
'''
Preprocess the context to split on underscores
'''
context_lines = [line.replace('_', ' ') for line in context_lines]
# return new_lines
variable_replaced_lines = []
variable_dict = {}
for line in context_lines:
match = re.match('(.*) = (.*)', line)
if match is not None:
variable_dict[match.group(2)] = match.group(1)
if line.startswith('PREDICT'):
params = parse_params(line.strip())
if 'find place' in line or 'places nearby' in line:
params = params[1:]
for param in params:
line = line.replace(param, variable_dict.get(param, param))
variable_replaced_lines.append(line)
return variable_replaced_lines |
Python | def reset(self):
'''
Called before each episode, returns the first observation
'''
if self.num_episodes % 1000 == 0:
logger.warning("completed {} episodes.".format(self.num_episodes))
if self.num_episodes >= self.print_episodes:
logger.warning('episode ' + str(self.num_episodes))
logger.warning('------------')
_, _, history,_ = self.state.get_global_state()
for h in history:
logger.warning(h)
logger.warning('-------------')
self.num_episodes += 1
# select the destination
if self.is_supervised and self.num_episodes < self.supervised_episodes:
a_list = [3, 4]
distribution = [.5, .5]
destination_id = random.choices(a_list, distribution)[0]
else:
destination_id = random.randint(3, len(NanoworldEnv.parameters) - 1)
if self.num_episodes >= self.print_episodes:
logger.warning('set destination: ' + NanoworldEnv.parameters[destination_id])
self.state = DialogStateNano(NanoworldEnv.max_num_actions, desired_destination=NanoworldEnv.parameters[destination_id])
self.obs = {
'passenger': self.state.make_passenger_observation()
}
return self.obs | def reset(self):
'''
Called before each episode, returns the first observation
'''
if self.num_episodes % 1000 == 0:
logger.warning("completed {} episodes.".format(self.num_episodes))
if self.num_episodes >= self.print_episodes:
logger.warning('episode ' + str(self.num_episodes))
logger.warning('------------')
_, _, history,_ = self.state.get_global_state()
for h in history:
logger.warning(h)
logger.warning('-------------')
self.num_episodes += 1
# select the destination
if self.is_supervised and self.num_episodes < self.supervised_episodes:
a_list = [3, 4]
distribution = [.5, .5]
destination_id = random.choices(a_list, distribution)[0]
else:
destination_id = random.randint(3, len(NanoworldEnv.parameters) - 1)
if self.num_episodes >= self.print_episodes:
logger.warning('set destination: ' + NanoworldEnv.parameters[destination_id])
self.state = DialogStateNano(NanoworldEnv.max_num_actions, desired_destination=NanoworldEnv.parameters[destination_id])
self.obs = {
'passenger': self.state.make_passenger_observation()
}
return self.obs |
Python | def step(self, action_dict):
'''
Given an action_dict, compute the next observation, rewards, and dones
'''
# pdb.set_trace()
driver_obs = None
passenger_obs = None
if 'driver' in action_dict:
driver_obs = self.driver_step(action_dict['driver'])
if 'passenger' in action_dict:
passenger_obs = self.passenger_step(action_dict['passenger'])
if self.state.turn == 0:
passenger_obs = self.state.make_passenger_observation()
driver_obs = None
elif self.state.turn == 1:
driver_obs = self.state.make_driver_observation()
passenger_obs = None
self.obs = {}
self.rewards = {}
if passenger_obs:
self.obs['passenger'] = passenger_obs
self.rewards['passenger'] = self.compute_passenger_reward()
if driver_obs:
self.obs['driver'] = driver_obs
self.rewards['driver'] = self.compute_driver_reward()
self.dones = {'__all__': self.state.is_done()}
if self.state.is_done():
self.obs['passenger'] = self.state.make_passenger_observation()
self.rewards['passenger'] = self.compute_passenger_reward()
self.obs['driver'] = self.state.make_driver_observation()
self.rewards['driver'] = self.compute_driver_reward()
self.infos = {}
return self.obs, self.rewards, self.dones, self.infos | def step(self, action_dict):
'''
Given an action_dict, compute the next observation, rewards, and dones
'''
# pdb.set_trace()
driver_obs = None
passenger_obs = None
if 'driver' in action_dict:
driver_obs = self.driver_step(action_dict['driver'])
if 'passenger' in action_dict:
passenger_obs = self.passenger_step(action_dict['passenger'])
if self.state.turn == 0:
passenger_obs = self.state.make_passenger_observation()
driver_obs = None
elif self.state.turn == 1:
driver_obs = self.state.make_driver_observation()
passenger_obs = None
self.obs = {}
self.rewards = {}
if passenger_obs:
self.obs['passenger'] = passenger_obs
self.rewards['passenger'] = self.compute_passenger_reward()
if driver_obs:
self.obs['driver'] = driver_obs
self.rewards['driver'] = self.compute_driver_reward()
self.dones = {'__all__': self.state.is_done()}
if self.state.is_done():
self.obs['passenger'] = self.state.make_passenger_observation()
self.rewards['passenger'] = self.compute_passenger_reward()
self.obs['driver'] = self.state.make_driver_observation()
self.rewards['driver'] = self.compute_driver_reward()
self.infos = {}
return self.obs, self.rewards, self.dones, self.infos |
Python | def _step(self, action_index):
'''
Steps the user one-click forward and sends utterances using templates after all placeholders are filled.
Args:
action_index - index corresponding to the item-to-click (wait-for-agent/template/variable)
Returns:
(reward, message) tuple. Message corresponds to the user message to respond with, it may be None.
'''
self.room.agent.state.steps += 1
reward = 0
message = []
action_type, sub_index = self.user_shared_state["action_space_partitions"][action_index]
reward_function = self.user_shared_state["rl_config"]["rewards"]
if action_type == ActionType.NO_ACTION:
# print("DEBUG User made no action")
message = {
'body': "NO ACTION",
'template': "NO ACTION",
'variables': []
}
return 0, message
elif action_type == ActionType.TEMPLATE:
template = self.domain.user_templates_list[sub_index]
if not self.room.agent.state.passenger_partial_command:
# print("User clicked template: {}".format(template))
self.room.agent.state.passenger_partial_command.append(template)
else:
# print("User tried invalid template click: {}".format(template))
assert False
return reward_function['passenger_invalid_template'], message
elif action_type == ActionType.VARIABLE:
# TODO: Combine utterance variables, as is done in the UI
if self.room.agent.state.passenger_partial_command:
if 0 <= sub_index < len(self.room.agent.state.passenger_variables):
# print("User clicked variable {}".format(sub_index))
variable = self.room.agent.state.passenger_variables[sub_index]
if len(self.room.agent.state.passenger_partial_command) > 0 and \
type(self.room.agent.state.passenger_partial_command[-1]) is dict and \
self.room.agent.state.passenger_partial_command[-1].get('full_name', '').startswith('a') and \
variable.get('full_name', '').startswith('a'):
# Concatenate consecutive user variables
new_user_variable = variable.get('value')
if not new_user_variable.startswith("'"):
new_user_variable = ' ' + new_user_variable
self.room.agent.state.passenger_partial_command[-1]['full_name'] += ' + ' + variable.get('full_name')
self.room.agent.state.passenger_partial_command[-1]['value'] += new_user_variable
else:
self.room.agent.state.passenger_partial_command.append(variable)
else:
# print("User tried invalid variable click: {}".format(sub_index))
return reward_function['passenger_invalid_variable'], message
else:
# print("User tried invalid variable click (no template selected)")
assert False
return reward_function['passenger_invalid_variable'], message
else:
assert False, "Invalid action_type: %s" % str(action_type)
if self._command_complete(self.room.agent.state.passenger_partial_command):
# print("User completing an action: {}".format(self.room.agent.state.passenger_partial_command))
reward, message = self._execute_command(self.room.agent.state.passenger_partial_command)
return reward, message | def _step(self, action_index):
'''
Steps the user one-click forward and sends utterances using templates after all placeholders are filled.
Args:
action_index - index corresponding to the item-to-click (wait-for-agent/template/variable)
Returns:
(reward, message) tuple. Message corresponds to the user message to respond with, it may be None.
'''
self.room.agent.state.steps += 1
reward = 0
message = []
action_type, sub_index = self.user_shared_state["action_space_partitions"][action_index]
reward_function = self.user_shared_state["rl_config"]["rewards"]
if action_type == ActionType.NO_ACTION:
# print("DEBUG User made no action")
message = {
'body': "NO ACTION",
'template': "NO ACTION",
'variables': []
}
return 0, message
elif action_type == ActionType.TEMPLATE:
template = self.domain.user_templates_list[sub_index]
if not self.room.agent.state.passenger_partial_command:
# print("User clicked template: {}".format(template))
self.room.agent.state.passenger_partial_command.append(template)
else:
# print("User tried invalid template click: {}".format(template))
assert False
return reward_function['passenger_invalid_template'], message
elif action_type == ActionType.VARIABLE:
# TODO: Combine utterance variables, as is done in the UI
if self.room.agent.state.passenger_partial_command:
if 0 <= sub_index < len(self.room.agent.state.passenger_variables):
# print("User clicked variable {}".format(sub_index))
variable = self.room.agent.state.passenger_variables[sub_index]
if len(self.room.agent.state.passenger_partial_command) > 0 and \
type(self.room.agent.state.passenger_partial_command[-1]) is dict and \
self.room.agent.state.passenger_partial_command[-1].get('full_name', '').startswith('a') and \
variable.get('full_name', '').startswith('a'):
# Concatenate consecutive user variables
new_user_variable = variable.get('value')
if not new_user_variable.startswith("'"):
new_user_variable = ' ' + new_user_variable
self.room.agent.state.passenger_partial_command[-1]['full_name'] += ' + ' + variable.get('full_name')
self.room.agent.state.passenger_partial_command[-1]['value'] += new_user_variable
else:
self.room.agent.state.passenger_partial_command.append(variable)
else:
# print("User tried invalid variable click: {}".format(sub_index))
return reward_function['passenger_invalid_variable'], message
else:
# print("User tried invalid variable click (no template selected)")
assert False
return reward_function['passenger_invalid_variable'], message
else:
assert False, "Invalid action_type: %s" % str(action_type)
if self._command_complete(self.room.agent.state.passenger_partial_command):
# print("User completing an action: {}".format(self.room.agent.state.passenger_partial_command))
reward, message = self._execute_command(self.room.agent.state.passenger_partial_command)
return reward, message |
Python | def call_api(self, slot_values: list) -> Tuple[dict, list]:
'''Return a 2-tuple: a debugging message, and a list of new variables (None if request is unsuccessful)'''
if self.n_slots != len(slot_values):
raise ValueError('Incorrect number of slot values')
request_params = [
{'param': name, 'variable_name': var['full_name'], 'value': var['value']}
for name, var in zip(self.param_names, slot_values)
]
# Format debug information
formatted_params = ' | '.join('{} = {}'.format(name, var['value']) for name, var in zip(self.param_names, slot_values))
variable_names = [v['full_name'] for v in slot_values]
new_variables = None
# Make API call
try:
response = self.function(request_params)
error_message = load_variable(response['variables'], 'error') # returns None if no error
except Exception as e:
# Catch Python errors
error_message = e
raise
# Error handling
if error_message:
debug_message = {
'body': 'DEBUG: Made an unsuccessful API call to {} with arguments {}. Received the error: {}.'.format(self.endpoint, formatted_params, str(error_message)),
'template': 'DEBUG',
'variables': variable_names,
'sender': 'agent'
}
elif not response:
# Empty responses are considered unsuccessful. This may change in the future,
# so it's better to explicitly throw an error or return an error message
debug_message = {
'body': 'DEBUG: Made an unsuccessful API call to {} with arguments {}. Got an empty response.'.format(self.endpoint, formatted_params),
'template': 'DEBUG',
'variables': variable_names,
'sender': 'agent'
}
else:
# API call was successful
debug_message = {
'body': 'DEBUG: Made a successful API call to {} with arguments {}.'.format(self.endpoint, formatted_params),
'template': 'DEBUG',
'variables': [v['full_name'] for v in slot_values],
'sender': 'agent',
}
new_variables = flatten_variables(response['variables'])
return debug_message, new_variables | def call_api(self, slot_values: list) -> Tuple[dict, list]:
'''Return a 2-tuple: a debugging message, and a list of new variables (None if request is unsuccessful)'''
if self.n_slots != len(slot_values):
raise ValueError('Incorrect number of slot values')
request_params = [
{'param': name, 'variable_name': var['full_name'], 'value': var['value']}
for name, var in zip(self.param_names, slot_values)
]
# Format debug information
formatted_params = ' | '.join('{} = {}'.format(name, var['value']) for name, var in zip(self.param_names, slot_values))
variable_names = [v['full_name'] for v in slot_values]
new_variables = None
# Make API call
try:
response = self.function(request_params)
error_message = load_variable(response['variables'], 'error') # returns None if no error
except Exception as e:
# Catch Python errors
error_message = e
raise
# Error handling
if error_message:
debug_message = {
'body': 'DEBUG: Made an unsuccessful API call to {} with arguments {}. Received the error: {}.'.format(self.endpoint, formatted_params, str(error_message)),
'template': 'DEBUG',
'variables': variable_names,
'sender': 'agent'
}
elif not response:
# Empty responses are considered unsuccessful. This may change in the future,
# so it's better to explicitly throw an error or return an error message
debug_message = {
'body': 'DEBUG: Made an unsuccessful API call to {} with arguments {}. Got an empty response.'.format(self.endpoint, formatted_params),
'template': 'DEBUG',
'variables': variable_names,
'sender': 'agent'
}
else:
# API call was successful
debug_message = {
'body': 'DEBUG: Made a successful API call to {} with arguments {}.'.format(self.endpoint, formatted_params),
'template': 'DEBUG',
'variables': [v['full_name'] for v in slot_values],
'sender': 'agent',
}
new_variables = flatten_variables(response['variables'])
return debug_message, new_variables |
Python | def predict_action(self, message: str, events: list, available_variables: list):
'''
Choose the next action when nothing is selected. Selects a variable container (either a template or API call or wait for user)
Should return an instance of Template or API
'''
raise NotImplementedError | def predict_action(self, message: str, events: list, available_variables: list):
'''
Choose the next action when nothing is selected. Selects a variable container (either a template or API call or wait for user)
Should return an instance of Template or API
'''
raise NotImplementedError |
Python | def fill_template(self, message: str, events: list, template: Template, slot_index: int, available_variables: list, selected_variables: list) -> dict:
'''
Choose the next click when a template is currently selected
Should return an element from available_variables'''
raise NotImplementedError | def fill_template(self, message: str, events: list, template: Template, slot_index: int, available_variables: list, selected_variables: list) -> dict:
'''
Choose the next click when a template is currently selected
Should return an element from available_variables'''
raise NotImplementedError |
Python | def fill_api(self, message: str, events: list, api: API, slot_index: int, available_variables: list, selected_variables: list) -> dict:
'''
Choose the next click when an API is selected
Should return an element from available_variables
'''
raise NotImplementedError | def fill_api(self, message: str, events: list, api: API, slot_index: int, available_variables: list, selected_variables: list) -> dict:
'''
Choose the next click when an API is selected
Should return an element from available_variables
'''
raise NotImplementedError |
Python | def find_latlon(self, request_params, alternate_events=None):
'''find_place, but only returns lat/long'''
query = load_parameter(request_params, "query")
latlon = load_parameter(request_params, "src lat/long")
# find_latlon is currently only supported with google maps
response = self.api_call(self.map_provider.find_latlon, request_params, query, latlon,
alternate_events=alternate_events)
return response | def find_latlon(self, request_params, alternate_events=None):
'''find_place, but only returns lat/long'''
query = load_parameter(request_params, "query")
latlon = load_parameter(request_params, "src lat/long")
# find_latlon is currently only supported with google maps
response = self.api_call(self.map_provider.find_latlon, request_params, query, latlon,
alternate_events=alternate_events)
return response |
Python | def start_driving_no_map(self, request_params, alternate_events=None):
'''Start driving with a text confirmation instead of a map'''
latitude = load_parameter(request_params, "dest latitude")
longitude = load_parameter(request_params, "dest longitude")
# we can't reliably split the variable name into entity and variable type because
# variable names can include v2_0_rating and v1_place_id
destination_name_variable = request_params[0]['variable_name'].replace(
'latitude', 'name')
destination_address_variable = request_params[0]['variable_name'].replace(
'latitude', 'address')
destination_name = self.manager.lookup_variable_by_name(
destination_name_variable)
destination_address = self.manager.lookup_variable_by_name(
destination_address_variable)
request_params.append({
'name': 'confirmationString',
'variable_name': 'confirmationString',
'value': 'The agent selected your destination as {} at {} ({}, {}). Is this correct?'
.format(destination_name, destination_address, latitude, longitude)
})
return self.api_call(self.map_provider.start_driving_no_map, request_params,
latitude, longitude, alternate_events=alternate_events) | def start_driving_no_map(self, request_params, alternate_events=None):
'''Start driving with a text confirmation instead of a map'''
latitude = load_parameter(request_params, "dest latitude")
longitude = load_parameter(request_params, "dest longitude")
# we can't reliably split the variable name into entity and variable type because
# variable names can include v2_0_rating and v1_place_id
destination_name_variable = request_params[0]['variable_name'].replace(
'latitude', 'name')
destination_address_variable = request_params[0]['variable_name'].replace(
'latitude', 'address')
destination_name = self.manager.lookup_variable_by_name(
destination_name_variable)
destination_address = self.manager.lookup_variable_by_name(
destination_address_variable)
request_params.append({
'name': 'confirmationString',
'variable_name': 'confirmationString',
'value': 'The agent selected your destination as {} at {} ({}, {}). Is this correct?'
.format(destination_name, destination_address, latitude, longitude)
})
return self.api_call(self.map_provider.start_driving_no_map, request_params,
latitude, longitude, alternate_events=alternate_events) |
Python | def _step(self, action_index):
'''
Steps the agent one-click forward and executes apis/templates if a full command results from the click.
Args:
action_index - index corresponding to the item-to-click (api/template/variable)
Returns:
(reward, message, ended_dialog) tuple. Message corresponds to the agent message to respond with, it may be None.
'''
self.state.steps += 1
reward = {"agent": 0}
ended_dialog = False
message = []
action_type, sub_index = self.agent_shared_state["action_space_partitions"][action_index]
reward_function = self.agent_shared_state["rl_config"]["rewards"]
if action_type == ActionType.NO_ACTION:
# print("DEBUG Driver made no action")
message = {
'body': "NO ACTION",
'template': "NO ACTION",
'variables': []
}
return {"agent": 0}, message, ended_dialog
elif action_type in (ActionType.API, ActionType.END_DIALOG_API):
api = list(self.domain.api_functions.values())[sub_index] if action_type == ActionType.API \
else self.domain.end_dialog
if not self.state.driver_partial_command:
# print( "Driver clicked API call: {}".format( api['function'].endpoint))
self.state.driver_partial_command.append(
api['function'].endpoint)
else:
# print("Driver tried invalid API click: {}".format(api['function'].endpoint))
assert False
return {"agent": reward_function['driver_invalid_api']}, message, ended_dialog
elif action_type == ActionType.TEMPLATE:
template = self.domain.agent_templates_list[sub_index]
if not self.state.driver_partial_command:
# print("Driver clicked template: {}".format(template))
self.state.driver_partial_command.append(template)
else:
# print("Driver tried invalid template click: {}".format(template))
assert False
return {"agent": reward_function['driver_invalid_template']}, message, ended_dialog
elif action_type == ActionType.VARIABLE:
if self.state.driver_partial_command:
if 0 <= sub_index < len(self.state.driver_variables):
# print("Driver clicked variable {}".format(sub_index))
variable = self.state.driver_variables[sub_index]
if len(self.state.driver_partial_command) > 0 and \
type(self.state.driver_partial_command[-1]) is dict and \
self.state.driver_partial_command[-1].get('full_name', '').startswith('u') and \
variable.get('full_name', '').startswith('u'):
# Concatenate consecutive user variables
new_user_variable = variable.get('value')
if not new_user_variable.startswith("'"):
new_user_variable = ' ' + new_user_variable
self.state.driver_partial_command[-1]['full_name'] += ' + ' + variable.get('full_name')
self.state.driver_partial_command[-1]['value'] += new_user_variable
else:
self.state.driver_partial_command.append(variable)
else:
# print( "Driver tried invalid variable click: {}".format(sub_index))
assert False
return {"agent": reward_function['driver_invalid_variable']}, message, ended_dialog
else:
# print("Driver tried invalid variable click (no action selected)")
assert False
return {"agent": reward_function['driver_invalid_variable']}, message, ended_dialog
else:
assert False, "Invalid action_type: %s" % str(action_type)
if self._command_complete(self.state.driver_partial_command):
print("Driver completed an action: {}".format( self.state.driver_partial_command))
reward, message, ended_dialog = self._execute_command(
self.state.driver_partial_command)
return reward, message, ended_dialog | def _step(self, action_index):
'''
Steps the agent one-click forward and executes apis/templates if a full command results from the click.
Args:
action_index - index corresponding to the item-to-click (api/template/variable)
Returns:
(reward, message, ended_dialog) tuple. Message corresponds to the agent message to respond with, it may be None.
'''
self.state.steps += 1
reward = {"agent": 0}
ended_dialog = False
message = []
action_type, sub_index = self.agent_shared_state["action_space_partitions"][action_index]
reward_function = self.agent_shared_state["rl_config"]["rewards"]
if action_type == ActionType.NO_ACTION:
# print("DEBUG Driver made no action")
message = {
'body': "NO ACTION",
'template': "NO ACTION",
'variables': []
}
return {"agent": 0}, message, ended_dialog
elif action_type in (ActionType.API, ActionType.END_DIALOG_API):
api = list(self.domain.api_functions.values())[sub_index] if action_type == ActionType.API \
else self.domain.end_dialog
if not self.state.driver_partial_command:
# print( "Driver clicked API call: {}".format( api['function'].endpoint))
self.state.driver_partial_command.append(
api['function'].endpoint)
else:
# print("Driver tried invalid API click: {}".format(api['function'].endpoint))
assert False
return {"agent": reward_function['driver_invalid_api']}, message, ended_dialog
elif action_type == ActionType.TEMPLATE:
template = self.domain.agent_templates_list[sub_index]
if not self.state.driver_partial_command:
# print("Driver clicked template: {}".format(template))
self.state.driver_partial_command.append(template)
else:
# print("Driver tried invalid template click: {}".format(template))
assert False
return {"agent": reward_function['driver_invalid_template']}, message, ended_dialog
elif action_type == ActionType.VARIABLE:
if self.state.driver_partial_command:
if 0 <= sub_index < len(self.state.driver_variables):
# print("Driver clicked variable {}".format(sub_index))
variable = self.state.driver_variables[sub_index]
if len(self.state.driver_partial_command) > 0 and \
type(self.state.driver_partial_command[-1]) is dict and \
self.state.driver_partial_command[-1].get('full_name', '').startswith('u') and \
variable.get('full_name', '').startswith('u'):
# Concatenate consecutive user variables
new_user_variable = variable.get('value')
if not new_user_variable.startswith("'"):
new_user_variable = ' ' + new_user_variable
self.state.driver_partial_command[-1]['full_name'] += ' + ' + variable.get('full_name')
self.state.driver_partial_command[-1]['value'] += new_user_variable
else:
self.state.driver_partial_command.append(variable)
else:
# print( "Driver tried invalid variable click: {}".format(sub_index))
assert False
return {"agent": reward_function['driver_invalid_variable']}, message, ended_dialog
else:
# print("Driver tried invalid variable click (no action selected)")
assert False
return {"agent": reward_function['driver_invalid_variable']}, message, ended_dialog
else:
assert False, "Invalid action_type: %s" % str(action_type)
if self._command_complete(self.state.driver_partial_command):
print("Driver completed an action: {}".format( self.state.driver_partial_command))
reward, message, ended_dialog = self._execute_command(
self.state.driver_partial_command)
return reward, message, ended_dialog |
Python | def _execute_command(self, command):
''' Executes a complete API or template command and returns the reward, agent message, and whether
the dialog was ended by an API call or not
'''
message = []
reward = {"agent": 0}
ended_dialog = False
action, params = command[0], command[1:]
api = None
if action == self.domain.end_dialog['function'].endpoint:
api = self.domain.end_dialog
else:
api = self.domain.api_functions.get(action, None)
if api:
response = api["function"](self._format_api_params(api, params))
self.state.driver_partial_command = []
self.state.api_call_count += 1
variables = flatten_variables(response)
if hasattr(api['function'], 'completes_dialog'):
ended_dialog = True
else:
if any('error' in v.get('full_name', 'test') for v in variables) or len(variables) == 0:
# print("API call was an error or empty")
reward["agent"] = self.agent_shared_state["rl_config"]["rewards"]['driver_bad_api_call']
else:
# print("API call got results!")
reward["agent"] = self.agent_shared_state["rl_config"]["rewards"]['driver_good_api_call']
reward["user"] = self.agent_shared_state["rl_config"]["rewards"]['passenger_good_api_call']
elif action in self.domain.agent_templates_list:
message = {
'body': action.format(*[p['value'] for p in params]),
'template': action,
'variables': []
}
self.state.driver_partial_command = []
else:
assert False, "Invalid action: '%s'" % action
# self.dones = {'__all__': self.state.is_done()}
return reward, message, ended_dialog | def _execute_command(self, command):
''' Executes a complete API or template command and returns the reward, agent message, and whether
the dialog was ended by an API call or not
'''
message = []
reward = {"agent": 0}
ended_dialog = False
action, params = command[0], command[1:]
api = None
if action == self.domain.end_dialog['function'].endpoint:
api = self.domain.end_dialog
else:
api = self.domain.api_functions.get(action, None)
if api:
response = api["function"](self._format_api_params(api, params))
self.state.driver_partial_command = []
self.state.api_call_count += 1
variables = flatten_variables(response)
if hasattr(api['function'], 'completes_dialog'):
ended_dialog = True
else:
if any('error' in v.get('full_name', 'test') for v in variables) or len(variables) == 0:
# print("API call was an error or empty")
reward["agent"] = self.agent_shared_state["rl_config"]["rewards"]['driver_bad_api_call']
else:
# print("API call got results!")
reward["agent"] = self.agent_shared_state["rl_config"]["rewards"]['driver_good_api_call']
reward["user"] = self.agent_shared_state["rl_config"]["rewards"]['passenger_good_api_call']
elif action in self.domain.agent_templates_list:
message = {
'body': action.format(*[p['value'] for p in params]),
'template': action,
'variables': []
}
self.state.driver_partial_command = []
else:
assert False, "Invalid action: '%s'" % action
# self.dones = {'__all__': self.state.is_done()}
return reward, message, ended_dialog |
Python | def generate_agent_response(self, api_call):
''' Generate an agent response utterance by calling find_place or places_nearby.
'''
assert api_call in ("places_nearby", "find_place")
api_signature = (api_call, self.query, self.relative_landmark_query)
logging.debug("last_api_signature: {}".format(self.last_api_signature))
logging.debug("new_api_signature: {}".format(api_signature))
if api_signature == self.last_api_signature:
return utils.construct_agent_response(
"Can you be more specific? I couldn't find anything new.", delay=2)
self.dst_list = None
src = self.initial_variables
if self.relative_landmark_query != self.last_api_signature[2]:
self.relative_landmark = self.extract_relative_landmark(
self.initial_variables, self.relative_landmark_query)
logging.debug(
"Setting new relative landmark {} with query: {}".format(
self.relative_landmark,
self.relative_landmark_query))
if self.relative_landmark:
src = {
"latitude": self.relative_landmark.lat,
"longitude": self.relative_landmark.lng
}
self.last_api_signature = api_signature
if not self.query:
return utils.construct_agent_response(
"Can you be more specific? I couldn't find anything.", delay=2)
query_params = utils.construct_query_params(src, self.query)
if api_call == "places_nearby":
api_response = self.map_api_interface.places_nearby(query_params)[
'variables']
else:
api_response = self.map_api_interface.find_place(query_params)[
'variables']
# TODO DEBUG
# logging.debug("API_RESPONSE %s" % json.dumps(api_response, indent=2))
# agent_utt = "[query] %s [end] " % (self.query)
agent_utt = ""
if len(api_response) == 0:
agent_utt += "Search yielded zero results. Can you please state clearly, where you want to go? Thanks!"
self.reset_state()
return utils.construct_agent_response(agent_utt)
if api_call == "places_nearby": # call find_place
self.dst_list = [Destination(response['value'])
for response in api_response]
if len(self.dst_list) == 1:
self.dst = self.dst_list[0]
self.dst_list = None
agent_utt += "My search only yielded one result. " + \
utils.gen_agent_utt_for_single_dst(
self.dst, self.relative_landmark)
else:
dest_names = [d.name for d in self.dst_list]
for i, name in enumerate(dest_names):
# if dest_names.count(name) > 1:
dest = self.dst_list[i]
if dest.st:
dest_names[i] = "%s on %s" % (name, dest.st)
else:
dest_names[i] = "%s located at %s" % (name, dest.addr)
assert len(self.dst_list) > 1, len(self.dst_list)
agent_utt += "I found these places: %s. " % (
', '.join("[%d] %s" % (i + 1, name) for i, name in enumerate(dest_names)))
agent_utt += "They are %s away respectively" % (
', '.join(d.drive_time for d in self.dst_list))
if self.relative_landmark:
agent_utt += " from %s. " % (self.relative_landmark.name)
else:
agent_utt += ". "
agent_utt += "Is it one of those? "
else: # called find_place
self.dst = Destination(api_response)
agent_utt += utils.gen_agent_utt_for_single_dst(
self.dst, self.relative_landmark)
return utils.construct_agent_response(agent_utt) | def generate_agent_response(self, api_call):
''' Generate an agent response utterance by calling find_place or places_nearby.
'''
assert api_call in ("places_nearby", "find_place")
api_signature = (api_call, self.query, self.relative_landmark_query)
logging.debug("last_api_signature: {}".format(self.last_api_signature))
logging.debug("new_api_signature: {}".format(api_signature))
if api_signature == self.last_api_signature:
return utils.construct_agent_response(
"Can you be more specific? I couldn't find anything new.", delay=2)
self.dst_list = None
src = self.initial_variables
if self.relative_landmark_query != self.last_api_signature[2]:
self.relative_landmark = self.extract_relative_landmark(
self.initial_variables, self.relative_landmark_query)
logging.debug(
"Setting new relative landmark {} with query: {}".format(
self.relative_landmark,
self.relative_landmark_query))
if self.relative_landmark:
src = {
"latitude": self.relative_landmark.lat,
"longitude": self.relative_landmark.lng
}
self.last_api_signature = api_signature
if not self.query:
return utils.construct_agent_response(
"Can you be more specific? I couldn't find anything.", delay=2)
query_params = utils.construct_query_params(src, self.query)
if api_call == "places_nearby":
api_response = self.map_api_interface.places_nearby(query_params)[
'variables']
else:
api_response = self.map_api_interface.find_place(query_params)[
'variables']
# TODO DEBUG
# logging.debug("API_RESPONSE %s" % json.dumps(api_response, indent=2))
# agent_utt = "[query] %s [end] " % (self.query)
agent_utt = ""
if len(api_response) == 0:
agent_utt += "Search yielded zero results. Can you please state clearly, where you want to go? Thanks!"
self.reset_state()
return utils.construct_agent_response(agent_utt)
if api_call == "places_nearby": # call find_place
self.dst_list = [Destination(response['value'])
for response in api_response]
if len(self.dst_list) == 1:
self.dst = self.dst_list[0]
self.dst_list = None
agent_utt += "My search only yielded one result. " + \
utils.gen_agent_utt_for_single_dst(
self.dst, self.relative_landmark)
else:
dest_names = [d.name for d in self.dst_list]
for i, name in enumerate(dest_names):
# if dest_names.count(name) > 1:
dest = self.dst_list[i]
if dest.st:
dest_names[i] = "%s on %s" % (name, dest.st)
else:
dest_names[i] = "%s located at %s" % (name, dest.addr)
assert len(self.dst_list) > 1, len(self.dst_list)
agent_utt += "I found these places: %s. " % (
', '.join("[%d] %s" % (i + 1, name) for i, name in enumerate(dest_names)))
agent_utt += "They are %s away respectively" % (
', '.join(d.drive_time for d in self.dst_list))
if self.relative_landmark:
agent_utt += " from %s. " % (self.relative_landmark.name)
else:
agent_utt += ". "
agent_utt += "Is it one of those? "
else: # called find_place
self.dst = Destination(api_response)
agent_utt += utils.gen_agent_utt_for_single_dst(
self.dst, self.relative_landmark)
return utils.construct_agent_response(agent_utt) |
Python | def most_frequent(fc_range, key):
'''return the most frequent value of fc_range[i][key] for all i'''
c = Counter(
block[key] for block in fc_range if hasattr(
block, key)).most_common(1)
if c:
return c[0][0]
else:
return None | def most_frequent(fc_range, key):
'''return the most frequent value of fc_range[i][key] for all i'''
c = Counter(
block[key] for block in fc_range if hasattr(
block, key)).most_common(1)
if c:
return c[0][0]
else:
return None |
Python | def weather_at_time(self, lat, lon, time_query):
'''
Fetch the weather at a specified location and time (between now and 7 days from now).
The future limit is because Darksky's forecast only extends that far.
It doesn't support times in the past because 1) it's not a common use case, and 2) implementing it for ranges of >1 day (e.g. last week) would require making multiple requests and more code
If desired, look at the time='whatever' parameter in darkskylib
lat, lon - floats
time_query - a string with a relative time. Something like 'tonight at 8' is fine
note: you should ensure that wit.ai app's timezone is set to GMT
darksky returns forecasts in local times without a timezone
'''
# find date/time with wit.ai and duckling
response = self.wit_client.message(time_query)['entities']
if not response['datetime']:
raise ValueError('could not parse time, <{}>'.format(time_query))
else:
# assume that time_query only contains one datetime object, but
# duckling is pretty good about handling ranges
time_instance = response['datetime'][0]
# parse a wit.ai datetime object, which should look like:
# {
# 'type': 'value',
# 'grain': 'second' | minute' | 'hour' | 'day' | 'week' | 'year'
# 'value': '2020-01-01T12:30:00.000+00:00'
# }
# OR an interval containing a start and end that each look like the
# above
is_interval = False
if time_instance['type'] == 'interval':
# for queries like "this weekend", the result will be a range.
# just use the start time.
start_dt = datetime.strptime(
time_instance['from']['value'],
"%Y-%m-%dT%H:%M:%S.%f+00:00")
end_dt = datetime.strptime(
time_instance['to']['value'],
"%Y-%m-%dT%H:%M:%S.%f+00:00")
grain = time_instance['from']['grain']
is_interval = True
elif time_instance['type'] == 'value':
start_dt = datetime.strptime(
time_instance['value'],
"%Y-%m-%dT%H:%M:%S.%f+00:00")
grain = time_instance['grain']
if grain == 'week':
end_dt = start_dt + timedelta(days=7)
is_interval = True
else:
raise Exception('unrecognized type', time_instance['type'])
# Get the full forecast that corresponds to the time granularity
fc = forecast(self.darksky_key, lat, lon, extend='hourly')
if grain == 'second' or grain == 'minute':
try:
# minutely forecasts are only available in some parts of the
# world. test if they work
fc_range = fc.minutely
# they also don't always include temperature, so test this too
_temperature_test = fc.minutely[0].temperature
except AttributeError:
fc_range = fc.hourly
grain = 'hour'
elif grain == 'hour':
fc_range = fc.hourly
elif grain == 'day' or grain == 'week' or grain == 'month' or grain == 'year':
fc_range = fc.daily
try:
summary = fc_range.summary
except AttributeError:
summary = fc_range[0].summary
# if we parsed an interval, create an aggregate forecast
if is_interval:
# trim the ends of the range. note: darksky only provides hourly
# forecasts for the next 48 hours, and daily forecasts for the next
# week
fc_filtered_range = [block for block in fc_range if start_dt.timestamp(
) <= block.time <= end_dt.timestamp()]
aggregate_fc = self.aggregate_forecast(fc_filtered_range)
transformed_forecast = self.transform_forecast(aggregate_fc)
return transformed_forecast + [
{'name': 'summary', 'value': summary},
{'name': 'start_date',
'value': start_dt.strftime('%a, %b %d')},
{'name': 'start_time', 'value': start_dt.strftime('%H:%M')},
{'name': 'end_date', 'value': end_dt.strftime('%a, %b %d')},
{'name': 'end_time', 'value': end_dt.strftime('%H:%M')},
{'name': 'grain', 'value': grain},
]
else:
# return the forecast for that time
transformed_forecast = self.transform_forecast(fc.currently)
return transformed_forecast + [
{'name': 'summary', 'value': summary},
{'name': 'date', 'value': start_dt.strftime('%a, %b %d')},
{'name': 'time', 'value': start_dt.strftime('%H:%M')},
{'name': 'grain', 'value': grain},
]
return timestamp | def weather_at_time(self, lat, lon, time_query):
'''
Fetch the weather at a specified location and time (between now and 7 days from now).
The future limit is because Darksky's forecast only extends that far.
It doesn't support times in the past because 1) it's not a common use case, and 2) implementing it for ranges of >1 day (e.g. last week) would require making multiple requests and more code
If desired, look at the time='whatever' parameter in darkskylib
lat, lon - floats
time_query - a string with a relative time. Something like 'tonight at 8' is fine
note: you should ensure that wit.ai app's timezone is set to GMT
darksky returns forecasts in local times without a timezone
'''
# find date/time with wit.ai and duckling
response = self.wit_client.message(time_query)['entities']
if not response['datetime']:
raise ValueError('could not parse time, <{}>'.format(time_query))
else:
# assume that time_query only contains one datetime object, but
# duckling is pretty good about handling ranges
time_instance = response['datetime'][0]
# parse a wit.ai datetime object, which should look like:
# {
# 'type': 'value',
# 'grain': 'second' | minute' | 'hour' | 'day' | 'week' | 'year'
# 'value': '2020-01-01T12:30:00.000+00:00'
# }
# OR an interval containing a start and end that each look like the
# above
is_interval = False
if time_instance['type'] == 'interval':
# for queries like "this weekend", the result will be a range.
# just use the start time.
start_dt = datetime.strptime(
time_instance['from']['value'],
"%Y-%m-%dT%H:%M:%S.%f+00:00")
end_dt = datetime.strptime(
time_instance['to']['value'],
"%Y-%m-%dT%H:%M:%S.%f+00:00")
grain = time_instance['from']['grain']
is_interval = True
elif time_instance['type'] == 'value':
start_dt = datetime.strptime(
time_instance['value'],
"%Y-%m-%dT%H:%M:%S.%f+00:00")
grain = time_instance['grain']
if grain == 'week':
end_dt = start_dt + timedelta(days=7)
is_interval = True
else:
raise Exception('unrecognized type', time_instance['type'])
# Get the full forecast that corresponds to the time granularity
fc = forecast(self.darksky_key, lat, lon, extend='hourly')
if grain == 'second' or grain == 'minute':
try:
# minutely forecasts are only available in some parts of the
# world. test if they work
fc_range = fc.minutely
# they also don't always include temperature, so test this too
_temperature_test = fc.minutely[0].temperature
except AttributeError:
fc_range = fc.hourly
grain = 'hour'
elif grain == 'hour':
fc_range = fc.hourly
elif grain == 'day' or grain == 'week' or grain == 'month' or grain == 'year':
fc_range = fc.daily
try:
summary = fc_range.summary
except AttributeError:
summary = fc_range[0].summary
# if we parsed an interval, create an aggregate forecast
if is_interval:
# trim the ends of the range. note: darksky only provides hourly
# forecasts for the next 48 hours, and daily forecasts for the next
# week
fc_filtered_range = [block for block in fc_range if start_dt.timestamp(
) <= block.time <= end_dt.timestamp()]
aggregate_fc = self.aggregate_forecast(fc_filtered_range)
transformed_forecast = self.transform_forecast(aggregate_fc)
return transformed_forecast + [
{'name': 'summary', 'value': summary},
{'name': 'start_date',
'value': start_dt.strftime('%a, %b %d')},
{'name': 'start_time', 'value': start_dt.strftime('%H:%M')},
{'name': 'end_date', 'value': end_dt.strftime('%a, %b %d')},
{'name': 'end_time', 'value': end_dt.strftime('%H:%M')},
{'name': 'grain', 'value': grain},
]
else:
# return the forecast for that time
transformed_forecast = self.transform_forecast(fc.currently)
return transformed_forecast + [
{'name': 'summary', 'value': summary},
{'name': 'date', 'value': start_dt.strftime('%a, %b %d')},
{'name': 'time', 'value': start_dt.strftime('%H:%M')},
{'name': 'grain', 'value': grain},
]
return timestamp |
Python | def initialize(self):
'''Reset the message interface. This is also called when restarting a dialog'''
self.messages = []
self.user_utterance_variables = []
self.user_utterance_variables_without_full_names = []
self.user_utterance_number = 0
self.emit_fn('/history/user_utterance_variables',
self.user_utterance_variables_without_full_names)
self.agent_utterance_variables = []
self.agent_utterance_variables_without_full_names = []
self.agent_utterance_number = 0
self.emit_fn('/history/agent_utterance_variables',
self.agent_utterance_variables_without_full_names)
self.emit_fn('/history/messages', self.messages)
initial_message = copy.deepcopy(
self.initial_message) if isinstance(self.agent, HumanAgent) else self.agent.initial_message()
self.handle_message(copy.deepcopy(initial_message)) | def initialize(self):
'''Reset the message interface. This is also called when restarting a dialog'''
self.messages = []
self.user_utterance_variables = []
self.user_utterance_variables_without_full_names = []
self.user_utterance_number = 0
self.emit_fn('/history/user_utterance_variables',
self.user_utterance_variables_without_full_names)
self.agent_utterance_variables = []
self.agent_utterance_variables_without_full_names = []
self.agent_utterance_number = 0
self.emit_fn('/history/agent_utterance_variables',
self.agent_utterance_variables_without_full_names)
self.emit_fn('/history/messages', self.messages)
initial_message = copy.deepcopy(
self.initial_message) if isinstance(self.agent, HumanAgent) else self.agent.initial_message()
self.handle_message(copy.deepcopy(initial_message)) |
Python | def clean_words(words):
'''
args:
words - list of word tokens
returns:
list of words lowercased and with non-alphanumeric characters removed.
'''
return ["".join(c for c in word.lower() if c.isalnum()) for word in words] | def clean_words(words):
'''
args:
words - list of word tokens
returns:
list of words lowercased and with non-alphanumeric characters removed.
'''
return ["".join(c for c in word.lower() if c.isalnum()) for word in words] |
Python | def find_longest_match_indicator(cleaned_word_tokens, indicator_map):
'''
Finds the longest match indicator, STARTING from the first token,
e.g. if first token doesn't match, no matches will be returned.
args:
cleaned_word_tokens - list that is lowercased with all all non-alphanumeric characters removed.
returns:
The longest match in the form of a list of word tokens.
If no match was found, returns None
'''
first_word = cleaned_word_tokens[0]
other_words = cleaned_word_tokens[1:] if len(
cleaned_word_tokens) > 1 else []
longest_matching_suffix = None
if first_word in indicator_map:
suffixes = indicator_map[first_word]
assert suffixes
for suffix in suffixes:
if len(other_words) < len(suffix):
continue
if longest_matching_suffix is None or len(
suffix) > len(longest_matching_suffix):
clean_suffix = other_words[:len(suffix)]
if clean_suffix == suffix:
longest_matching_suffix = suffix
output = None if longest_matching_suffix is None else [
first_word] + longest_matching_suffix
if output:
logging.debug("Found indicator: {}".format(output))
return output | def find_longest_match_indicator(cleaned_word_tokens, indicator_map):
'''
Finds the longest match indicator, STARTING from the first token,
e.g. if first token doesn't match, no matches will be returned.
args:
cleaned_word_tokens - list that is lowercased with all all non-alphanumeric characters removed.
returns:
The longest match in the form of a list of word tokens.
If no match was found, returns None
'''
first_word = cleaned_word_tokens[0]
other_words = cleaned_word_tokens[1:] if len(
cleaned_word_tokens) > 1 else []
longest_matching_suffix = None
if first_word in indicator_map:
suffixes = indicator_map[first_word]
assert suffixes
for suffix in suffixes:
if len(other_words) < len(suffix):
continue
if longest_matching_suffix is None or len(
suffix) > len(longest_matching_suffix):
clean_suffix = other_words[:len(suffix)]
if clean_suffix == suffix:
longest_matching_suffix = suffix
output = None if longest_matching_suffix is None else [
first_word] + longest_matching_suffix
if output:
logging.debug("Found indicator: {}".format(output))
return output |
Python | def reset(self):
'''
Called before each episode, returns the first observation
'''
if self.num_epidodes % 1000 == 0:
logger.warning("completed {} episodes.".format(self.num_epidodes))
if self.num_epidodes >= 10000:
logger.warning('episode ' + str(self.num_epidodes))
logger.warning('------------')
_, _, history, _ = self.state.get_global_state()
for h in history:
logger.warning(h)
logger.warning('-------------')
self.num_epidodes += 1
destination_id = random.randint(1, 2)
if self.num_epidodes >= 10000:
logger.warning(
'set destination: ' +
NanoworldEnv.destination[destination_id])
self.state = DialogStateNano(
NanoworldEnv.max_num_actions,
desired_destination=NanoworldEnv.destination[destination_id])
self.obs = {
'driver': self.state.make_driver_observation(),
'passenger': self.state.make_passenger_observation()
}
return self.obs | def reset(self):
'''
Called before each episode, returns the first observation
'''
if self.num_epidodes % 1000 == 0:
logger.warning("completed {} episodes.".format(self.num_epidodes))
if self.num_epidodes >= 10000:
logger.warning('episode ' + str(self.num_epidodes))
logger.warning('------------')
_, _, history, _ = self.state.get_global_state()
for h in history:
logger.warning(h)
logger.warning('-------------')
self.num_epidodes += 1
destination_id = random.randint(1, 2)
if self.num_epidodes >= 10000:
logger.warning(
'set destination: ' +
NanoworldEnv.destination[destination_id])
self.state = DialogStateNano(
NanoworldEnv.max_num_actions,
desired_destination=NanoworldEnv.destination[destination_id])
self.obs = {
'driver': self.state.make_driver_observation(),
'passenger': self.state.make_passenger_observation()
}
return self.obs |
Python | def step(self, action_dict):
'''
Given an action_dict, compute the next observation, rewards, and dones
'''
if 'driver' in action_dict:
driver_obs = self.driver_step(action_dict['driver'])
if self.state.is_done():
driver_reward = self.compute_driver_reward()
return {'driver': driver_obs, 'passenger': self.state.make_passenger_observation()}, \
{'driver': driver_reward, 'passenger': self.compute_passenger_reward()}, \
{'__all__': self.state.is_done()}, {}
if 'passenger' in action_dict:
passenger_obs = self.passenger_step(action_dict['passenger'])
self.obs = {
'driver': driver_obs,
'passenger': passenger_obs
}
self.rewards = {
'driver': self.compute_driver_reward(),
'passenger': self.compute_passenger_reward()
}
self.dones = {'__all__': self.state.is_done()}
self.infos = {}
return self.obs, self.rewards, self.dones, self.infos | def step(self, action_dict):
'''
Given an action_dict, compute the next observation, rewards, and dones
'''
if 'driver' in action_dict:
driver_obs = self.driver_step(action_dict['driver'])
if self.state.is_done():
driver_reward = self.compute_driver_reward()
return {'driver': driver_obs, 'passenger': self.state.make_passenger_observation()}, \
{'driver': driver_reward, 'passenger': self.compute_passenger_reward()}, \
{'__all__': self.state.is_done()}, {}
if 'passenger' in action_dict:
passenger_obs = self.passenger_step(action_dict['passenger'])
self.obs = {
'driver': driver_obs,
'passenger': passenger_obs
}
self.rewards = {
'driver': self.compute_driver_reward(),
'passenger': self.compute_passenger_reward()
}
self.dones = {'__all__': self.state.is_done()}
self.infos = {}
return self.obs, self.rewards, self.dones, self.infos |
Python | def _get_received(self):
'''return a list of messages received from the server from the agent'''
result = []
for variable in self.socket_client.get_received():
if variable['name'] == '/message' and variable['args'][0]['sender'] == 'agent':
result.append(variable['args'][0]['body'])
return result | def _get_received(self):
'''return a list of messages received from the server from the agent'''
result = []
for variable in self.socket_client.get_received():
if variable['name'] == '/message' and variable['args'][0]['sender'] == 'agent':
result.append(variable['args'][0]['body'])
return result |
Python | def _setup_helper(self):
'''Create commonly used objects and join the chatroom'''
self.flask_client, self.socket_client = self.app.create_test_clients()
self.interfaces = self.app.rooms['0'].interfaces
self.socket_client.emit('join', {'roomId': '0', 'sender': 'agent'})
self.domain = self.app.domain.clone(self.interfaces) | def _setup_helper(self):
'''Create commonly used objects and join the chatroom'''
self.flask_client, self.socket_client = self.app.create_test_clients()
self.interfaces = self.app.rooms['0'].interfaces
self.socket_client.emit('join', {'roomId': '0', 'sender': 'agent'})
self.domain = self.app.domain.clone(self.interfaces) |
Python | def at_time(self, request_params):
'''Return the current weather at the specified time'''
lat_long = load_parameter(request_params, "lat/long")
lat, lon = lat_long.split(',')
time_query = load_parameter(request_params, "time query")
response = self.api_call(
self.provider.weather_at_time,
request_params,
lat,
lon,
time_query)
return response | def at_time(self, request_params):
'''Return the current weather at the specified time'''
lat_long = load_parameter(request_params, "lat/long")
lat, lon = lat_long.split(',')
time_query = load_parameter(request_params, "time query")
response = self.api_call(
self.provider.weather_at_time,
request_params,
lat,
lon,
time_query)
return response |
Python | def clear_variables(self):
'''Reset variables available to the agent. This should be called when resetting the chat'''
self.request_number = 0
self.request_variables = [copy.deepcopy(self.initial_variables)]
self.emit('/history/request_variables/agent', self.request_variables)
if self.get_destination is not None:
source_lat, source_lng = None, None
for variable in self.initial_variables['variables']:
if variable['name'] == 'latitude':
source_lat = variable['value']
elif variable['name'] == 'longitude':
source_lng = variable['value']
user_destination = self.get_destination(source_lat, source_lng)
user_destination['name'] = 'destination'
user_destination['variables'] = user_destination['value']
del user_destination['value']
for variable in user_destination['variables']:
if variable['name'] == 'latitude':
self.dst_lat = variable['value']
elif variable['name'] == 'longitude':
self.dst_lng = variable['value']
self.user_destination = self.remove_latlong(user_destination)
add_full_names(
self.user_destination['variables'],
self.user_destination['variable_group'])
if self.user is not None:
self.user.destination = user_destination
else:
self.user_destination = None
self.emit('/history/request_variables/user', [self.user_destination])
self.end_hint = None | def clear_variables(self):
'''Reset variables available to the agent. This should be called when resetting the chat'''
self.request_number = 0
self.request_variables = [copy.deepcopy(self.initial_variables)]
self.emit('/history/request_variables/agent', self.request_variables)
if self.get_destination is not None:
source_lat, source_lng = None, None
for variable in self.initial_variables['variables']:
if variable['name'] == 'latitude':
source_lat = variable['value']
elif variable['name'] == 'longitude':
source_lng = variable['value']
user_destination = self.get_destination(source_lat, source_lng)
user_destination['name'] = 'destination'
user_destination['variables'] = user_destination['value']
del user_destination['value']
for variable in user_destination['variables']:
if variable['name'] == 'latitude':
self.dst_lat = variable['value']
elif variable['name'] == 'longitude':
self.dst_lng = variable['value']
self.user_destination = self.remove_latlong(user_destination)
add_full_names(
self.user_destination['variables'],
self.user_destination['variable_group'])
if self.user is not None:
self.user.destination = user_destination
else:
self.user_destination = None
self.emit('/history/request_variables/user', [self.user_destination])
self.end_hint = None |
Python | def _command_complete(self, partial_command):
''' Args:
partial_command - A list consisting of API endpoint or a template plus its parameters
Returns bool:
Whether the partial command has all the necessary parameters or not
'''
if len(partial_command) == 0:
return False
action, params = partial_command[0], partial_command[1:]
api = self.domain.api_functions.get(action, None)
if api is not None:
return len(api["params"]) == len(params)
if action == self.domain.end_dialog['function'].endpoint:
return len(self.domain.end_dialog["params"]) == len(params)
for template in self.domain.agent_templates_list:
if template == action:
return len(re.findall(r'{.*?}', template)) == len(params)
assert False, "Couldn't find matching api or templates for action: '%s'" % action | def _command_complete(self, partial_command):
''' Args:
partial_command - A list consisting of API endpoint or a template plus its parameters
Returns bool:
Whether the partial command has all the necessary parameters or not
'''
if len(partial_command) == 0:
return False
action, params = partial_command[0], partial_command[1:]
api = self.domain.api_functions.get(action, None)
if api is not None:
return len(api["params"]) == len(params)
if action == self.domain.end_dialog['function'].endpoint:
return len(self.domain.end_dialog["params"]) == len(params)
for template in self.domain.agent_templates_list:
if template == action:
return len(re.findall(r'{.*?}', template)) == len(params)
assert False, "Couldn't find matching api or templates for action: '%s'" % action |
Python | def find_variable(request_body, parameter_name, value):
'''Find the full name of a variable'''
for variable in request_body:
if variable['name'] == parameter_name and abs(
float(variable['value']) - float(value)) < 0.000005:
return variable['full_name']
elif isinstance(variable['value'], list):
val = find_variable(variable['value'], parameter_name, value)
if val is not None:
return val | def find_variable(request_body, parameter_name, value):
'''Find the full name of a variable'''
for variable in request_body:
if variable['name'] == parameter_name and abs(
float(variable['value']) - float(value)) < 0.000005:
return variable['full_name']
elif isinstance(variable['value'], list):
val = find_variable(variable['value'], parameter_name, value)
if val is not None:
return val |
Python | def driver_valid_actions(self):
'''
Return list of valid actions for driver
'''
null_action_mask = [1]
api_and_template_mask = [len(self.state.driver_partial_command) == 0 for _ in MicroworldEnv.apis + MicroworldEnv.driver_templates]
variable_mask = []
for i in range(self.max_variables):
if i >= len(self.state.driver_variables) or \
len(self.state.driver_partial_command) == 0:
variable_mask.append(0)
else:
variable = self.state.driver_variables[i]
if self.state.driver_partial_command[0] in ('find_place', 'places_nearby'):
if len(self.state.driver_partial_command) == 1:
# Query parameter, must click a user utterance
variable_mask.append(variable.get('full_name', '').startswith('u'))
elif len(self.state.driver_partial_command) == 2:
# Latitude
variable_mask.append('latitude' in variable.get('full_name', ''))
elif len(self.state.driver_partial_command) == 3:
# Longitude
variable_mask.append('longitude' in variable.get('full_name', ''))
elif self.state.driver_partial_command[0] == 'start_driving':
if len(self.state.driver_partial_command) == 1:
# Latitude
variable_mask.append('latitude' in variable.get('full_name', ''))
elif len(self.state.driver_partial_command) == 2:
# Longitude
variable_mask.append('longitude' in variable.get('full_name', ''))
else:
variable_mask.append(1)
return null_action_mask + api_and_template_mask + variable_mask | def driver_valid_actions(self):
'''
Return list of valid actions for driver
'''
null_action_mask = [1]
api_and_template_mask = [len(self.state.driver_partial_command) == 0 for _ in MicroworldEnv.apis + MicroworldEnv.driver_templates]
variable_mask = []
for i in range(self.max_variables):
if i >= len(self.state.driver_variables) or \
len(self.state.driver_partial_command) == 0:
variable_mask.append(0)
else:
variable = self.state.driver_variables[i]
if self.state.driver_partial_command[0] in ('find_place', 'places_nearby'):
if len(self.state.driver_partial_command) == 1:
# Query parameter, must click a user utterance
variable_mask.append(variable.get('full_name', '').startswith('u'))
elif len(self.state.driver_partial_command) == 2:
# Latitude
variable_mask.append('latitude' in variable.get('full_name', ''))
elif len(self.state.driver_partial_command) == 3:
# Longitude
variable_mask.append('longitude' in variable.get('full_name', ''))
elif self.state.driver_partial_command[0] == 'start_driving':
if len(self.state.driver_partial_command) == 1:
# Latitude
variable_mask.append('latitude' in variable.get('full_name', ''))
elif len(self.state.driver_partial_command) == 2:
# Longitude
variable_mask.append('longitude' in variable.get('full_name', ''))
else:
variable_mask.append(1)
return null_action_mask + api_and_template_mask + variable_mask |
Python | def passenger_valid_actions(self):
'''
Return list of valid actions for passenger
'''
return [1] + \
[len(self.state.passenger_partial_command) == 0 for _ in MicroworldEnv.passenger_templates] + \
[len(self.state.passenger_partial_command) > 0 and i < len(self.state.passenger_variables) for i in range(self.max_variables)] | def passenger_valid_actions(self):
'''
Return list of valid actions for passenger
'''
return [1] + \
[len(self.state.passenger_partial_command) == 0 for _ in MicroworldEnv.passenger_templates] + \
[len(self.state.passenger_partial_command) > 0 and i < len(self.state.passenger_variables) for i in range(self.max_variables)] |
Python | def reset(self):
'''
Called before each episode, returns the first observation
'''
logger.info("[{}] Resetting environment".format(self.room_id))
self.dialog_completed = False
self.socket.emit('/restart_dialog', {
'roomId': self.room_id,
})
self.state = DialogState(self.max_steps, self.max_utterances, self.max_variables, self.embed_dim, self.max_command_length, self.max_conversation_length, self.passenger_max_actions, self.passenger_max_actions)
self.state.update_state(self.get_global_state())
self.obs = {
'driver': self.state.make_driver_observation(self.driver_valid_actions()),
'passenger': self.state.make_passenger_observation(self.passenger_valid_actions())
}
self.rewards = {'driver': 0, 'passenger': 0}
self.dones = {'__all__': False}
self.infos = {}
return self.obs | def reset(self):
'''
Called before each episode, returns the first observation
'''
logger.info("[{}] Resetting environment".format(self.room_id))
self.dialog_completed = False
self.socket.emit('/restart_dialog', {
'roomId': self.room_id,
})
self.state = DialogState(self.max_steps, self.max_utterances, self.max_variables, self.embed_dim, self.max_command_length, self.max_conversation_length, self.passenger_max_actions, self.passenger_max_actions)
self.state.update_state(self.get_global_state())
self.obs = {
'driver': self.state.make_driver_observation(self.driver_valid_actions()),
'passenger': self.state.make_passenger_observation(self.passenger_valid_actions())
}
self.rewards = {'driver': 0, 'passenger': 0}
self.dones = {'__all__': False}
self.infos = {}
return self.obs |
Python | def _driver_step(self, action):
'''
Returns the driver's reward from the action
'''
reward = 0
if action == 0:
# 0 => No action
logger.info("[{}] Driver clicked no action".format(self.room_id))
return MicroworldEnv.rewards['driver_no_action']
elif 1 <= action < 1 + len(MicroworldEnv.apis):
# API clicked
api_index = action - 1
api = MicroworldEnv.apis[api_index]
if not self.state.driver_partial_command:
self.state.driver_partial_command.append(api.name)
logger.info("[{}] Driver clicked API call: {}".format(self.room_id, api.name))
else:
logger.info("[{}] Driver tried invalid API click: {}".format(self.room_id, api.name))
reward = MicroworldEnv.rewards['driver_invalid_api']
if reward:
logger.info("[{}] --- Driver got a reward: {}".format(self.room_id, reward))
return reward
elif 1 + len(self.apis) <= action < 1 + len(self.apis) + len(self.driver_templates):
# Template clicked
template_index = action - len(MicroworldEnv.apis) - 1
template = MicroworldEnv.driver_templates[template_index]
if not self.state.driver_partial_command:
logger.info("[{}] Driver clicked template: {}".format(self.room_id, template))
self.state.driver_partial_command.append(template)
else:
logger.info("[{}] Driver tried invalid template click: {}".format(self.room_id, template))
reward = MicroworldEnv.rewards['driver_invalid_template']
if reward:
logger.info("[{}] --- Driver got a reward: {}".format(self.room_id, reward))
return reward
else:
# Variable clicked
# TODO: Combine utterance variables, as is done in the UI
if self.state.driver_partial_command:
variable_index = action - len(MicroworldEnv.apis) - len(MicroworldEnv.driver_templates) - 1
if 0 <= variable_index < len(self.state.driver_variables):
variable = self.state.driver_variables[variable_index]
logger.info("[{}] Driver clicked variable: {}".format(self.room_id, variable))
self.state.driver_partial_command.append(variable)
else:
logger.info("[{}] Driver tried invalid variable click: {}".format(self.room_id, variable_index))
reward = MicroworldEnv.rewards['driver_invalid_variable']
if reward:
logger.info("[{}] --- Driver got a reward: {}".format(self.room_id, reward))
return reward
else:
logger.info("[{}] Driver tried invalid variable click (no action selected)".format(self.room_id))
reward = MicroworldEnv.rewards['driver_invalid_variable']
if reward:
logger.info("[{}] --- Driver got a reward: {}".format(self.room_id, reward))
return reward
if self._driver_command_complete(self.state.driver_partial_command):
logger.info("[{}] --- Driver completed an action: {}".format(self.room_id, self.state.driver_partial_command))
reward = self._apply_driver_command(self.state.driver_partial_command)
if reward:
logger.info("[{}] --- Driver got a reward: {}".format(self.room_id, reward))
return reward | def _driver_step(self, action):
'''
Returns the driver's reward from the action
'''
reward = 0
if action == 0:
# 0 => No action
logger.info("[{}] Driver clicked no action".format(self.room_id))
return MicroworldEnv.rewards['driver_no_action']
elif 1 <= action < 1 + len(MicroworldEnv.apis):
# API clicked
api_index = action - 1
api = MicroworldEnv.apis[api_index]
if not self.state.driver_partial_command:
self.state.driver_partial_command.append(api.name)
logger.info("[{}] Driver clicked API call: {}".format(self.room_id, api.name))
else:
logger.info("[{}] Driver tried invalid API click: {}".format(self.room_id, api.name))
reward = MicroworldEnv.rewards['driver_invalid_api']
if reward:
logger.info("[{}] --- Driver got a reward: {}".format(self.room_id, reward))
return reward
elif 1 + len(self.apis) <= action < 1 + len(self.apis) + len(self.driver_templates):
# Template clicked
template_index = action - len(MicroworldEnv.apis) - 1
template = MicroworldEnv.driver_templates[template_index]
if not self.state.driver_partial_command:
logger.info("[{}] Driver clicked template: {}".format(self.room_id, template))
self.state.driver_partial_command.append(template)
else:
logger.info("[{}] Driver tried invalid template click: {}".format(self.room_id, template))
reward = MicroworldEnv.rewards['driver_invalid_template']
if reward:
logger.info("[{}] --- Driver got a reward: {}".format(self.room_id, reward))
return reward
else:
# Variable clicked
# TODO: Combine utterance variables, as is done in the UI
if self.state.driver_partial_command:
variable_index = action - len(MicroworldEnv.apis) - len(MicroworldEnv.driver_templates) - 1
if 0 <= variable_index < len(self.state.driver_variables):
variable = self.state.driver_variables[variable_index]
logger.info("[{}] Driver clicked variable: {}".format(self.room_id, variable))
self.state.driver_partial_command.append(variable)
else:
logger.info("[{}] Driver tried invalid variable click: {}".format(self.room_id, variable_index))
reward = MicroworldEnv.rewards['driver_invalid_variable']
if reward:
logger.info("[{}] --- Driver got a reward: {}".format(self.room_id, reward))
return reward
else:
logger.info("[{}] Driver tried invalid variable click (no action selected)".format(self.room_id))
reward = MicroworldEnv.rewards['driver_invalid_variable']
if reward:
logger.info("[{}] --- Driver got a reward: {}".format(self.room_id, reward))
return reward
if self._driver_command_complete(self.state.driver_partial_command):
logger.info("[{}] --- Driver completed an action: {}".format(self.room_id, self.state.driver_partial_command))
reward = self._apply_driver_command(self.state.driver_partial_command)
if reward:
logger.info("[{}] --- Driver got a reward: {}".format(self.room_id, reward))
return reward |
Python | def step(self, action_dict):
'''
Given an action_dict, compute the next observation, rewards, and dones
'''
# (state, action) => state
if 'driver' in action_dict:
driver_reward = self._driver_step(action_dict['driver'])
if 'passenger' in action_dict:
passenger_reward = self._passenger_step(action_dict['passenger'])
# Update obs from state
self.state.update_state(self.get_global_state())
self.state.steps += 1
self.obs = {
'driver': self.state.make_driver_observation(self.driver_valid_actions()),
'passenger': self.state.make_passenger_observation(self.passenger_valid_actions())
}
if not self.dialog_completed:
self.dones = {'__all__': self.state.is_done()}
if self.dones['__all__']:
driver_reward += MicroworldEnv.rewards['driver_max_steps']
passenger_reward += MicroworldEnv.rewards['passenger_max_steps']
self.rewards = {'driver': driver_reward, 'passenger': passenger_reward}
self.infos = {}
return self.obs, self.rewards, self.dones, self.infos | def step(self, action_dict):
'''
Given an action_dict, compute the next observation, rewards, and dones
'''
# (state, action) => state
if 'driver' in action_dict:
driver_reward = self._driver_step(action_dict['driver'])
if 'passenger' in action_dict:
passenger_reward = self._passenger_step(action_dict['passenger'])
# Update obs from state
self.state.update_state(self.get_global_state())
self.state.steps += 1
self.obs = {
'driver': self.state.make_driver_observation(self.driver_valid_actions()),
'passenger': self.state.make_passenger_observation(self.passenger_valid_actions())
}
if not self.dialog_completed:
self.dones = {'__all__': self.state.is_done()}
if self.dones['__all__']:
driver_reward += MicroworldEnv.rewards['driver_max_steps']
passenger_reward += MicroworldEnv.rewards['passenger_max_steps']
self.rewards = {'driver': driver_reward, 'passenger': passenger_reward}
self.infos = {}
return self.obs, self.rewards, self.dones, self.infos |
Python | def _command_complete(self, partial_command):
''' Args:
partial_command - A list consisting of API endpoint or a template plus its parameters
Returns bool:
Whether the partial command has all the necessary parameters or not
'''
if len(partial_command) == 0: return False
action, params = partial_command[0], partial_command[1:]
for template in self.domain.user_templates_list:
if template == action:
return len(re.findall(r'{.*?}', template)) == len(params)
assert False, "Couldn't find matching api or templates for action: '%s'" % action | def _command_complete(self, partial_command):
''' Args:
partial_command - A list consisting of API endpoint or a template plus its parameters
Returns bool:
Whether the partial command has all the necessary parameters or not
'''
if len(partial_command) == 0: return False
action, params = partial_command[0], partial_command[1:]
for template in self.domain.user_templates_list:
if template == action:
return len(re.findall(r'{.*?}', template)) == len(params)
assert False, "Couldn't find matching api or templates for action: '%s'" % action |
Python | def acquire(self, blocking=True):
""" Acquire the lock, if possible. If the lock is in use, and `blocking` is False, return False.
Otherwise, check again every `self.delay` seconds until it either gets the lock or
exceeds `timeout` number of seconds, in which case it raises an exception.
"""
start_time = time.time()
while True:
try:
# Attempt to create the lockfile.
# These flags cause os.open to raise an OSError if the file
# already exists.
fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR)
with os.fdopen(fd, "a") as f:
# Print some info about the current process as debug info
# for anyone who bothers to look.
f.write(self._lock_file_contents)
break
except OSError as e:
if e.errno != errno.EEXIST:
raise
if self.timeout is not None and (
time.time() - start_time) >= self.timeout:
raise FileLock.FileLockException("Timeout occurred.")
if not blocking:
return False
time.sleep(self.delay)
self.is_locked = True
return True | def acquire(self, blocking=True):
""" Acquire the lock, if possible. If the lock is in use, and `blocking` is False, return False.
Otherwise, check again every `self.delay` seconds until it either gets the lock or
exceeds `timeout` number of seconds, in which case it raises an exception.
"""
start_time = time.time()
while True:
try:
# Attempt to create the lockfile.
# These flags cause os.open to raise an OSError if the file
# already exists.
fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR)
with os.fdopen(fd, "a") as f:
# Print some info about the current process as debug info
# for anyone who bothers to look.
f.write(self._lock_file_contents)
break
except OSError as e:
if e.errno != errno.EEXIST:
raise
if self.timeout is not None and (
time.time() - start_time) >= self.timeout:
raise FileLock.FileLockException("Timeout occurred.")
if not blocking:
return False
time.sleep(self.delay)
self.is_locked = True
return True |
Python | def on_message_with_alternate_events(
self, events, initial_alternate_events=None):
''' Optional implementation: This is an experimental version of on_message() that adds
initial_alternate_events as additional context before predicting the next action. '''
raise NotImplementedError | def on_message_with_alternate_events(
self, events, initial_alternate_events=None):
''' Optional implementation: This is an experimental version of on_message() that adds
initial_alternate_events as additional context before predicting the next action. '''
raise NotImplementedError |
Python | def on_dialog_finished(self, completed: bool, correct: bool):
'''
Called at the end of a dialog
'''
pass | def on_dialog_finished(self, completed: bool, correct: bool):
'''
Called at the end of a dialog
'''
pass |
Python | def on_dialog_finished(self, completed, correct):
'''
Called at the end of a dialog.
If the dialog is restarted before completion, 'completed' is set to False.
'''
reward_function = self.agent_shared_state["rl_config"]["rewards"]
if self.state.is_done(): # early termination
agent_reward = reward_function["driver_max_steps"]
else:
agent_reward = reward_function["driver_correct_destination"] if correct \
else reward_function["driver_incorrect_destination"]
user_reward = None
if not isinstance(self.room.user, HumanUser):
if self.state.is_done(): # early termination
user_reward = reward_function["passenger_max_steps"]
else:
user_reward = reward_function["passenger_correct_destination"] if correct\
else reward_function["passenger_incorrect_destination"]
# print("DEBUG: Dialog was finished with reward", agent_reward + user_reward)
if user_reward is not None:
joint_reward = {"agent": agent_reward, "user": user_reward}
else:
joint_reward = {"agent": agent_reward}
self.send_reward_to_policy_server(joint_reward)
if self.agent_shared_state["rl_config"]["multiagent"]:
final_obs = {
**self.make_observation(),
**(self.room.user.make_observation() if not isinstance(self.room.user, HumanUser) else {})
}
else:
final_obs = self.make_observation()
self.policy_client.end_episode(
self.current_episode_id, final_obs) | def on_dialog_finished(self, completed, correct):
'''
Called at the end of a dialog.
If the dialog is restarted before completion, 'completed' is set to False.
'''
reward_function = self.agent_shared_state["rl_config"]["rewards"]
if self.state.is_done(): # early termination
agent_reward = reward_function["driver_max_steps"]
else:
agent_reward = reward_function["driver_correct_destination"] if correct \
else reward_function["driver_incorrect_destination"]
user_reward = None
if not isinstance(self.room.user, HumanUser):
if self.state.is_done(): # early termination
user_reward = reward_function["passenger_max_steps"]
else:
user_reward = reward_function["passenger_correct_destination"] if correct\
else reward_function["passenger_incorrect_destination"]
# print("DEBUG: Dialog was finished with reward", agent_reward + user_reward)
if user_reward is not None:
joint_reward = {"agent": agent_reward, "user": user_reward}
else:
joint_reward = {"agent": agent_reward}
self.send_reward_to_policy_server(joint_reward)
if self.agent_shared_state["rl_config"]["multiagent"]:
final_obs = {
**self.make_observation(),
**(self.room.user.make_observation() if not isinstance(self.room.user, HumanUser) else {})
}
else:
final_obs = self.make_observation()
self.policy_client.end_episode(
self.current_episode_id, final_obs) |
Python | def _get_valid_actions_mask(self):
'''
Return indicator mask of valid actions for driver
TODO use action partition indices instead of hard-coded ordering if different action types.
'''
mask = [0] * len(self.agent_shared_state["action_space_partitions"])
assert len(mask) == self.state.driver_max_actions, \
"%d != %d" % (len(mask) == len(self.state.driver_max_actions))
empty_command = len(self.state.driver_partial_command) == 0
for index, action_type_and_sub_index in self.agent_shared_state["action_space_partitions"].items():
action_type, sub_index = action_type_and_sub_index
if empty_command and action_type in \
(ActionType.API, ActionType.END_DIALOG_API, ActionType.TEMPLATE): # TODO add ActionType.NO_ACTION
mask[index] = 1
elif not empty_command and action_type == ActionType.VARIABLE and \
sub_index < len(self.state.driver_variables):
variable = self.state.driver_variables[sub_index]
variable_name = variable.get('full_name', '')
if self.state.driver_partial_command[0] in ('/maps/find_place', '/maps/places_nearby'):
if (len(self.state.driver_partial_command) == 1 # Query parameter, must click a user utterance
and variable_name.startswith('u')) or \
(len(self.state.driver_partial_command) == 2 and (variable_name.startswith('u') or 'latitude' in variable_name)) or \
(len(self.state.driver_partial_command) == 3 and 'longitude' in variable_name):
mask[index] = 1
elif self.state.driver_partial_command[0] == '/maps/start_driving_no_map':
if (len(self.state.driver_partial_command) == 1 and 'latitude' in variable_name) or \
(len(self.state.driver_partial_command) == 2 and 'longitude' in variable_name):
mask[index] = 1
else:
# Template variable
mask[index] = 1
return mask | def _get_valid_actions_mask(self):
'''
Return indicator mask of valid actions for driver
TODO use action partition indices instead of hard-coded ordering if different action types.
'''
mask = [0] * len(self.agent_shared_state["action_space_partitions"])
assert len(mask) == self.state.driver_max_actions, \
"%d != %d" % (len(mask) == len(self.state.driver_max_actions))
empty_command = len(self.state.driver_partial_command) == 0
for index, action_type_and_sub_index in self.agent_shared_state["action_space_partitions"].items():
action_type, sub_index = action_type_and_sub_index
if empty_command and action_type in \
(ActionType.API, ActionType.END_DIALOG_API, ActionType.TEMPLATE): # TODO add ActionType.NO_ACTION
mask[index] = 1
elif not empty_command and action_type == ActionType.VARIABLE and \
sub_index < len(self.state.driver_variables):
variable = self.state.driver_variables[sub_index]
variable_name = variable.get('full_name', '')
if self.state.driver_partial_command[0] in ('/maps/find_place', '/maps/places_nearby'):
if (len(self.state.driver_partial_command) == 1 # Query parameter, must click a user utterance
and variable_name.startswith('u')) or \
(len(self.state.driver_partial_command) == 2 and (variable_name.startswith('u') or 'latitude' in variable_name)) or \
(len(self.state.driver_partial_command) == 3 and 'longitude' in variable_name):
mask[index] = 1
elif self.state.driver_partial_command[0] == '/maps/start_driving_no_map':
if (len(self.state.driver_partial_command) == 1 and 'latitude' in variable_name) or \
(len(self.state.driver_partial_command) == 2 and 'longitude' in variable_name):
mask[index] = 1
else:
# Template variable
mask[index] = 1
return mask |
Python | def _step(self, action_index):
'''
Steps the agent one-click forward and executes apis/templates if a full command results from the click.
Args:
action_index - index corresponding to the item-to-click (api/template/variable)
Returns:
(reward, message) tuple. Message corresponds to the agent message to respond with, it may be None.
'''
raise NotImplementedError | def _step(self, action_index):
'''
Steps the agent one-click forward and executes apis/templates if a full command results from the click.
Args:
action_index - index corresponding to the item-to-click (api/template/variable)
Returns:
(reward, message) tuple. Message corresponds to the agent message to respond with, it may be None.
'''
raise NotImplementedError |
Python | def load_variable(api_variables, variable_name):
'''Used by runnable log to select a variable by name'''
for variable in api_variables:
if variable['name'] == variable_name:
return variable['value'] | def load_variable(api_variables, variable_name):
'''Used by runnable log to select a variable by name'''
for variable in api_variables:
if variable['name'] == variable_name:
return variable['value'] |
Python | def load_parameter(request_body, parameter_name):
'''Find `parameter_name` in `request_body`, which should be in the format that data is sent by requests'''
for parameter in request_body:
if parameter['param'] == parameter_name:
return parameter['value'] | def load_parameter(request_body, parameter_name):
'''Find `parameter_name` in `request_body`, which should be in the format that data is sent by requests'''
for parameter in request_body:
if parameter['param'] == parameter_name:
return parameter['value'] |
Python | def make_english_list(list_, conjunction, oxford_comma=False):
'''
Turns a list into an English list. The conjunction should be a word like 'and' or 'or'.
e.g. [cat, dog, pig], conjunction='and' -> "cat, dog and pig"
Returns a string
'''
if len(list_) <= 1:
return ''.join(list_)
elif len(list_) == 2:
oxford_comma = False # two element lists never get Oxford commas
list_ = list_[:]
if oxford_comma:
list_[-1] = conjunction + ' ' + list_[-1]
return ', '.join(list_)
else:
list_[-2:] = [list_[-2] + ' ' + conjunction + ' ' + list_[-1]]
return ', '.join(list_) | def make_english_list(list_, conjunction, oxford_comma=False):
'''
Turns a list into an English list. The conjunction should be a word like 'and' or 'or'.
e.g. [cat, dog, pig], conjunction='and' -> "cat, dog and pig"
Returns a string
'''
if len(list_) <= 1:
return ''.join(list_)
elif len(list_) == 2:
oxford_comma = False # two element lists never get Oxford commas
list_ = list_[:]
if oxford_comma:
list_[-1] = conjunction + ' ' + list_[-1]
return ', '.join(list_)
else:
list_[-2:] = [list_[-2] + ' ' + conjunction + ' ' + list_[-1]]
return ', '.join(list_) |
Python | def route(endpoint, **kwargs):
'''
Decorator to annotate a function, which is used to create React API endpoints
(see apis/base.py for how they are consumed)
endpoint (str): the URL endpoint used to mount this function
'''
def decorator(fcn):
fcn.endpoint = endpoint
fcn.flask_kwargs = kwargs
return fcn
return decorator | def route(endpoint, **kwargs):
'''
Decorator to annotate a function, which is used to create React API endpoints
(see apis/base.py for how they are consumed)
endpoint (str): the URL endpoint used to mount this function
'''
def decorator(fcn):
fcn.endpoint = endpoint
fcn.flask_kwargs = kwargs
return fcn
return decorator |
Python | def completes_dialog(success=True, confirmation_type=None,
*, confirmation_params=None):
'''
This decorator needs to be called after @route
I'm not sure why, but it has something to do with how decorators interact
'''
if confirmation_type not in [
'map', 'rate_satisfaction', 'confirm_information', 'default']:
raise ValueError(
'Got unexpected confirmation type "{}"'.format(confirmation_type))
def decorator(fcn):
fcn.completes_dialog = True
@wraps(fcn)
def api_call(self, request_params, *args, **kwargs):
result = fcn(self, request_params, *args, **kwargs)
self.manager.end_dialog(
success=success,
confirmation_type=confirmation_type,
method_name=fcn.__name__,
request_params=request_params)
return result
return api_call
return decorator | def completes_dialog(success=True, confirmation_type=None,
*, confirmation_params=None):
'''
This decorator needs to be called after @route
I'm not sure why, but it has something to do with how decorators interact
'''
if confirmation_type not in [
'map', 'rate_satisfaction', 'confirm_information', 'default']:
raise ValueError(
'Got unexpected confirmation type "{}"'.format(confirmation_type))
def decorator(fcn):
fcn.completes_dialog = True
@wraps(fcn)
def api_call(self, request_params, *args, **kwargs):
result = fcn(self, request_params, *args, **kwargs)
self.manager.end_dialog(
success=success,
confirmation_type=confirmation_type,
method_name=fcn.__name__,
request_params=request_params)
return result
return api_call
return decorator |
Python | def add_adjacent_variable(param_name, replacement):
'''
Add a variable to the request_params before the request.
This is useful for finding extra information about a variable without making the agent enter it
param_name - name to give the new variable
replacement - a 2-tuple, containing the first variable name in request_params and the new key to add the value of
TODO: Make this operate on the entity that the variable corresponds to and move this functionality into interface functions
'''
def decorator(fcn):
@wraps(fcn)
def api_call(self, request_params, *args, **kwargs):
new_variable_name = request_params[0]['variable_name'].replace(
replacement[0], replacement[1])
new_variable_value = self.manager.lookup_variable_by_name(
new_variable_name, 'undefined')
request_params.append({
"param": param_name,
"variable_name": new_variable_name,
"value": new_variable_value
})
return fcn(self, request_params, *args, **kwargs)
return api_call
return decorator | def add_adjacent_variable(param_name, replacement):
'''
Add a variable to the request_params before the request.
This is useful for finding extra information about a variable without making the agent enter it
param_name - name to give the new variable
replacement - a 2-tuple, containing the first variable name in request_params and the new key to add the value of
TODO: Make this operate on the entity that the variable corresponds to and move this functionality into interface functions
'''
def decorator(fcn):
@wraps(fcn)
def api_call(self, request_params, *args, **kwargs):
new_variable_name = request_params[0]['variable_name'].replace(
replacement[0], replacement[1])
new_variable_value = self.manager.lookup_variable_by_name(
new_variable_name, 'undefined')
request_params.append({
"param": param_name,
"variable_name": new_variable_name,
"value": new_variable_value
})
return fcn(self, request_params, *args, **kwargs)
return api_call
return decorator |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.