code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
'''Decipher string using Columnar Transposition cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
plaintext = ColTrans('GERMAN').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string.
'''
string = self.remove_punctuation(string)
ret = ['_']*len(string)
L,M = len(string),len(self.keyword)
ind = self.unsortind(self.keyword)
upto = 0
for i in range(len(self.keyword)):
thiscollen = (int)(L/M)
if ind[i]< L%M: thiscollen += 1
ret[ind[i]::M] = string[upto:upto+thiscollen]
upto += thiscollen
return ''.join(ret) | def decipher(self,string) | Decipher string using Columnar Transposition cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
plaintext = ColTrans('GERMAN').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string. | 5.39121 | 3.107518 | 1.734892 |
if not keep_punct: string = self.remove_punctuation(string)
return ''.join(self.buildfence(string, self.key)) | def encipher(self,string,keep_punct=False) | Encipher string using Railfence cipher according to initialised key.
Example::
ciphertext = Railfence(3).encipher(plaintext)
:param string: The string to encipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is False.
:returns: The enciphered string. | 6.850749 | 7.962504 | 0.860376 |
if not keep_punct: string = self.remove_punctuation(string)
ind = range(len(string))
pos = self.buildfence(ind, self.key)
return ''.join(string[pos.index(i)] for i in ind) | def decipher(self,string,keep_punct=False) | Decipher string using Railfence cipher according to initialised key.
Example::
plaintext = Railfence(3).decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is False.
:returns: The deciphered string. | 6.085458 | 6.059838 | 1.004228 |
if not keep_punct: string = self.remove_punctuation(string)
ret = ''
for c in string:
if c.isalpha(): ret += self.i2a(self.inva*(self.a2i(c) - self.b))
else: ret += c
return ret | def decipher(self,string,keep_punct=False) | Decipher string using affine cipher according to initialised key.
Example::
plaintext = Affine(a,b).decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is False.
:returns: The deciphered string. | 4.24877 | 4.874681 | 0.8716 |
string = self.remove_punctuation(string)
ret = ''
for (i,c) in enumerate(string):
if i<len(self.key): offset = self.a2i(self.key[i])
else: offset = self.a2i(string[i-len(self.key)])
ret += self.i2a(self.a2i(c)+offset)
return ret | def encipher(self,string) | Encipher string using Autokey cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Autokey('HELLO').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string. | 3.381388 | 3.573111 | 0.946343 |
string = self.remove_punctuation(string)
step1 = self.pb.encipher(string)
evens = step1[::2]
odds = step1[1::2]
step2 = []
for i in range(0,len(string),self.period):
step2 += evens[i:int(i+self.period)]
step2 += odds[i:int(i+self.period)]
return self.pb.decipher(''.join(step2)) | def encipher(self,string) | Encipher string using Bifid cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
ciphertext = Bifid('phqgmeaylnofdxkrcvszwbuti',5).encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string. | 2.932609 | 3.346096 | 0.876427 |
ret = ''
string = string.upper()
rowseq,colseq = [],[]
# take blocks of length period, reform rowseq,colseq from them
for i in range(0,len(string),self.period):
tempseq = []
for j in range(0,self.period):
if i+j >= len(string): continue
tempseq.append(int(self.key.index(string[i + j]) / 5))
tempseq.append(int(self.key.index(string[i + j]) % 5))
rowseq.extend(tempseq[0:int(len(tempseq)/2)])
colseq.extend(tempseq[int(len(tempseq)/2):])
for i in range(len(rowseq)):
ret += self.key[rowseq[i]*5 + colseq[i]]
return ret | def decipher(self,string) | Decipher string using Bifid cipher according to initialised key. Punctuation and whitespace
are removed from the input.
Example::
plaintext = Bifid('phqgmeaylnofdxkrcvszwbuti',5).decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string. | 2.929392 | 3.107766 | 0.942604 |
# if we have not yet calculated the inverse key, calculate it now
if self.invkey == '':
for i in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
self.invkey += self.i2a(self.key.index(i))
if not keep_punct: string = self.remove_punctuation(string)
ret = ''
for c in string.upper():
if c.isalpha(): ret += self.invkey[self.a2i(c)]
else: ret += c
return ret | def decipher(self,string,keep_punct=False) | Decipher string using Simple Substitution cipher according to initialised key.
Example::
plaintext = SimpleSubstitution('AJPCZWRLFBDKOTYUQGENHXMIVS').decipher(ciphertext)
:param string: The string to decipher.
:param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default is False.
:returns: The deciphered string. | 3.425168 | 3.598523 | 0.951826 |
if hasattr(a, '__kron__'):
return a.__kron__(b)
if a is None:
return b
else:
raise ValueError(
'Kron is waiting for two TT-vectors or two TT-matrices') | def kron(a, b) | Kronecker product of two TT-matrices or two TT-vectors | 7.115146 | 5.090212 | 1.397809 |
if hasattr(a, '__dot__'):
return a.__dot__(b)
if a is None:
return b
else:
raise ValueError(
'Dot is waiting for two TT-vectors or two TT- matrices') | def dot(a, b) | Dot product of two TT-matrices or two TT-vectors | 10.465446 | 7.233325 | 1.446837 |
if not isinstance(a, list):
a = [a]
a = list(a) # copy list
for i in args:
if isinstance(i, list):
a.extend(i)
else:
a.append(i)
c = _vector.vector()
c.d = 0
c.n = _np.array([], dtype=_np.int32)
c.r = _np.array([], dtype=_np.int32)
c.core = []
for t in a:
thetensor = t.tt if isinstance(t, _matrix.matrix) else t
c.d += thetensor.d
c.n = _np.concatenate((c.n, thetensor.n))
c.r = _np.concatenate((c.r[:-1], thetensor.r))
c.core = _np.concatenate((c.core, thetensor.core))
c.get_ps()
return c | def mkron(a, *args) | Kronecker product of all the arguments | 2.852232 | 2.812618 | 1.014084 |
Al = _matrix.matrix.to_list(ttA)
Bl = _matrix.matrix.to_list(ttB)
Hl = [_np.kron(B, A) for (A, B) in zip(Al, Bl)]
return _matrix.matrix.from_list(Hl) | def zkron(ttA, ttB) | Do kronecker product between cores of two matrices ttA and ttB.
Look about kronecker at: https://en.wikipedia.org/wiki/Kronecker_product
For details about operation refer: https://arxiv.org/abs/1802.02839
:param ttA: first TT-matrix;
:param ttB: second TT-matrix;
:return: TT-matrix in z-order | 3.64821 | 3.678181 | 0.991852 |
Al = _vector.vector.to_list(ttA)
Bl = _vector.vector.to_list(ttB)
Hl = [_np.kron(B, A) for (A, B) in zip(Al, Bl)]
return _vector.vector.from_list(Hl) | def zkronv(ttA, ttB) | Do kronecker product between vectors ttA and ttB.
Look about kronecker at: https://en.wikipedia.org/wiki/Kronecker_product
For details about operation refer: https://arxiv.org/abs/1802.02839
:param ttA: first TT-vector;
:param ttB: second TT-vector;
:return: operation result in z-order | 3.80684 | 3.781677 | 1.006654 |
lin = xfun(2, d)
one = ones(2, d)
xx = zkronv(lin, one)
yy = zkronv(one, lin)
return xx, yy | def zmeshgrid(d) | Returns a meshgrid like np.meshgrid but in z-order
:param d: you'll get 4**d nodes in meshgrid
:return: xx, yy in z-order | 10.002673 | 11.197272 | 0.893313 |
xx, yy = zmeshgrid(d)
Hx, Hy = _vector.vector.to_list(xx), _vector.vector.to_list(yy)
Hs = _cp.deepcopy(Hx)
Hs[0][:, :, 0] = c1 * Hx[0][:, :, 0] + c2 * Hy[0][:, :, 0]
Hs[-1][1, :, :] = c1 * Hx[-1][1, :, :] + (c0 + c2 * Hy[-1][1, :, :])
d = len(Hs)
for k in range(1, d - 1):
Hs[k][1, :, 0] = c1 * Hx[k][1, :, 0] + c2 * Hy[k][1, :, 0]
return _vector.vector.from_list(Hs) | def zaffine(c0, c1, c2, d) | Generate linear function c0 + c1 ex + c2 ey in z ordering with d cores in QTT
:param c0:
:param c1:
:param c2:
:param d:
:return: | 2.984018 | 3.101745 | 0.962045 |
tmp = _np.array([[1] + [0] * (len(args) - 1)])
result = kron(_vector.vector(tmp), args[0])
for i in range(1, len(args)):
result += kron(_vector.vector(_np.array([[0] * i +
[1] + [0] * (len(args) - i - 1)])), args[i])
return result | def concatenate(*args) | Concatenates given TT-vectors.
For two tensors :math:`X(i_1,\\ldots,i_d),Y(i_1,\\ldots,i_d)` returns :math:`(d+1)`-dimensional
tensor :math:`Z(i_0,i_1,\\ldots,i_d)`, :math:`i_0=\\overline{0,1}`, such that
.. math::
Z(0, i_1, \\ldots, i_d) = X(i_1, \\ldots, i_d),
Z(1, i_1, \\ldots, i_d) = Y(i_1, \\ldots, i_d). | 3.130641 | 3.878942 | 0.807086 |
d = a.d
crs = _vector.vector.to_list(a.tt if isinstance(a, _matrix.matrix) else a)
if axis < 0:
axis = range(a.d)
elif isinstance(axis, int):
axis = [axis]
axis = list(axis)[::-1]
for ax in axis:
crs[ax] = _np.sum(crs[ax], axis=1)
rleft, rright = crs[ax].shape
if (rleft >= rright or rleft < rright and ax + 1 >= d) and ax > 0:
crs[ax - 1] = _np.tensordot(crs[ax - 1], crs[ax], axes=(2, 0))
elif ax + 1 < d:
crs[ax + 1] = _np.tensordot(crs[ax], crs[ax + 1], axes=(1, 0))
else:
return _np.sum(crs[ax])
crs.pop(ax)
d -= 1
return _vector.vector.from_list(crs) | def sum(a, axis=-1) | Sum TT-vector over specified axes | 2.956069 | 2.896956 | 1.020405 |
c = _vector.vector()
if d is None:
c.n = _np.array(n, dtype=_np.int32)
c.d = c.n.size
else:
c.n = _np.array([n] * d, dtype=_np.int32)
c.d = d
c.r = _np.ones((c.d + 1,), dtype=_np.int32)
c.get_ps()
c.core = _np.ones(c.ps[c.d] - 1)
return c | def ones(n, d=None) | Creates a TT-vector of all ones | 3.326518 | 3.359921 | 0.990058 |
n0 = _np.asanyarray(n, dtype=_np.int32)
r0 = _np.asanyarray(r, dtype=_np.int32)
if d is None:
d = n.size
if n0.size is 1:
n0 = _np.ones((d,), dtype=_np.int32) * n0
if r0.size is 1:
r0 = _np.ones((d + 1,), dtype=_np.int32) * r0
r0[0] = 1
r0[d] = 1
c = _vector.vector()
c.d = d
c.n = n0
c.r = r0
c.get_ps()
c.core = samplefunc(c.ps[d] - 1)
return c | def rand(n, d=None, r=2, samplefunc=_np.random.randn) | Generate a random d-dimensional TT-vector with ranks ``r``.
Distribution to sample cores is provided by the samplefunc.
Default is to sample from normal distribution. | 2.610177 | 2.556922 | 1.020828 |
c = _matrix.matrix()
c.tt = _vector.vector()
if d is None:
n0 = _np.asanyarray(n, dtype=_np.int32)
c.tt.d = n0.size
else:
n0 = _np.asanyarray([n] * d, dtype=_np.int32)
c.tt.d = d
c.n = n0.copy()
c.m = n0.copy()
c.tt.n = (c.n) * (c.m)
c.tt.r = _np.ones((c.tt.d + 1,), dtype=_np.int32)
c.tt.get_ps()
c.tt.alloc_core()
for i in xrange(c.tt.d):
c.tt.core[
c.tt.ps[i] -
1:c.tt.ps[
i +
1] -
1] = _np.eye(
c.n[i]).flatten()
return c | def eye(n, d=None) | Creates an identity TT-matrix | 3.354542 | 3.216269 | 1.042992 |
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 d == 1:
return _vector.vector.from_list(
[_np.reshape(_np.arange(n0[0]), (1, n0[0], 1))])
cr = []
cur_core = _np.ones((1, n0[0], 2))
cur_core[0, :, 0] = _np.arange(n0[0])
cr.append(cur_core)
ni = float(n0[0])
for i in xrange(1, d - 1):
cur_core = _np.zeros((2, n0[i], 2))
for j in xrange(n0[i]):
cur_core[:, j, :] = _np.eye(2)
cur_core[1, :, 0] = ni * _np.arange(n0[i])
ni *= n0[i]
cr.append(cur_core)
cur_core = _np.ones((2, n0[d - 1], 1))
cur_core[1, :, 0] = ni * _np.arange(n0[d - 1])
cr.append(cur_core)
return _vector.vector.from_list(cr) | def xfun(n, d=None) | Create a QTT-representation of 0:prod(n) _vector
call examples:
tt.xfun(2, 5) # create 2 x 2 x 2 x 2 x 2 TT-vector
tt.xfun(3) # create [0, 1, 2] one-dimensional TT-vector
tt.xfun([3, 5, 7], 2) # create 3 x 5 x 7 x 3 x 5 x 7 TT-vector | 2.155626 | 2.092352 | 1.03024 |
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
t = xfun(n0)
e = ones(n0)
N = _np.prod(n0) # Size
if left and right:
h = (b - a) * 1.0 / (N - 1)
res = a * e + t * h
elif left and not right:
h = (b - a) * 1.0 / N
res = a * e + t * h
elif right and not left:
h = (b - a) * 1.0 / N
res = a * e + (t + e) * h
else:
h = (b - a) * 1.0 / (N - 1)
res = a * e + (t + e) * h
return res.round(1e-13) | def linspace(n, d=None, a=0.0, b=1.0, right=True, left=True) | Create a QTT-representation of a uniform grid on an interval [a, b] | 2.576784 | 2.548683 | 1.011026 |
cr = []
cur_core = _np.zeros([1, 2, 2], dtype=_np.float)
cur_core[0, 0, :] = [_math.cos(phase), _math.sin(phase)]
cur_core[0, 1, :] = [_math.cos(alpha + phase), _math.sin(alpha + phase)]
cr.append(cur_core)
for i in xrange(1, d - 1):
cur_core = _np.zeros([2, 2, 2], dtype=_np.float)
cur_core[0, 0, :] = [1.0, 0.0]
cur_core[1, 0, :] = [0.0, 1.0]
cur_core[
0,
1,
:] = [
_math.cos(
alpha *
2 ** i),
_math.sin(
alpha *
2 ** i)]
cur_core[1,
1,
:] = [-_math.sin(alpha * 2 ** i),
_math.cos(alpha * 2 ** i)]
cr.append(cur_core)
cur_core = _np.zeros([2, 2, 1], dtype=_np.float)
cur_core[0, :, 0] = [0.0, _math.sin(alpha * 2 ** (d - 1))]
cur_core[1, :, 0] = [1.0, _math.cos(alpha * 2 ** (d - 1))]
cr.append(cur_core)
return _vector.vector.from_list(cr) | def sin(d, alpha=1.0, phase=0.0) | Create TT-vector for :math:`\\sin(\\alpha n + \\varphi)`. | 1.89465 | 1.906822 | 0.993616 |
return sin(d, alpha, phase + _math.pi * 0.5) | def cos(d, alpha=1.0, phase=0.0) | Create TT-vector for :math:`\\cos(\\alpha n + \\varphi)`. | 6.353744 | 7.043654 | 0.902052 |
if isinstance(n, six.integer_types):
n = [n]
if d is None:
n0 = _np.asanyarray(n, dtype=_np.int32)
else:
n0 = _np.array(n * d, dtype=_np.int32)
d = n0.size
if center < 0:
cind = [0] * d
else:
cind = []
for i in xrange(d):
cind.append(center % n0[i])
center //= n0[i]
if center > 0:
cind = [0] * d
cr = []
for i in xrange(d):
cur_core = _np.zeros((1, n0[i], 1))
cur_core[0, cind[i], 0] = 1
cr.append(cur_core)
return _vector.vector.from_list(cr) | def delta(n, d=None, center=0) | Create TT-vector for delta-function :math:`\\delta(x - x_0)`. | 2.831006 | 2.856122 | 0.991207 |
if isinstance(n, six.integer_types):
n = [n]
if d is None:
n0 = _np.asanyarray(n, dtype=_np.int32)
else:
n0 = _np.array(n * d, dtype=_np.int32)
d = n0.size
N = _np.prod(n0)
if center >= N and direction < 0 or center <= 0 and direction > 0:
return ones(n0)
if center <= 0 and direction < 0 or center >= N and direction > 0:
raise ValueError(
"Heaviside function with specified center and direction gives zero tensor!")
if direction > 0:
center = N - center
cind = []
for i in xrange(d):
cind.append(center % n0[i])
center //= n0[i]
def gen_notx(currcind, currn):
return [0.0] * (currn - currcind) + [1.0] * currcind
def gen_notx_rev(currcind, currn):
return [1.0] * currcind + [0.0] * (currn - currcind)
def gen_x(currcind, currn):
result = [0.0] * currn
result[currn - currcind - 1] = 1.0
return result
def gen_x_rev(currcind, currn):
result = [0.0] * currn
result[currcind] = 1.0
return result
if direction > 0:
x = gen_x
notx = gen_notx
else:
x = gen_x_rev
notx = gen_notx_rev
crs = []
prevrank = 1
for i in range(d)[::-1]:
break_further = max([0] + cind[:i])
nextrank = 2 if break_further else 1
one = [1] * n0[i]
cr = _np.zeros([nextrank, n0[i], prevrank], dtype=_np.float)
tempx = x(cind[i], n0[i])
tempnotx = notx(cind[i], n0[i])
# high-conditional magic
if not break_further:
if cind[i]:
if prevrank > 1:
cr[0, :, 0] = one
cr[0, :, 1] = tempnotx
else:
cr[0, :, 0] = tempnotx
else:
cr[0, :, 0] = one
else:
if prevrank > 1:
cr[0, :, 0] = one
if cind[i]:
cr[0, :, 1] = tempnotx
cr[1, :, 1] = tempx
else:
cr[1, :, 1] = tempx
else:
if cind[i]:
cr[0, :, 0] = tempnotx
cr[1, :, 0] = tempx
else:
nextrank = 1
cr = cr[:1, :, :]
cr[0, :, 0] = tempx
prevrank = nextrank
crs.append(cr)
return _vector.vector.from_list(crs[::-1]) | 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 value of ``direction`` :math:`\chi(x_0 - x)` is approximated. | 2.507137 | 2.548108 | 0.983921 |
''' 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
'''
if isinstance(n, int):
if d is None:
d = 1
n = n * _np.ones(d, dtype=_np.int32)
else:
d = len(n)
if j is None:
j = 0
rv = []
j = _ind2sub(n, j)
for k in xrange(d):
rv.append(_np.zeros((1, n[k], 1)))
rv[-1][0, j[k], 0] = 1
if tt_instance:
rv = _vector.vector.from_list(rv)
return rv | 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;
if False, returns tt cores as a list | 4.887888 | 2.233695 | 2.188252 |
'''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], [a, 1]]).reshape((1, 2, 2, 1), order='F')
else:
M = [None] * d
M[0] = _np.zeros((1, 2, 2, 2))
M[0][0, :, :, 0] = _np.array([[1, 0], [a, 1]])
M[0][0, :, :, 1] = _np.array([[0, a], [0, 0]])
for i in xrange(1, d - 1):
M[i] = _np.zeros((2, 2, 2, 2))
M[i][:, :, 0, 0] = _np.eye(2)
M[i][:, :, 1, 0] = _np.array([[0, 0], [1, 0]])
M[i][:, :, 1, 1] = _np.array([[0, 1], [0, 0]])
M[d - 1] = _np.zeros((2, 2, 2, 1))
M[d - 1][:, :, 0, 0] = _np.eye(2)
M[d - 1][:, :, 1, 0] = _np.array([[0, 0], [1, 0]])
if tt_instance:
M = _matrix.matrix.from_list(M)
return M | 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 | 2.529892 | 1.631488 | 1.550666 |
cc = coresX[dim]
r1, n, r2 = cc.shape
if left_to_right:
# Left to right orthogonalization step.
assert(0 <= dim < len(coresX) - 1)
cc, rr = np.linalg.qr(reshape(cc, (-1, r2)))
r2 = cc.shape[1]
coresX[dim] = reshape(cc, (r1, n, r2))
coresX[dim+1] = np.tensordot(rr, coresX[dim+1], 1)
else:
# Right to left orthogonalization step.
assert(0 < dim < len(coresX))
cc, rr = np.linalg.qr(reshape(cc, (r1, -1)).T)
r1 = cc.shape[1]
coresX[dim] = reshape(cc.T, (r1, n, r2))
coresX[dim-1] = np.tensordot(coresX[dim-1], rr.T, 1)
return coresX | def cores_orthogonalization_step(coresX, dim, left_to_right=True) | TT-Tensor X orthogonalization step.
The function can change the shape of some cores. | 2.122957 | 2.108179 | 1.00701 |
if i < 0:
return np.ones([1, 1])
answ = np.ones([1, 1])
cores = tt.tensor.to_list(X)
for dim in xrange(i+1):
answ = np.tensordot(answ, cores[dim], 1)
answ = reshape(answ, (-1, X.r[i+1]))
return answ | def left(X, i) | Compute the orthogonal matrix Q_{\leq i} as defined in [1]. | 5.065492 | 5.013378 | 1.010395 |
if i > X.d-1:
return np.ones([1, 1])
answ = np.ones([1, 1])
cores = tt.tensor.to_list(X)
for dim in xrange(X.d-1, i-1, -1):
answ = np.tensordot(cores[dim], answ, 1)
answ = reshape(answ, (X.r[i], -1))
return answ.T | def right(X, i) | Compute the orthogonal matrix Q_{\geq i} as defined in [1]. | 4.75953 | 4.757488 | 1.000429 |
return reshape(tens.full(), (np.prod(tens.n[0:(i+1)]), -1)) | def unfolding(tens, i) | Compute the i-th unfolding of a tensor. | 10.01854 | 10.985939 | 0.911942 |
# TODO: Use intermediate variable to use 5 nested loops instead of 6.
r_old_x, n, r_x = xCore.shape
num_obj, r_old_z, n, r_z = zCore.shape
for idx in range(num_obj):
for val in range(n):
for alpha_old_z in range(r_old_z):
for alpha_z in range(r_z):
for alpha_old_x in range(r_old_x):
for alpha_x in range(r_x):
curr_value = lhs[idx, alpha_old_x, alpha_old_z]
curr_value *= xCore[alpha_old_x, val, alpha_x]
curr_value *= zCore[idx, alpha_old_z, val, alpha_z]
new_lhs[idx, alpha_x, alpha_z] += curr_value | def _update_lhs(lhs, xCore, zCore, new_lhs) | Function to be called from the project() | 2.982145 | 2.98577 | 0.998786 |
# TODO: Use intermediate variable to use 5 nested loops instead of 6.
r_x, n, r_old_x = xCore.shape
num_obj, r_z, n, r_old_z = zCore.shape
for idx in range(num_obj):
for val in range(n):
for alpha_old_z in range(r_old_z):
for alpha_z in range(r_z):
for alpha_old_x in range(r_old_x):
for alpha_x in range(r_x):
curr_value = curr_rhs[idx, alpha_old_z, alpha_old_x]
curr_value *= xCore[alpha_x, val, alpha_old_x]
curr_value *= zCore[idx, alpha_z, val, alpha_old_z]
new_rhs[idx, alpha_z, alpha_x] += curr_value | def _update_rhs(curr_rhs, xCore, zCore, new_rhs) | Function to be called from the project() | 2.977327 | 2.969083 | 1.002777 |
# Get rid of redundant ranks (they cause technical difficulties).
X = X.round(eps=0)
numDims = X.d
coresX = tt.tensor.to_list(X)
if left_to_right:
# Left to right orthogonalization of the X cores.
for dim in xrange(0, numDims-1):
coresX = cores_orthogonalization_step(
coresX, dim, left_to_right=left_to_right)
last_core = coresX[numDims-1]
r1, n, r2 = last_core.shape
last_core, rr = np.linalg.qr(reshape(last_core, (-1, r2)))
coresX[numDims-1] = reshape(last_core, (r1, n, -1))
else:
# Right to left orthogonalization of X cores
for dim in xrange(numDims-1, 0, -1):
coresX = cores_orthogonalization_step(
coresX, dim, left_to_right=left_to_right)
last_core = coresX[0]
r1, n, r2 = last_core.shape
last_core, rr = np.linalg.qr(
np.transpose(reshape(last_core, (r1, -1)))
)
coresX[0] = reshape(
np.transpose(last_core),
(-1, n, r2))
rr = np.transpose(rr)
return tt.tensor.from_list(coresX), rr | 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 (left)
upper (lower) triangular matrix
>>> import tt, numpy as np
>>> x = tt.rand(np.array([2, 3, 4, 5]), d=4)
>>> x_q, r = tt_qr(x, left_to_right=True)
>>> np.allclose((rm[0][0]*x_q).norm(), x.norm())
True
>>> x_u, l = tt_qr(x, left_to_right=False)
>>> np.allclose((l[0][0]*x_u).norm(), x.norm())
True | 2.895922 | 2.865 | 1.010793 |
'''
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(1), k))
for i in xrange(n - 1, -1, -1):
subs[i] = _np.floor(idx / k[i])
idx = idx % k[i]
return subs.astype(_np.int32) | 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. | 5.197369 | 2.198084 | 2.3645 |
'''Greatest common divider'''
f = _np.frompyfunc(_fractions.gcd, 2, 1)
return f(a, b) | def gcd(a, b) | Greatest common divider | 5.189722 | 4.564363 | 1.137009 |
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) | Transposed TT-matrix | 5.90038 | 4.984619 | 1.183717 |
return matrix(self.tt.real(), n=self.n, m=self.m) | def real(self) | Return real part of a matrix. | 11.298826 | 8.001785 | 1.412038 |
return matrix(self.tt.imag(), n=self.n, m=self.m) | def imag(self) | Return imaginary part of a matrix. | 10.843625 | 7.960583 | 1.362165 |
return matrix(a=self.tt.__complex_op('M'), n=_np.concatenate(
(self.n, [2])), m=_np.concatenate((self.m, [2]))) | 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:`\\begin{bmatrix}\\Re M & -\\Im M \\\\ \\Im M & \\Re M \\end{bmatrix}`. This function
is useful for solving complex linear system :math:`\\mathcal{A}X = B` with real solver by
transforming it into
.. math::
\\begin{bmatrix}\\Re\\mathcal{A} & -\\Im\\mathcal{A} \\\\
\\Im\\mathcal{A} & \\Re\\mathcal{A} \\end{bmatrix}
\\begin{bmatrix}\\Re X \\\\ \\Im X\\end{bmatrix} =
\\begin{bmatrix}\\Re B \\\\ \\Im B\\end{bmatrix}. | 18.539808 | 18.949133 | 0.978399 |
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) | Computes an approximation to a
TT-matrix in with accuracy EPS | 4.668099 | 4.249463 | 1.098515 |
c = matrix()
c.tt = self.tt.copy()
c.n = self.n.copy()
c.m = self.m.copy()
return c | def copy(self) | Creates a copy of the TT-matrix | 4.038385 | 2.973338 | 1.358199 |
N = self.n.prod()
M = self.m.prod()
a = self.tt.full()
d = self.tt.d
sz = _np.vstack((self.n, self.m)).flatten('F')
a = a.reshape(sz, order='F')
# Design a permutation
prm = _np.arange(2 * d)
prm = prm.reshape((d, 2), order='F')
prm = prm.transpose()
prm = prm.flatten('F')
# Get the inverse permutation
iprm = [0] * (2 * d)
for i in xrange(2 * d):
iprm[prm[i]] = i
a = a.transpose(iprm).reshape(N, M, order='F')
a = a.reshape(N, M)
return a | def full(self) | Transforms a TT-matrix into a full matrix | 3.395956 | 3.198559 | 1.061714 |
''' 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 truncation with Fro-threshold.
'''
R2 = _np.dot(_tconj(A), A)
[u, s, vt] = _np.linalg.svd(R2, full_matrices=False)
u = _np.dot(A, _tconj(vt))
s = (u**2).sum(axis=0)
s = s ** 0.5
if tol is not None:
p = _my_chop2(s, _np.linalg.norm(s) * tol)
u = u[:, :p]
s = s[:p]
vt = vt[:p, :]
tmp = _spdiags(1. / s, 0, len(s), len(s)).todense()
tmp = _np.array(tmp)
u = _np.dot(u, tmp)
r = _np.dot(_np.diag(s), vt)
# Run chol for reortogonalization.
# It will stop if the matrix will be singular.
# Fortunately, it means rank truncation with eps in our business.
if (s[0] / s[-1] > 1. / tol2):
p = 1
while (p > 0):
R2 = _np.dot(_tconj(u), u)
#[u_r2, s_r2, vt_r2] = _np.linalg.svd(R2) # in matlab [R, p] = chol(a) - here is a *dirty* patch
#p = s_r2[s_r2 > eps].size
#R2 = R2[:p, :p]
R = _cholesky(R2, lower=True)
if (p > 0):
u = u[:, :p]
s = s[:p]
r = r[:p, :]
iR = _np.linalg.inv(R)
u = _np.dot(u, iR)
r = _np.dot(R, r)
return u, s, r | 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'.
if tol is given, performs the truncation with Fro-threshold. | 5.435787 | 3.382099 | 1.607223 |
d = len(a) # Number of cores
res = vector()
n = _np.zeros(d, dtype=_np.int32)
r = _np.zeros(d+1, dtype=_np.int32)
cr = _np.array([])
for i in xrange(d):
cr = _np.concatenate((cr, a[i].flatten(order)))
r[i] = a[i].shape[0]
r[i+1] = a[i].shape[2]
n[i] = a[i].shape[1]
res.d = d
res.n = n
res.r = r
res.core = cr
res.get_ps()
return res | 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. | 3.170935 | 2.878627 | 1.101544 |
r = self.r
n = self.n
d = self.d
if d <= 1:
er = 0e0
else:
sz = _np.dot(n * r[0:d], r[1:])
if sz == 0:
er = 0e0
else:
b = r[0] * n[0] + n[d - 1] * r[d]
if d is 2:
er = sz * 1.0 / b
else:
a = _np.sum(n[1:d - 1])
er = (_np.sqrt(b * b + 4 * a * sz) - b) / (2 * a)
return er | def erank(self) | Effective rank of the TT-vector | 3.572527 | 3.508548 | 1.018235 |
tmp = self.copy()
newcore = _np.array(tmp.core, dtype=_np.complex)
cr = newcore[tmp.ps[-2] - 1:tmp.ps[-1] - 1]
cr = cr.reshape((tmp.r[-2], tmp.n[-1], tmp.r[-1]), order='F')
cr[:, 1, :] *= 1j
newcore[tmp.ps[-2] - 1:tmp.ps[-1] - 1] = cr.flatten('F')
tmp.core = newcore
return sum(tmp, axis=tmp.d - 1) | 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) + 1j * tt.rand(2,10,5)
>>> (a.c2r().r2c() - a).norm() / a.norm()
7.310562016615692e-16 | 4.343589 | 4.549964 | 0.954642 |
# Generate correct size vector
sz = self.n.copy()
if self.r[0] > 1:
sz = _np.concatenate(([self.r[0]], sz))
if self.r[self.d] > 1:
sz = _np.concatenate(([self.r[self.d]], sz))
if (_np.iscomplex(self.core).any()):
a = _tt_f90.tt_f90.ztt_to_full(
self.n, self.r, self.ps, self.core, _np.prod(sz))
else:
a = _tt_f90.tt_f90.dtt_to_full(
self.n, self.r, self.ps, _np.real(
self.core), _np.prod(sz))
a = a.reshape(sz, order='F')
if asvector:
a=a.flatten(order='F')
return a | 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 -- full tensor. | 3.558082 | 3.5711 | 0.996355 |
c = vector()
c.n = _np.copy(self.n)
c.d = self.d
c.r = _np.copy(self.r)
c.ps = _np.copy(self.ps)
if (_np.iscomplex(self.core).any()):
_tt_f90.tt_f90.ztt_compr2(c.n, c.r, c.ps, self.core, eps, rmax)
c.core = _tt_f90.tt_f90.zcore.copy()
else:
_tt_f90.tt_f90.dtt_compr2(c.n, c.r, c.ps, self.core, eps, rmax)
c.core = _tt_f90.tt_f90.core.copy()
_tt_f90.tt_f90.tt_dealloc()
return c | 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 example:
>>> a = tt.ones(2, 10)
>>> b = a + a
>>> print b.r
array([1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1], dtype=int32)
>>> b = b.round(1E-14)
>>> print b.r
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32) | 2.922438 | 3.112819 | 0.93884 |
if not _np.all(self.n):
return 0
# Solving quadratic equation ar^2 + br + c = 0;
a = _np.sum(self.n[1:-1])
b = self.n[0] + self.n[-1]
c = - _np.sum(self.n * self.r[1:] * self.r[:-1])
D = b ** 2 - 4 * a * c
r = 0.5 * (-b + _np.sqrt(D)) / a
return r | def rmean(self) | Calculates the mean rank of a TT-vector. | 3.788808 | 3.784419 | 1.00116 |
ry = y0.r.copy()
lam = tt_eigb.tt_block_eig.tt_eigb(y0.d, A.n, A.m, A.tt.r, A.tt.core, y0.core, ry, eps,
rmax, ry[y0.d], 0, nswp, max_full_size, verb)
y = tensor()
y.d = y0.d
y.n = A.n.copy()
y.r = ry
y.core = tt_eigb.tt_block_eig.result_core.copy()
tt_eigb.tt_block_eig.deallocate_result()
y.get_ps()
return y, lam | 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 function.
:Reference:
S. V. Dolgov, B. N. Khoromskij, I. V. Oseledets, and D. V. Savostyanov.
Computation of extreme eigenvalues in higher dimensions using block tensor train format. Computer Phys. Comm.,
185(4):1207-1216, 2014. http://dx.doi.org/10.1016/j.cpc.2013.12.017
:param A: Matrix in the TT-format
:type A: matrix
:param y0: Initial guess in the block TT-format, r(d+1) is the number of eigenvalues sought
:type y0: tensor
:param eps: Accuracy required
:type eps: float
:param rmax: Maximal rank
:type rmax: int
:param kickrank: Addition rank, the larger the more robus the method,
:type kickrank: int
:rtype: A tuple (ev, tensor), where ev is a list of eigenvalues, tensor is an approximation to eigenvectors.
:Example:
>>> import tt
>>> import tt.eigb
>>> d = 8; f = 3
>>> r = [8] * (d * f + 1); r[d * f] = 8; r[0] = 1
>>> x = tt.rand(n, d * f, r)
>>> a = tt.qlaplace_dd([8, 8, 8])
>>> sol, ev = tt.eigb.eigb(a, x, 1e-6, verb=0)
Solving a block eigenvalue problem
Looking for 8 eigenvalues with accuracy 1E-06
swp: 1 er = 35.93 rmax:19
swp: 2 er = 4.51015E-04 rmax:18
swp: 3 er = 1.87584E-12 rmax:17
Total number of matvecs: 0
>>> print ev
[ 0.00044828 0.00089654 0.00089654 0.00089654 0.0013448 0.0013448
0.0013448 0.00164356] | 4.915495 | 5.553185 | 0.885167 |
maxitexceeded = False
converged = False
if verbose:
print('GMRES(m=%d, _iteration=%d, maxit=%d)' % (m, _iteration, maxit))
v = np.ones((m + 1), dtype=object) * np.nan
R = np.ones((m, m)) * np.nan
g = np.zeros(m)
s = np.ones(m) * np.nan
c = np.ones(m) * np.nan
v[0] = b - A(u_0, eps=eps)
v[0] = v[0].round(eps)
resnorm = v[0].norm()
curr_beta = resnorm
bnorm = b.norm()
wlen = resnorm
q = m
for j in range(m):
_iteration += 1
delta = eps / (curr_beta / resnorm)
if verbose:
print("it = %d delta = " % _iteration, delta)
v[j] *= 1.0 / wlen
v[j + 1] = A(v[j], eps=delta)
for i in range(j + 1):
R[i, j] = tt.dot(v[j + 1], v[i])
v[j + 1] = v[j + 1] - R[i, j] * v[i]
v[j + 1] = v[j + 1].round(delta)
wlen = v[j + 1].norm()
for i in range(j):
r1 = R[i, j]
r2 = R[i + 1, j]
R[i, j] = c[i] * r1 - s[i] * r2
R[i + 1, j] = c[i] * r2 + s[i] * r1
denom = np.hypot(wlen, R[j, j])
s[j] = wlen / denom
c[j] = -R[j, j] / denom
R[j, j] = -denom
g[j] = c[j] * curr_beta
curr_beta *= s[j]
if verbose:
print("it = {}, ||r|| = {}".format(_iteration, curr_beta / bnorm))
converged = (curr_beta / bnorm) < eps or (curr_beta / resnorm) < eps
maxitexceeded = _iteration >= maxit
if converged or maxitexceeded:
q = j + 1
break
y = la.solve_triangular(R[:q, :q], g[:q], check_finite=False)
for idx in range(q):
u_0 += v[idx] * y[idx]
u_0 = u_0.round(eps)
if callback is not None:
callback(u_0)
if converged or maxitexceeded:
return u_0, resnorm / bnorm
return GMRES(A, u_0, b, eps, maxit, m, _iteration, callback=callback, verbose=verbose) | 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 restart
:param _iteration: iteration counter
:param callback:
:param verbose: to print debug info or not
:return: answer, residual
>>> from tt import GMRES
>>> def matvec(x, eps):
>>> return tt.matvec(S, x).round(eps)
>>> answer, res = GMRES(matvec, u_0, b, eps=1e-8) | 2.584271 | 2.656932 | 0.972652 |
'''
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
:list of numpy.arrays: rightV
right-orthogonal cores from \mu+1 to d
:list, tuple, np.array: jVec
indices for each dimension n[k]
Returns:
:numpy.array: result
Kronecker product between left and right interface
matrices. Left matrix is transposed.
'''
jLeft = None
jRight = None
if len(leftU) > 0:
jLeft = jVec[:len(leftU)]
if len(rightV) > 0:
jRight = jVec[-len(rightV):]
multU = np.ones([1,1])
for k in xrange(len(leftU)):
multU = np.dot(multU, leftU[k][:, jLeft[k], :])
multV= np.ones([1,1])
for k in xrange(len(rightV)-1, -1, -1):
multV = np.dot(rightV[k][:, jRight[k], :], multV)
result = np.kron(multV.T, multU)
return result | 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
left-orthogonal cores from 1 to \mu-1
:list of numpy.arrays: rightV
right-orthogonal cores from \mu+1 to d
:list, tuple, np.array: jVec
indices for each dimension n[k]
Returns:
:numpy.array: result
Kronecker product between left and right interface
matrices. Left matrix is transposed. | 4.114558 | 1.553398 | 2.648746 |
'''
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-orthogonal for dimensions from \mu+1 to d
:boolean: splitResult = True
Controls whether outut should be splitted into left-, non-, right-orthogonal
parts or not.
Returns:
:list: resultU
left-orthogonal cores with indices from 1 to \mu-1
:np.array: W
\mu-th core
:list: reultV
right-orthogonal cores with indices from \mu+1 to d
OR
:list: resultU + [W] + resultV
concatenated list of cores
'''
d = len(coreList)
assert (mu >= 0) and (mu <= d)
resultU = []
for k in xrange(mu):
core = coreList[k].copy()
if k > 0:
core = np.einsum('ijk,li->ljk', core, R)
[r1, n, r2] = core.shape
if (k < mu-1):
core = reshape(core, [r1*n, r2])
Q, R = np.linalg.qr(core)
rnew = Q.shape[1]
core = reshape(Q, [r1, n, rnew])
resultU = resultU + [core]
if mu > 0:
W = core.copy()
resultV = []
for k in xrange(d-1, mu, -1):
core = coreList[k].copy()
if (k < d-1):
core = np.einsum('ijk,lk->ijl', core, R)
[r1, n, r2] = core.shape
if (k > mu+1):
core = reshape(core, [r1, n*r2])
Q, R = np.linalg.qr(core.T)
rnew = Q.shape[1]
core = reshape(Q.T, [rnew, n, r2])
resultV = [core] + resultV
if mu < d-1:
if mu > 0:
W = np.einsum('ijk,lk->ijl', W, R)
else:
W = np.einsum('ijk,lk->ijl', coreList[0], R)
if splitResult:
return resultU, W, resultV
return resultU + [W] + resultV | 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-orthogonal for dimensions from 1 to \mu-1
and right-orthogonal for dimensions from \mu+1 to d
:boolean: splitResult = True
Controls whether outut should be splitted into left-, non-, right-orthogonal
parts or not.
Returns:
:list: resultU
left-orthogonal cores with indices from 1 to \mu-1
:np.array: W
\mu-th core
:list: reultV
right-orthogonal cores with indices from \mu+1 to d
OR
:list: resultU + [W] + resultV
concatenated list of cores | 2.999425 | 1.6644 | 1.802105 |
'''
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 records
- 'indices': numpy.array of P x d shape,
contains index subspace of P known elements;
each string is an index of one element.
- 'values': numpy array of size P,
contains P known values.
Returns:
:float: result
value of functional
'''
indices = cooP['indices']
values = cooP['values']
[P, d] = indices.shape
assert P == len(values)
result = 0
for p in xrange(P):
index = tuple(indices[p, :])
result += (x[index] - values[p])**2
result *= 0.5
return result | 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]
: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.
- 'values': numpy array of size P,
contains P known values.
Returns:
:float: result
value of functional | 8.375587 | 1.578705 | 5.305352 |
def update(self, icon=None, hover_text=None):
if icon:
self._icon = icon
self._load_icon()
if hover_text:
self._hover_text = hover_text
self._refresh_icon() | update icon image and/or hover text | null | null | null |
|
def encode_for_locale(s):
try:
return s.encode(LOCALE_ENCODING, 'ignore')
except (AttributeError, UnicodeDecodeError):
return s.decode('ascii', 'ignore').encode(LOCALE_ENCODING) | Encode text items for system locale. If encoding fails, fall back to ASCII. | null | null | null |
|
def func_wrapper(func):
_cached_func = clru_cache(maxsize, typed, state, unhashable)(func)
def wrapper(*args, **kwargs):
return _cached_func(*args, **kwargs)
wrapper.__wrapped__ = func
wrapper.cache_info = _cached_func.cache_info
wrapper.cache_clear = _cached_func.cache_clear
return update_wrapper(wrapper,func)
return func_wrapper | 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, f(3.0) and f(3) will be treated as distinct
calls with distinct results.
If *state* is a list or dict, the items will be incorporated into
argument hash.
The result of calling the cached function with unhashable (mutable)
arguments depends on the value of *unhashable*:
If *unhashable* is 'error', a TypeError will be raised.
If *unhashable* is 'warning', a UserWarning will be raised, and
the wrapped function will be called with the supplied arguments.
A miss will be recorded in the cache statistics.
If *unhashable* is 'ignore', the wrapped function will be called
with the supplied arguments. A miss will will be recorded in
the cache statistics.
View the cache statistics named tuple (hits, misses, maxsize, currsize)
with f.cache_info(). Clear the cache and statistics with
f.cache_clear(). Access the underlying function with f.__wrapped__.
See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used | 2.169664 | 2.66355 | 0.814576 |
v = n.value
return v if v < 2 else fib2(PythonInt(v-1)) + fib(PythonInt(v-2)) | def fib(n) | Terrible Fibonacci number generator. | 8.124709 | 7.394 | 1.098825 |
for i in range(r):
if randint(RAND_MIN, RAND_MAX) == RAND_MIN:
fib.cache_clear()
fib2.cache_clear()
res = fib(PythonInt(FIB))
if RESULT != res:
raise ValueError("Expected %d, Got %d" % (RESULT, res)) | def run_fib_with_clear(r) | Run Fibonacci generator r times. | 6.361051 | 6.193517 | 1.02705 |
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) | Run Fibonacci generator r times. | 8.829989 | 8.293281 | 1.064716 |
if not jpype.isThreadAttachedToJVM():
jpype.attachThreadToJVM()
if reference_date:
return json.loads(self._sutime.annotate(input_str, reference_date))
return json.loads(self._sutime.annotate(input_str)) | 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.
Returns:
A list of dicts with the result from the SUTimeWrapper.annotate()
call. | 3.806778 | 3.185792 | 1.194923 |
# Make sure the string is Unicode for Python 2.
if sys.version_info[0] < 3 and isinstance(msg, str):
msg = msg.decode()
# Lowercase it.
msg = msg.lower()
# Run substitutions on it.
msg = self.substitute(msg, "sub")
# In UTF-8 mode, only strip metacharacters and HTML brackets
# (to protect from obvious XSS attacks).
if self.utf8:
msg = re.sub(RE.utf8_meta, '', msg)
msg = re.sub(self.master.unicode_punctuation, '', msg)
# For the bot's reply, also strip common punctuation.
if botreply:
msg = re.sub(RE.utf8_punct, '', msg)
else:
# For everything else, strip all non-alphanumerics.
msg = utils.strip_nasties(msg)
msg = msg.strip() # Strip leading and trailing white space
msg = RE.ws.sub(" ",msg) # Replace the multiple whitespaces by single whitespace
return msg | 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 formatting is being done for the
bot's last reply (e.g. in a ``%Previous`` command).
:return str: The formatted message. | 5.19407 | 4.784115 | 1.085691 |
if depth > self.master._depth:
raise Exception("deep recursion detected")
if not array_name in self.master._array:
raise Exception("array '%s' not defined" % (array_name))
ret = list(self.master._array[array_name])
for array in self.master._array[array_name]:
if array.startswith('@'):
ret.remove(array)
expanded = self.do_expand_array(array[1:], depth+1)
ret.extend(expanded)
return set(ret) | 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 expand.
:param int depth: The recursion depth counter.
:return set: The final set of array entries. | 3.195592 | 3.061246 | 1.043886 |
ret = self.master._array[array_name] if array_name in self.master._array else []
try:
ret = self.do_expand_array(array_name)
except Exception as e:
self.warn("Error expanding array '%s': %s" % (array_name, str(e)))
return ret | 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. | 3.280837 | 3.33013 | 0.985198 |
# Safety checking.
if 'lists' not in self.master._sorted:
raise RepliesNotSortedError("You must call sort_replies() once you are done loading RiveScript documents")
if kind not in self.master._sorted["lists"]:
raise RepliesNotSortedError("You must call sort_replies() once you are done loading RiveScript documents")
# Get the substitution map.
subs = None
if kind == 'sub':
subs = self.master._sub
else:
subs = self.master._person
# Make placeholders each time we substitute something.
ph = []
i = 0
for pattern in self.master._sorted["lists"][kind]:
result = subs[pattern]
# Make a placeholder.
ph.append(result)
placeholder = "\x00%d\x00" % i
i += 1
cache = self.master._regexc[kind][pattern]
msg = re.sub(cache["sub1"], placeholder, msg)
msg = re.sub(cache["sub2"], placeholder + r'\1', msg)
msg = re.sub(cache["sub3"], r'\1' + placeholder + r'\2', msg)
msg = re.sub(cache["sub4"], r'\1' + placeholder, msg)
placeholders = re.findall(RE.placeholder, msg)
for match in placeholders:
i = int(match)
result = ph[i]
msg = msg.replace('\x00' + match + '\x00', result)
# Strip & return.
return msg.strip() | 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``. | 3.89206 | 3.747729 | 1.038512 |
# We need to make a dynamic Python method.
source = "def RSOBJ(rs, args):\n"
for line in code:
source = source + "\t" + line + "\n"
source += "self._objects[name] = RSOBJ\n"
try:
exec(source)
# self._objects[name] = RSOBJ
except Exception as e:
print("Failed to load code from object", name)
print("The error given was: ", e) | 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. | 6.387156 | 5.661174 | 1.128239 |
# Call the dynamic method.
if name not in self._objects:
return '[ERR: Object Not Found]'
func = self._objects[name]
reply = ''
try:
reply = func(rs, fields)
if reply is None:
reply = ''
except Exception as e:
raise PythonObjectError("Error executing Python object: " + str(e))
return text_type(reply) | 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 words sent as the object's arguments.
:return str: The output of the object macro. | 5.286303 | 5.39327 | 0.980167 |
# Break if we're in too deep.
if depth > rs._depth:
rs._warn("Deep recursion while scanning topic trees!")
return []
# Collect an array of all topics.
topics = [topic]
# Does this topic include others?
if topic in rs._includes:
# Try each of these.
for includes in sorted(rs._includes[topic]):
topics.extend(get_topic_tree(rs, includes, depth + 1))
# Does this topic inherit others?
if topic in rs._lineage:
# Try each of these.
for inherits in sorted(rs._lineage[topic]):
topics.extend(get_topic_tree(rs, inherits, depth + 1))
return topics | 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. | 3.609128 | 3.246391 | 1.111735 |
words = []
if all:
words = re.split(RE.ws, trigger)
else:
words = re.split(RE.wilds_and_optionals, trigger)
wc = 0 # Word count
for word in words:
if len(word) > 0:
wc += 1
return wc | 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. | 4.186153 | 3.857242 | 1.085271 |
if method == "uppercase":
return msg.upper()
elif method == "lowercase":
return msg.lower()
elif method == "sentence":
return msg.capitalize()
elif method == "formal":
return string.capwords(msg) | 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. | 2.5312 | 2.115618 | 1.196435 |
source = "\n".join(code)
self._objects[name] = source | def load(self, name, code) | Prepare a Perl code object given by the RS interpreter. | 10.709186 | 9.500321 | 1.127245 |
from_number = request.values.get("From", "unknown")
message = request.values.get("Body")
reply = "(Internal error)"
# Get a reply from RiveScript.
if message:
reply = bot.reply(from_number, message)
# Send the response.
resp = twilio.twiml.Response()
resp.message(reply)
return str(resp) | def hello_rivescript() | Receive an inbound SMS and send a reply from RiveScript. | 4.080923 | 3.477513 | 1.173518 |
params = request.json
if not params:
return jsonify({
"status": "error",
"error": "Request must be of the application/json type!",
})
username = params.get("username")
message = params.get("message")
uservars = params.get("vars", dict())
# Make sure the required params are present.
if username is None or message is None:
return jsonify({
"status": "error",
"error": "username and message are required keys",
})
# Copy and user vars from the post into RiveScript.
if type(uservars) is dict:
for key, value in uservars.items():
bot.set_uservar(username, key, value)
# Get a reply from the bot.
reply = bot.reply(username, message)
# Get all the user's vars back out of the bot to include in the response.
uservars = bot.get_uservars(username)
# Send the response.
return jsonify({
"status": "ok",
"reply": reply,
"vars": uservars,
}) | def reply() | Fetch a reply from RiveScript.
Parameters (JSON):
* username
* message
* vars | 3.271594 | 2.965285 | 1.103298 |
payload = {
"username": "soandso",
"message": "Hello bot",
"vars": {
"name": "Soandso",
}
}
return Response(r.format(json.dumps(payload)),
mimetype="text/plain") | def index(path=None) | On all other routes, just return an example `curl` command. | 9.589105 | 8.581615 | 1.117401 |
if frozen:
return self.frozen + username
return self.prefix + username | def _key(self, username, frozen=False) | Translate a username into a key for Redis. | 8.681902 | 5.807473 | 1.494954 |
data = self.client.get(self._key(username))
if data is None:
return None
return json.loads(data.decode()) | def _get_user(self, username) | Custom helper method to retrieve a user's data from Redis. | 4.785328 | 2.988641 | 1.601172 |
if say is None:
say = lambda x: x
# KEEP IN MIND: the `triggers` array is composed of array elements of the form
# ["trigger text", pointer to trigger data]
# So this code will use e.g. `trig[0]` when referring to the trigger text.
# Create a list of trigger objects map.
trigger_object_list = []
for index, trig in enumerate(triggers):
if exclude_previous and trig[1]["previous"]:
continue
pattern = trig[0] # Extract only the text of the trigger, with possible tag of inherit
# See if it has a weight tag
match, weight = re.search(RE.weight, trig[0]), 0
if match: # Value of math is not None if there is a match.
weight = int(match.group(1)) # Get the weight from the tag ``{weight}``
# See if it has an inherits tag.
match = re.search(RE.inherit, pattern)
if match:
inherit = int(match.group(1)) # Get inherit value from the tag ``{inherit}``
say("\t\t\tTrigger belongs to a topic which inherits other topics: level=" + str(inherit))
triggers[index][0] = pattern = re.sub(RE.inherit, "", pattern) # Remove the inherit tag if any
else:
inherit = sys.maxsize # If not found any inherit, set it to the maximum value, to place it last in the sort
trigger_object_list.append(TriggerObj(pattern, index, weight, inherit))
# Priority order of sorting criteria:
# weight, inherit, is_empty, star, pound, under, option, wordcount, len, alphabet
sorted_list = sorted(trigger_object_list,
key=attrgetter('weight', 'inherit', 'is_empty', 'star', 'pound',
'under', 'option', 'wordcount', 'len', 'alphabet'))
return [triggers[item.index] for item in sorted_list] | 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
first. Triggers with equal word counts are sorted by length, and then
alphabetically if they have the same length.
* Triggers containing optionals are sorted next, by word count like
atomic triggers.
* Triggers containing wildcards are next, with ``_`` (alphabetic)
wildcards on top, then ``#`` (numeric) and finally ``*``.
* At the bottom of the sorted list are triggers consisting of only a
single wildcard, in the order: ``_``, ``#``, ``*``.
Triggers that have ``{weight}`` tags are grouped together by weight
value and sorted amongst themselves. Higher weighted groups are then
ordered before lower weighted groups regardless of the normal sorting
algorithm.
Triggers that come from topics which inherit other topics are also
sorted with higher priority than triggers from the inherited topics.
Arguments:
triggers ([]str): Array of triggers to sort.
exclude_previous (bool): Create a sort buffer for 'previous' triggers.
say (function): A reference to ``RiveScript._say()`` or provide your
own function. | 5.921727 | 5.517223 | 1.073317 |
# Track by number of words.
track = {}
def by_length(word1, word2):
return len(word2) - len(word1)
# Loop through each item.
for item in items:
# Count the words.
cword = utils.word_count(item, all=True)
if cword not in track:
track[cword] = []
track[cword].append(item)
# Sort them.
output = []
for count in sorted(track.keys(), reverse=True):
sort = sorted(track[count], key=len, reverse=True)
output.extend(sort)
return output | def sort_list(items) | Sort a simple list by number of words and length. | 3.368852 | 3.090246 | 1.090156 |
self._say("Loading from directory: " + directory)
if ext is None:
# Use the default extensions - .rive is preferable.
ext = ['.rive', '.rs']
elif type(ext) == str:
# Backwards compatibility for ext being a string value.
ext = [ext]
if not os.path.isdir(directory):
self._warn("Error: " + directory + " is not a directory.")
return
for root, subdirs, files in os.walk(directory):
for file in files:
for extension in ext:
if file.lower().endswith(extension):
# Load this file.
self.load_file(os.path.join(root, file))
break | 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 ``[".rive", ".rs"]``. | 3.360636 | 2.846604 | 1.180578 |
self._say("Loading file: " + filename)
fh = codecs.open(filename, 'r', 'utf-8')
lines = fh.readlines()
fh.close()
self._say("Parsing " + str(len(lines)) + " lines of code from " + filename)
self._parse(filename, lines) | def load_file(self, filename) | Load and parse a RiveScript document.
:param str filename: The path to a RiveScript file. | 3.273136 | 3.166265 | 1.033753 |
self._say("Streaming code.")
if type(code) in [str, text_type]:
code = code.split("\n")
self._parse("stream()", code) | 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. | 9.388798 | 8.609152 | 1.09056 |
# Get the "abstract syntax tree"
ast = self._parser.parse(fname, code)
# Get all of the "begin" type variables: global, var, sub, person, ...
for kind, data in ast["begin"].items():
internal = getattr(self, "_" + kind) # The internal name for this attribute
for name, value in data.items():
if value == "<undef>":
del internal[name]
else:
internal[name] = value
# Precompile substitutions.
if kind in ["sub", "person"]:
self._precompile_substitution(kind, name)
# Let the scripts set the debug mode and other special globals.
if self._global.get("debug"):
self._debug = str(self._global["debug"]).lower() == "true"
if self._global.get("depth"):
self._depth = int(self._global["depth"])
# Consume all the parsed triggers.
for topic, data in ast["topics"].items():
# Keep a map of the topics that are included/inherited under this topic.
if not topic in self._includes:
self._includes[topic] = {}
if not topic in self._lineage:
self._lineage[topic] = {}
self._includes[topic].update(data["includes"])
self._lineage[topic].update(data["inherits"])
# Consume the triggers.
if not topic in self._topics:
self._topics[topic] = []
for trigger in data["triggers"]:
self._topics[topic].append(trigger)
# Precompile the regexp for this trigger.
self._precompile_regexp(trigger["trigger"])
# Does this trigger have a %Previous? If so, make a pointer to
# this exact trigger in _thats.
if trigger["previous"] is not None:
if not topic in self._thats:
self._thats[topic] = {}
if not trigger["trigger"] in self._thats[topic]:
self._thats[topic][trigger["trigger"]] = {}
self._thats[topic][trigger["trigger"]][trigger["previous"]] = trigger
# Load all the parsed objects.
for obj in ast["objects"]:
# Have a handler for it?
if obj["language"] in self._handlers:
self._objlangs[obj["name"]] = obj["language"]
self._handlers[obj["language"]].load(obj["name"], obj["code"]) | 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. | 3.900192 | 3.813722 | 1.022673 |
# Data to return.
result = {
"begin": {
"global": {},
"var": {},
"sub": {},
"person": {},
"array": {},
"triggers": [],
},
"topics": {},
}
# Populate the config fields.
if self._debug:
result["begin"]["global"]["debug"] = self._debug
if self._depth != 50:
result["begin"]["global"]["depth"] = 50
# Definitions
result["begin"]["var"] = self._var.copy()
result["begin"]["sub"] = self._sub.copy()
result["begin"]["person"] = self._person.copy()
result["begin"]["array"] = self._array.copy()
result["begin"]["global"].update(self._global.copy())
# Topic Triggers.
for topic in self._topics:
dest = None # Where to place the topic info
if topic == "__begin__":
# Begin block.
dest = result["begin"]
else:
# Normal topic.
if topic not in result["topics"]:
result["topics"][topic] = {
"triggers": [],
"includes": {},
"inherits": {},
}
dest = result["topics"][topic]
# Copy the triggers.
for trig in self._topics[topic]:
dest["triggers"].append(copy.deepcopy(trig))
# Inherits/Includes.
for label, mapping in {"inherits": self._lineage, "includes": self._includes}.items():
if topic in mapping and len(mapping[topic]):
dest[label] = mapping[topic].copy()
return result | 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 data structure containing the
contents of all RiveScript replies currently loaded in memory. | 3.57883 | 3.487732 | 1.02612 |
# Passed a string instead of a file handle?
if type(fh) is str:
fh = codecs.open(fh, "w", "utf-8")
# Deparse the loaded data.
if deparsed is None:
deparsed = self.deparse()
# Start at the beginning.
fh.write("// Written by rivescript.deparse()\n")
fh.write("! version = 2.0\n\n")
# Variables of all sorts!
for kind in ["global", "var", "sub", "person", "array"]:
if len(deparsed["begin"][kind].keys()) == 0:
continue
for var in sorted(deparsed["begin"][kind].keys()):
# Array types need to be separated by either spaces or pipes.
data = deparsed["begin"][kind][var]
if type(data) not in [str, text_type]:
needs_pipes = False
for test in data:
if " " in test:
needs_pipes = True
break
# Word-wrap the result, target width is 78 chars minus the
# kind, var, and spaces and equals sign.
# TODO: not implemented yet.
# width = 78 - len(kind) - len(var) - 4
if needs_pipes:
data = self._write_wrapped("|".join(data), sep="|")
else:
data = " ".join(data)
fh.write("! {kind} {var} = {data}\n".format(
kind=kind,
var=var,
data=data,
))
fh.write("\n")
# Begin block.
if len(deparsed["begin"]["triggers"]):
fh.write("> begin\n\n")
self._write_triggers(fh, deparsed["begin"]["triggers"], indent="\t")
fh.write("< begin\n\n")
# The topics. Random first!
topics = ["random"]
topics.extend(sorted(deparsed["topics"].keys()))
done_random = False
for topic in topics:
if topic not in deparsed["topics"]: continue
if topic == "random" and done_random: continue
if topic == "random": done_random = True
tagged = False # Used > topic tag
data = deparsed["topics"][topic]
if topic != "random" or len(data["includes"]) or len(data["inherits"]):
tagged = True
fh.write("> topic " + topic)
if data["inherits"]:
fh.write(" inherits " + " ".join(sorted(data["inherits"].keys())))
if data["includes"]:
fh.write(" includes " + " ".join(sorted(data["includes"].keys())))
fh.write("\n\n")
indent = "\t" if tagged else ""
self._write_triggers(fh, data["triggers"], indent=indent)
if tagged:
fh.write("< topic\n\n")
return True | 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 data as the
``deparsed`` argument, it will use that data instead of calling
``deparse()`` itself. This way you can use ``deparse()``, edit the data,
and use that to write the RiveScript document (for example, to be used
by a user interface for editing RiveScript without writing the code
directly).
Parameters:
fh (str or file): a string or a file-like object.
deparsed (dict): a data structure in the same format as what
``deparse()`` returns. If not passed, this value will come from
the current in-memory data from ``deparse()``. | 3.732733 | 3.656713 | 1.020789 |
for trig in triggers:
fh.write(indent + "+ " + self._write_wrapped(trig["trigger"], indent=indent) + "\n")
d = trig
if d.get("previous"):
fh.write(indent + "% " + self._write_wrapped(d["previous"], indent=indent) + "\n")
for cond in d["condition"]:
fh.write(indent + "* " + self._write_wrapped(cond, indent=indent) + "\n")
if d.get("redirect"):
fh.write(indent + "@ " + self._write_wrapped(d["redirect"], indent=indent) + "\n")
for reply in d["reply"]:
fh.write(indent + "- " + self._write_wrapped(reply, indent=indent) + "\n")
fh.write("\n") | 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. | 2.334254 | 2.440917 | 0.956302 |
words = line.split(sep)
lines = []
line = ""
buf = []
while len(words):
buf.append(words.pop(0))
line = sep.join(buf)
if len(line) > width:
# Need to word wrap!
words.insert(0, buf.pop()) # Undo
lines.append(sep.join(buf))
buf = []
line = ""
# Straggler?
if line:
lines.append(line)
# Returned output
result = lines.pop(0)
if len(lines):
eol = ""
if sep == " ":
eol = "\s"
for item in lines:
result += eol + "\n" + indent + "^ " + item
return result | 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).
:param int width: The character width to constrain each line to.
:return str: The reformatted line(s). | 4.109231 | 4.142865 | 0.991882 |
# (Re)initialize the sort cache.
self._sorted["topics"] = {}
self._sorted["thats"] = {}
self._say("Sorting triggers...")
# Loop through all the topics.
for topic in self._topics.keys():
self._say("Analyzing topic " + topic)
# Collect a list of all the triggers we're going to worry about.
# If this topic inherits another topic, we need to recursively add
# those to the list as well.
alltrig = inherit_utils.get_topic_triggers(self, topic, False)
# Sort them.
self._sorted["topics"][topic] = sorting.sort_trigger_set(alltrig, True, self._say)
# Get all of the %Previous triggers for this topic.
that_triggers = inherit_utils.get_topic_triggers(self, topic, True)
# And sort them, too.
self._sorted["thats"][topic] = sorting.sort_trigger_set(that_triggers, False, self._say)
# And sort the substitution lists.
if not "lists" in self._sorted:
self._sorted["lists"] = {}
self._sorted["lists"]["sub"] = sorting.sort_list(self._sub.keys())
self._sorted["lists"]["person"] = sorting.sort_list(self._person.keys()) | 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! | 4.218731 | 3.969657 | 1.062745 |
# Allow them to delete a handler too.
if obj is None:
if language in self._handlers:
del self._handlers[language]
else:
self._handlers[language] = obj | 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 rivescript-python distribution for
an example script that sets up a JavaScript language handler.
:param str language: The lowercased name of the programming language.
Examples: python, javascript, perl
:param class obj: An instance of an implementation class object.
It should provide the following interface::
class MyObjectHandler:
def __init__(self):
pass
def load(self, name, code):
# name = the name of the object from the RiveScript code
# code = the source code of the object
def call(self, rs, name, fields):
# rs = the current RiveScript interpreter object
# name = the name of the object being called
# fields = array of arguments passed to the object
return reply | 5.089602 | 4.017328 | 1.266912 |
# Do we have a Python handler?
if 'python' in self._handlers:
self._handlers['python']._objects[name] = code
self._objlangs[name] = 'python'
else:
self._warn("Can't set_subroutine: no Python object handler!") | 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 function with a method signature of
``(rs, args)``
This method is only available if there is a Python handler set up
(which there is by default, unless you've called
``set_handler("python", None)``). | 7.181961 | 5.304086 | 1.354043 |
if value is None:
# Unset the variable.
if name in self._global:
del self._global[name]
self._global[name] = value | 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. | 3.910143 | 4.439991 | 0.880665 |
if value is None:
# Unset the variable.
if name in self._var:
del self._var[name]
self._var[name] = value | 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. | 3.876374 | 4.963394 | 0.780993 |
if rep is None:
# Unset the variable.
if what in self._subs:
del self._subs[what]
self._subs[what] = rep | 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. | 4.37681 | 4.930574 | 0.887688 |
if rep is None:
# Unset the variable.
if what in self._person:
del self._person[what]
self._person[what] = rep | 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. | 4.369724 | 5.080297 | 0.860132 |
self._session.set(user, {name: value}) | 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. | 11.026203 | 18.93046 | 0.582458 |
# Check the parameters to see how we're being used.
if type(user) is dict and data is None:
# Setting many variables for many users.
for uid, uservars in user.items():
if type(uservars) is not dict:
raise TypeError(
"In set_uservars(many_vars) syntax, the many_vars dict "
"must be in the format of `many_vars['username'] = "
"dict(key=value)`, but the contents of many_vars['{}']"
" is not a dict.".format(uid)
)
self._session.set(uid, uservars)
elif type(user) in [text_type, str] and type(data) is dict:
# Setting variables for a single user.
self._session.set(user, data)
else:
raise TypeError(
"set_uservars() may only be called with types ({str}, dict) or "
"(dict<{str}, dict>) but you called it with types ({a}, {b})"
.format(
str="unicode" if sys.version_info[0] < 3 else "str",
a=type(user),
b=type(data),
),
) | 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 for many users.
rs.set_uservars(many_vars)
In the first syntax, ``vars`` is a simple dict of key/value string
pairs. In the second syntax, ``many_vars`` is a structure like this::
{
"username1": {
"key": "value",
},
"username2": {
"key": "value",
},
}
This way you can export *all* user variables via ``get_uservars()``
and then re-import them all at once, instead of setting them once per
user.
:param optional str user: The user ID to set many variables for.
Skip this parameter to set many variables for many users instead.
:param dict data: The dictionary of key/value pairs for user variables,
or else a dict of dicts mapping usernames to key/value pairs.
This may raise a ``TypeError`` exception if you pass it invalid data
types. Note that only the standard ``dict`` type is accepted, but not
variants like ``OrderedDict``, so if you have a dict-like type you
should cast it to ``dict`` first. | 4.209327 | 3.514672 | 1.197644 |
if name == '__lastmatch__': # Treat var `__lastmatch__` since it can't receive "undefined" value
return self.last_match(user)
else:
return self._session.get(user, name) | 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 returns ``None``.
* If the user doesn't have this variable set, this returns the
string ``"undefined"``.
* Otherwise this returns the string value of the variable. | 13.58221 | 15.990017 | 0.849418 |
if user is None:
# All the users!
return self._session.get_all()
else:
# Just this one!
return self._session.get_any(user) | 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 ``user`` was passed, this is a ``dict`` of key/value pairs
of that user's variables. If the user doesn't exist in memory,
this returns ``None``.
* Otherwise, this returns a ``dict`` of key/value pairs that map
user IDs to their variables (a ``dict`` of ``dict``). | 5.666521 | 6.042542 | 0.937771 |
if user is None:
# All the users!
self._session.reset_all()
else:
# Just this one.
self._session.reset(user) | 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. | 6.100304 | 6.356982 | 0.959623 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.