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 decip...
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 strin...
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 i...
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 i...
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 Fa...
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 re...
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(...
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 encipher...
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(strin...
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 stri...
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 = '' ...
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. ...
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...
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...
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(...
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].shap...
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 = ...
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...
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))]) ...
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 - ...
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) ...
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.app...
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) ...
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 approxi...
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 ...
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), ...
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.tens...
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): ...
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): ...
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_ste...
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 mat...
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 xr...
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 & -\\...
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') pr...
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 ...
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 truncati...
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+...
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: ...
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.cor...
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) ...
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...
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() ...
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 =...
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 ...
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(...
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. Oselede...
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 -...
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 d...
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...
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 ...
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 a...
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-ort...
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 diction...
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...
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 = _cach...
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. ...
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 resu...
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 st...
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....
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_na...
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 coun...
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_repl...
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 exc...
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: ...
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. :retu...
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 inc...
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.messag...
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 sur...
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_o...
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 ...
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] = [] ...
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] ...
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 ...
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": {}, ...
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...
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.de...
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 wil...
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["...
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 ...
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. ...
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 ...
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 scri...
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 ``(r...
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( ...
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_var...
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 doe...
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/valu...
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