How to use block method in pytest-django

Best Python code snippet using pytest-django_python

lobpcg.py

Source:lobpcg.py Github

copy

Full Screen

1"""2Locally Optimal Block Preconditioned Conjugate Gradient Method (LOBPCG).3References4----------5.. [1] A. V. Knyazev (2001),6 Toward the Optimal Preconditioned Eigensolver: Locally Optimal7 Block Preconditioned Conjugate Gradient Method.8 SIAM Journal on Scientific Computing 23, no. 2,9 pp. 517-541. http://dx.doi.org/10.1137/S106482750036612410.. [2] A. V. Knyazev, I. Lashuk, M. E. Argentati, and E. Ovchinnikov (2007),11 Block Locally Optimal Preconditioned Eigenvalue Xolvers (BLOPEX)12 in hypre and PETSc. https://arxiv.org/abs/0705.262613.. [3] A. V. Knyazev's C and MATLAB implementations:14 https://github.com/lobpcg/blopex15"""16from __future__ import division, print_function, absolute_import17import numpy as np18from scipy.linalg import (inv, eigh, cho_factor, cho_solve, cholesky, orth,19 LinAlgError)20from scipy.sparse.linalg import aslinearoperator21from scipy.sparse.sputils import bmat22__all__ = ['lobpcg']23def _report_nonhermitian(M, name):24 """25 Report if `M` is not a hermitian matrix given its type.26 """27 from scipy.linalg import norm28 md = M - M.T.conj()29 nmd = norm(md, 1)30 tol = 10 * np.finfo(M.dtype).eps31 tol = max(tol, tol * norm(M, 1))32 if nmd > tol:33 print('matrix %s of the type %s is not sufficiently Hermitian:'34 % (name, M.dtype))35 print('condition: %.e < %e' % (nmd, tol))36def _as2d(ar):37 """38 If the input array is 2D return it, if it is 1D, append a dimension,39 making it a column vector.40 """41 if ar.ndim == 2:42 return ar43 else: # Assume 1!44 aux = np.array(ar, copy=False)45 aux.shape = (ar.shape[0], 1)46 return aux47def _makeOperator(operatorInput, expectedShape):48 """Takes a dense numpy array or a sparse matrix or49 a function and makes an operator performing matrix * blockvector50 products."""51 if operatorInput is None:52 return None53 else:54 operator = aslinearoperator(operatorInput)55 if operator.shape != expectedShape:56 raise ValueError('operator has invalid shape')57 return operator58def _applyConstraints(blockVectorV, factYBY, blockVectorBY, blockVectorY):59 """Changes blockVectorV in place."""60 YBV = np.dot(blockVectorBY.T.conj(), blockVectorV)61 tmp = cho_solve(factYBY, YBV)62 blockVectorV -= np.dot(blockVectorY, tmp)63def _b_orthonormalize(B, blockVectorV, blockVectorBV=None, retInvR=False):64 """B-orthonormalize the given block vector using Cholesky."""65 normalization = blockVectorV.max(axis=0)+np.finfo(blockVectorV.dtype).eps66 blockVectorV = blockVectorV / normalization67 if blockVectorBV is None:68 if B is not None:69 blockVectorBV = B(blockVectorV)70 else:71 blockVectorBV = blockVectorV # Shared data!!!72 else:73 blockVectorBV = blockVectorBV / normalization74 VBV = np.matmul(blockVectorV.T.conj(), blockVectorBV)75 try:76 # VBV is a Cholesky factor from now on...77 VBV = cholesky(VBV, overwrite_a=True)78 VBV = inv(VBV, overwrite_a=True)79 blockVectorV = np.matmul(blockVectorV, VBV)80 # blockVectorV = (cho_solve((VBV.T, True), blockVectorV.T)).T81 if B is not None:82 blockVectorBV = np.matmul(blockVectorBV, VBV)83 # blockVectorBV = (cho_solve((VBV.T, True), blockVectorBV.T)).T84 else:85 blockVectorBV = None86 except LinAlgError:87 #raise ValueError('Cholesky has failed')88 blockVectorV = None89 blockVectorBV = None90 VBV = None91 if retInvR:92 return blockVectorV, blockVectorBV, VBV, normalization93 else:94 return blockVectorV, blockVectorBV95def _get_indx(_lambda, num, largest):96 """Get `num` indices into `_lambda` depending on `largest` option."""97 ii = np.argsort(_lambda)98 if largest:99 ii = ii[:-num-1:-1]100 else:101 ii = ii[:num]102 return ii103def lobpcg(A, X,104 B=None, M=None, Y=None,105 tol=None, maxiter=None,106 largest=True, verbosityLevel=0,107 retLambdaHistory=False, retResidualNormsHistory=False):108 """Locally Optimal Block Preconditioned Conjugate Gradient Method (LOBPCG)109 LOBPCG is a preconditioned eigensolver for large symmetric positive110 definite (SPD) generalized eigenproblems.111 Parameters112 ----------113 A : {sparse matrix, dense matrix, LinearOperator}114 The symmetric linear operator of the problem, usually a115 sparse matrix. Often called the "stiffness matrix".116 X : ndarray, float32 or float64117 Initial approximation to the ``k`` eigenvectors (non-sparse). If `A`118 has ``shape=(n,n)`` then `X` should have shape ``shape=(n,k)``.119 B : {dense matrix, sparse matrix, LinearOperator}, optional120 The right hand side operator in a generalized eigenproblem.121 By default, ``B = Identity``. Often called the "mass matrix".122 M : {dense matrix, sparse matrix, LinearOperator}, optional123 Preconditioner to `A`; by default ``M = Identity``.124 `M` should approximate the inverse of `A`.125 Y : ndarray, float32 or float64, optional126 n-by-sizeY matrix of constraints (non-sparse), sizeY < n127 The iterations will be performed in the B-orthogonal complement128 of the column-space of Y. Y must be full rank.129 tol : scalar, optional130 Solver tolerance (stopping criterion).131 The default is ``tol=n*sqrt(eps)``.132 maxiter : int, optional133 Maximum number of iterations. The default is ``maxiter = 20``.134 largest : bool, optional135 When True, solve for the largest eigenvalues, otherwise the smallest.136 verbosityLevel : int, optional137 Controls solver output. The default is ``verbosityLevel=0``.138 retLambdaHistory : bool, optional139 Whether to return eigenvalue history. Default is False.140 retResidualNormsHistory : bool, optional141 Whether to return history of residual norms. Default is False.142 Returns143 -------144 w : ndarray145 Array of ``k`` eigenvalues146 v : ndarray147 An array of ``k`` eigenvectors. `v` has the same shape as `X`.148 lambdas : list of ndarray, optional149 The eigenvalue history, if `retLambdaHistory` is True.150 rnorms : list of ndarray, optional151 The history of residual norms, if `retResidualNormsHistory` is True.152 Notes153 -----154 If both ``retLambdaHistory`` and ``retResidualNormsHistory`` are True,155 the return tuple has the following format156 ``(lambda, V, lambda history, residual norms history)``.157 In the following ``n`` denotes the matrix size and ``m`` the number158 of required eigenvalues (smallest or largest).159 The LOBPCG code internally solves eigenproblems of the size ``3m`` on every160 iteration by calling the "standard" dense eigensolver, so if ``m`` is not161 small enough compared to ``n``, it does not make sense to call the LOBPCG162 code, but rather one should use the "standard" eigensolver, e.g. numpy or163 scipy function in this case.164 If one calls the LOBPCG algorithm for ``5m > n``, it will most likely break165 internally, so the code tries to call the standard function instead.166 It is not that ``n`` should be large for the LOBPCG to work, but rather the167 ratio ``n / m`` should be large. It you call LOBPCG with ``m=1``168 and ``n=10``, it works though ``n`` is small. The method is intended169 for extremely large ``n / m``, see e.g., reference [28] in170 https://arxiv.org/abs/0705.2626171 The convergence speed depends basically on two factors:172 1. How well relatively separated the seeking eigenvalues are from the rest173 of the eigenvalues. One can try to vary ``m`` to make this better.174 2. How well conditioned the problem is. This can be changed by using proper175 preconditioning. For example, a rod vibration test problem (under tests176 directory) is ill-conditioned for large ``n``, so convergence will be177 slow, unless efficient preconditioning is used. For this specific178 problem, a good simple preconditioner function would be a linear solve179 for `A`, which is easy to code since A is tridiagonal.180 References181 ----------182 .. [1] A. V. Knyazev (2001),183 Toward the Optimal Preconditioned Eigensolver: Locally Optimal184 Block Preconditioned Conjugate Gradient Method.185 SIAM Journal on Scientific Computing 23, no. 2,186 pp. 517-541. http://dx.doi.org/10.1137/S1064827500366124187 .. [2] A. V. Knyazev, I. Lashuk, M. E. Argentati, and E. Ovchinnikov188 (2007), Block Locally Optimal Preconditioned Eigenvalue Xolvers189 (BLOPEX) in hypre and PETSc. https://arxiv.org/abs/0705.2626190 .. [3] A. V. Knyazev's C and MATLAB implementations:191 https://bitbucket.org/joseroman/blopex192 Examples193 --------194 Solve ``A x = lambda x`` with constraints and preconditioning.195 >>> import numpy as np196 >>> from scipy.sparse import spdiags, issparse197 >>> from scipy.sparse.linalg import lobpcg, LinearOperator198 >>> n = 100199 >>> vals = np.arange(1, n + 1)200 >>> A = spdiags(vals, 0, n, n)201 >>> A.toarray()202 array([[ 1., 0., 0., ..., 0., 0., 0.],203 [ 0., 2., 0., ..., 0., 0., 0.],204 [ 0., 0., 3., ..., 0., 0., 0.],205 ...,206 [ 0., 0., 0., ..., 98., 0., 0.],207 [ 0., 0., 0., ..., 0., 99., 0.],208 [ 0., 0., 0., ..., 0., 0., 100.]])209 Constraints:210 >>> Y = np.eye(n, 3)211 Initial guess for eigenvectors, should have linearly independent212 columns. Column dimension = number of requested eigenvalues.213 >>> X = np.random.rand(n, 3)214 Preconditioner in the inverse of A in this example:215 >>> invA = spdiags([1./vals], 0, n, n)216 The preconditiner must be defined by a function:217 >>> def precond( x ):218 ... return invA @ x219 The argument x of the preconditioner function is a matrix inside `lobpcg`,220 thus the use of matrix-matrix product ``@``.221 The preconditioner function is passed to lobpcg as a `LinearOperator`:222 >>> M = LinearOperator(matvec=precond, matmat=precond,223 ... shape=(n, n), dtype=float)224 Let us now solve the eigenvalue problem for the matrix A:225 >>> eigenvalues, _ = lobpcg(A, X, Y=Y, M=M, largest=False)226 >>> eigenvalues227 array([4., 5., 6.])228 Note that the vectors passed in Y are the eigenvectors of the 3 smallest229 eigenvalues. The results returned are orthogonal to those.230 """231 blockVectorX = X232 blockVectorY = Y233 residualTolerance = tol234 if maxiter is None:235 maxiter = 20236 if blockVectorY is not None:237 sizeY = blockVectorY.shape[1]238 else:239 sizeY = 0240 # Block size.241 if len(blockVectorX.shape) != 2:242 raise ValueError('expected rank-2 array for argument X')243 n, sizeX = blockVectorX.shape244 if verbosityLevel:245 aux = "Solving "246 if B is None:247 aux += "standard"248 else:249 aux += "generalized"250 aux += " eigenvalue problem with"251 if M is None:252 aux += "out"253 aux += " preconditioning\n\n"254 aux += "matrix size %d\n" % n255 aux += "block size %d\n\n" % sizeX256 if blockVectorY is None:257 aux += "No constraints\n\n"258 else:259 if sizeY > 1:260 aux += "%d constraints\n\n" % sizeY261 else:262 aux += "%d constraint\n\n" % sizeY263 print(aux)264 A = _makeOperator(A, (n, n))265 B = _makeOperator(B, (n, n))266 M = _makeOperator(M, (n, n))267 if (n - sizeY) < (5 * sizeX):268 # warn('The problem size is small compared to the block size.' \269 # ' Using dense eigensolver instead of LOBPCG.')270 sizeX = min(sizeX, n)271 if blockVectorY is not None:272 raise NotImplementedError('The dense eigensolver '273 'does not support constraints.')274 # Define the closed range of indices of eigenvalues to return.275 if largest:276 eigvals = (n - sizeX, n-1)277 else:278 eigvals = (0, sizeX-1)279 A_dense = A(np.eye(n, dtype=A.dtype))280 B_dense = None if B is None else B(np.eye(n, dtype=B.dtype))281 vals, vecs = eigh(A_dense, B_dense, eigvals=eigvals,282 check_finite=False)283 if largest:284 # Reverse order to be compatible with eigs() in 'LM' mode.285 vals = vals[::-1]286 vecs = vecs[:, ::-1]287 return vals, vecs288 if (residualTolerance is None) or (residualTolerance <= 0.0):289 residualTolerance = np.sqrt(1e-15) * n290 # Apply constraints to X.291 if blockVectorY is not None:292 if B is not None:293 blockVectorBY = B(blockVectorY)294 else:295 blockVectorBY = blockVectorY296 # gramYBY is a dense array.297 gramYBY = np.dot(blockVectorY.T.conj(), blockVectorBY)298 try:299 # gramYBY is a Cholesky factor from now on...300 gramYBY = cho_factor(gramYBY)301 except LinAlgError:302 raise ValueError('cannot handle linearly dependent constraints')303 _applyConstraints(blockVectorX, gramYBY, blockVectorBY, blockVectorY)304 ##305 # B-orthonormalize X.306 blockVectorX, blockVectorBX = _b_orthonormalize(B, blockVectorX)307 ##308 # Compute the initial Ritz vectors: solve the eigenproblem.309 blockVectorAX = A(blockVectorX)310 gramXAX = np.dot(blockVectorX.T.conj(), blockVectorAX)311 _lambda, eigBlockVector = eigh(gramXAX, check_finite=False)312 ii = _get_indx(_lambda, sizeX, largest)313 _lambda = _lambda[ii]314 eigBlockVector = np.asarray(eigBlockVector[:, ii])315 blockVectorX = np.dot(blockVectorX, eigBlockVector)316 blockVectorAX = np.dot(blockVectorAX, eigBlockVector)317 if B is not None:318 blockVectorBX = np.dot(blockVectorBX, eigBlockVector)319 ##320 # Active index set.321 activeMask = np.ones((sizeX,), dtype=bool)322 lambdaHistory = [_lambda]323 residualNormsHistory = []324 previousBlockSize = sizeX325 ident = np.eye(sizeX, dtype=A.dtype)326 ident0 = np.eye(sizeX, dtype=A.dtype)327 ##328 # Main iteration loop.329 blockVectorP = None # set during iteration330 blockVectorAP = None331 blockVectorBP = None332 iterationNumber = -1333 restart = True334 explicitGramFlag = False335 while iterationNumber < maxiter:336 iterationNumber += 1337 if verbosityLevel > 0:338 print('iteration %d' % iterationNumber)339 if B is not None:340 aux = blockVectorBX * _lambda[np.newaxis, :]341 else:342 aux = blockVectorX * _lambda[np.newaxis, :]343 blockVectorR = blockVectorAX - aux344 aux = np.sum(blockVectorR.conj() * blockVectorR, 0)345 residualNorms = np.sqrt(aux)346 residualNormsHistory.append(residualNorms)347 ii = np.where(residualNorms > residualTolerance, True, False)348 activeMask = activeMask & ii349 if verbosityLevel > 2:350 print(activeMask)351 currentBlockSize = activeMask.sum()352 if currentBlockSize != previousBlockSize:353 previousBlockSize = currentBlockSize354 ident = np.eye(currentBlockSize, dtype=A.dtype)355 if currentBlockSize == 0:356 break357 if verbosityLevel > 0:358 print('current block size:', currentBlockSize)359 print('eigenvalue:', _lambda)360 print('residual norms:', residualNorms)361 if verbosityLevel > 10:362 print(eigBlockVector)363 activeBlockVectorR = _as2d(blockVectorR[:, activeMask])364 if iterationNumber > 0:365 activeBlockVectorP = _as2d(blockVectorP[:, activeMask])366 activeBlockVectorAP = _as2d(blockVectorAP[:, activeMask])367 if B is not None:368 activeBlockVectorBP = _as2d(blockVectorBP[:, activeMask])369 if M is not None:370 # Apply preconditioner T to the active residuals.371 activeBlockVectorR = M(activeBlockVectorR)372 ##373 # Apply constraints to the preconditioned residuals.374 if blockVectorY is not None:375 _applyConstraints(activeBlockVectorR,376 gramYBY, blockVectorBY, blockVectorY)377 ##378 # B-orthogonalize the preconditioned residuals to X.379 if B is not None:380 activeBlockVectorR = activeBlockVectorR - np.matmul(blockVectorX,381 np.matmul(blockVectorBX.T.conj(),382 activeBlockVectorR))383 else:384 activeBlockVectorR = activeBlockVectorR - np.matmul(blockVectorX,385 np.matmul(blockVectorX.T.conj(),386 activeBlockVectorR))387 ##388 # B-orthonormalize the preconditioned residuals.389 aux = _b_orthonormalize(B, activeBlockVectorR)390 activeBlockVectorR, activeBlockVectorBR = aux391 activeBlockVectorAR = A(activeBlockVectorR)392 if iterationNumber > 0:393 if B is not None:394 aux = _b_orthonormalize(B, activeBlockVectorP,395 activeBlockVectorBP, retInvR=True)396 activeBlockVectorP, activeBlockVectorBP, invR, normal = aux397 else:398 aux = _b_orthonormalize(B, activeBlockVectorP, retInvR=True)399 activeBlockVectorP, _, invR, normal = aux400 # Function _b_orthonormalize returns None if Cholesky fails401 if activeBlockVectorP is not None:402 activeBlockVectorAP = activeBlockVectorAP / normal403 activeBlockVectorAP = np.dot(activeBlockVectorAP, invR)404 restart = False405 else:406 restart = True407 ##408 # Perform the Rayleigh Ritz Procedure:409 # Compute symmetric Gram matrices:410 if activeBlockVectorAR.dtype == 'float32':411 myeps = 1412 elif activeBlockVectorR.dtype == 'float32':413 myeps = 1e-4414 else:415 myeps = 1e-8416 if residualNorms.max() > myeps and not explicitGramFlag:417 explicitGramFlag = False418 else:419 # Once explicitGramFlag, forever explicitGramFlag.420 explicitGramFlag = True421 # Shared memory assingments to simplify the code422 if B is None:423 blockVectorBX = blockVectorX424 activeBlockVectorBR = activeBlockVectorR425 if not restart:426 activeBlockVectorBP = activeBlockVectorP427 # Common submatrices:428 gramXAR = np.dot(blockVectorX.T.conj(), activeBlockVectorAR)429 gramRAR = np.dot(activeBlockVectorR.T.conj(), activeBlockVectorAR)430 if explicitGramFlag:431 gramRAR = (gramRAR + gramRAR.T.conj())/2432 gramXAX = np.dot(blockVectorX.T.conj(), blockVectorAX)433 gramXAX = (gramXAX + gramXAX.T.conj())/2434 gramXBX = np.dot(blockVectorX.T.conj(), blockVectorBX)435 gramRBR = np.dot(activeBlockVectorR.T.conj(), activeBlockVectorBR)436 gramXBR = np.dot(blockVectorX.T.conj(), activeBlockVectorBR)437 else:438 gramXAX = np.diag(_lambda)439 gramXBX = ident0440 gramRBR = ident441 gramXBR = np.zeros((sizeX, currentBlockSize), dtype=A.dtype)442 def _handle_gramA_gramB_verbosity(gramA, gramB):443 if verbosityLevel > 0:444 _report_nonhermitian(gramA, 'gramA')445 _report_nonhermitian(gramB, 'gramB')446 if verbosityLevel > 10:447 # Note: not documented, but leave it in here for now448 np.savetxt('gramA.txt', gramA)449 np.savetxt('gramB.txt', gramB)450 if not restart:451 gramXAP = np.dot(blockVectorX.T.conj(), activeBlockVectorAP)452 gramRAP = np.dot(activeBlockVectorR.T.conj(), activeBlockVectorAP)453 gramPAP = np.dot(activeBlockVectorP.T.conj(), activeBlockVectorAP)454 gramXBP = np.dot(blockVectorX.T.conj(), activeBlockVectorBP)455 gramRBP = np.dot(activeBlockVectorR.T.conj(), activeBlockVectorBP)456 if explicitGramFlag:457 gramPAP = (gramPAP + gramPAP.T.conj())/2458 gramPBP = np.dot(activeBlockVectorP.T.conj(),459 activeBlockVectorBP)460 else:461 gramPBP = ident462 gramA = bmat([[gramXAX, gramXAR, gramXAP],463 [gramXAR.T.conj(), gramRAR, gramRAP],464 [gramXAP.T.conj(), gramRAP.T.conj(), gramPAP]])465 gramB = bmat([[gramXBX, gramXBR, gramXBP],466 [gramXBR.T.conj(), gramRBR, gramRBP],467 [gramXBP.T.conj(), gramRBP.T.conj(), gramPBP]])468 _handle_gramA_gramB_verbosity(gramA, gramB)469 try:470 _lambda, eigBlockVector = eigh(gramA, gramB,471 check_finite=False)472 except LinAlgError:473 # try again after dropping the direction vectors P from RR474 restart = True475 if restart:476 gramA = bmat([[gramXAX, gramXAR],477 [gramXAR.T.conj(), gramRAR]])478 gramB = bmat([[gramXBX, gramXBR],479 [gramXBR.T.conj(), gramRBR]])480 _handle_gramA_gramB_verbosity(gramA, gramB)481 try:482 _lambda, eigBlockVector = eigh(gramA, gramB,483 check_finite=False)484 except LinAlgError:485 raise ValueError('eigh has failed in lobpcg iterations')486 ii = _get_indx(_lambda, sizeX, largest)487 if verbosityLevel > 10:488 print(ii)489 print(_lambda)490 _lambda = _lambda[ii]491 eigBlockVector = eigBlockVector[:, ii]492 lambdaHistory.append(_lambda)493 if verbosityLevel > 10:494 print('lambda:', _lambda)495# # Normalize eigenvectors!496# aux = np.sum( eigBlockVector.conj() * eigBlockVector, 0 )497# eigVecNorms = np.sqrt( aux )498# eigBlockVector = eigBlockVector / eigVecNorms[np.newaxis, :]499# eigBlockVector, aux = _b_orthonormalize( B, eigBlockVector )500 if verbosityLevel > 10:501 print(eigBlockVector)502 # Compute Ritz vectors.503 if B is not None:504 if not restart:505 eigBlockVectorX = eigBlockVector[:sizeX]506 eigBlockVectorR = eigBlockVector[sizeX:sizeX+currentBlockSize]507 eigBlockVectorP = eigBlockVector[sizeX+currentBlockSize:]508 pp = np.dot(activeBlockVectorR, eigBlockVectorR)509 pp += np.dot(activeBlockVectorP, eigBlockVectorP)510 app = np.dot(activeBlockVectorAR, eigBlockVectorR)511 app += np.dot(activeBlockVectorAP, eigBlockVectorP)512 bpp = np.dot(activeBlockVectorBR, eigBlockVectorR)513 bpp += np.dot(activeBlockVectorBP, eigBlockVectorP)514 else:515 eigBlockVectorX = eigBlockVector[:sizeX]516 eigBlockVectorR = eigBlockVector[sizeX:]517 pp = np.dot(activeBlockVectorR, eigBlockVectorR)518 app = np.dot(activeBlockVectorAR, eigBlockVectorR)519 bpp = np.dot(activeBlockVectorBR, eigBlockVectorR)520 if verbosityLevel > 10:521 print(pp)522 print(app)523 print(bpp)524 blockVectorX = np.dot(blockVectorX, eigBlockVectorX) + pp525 blockVectorAX = np.dot(blockVectorAX, eigBlockVectorX) + app526 blockVectorBX = np.dot(blockVectorBX, eigBlockVectorX) + bpp527 blockVectorP, blockVectorAP, blockVectorBP = pp, app, bpp528 else:529 if not restart:530 eigBlockVectorX = eigBlockVector[:sizeX]531 eigBlockVectorR = eigBlockVector[sizeX:sizeX+currentBlockSize]532 eigBlockVectorP = eigBlockVector[sizeX+currentBlockSize:]533 pp = np.dot(activeBlockVectorR, eigBlockVectorR)534 pp += np.dot(activeBlockVectorP, eigBlockVectorP)535 app = np.dot(activeBlockVectorAR, eigBlockVectorR)536 app += np.dot(activeBlockVectorAP, eigBlockVectorP)537 else:538 eigBlockVectorX = eigBlockVector[:sizeX]539 eigBlockVectorR = eigBlockVector[sizeX:]540 pp = np.dot(activeBlockVectorR, eigBlockVectorR)541 app = np.dot(activeBlockVectorAR, eigBlockVectorR)542 if verbosityLevel > 10:543 print(pp)544 print(app)545 blockVectorX = np.dot(blockVectorX, eigBlockVectorX) + pp546 blockVectorAX = np.dot(blockVectorAX, eigBlockVectorX) + app547 blockVectorP, blockVectorAP = pp, app548 if B is not None:549 aux = blockVectorBX * _lambda[np.newaxis, :]550 else:551 aux = blockVectorX * _lambda[np.newaxis, :]552 blockVectorR = blockVectorAX - aux553 aux = np.sum(blockVectorR.conj() * blockVectorR, 0)554 residualNorms = np.sqrt(aux)555 # Future work: Need to add Postprocessing here:556 # Making sure eigenvectors "exactly" satisfy the blockVectorY constrains?557 # Making sure eigenvecotrs are "exactly" othonormalized by final "exact" RR558 # Computing the actual true residuals559 if verbosityLevel > 0:560 print('final eigenvalue:', _lambda)561 print('final residual norms:', residualNorms)562 if retLambdaHistory:563 if retResidualNormsHistory:564 return _lambda, blockVectorX, lambdaHistory, residualNormsHistory565 else:566 return _lambda, blockVectorX, lambdaHistory567 else:568 if retResidualNormsHistory:569 return _lambda, blockVectorX, residualNormsHistory570 else:...

Full Screen

Full Screen

js.js

Source:js.js Github

copy

Full Screen

1var chess=document.getElementById('chess');2var context=chess.getContext('2d');3var i;4var superBlock=-1;5var block=[];6var startD=[],endD=[];7for(var i=1;i<=10;i++){8 block[i]=[];9 for(j=1;j<=10;j++){10 block[i][j]=0;11 }12}13window.onload=function(){14 drawchessbox();15 clickXY();16}17//¼üÅÌʼþ18document.onkeydown=function(event){19 var e = event || window.event || arguments.callee.caller.arguments[0];20 if(e && e.keyCode==65){ // °´ A21 mvRobot();22 mvSuper(1,0);23 }24 if(e && e.keyCode==68){ // °´ D25 mvRobot();26 mvSuper(-1,0);27 }28 if(e && e.keyCode==83){ // S ¼ü29 mvRobot();30 mvSuper(0,-1);31 }32 if(e && e.keyCode==87){ // W ¼ü33 mvRobot();34 mvSuper(0,1);35 }36};37function mvRobot(){38 for(var i=1;i<=10;i++){39 for(var j=1;j<=10;j++){40 if(block[i][j]==3){41 robot(i,j);42 }43 }44 }45}46function robot(i,j){47 if(i<=startD[1]&&j<=endD[1]){48 if(block[i][j]==2){49 drawBlock(i+1,j,"red");50 drawBlock(i,j,"white");51 block[i+1][j]=3;52 block[i][j]=0;53 }else{54 drawBlock(i,j+1,"red");55 drawBlock(i,j,"white");56 block[i][j+1]=3;57 block[i][j]=0;58 }59 }else if(i>startD[1]&&j<=endD[1]){60 if(block[i][j]==2){61 drawBlock(i,j+1,"red");62 drawBlock(i,j,"white");63 block[i][j+1]=3;64 block[i][j]=0;65 }else{66 drawBlock(i-1,j,"red");67 drawBlock(i,j,"white");68 block[i-1][j]=3;69 block[i][j]=0;70 }71 }else if(i>startD[1]&&j>endD[1]){72 if(block[i][j]==2){73 drawBlock(i-1,j,"red");74 drawBlock(i,j,"white");75 block[i-1][j]=3;76 block[i][j]=0;77 }else{78 drawBlock(i,j-1,"red");79 drawBlock(i,j,"white");80 block[i][j-1]=3;81 block[i][j]=0;82 }83 }else if(i<=startD[1]&&j>endD[1]){84 if(block[i][j]==2){85 drawBlock(i,j-1,"red");86 drawBlock(i,j,"white");87 block[i][j-1]=3;88 block[i][j]=0;89 }else{90 drawBlock(i+1,j,"red");91 drawBlock(i,j,"white");92 block[i+1][j]=3;93 block[i][j]=0;94 }95 }96}97//Òƶ¯»úÆ÷ÈË98//function mvRobot(){99// for(var i=1;i<10;i++){100// for(var j=1;j<10;j++){101// if(block[i][j]==3){102// if(i<=startD[1]){103// if(j<=endD[1]){104// if(block[i][j+1]==2){105// drawBlock(i+1,j,"red");106// drawBlock(i,j,"white");107// block[i+1][j]=3;108// block[i][j]=0;109// }else {110// if(j-endD[1]>=i-startD[1]){111// drawBlock(i,j+1,"red");112// drawBlock(i,j,"white");113// block[i][j+1]=3;114// block[i][j]=0;115// }else if(j-endD[1]<i-startD[1]){116// drawBlock(i+1,j,"red");117// drawBlock(i,j,"white");118// block[i+1][j]=3;119// block[i][j]=0;120// }121// }122// }else{123// if(block[i][j+1]==2){124// drawBlock(i-1,j,"red");125// drawBlock(i,j,"white");126// block[i-1][j]=3;127// block[i][j]=0;128// }else{129// if(j-endD[1]>=i-startD[1]){130// drawBlock(i,j-1,"red");131// drawBlock(i,j,"white");132// block[i][j-1]=3;133// block[i][j]=0;134// }else if(j-endD[1]<i-startD[1]){135// drawBlock(i-1,j,"red");136// drawBlock(i,j,"white");137// block[i-1][j]=3;138// block[i][j]=0;139// }140// }141// }142// }else{143// if(j<=endD[1]){144// if(block[i][j+1]==2){145// drawBlock(i-1,j,"red");146// drawBlock(i,j,"white");147// block[i-1][j]=3;148// block[i][j]=0;149// }else{150// if(j-endD[1]>=i-startD[1]){151// drawBlock(i,j+1,"red");152// drawBlock(i,j,"white");153// block[i][j+1]=3;154// block[i][j]=0;155// }else if(j-endD[1]<i-startD[1]){156// drawBlock(i+1,j,"red");157// drawBlock(i,j,"white");158// block[i+1][j]=3;159// block[i][j]=0;160// }161// }162// }else{163// if(block[i][j+1]==2){164// drawBlock(i+1,j,"red");165// drawBlock(i,j,"white");166// block[i+1][j]=3;167// block[i][j]=0;168// }else{169// if(j-endD[1]>=i-startD[1]){170// drawBlock(i,j-1,"red");171// drawBlock(i,j,"white");172// block[i][j-1]=3;173// block[i][j]=0;174// }else if(j-endD[1]<i-startD[1]){175// drawBlock(i-1,j,"red");176// drawBlock(i,j,"white");177// block[i-1][j]=3;178// block[i][j]=0;179// }180// }181// }182// }183// }184// }185// }186//}187//Òƶ¯hero188function mvSuper(pX,pY){189 if(block[startD[1]-pX][endD[1]-pY]==0){//-1 0190 startD[1] -= pX;191 endD[1]-=pY;192 if(superBlock==-1){193 drawBlock(startD[1],endD[1],"green");194 }else if(superBlock<3){195 drawBlock(startD[1],endD[1],"#6BF65E");196 superBlock+=1;197 if(superBlock==2){198 superBlock=-1;199 }200 }201 drawBlock(startD[1]+pX,endD[1]+pY,"white");//+1 0202 block[startD[1]][endD[1]]=-1;203 block[startD[1]+pX][endD[1]+pY]=0;//+1 0204 }else if(block[startD[1]-pX][endD[1]-pY]==2){//-1 0205 alert("no");206 }else if(block[startD[1]-pX][endD[1]-pY]==1){207 startD[1] -= pX;208 endD[1]-=pY;209 drawBlock(startD[1],endD[1],"#6BF65E");210 drawBlock(startD[1]+pX,endD[1]+pY,"white");211 block[startD[1]][endD[1]]=-1;212 block[startD[1]+pX][endD[1]+pY]=0;213 superBlock=0;214 }else if(block[startD[1]-pX][endD[1]-pY]==3){215 if(superBlock==-1) {216 alert("failed");217 } else if(superBlock!=-1){218 startD[1] -= pX;219 endD[1]-=pY;220 drawBlock(startD[1],endD[1],"#6BF65E");221 drawBlock(startD[1]+pX,endD[1]+pY,"white");222 block[startD[1]][endD[1]]=-1;223 block[startD[1]+1][endD[1]]=0;224 superBlock++;225 }226 }227 var robot=0;228 var suptool=0;229 for(var i=1;i<=10;i++){230 for(var j=1;j<=10;j++){231 if(block[i][j]==3){232 robot++;233 }234 if(block[i][j]==1){235 suptool++;236 }237 }238 }239 if(robot==0){240 alert("win");241 }else if(robot!=0 || (robot!=0&&suptool==0)){242 if(superBlock==-1) alert("failed");243 else{244 return;245 }246 }247}248//²úÉúhero robot super as....249function clickXY(){250 i=1;251 var x,y;252 chess.onclick=function(e){253 x= e.offsetX;254 y= e.offsetY;255 startD[i]= Math.floor(x / 30);256 endD [i]= Math.floor(y / 30);257 if(startD[i]<1 || startD[i]>10 || endD[i]<1 || endD[i]>10) return;258 if(i==1){259 drawBlock(startD[i],endD[i],"green");260 block[startD[i]][endD[i]]=-1;261 //console.log(startD[i],endD[i]);262 i++;263 }else if(i>1){264 if(block[startD[i]][endD[i]]==0){265 var str=window.prompt("1,0,2","");266 if(str==0){267 drawBlock(startD[i],endD[i],"red");268 block[startD[i]][endD[i]]=3;269 i++;270 }else if(str==1){271 drawBlock(startD[i],endD[i],"blue");272 block[startD[i]][endD[i]]=1;273 i++;274 }else if(str==2){275 drawBlock(startD[i],endD[i],"#F6C462");276 block[startD[i]][endD[i]]=2;277 i++;278 }279 }else alert("repeat");280 }281 else return;282 }283}284//»­±í¸ñ285var drawchessbox=function(){286 for(var i=0;i<11;i++)287 {288 context.moveTo(30+i*30,30);289 context.lineTo(30+i*30,360-30);290 context.stroke();291 context.moveTo(30,30+i*30);292 context.lineTo(360-30,30+i*30);293 context.stroke();294 }295}296//»­·½¿é297function drawBlock(startD,endD,color) {298 if(startD>0&&startD<11&&endD>0&&endD<11){299 context.strokeStyle = "block";300 context.fillStyle = color;301 context.fillRect(startD*30,endD*30,30,30);302 context.strokeRect(startD*30,endD*30,30,30);303 }304}305//if(block[startD[1]-1][endD[1]]==0){306// startD[1] -= 1;307// if(superBlock==-1){308// drawBlock(startD[1],endD[1],"green");309// }else if(superBlock<3){310// drawBlock(startD[1],endD[1],"#6BF65E");311// superBlock+=1;312// if(superBlock==2){313// superBlock=-1;314// }315// }316// drawBlock(startD[1]+1,endD[1],"white");317// block[startD[1]][endD[1]]=-1;318// block[startD[1]+1][endD[1]]=0;319//}else if(block[startD[1]-1][endD[1]]==2){320// alert("no");321//}else if(block[startD[1]-1][endD[1]]==1){322// startD[1] -= 1;323// drawBlock(startD[1],endD[1],"#6BF65E");324// drawBlock(startD[1]+1,endD[1],"white");325// block[startD[1]][endD[1]]=-1;326// block[startD[1]+1][endD[1]]=0;327// superBlock=0;328//}else if(block[startD[1]-1][endD[1]]==3){329// if(superBlock==-1) {330// alert("failed");331// } else if(superBlock!=-1){332// startD[1] -= 1;333// drawBlock(startD[1],endD[1],"#6BF65E");334// drawBlock(startD[1]+1,endD[1],"white");335// block[startD[1]][endD[1]]=-1;336// block[startD[1]+1][endD[1]]=0;337// superBlock++;338// }339//}340//startD[1] += 1;341//drawBlock(startD[1],endD[1],"green");342//drawBlock(startD[1]-1,endD[1],"white");343//endD[1] += 1;344//drawBlock(startD[1],endD[1],"green");345//drawBlock(startD[1],endD[1]-1,"white");346//endD[1] -= 1;347//drawBlock(startD[1],endD[1],"green");348//drawBlock(startD[1],endD[1]+1,"white");349//if(i<=startD[1]){350// if(j<=endD[1]){351// if(block[i][j+1]!=2){352// drawBlock(i,j+1,"red");353// drawBlock(i,j-1,"white");354// block[i][j+1]=3;355// block[i][j]=0;356// }else{357// drawBlock(i+1,j,"red");358// drawBlock(i-1,j,"white");359// block[i+1][j]=3;360// block[i][j]=0;361// }362// }else{363// if(block[i][j-1]!=2){364// drawBlock(i,j-1,"red");365// drawBlock(i,j+1,"white");366// block[i][j-1]=3;367// block[i][j]=0;368// }else{369// drawBlock(i-1,j,"red");370// drawBlock(i+1,j,"white");371// block[i-1][j]=3;372// block[i][j]=0;373// }374// }375//}376//if(i>startD[1]){377// if(j<=endD[1]){378// if(block[i][j-1]!=2){379// drawBlock(i,j-1,"red");380// drawBlock(i,j+1,"white");381// block[i][j-1]=3;382// block[i][j]=0;383// }else{384// drawBlock(i-1,j,"red");385// drawBlock(i+1,j,"white");386// block[i-1][j]=3;387// block[i][j]=0;388// }389// }else{390// if(block[i][j+1]!=2){391// drawBlock(i,j+1,"red");392// drawBlock(i,j-1,"white");393// block[i][j+1]=3;394// block[i][j]=0;395// }else{396// drawBlock(i+1,j,"red");397// drawBlock(i-1,j,"white");398// block[i+1][j]=3;399// block[i][j]=0;400// }401// }...

Full Screen

Full Screen

block-prop-container.ts

Source:block-prop-container.ts Github

copy

Full Screen

1import {AfterViewInit, ChangeDetectorRef, Component, Inject, ViewChild} from "@angular/core";2import {Compbaser} from "ng-mslib";3import {YellowPepperService} from "../../services/yellowpepper.service";4import {BlockService, IBlockData, ISceneData} from "./block-service";5import {CampaignTimelineChanelPlayersModel} from "../../store/imsdb.interfaces_auto";6import {ColorPickerService} from "ngx-color-picker";7import {Tab} from "../../comps/tabs/tab";8import {BlockLabels, PLACEMENT_CHANNEL, PLACEMENT_SCENE} from "../../interfaces/Consts";9@Component({10 selector: 'block-prop-container',11 template: `12 <small class="debug">{{me}}</small>13 <tabs>14 <tab [tabtitle]="'style'">15 <block-prop-common [setBlockData]="m_blockData"></block-prop-common>16 </tab>17 <tab [tabtitle]="m_tabTitle">18 <div [ngSwitch]="m_blockTypeSelected">19 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_IMAGE">20 <block-prop-image [external]="false" [setBlockData]="m_blockData"></block-prop-image>21 </div>22 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_SVG">23 <block-prop-image [external]="false" [setBlockData]="m_blockData"></block-prop-image>24 </div>25 <div *ngSwitchCase="m_blockLabels.IMAGE">26 <block-prop-image [external]="true" [setBlockData]="m_blockData"></block-prop-image>27 </div>28 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_VIDEO">29 <block-prop-video [external]="false" [setBlockData]="m_blockData"></block-prop-video>30 </div>31 <div *ngSwitchCase="m_blockLabels.EXTERNAL_VIDEO">32 <block-prop-video [external]="true" [setBlockData]="m_blockData"></block-prop-video>33 </div>34 <div *ngSwitchCase="m_blockLabels.MRSS">35 <block-prop-mrss [setBlockData]="m_blockData"></block-prop-mrss>36 </div>37 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_COLLECTION">38 <block-prop-collection [setBlockData]="m_blockData"></block-prop-collection>39 </div>40 <div *ngSwitchCase="m_blockLabels.RSS">41 <block-prop-rss [setBlockData]="m_blockData"></block-prop-rss>42 </div>43 <div *ngSwitchCase="m_blockLabels.LABEL">44 <block-prop-label [setBlockData]="m_blockData"></block-prop-label>45 </div>46 <div *ngSwitchCase="m_blockLabels.QR">47 <block-prop-qr [setBlockData]="m_blockData"></block-prop-qr>48 </div>49 <div *ngSwitchCase="m_blockLabels.CLOCK">50 <block-prop-clock [setBlockData]="m_blockData"></block-prop-clock>51 </div>52 <div *ngSwitchCase="m_blockLabels.HTML">53 <block-prop-html [setBlockData]="m_blockData"></block-prop-html>54 </div>55 <div *ngSwitchCase="m_blockLabels.FASTERQ">56 <block-prop-fasterq [setBlockData]="m_blockData"></block-prop-fasterq>57 </div>58 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_SCENE">59 <block-prop-scene [setBlockData]="m_blockData"></block-prop-scene>60 </div>61 <div *ngSwitchCase="m_blockLabels.LOCATION">62 <block-prop-location [setBlockData]="m_blockData"></block-prop-location>63 </div>64 <div *ngSwitchCase="m_blockLabels.YOUTUBE">65 <block-prop-youtube [setBlockData]="m_blockData"></block-prop-youtube>66 </div>67 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_JSON">68 <block-prop-json-player [standAlone]="true" [setBlockData]="m_blockData"></block-prop-json-player>69 </div>70 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_JSON_ITEM">71 <block-prop-json-item [setBlockData]="m_blockData"></block-prop-json-item>72 </div>73 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_WORLD_WEATHER">74 <block-prop-weather [setBlockData]="m_blockData"></block-prop-weather>75 </div>76 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_INSTAGRAM">77 <block-prop-instagram [setBlockData]="m_blockData"></block-prop-instagram>78 </div>79 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_DIGG">80 <block-prop-digg [setBlockData]="m_blockData"></block-prop-digg>81 </div>82 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_CALENDAR">83 <block-prop-calendar [setBlockData]="m_blockData"></block-prop-calendar>84 </div>85 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_TWITTERV3">86 <block-prop-twitter [setBlockData]="m_blockData"></block-prop-twitter>87 </div>88 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_GOOGLE_SHEETS">89 <block-prop-sheets [setBlockData]="m_blockData"></block-prop-sheets>90 </div>91 <div *ngSwitchDefault>92 <h3>no block prop found, new?</h3>93 {{m_blockTypeSelected}}94 </div>95 </div>96 </tab>97 <!-- below are JSON based blocked which bind to scenes -->98 <tab #settings [tabtitle]="'settings'">99 <div [ngSwitch]="m_blockTypeSelected">100 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_WORLD_WEATHER">101 <block-prop-weather [jsonMode]="true" [setBlockData]="m_blockData"></block-prop-weather>102 </div>103 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_INSTAGRAM">104 <block-prop-instagram [jsonMode]="true" [setBlockData]="m_blockData"></block-prop-instagram>105 </div>106 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_DIGG">107 <block-prop-digg [jsonMode]="true" [setBlockData]="m_blockData"></block-prop-digg>108 </div>109 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_CALENDAR">110 <block-prop-calendar [jsonMode]="true" [setBlockData]="m_blockData"></block-prop-calendar>111 </div>112 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_TWITTERV3">113 <block-prop-twitter [jsonMode]="true" [setBlockData]="m_blockData"></block-prop-twitter>114 </div>115 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_GOOGLE_SHEETS">116 <block-prop-sheets [jsonMode]="true" [setBlockData]="m_blockData"></block-prop-sheets>117 </div>118 </div>119 </tab>120 </tabs>121 `,122})123export class BlockPropContainer extends Compbaser implements AfterViewInit {124 m_blockTypeSelected: string = 'none';125 m_blockLabels = BlockLabels;126 m_blockData: IBlockData;127 m_tabTitle: string = 'none';128 m_showSettingsTab = true;129 constructor(@Inject('BLOCK_PLACEMENT') private blockPlacement: string, private yp: YellowPepperService, private bs: BlockService, private cpService: ColorPickerService, private cd: ChangeDetectorRef) {130 super();131 // console.log(blockPlacement);132 if (this.blockPlacement == PLACEMENT_CHANNEL)133 this._listenOnChannels();134 if (this.blockPlacement == PLACEMENT_SCENE)135 this._listenOnScenes();136 }137 @ViewChild('settings')138 settings: Tab;139 ngAfterViewInit() {140 this.toggleSettingsTab();141 }142 private _listenOnChannels() {143 this.cancelOnDestroy(144 //145 this.yp.listenBlockChannelSelectedOrChanged()146 .mergeMap((i_campaignTimelineChanelPlayersModel: CampaignTimelineChanelPlayersModel) => {147 return this.bs.getBlockData(i_campaignTimelineChanelPlayersModel.getCampaignTimelineChanelPlayerId())148 })149 .subscribe((blockData: IBlockData) => {150 this.m_blockTypeSelected = blockData.blockCode;151 this.m_tabTitle = blockData.blockAcronym;152 this.m_blockData = blockData;153 // for json based scenes show the settings, unless its the actual Json Player which we don't154 if (blockData.playerMimeScene && this.m_blockTypeSelected != '4300') {155 this.m_showSettingsTab = true;156 this.toggleSettingsTab();157 } else {158 this.m_showSettingsTab = false;159 this.toggleSettingsTab();160 }161 }, (e) => console.error(e))162 )163 }164 private _listenOnScenes() {165 this.cancelOnDestroy(166 //167 this.yp.listenSceneOrBlockSelectedChanged()168 .mergeMap((i_sceneData: ISceneData) => {169 return this.bs.getBlockDataInScene(i_sceneData)170 })171 .subscribe((blockData: IBlockData) => {172 this.m_blockTypeSelected = blockData.blockCode;173 this.m_tabTitle = blockData.blockAcronym;174 this.m_blockData = blockData;175 this.m_showSettingsTab = false;176 this.toggleSettingsTab();177 this.cd.markForCheck();178 }, (e) => console.error(e))179 )180 }181 // private getTabTitle(i_blockData: IBlockData): string {182 // // this.bs.getCommonBorderXML()if (i_blockData.blockAcronym.indexOf('JSON')) > -1 ? blockData.playerMimeScene : blockData.blockAcronym183 // }184 private toggleSettingsTab() {185 if (!this.settings) return;186 this.settings.show = this.m_showSettingsTab;187 }188 ngOnInit() {189 }190 destroy() {191 }...

Full Screen

Full Screen

zerocoin_publicSpend_reorg.py

Source:zerocoin_publicSpend_reorg.py Github

copy

Full Screen

...38 block_count = self.node.getblockcount()39 pastBlockHash = self.node.getblockhash(block_count)40 self.log.info("Block count: %d - Current best: %s..." % (self.node.getblockcount(), self.node.getbestblockhash()[:5]))41 pastBlock = CBlock()42 pastBlock.deserialize(BytesIO(hex_str_to_bytes(self.node.getblock(pastBlockHash, False))))43 checkpoint = pastBlock.nAccumulatorCheckpoint44 # 5) get the raw zerocoin spend txes45 self.log.info("Getting the raw zerocoin public spends...")46 public_spend_A = self.node.createrawzerocoinpublicspend(mints[0].get("serial hash"))47 tx_A = CTransaction()48 tx_A.deserialize(BytesIO(hex_str_to_bytes(public_spend_A)))49 tx_A.rehash()50 public_spend_B = self.node.createrawzerocoinpublicspend(mints[1].get("serial hash"))51 tx_B = CTransaction()52 tx_B.deserialize(BytesIO(hex_str_to_bytes(public_spend_B)))53 tx_B.rehash()54 # Spending same coins to different recipients to get different txids55 my_addy = "yAVWM5urwaTyhiuFQHP2aP47rdZsLUG5PH"56 public_spend_A2 = self.node.createrawzerocoinpublicspend(mints[0].get("serial hash"), my_addy)57 tx_A2 = CTransaction()58 tx_A2.deserialize(BytesIO(hex_str_to_bytes(public_spend_A2)))59 tx_A2.rehash()60 public_spend_B2 = self.node.createrawzerocoinpublicspend(mints[1].get("serial hash"), my_addy)61 tx_B2 = CTransaction()62 tx_B2.deserialize(BytesIO(hex_str_to_bytes(public_spend_B2)))63 tx_B2.rehash()64 self.log.info("tx_A id: %s" % str(tx_A.hash))65 self.log.info("tx_B id: %s" % str(tx_B.hash))66 self.log.info("tx_A2 id: %s" % str(tx_A2.hash))67 self.log.info("tx_B2 id: %s" % str(tx_B2.hash))68 self.test_nodes[0].handle_connect()69 # 6) create block_A --> main chain70 self.log.info("")71 self.log.info("*** block_A ***")72 self.log.info("Creating block_A [%d] with public spend tx_A in it." % (block_count + 1))73 block_A = self.new_block(block_count, pastBlock, checkpoint, tx_A)74 self.log.info("Hash of block_A: %s..." % block_A.hash[:5])75 self.log.info("sending block_A...")76 var = self.node.submitblock(bytes_to_hex_str(block_A.serialize()))77 if var is not None:78 self.log.info("result: %s" % str(var))79 raise Exception("block_A not accepted")80 time.sleep(2)81 assert_equal(self.node.getblockcount(), block_count+1)82 assert_equal(self.node.getbestblockhash(), block_A.hash)83 self.log.info(" >> block_A connected <<")84 self.log.info("Current chain: ... --> block_0 [%d] --> block_A [%d]\n" % (block_count, block_count+1))85 # 7) create block_B --> forked chain86 self.log.info("*** block_B ***")87 self.log.info("Creating block_B [%d] with public spend tx_B in it." % (block_count + 1))88 block_B = self.new_block(block_count, pastBlock, checkpoint, tx_B)89 self.log.info("Hash of block_B: %s..." % block_B.hash[:5])90 self.log.info("sending block_B...")91 var = self.node.submitblock(bytes_to_hex_str(block_B.serialize()))92 self.log.info("result of block_B submission: %s" % str(var))93 time.sleep(2)94 assert_equal(self.node.getblockcount(), block_count+1)95 assert_equal(self.node.getbestblockhash(), block_A.hash)96 # block_B is not added. Chain remains the same97 self.log.info(" >> block_B not connected <<")98 self.log.info("Current chain: ... --> block_0 [%d] --> block_A [%d]\n" % (block_count, block_count+1))99 # 8) Create new block block_C on the forked chain (block_B)100 block_count += 1101 self.log.info("*** block_C ***")102 self.log.info("Creating block_C [%d] on top of block_B triggering the reorg" % (block_count + 1))103 block_C = self.new_block(block_count, block_B, checkpoint)104 self.log.info("Hash of block_C: %s..." % block_C.hash[:5])105 self.log.info("sending block_C...")106 var = self.node.submitblock(bytes_to_hex_str(block_C.serialize()))107 if var is not None:108 self.log.info("result: %s" % str(var))109 raise Exception("block_C not accepted")110 time.sleep(2)111 assert_equal(self.node.getblockcount(), block_count+1)112 assert_equal(self.node.getbestblockhash(), block_C.hash)113 self.log.info(" >> block_A disconnected / block_B and block_C connected <<")114 self.log.info("Current chain: ... --> block_0 [%d] --> block_B [%d] --> block_C [%d]\n" % (115 block_count - 1, block_count, block_count+1116 ))117 # 7) Now create block_D which tries to spend same coin of tx_B again on the (new) main chain118 # (this block will be rejected)119 block_count += 1120 self.log.info("*** block_D ***")121 self.log.info("Creating block_D [%d] trying to double spend the coin of tx_B" % (block_count + 1))122 block_D = self.new_block(block_count, block_C, checkpoint, tx_B2)123 self.log.info("Hash of block_D: %s..." % block_D.hash[:5])124 self.log.info("sending block_D...")125 var = self.node.submitblock(bytes_to_hex_str(block_D.serialize()))126 self.log.info("result of block_D submission: %s" % str(var))127 time.sleep(2)128 assert_equal(self.node.getblockcount(), block_count)129 assert_equal(self.node.getbestblockhash(), block_C.hash)130 # block_D is not added. Chain remains the same131 self.log.info(" >> block_D rejected <<")132 self.log.info("Current chain: ... --> block_0 [%d] --> block_B [%d] --> block_C [%d]\n" % (133 block_count - 2, block_count - 1, block_count134 ))135 # 8) Now create block_E which spends tx_A again on main chain136 # (this block will be accepted and connected since tx_A was spent on block_A now disconnected)137 self.log.info("*** block_E ***")138 self.log.info("Creating block_E [%d] trying spend tx_A on main chain" % (block_count + 1))139 block_E = self.new_block(block_count, block_C, checkpoint, tx_A)140 self.log.info("Hash of block_E: %s..." % block_E.hash[:5])141 self.log.info("sending block_E...")142 var = self.node.submitblock(bytes_to_hex_str(block_E.serialize()))143 if var is not None:144 self.log.info("result: %s" % str(var))145 raise Exception("block_E not accepted")146 time.sleep(2)147 assert_equal(self.node.getblockcount(), block_count+1)148 assert_equal(self.node.getbestblockhash(), block_E.hash)149 self.log.info(" >> block_E connected <<")150 self.log.info("Current chain: ... --> block_0 [%d] --> block_B [%d] --> block_C [%d] --> block_E [%d]\n" % (151 block_count - 2, block_count - 1, block_count, block_count+1152 ))153 # 9) Now create block_F which tries to double spend the coin in tx_A154 # # (this block will be rejected)155 block_count += 1156 self.log.info("*** block_F ***")157 self.log.info("Creating block_F [%d] trying to double spend the coin in tx_A" % (block_count + 1))158 block_F = self.new_block(block_count, block_E, checkpoint, tx_A2)159 self.log.info("Hash of block_F: %s..." % block_F.hash[:5])160 self.log.info("sending block_F...")161 var = self.node.submitblock(bytes_to_hex_str(block_F.serialize()))162 self.log.info("result of block_F submission: %s" % str(var))163 time.sleep(2)164 assert_equal(self.node.getblockcount(), block_count)165 assert_equal(self.node.getbestblockhash(), block_E.hash)166 self.log.info(" >> block_F rejected <<")167 self.log.info("Current chain: ... --> block_0 [%d] --> block_B [%d] --> block_C [%d] --> block_E [%d]\n" % (168 block_count - 3, block_count - 2, block_count - 1, block_count169 ))170 self.log.info("All good.")171 def new_block(self, block_count, prev_block, checkpoint, zcspend = None):172 if prev_block.hash is None:173 prev_block.rehash()174 staking_utxo_list = [self.unspent.pop()]175 pastBlockHash = prev_block.hash176 stakingPrevOuts = self.get_prevouts(staking_utxo_list, block_count)177 block = self.create_spam_block(pastBlockHash, stakingPrevOuts, block_count + 1)178 if zcspend is not None:179 block.vtx.append(zcspend)180 block.hashMerkleRoot = block.calc_merkle_root()181 block.nAccumulatorCheckpoint = checkpoint182 block.rehash()183 block.sign_block(self.block_sig_key)184 return block185if __name__ == '__main__':...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pytest-django automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful