func_code_string stringlengths 52 1.94M | func_documentation_string stringlengths 1 47.2k |
|---|---|
def delta(n, d=None, center=0):
if isinstance(n, six.integer_types):
n = [n]
if d is None:
n0 = _np.asanyarray(n, dtype=_np.int32)
else:
n0 = _np.array(n * d, dtype=_np.int32)
d = n0.size
if center < 0:
cind = [0] * d
else:
cind = []
for i in ... | Create TT-vector for delta-function :math:`\\delta(x - x_0)`. |
def stepfun(n, d=None, center=1, direction=1):
if isinstance(n, six.integer_types):
n = [n]
if d is None:
n0 = _np.asanyarray(n, dtype=_np.int32)
else:
n0 = _np.array(n * d, dtype=_np.int32)
d = n0.size
N = _np.prod(n0)
if center >= N and direction < 0 or center <= 0... | Create TT-vector for Heaviside step function :math:`\chi(x - x_0)`.
Heaviside step function is defined as
.. math::
\chi(x) = \\left\{ \\begin{array}{l} 1 \mbox{ when } x \ge 0, \\\\ 0 \mbox{ when } x < 0. \\end{array} \\right.
For negative value of ``direction`` :math:`\chi(x_0 - x)` is approxi... |
def unit(n, d=None, j=None, tt_instance=True):
if isinstance(n, int):
if d is None:
d = 1
n = n * _np.ones(d, dtype=_np.int32)
else:
d = len(n)
if j is None:
j = 0
rv = []
j = _ind2sub(n, j)
for k in xrange(d):
rv.append(_np.zeros((1, n[k]... | Generates e_j _vector in tt.vector format
---------
Parameters:
n - modes (either integer or array)
d - dimensionality (integer)
j - position of 1 in full-format e_j (integer)
tt_instance - if True, returns tt.vector;
if False, returns tt cores as a list |
def IpaS(d, a, tt_instance=True):
if d == 1:
M = _np.array([[1, 0], [a, 1]]).reshape((1, 2, 2, 1), order='F')
else:
M = [None] * d
M[0] = _np.zeros((1, 2, 2, 2))
M[0][0, :, :, 0] = _np.array([[1, 0], [a, 1]])
M[0][0, :, :, 1] = _np.array([[0, a], [0, 0]])
for... | A special bidiagonal _matrix in the QTT-format
M = IPAS(D, A)
Generates I+a*S_{-1} _matrix in the QTT-format:
1 0 0 0
a 1 0 0
0 a 1 0
0 0 a 1
Convenient for Crank-Nicolson and time gradient matrices |
def reshape(tt_array, shape, eps=1e-14, rl=1, rr=1):
tt1 = _cp.deepcopy(tt_array)
sz = _cp.deepcopy(shape)
ismatrix = False
if isinstance(tt1, _matrix.matrix):
d1 = tt1.tt.d
d2 = sz.shape[0]
ismatrix = True
# The size should be [n,m] in R^{d x 2}
restn2_n = s... | Reshape of the TT-vector
[TT1]=TT_RESHAPE(TT,SZ) reshapes TT-vector or TT-matrix into another
with mode sizes SZ, accuracy 1e-14
[TT1]=TT_RESHAPE(TT,SZ,EPS) reshapes TT-vector/matrix into another with
mode sizes SZ and accuracy EPS
[TT1]=TT_RESHAPE(TT,SZ,EPS, RL) reshapes TT-vector/... |
def permute(x, order, eps=None, return_cores=False):
def _reshape(tensor, shape):
return _np.reshape(tensor, shape, order='F')
# Parse input
if eps is None:
eps = _np.spacing(1)
cores = _vector.vector.to_list(x)
d = _cp.deepcopy(x.d)
n = _cp.deepcopy(x.n)
r = _cp.deepcop... | Permute dimensions (python translation of original matlab code)
Y = permute(X, ORDER, EPS) permutes the dimensions of the TT-tensor X
according to ORDER, delivering a result at relative accuracy EPS. This
function is equivalent to
Y = tt_tensor(permute(reshape(full(X), X.n'),ORDER), EPS)
... |
def min_func(fun, bounds_min, bounds_max, d=None, rmax=10,
n0=64, nswp=10, verb=True, smooth_fun=None):
if d is None:
d = len(bounds_min)
a = np.asanyarray(bounds_min).copy()
b = np.asanyarray(bounds_max).copy()
else:
a = np.ones(d) * bounds_min
b = np.o... | Find (approximate) minimal value of the function on a d-dimensional grid. |
def min_tens(tens, rmax=10, nswp=10, verb=True, smooth_fun=None):
if smooth_fun is None:
smooth_fun = lambda p, lam: (math.pi / 2 - np.arctan(p - lam))
d = tens.d
Rx = [[]] * (d + 1) # Python list for the interfaces
Rx[0] = np.ones((1, 1))
Rx[d] = np.ones((1, 1))
Jy = [np.empty(0, ... | Find (approximate) minimal element in a TT-tensor. |
def cores_orthogonalization_step(coresX, dim, left_to_right=True):
cc = coresX[dim]
r1, n, r2 = cc.shape
if left_to_right:
# Left to right orthogonalization step.
assert(0 <= dim < len(coresX) - 1)
cc, rr = np.linalg.qr(reshape(cc, (-1, r2)))
r2 = cc.shape[1]
cor... | TT-Tensor X orthogonalization step.
The function can change the shape of some cores. |
def left(X, i):
if i < 0:
return np.ones([1, 1])
answ = np.ones([1, 1])
cores = tt.tensor.to_list(X)
for dim in xrange(i+1):
answ = np.tensordot(answ, cores[dim], 1)
answ = reshape(answ, (-1, X.r[i+1]))
return answ | Compute the orthogonal matrix Q_{\leq i} as defined in [1]. |
def right(X, i):
if i > X.d-1:
return np.ones([1, 1])
answ = np.ones([1, 1])
cores = tt.tensor.to_list(X)
for dim in xrange(X.d-1, i-1, -1):
answ = np.tensordot(cores[dim], answ, 1)
answ = reshape(answ, (X.r[i], -1))
return answ.T | Compute the orthogonal matrix Q_{\geq i} as defined in [1]. |
def unfolding(tens, i):
return reshape(tens.full(), (np.prod(tens.n[0:(i+1)]), -1)) | Compute the i-th unfolding of a tensor. |
def _update_lhs(lhs, xCore, zCore, new_lhs):
# TODO: Use intermediate variable to use 5 nested loops instead of 6.
r_old_x, n, r_x = xCore.shape
num_obj, r_old_z, n, r_z = zCore.shape
for idx in range(num_obj):
for val in range(n):
for alpha_old_z in range(r_old_z):
... | Function to be called from the project() |
def _update_rhs(curr_rhs, xCore, zCore, new_rhs):
# TODO: Use intermediate variable to use 5 nested loops instead of 6.
r_x, n, r_old_x = xCore.shape
num_obj, r_z, n, r_old_z = zCore.shape
for idx in range(num_obj):
for val in range(n):
for alpha_old_z in range(r_old_z):
... | Function to be called from the project() |
def project(X, Z, use_jit=False, debug=False):
zArr = None
if isinstance(Z, tt.vector):
zArr = [Z]
else:
zArr = Z
# Get rid of redundant ranks (they cause technical difficulties).
X = X.round(eps=0)
numDims, modeSize = X.d, X.n
coresX = tt.tensor.to_list(X)
coresZ = ... | Project tensor Z on the tangent space of tensor X.
X is a tensor in the TT format.
Z can be a tensor in the TT format or a list of tensors (in this case
the function computes projection of the sum off all tensors in the list:
project(X, Z) = P_X(\sum_i Z_i)
).
This function implements an al... |
def projector_splitting_add(Y, delta, debug=False):
# Get rid of redundant ranks (they cause technical difficulties).
delta = delta.round(eps=0)
numDims = delta.d
assert(numDims == Y.d)
modeSize = delta.n
assert(modeSize == Y.n).all()
coresDelta = tt.tensor.to_list(delta)
coresY = t... | Compute Y + delta via the projector splitting scheme.
This function implements the projector splitting scheme (section 4.2 of [1]).
The result is a TT-tensor with the TT-ranks equal to the TT-ranks of Y. |
def tt_qr(X, left_to_right=True):
# Get rid of redundant ranks (they cause technical difficulties).
X = X.round(eps=0)
numDims = X.d
coresX = tt.tensor.to_list(X)
if left_to_right:
# Left to right orthogonalization of the X cores.
for dim in xrange(0, numDims-1):
cor... | Orthogonalizes a TT tensor from left to right or
from right to left.
:param: X - thensor to orthogonalise
:param: direction - direction. May be 'lr/LR' or 'rl/RL'
for left/right orthogonalization
:return: X_orth, R - orthogonal tensor and right (left)
upper (lower) triangular mat... |
def ind2sub(siz, idx):
n = len(siz)
subs = _np.empty((n))
k = _np.cumprod(siz[:-1])
k = _np.concatenate((_np.ones(1), k))
for i in xrange(n - 1, -1, -1):
subs[i] = _np.floor(idx / k[i])
idx = idx % k[i]
return subs.astype(_np.int32) | Translates full-format index into tt.vector one's.
----------
Parameters:
siz - tt.vector modes
idx - full-vector index
Note: not vectorized. |
def gcd(a, b):
f = _np.frompyfunc(_fractions.gcd, 2, 1)
return f(a, b) | Greatest common divider |
def ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000, use_normest=1):
y0 = y0.round(1e-14) # This will fix ranks
# to be no more than maximal reasonable.
# Fortran part doesn't handle excessive ranks
ry = y0.r.copy()
if scheme is 'sym... | Dynamical tensor-train approximation based on projector splitting
This function performs one step of dynamical tensor-train approximation
for the equation
.. math ::
\\frac{dy}{dt} = A y, \\quad y(0) = y_0
and outputs approximation for :math:`y(\\tau)`
:References:
... |
def diag_ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000):
y0 = y0.round(1e-14) # This will fix ranks
# to be no more than maximal reasonable.
# Fortran part doesn't handle excessive ranks
ry = y0.r.copy()
if scheme is 'symm':
... | Dynamical tensor-train approximation based on projector splitting
This function performs one step of dynamical tensor-train approximation with diagonal matrix, i.e. it solves the equation
for the equation
.. math ::
\\frac{dy}{dt} = V y, \\quad y(0) = y_0
and outputs approx... |
def amen_solve(A, f, x0, eps, kickrank=4, nswp=20, local_prec='n',
local_iters=2, local_restart=40, trunc_norm=1, max_full_size=50, verb=1):
m = A.m.copy()
rx0 = x0.r.copy()
psx0 = x0.ps.copy()
if A.is_complex or f.is_complex:
amen_f90.amen_f90.ztt_amen_wrapper(f.d, A.n, m,
... | Approximate linear system solution in the tensor-train (TT) format
using Alternating minimal energy (AMEN approach)
:References: Sergey Dolgov, Dmitry. Savostyanov
Paper 1: http://arxiv.org/abs/1301.6068
Paper 2: http://arxiv.org/abs/1304.1222
:param A: Matrix in th... |
def T(self):
mycrs = matrix.to_list(self)
trans_crs = []
for cr in mycrs:
trans_crs.append(_np.transpose(cr, [0, 2, 1, 3]))
return matrix.from_list(trans_crs) | Transposed TT-matrix |
def real(self):
return matrix(self.tt.real(), n=self.n, m=self.m) | Return real part of a matrix. |
def imag(self):
return matrix(self.tt.imag(), n=self.n, m=self.m) | Return imaginary part of a matrix. |
def c2r(self):
return matrix(a=self.tt.__complex_op('M'), n=_np.concatenate(
(self.n, [2])), m=_np.concatenate((self.m, [2]))) | Get real matrix from complex one suitable for solving complex linear system with real solver.
For matrix :math:`M(i_1,j_1,\\ldots,i_d,j_d) = \\Re M + i\\Im M` returns (d+1)-dimensional matrix
:math:`\\tilde{M}(i_1,j_1,\\ldots,i_d,j_d,i_{d+1},j_{d+1})` of form
:math:`\\begin{bmatrix}\\Re M & -\\... |
def round(self, eps=1e-14, rmax=100000):
c = matrix()
c.tt = self.tt.round(eps, rmax)
c.n = self.n.copy()
c.m = self.m.copy()
return c | Computes an approximation to a
TT-matrix in with accuracy EPS |
def copy(self):
c = matrix()
c.tt = self.tt.copy()
c.n = self.n.copy()
c.m = self.m.copy()
return c | Creates a copy of the TT-matrix |
def full(self):
N = self.n.prod()
M = self.m.prod()
a = self.tt.full()
d = self.tt.d
sz = _np.vstack((self.n, self.m)).flatten('F')
a = a.reshape(sz, order='F')
# Design a permutation
prm = _np.arange(2 * d)
prm = prm.reshape((d, 2), order... | Transforms a TT-matrix into a full matrix |
def _svdgram(A, tol=None, tol2=1e-7):
R2 = _np.dot(_tconj(A), A)
[u, s, vt] = _np.linalg.svd(R2, full_matrices=False)
u = _np.dot(A, _tconj(vt))
s = (u**2).sum(axis=0)
s = s ** 0.5
if tol is not None:
p = _my_chop2(s, _np.linalg.norm(s) * tol)
u = u[:, :p]
s = s[:p]
... | Highly experimental acceleration of SVD/QR using Gram matrix.
Use with caution for m>>n only!
function [u,s,r]=_svdgram(A,[tol])
u is the left singular factor of A,
s is the singular values (vector!),
r has the meaning of diag(s)*v'.
if tol is given, performs the truncati... |
def amen_mv(A, x, tol, y=None, z=None, nswp=20, kickrank=4,
kickrank2=0, verb=True, init_qr=True, renorm='direct', fkick=False):
if renorm is 'gram':
print("Not implemented yet. Renorm is switched to 'direct'")
renorm = 'direct'
if isinstance(x, _tt.vector):
d = x.d
... | Approximate the matrix-by-vector via the AMEn iteration
[y,z]=amen_mv(A, x, tol, varargin)
Attempts to approximate the y = A*x
with accuracy TOL using the AMEn+ALS iteration.
Matrix A has to be given in the TT-format, right-hand side x should be
given in the TT-format also.
Op... |
def _compute_next_Phi(Phi_prev, x, y, direction, A=None,
extnrm=None, return_norm=True):
[rx1, n, rx2] = x.shape
[ry1, m, ry2] = y.shape
if A is not None:
if isinstance(A, list): # ?????????????????????????????????
# A is a canonical block
ra = len... | Performs the recurrent Phi (or Psi) matrix computation
Phi = Phi_prev * (x'Ay).
If direction is 'lr', computes Psi
if direction is 'rl', computes Phi
A can be empty, then only x'y is computed.
Phi1: rx1, ry1, ra1, or {rx1, ry1}_ra, or rx1, ry1
Phi2: ry2, ra2, rx2, or {ry2, rx2}_ra, or r... |
def multifuncrs(X, funs, eps=1E-6,
nswp=10,
kickrank=5,
y0=None,
rmax=999999, # TODO:infinity \
kicktype='amr-two', \
pcatype='svd', \
trunctype='fro', \
d2=1, ... | Cross approximation of a (vector-)function of several TT-tensors.
:param X: tuple of TT-tensors
:param funs: multivariate function
:param eps: accuracy |
def from_list(a, order='F'):
d = len(a) # Number of cores
res = vector()
n = _np.zeros(d, dtype=_np.int32)
r = _np.zeros(d+1, dtype=_np.int32)
cr = _np.array([])
for i in xrange(d):
cr = _np.concatenate((cr, a[i].flatten(order)))
r[i] = a... | Generate TT-vectorr object from given TT cores.
:param a: List of TT cores.
:type a: list
:returns: vector -- TT-vector constructed from the given cores. |
def erank(self):
r = self.r
n = self.n
d = self.d
if d <= 1:
er = 0e0
else:
sz = _np.dot(n * r[0:d], r[1:])
if sz == 0:
er = 0e0
else:
b = r[0] * n[0] + n[d - 1] * r[d]
if d i... | Effective rank of the TT-vector |
def r2c(self):
tmp = self.copy()
newcore = _np.array(tmp.core, dtype=_np.complex)
cr = newcore[tmp.ps[-2] - 1:tmp.ps[-1] - 1]
cr = cr.reshape((tmp.r[-2], tmp.n[-1], tmp.r[-1]), order='F')
cr[:, 1, :] *= 1j
newcore[tmp.ps[-2] - 1:tmp.ps[-1] - 1] = cr.flatten('F')
... | Get complex vector.from real one made by ``tensor.c2r()``.
For tensor :math:`\\tilde{X}(i_1,\\ldots,i_d,i_{d+1})` returns complex tensor
.. math::
X(i_1,\\ldots,i_d) = \\tilde{X}(i_1,\\ldots,i_d,0) + i\\tilde{X}(i_1,\\ldots,i_d,1).
>>> a = tt.rand(2,10,5) + 1j * tt.rand(2,10,5)
... |
def full(self, asvector=False):
# Generate correct size vector
sz = self.n.copy()
if self.r[0] > 1:
sz = _np.concatenate(([self.r[0]], sz))
if self.r[self.d] > 1:
sz = _np.concatenate(([self.r[self.d]], sz))
if (_np.iscomplex(self.core).any()):
... | Returns full array (uncompressed).
.. warning::
TT compression allows to keep in memory tensors much larger than ones PC can handle in
raw format. Therefore this function is quite unsafe; use it at your own risk.
:returns: numpy.ndarray -- full tensor. |
def round(self, eps=1e-14, rmax=1000000):
c = vector()
c.n = _np.copy(self.n)
c.d = self.d
c.r = _np.copy(self.r)
c.ps = _np.copy(self.ps)
if (_np.iscomplex(self.core).any()):
_tt_f90.tt_f90.ztt_compr2(c.n, c.r, c.ps, self.core, eps, rmax)
... | Applies TT rounding procedure to the TT-vector and **returns rounded tensor**.
:param eps: Rounding accuracy.
:type eps: float
:param rmax: Maximal rank
:type rmax: int
:returns: tensor -- rounded TT-vector.
Usage example:
>>> a = tt.ones(2, 10)
>>> b =... |
def rmean(self):
if not _np.all(self.n):
return 0
# Solving quadratic equation ar^2 + br + c = 0;
a = _np.sum(self.n[1:-1])
b = self.n[0] + self.n[-1]
c = - _np.sum(self.n * self.r[1:] * self.r[:-1])
D = b ** 2 - 4 * a * c
r = 0.5 * (-b + _np.... | Calculates the mean rank of a TT-vector. |
def qtt_fft1(self,tol,inverse=False, bitReverse=True):
d = self.d
r = self.r.copy()
y = self.to_list(self)
if inverse:
twiddle =-1+1.22e-16j # exp(pi*1j)
else:
twiddle =-1-1.22e-16j # exp(-pi*1j)
for i in range(... | Compute 1D (inverse) discrete Fourier Transform in the QTT format.
:param tol: error tolerance.
:type tol: float
:param inverse: whether do an inverse FFT or not.
:type inverse: Boolean
:param bitReverse: whether do the bit reversion or not. If this function i... |
def eigb(A, y0, eps, rmax=150, nswp=20, max_full_size=1000, verb=1):
ry = y0.r.copy()
lam = tt_eigb.tt_block_eig.tt_eigb(y0.d, A.n, A.m, A.tt.r, A.tt.core, y0.core, ry, eps,
rmax, ry[y0.d], 0, nswp, max_full_size, verb)
y = tensor()
y.d = y0.d
y.n = A.n.co... | Approximate computation of minimal eigenvalues in tensor train format
This function uses alternating least-squares algorithm for the computation of several
minimal eigenvalues. If you want maximal eigenvalues, just send -A to the function.
:Reference:
S. V. Dolgov, B. N. Khoromskij, I. V. Oselede... |
def GMRES(A, u_0, b, eps=1e-6, maxit=100, m=20, _iteration=0, callback=None, verbose=0):
maxitexceeded = False
converged = False
if verbose:
print('GMRES(m=%d, _iteration=%d, maxit=%d)' % (m, _iteration, maxit))
v = np.ones((m + 1), dtype=object) * np.nan
R = np.ones((m, m)) * np.nan
... | Flexible TT GMRES
:param A: matvec(x[, eps])
:param u_0: initial vector
:param b: answer
:param maxit: max number of iterations
:param eps: required accuracy
:param m: number of iteration without restart
:param _iteration: iteration counter
:param callback:
:param verbose: to print d... |
def getRow(leftU, rightV, jVec):
jLeft = None
jRight = None
if len(leftU) > 0:
jLeft = jVec[:len(leftU)]
if len(rightV) > 0:
jRight = jVec[-len(rightV):]
multU = np.ones([1,1])
for k in xrange(len(leftU)):
multU = np.dot(multU, leftU[k][:, jLeft[k], :])
mult... | Compute X_{\geq \mu}^T \otimes X_{leq \mu}
X_{\geq \mu} = V_{\mu+1}(j_{\mu}) \ldots V_{d} (j_{d}) [left interface matrix]
X_{\leq \mu} = U_{1} (j_{1}) \ldots U_{\mu-1}(j_{\mu-1}) [right interface matrix]
Parameters:
:list of numpy.arrays: leftU
left-orthogonal cores from 1 to \mu-1
... |
def orthLRFull(coreList, mu, splitResult = True):
d = len(coreList)
assert (mu >= 0) and (mu <= d)
resultU = []
for k in xrange(mu):
core = coreList[k].copy()
if k > 0:
core = np.einsum('ijk,li->ljk', core, R)
[r1, n, r2] = core.shape
if (k < mu-1):
... | Orthogonalize list of TT-cores.
Parameters:
:list: coreList
list of TT-cores (stored as numpy arrays)
:int: mu
separating index for left and right orthogonalization.
Output cores will be left-orthogonal for dimensions from 1 to \mu-1
and right-ort... |
def computeFunctional(x, cooP):
indices = cooP['indices']
values = cooP['values']
[P, d] = indices.shape
assert P == len(values)
result = 0
for p in xrange(P):
index = tuple(indices[p, :])
result += (x[index] - values[p])**2
result *= 0.5
return result | Compute value of functional J(X) = ||PX - PA||^2_F,
where P is projector into index subspace of known elements,
X is our approximation,
A is original tensor.
Parameters:
:tt.vector: x
current approximation [X]
:dict: cooP
dictionary with two... |
def ttSparseALS(cooP, shape, x0=None, ttRank=1, tol=1e-5, maxnsweeps=20, verbose=True, alpha=1e-2):
indices = cooP['indices']
values = cooP['values']
[P, d] = indices.shape
assert P == len(values)
timeVal = time.clock()
if x0 is None:
x = tt.rand(shape, r = ttRank)
... | TT completion via Alternating Least Squares algorithm.
Parameters:
:dict: cooP
dictionary with two records
- 'indices': numpy.array of P x d shape,
contains index subspace of P known elements;
each string is an index of one element.
... |
def update(self, icon=None, hover_text=None):
if icon:
self._icon = icon
self._load_icon()
if hover_text:
self._hover_text = hover_text
self._refresh_icon() | update icon image and/or hover text |
def encode_for_locale(s):
try:
return s.encode(LOCALE_ENCODING, 'ignore')
except (AttributeError, UnicodeDecodeError):
return s.decode('ascii', 'ignore').encode(LOCALE_ENCODING) | Encode text items for system locale. If encoding fails, fall back to ASCII. |
def lru_cache(maxsize=128, typed=False, state=None, unhashable='error'):
def func_wrapper(func):
_cached_func = clru_cache(maxsize, typed, state, unhashable)(func)
def wrapper(*args, **kwargs):
return _cached_func(*args, **kwargs)
wrapper.__wrapped__ = func
wrapper.c... | Least-recently-used cache decorator.
If *maxsize* is set to None, the LRU features are disabled and
the cache can grow without bound.
If *typed* is True, arguments of different types will be cached
separately. For example, f(3.0) and f(3) will be treated as distinct
calls with distinct results.
... |
def fib(n):
v = n.value
return v if v < 2 else fib2(PythonInt(v-1)) + fib(PythonInt(v-2)) | Terrible Fibonacci number generator. |
def run_fib_with_clear(r):
for i in range(r):
if randint(RAND_MIN, RAND_MAX) == RAND_MIN:
fib.cache_clear()
fib2.cache_clear()
res = fib(PythonInt(FIB))
if RESULT != res:
raise ValueError("Expected %d, Got %d" % (RESULT, res)) | Run Fibonacci generator r times. |
def run_fib_with_stats(r):
for i in range(r):
res = fib(PythonInt(FIB))
if RESULT != res:
raise ValueError("Expected %d, Got %d" % (RESULT, res)) | Run Fibonacci generator r times. |
def parse(self, input_str, reference_date=""):
if not jpype.isThreadAttachedToJVM():
jpype.attachThreadToJVM()
if reference_date:
return json.loads(self._sutime.annotate(input_str, reference_date))
return json.loads(self._sutime.annotate(input_str)) | Parses datetime information out of string input.
It invokes the SUTimeWrapper.annotate() function in Java.
Args:
input_str: The input as string that has to be parsed.
reference_date: Optional reference data for SUTime.
Returns:
A list of dicts with the resu... |
def format_message(self, msg, botreply=False):
# Make sure the string is Unicode for Python 2.
if sys.version_info[0] < 3 and isinstance(msg, str):
msg = msg.decode()
# Lowercase it.
msg = msg.lower()
# Run substitutions on it.
msg = self.substitute(m... | Format a user's message for safe processing.
This runs substitutions on the message and strips out any remaining
symbols (depending on UTF-8 mode).
:param str msg: The user's message.
:param bool botreply: Whether this formatting is being done for the
bot's last reply (e.g.... |
def _getreply(self, user, msg, context='normal', step=0, ignore_object_errors=True):
# Needed to sort replies?
if 'topics' not in self.master._sorted:
raise RepliesNotSortedError("You must call sort_replies() once you are done loading RiveScript documents")
# Initialize the ... | The internal reply getter function.
DO NOT CALL THIS YOURSELF.
:param str user: The user ID as passed to ``reply()``.
:param str msg: The formatted user message.
:param str context: The reply context, one of ``begin`` or ``normal``.
:param int step: The recursion depth counter.... |
def reply_regexp(self, user, regexp):
if regexp in self.master._regexc["trigger"]:
# Already compiled this one!
return self.master._regexc["trigger"][regexp]
# If the trigger is simply '*' then the * there needs to become (.*?)
# to match the blank string too.
... | Prepares a trigger for the regular expression engine.
:param str user: The user ID invoking a reply.
:param str regexp: The original trigger text to be turned into a regexp.
:return regexp: The final regexp object. |
def do_expand_array(self, array_name, depth=0):
if depth > self.master._depth:
raise Exception("deep recursion detected")
if not array_name in self.master._array:
raise Exception("array '%s' not defined" % (array_name))
ret = list(self.master._array[array_name])
... | Do recurrent array expansion, returning a set of keywords.
Exception is thrown when there are cyclical dependencies between
arrays or if the ``@array`` name references an undefined array.
:param str array_name: The name of the array to expand.
:param int depth: The recursion depth coun... |
def expand_array(self, array_name):
ret = self.master._array[array_name] if array_name in self.master._array else []
try:
ret = self.do_expand_array(array_name)
except Exception as e:
self.warn("Error expanding array '%s': %s" % (array_name, str(e)))
retu... | Expand variables and return a set of keywords.
:param str array_name: The name of the array to expand.
:return list: The final array contents.
Warning is issued when exceptions occur. |
def process_tags(self, user, msg, reply, st=[], bst=[], depth=0, ignore_object_errors=True):
stars = ['']
stars.extend(st)
botstars = ['']
botstars.extend(bst)
if len(stars) == 1:
stars.append("undefined")
if len(botstars) == 1:
botstars.a... | Post process tags in a message.
:param str user: The user ID.
:param str msg: The user's formatted message.
:param str reply: The raw RiveScript reply for the message.
:param []str st: The array of ``<star>`` matches from the trigger.
:param []str bst: The array of ``<botstar>``... |
def substitute(self, msg, kind):
# Safety checking.
if 'lists' not in self.master._sorted:
raise RepliesNotSortedError("You must call sort_replies() once you are done loading RiveScript documents")
if kind not in self.master._sorted["lists"]:
raise RepliesNotSort... | Run a kind of substitution on a message.
:param str msg: The message to run substitutions against.
:param str kind: The kind of substitution to run,
one of ``subs`` or ``person``. |
def load(self, name, code):
# We need to make a dynamic Python method.
source = "def RSOBJ(rs, args):\n"
for line in code:
source = source + "\t" + line + "\n"
source += "self._objects[name] = RSOBJ\n"
try:
exec(source)
# self._objects... | Prepare a Python code object given by the RiveScript interpreter.
:param str name: The name of the Python object macro.
:param []str code: The Python source code for the object macro. |
def call(self, rs, name, user, fields):
# Call the dynamic method.
if name not in self._objects:
return '[ERR: Object Not Found]'
func = self._objects[name]
reply = ''
try:
reply = func(rs, fields)
if reply is None:
rep... | Invoke a previously loaded object.
:param RiveScript rs: the parent RiveScript instance.
:param str name: The name of the object macro to be called.
:param str user: The user ID invoking the object macro.
:param []str fields: Array of words sent as the object's arguments.
:retu... |
def get_topic_triggers(rs, topic, thats, depth=0, inheritance=0, inherited=False):
# Break if we're in too deep.
if depth > rs._depth:
rs._warn("Deep recursion while scanning topic inheritance")
# Keep in mind here that there is a difference between 'includes' and
# 'inherits' -- topics tha... | Recursively scan a topic and return a list of all triggers.
Arguments:
rs (RiveScript): A reference to the parent RiveScript instance.
topic (str): The original topic name.
thats (bool): Are we getting triggers for 'previous' replies?
depth (int): Recursion step counter.
inh... |
def get_topic_tree(rs, topic, depth=0):
# Break if we're in too deep.
if depth > rs._depth:
rs._warn("Deep recursion while scanning topic trees!")
return []
# Collect an array of all topics.
topics = [topic]
# Does this topic include others?
if topic in rs._includes:
... | Given one topic, get the list of all included/inherited topics.
:param str topic: The topic to start the search at.
:param int depth: The recursion depth counter.
:return []str: Array of topics. |
def word_count(trigger, all=False):
words = []
if all:
words = re.split(RE.ws, trigger)
else:
words = re.split(RE.wilds_and_optionals, trigger)
wc = 0 # Word count
for word in words:
if len(word) > 0:
wc += 1
return wc | Count the words that aren't wildcards or options in a trigger.
:param str trigger: The trigger to count words for.
:param bool all: Count purely based on whitespace separators, or
consider wildcards not to be their own words.
:return int: The word count. |
def string_format(msg, method):
if method == "uppercase":
return msg.upper()
elif method == "lowercase":
return msg.lower()
elif method == "sentence":
return msg.capitalize()
elif method == "formal":
return string.capwords(msg) | Format a string (upper, lower, formal, sentence).
:param str msg: The user's message.
:param str method: One of ``uppercase``, ``lowercase``,
``sentence`` or ``formal``.
:return str: The reformatted string. |
def load(self, name, code):
source = "\n".join(code)
self._objects[name] = source | Prepare a Perl code object given by the RS interpreter. |
def hello_rivescript():
from_number = request.values.get("From", "unknown")
message = request.values.get("Body")
reply = "(Internal error)"
# Get a reply from RiveScript.
if message:
reply = bot.reply(from_number, message)
# Send the response.
resp = twilio.twiml.Respo... | Receive an inbound SMS and send a reply from RiveScript. |
def interactive_mode():
parser = argparse.ArgumentParser(description="RiveScript interactive mode.")
parser.add_argument("--debug", "-d",
help="Enable debug logging within RiveScript.",
action="store_true",
)
parser.add_argument("--json", "-j",
help="Enable JSON mode. In thi... | The built-in RiveScript Interactive Mode.
This feature of RiveScript allows you to test and debug a chatbot in your
terminal window. There are two ways to invoke this mode::
# By running the Python RiveScript module directly:
python rivescript eg/brain
# By running the shell.py in the... |
def reply():
params = request.json
if not params:
return jsonify({
"status": "error",
"error": "Request must be of the application/json type!",
})
username = params.get("username")
message = params.get("message")
uservars = params.get("vars", dict())
... | Fetch a reply from RiveScript.
Parameters (JSON):
* username
* message
* vars |
def index(path=None):
payload = {
"username": "soandso",
"message": "Hello bot",
"vars": {
"name": "Soandso",
}
}
return Response(r.format(json.dumps(payload)),
mimetype="text/plain") | On all other routes, just return an example `curl` command. |
def _key(self, username, frozen=False):
if frozen:
return self.frozen + username
return self.prefix + username | Translate a username into a key for Redis. |
def _get_user(self, username):
data = self.client.get(self._key(username))
if data is None:
return None
return json.loads(data.decode()) | Custom helper method to retrieve a user's data from Redis. |
def sort_trigger_set(triggers, exclude_previous=True, say=None):
if say is None:
say = lambda x: x
# KEEP IN MIND: the `triggers` array is composed of array elements of the form
# ["trigger text", pointer to trigger data]
# So this code will use e.g. `trig[0]` when referring to the trigger ... | Sort a group of triggers in optimal sorting order.
The optimal sorting order is, briefly:
* Atomic triggers (containing nothing but plain words and alternation
groups) are on top, with triggers containing the most words coming
first. Triggers with equal word counts are sorted by length, and then
... |
def sort_list(items):
# Track by number of words.
track = {}
def by_length(word1, word2):
return len(word2) - len(word1)
# Loop through each item.
for item in items:
# Count the words.
cword = utils.word_count(item, all=True)
if cword not in track:
tr... | Sort a simple list by number of words and length. |
def load_directory(self, directory, ext=None):
self._say("Loading from directory: " + directory)
if ext is None:
# Use the default extensions - .rive is preferable.
ext = ['.rive', '.rs']
elif type(ext) == str:
# Backwards compatibility for ext being ... | Load RiveScript documents from a directory.
:param str directory: The directory of RiveScript documents to load
replies from.
:param []str ext: List of file extensions to consider as RiveScript
documents. The default is ``[".rive", ".rs"]``. |
def load_file(self, filename):
self._say("Loading file: " + filename)
fh = codecs.open(filename, 'r', 'utf-8')
lines = fh.readlines()
fh.close()
self._say("Parsing " + str(len(lines)) + " lines of code from " + filename)
self._parse(filename, lines) | Load and parse a RiveScript document.
:param str filename: The path to a RiveScript file. |
def stream(self, code):
self._say("Streaming code.")
if type(code) in [str, text_type]:
code = code.split("\n")
self._parse("stream()", code) | Stream in RiveScript source code dynamically.
:param code: Either a string containing RiveScript code or an array of
lines of RiveScript code. |
def _parse(self, fname, code):
# Get the "abstract syntax tree"
ast = self._parser.parse(fname, code)
# Get all of the "begin" type variables: global, var, sub, person, ...
for kind, data in ast["begin"].items():
internal = getattr(self, "_" + kind) # The internal n... | Parse RiveScript code into memory.
:param str fname: The arbitrary file name used for syntax reporting.
:param []str code: Lines of RiveScript source code to parse. |
def deparse(self):
# Data to return.
result = {
"begin": {
"global": {},
"var": {},
"sub": {},
"person": {},
"array": {},
"triggers": [],
},
"topi... | Dump the in-memory RiveScript brain as a Python data structure.
This would be useful, for example, to develop a user interface for
editing RiveScript replies without having to edit the RiveScript
source code directly.
:return dict: JSON-serializable Python data structure containing the... |
def write(self, fh, deparsed=None):
# Passed a string instead of a file handle?
if type(fh) is str:
fh = codecs.open(fh, "w", "utf-8")
# Deparse the loaded data.
if deparsed is None:
deparsed = self.deparse()
# Start at the beginning.
fh.w... | Write the currently parsed RiveScript data into a file.
Pass either a file name (string) or a file handle object.
This uses ``deparse()`` to dump a representation of the loaded data and
writes it to the destination file. If you provide your own data as the
``deparsed`` argument, it wil... |
def _write_triggers(self, fh, triggers, indent=""):
for trig in triggers:
fh.write(indent + "+ " + self._write_wrapped(trig["trigger"], indent=indent) + "\n")
d = trig
if d.get("previous"):
fh.write(indent + "% " + self._write_wrapped(d["previous"], i... | Write triggers to a file handle.
Parameters:
fh (file): file object.
triggers (list): list of triggers to write.
indent (str): indentation for each line. |
def _write_wrapped(self, line, sep=" ", indent="", width=78):
words = line.split(sep)
lines = []
line = ""
buf = []
while len(words):
buf.append(words.pop(0))
line = sep.join(buf)
if len(line) > width:
# Need to word... | Word-wrap a line of RiveScript code for being written to a file.
:param str line: The original line of text to word-wrap.
:param str sep: The word separator.
:param str indent: The indentation to use (as a set of spaces).
:param int width: The character width to constrain each line to.
... |
def sort_replies(self, thats=False):
# (Re)initialize the sort cache.
self._sorted["topics"] = {}
self._sorted["thats"] = {}
self._say("Sorting triggers...")
# Loop through all the topics.
for topic in self._topics.keys():
self._say("Analyzing topic ... | Sort the loaded triggers in memory.
After you have finished loading your RiveScript code, call this method
to populate the various internal sort buffers. This is absolutely
necessary for reply matching to work efficiently! |
def set_handler(self, language, obj):
# Allow them to delete a handler too.
if obj is None:
if language in self._handlers:
del self._handlers[language]
else:
self._handlers[language] = obj | Define a custom language handler for RiveScript objects.
Pass in a ``None`` value for the object to delete an existing handler (for
example, to prevent Python code from being able to be run by default).
Look in the ``eg`` folder of the rivescript-python distribution for
an example scri... |
def set_subroutine(self, name, code):
# Do we have a Python handler?
if 'python' in self._handlers:
self._handlers['python']._objects[name] = code
self._objlangs[name] = 'python'
else:
self._warn("Can't set_subroutine: no Python object handler!") | Define a Python object from your program.
This is equivalent to having an object defined in the RiveScript code,
except your Python code is defining it instead.
:param str name: The name of the object macro.
:param def code: A Python function with a method signature of
``(r... |
def set_global(self, name, value):
if value is None:
# Unset the variable.
if name in self._global:
del self._global[name]
self._global[name] = value | Set a global variable.
Equivalent to ``! global`` in RiveScript code.
:param str name: The name of the variable to set.
:param str value: The value of the variable.
Set this to ``None`` to delete the variable. |
def set_variable(self, name, value):
if value is None:
# Unset the variable.
if name in self._var:
del self._var[name]
self._var[name] = value | Set a bot variable.
Equivalent to ``! var`` in RiveScript code.
:param str name: The name of the variable to set.
:param str value: The value of the variable.
Set this to ``None`` to delete the variable. |
def set_substitution(self, what, rep):
if rep is None:
# Unset the variable.
if what in self._subs:
del self._subs[what]
self._subs[what] = rep | Set a substitution.
Equivalent to ``! sub`` in RiveScript code.
:param str what: The original text to replace.
:param str rep: The text to replace it with.
Set this to ``None`` to delete the substitution. |
def set_person(self, what, rep):
if rep is None:
# Unset the variable.
if what in self._person:
del self._person[what]
self._person[what] = rep | Set a person substitution.
Equivalent to ``! person`` in RiveScript code.
:param str what: The original text to replace.
:param str rep: The text to replace it with.
Set this to ``None`` to delete the substitution. |
def set_uservar(self, user, name, value):
self._session.set(user, {name: value}) | Set a variable for a user.
This is like the ``<set>`` tag in RiveScript code.
:param str user: The user ID to set a variable for.
:param str name: The name of the variable to set.
:param str value: The value to set there. |
def set_uservars(self, user, data=None):
# Check the parameters to see how we're being used.
if type(user) is dict and data is None:
# Setting many variables for many users.
for uid, uservars in user.items():
if type(uservars) is not dict:
... | Set many variables for a user, or set many variables for many users.
This function can be called in two ways::
# Set a dict of variables for a single user.
rs.set_uservars(username, vars)
# Set a nested dict of variables for many users.
rs.set_uservars(many_var... |
def get_uservar(self, user, name):
if name == '__lastmatch__': # Treat var `__lastmatch__` since it can't receive "undefined" value
return self.last_match(user)
else:
return self._session.get(user, name) | Get a variable about a user.
:param str user: The user ID to look up a variable for.
:param str name: The name of the variable to get.
:return: The user variable, or ``None`` or ``"undefined"``:
* If the user has no data at all, this returns ``None``.
* If the user doe... |
def get_uservars(self, user=None):
if user is None:
# All the users!
return self._session.get_all()
else:
# Just this one!
return self._session.get_any(user) | Get all variables about a user (or all users).
:param optional str user: The user ID to retrieve all variables for.
If not passed, this function will return all data for all users.
:return dict: All the user variables.
* If a ``user`` was passed, this is a ``dict`` of key/valu... |
def clear_uservars(self, user=None):
if user is None:
# All the users!
self._session.reset_all()
else:
# Just this one.
self._session.reset(user) | Delete all variables about a user (or all users).
:param str user: The user ID to clear variables for, or else clear all
variables for all users if not provided. |
def trigger_info(self, trigger=None, dump=False):
if dump:
return self._syntax
response = None
# Search the syntax tree for the trigger.
for category in self._syntax:
for topic in self._syntax[category]:
if trigger in self._syntax[category... | Get information about a trigger.
Pass in a raw trigger to find out what file name and line number it
appeared at. This is useful for e.g. tracking down the location of the
trigger last matched by the user via ``last_match()``. Returns a list
of matching triggers, containing their topics... |
def current_user(self):
if self._brain._current_user is None:
# They're doing it wrong.
self._warn("current_user() is meant to be used from within a Python object macro!")
return self._brain._current_user | Retrieve the user ID of the current user talking to your bot.
This is mostly useful inside of a Python object macro to get the user
ID of the person who caused the object macro to be invoked (i.e. to
set a variable for that user from within the object).
This will return ``None`` if use... |
def reply(self, user, msg, errors_as_replies=True):
return self._brain.reply(user, msg, errors_as_replies) | Fetch a reply from the RiveScript brain.
Arguments:
user (str): A unique user ID for the person requesting a reply.
This could be e.g. a screen name or nickname. It's used internally
to store user variables (including topic and history), so if your
bo... |
def _precompile_substitution(self, kind, pattern):
if pattern not in self._regexc[kind]:
qm = re.escape(pattern)
self._regexc[kind][pattern] = {
"qm": qm,
"sub1": re.compile(r'^' + qm + r'$'),
"sub2": re.compile(r'^' + qm + r'(\W+)... | Pre-compile the regexp for a substitution pattern.
This will speed up the substitutions that happen at the beginning of
the reply fetching process. With the default brain, this took the
time for _substitute down from 0.08s to 0.02s
:param str kind: One of ``sub``, ``person``.
:... |
def _precompile_regexp(self, trigger):
if utils.is_atomic(trigger):
return # Don't need a regexp for atomic triggers.
# Check for dynamic tags.
for tag in ["@", "<bot", "<get", "<input", "<reply"]:
if tag in trigger:
return # Can't precompile th... | Precompile the regex for most triggers.
If the trigger is non-atomic, and doesn't include dynamic tags like
``<bot>``, ``<get>``, ``<input>/<reply>`` or arrays, it can be
precompiled and save time when matching.
:param str trigger: The trigger text to attempt to precompile. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.