repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
oseledets/ttpy | tt/core/tools.py | delta | def delta(n, d=None, center=0):
""" Create TT-vector for delta-function :math:`\\delta(x - x_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... | python | def delta(n, d=None, center=0):
""" Create TT-vector for delta-function :math:`\\delta(x - x_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... | [
"def",
"delta",
"(",
"n",
",",
"d",
"=",
"None",
",",
"center",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"n",
",",
"six",
".",
"integer_types",
")",
":",
"n",
"=",
"[",
"n",
"]",
"if",
"d",
"is",
"None",
":",
"n0",
"=",
"_np",
".",
"asa... | Create TT-vector for delta-function :math:`\\delta(x - x_0)`. | [
"Create",
"TT",
"-",
"vector",
"for",
"delta",
"-",
"function",
":",
"math",
":",
"\\\\",
"delta",
"(",
"x",
"-",
"x_0",
")",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/tools.py#L712-L736 |
oseledets/ttpy | tt/core/tools.py | stepfun | def stepfun(n, d=None, center=1, direction=1):
""" 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 ... | python | def stepfun(n, d=None, center=1, direction=1):
""" 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 ... | [
"def",
"stepfun",
"(",
"n",
",",
"d",
"=",
"None",
",",
"center",
"=",
"1",
",",
"direction",
"=",
"1",
")",
":",
"if",
"isinstance",
"(",
"n",
",",
"six",
".",
"integer_types",
")",
":",
"n",
"=",
"[",
"n",
"]",
"if",
"d",
"is",
"None",
":",... | 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... | [
"Create",
"TT",
"-",
"vector",
"for",
"Heaviside",
"step",
"function",
":",
"math",
":",
"\\",
"chi",
"(",
"x",
"-",
"x_0",
")",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/tools.py#L739-L831 |
oseledets/ttpy | tt/core/tools.py | unit | def unit(n, d=None, j=None, tt_instance=True):
''' 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;
... | python | def unit(n, d=None, j=None, tt_instance=True):
''' 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;
... | [
"def",
"unit",
"(",
"n",
",",
"d",
"=",
"None",
",",
"j",
"=",
"None",
",",
"tt_instance",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"n",
",",
"int",
")",
":",
"if",
"d",
"is",
"None",
":",
"d",
"=",
"1",
"n",
"=",
"n",
"*",
"_np",
... | 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 | [
"Generates",
"e_j",
"_vector",
"in",
"tt",
".",
"vector",
"format",
"---------",
"Parameters",
":",
"n",
"-",
"modes",
"(",
"either",
"integer",
"or",
"array",
")",
"d",
"-",
"dimensionality",
"(",
"integer",
")",
"j",
"-",
"position",
"of",
"1",
"in",
... | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/tools.py#L843-L870 |
oseledets/ttpy | tt/core/tools.py | IpaS | def IpaS(d, a, tt_instance=True):
'''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
'''
if d == 1:
M = _np.array([[1, 0... | python | def IpaS(d, a, tt_instance=True):
'''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
'''
if d == 1:
M = _np.array([[1, 0... | [
"def",
"IpaS",
"(",
"d",
",",
"a",
",",
"tt_instance",
"=",
"True",
")",
":",
"if",
"d",
"==",
"1",
":",
"M",
"=",
"_np",
".",
"array",
"(",
"[",
"[",
"1",
",",
"0",
"]",
",",
"[",
"a",
",",
"1",
"]",
"]",
")",
".",
"reshape",
"(",
"(",... | 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 | [
"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",
... | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/tools.py#L873-L901 |
oseledets/ttpy | tt/core/tools.py | reshape | def reshape(tt_array, shape, eps=1e-14, rl=1, rr=1):
''' 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 EP... | python | def reshape(tt_array, shape, eps=1e-14, rl=1, rr=1):
''' 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 EP... | [
"def",
"reshape",
"(",
"tt_array",
",",
"shape",
",",
"eps",
"=",
"1e-14",
",",
"rl",
"=",
"1",
",",
"rr",
"=",
"1",
")",
":",
"tt1",
"=",
"_cp",
".",
"deepcopy",
"(",
"tt_array",
")",
"sz",
"=",
"_cp",
".",
"deepcopy",
"(",
"shape",
")",
"isma... | 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/... | [
"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"
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/tools.py#L904-L1164 |
oseledets/ttpy | tt/core/tools.py | permute | def permute(x, order, eps=None, return_cores=False):
'''
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
... | python | def permute(x, order, eps=None, return_cores=False):
'''
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
... | [
"def",
"permute",
"(",
"x",
",",
"order",
",",
"eps",
"=",
"None",
",",
"return_cores",
"=",
"False",
")",
":",
"def",
"_reshape",
"(",
"tensor",
",",
"shape",
")",
":",
"return",
"_np",
".",
"reshape",
"(",
"tensor",
",",
"shape",
",",
"order",
"=... | 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)
... | [
"Permute",
"dimensions",
"(",
"python",
"translation",
"of",
"original",
"matlab",
"code",
")",
"Y",
"=",
"permute",
"(",
"X",
"ORDER",
"EPS",
")",
"permutes",
"the",
"dimensions",
"of",
"the",
"TT",
"-",
"tensor",
"X",
"according",
"to",
"ORDER",
"deliver... | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/tools.py#L1167-L1273 |
oseledets/ttpy | tt/optimize/tt_min.py | min_func | def min_func(fun, bounds_min, bounds_max, d=None, rmax=10,
n0=64, nswp=10, verb=True, smooth_fun=None):
"""Find (approximate) minimal value of the function on a d-dimensional grid."""
if d is None:
d = len(bounds_min)
a = np.asanyarray(bounds_min).copy()
b = np.asanyarray(bo... | python | def min_func(fun, bounds_min, bounds_max, d=None, rmax=10,
n0=64, nswp=10, verb=True, smooth_fun=None):
"""Find (approximate) minimal value of the function on a d-dimensional grid."""
if d is None:
d = len(bounds_min)
a = np.asanyarray(bounds_min).copy()
b = np.asanyarray(bo... | [
"def",
"min_func",
"(",
"fun",
",",
"bounds_min",
",",
"bounds_max",
",",
"d",
"=",
"None",
",",
"rmax",
"=",
"10",
",",
"n0",
"=",
"64",
",",
"nswp",
"=",
"10",
",",
"verb",
"=",
"True",
",",
"smooth_fun",
"=",
"None",
")",
":",
"if",
"d",
"is... | Find (approximate) minimal value of the function on a d-dimensional grid. | [
"Find",
"(",
"approximate",
")",
"minimal",
"value",
"of",
"the",
"function",
"on",
"a",
"d",
"-",
"dimensional",
"grid",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/optimize/tt_min.py#L29-L144 |
oseledets/ttpy | tt/optimize/tt_min.py | min_tens | def min_tens(tens, rmax=10, nswp=10, verb=True, smooth_fun=None):
"""Find (approximate) minimal element in a TT-tensor."""
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... | python | def min_tens(tens, rmax=10, nswp=10, verb=True, smooth_fun=None):
"""Find (approximate) minimal element in a TT-tensor."""
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... | [
"def",
"min_tens",
"(",
"tens",
",",
"rmax",
"=",
"10",
",",
"nswp",
"=",
"10",
",",
"verb",
"=",
"True",
",",
"smooth_fun",
"=",
"None",
")",
":",
"if",
"smooth_fun",
"is",
"None",
":",
"smooth_fun",
"=",
"lambda",
"p",
",",
"lam",
":",
"(",
"ma... | Find (approximate) minimal element in a TT-tensor. | [
"Find",
"(",
"approximate",
")",
"minimal",
"element",
"in",
"a",
"TT",
"-",
"tensor",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/optimize/tt_min.py#L147-L261 |
oseledets/ttpy | tt/riemannian/riemannian.py | cores_orthogonalization_step | def cores_orthogonalization_step(coresX, dim, left_to_right=True):
"""TT-Tensor X orthogonalization step.
The function can change the shape of some cores.
"""
cc = coresX[dim]
r1, n, r2 = cc.shape
if left_to_right:
# Left to right orthogonalization step.
assert(0 <= dim < len(co... | python | def cores_orthogonalization_step(coresX, dim, left_to_right=True):
"""TT-Tensor X orthogonalization step.
The function can change the shape of some cores.
"""
cc = coresX[dim]
r1, n, r2 = cc.shape
if left_to_right:
# Left to right orthogonalization step.
assert(0 <= dim < len(co... | [
"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 orthogonal... | TT-Tensor X orthogonalization step.
The function can change the shape of some cores. | [
"TT",
"-",
"Tensor",
"X",
"orthogonalization",
"step",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/riemannian/riemannian.py#L16-L37 |
oseledets/ttpy | tt/riemannian/riemannian.py | left | def left(X, i):
"""Compute the orthogonal matrix Q_{\leq i} as defined in [1]."""
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 ... | python | def left(X, i):
"""Compute the orthogonal matrix Q_{\leq i} as defined in [1]."""
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 ... | [
"def",
"left",
"(",
"X",
",",
"i",
")",
":",
"if",
"i",
"<",
"0",
":",
"return",
"np",
".",
"ones",
"(",
"[",
"1",
",",
"1",
"]",
")",
"answ",
"=",
"np",
".",
"ones",
"(",
"[",
"1",
",",
"1",
"]",
")",
"cores",
"=",
"tt",
".",
"tensor",... | Compute the orthogonal matrix Q_{\leq i} as defined in [1]. | [
"Compute",
"the",
"orthogonal",
"matrix",
"Q_",
"{",
"\\",
"leq",
"i",
"}",
"as",
"defined",
"in",
"[",
"1",
"]",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/riemannian/riemannian.py#L42-L51 |
oseledets/ttpy | tt/riemannian/riemannian.py | right | def right(X, i):
"""Compute the orthogonal matrix Q_{\geq i} as defined in [1]."""
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... | python | def right(X, i):
"""Compute the orthogonal matrix Q_{\geq i} as defined in [1]."""
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... | [
"def",
"right",
"(",
"X",
",",
"i",
")",
":",
"if",
"i",
">",
"X",
".",
"d",
"-",
"1",
":",
"return",
"np",
".",
"ones",
"(",
"[",
"1",
",",
"1",
"]",
")",
"answ",
"=",
"np",
".",
"ones",
"(",
"[",
"1",
",",
"1",
"]",
")",
"cores",
"=... | Compute the orthogonal matrix Q_{\geq i} as defined in [1]. | [
"Compute",
"the",
"orthogonal",
"matrix",
"Q_",
"{",
"\\",
"geq",
"i",
"}",
"as",
"defined",
"in",
"[",
"1",
"]",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/riemannian/riemannian.py#L54-L63 |
oseledets/ttpy | tt/riemannian/riemannian.py | unfolding | def unfolding(tens, i):
"""Compute the i-th unfolding of a tensor."""
return reshape(tens.full(), (np.prod(tens.n[0:(i+1)]), -1)) | python | def unfolding(tens, i):
"""Compute the i-th unfolding of a tensor."""
return reshape(tens.full(), (np.prod(tens.n[0:(i+1)]), -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. | [
"Compute",
"the",
"i",
"-",
"th",
"unfolding",
"of",
"a",
"tensor",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/riemannian/riemannian.py#L66-L68 |
oseledets/ttpy | tt/riemannian/riemannian.py | _update_lhs | def _update_lhs(lhs, xCore, zCore, new_lhs):
""" Function to be called from the project()"""
# 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):
... | python | def _update_lhs(lhs, xCore, zCore, new_lhs):
""" Function to be called from the project()"""
# 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):
... | [
"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",
","... | Function to be called from the project() | [
"Function",
"to",
"be",
"called",
"from",
"the",
"project",
"()"
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/riemannian/riemannian.py#L75-L89 |
oseledets/ttpy | tt/riemannian/riemannian.py | _update_rhs | def _update_rhs(curr_rhs, xCore, zCore, new_rhs):
""" Function to be called from the project()"""
# 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):
... | python | def _update_rhs(curr_rhs, xCore, zCore, new_rhs):
""" Function to be called from the project()"""
# 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):
... | [
"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",
",... | Function to be called from the project() | [
"Function",
"to",
"be",
"called",
"from",
"the",
"project",
"()"
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/riemannian/riemannian.py#L93-L107 |
oseledets/ttpy | tt/riemannian/riemannian.py | project | def project(X, Z, use_jit=False, debug=False):
""" 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_... | python | def project(X, Z, use_jit=False, debug=False):
""" 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_... | [
"def",
"project",
"(",
"X",
",",
"Z",
",",
"use_jit",
"=",
"False",
",",
"debug",
"=",
"False",
")",
":",
"zArr",
"=",
"None",
"if",
"isinstance",
"(",
"Z",
",",
"tt",
".",
"vector",
")",
":",
"zArr",
"=",
"[",
"Z",
"]",
"else",
":",
"zArr",
... | 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... | [
"Project",
"tensor",
"Z",
"on",
"the",
"tangent",
"space",
"of",
"tensor",
"X",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/riemannian/riemannian.py#L110-L356 |
oseledets/ttpy | tt/riemannian/riemannian.py | projector_splitting_add | def projector_splitting_add(Y, delta, debug=False):
"""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."""
# Get rid of redundant ranks (they cause... | python | def projector_splitting_add(Y, delta, debug=False):
"""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."""
# Get rid of redundant ranks (they cause... | [
"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"... | 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. | [
"Compute",
"Y",
"+",
"delta",
"via",
"the",
"projector",
"splitting",
"scheme",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/riemannian/riemannian.py#L359-L432 |
oseledets/ttpy | tt/riemannian/riemannian.py | tt_qr | def tt_qr(X, left_to_right=True):
"""
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 (... | python | def tt_qr(X, left_to_right=True):
"""
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 (... | [
"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",
".",
"te... | 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... | [
"Orthogonalizes",
"a",
"TT",
"tensor",
"from",
"left",
"to",
"right",
"or",
"from",
"right",
"to",
"left",
".",
":",
"param",
":",
"X",
"-",
"thensor",
"to",
"orthogonalise",
":",
"param",
":",
"direction",
"-",
"direction",
".",
"May",
"be",
"lr",
"/"... | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/riemannian/riemannian.py#L435-L483 |
oseledets/ttpy | tt/core/utils.py | ind2sub | def ind2sub(siz, idx):
'''
Translates full-format index into tt.vector one's.
----------
Parameters:
siz - tt.vector modes
idx - full-vector index
Note: not vectorized.
'''
n = len(siz)
subs = _np.empty((n))
k = _np.cumprod(siz[:-1])
k = _np.concatenate((_np.ones(... | python | def ind2sub(siz, idx):
'''
Translates full-format index into tt.vector one's.
----------
Parameters:
siz - tt.vector modes
idx - full-vector index
Note: not vectorized.
'''
n = len(siz)
subs = _np.empty((n))
k = _np.cumprod(siz[:-1])
k = _np.concatenate((_np.ones(... | [
"def",
"ind2sub",
"(",
"siz",
",",
"idx",
")",
":",
"n",
"=",
"len",
"(",
"siz",
")",
"subs",
"=",
"_np",
".",
"empty",
"(",
"(",
"n",
")",
")",
"k",
"=",
"_np",
".",
"cumprod",
"(",
"siz",
"[",
":",
"-",
"1",
"]",
")",
"k",
"=",
"_np",
... | Translates full-format index into tt.vector one's.
----------
Parameters:
siz - tt.vector modes
idx - full-vector index
Note: not vectorized. | [
"Translates",
"full",
"-",
"format",
"index",
"into",
"tt",
".",
"vector",
"one",
"s",
".",
"----------",
"Parameters",
":",
"siz",
"-",
"tt",
".",
"vector",
"modes",
"idx",
"-",
"full",
"-",
"vector",
"index",
"Note",
":",
"not",
"vectorized",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/utils.py#L9-L25 |
oseledets/ttpy | tt/core/utils.py | gcd | def gcd(a, b):
'''Greatest common divider'''
f = _np.frompyfunc(_fractions.gcd, 2, 1)
return f(a, b) | python | def gcd(a, b):
'''Greatest common divider'''
f = _np.frompyfunc(_fractions.gcd, 2, 1)
return f(a, b) | [
"def",
"gcd",
"(",
"a",
",",
"b",
")",
":",
"f",
"=",
"_np",
".",
"frompyfunc",
"(",
"_fractions",
".",
"gcd",
",",
"2",
",",
"1",
")",
"return",
"f",
"(",
"a",
",",
"b",
")"
] | Greatest common divider | [
"Greatest",
"common",
"divider"
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/utils.py#L27-L30 |
oseledets/ttpy | tt/ksl/ksl.py | ksl | def ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000, use_normest=1):
""" 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... | python | def ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000, use_normest=1):
""" 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... | [
"def",
"ksl",
"(",
"A",
",",
"y0",
",",
"tau",
",",
"verb",
"=",
"1",
",",
"scheme",
"=",
"'symm'",
",",
"space",
"=",
"8",
",",
"rmax",
"=",
"2000",
",",
"use_normest",
"=",
"1",
")",
":",
"y0",
"=",
"y0",
".",
"round",
"(",
"1e-14",
")",
... | 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:
... | [
"Dynamical",
"tensor",
"-",
"train",
"approximation",
"based",
"on",
"projector",
"splitting",
"This",
"function",
"performs",
"one",
"step",
"of",
"dynamical",
"tensor",
"-",
"train",
"approximation",
"for",
"the",
"equation"
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/ksl/ksl.py#L7-L123 |
oseledets/ttpy | tt/ksl/ksl.py | diag_ksl | def diag_ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000):
""" 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 ::
... | python | def diag_ksl(A, y0, tau, verb=1, scheme='symm', space=8, rmax=2000):
""" 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 ::
... | [
"def",
"diag_ksl",
"(",
"A",
",",
"y0",
",",
"tau",
",",
"verb",
"=",
"1",
",",
"scheme",
"=",
"'symm'",
",",
"space",
"=",
"8",
",",
"rmax",
"=",
"2000",
")",
":",
"y0",
"=",
"y0",
".",
"round",
"(",
"1e-14",
")",
"# This will fix ranks",
"# to ... | 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... | [
"Dynamical",
"tensor",
"-",
"train",
"approximation",
"based",
"on",
"projector",
"splitting",
"This",
"function",
"performs",
"one",
"step",
"of",
"dynamical",
"tensor",
"-",
"train",
"approximation",
"with",
"diagonal",
"matrix",
"i",
".",
"e",
".",
"it",
"s... | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/ksl/ksl.py#L126-L231 |
oseledets/ttpy | tt/amen/__init__.py | amen_solve | 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):
""" Approximate linear system solution in the tensor-train (TT) format
using Alternating minimal energy (AMEN approach)
:References: Sergey Dolgov... | python | 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):
""" Approximate linear system solution in the tensor-train (TT) format
using Alternating minimal energy (AMEN approach)
:References: Sergey Dolgov... | [
"def",
"amen_solve",
"(",
"A",
",",
"f",
",",
"x0",
",",
"eps",
",",
"kickrank",
"=",
"4",
",",
"nswp",
"=",
"20",
",",
"local_prec",
"=",
"'n'",
",",
"local_iters",
"=",
"2",
",",
"local_restart",
"=",
"40",
",",
"trunc_norm",
"=",
"1",
",",
"ma... | 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... | [
"Approximate",
"linear",
"system",
"solution",
"in",
"the",
"tensor",
"-",
"train",
"(",
"TT",
")",
"format",
"using",
"Alternating",
"minimal",
"energy",
"(",
"AMEN",
"approach",
")"
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/amen/__init__.py#L7-L92 |
oseledets/ttpy | tt/core/matrix.py | matrix.T | def T(self):
"""Transposed TT-matrix"""
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) | python | def T(self):
"""Transposed TT-matrix"""
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) | [
"def",
"T",
"(",
"self",
")",
":",
"mycrs",
"=",
"matrix",
".",
"to_list",
"(",
"self",
")",
"trans_crs",
"=",
"[",
"]",
"for",
"cr",
"in",
"mycrs",
":",
"trans_crs",
".",
"append",
"(",
"_np",
".",
"transpose",
"(",
"cr",
",",
"[",
"0",
",",
"... | Transposed TT-matrix | [
"Transposed",
"TT",
"-",
"matrix"
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/matrix.py#L126-L132 |
oseledets/ttpy | tt/core/matrix.py | matrix.real | def real(self):
"""Return real part of a matrix."""
return matrix(self.tt.real(), n=self.n, m=self.m) | python | def real(self):
"""Return real part of a matrix."""
return matrix(self.tt.real(), n=self.n, m=self.m) | [
"def",
"real",
"(",
"self",
")",
":",
"return",
"matrix",
"(",
"self",
".",
"tt",
".",
"real",
"(",
")",
",",
"n",
"=",
"self",
".",
"n",
",",
"m",
"=",
"self",
".",
"m",
")"
] | Return real part of a matrix. | [
"Return",
"real",
"part",
"of",
"a",
"matrix",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/matrix.py#L134-L136 |
oseledets/ttpy | tt/core/matrix.py | matrix.imag | def imag(self):
"""Return imaginary part of a matrix."""
return matrix(self.tt.imag(), n=self.n, m=self.m) | python | def imag(self):
"""Return imaginary part of a matrix."""
return matrix(self.tt.imag(), n=self.n, m=self.m) | [
"def",
"imag",
"(",
"self",
")",
":",
"return",
"matrix",
"(",
"self",
".",
"tt",
".",
"imag",
"(",
")",
",",
"n",
"=",
"self",
".",
"n",
",",
"m",
"=",
"self",
".",
"m",
")"
] | Return imaginary part of a matrix. | [
"Return",
"imaginary",
"part",
"of",
"a",
"matrix",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/matrix.py#L138-L140 |
oseledets/ttpy | tt/core/matrix.py | matrix.c2r | def c2r(self):
"""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:`\\... | python | def c2r(self):
"""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:`\\... | [
"def",
"c2r",
"(",
"self",
")",
":",
"return",
"matrix",
"(",
"a",
"=",
"self",
".",
"tt",
".",
"__complex_op",
"(",
"'M'",
")",
",",
"n",
"=",
"_np",
".",
"concatenate",
"(",
"(",
"self",
".",
"n",
",",
"[",
"2",
"]",
")",
")",
",",
"m",
"... | 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 & -\\... | [
"Get",
"real",
"matrix",
"from",
"complex",
"one",
"suitable",
"for",
"solving",
"complex",
"linear",
"system",
"with",
"real",
"solver",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/matrix.py#L142-L159 |
oseledets/ttpy | tt/core/matrix.py | matrix.round | def round(self, eps=1e-14, rmax=100000):
""" Computes an approximation to a
TT-matrix in with accuracy EPS
"""
c = matrix()
c.tt = self.tt.round(eps, rmax)
c.n = self.n.copy()
c.m = self.m.copy()
return c | python | def round(self, eps=1e-14, rmax=100000):
""" Computes an approximation to a
TT-matrix in with accuracy EPS
"""
c = matrix()
c.tt = self.tt.round(eps, rmax)
c.n = self.n.copy()
c.m = self.m.copy()
return c | [
"def",
"round",
"(",
"self",
",",
"eps",
"=",
"1e-14",
",",
"rmax",
"=",
"100000",
")",
":",
"c",
"=",
"matrix",
"(",
")",
"c",
".",
"tt",
"=",
"self",
".",
"tt",
".",
"round",
"(",
"eps",
",",
"rmax",
")",
"c",
".",
"n",
"=",
"self",
".",
... | Computes an approximation to a
TT-matrix in with accuracy EPS | [
"Computes",
"an",
"approximation",
"to",
"a",
"TT",
"-",
"matrix",
"in",
"with",
"accuracy",
"EPS"
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/matrix.py#L317-L325 |
oseledets/ttpy | tt/core/matrix.py | matrix.copy | def copy(self):
""" Creates a copy of the TT-matrix """
c = matrix()
c.tt = self.tt.copy()
c.n = self.n.copy()
c.m = self.m.copy()
return c | python | def copy(self):
""" Creates a copy of the TT-matrix """
c = matrix()
c.tt = self.tt.copy()
c.n = self.n.copy()
c.m = self.m.copy()
return c | [
"def",
"copy",
"(",
"self",
")",
":",
"c",
"=",
"matrix",
"(",
")",
"c",
".",
"tt",
"=",
"self",
".",
"tt",
".",
"copy",
"(",
")",
"c",
".",
"n",
"=",
"self",
".",
"n",
".",
"copy",
"(",
")",
"c",
".",
"m",
"=",
"self",
".",
"m",
".",
... | Creates a copy of the TT-matrix | [
"Creates",
"a",
"copy",
"of",
"the",
"TT",
"-",
"matrix"
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/matrix.py#L327-L333 |
oseledets/ttpy | tt/core/matrix.py | matrix.full | def full(self):
""" Transforms a TT-matrix into a full matrix"""
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.arang... | python | def full(self):
""" Transforms a TT-matrix into a full matrix"""
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.arang... | [
"def",
"full",
"(",
"self",
")",
":",
"N",
"=",
"self",
".",
"n",
".",
"prod",
"(",
")",
"M",
"=",
"self",
".",
"m",
".",
"prod",
"(",
")",
"a",
"=",
"self",
".",
"tt",
".",
"full",
"(",
")",
"d",
"=",
"self",
".",
"tt",
".",
"d",
"sz",... | Transforms a TT-matrix into a full matrix | [
"Transforms",
"a",
"TT",
"-",
"matrix",
"into",
"a",
"full",
"matrix"
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/matrix.py#L355-L374 |
oseledets/ttpy | tt/amen/amen_mv.py | _svdgram | def _svdgram(A, tol=None, tol2=1e-7):
''' 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'.
... | python | def _svdgram(A, tol=None, tol2=1e-7):
''' 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'.
... | [
"def",
"_svdgram",
"(",
"A",
",",
"tol",
"=",
"None",
",",
"tol2",
"=",
"1e-7",
")",
":",
"R2",
"=",
"_np",
".",
"dot",
"(",
"_tconj",
"(",
"A",
")",
",",
"A",
")",
"[",
"u",
",",
"s",
",",
"vt",
"]",
"=",
"_np",
".",
"linalg",
".",
"svd"... | 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... | [
"Highly",
"experimental",
"acceleration",
"of",
"SVD",
"/",
"QR",
"using",
"Gram",
"matrix",
".",
"Use",
"with",
"caution",
"for",
"m",
">>",
"n",
"only!",
"function",
"[",
"u",
"s",
"r",
"]",
"=",
"_svdgram",
"(",
"A",
"[",
"tol",
"]",
")",
"u",
"... | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/amen/amen_mv.py#L29-L74 |
oseledets/ttpy | tt/amen/amen_mv.py | amen_mv | 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):
'''
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 TO... | python | 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):
'''
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 TO... | [
"def",
"amen_mv",
"(",
"A",
",",
"x",
",",
"tol",
",",
"y",
"=",
"None",
",",
"z",
"=",
"None",
",",
"nswp",
"=",
"20",
",",
"kickrank",
"=",
"4",
",",
"kickrank2",
"=",
"0",
",",
"verb",
"=",
"True",
",",
"init_qr",
"=",
"True",
",",
"renorm... | 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... | [
"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... | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/amen/amen_mv.py#L77-L477 |
oseledets/ttpy | tt/amen/amen_mv.py | _compute_next_Phi | def _compute_next_Phi(Phi_prev, x, y, direction, A=None,
extnrm=None, return_norm=True):
'''
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 i... | python | def _compute_next_Phi(Phi_prev, x, y, direction, A=None,
extnrm=None, return_norm=True):
'''
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 i... | [
"def",
"_compute_next_Phi",
"(",
"Phi_prev",
",",
"x",
",",
"y",
",",
"direction",
",",
"A",
"=",
"None",
",",
"extnrm",
"=",
"None",
",",
"return_norm",
"=",
"True",
")",
":",
"[",
"rx1",
",",
"n",
",",
"rx2",
"]",
"=",
"x",
".",
"shape",
"[",
... | 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... | [
"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"... | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/amen/amen_mv.py#L480-L608 |
oseledets/ttpy | tt/multifuncrs.py | multifuncrs | 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, ... | python | 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, ... | [
"def",
"multifuncrs",
"(",
"X",
",",
"funs",
",",
"eps",
"=",
"1E-6",
",",
"nswp",
"=",
"10",
",",
"kickrank",
"=",
"5",
",",
"y0",
"=",
"None",
",",
"rmax",
"=",
"999999",
",",
"# TODO:infinity \\",
"kicktype",
"=",
"'amr-two'",
",",
"pcatype",
"=",... | Cross approximation of a (vector-)function of several TT-tensors.
:param X: tuple of TT-tensors
:param funs: multivariate function
:param eps: accuracy | [
"Cross",
"approximation",
"of",
"a",
"(",
"vector",
"-",
")",
"function",
"of",
"several",
"TT",
"-",
"tensors",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/multifuncrs.py#L54-L425 |
oseledets/ttpy | tt/core/vector.py | vector.from_list | def from_list(a, order='F'):
"""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.
"""
d = len(a) # Number of cores
res = vector()
n = _np.zeros(d, dt... | python | def from_list(a, order='F'):
"""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.
"""
d = len(a) # Number of cores
res = vector()
n = _np.zeros(d, dt... | [
"def",
"from_list",
"(",
"a",
",",
"order",
"=",
"'F'",
")",
":",
"d",
"=",
"len",
"(",
"a",
")",
"# Number of cores",
"res",
"=",
"vector",
"(",
")",
"n",
"=",
"_np",
".",
"zeros",
"(",
"d",
",",
"dtype",
"=",
"_np",
".",
"int32",
")",
"r",
... | 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. | [
"Generate",
"TT",
"-",
"vectorr",
"object",
"from",
"given",
"TT",
"cores",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/vector.py#L82-L105 |
oseledets/ttpy | tt/core/vector.py | vector.erank | def erank(self):
""" Effective rank of the TT-vector """
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] +... | python | def erank(self):
""" Effective rank of the TT-vector """
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] +... | [
"def",
"erank",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"r",
"n",
"=",
"self",
".",
"n",
"d",
"=",
"self",
".",
"d",
"if",
"d",
"<=",
"1",
":",
"er",
"=",
"0e0",
"else",
":",
"sz",
"=",
"_np",
".",
"dot",
"(",
"n",
"*",
"r",
"[",
... | Effective rank of the TT-vector | [
"Effective",
"rank",
"of",
"the",
"TT",
"-",
"vector"
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/vector.py#L127-L145 |
oseledets/ttpy | tt/core/vector.py | vector.r2c | def r2c(self):
"""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) ... | python | def r2c(self):
"""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) ... | [
"def",
"r2c",
"(",
"self",
")",
":",
"tmp",
"=",
"self",
".",
"copy",
"(",
")",
"newcore",
"=",
"_np",
".",
"array",
"(",
"tmp",
".",
"core",
",",
"dtype",
"=",
"_np",
".",
"complex",
")",
"cr",
"=",
"newcore",
"[",
"tmp",
".",
"ps",
"[",
"-"... | 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)
... | [
"Get",
"complex",
"vector",
".",
"from",
"real",
"one",
"made",
"by",
"tensor",
".",
"c2r",
"()",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/vector.py#L282-L302 |
oseledets/ttpy | tt/core/vector.py | vector.full | def full(self, asvector=False):
"""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 -... | python | def full(self, asvector=False):
"""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 -... | [
"def",
"full",
"(",
"self",
",",
"asvector",
"=",
"False",
")",
":",
"# Generate correct size vector",
"sz",
"=",
"self",
".",
"n",
".",
"copy",
"(",
")",
"if",
"self",
".",
"r",
"[",
"0",
"]",
">",
"1",
":",
"sz",
"=",
"_np",
".",
"concatenate",
... | 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. | [
"Returns",
"full",
"array",
"(",
"uncompressed",
")",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/vector.py#L326-L352 |
oseledets/ttpy | tt/core/vector.py | vector.round | def round(self, eps=1e-14, rmax=1000000):
"""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 exa... | python | def round(self, eps=1e-14, rmax=1000000):
"""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 exa... | [
"def",
"round",
"(",
"self",
",",
"eps",
"=",
"1e-14",
",",
"rmax",
"=",
"1000000",
")",
":",
"c",
"=",
"vector",
"(",
")",
"c",
".",
"n",
"=",
"_np",
".",
"copy",
"(",
"self",
".",
"n",
")",
"c",
".",
"d",
"=",
"self",
".",
"d",
"c",
"."... | 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 =... | [
"Applies",
"TT",
"rounding",
"procedure",
"to",
"the",
"TT",
"-",
"vector",
"and",
"**",
"returns",
"rounded",
"tensor",
"**",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/vector.py#L381-L413 |
oseledets/ttpy | tt/core/vector.py | vector.rmean | def rmean(self):
""" Calculates the mean rank of a TT-vector."""
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 = ... | python | def rmean(self):
""" Calculates the mean rank of a TT-vector."""
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 = ... | [
"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",
"... | Calculates the mean rank of a TT-vector. | [
"Calculates",
"the",
"mean",
"rank",
"of",
"a",
"TT",
"-",
"vector",
"."
] | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/vector.py#L568-L578 |
oseledets/ttpy | tt/core/vector.py | vector.qtt_fft1 | def qtt_fft1(self,tol,inverse=False, bitReverse=True):
""" 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... | python | def qtt_fft1(self,tol,inverse=False, bitReverse=True):
""" 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... | [
"def",
"qtt_fft1",
"(",
"self",
",",
"tol",
",",
"inverse",
"=",
"False",
",",
"bitReverse",
"=",
"True",
")",
":",
"d",
"=",
"self",
".",
"d",
"r",
"=",
"self",
".",
"r",
".",
"copy",
"(",
")",
"y",
"=",
"self",
".",
"to_list",
"(",
"self",
... | 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... | [
"Compute",
"1D",
"(",
"inverse",
")",
"discrete",
"Fourier",
"Transform",
"in",
"the",
"QTT",
"format",
".",
":",
"param",
"tol",
":",
"error",
"tolerance",
".",
":",
"type",
"tol",
":",
"float",
":",
"param",
"inverse",
":",
"whether",
"do",
"an",
"in... | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/core/vector.py#L580-L687 |
oseledets/ttpy | tt/eigb/eigb.py | eigb | def eigb(A, y0, eps, rmax=150, nswp=20, max_full_size=1000, verb=1):
""" 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 funct... | python | def eigb(A, y0, eps, rmax=150, nswp=20, max_full_size=1000, verb=1):
""" 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 funct... | [
"def",
"eigb",
"(",
"A",
",",
"y0",
",",
"eps",
",",
"rmax",
"=",
"150",
",",
"nswp",
"=",
"20",
",",
"max_full_size",
"=",
"1000",
",",
"verb",
"=",
"1",
")",
":",
"ry",
"=",
"y0",
".",
"r",
".",
"copy",
"(",
")",
"lam",
"=",
"tt_eigb",
".... | 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... | [
"Approximate",
"computation",
"of",
"minimal",
"eigenvalues",
"in",
"tensor",
"train",
"format",
"This",
"function",
"uses",
"alternating",
"least",
"-",
"squares",
"algorithm",
"for",
"the",
"computation",
"of",
"several",
"minimal",
"eigenvalues",
".",
"If",
"yo... | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/eigb/eigb.py#L7-L65 |
oseledets/ttpy | tt/solvers.py | GMRES | def GMRES(A, u_0, b, eps=1e-6, maxit=100, m=20, _iteration=0, callback=None, verbose=0):
"""
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... | python | def GMRES(A, u_0, b, eps=1e-6, maxit=100, m=20, _iteration=0, callback=None, verbose=0):
"""
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... | [
"def",
"GMRES",
"(",
"A",
",",
"u_0",
",",
"b",
",",
"eps",
"=",
"1e-6",
",",
"maxit",
"=",
"100",
",",
"m",
"=",
"20",
",",
"_iteration",
"=",
"0",
",",
"callback",
"=",
"None",
",",
"verbose",
"=",
"0",
")",
":",
"maxitexceeded",
"=",
"False"... | 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... | [
"Flexible",
"TT",
"GMRES",
":",
"param",
"A",
":",
"matvec",
"(",
"x",
"[",
"eps",
"]",
")",
":",
"param",
"u_0",
":",
"initial",
"vector",
":",
"param",
"b",
":",
"answer",
":",
"param",
"maxit",
":",
"max",
"number",
"of",
"iterations",
":",
"par... | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/solvers.py#L10-L95 |
oseledets/ttpy | tt/completion/als.py | getRow | def getRow(leftU, rightV, jVec):
'''
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
... | python | def getRow(leftU, rightV, jVec):
'''
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
... | [
"def",
"getRow",
"(",
"leftU",
",",
"rightV",
",",
"jVec",
")",
":",
"jLeft",
"=",
"None",
"jRight",
"=",
"None",
"if",
"len",
"(",
"leftU",
")",
">",
"0",
":",
"jLeft",
"=",
"jVec",
"[",
":",
"len",
"(",
"leftU",
")",
"]",
"if",
"len",
"(",
... | 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
... | [
"Compute",
"X_",
"{",
"\\",
"geq",
"\\",
"mu",
"}",
"^T",
"\\",
"otimes",
"X_",
"{",
"leq",
"\\",
"mu",
"}",
"X_",
"{",
"\\",
"geq",
"\\",
"mu",
"}",
"=",
"V_",
"{",
"\\",
"mu",
"+",
"1",
"}",
"(",
"j_",
"{",
"\\",
"mu",
"}",
")",
"\\",
... | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/completion/als.py#L23-L56 |
oseledets/ttpy | tt/completion/als.py | orthLRFull | def orthLRFull(coreList, mu, splitResult = True):
'''
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-ortho... | python | def orthLRFull(coreList, mu, splitResult = True):
'''
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-ortho... | [
"def",
"orthLRFull",
"(",
"coreList",
",",
"mu",
",",
"splitResult",
"=",
"True",
")",
":",
"d",
"=",
"len",
"(",
"coreList",
")",
"assert",
"(",
"mu",
">=",
"0",
")",
"and",
"(",
"mu",
"<=",
"d",
")",
"resultU",
"=",
"[",
"]",
"for",
"k",
"in"... | 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... | [
"Orthogonalize",
"list",
"of",
"TT",
"-",
"cores",
".",
"Parameters",
":",
":",
"list",
":",
"coreList",
"list",
"of",
"TT",
"-",
"cores",
"(",
"stored",
"as",
"numpy",
"arrays",
")",
":",
"int",
":",
"mu",
"separating",
"index",
"for",
"left",
"and",
... | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/completion/als.py#L58-L119 |
oseledets/ttpy | tt/completion/als.py | computeFunctional | def computeFunctional(x, cooP):
'''
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]
... | python | def computeFunctional(x, cooP):
'''
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]
... | [
"def",
"computeFunctional",
"(",
"x",
",",
"cooP",
")",
":",
"indices",
"=",
"cooP",
"[",
"'indices'",
"]",
"values",
"=",
"cooP",
"[",
"'values'",
"]",
"[",
"P",
",",
"d",
"]",
"=",
"indices",
".",
"shape",
"assert",
"P",
"==",
"len",
"(",
"values... | 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... | [
"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",
".",
"P... | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/completion/als.py#L121-L154 |
oseledets/ttpy | tt/completion/als.py | ttSparseALS | def ttSparseALS(cooP, shape, x0=None, ttRank=1, tol=1e-5, maxnsweeps=20, verbose=True, alpha=1e-2):
'''
TT completion via Alternating Least Squares algorithm.
Parameters:
:dict: cooP
dictionary with two records
- 'indices': numpy.array of P x d shape,
... | python | def ttSparseALS(cooP, shape, x0=None, ttRank=1, tol=1e-5, maxnsweeps=20, verbose=True, alpha=1e-2):
'''
TT completion via Alternating Least Squares algorithm.
Parameters:
:dict: cooP
dictionary with two records
- 'indices': numpy.array of P x d shape,
... | [
"def",
"ttSparseALS",
"(",
"cooP",
",",
"shape",
",",
"x0",
"=",
"None",
",",
"ttRank",
"=",
"1",
",",
"tol",
"=",
"1e-5",
",",
"maxnsweeps",
"=",
"20",
",",
"verbose",
"=",
"True",
",",
"alpha",
"=",
"1e-2",
")",
":",
"indices",
"=",
"cooP",
"["... | 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.
... | [
"TT",
"completion",
"via",
"Alternating",
"Least",
"Squares",
"algorithm",
".",
"Parameters",
":",
":",
"dict",
":",
"cooP",
"dictionary",
"with",
"two",
"records",
"-",
"indices",
":",
"numpy",
".",
"array",
"of",
"P",
"x",
"d",
"shape",
"contains",
"inde... | train | https://github.com/oseledets/ttpy/blob/b440f6299a6338de4aea67f3d839d613f4ef1374/tt/completion/als.py#L157-L290 |
Infinidat/infi.systray | src/infi/systray/traybar.py | SysTrayIcon.update | def update(self, icon=None, hover_text=None):
""" update icon image and/or hover text """
if icon:
self._icon = icon
self._load_icon()
if hover_text:
self._hover_text = hover_text
self._refresh_icon() | python | def update(self, icon=None, hover_text=None):
""" update icon image and/or hover text """
if icon:
self._icon = icon
self._load_icon()
if hover_text:
self._hover_text = hover_text
self._refresh_icon() | [
"def",
"update",
"(",
"self",
",",
"icon",
"=",
"None",
",",
"hover_text",
"=",
"None",
")",
":",
"if",
"icon",
":",
"self",
".",
"_icon",
"=",
"icon",
"self",
".",
"_load_icon",
"(",
")",
"if",
"hover_text",
":",
"self",
".",
"_hover_text",
"=",
"... | update icon image and/or hover text | [
"update",
"icon",
"image",
"and",
"/",
"or",
"hover",
"text"
] | train | https://github.com/Infinidat/infi.systray/blob/209a6f8e5313122b35fdd2774aeceeaf9ce7c16d/src/infi/systray/traybar.py#L125-L132 |
Infinidat/infi.systray | src/infi/systray/win32_adapter.py | encode_for_locale | def encode_for_locale(s):
"""
Encode text items for system locale. If encoding fails, fall back to ASCII.
"""
try:
return s.encode(LOCALE_ENCODING, 'ignore')
except (AttributeError, UnicodeDecodeError):
return s.decode('ascii', 'ignore').encode(LOCALE_ENCODING) | python | def encode_for_locale(s):
"""
Encode text items for system locale. If encoding fails, fall back to ASCII.
"""
try:
return s.encode(LOCALE_ENCODING, 'ignore')
except (AttributeError, UnicodeDecodeError):
return s.decode('ascii', 'ignore').encode(LOCALE_ENCODING) | [
"def",
"encode_for_locale",
"(",
"s",
")",
":",
"try",
":",
"return",
"s",
".",
"encode",
"(",
"LOCALE_ENCODING",
",",
"'ignore'",
")",
"except",
"(",
"AttributeError",
",",
"UnicodeDecodeError",
")",
":",
"return",
"s",
".",
"decode",
"(",
"'ascii'",
",",... | Encode text items for system locale. If encoding fails, fall back to ASCII. | [
"Encode",
"text",
"items",
"for",
"system",
"locale",
".",
"If",
"encoding",
"fails",
"fall",
"back",
"to",
"ASCII",
"."
] | train | https://github.com/Infinidat/infi.systray/blob/209a6f8e5313122b35fdd2774aeceeaf9ce7c16d/src/infi/systray/win32_adapter.py#L86-L93 |
pbrady/fastcache | fastcache/__init__.py | lru_cache | def lru_cache(maxsize=128, typed=False, state=None, unhashable='error'):
"""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,... | python | def lru_cache(maxsize=128, typed=False, state=None, unhashable='error'):
"""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,... | [
"def",
"lru_cache",
"(",
"maxsize",
"=",
"128",
",",
"typed",
"=",
"False",
",",
"state",
"=",
"None",
",",
"unhashable",
"=",
"'error'",
")",
":",
"def",
"func_wrapper",
"(",
"func",
")",
":",
"_cached_func",
"=",
"clru_cache",
"(",
"maxsize",
",",
"t... | 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.
... | [
"Least",
"-",
"recently",
"-",
"used",
"cache",
"decorator",
"."
] | train | https://github.com/pbrady/fastcache/blob/c216def5d29808585123562b56a9a083ea337cad/fastcache/__init__.py#L30-L75 |
pbrady/fastcache | scripts/threadsafety.py | fib | def fib(n):
"""Terrible Fibonacci number generator."""
v = n.value
return v if v < 2 else fib2(PythonInt(v-1)) + fib(PythonInt(v-2)) | python | def fib(n):
"""Terrible Fibonacci number generator."""
v = n.value
return v if v < 2 else fib2(PythonInt(v-1)) + fib(PythonInt(v-2)) | [
"def",
"fib",
"(",
"n",
")",
":",
"v",
"=",
"n",
".",
"value",
"return",
"v",
"if",
"v",
"<",
"2",
"else",
"fib2",
"(",
"PythonInt",
"(",
"v",
"-",
"1",
")",
")",
"+",
"fib",
"(",
"PythonInt",
"(",
"v",
"-",
"2",
")",
")"
] | Terrible Fibonacci number generator. | [
"Terrible",
"Fibonacci",
"number",
"generator",
"."
] | train | https://github.com/pbrady/fastcache/blob/c216def5d29808585123562b56a9a083ea337cad/scripts/threadsafety.py#L43-L46 |
pbrady/fastcache | scripts/threadsafety.py | run_fib_with_clear | def run_fib_with_clear(r):
""" Run Fibonacci generator r times. """
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" %... | python | def run_fib_with_clear(r):
""" Run Fibonacci generator r times. """
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" %... | [
"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",
"(",
")",
... | Run Fibonacci generator r times. | [
"Run",
"Fibonacci",
"generator",
"r",
"times",
"."
] | train | https://github.com/pbrady/fastcache/blob/c216def5d29808585123562b56a9a083ea337cad/scripts/threadsafety.py#L59-L67 |
pbrady/fastcache | scripts/threadsafety.py | run_fib_with_stats | def run_fib_with_stats(r):
""" Run Fibonacci generator r times. """
for i in range(r):
res = fib(PythonInt(FIB))
if RESULT != res:
raise ValueError("Expected %d, Got %d" % (RESULT, res)) | python | def run_fib_with_stats(r):
""" Run Fibonacci generator r times. """
for i in range(r):
res = fib(PythonInt(FIB))
if RESULT != res:
raise ValueError("Expected %d, Got %d" % (RESULT, res)) | [
"def",
"run_fib_with_stats",
"(",
"r",
")",
":",
"for",
"i",
"in",
"range",
"(",
"r",
")",
":",
"res",
"=",
"fib",
"(",
"PythonInt",
"(",
"FIB",
")",
")",
"if",
"RESULT",
"!=",
"res",
":",
"raise",
"ValueError",
"(",
"\"Expected %d, Got %d\"",
"%",
"... | Run Fibonacci generator r times. | [
"Run",
"Fibonacci",
"generator",
"r",
"times",
"."
] | train | https://github.com/pbrady/fastcache/blob/c216def5d29808585123562b56a9a083ea337cad/scripts/threadsafety.py#L69-L74 |
FraBle/python-sutime | sutime/sutime.py | SUTime.parse | def parse(self, input_str, reference_date=""):
"""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.
... | python | def parse(self, input_str, reference_date=""):
"""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.
... | [
"def",
"parse",
"(",
"self",
",",
"input_str",
",",
"reference_date",
"=",
"\"\"",
")",
":",
"if",
"not",
"jpype",
".",
"isThreadAttachedToJVM",
"(",
")",
":",
"jpype",
".",
"attachThreadToJVM",
"(",
")",
"if",
"reference_date",
":",
"return",
"json",
".",... | 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... | [
"Parses",
"datetime",
"information",
"out",
"of",
"string",
"input",
"."
] | train | https://github.com/FraBle/python-sutime/blob/2b36828cd1d215c472572d253cd6c56271d71169/sutime/sutime.py#L143-L160 |
aichaos/rivescript-python | rivescript/brain.py | Brain.format_message | def format_message(self, msg, botreply=False):
"""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 formattin... | python | def format_message(self, msg, botreply=False):
"""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 formattin... | [
"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",
")",
":",
... | 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.... | [
"Format",
"a",
"user",
"s",
"message",
"for",
"safe",
"processing",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/brain.py#L104-L141 |
aichaos/rivescript-python | rivescript/brain.py | Brain._getreply | def _getreply(self, user, msg, context='normal', step=0, ignore_object_errors=True):
"""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 repl... | python | def _getreply(self, user, msg, context='normal', step=0, ignore_object_errors=True):
"""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 repl... | [
"def",
"_getreply",
"(",
"self",
",",
"user",
",",
"msg",
",",
"context",
"=",
"'normal'",
",",
"step",
"=",
"0",
",",
"ignore_object_errors",
"=",
"True",
")",
":",
"# Needed to sort replies?",
"if",
"'topics'",
"not",
"in",
"self",
".",
"master",
".",
... | 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.... | [
"The",
"internal",
"reply",
"getter",
"function",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/brain.py#L143-L419 |
aichaos/rivescript-python | rivescript/brain.py | Brain.reply_regexp | def reply_regexp(self, user, regexp):
"""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."""
if regexp in self.... | python | def reply_regexp(self, user, regexp):
"""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."""
if regexp in self.... | [
"def",
"reply_regexp",
"(",
"self",
",",
"user",
",",
"regexp",
")",
":",
"if",
"regexp",
"in",
"self",
".",
"master",
".",
"_regexc",
"[",
"\"trigger\"",
"]",
":",
"# Already compiled this one!",
"return",
"self",
".",
"master",
".",
"_regexc",
"[",
"\"tr... | 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. | [
"Prepares",
"a",
"trigger",
"for",
"the",
"regular",
"expression",
"engine",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/brain.py#L421-L507 |
aichaos/rivescript-python | rivescript/brain.py | Brain.do_expand_array | def do_expand_array(self, array_name, depth=0):
"""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... | python | def do_expand_array(self, array_name, depth=0):
"""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... | [
"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... | 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... | [
"Do",
"recurrent",
"array",
"expansion",
"returning",
"a",
"set",
"of",
"keywords",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/brain.py#L509-L531 |
aichaos/rivescript-python | rivescript/brain.py | Brain.expand_array | def expand_array(self, array_name):
"""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."""
ret = self.master._array[array_name] if array_name ... | python | def expand_array(self, array_name):
"""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."""
ret = self.master._array[array_name] if array_name ... | [
"def",
"expand_array",
"(",
"self",
",",
"array_name",
")",
":",
"ret",
"=",
"self",
".",
"master",
".",
"_array",
"[",
"array_name",
"]",
"if",
"array_name",
"in",
"self",
".",
"master",
".",
"_array",
"else",
"[",
"]",
"try",
":",
"ret",
"=",
"self... | 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. | [
"Expand",
"variables",
"and",
"return",
"a",
"set",
"of",
"keywords",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/brain.py#L533-L546 |
aichaos/rivescript-python | rivescript/brain.py | Brain.process_tags | def process_tags(self, user, msg, reply, st=[], bst=[], depth=0, ignore_object_errors=True):
"""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... | python | def process_tags(self, user, msg, reply, st=[], bst=[], depth=0, ignore_object_errors=True):
"""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... | [
"def",
"process_tags",
"(",
"self",
",",
"user",
",",
"msg",
",",
"reply",
",",
"st",
"=",
"[",
"]",
",",
"bst",
"=",
"[",
"]",
",",
"depth",
"=",
"0",
",",
"ignore_object_errors",
"=",
"True",
")",
":",
"stars",
"=",
"[",
"''",
"]",
"stars",
"... | 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>``... | [
"Post",
"process",
"tags",
"in",
"a",
"message",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/brain.py#L548-L782 |
aichaos/rivescript-python | rivescript/brain.py | Brain.substitute | def substitute(self, msg, kind):
"""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``.
"""
# Safety checking.
if 'lists' not in s... | python | def substitute(self, msg, kind):
"""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``.
"""
# Safety checking.
if 'lists' not in s... | [
"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 RiveSc... | 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``. | [
"Run",
"a",
"kind",
"of",
"substitution",
"on",
"a",
"message",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/brain.py#L784-L830 |
aichaos/rivescript-python | rivescript/python.py | PyRiveObjects.load | def load(self, name, code):
"""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.
"""
# We need to make a dynamic Python method.
source = ... | python | def load(self, name, code):
"""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.
"""
# We need to make a dynamic Python method.
source = ... | [
"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\"",
... | 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. | [
"Prepare",
"a",
"Python",
"code",
"object",
"given",
"by",
"the",
"RiveScript",
"interpreter",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/python.py#L41-L59 |
aichaos/rivescript-python | rivescript/python.py | PyRiveObjects.call | def call(self, rs, name, user, fields):
"""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 w... | python | def call(self, rs, name, user, fields):
"""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 w... | [
"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",
"[... | 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... | [
"Invoke",
"a",
"previously",
"loaded",
"object",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/python.py#L61-L82 |
aichaos/rivescript-python | rivescript/inheritance.py | get_topic_triggers | def get_topic_triggers(rs, topic, thats, depth=0, inheritance=0, inherited=False):
"""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... | python | def get_topic_triggers(rs, topic, thats, depth=0, inheritance=0, inherited=False):
"""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... | [
"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",
".",
... | 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... | [
"Recursively",
"scan",
"a",
"topic",
"and",
"return",
"a",
"list",
"of",
"all",
"triggers",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/inheritance.py#L8-L113 |
aichaos/rivescript-python | rivescript/inheritance.py | get_topic_tree | def get_topic_tree(rs, topic, depth=0):
"""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.
"""
# Break if we're in too deep.
if depth > rs._de... | python | def get_topic_tree(rs, topic, depth=0):
"""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.
"""
# Break if we're in too deep.
if depth > rs._de... | [
"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",
"[",
"]... | 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. | [
"Given",
"one",
"topic",
"get",
"the",
"list",
"of",
"all",
"included",
"/",
"inherited",
"topics",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/inheritance.py#L115-L144 |
aichaos/rivescript-python | rivescript/utils.py | word_count | def word_count(trigger, all=False):
"""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."... | python | def word_count(trigger, all=False):
"""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",
"word_count",
"(",
"trigger",
",",
"all",
"=",
"False",
")",
":",
"words",
"=",
"[",
"]",
"if",
"all",
":",
"words",
"=",
"re",
".",
"split",
"(",
"RE",
".",
"ws",
",",
"trigger",
")",
"else",
":",
"words",
"=",
"re",
".",
"split",
"(",
... | 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. | [
"Count",
"the",
"words",
"that",
"aren",
"t",
"wildcards",
"or",
"options",
"in",
"a",
"trigger",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/utils.py#L14-L33 |
aichaos/rivescript-python | rivescript/utils.py | string_format | def string_format(msg, method):
"""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.
"""
if method == "uppercase":
return... | python | def string_format(msg, method):
"""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.
"""
if method == "uppercase":
return... | [
"def",
"string_format",
"(",
"msg",
",",
"method",
")",
":",
"if",
"method",
"==",
"\"uppercase\"",
":",
"return",
"msg",
".",
"upper",
"(",
")",
"elif",
"method",
"==",
"\"lowercase\"",
":",
"return",
"msg",
".",
"lower",
"(",
")",
"elif",
"method",
"... | 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. | [
"Format",
"a",
"string",
"(",
"upper",
"lower",
"formal",
"sentence",
")",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/utils.py#L63-L79 |
aichaos/rivescript-python | eg/perl-objects/perl.py | PerlObject.load | def load(self, name, code):
"""Prepare a Perl code object given by the RS interpreter."""
source = "\n".join(code)
self._objects[name] = source | python | def load(self, name, code):
"""Prepare a Perl code object given by the RS interpreter."""
source = "\n".join(code)
self._objects[name] = source | [
"def",
"load",
"(",
"self",
",",
"name",
",",
"code",
")",
":",
"source",
"=",
"\"\\n\"",
".",
"join",
"(",
"code",
")",
"self",
".",
"_objects",
"[",
"name",
"]",
"=",
"source"
] | Prepare a Perl code object given by the RS interpreter. | [
"Prepare",
"a",
"Perl",
"code",
"object",
"given",
"by",
"the",
"RS",
"interpreter",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/eg/perl-objects/perl.py#L13-L17 |
aichaos/rivescript-python | eg/twilio/app.py | hello_rivescript | def hello_rivescript():
"""Receive an inbound SMS and send a reply from 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,... | python | def hello_rivescript():
"""Receive an inbound SMS and send a reply from 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,... | [
"def",
"hello_rivescript",
"(",
")",
":",
"from_number",
"=",
"request",
".",
"values",
".",
"get",
"(",
"\"From\"",
",",
"\"unknown\"",
")",
"message",
"=",
"request",
".",
"values",
".",
"get",
"(",
"\"Body\"",
")",
"reply",
"=",
"\"(Internal error)\"",
... | Receive an inbound SMS and send a reply from RiveScript. | [
"Receive",
"an",
"inbound",
"SMS",
"and",
"send",
"a",
"reply",
"from",
"RiveScript",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/eg/twilio/app.py#L28-L42 |
aichaos/rivescript-python | rivescript/interactive.py | interactive_mode | def interactive_mode():
"""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
#... | python | def interactive_mode():
"""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
#... | [
"def",
"interactive_mode",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"RiveScript interactive mode.\"",
")",
"parser",
".",
"add_argument",
"(",
"\"--debug\"",
",",
"\"-d\"",
",",
"help",
"=",
"\"Enable debug logging ... | 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... | [
"The",
"built",
"-",
"in",
"RiveScript",
"Interactive",
"Mode",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/interactive.py#L62-L262 |
aichaos/rivescript-python | eg/json-server/server.py | reply | def reply():
"""Fetch a reply from RiveScript.
Parameters (JSON):
* username
* message
* vars
"""
params = request.json
if not params:
return jsonify({
"status": "error",
"error": "Request must be of the application/json type!",
})
username =... | python | def reply():
"""Fetch a reply from RiveScript.
Parameters (JSON):
* username
* message
* vars
"""
params = request.json
if not params:
return jsonify({
"status": "error",
"error": "Request must be of the application/json type!",
})
username =... | [
"def",
"reply",
"(",
")",
":",
"params",
"=",
"request",
".",
"json",
"if",
"not",
"params",
":",
"return",
"jsonify",
"(",
"{",
"\"status\"",
":",
"\"error\"",
",",
"\"error\"",
":",
"\"Request must be of the application/json type!\"",
",",
"}",
")",
"usernam... | Fetch a reply from RiveScript.
Parameters (JSON):
* username
* message
* vars | [
"Fetch",
"a",
"reply",
"from",
"RiveScript",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/eg/json-server/server.py#L24-L66 |
aichaos/rivescript-python | eg/json-server/server.py | index | def index(path=None):
"""On all other routes, just return an example `curl` command."""
payload = {
"username": "soandso",
"message": "Hello bot",
"vars": {
"name": "Soandso",
}
}
return Response(r"""Usage: curl -i \
-H "Content-Type: application/json" \
... | python | def index(path=None):
"""On all other routes, just return an example `curl` command."""
payload = {
"username": "soandso",
"message": "Hello bot",
"vars": {
"name": "Soandso",
}
}
return Response(r"""Usage: curl -i \
-H "Content-Type: application/json" \
... | [
"def",
"index",
"(",
"path",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"\"username\"",
":",
"\"soandso\"",
",",
"\"message\"",
":",
"\"Hello bot\"",
",",
"\"vars\"",
":",
"{",
"\"name\"",
":",
"\"Soandso\"",
",",
"}",
"}",
"return",
"Response",
"(",
"r... | On all other routes, just return an example `curl` command. | [
"On",
"all",
"other",
"routes",
"just",
"return",
"an",
"example",
"curl",
"command",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/eg/json-server/server.py#L70-L83 |
aichaos/rivescript-python | contrib/redis/rivescript_redis.py | RedisSessionManager._key | def _key(self, username, frozen=False):
"""Translate a username into a key for Redis."""
if frozen:
return self.frozen + username
return self.prefix + username | python | def _key(self, username, frozen=False):
"""Translate a username into a key for Redis."""
if frozen:
return self.frozen + username
return self.prefix + username | [
"def",
"_key",
"(",
"self",
",",
"username",
",",
"frozen",
"=",
"False",
")",
":",
"if",
"frozen",
":",
"return",
"self",
".",
"frozen",
"+",
"username",
"return",
"self",
".",
"prefix",
"+",
"username"
] | Translate a username into a key for Redis. | [
"Translate",
"a",
"username",
"into",
"a",
"key",
"for",
"Redis",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/contrib/redis/rivescript_redis.py#L42-L46 |
aichaos/rivescript-python | contrib/redis/rivescript_redis.py | RedisSessionManager._get_user | def _get_user(self, username):
"""Custom helper method to retrieve a user's data from Redis."""
data = self.client.get(self._key(username))
if data is None:
return None
return json.loads(data.decode()) | python | def _get_user(self, username):
"""Custom helper method to retrieve a user's data from Redis."""
data = self.client.get(self._key(username))
if data is None:
return None
return json.loads(data.decode()) | [
"def",
"_get_user",
"(",
"self",
",",
"username",
")",
":",
"data",
"=",
"self",
".",
"client",
".",
"get",
"(",
"self",
".",
"_key",
"(",
"username",
")",
")",
"if",
"data",
"is",
"None",
":",
"return",
"None",
"return",
"json",
".",
"loads",
"(",... | Custom helper method to retrieve a user's data from Redis. | [
"Custom",
"helper",
"method",
"to",
"retrieve",
"a",
"user",
"s",
"data",
"from",
"Redis",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/contrib/redis/rivescript_redis.py#L48-L53 |
aichaos/rivescript-python | rivescript/sorting.py | sort_trigger_set | def sort_trigger_set(triggers, exclude_previous=True, say=None):
"""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
... | python | def sort_trigger_set(triggers, exclude_previous=True, say=None):
"""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
... | [
"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"... | 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
... | [
"Sort",
"a",
"group",
"of",
"triggers",
"in",
"optimal",
"sorting",
"order",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/sorting.py#L52-L118 |
aichaos/rivescript-python | rivescript/sorting.py | sort_list | def sort_list(items):
"""Sort a simple list by number of words and length."""
# 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(ite... | python | def sort_list(items):
"""Sort a simple list by number of words and length."""
# 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(ite... | [
"def",
"sort_list",
"(",
"items",
")",
":",
"# Track by number of words.",
"track",
"=",
"{",
"}",
"def",
"by_length",
"(",
"word1",
",",
"word2",
")",
":",
"return",
"len",
"(",
"word2",
")",
"-",
"len",
"(",
"word1",
")",
"# Loop through each item.",
"fo... | Sort a simple list by number of words and length. | [
"Sort",
"a",
"simple",
"list",
"by",
"number",
"of",
"words",
"and",
"length",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/sorting.py#L120-L143 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.load_directory | def load_directory(self, directory, ext=None):
"""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 `... | python | def load_directory(self, directory, ext=None):
"""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 `... | [
"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"... | 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"]``. | [
"Load",
"RiveScript",
"documents",
"from",
"a",
"directory",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L165-L192 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.load_file | def load_file(self, filename):
"""Load and parse a RiveScript document.
:param str filename: The path to a RiveScript file.
"""
self._say("Loading file: " + filename)
fh = codecs.open(filename, 'r', 'utf-8')
lines = fh.readlines()
fh.close()
self._sa... | python | def load_file(self, filename):
"""Load and parse a RiveScript document.
:param str filename: The path to a RiveScript file.
"""
self._say("Loading file: " + filename)
fh = codecs.open(filename, 'r', 'utf-8')
lines = fh.readlines()
fh.close()
self._sa... | [
"def",
"load_file",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"_say",
"(",
"\"Loading file: \"",
"+",
"filename",
")",
"fh",
"=",
"codecs",
".",
"open",
"(",
"filename",
",",
"'r'",
",",
"'utf-8'",
")",
"lines",
"=",
"fh",
".",
"readlines",
... | Load and parse a RiveScript document.
:param str filename: The path to a RiveScript file. | [
"Load",
"and",
"parse",
"a",
"RiveScript",
"document",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L194-L206 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.stream | def stream(self, code):
"""Stream in RiveScript source code dynamically.
:param code: Either a string containing RiveScript code or an array of
lines of RiveScript code.
"""
self._say("Streaming code.")
if type(code) in [str, text_type]:
code = code.split... | python | def stream(self, code):
"""Stream in RiveScript source code dynamically.
:param code: Either a string containing RiveScript code or an array of
lines of RiveScript code.
"""
self._say("Streaming code.")
if type(code) in [str, text_type]:
code = code.split... | [
"def",
"stream",
"(",
"self",
",",
"code",
")",
":",
"self",
".",
"_say",
"(",
"\"Streaming code.\"",
")",
"if",
"type",
"(",
"code",
")",
"in",
"[",
"str",
",",
"text_type",
"]",
":",
"code",
"=",
"code",
".",
"split",
"(",
"\"\\n\"",
")",
"self",... | Stream in RiveScript source code dynamically.
:param code: Either a string containing RiveScript code or an array of
lines of RiveScript code. | [
"Stream",
"in",
"RiveScript",
"source",
"code",
"dynamically",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L208-L217 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript._parse | def _parse(self, fname, code):
"""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.
"""
# Get the "abstract syntax tree"
ast = self._parser.parse(fname, co... | python | def _parse(self, fname, code):
"""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.
"""
# Get the "abstract syntax tree"
ast = self._parser.parse(fname, co... | [
"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"... | 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. | [
"Parse",
"RiveScript",
"code",
"into",
"memory",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L219-L281 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.deparse | def deparse(self):
"""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... | python | def deparse(self):
"""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... | [
"def",
"deparse",
"(",
"self",
")",
":",
"# Data to return.",
"result",
"=",
"{",
"\"begin\"",
":",
"{",
"\"global\"",
":",
"{",
"}",
",",
"\"var\"",
":",
"{",
"}",
",",
"\"sub\"",
":",
"{",
"}",
",",
"\"person\"",
":",
"{",
"}",
",",
"\"array\"",
... | 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... | [
"Dump",
"the",
"in",
"-",
"memory",
"RiveScript",
"brain",
"as",
"a",
"Python",
"data",
"structure",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L283-L346 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.write | def write(self, fh, deparsed=None):
"""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 da... | python | def write(self, fh, deparsed=None):
"""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 da... | [
"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\"",
... | 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... | [
"Write",
"the",
"currently",
"parsed",
"RiveScript",
"data",
"into",
"a",
"file",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L348-L448 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript._write_triggers | def _write_triggers(self, fh, triggers, indent=""):
"""Write triggers to a file handle.
Parameters:
fh (file): file object.
triggers (list): list of triggers to write.
indent (str): indentation for each line.
"""
for trig in triggers:
fh.... | python | def _write_triggers(self, fh, triggers, indent=""):
"""Write triggers to a file handle.
Parameters:
fh (file): file object.
triggers (list): list of triggers to write.
indent (str): indentation for each line.
"""
for trig in triggers:
fh.... | [
"def",
"_write_triggers",
"(",
"self",
",",
"fh",
",",
"triggers",
",",
"indent",
"=",
"\"\"",
")",
":",
"for",
"trig",
"in",
"triggers",
":",
"fh",
".",
"write",
"(",
"indent",
"+",
"\"+ \"",
"+",
"self",
".",
"_write_wrapped",
"(",
"trig",
"[",
"\"... | Write triggers to a file handle.
Parameters:
fh (file): file object.
triggers (list): list of triggers to write.
indent (str): indentation for each line. | [
"Write",
"triggers",
"to",
"a",
"file",
"handle",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L450-L475 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript._write_wrapped | def _write_wrapped(self, line, sep=" ", indent="", width=78):
"""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).
... | python | def _write_wrapped(self, line, sep=" ", indent="", width=78):
"""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).
... | [
"def",
"_write_wrapped",
"(",
"self",
",",
"line",
",",
"sep",
"=",
"\" \"",
",",
"indent",
"=",
"\"\"",
",",
"width",
"=",
"78",
")",
":",
"words",
"=",
"line",
".",
"split",
"(",
"sep",
")",
"lines",
"=",
"[",
"]",
"line",
"=",
"\"\"",
"buf",
... | 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.
... | [
"Word",
"-",
"wrap",
"a",
"line",
"of",
"RiveScript",
"code",
"for",
"being",
"written",
"to",
"a",
"file",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L477-L515 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.sort_replies | def sort_replies(self, thats=False):
"""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!
"""
# (R... | python | def sort_replies(self, thats=False):
"""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!
"""
# (R... | [
"def",
"sort_replies",
"(",
"self",
",",
"thats",
"=",
"False",
")",
":",
"# (Re)initialize the sort cache.",
"self",
".",
"_sorted",
"[",
"\"topics\"",
"]",
"=",
"{",
"}",
"self",
".",
"_sorted",
"[",
"\"thats\"",
"]",
"=",
"{",
"}",
"self",
".",
"_say"... | 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! | [
"Sort",
"the",
"loaded",
"triggers",
"in",
"memory",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L521-L555 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.set_handler | def set_handler(self, 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 rivescrip... | python | def set_handler(self, 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 rivescrip... | [
"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",
"]",
... | 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... | [
"Define",
"a",
"custom",
"language",
"handler",
"for",
"RiveScript",
"objects",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L561-L593 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.set_subroutine | def set_subroutine(self, name, code):
"""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 fun... | python | def set_subroutine(self, name, code):
"""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 fun... | [
"def",
"set_subroutine",
"(",
"self",
",",
"name",
",",
"code",
")",
":",
"# Do we have a Python handler?",
"if",
"'python'",
"in",
"self",
".",
"_handlers",
":",
"self",
".",
"_handlers",
"[",
"'python'",
"]",
".",
"_objects",
"[",
"name",
"]",
"=",
"code... | 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... | [
"Define",
"a",
"Python",
"object",
"from",
"your",
"program",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L595-L615 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.set_global | def set_global(self, 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.
"""
if val... | python | def set_global(self, 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.
"""
if val... | [
"def",
"set_global",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"# Unset the variable.",
"if",
"name",
"in",
"self",
".",
"_global",
":",
"del",
"self",
".",
"_global",
"[",
"name",
"]",
"self",
".",
"_global",
... | 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. | [
"Set",
"a",
"global",
"variable",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L617-L630 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.set_variable | def set_variable(self, 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.
"""
if value i... | python | def set_variable(self, 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.
"""
if value i... | [
"def",
"set_variable",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"# Unset the variable.",
"if",
"name",
"in",
"self",
".",
"_var",
":",
"del",
"self",
".",
"_var",
"[",
"name",
"]",
"self",
".",
"_var",
"[",
... | 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. | [
"Set",
"a",
"bot",
"variable",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L640-L653 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.set_substitution | def set_substitution(self, 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.
"""
if rep ... | python | def set_substitution(self, 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.
"""
if rep ... | [
"def",
"set_substitution",
"(",
"self",
",",
"what",
",",
"rep",
")",
":",
"if",
"rep",
"is",
"None",
":",
"# Unset the variable.",
"if",
"what",
"in",
"self",
".",
"_subs",
":",
"del",
"self",
".",
"_subs",
"[",
"what",
"]",
"self",
".",
"_subs",
"[... | 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. | [
"Set",
"a",
"substitution",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L663-L676 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.set_person | def set_person(self, 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.
"""
if ... | python | def set_person(self, 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.
"""
if ... | [
"def",
"set_person",
"(",
"self",
",",
"what",
",",
"rep",
")",
":",
"if",
"rep",
"is",
"None",
":",
"# Unset the variable.",
"if",
"what",
"in",
"self",
".",
"_person",
":",
"del",
"self",
".",
"_person",
"[",
"what",
"]",
"self",
".",
"_person",
"[... | 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. | [
"Set",
"a",
"person",
"substitution",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L678-L691 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.set_uservar | def set_uservar(self, 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.
"""... | python | def set_uservar(self, 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_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. | [
"Set",
"a",
"variable",
"for",
"a",
"user",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L693-L702 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.set_uservars | def set_uservars(self, user, data=None):
"""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 ... | python | def set_uservars(self, user, data=None):
"""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 ... | [
"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.",
... | 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... | [
"Set",
"many",
"variables",
"for",
"a",
"user",
"or",
"set",
"many",
"variables",
"for",
"many",
"users",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L704-L769 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.get_uservar | def get_uservar(self, 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 r... | python | def get_uservar(self, 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 r... | [
"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",... | 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... | [
"Get",
"a",
"variable",
"about",
"a",
"user",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L771-L787 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.get_uservars | def get_uservars(self, user=None):
"""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 ``use... | python | def get_uservars(self, user=None):
"""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 ``use... | [
"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 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... | [
"Get",
"all",
"variables",
"about",
"a",
"user",
"(",
"or",
"all",
"users",
")",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L789-L809 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.clear_uservars | def clear_uservars(self, user=None):
"""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.
"""
if user is None:
# All the users!
self._sess... | python | def clear_uservars(self, user=None):
"""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.
"""
if user is None:
# All the users!
self._sess... | [
"def",
"clear_uservars",
"(",
"self",
",",
"user",
"=",
"None",
")",
":",
"if",
"user",
"is",
"None",
":",
"# All the users!",
"self",
".",
"_session",
".",
"reset_all",
"(",
")",
"else",
":",
"# Just this one.",
"self",
".",
"_session",
".",
"reset",
"(... | 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. | [
"Delete",
"all",
"variables",
"about",
"a",
"user",
"(",
"or",
"all",
"users",
")",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L811-L823 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.trigger_info | def trigger_info(self, trigger=None, dump=False):
"""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... | python | def trigger_info(self, trigger=None, dump=False):
"""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... | [
"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",
... | 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... | [
"Get",
"information",
"about",
"a",
"trigger",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L858-L905 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.current_user | def current_user(self):
"""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).
... | python | def current_user(self):
"""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).
... | [
"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"... | 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... | [
"Retrieve",
"the",
"user",
"ID",
"of",
"the",
"current",
"user",
"talking",
"to",
"your",
"bot",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L907-L920 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript.reply | def reply(self, user, msg, errors_as_replies=True):
"""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 variabl... | python | def reply(self, user, msg, errors_as_replies=True):
"""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 variabl... | [
"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... | [
"Fetch",
"a",
"reply",
"from",
"the",
"RiveScript",
"brain",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L926-L947 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript._precompile_substitution | def _precompile_substitution(self, kind, pattern):
"""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
... | python | def _precompile_substitution(self, kind, pattern):
"""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
... | [
"def",
"_precompile_substitution",
"(",
"self",
",",
"kind",
",",
"pattern",
")",
":",
"if",
"pattern",
"not",
"in",
"self",
".",
"_regexc",
"[",
"kind",
"]",
":",
"qm",
"=",
"re",
".",
"escape",
"(",
"pattern",
")",
"self",
".",
"_regexc",
"[",
"kin... | 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``.
:... | [
"Pre",
"-",
"compile",
"the",
"regexp",
"for",
"a",
"substitution",
"pattern",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L949-L967 |
aichaos/rivescript-python | rivescript/rivescript.py | RiveScript._precompile_regexp | def _precompile_regexp(self, trigger):
"""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 ... | python | def _precompile_regexp(self, trigger):
"""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 ... | [
"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\"",
"... | 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. | [
"Precompile",
"the",
"regex",
"for",
"most",
"triggers",
"."
] | train | https://github.com/aichaos/rivescript-python/blob/b55c820cf02a194605fd66af1f070e239f84ed31/rivescript/rivescript.py#L969-L986 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.