Esempio n. 1
1
 def OkButtonClicked(self):
     """listwidgitem = QListWidgetItem()
     listwidgitem.setSizeHint(QtCore.QSize(self.listWidget.width(), 100))
     listwidgitem.setText("ress")
     self.listWidget.addItem(listwidgitem)
     self.listWidget.setItemWidget(self.listWidget.item(1), QTextEdit("1)<html><head/><body><p>x<span style=\" vertical-align:sub;\">0</span></p></body></html>"))
     """
     a = np.empty((self.Dim, self.Dim))
     b = np.empty((self.Dim))
     for i in range(self.Dim):
         for j in range(self.Dim):
             try:
                 a[i, j] = np.float64(self.InputTableWidget.item(i, j).text())
                 self.InputTableWidget.item(i,j).setBackground(QtGui.QColor(255,255,255))
             except:
                 self.InputTableWidget.setItem(i, j, QTableWidgetItem())
                 self.InputTableWidget.item(i,j).setBackground(QtGui.QColor(255,128,128))
                 return -1;
     if self.methodBox.currentIndex() != 3:
         for i in range(self.Dim):
             try:
                 b[i] = np.float64(self.InputTableWidget.item(i, self.Dim).text())
                 self.InputTableWidget.item(i,self.Dim).setBackground(QtGui.QColor(255,255,255))
             except:
                 self.InputTableWidget.setItem(i, self.Dim, QTableWidgetItem())
                 self.InputTableWidget.item(i, self.Dim).setBackground(QtGui.QColor(255,128,128))
                 return -1;
     if self.methodBox.currentIndex()==0:
         tabels = []
         tabels.append(genTable(a, b, np.sum(a, 1)+b, np.sum(a, 1)+b))
         gauss_d = gauss_det(a)
         a, b, Sum, S, tabels1 = gauss(a, b)
         tabels += tabels1
         html = genHtml(tables=tabels)
         self.textBrowser.setText(html.replace('{%det%}','Det(A) = {0}'.format(gauss_d)))
     elif self.methodBox.currentIndex() == 1:
         for i in range(self.Dim):
             for j in range(self.Dim):
                 if a[i, j] != a[j, i]:
                     QtGui.QMessageBox.warning(None, 'Warning', 'Matrix is asymetric')
                     return
         x, L, D = sqrt_method(a, b)
         Dtmp = np.zeros((len(D), len(D)))
         for i in range(len(D)):
             Dtmp[i, i] = D[i]
         tabels = []
         tabels.append(genMatrix(L))
         tabels.append(genMatrix(Dtmp))
         tabels.append(genVector(x))
         self.textBrowser.setText(genHtml(tabels,
                                          labels=['L', 'D', 'X']).replace('{%det%}','Det(A) = {0}'.format(np.prod(D))))
     elif self.methodBox.currentIndex() == 2:
         C = np.zeros(self.Dim)
         B = np.zeros(self.Dim)
         A = np.zeros(self.Dim)
         for i in range(self.Dim):
             C[i] = a[i, i]
             if i!= self.Dim-1:
                 B[i] = a[i, i+1]
                 A[i+1] = a[i+1, i]
         x = TDMA(A, B, C, b)
         tabels = []
         tabels.append(genVector(x))
         self.textBrowser.setText(genHtml(tabels,
                                          ['X']).replace('{%det%}','Det(A) = {0}'.format(np.linalg.det(a))))
     elif self.methodBox.currentIndex() == 3:
         inverse = inverse_matrix(a)
         self.textBrowser.setText(genHtml(np.array([genMatrix(inverse)]), ['Inverse Matrix']).replace('{%det%}', ''))
     elif self.methodBox.currentIndex() == 4:
         x0 = np.zeros(self.Dim)
         for i in range(self.Dim):
             try:
                 x0[i] = np.float64(self.InputTableWidget.item(i, self.Dim+1).text())
             except:
                 continue
         try:
             N = np.int32(self.InputTableWidget.item(0, self.Dim+2).text())
         except:
             pass
         x = jacobi(a, b, N, x0)
         self.textBrowser.setText(genHtml(np.array([genVector(x)]), ['X']).replace('{%det%}', ''))
     elif self.methodBox.currentIndex() == 5:
         try:
             eps = np.float64(self.InputTableWidget.item(0, self.Dim+1).text())
         except:
             eps = 10**(-10)
         x, N = seidel(a, b, eps)
         self.textBrowser.setText(genHtml(np.array([genVector(x)]), ['X']).replace('{%det%}', str(N)))
def solovaystrassen(n,k=2,bases=[],seed=time.time()):
	if(n&1==0 || n<2): return (n==2)
	random.seed(time.time())
	if(bases==[]): # if bases not given, use random 'a'
		for i in range(k):
			a = 0
			while(True): # generate 'a' that hasn't been used already
				a = random.randint(1,n-1)
				#print "New 'a'"
				if not (a in bases):
					break
			#print a
			x=jacobi(a,n)%n
			if x==0 or pow(a,(n-1)/2,n) != x:
				return False
		return True
	else: # if bases given, use bases 'a' from the array
		basesTested = 0 # makes sure that all bases given are NOT larger than n-1
		for a in bases:
			if a > n-1:
				continue
			x=jacobi(a,n)
			if x==0 or pow(a,(n-1)/2,n) != x:
				return False
			basesTested = basesTested+1
		if basesTested == 0: return "Bases too large for number to be tested."
		return True
Esempio n. 3
0
def test_method(method):
    d = {}
    fp, fpe = jacobi(lambda x: x, 0, method=method, diagnostic=d)
    assert_equal(d["method"], [method])
    assert_allclose(fp, 1)
    assert_allclose(fpe, 0, atol=1e-10)

    fp, fpe = jacobi(lambda x: x if x >= 0 else np.nan,
                     0,
                     method=method,
                     diagnostic=d)
    assert_equal(d["method"], [method])
    if method == 1:
        assert_allclose(fp, 1)
        assert_allclose(fpe, 0, atol=1e-10)
    else:
        assert_equal(fp, np.nan)
        assert_equal(fpe, np.inf)

    fp, fpe = jacobi(lambda x: x if x <= 0 else np.nan,
                     0,
                     method=method,
                     diagnostic=d)
    assert_equal(d["method"], [method])
    if method == -1:
        assert_allclose(fp, 1)
        assert_allclose(fpe, 0, atol=1e-10)
    else:
        assert_equal(fp, np.nan)
        assert_equal(fpe, np.inf)
def cfd(iterations, edge, inlet_x, inlet_width, outlet_y, outlet_height, dat_file, quiet=True):
    """
    Run simulation and output stream function data into a file.

    Keyword arguments:
    iterations -- number of iterations to update stream function over.
    edge -- width and height of box.
    inlet_x -- point on top edge of box where inlet begins.
    inlet_width -- inlet width.
    inlet_y -- point on right edge where outlet begins.
    inlet_height -- outlet height.
    dat_file -- stream function data output file name.
    quiet -- if True then no status information is printed.
    """

    width = edge
    height = edge

    assert inlet_x <= width
    assert inlet_x + inlet_width < width
    assert outlet_y <= height
    assert outlet_y + outlet_height < height
    
    if (not quiet):
	sys.stdout.write("\n2D CFD Simulation\n")
	sys.stdout.write("=================\n")
	sys.stdout.write("   Iterations = {0}\n".format(iterations))
	sys.stdout.write("         Edge = {0}\n".format(edge))
	sys.stdout.write("      Inlet X = {0}\n".format(inlet_x))
	sys.stdout.write("  Inlet width = {0}\n".format(inlet_width))
	sys.stdout.write("     Outlet Y = {0}\n".format(outlet_y))
	sys.stdout.write("Outlet height = {0}\n".format(outlet_height))
	sys.stdout.write("Grid size     = {0} x {1}\n".format(width, height))
    time_starts = time.time()

    # Initialise stream function, psi, to 0.
    psi = [[0 for col in range(width+2)] for row in range(height+2)]

    # Set the boundary conditions.
    set_inlet_boundary(psi, width, inlet_x, inlet_width)
    set_outlet_boundary(psi, width, outlet_y, outlet_height)

    time_ends = time.time()
    if (not quiet):
	sys.stdout.write("\nInitialisation took {0:.5f}s\n".format(time_ends-time_starts))
    
    # Call the Jacobi iterative loop (and calculate timings).
    if (not quiet):
	sys.stdout.write("\nStarting main Jacobi loop...\n")
    time_starts = time.time()

    jacobi(iterations, psi)

    time_ends = time.time()
    if (not quiet):
	sys.stdout.write("...finished\n")
	sys.stdout.write("\nCalculation took {0:.5f}s\n\n".format(time_ends-time_starts))
    
    write_data(width, height, psi, dat_file)
Esempio n. 5
0
def sqrt_mod(a,p):
    """
    Calcula la raiz cuadrada modular de a módulo p
    
    Args:
        a(int): Entero
        p(int): Entero primo
        
    Returns:
        r(int): Raiz de a modulo p        
        
    Examples:
        sqrt_mod(319,353)
        242
    """
    
    if jacobi(a,p) == -1:
        return -1
        
        
    n=1
    
    while jacobi(n,p) != -1:
        n+=1
        
    
    u=0
    s=p-1
    while s%2==0:
        u=u+1
        s=s//2
    print(u,s);
        
    if u == 1:
        r=exp_mod(a,(p+1)/4,p)
    elif u >= 2:
        r=exp_mod(a,(s+1)/2,p)
        b=exp_mod(n,s,p)
        j=0
        
        while j<= u-2:
            base = (inverso_mod(a,p)*r*r)%p
            exp = exp_mod(2,u-2-j,p)  
            if exp_mod(base,exp,p) == (-1%p):
                r=(r*b)%p
            b=(b*b)%p
            j+=1
            
      
    return r
Esempio n. 6
0
def jacobi_test ( ):

#*****************************************************************************80
#
## JACOBI_TEST tests JACOBI.
#
#  Licensing:
#
#    This code is distributed under the GNU LGPL license.
#
#  Modified:
#
#    16 February 2015
#
#  Author:
#
#    John Burkardt
#
  from r8mat_print import r8mat_print

  print ''
  print 'JACOBI_TEST'
  print '  JACOBI computes the JACOBI matrix.'

  m = 4
  n = m

  a = jacobi ( m, n )
  r8mat_print ( m, n, a, '  JACOBI matrix:' )

  print ''
  print 'JACOBI_TEST'
  print '  Normal end of execution.'

  return
Esempio n. 7
0
def solovay_stassen(n: int, iterations: int) -> bool:
    if (n == 1):
        return False

    if (n == 2) or (n == 3) or (n == 5):
        return True

    if (n % 2 == 0):
        return False

    for i in range(iterations):
        # [0, n-5) -> [0, n-4] -> [2, n-2]
        b = secrets.randbelow(n - 5)
        b += 2

        r = modular_exp.modular_exp(b, (n - 1) // 2, n)

        # 如果 r 是 n - 1,把 r 设为 -1,以与 Jacobi 符号匹配
        if (r == n - 1):
            r = -1

        if (r != 1) and (r != -1):
            return False

        s = jacobi.jacobi(b, n)

        if (r != s):
            return False

    return True
Esempio n. 8
0
def main():
    """Using jacobi's algorithm to estimate the eigenvalues
    of the Hamiltonian for a one-electron system with a HO-potential."""
    N = int(eval(input("Number of grid points: ")))
    rho_max = 12.5  # 6.25  # setting max value for position.
    rho = np.linspace(0, rho_max, N)  # step-variable.

    h = (rho[-1] - rho[0]) / N  # step size.
    e = -1 / h**2  # off-diagonal elements.
    d = 2 / h**2 + rho[1:-1]**2  # diagonal elements.
    # creating matrix:
    A = np.diag(d) + sp.diags([e, e], [-1, 1], [N - 2, N - 2]).toarray()

    mask = np.ones(A.shape, dtype=bool)  # creating mask to conceal diagonal.
    np.fill_diagonal(mask, 0)

    a = np.linalg.norm(A[mask])  # norm of non-diagonal elements.

    A = jac.jacobi(A, mask, a, N - 2)  # diagonalizing matrix.
    eigvals = np.sort(np.diag(A))[:4]
    print(eigvals)  # printing first 4 eigenvalues.
    # print(np.sort(np.linalg.eig(A)[0])[:4])
    anal_eigvals = np.array([3, 7, 11, 15])
    error = abs((eigvals - anal_eigvals) / anal_eigvals)  # relative error.
    print(error)
Esempio n. 9
0
def main():
    inicializar()
    M = gauss.gauss(n + 1, Matriz, d)
    A = parametros.parametroA(x, M, h, n)
    B = parametros.parametroB(x, M, h, n)

    print("Sistema resolvido pelo método de Gauss: \n")

    for i in range(n + 1):
        print("M[" + str(i) + "]: " + str(M[i]) + "\n")
    for i in range(n):
        print("A[" + str(i) + "]: " + str(A[i]) + "\n")
    for i in range(n):
        print("B[" + str(i) + "]: " + str(B[i]) + "\n")
    print("\n")

    inicializar()
    M = jacobi.jacobi(n, Matriz, d, 0.00000000000001, 40)
    A = parametros.parametroA(x, M, h, n)
    B = parametros.parametroB(x, M, h, n)

    print("Sistema resolvido pelo método de Jacobi: \n")

    for i in range(n + 1):
        print("M[" + str(i) + "]: " + str(M[i]) + "\n")
    for i in range(n):
        print("A[" + str(i) + "]: " + str(A[i]) + "\n")
    for i in range(n):
        print("B[" + str(i) + "]: " + str(B[i]) + "\n")
    print("\n")
def PKG(email, p, q):
    # Calculate modulus
    n = p * q

    # Hash the identity
    a = sha1(email.encode('utf-8')).digest()
    a_int = int.from_bytes(a, 'big')

    # Keep hashing id until the jacobi symbol is not equal 1
    while jacobi(a_int, n) != 1:
        a = sha1(a).digest()
        a_int = int.from_bytes(a, 'big')

    # Calculate r based on the identity hash, p, q and n
    r = pow(a_int, (n + 5 - (p + q)) // 8, n)
    r2 = (r * r) % n

    # Check that r satisfies the requirements
    if r2 != (a_int % n) and r2 != (-a_int % n):
        raise Exception("Error deriving r!")

    # Return the private key and the hashed identity, fill with 0 if r is not 64 long
    r = hex(r)[2:].zfill(64)

    return (r, r2, a, n)
Esempio n. 11
0
def jacobi_test():

    #*****************************************************************************80
    #
    ## JACOBI_TEST tests JACOBI.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    16 February 2015
    #
    #  Author:
    #
    #    John Burkardt
    #
    from r8mat_print import r8mat_print

    print ''
    print 'JACOBI_TEST'
    print '  JACOBI computes the JACOBI matrix.'

    m = 4
    n = m

    a = jacobi(m, n)
    r8mat_print(m, n, a, '  JACOBI matrix:')

    print ''
    print 'JACOBI_TEST'
    print '  Normal end of execution.'

    return
Esempio n. 12
0
def check(N, a, o):
    alfa = a
    A = np.zeros((N, N), float)
    AA = np.zeros((N, N), float)
    b = np.zeros(N)
    bb = np.zeros(N, float)
    x0 = np.zeros(N)
    A[0, 0] = 2
    A[0, 1] = -1 + alfa
    A[N - 1, N - 1] = 2
    A[N - 1, N - 2] = -1 + alfa
    b[0] = 1 - alfa
    b[N - 1] = 1 + alfa
    x0[0] = 0.7
    x0[N - 1] = 0.8
    for i in range(1, N - 1, 1):
        A[i, i] = 2
        A[i, i + 1] = -1 + alfa
        A[i, i - 1] = -1 + alfa
        b[i] = 0
        x0[i] = 0.1 * i
    xj, kj, tj = jacobi.jacobi(A, b, x0, 0.00001, 1000)
    xjv, kjv, tjv = jacobi.jacobi_vec(A, b, x0, 0.00001, 1000)
    xs, ks, tjs = seidel.seidel(A, b, x0, 0.00001, 1000)
    xsv, ksv, tsv = seidel.seidel_vec(A, b, x0, 0.00001, 1000)
    xsor, ksor, tsor = sor.sor(A, b, x0, o, 0.00001, 1000)
    xsorv, ksorv, tsorv = sor.sor_vec(A, b, x0, o, 0.00001, 1000)
    xcg, kcg, tcg = cg.cg(A, b, 0.00001, 1000)
    return kj, kjv, ks, ksv, ksor, ksorv, kcg
Esempio n. 13
0
def newton(F,x0,eps=1e-5,alpha=1.05e-4):
    it=int(1e2)
    x=np.copy(x0)
    Fx=F(x)

    breakit=int(argv[2]) if len(argv) > 2  else 5
    residuum2=0
    residuum=np.linalg.norm(Fx,np.inf)
    diff=abs(residuum-residuum2)
    while residuum > eps and it > 0 and diff > eps and breakit > 0:
        dFx = jacobi(F, x)
        
        # Tikhonov regularisation
        A = dFx
        R = np.dot(np.linalg.inv(np.dot(A.T, A) + alpha * np.eye(A.shape[1])), A.T)
        xalpha = np.dot(R, Fx)
        x -= xalpha
        Fx = F(x)
        
        residuum2=np.linalg.norm(Fx)
        diff=abs(residuum-residuum2)
	if residuum2 > residuum:
            x+=xalpha
            Fx=F(x)
            alpha/=2
            alpha=min(1,abs(alpha))
            breakit-=1
	else:
            residuum=residuum2
            breakit=int(argv[2]) if len(argv) > 2  else 5
        it-=1

    return x, residuum
Esempio n. 14
0
def test_method_auto():
    d = {}
    fp, fpe = jacobi(lambda x: x, 0, diagnostic=d)
    assert_equal(d["method"], [0])
    assert_allclose(fp, 1)
    assert_allclose(fpe, 0, atol=1e-10)

    fp, fpe = jacobi(lambda x: x if x >= 0 else np.nan, 0, diagnostic=d)
    assert_equal(d["method"], [1])
    assert_allclose(fp, 1)
    assert_allclose(fpe, 0, atol=1e-10)

    fp, fpe = jacobi(lambda x: x if x <= 0 else np.nan, 0, diagnostic=d)
    assert_equal(d["method"], [-1])
    assert_allclose(fp, 1)
    assert_allclose(fpe, 0, atol=1e-10)
Esempio n. 15
0
def gen_QNR(p, d):
    '''
    generating quardratic residue
    p -- prime
    '''
    # generate random number g
    g = random.randrange(2, p)
    # 1. g has to be quadratic nonresidue
    # 2. repeat if p = 1 (mod 3) and g^((p-1)/3) = 1 (mod p)
    '''
    while jacobi(g, p) != -1 \
            or (p % 3 == 1 and pow(g, (p-1)/3, p) == 1):
        g = random.randrange(2, p)
    return g
    '''

    #while True:
     #   g = random.randrange(2, p)
    for g in bigrange.range(2, p):
        if jacobi(g, p) != -1:
            continue
        if p%3 != 1:
            return g
        cube = pow(g, (p-1)/3, p)
        if cube != 1:
            if d==-3 and pow(cube, 3, p) != 1:
                continue
            return g
Esempio n. 16
0
def jacob():
    data = request.json
    a = data["a"]
    b = data["b"]
    x = data["x"]
    tol = data["tol"]
    iters = data["iters"]
    return dict(jacobi(a, b, x, 2, tol, iters))
Esempio n. 17
0
def test_jacobi():
    A, b = generate_problem(0.5, 3)
    max_it = 1
    x, it = jacobi(A, b, max_it=max_it)
    expected = np.array([0.25, 1.25, 0.75])
    success = (x == expected).any()
    msg = "x = %s, expected = %s, b = %s, it = %s" % (x, expected, b, it)

    assert success, msg
Esempio n. 18
0
def test_convergence():
    A, b = generate_problem(0.5, 100)
    exact = np.linalg.solve(A, b)
    tol = 1e-15
    x, it = jacobi(A, b, tol=tol)
    error = np.linalg.norm(exact - x)
    success = (error - tol*np.linalg.norm(A)) < tol
    msg = "error = %s, tol*norm(A) = %s, " % (error, tol*np.linalg.norm(A))

    assert success, msg
Esempio n. 19
0
def find_max_from_env(inp_matrix):

    eival, eivect = j.jacobi(inp_matrix)

    maxim = inp_matrix[0][0]

    for i in range(1, len(eival)):
        if eival[i] > maxim:
            maxim = eival[i]

    return maxim
Esempio n. 20
0
def find_min_from_env(inp_matrix):

    eival, eivect = j.jacobi(inp_matrix)

    minimal = inp_matrix[0][0]

    for i in range(1, len(eival)):
        if eival[i] < minimal:
            minimal = eival[i]

    return minimal
Esempio n. 21
0
def errcon(n, ievt, se, prax):
    #n - number of phases used to calculate error ellipse (??)
    #ievt - boolean whether depth was fixed or free (do I know this?)
    #se - std error from origin quality
    #prax - Matrix with values:
    #[minorazimuth minorplunge minorlength;
    # interazimuth interplunge interlength;
    # majorazimuth majorplunge majorlength]
    #output - 2x2

    #     /* initialize some values */
    nFree = 8
    tol = 1.0e-15
    tol2 = 2.0e-15
    m = 3
    m1 = 2
    m2 = 4

    a = np.zeros((2, 2))
    s2 = (nFree + (n - m2) * se * se) / (nFree + n - m2)
    f10 = Fisher10(m, nFree + n - m2)
    fac = 1.0 / (m * s2 * f10)

    x = np.zeros((2, 1))
    for k in range(0, m):
        ce = np.cos(DEG2RAD * prax[k][1])
        x[0] = -ce * np.cos(DEG2RAD * prax[k][0])
        x[1] = ce * np.sin(DEG2RAD * prax[k][0])
        ce = fac * prax[k][2] * prax[k][2]
        for j in range(0, m1):
            for i in range(0, m1):
                a[j][i] = a[j][i] + ce * x[i] * x[j]

    ellipse2d = np.zeros((3, 3))
    #we're running into a problem with jacobi - namely, the diagonal values aren't exactly
    #equal (differ at 15th decimal).  We'll round them both to nearest billionth.
    a[0][1] = text.roundToNearest(a[0][1], 1e-9)
    a[1][0] = text.roundToNearest(a[0][1], 1e-9)
    eigenvalue, eigenvector, sweeps = jacobi.jacobi(a)
    idx = eigenvalue.argsort()[::-1]
    eigenvalue = eigenvalue[idx]
    eigenvector = eigenvector[:, idx]

    for i in range(0, m1):
        ce = 1.0
        if np.fabs(eigenvector[0][i]) + np.fabs(eigenvector[1][i]) > tol2:
            ellipse2d[i][0] = RAD2DEG * np.arctan2(ce * eigenvector[1][i],
                                                   -ce * eigenvector[0][i])
        if (ellipse2d[i][0] < 0.0):
            ellipse2d[i][0] += 360.0
        ellipse2d[i][2] = np.sqrt(fac * max(eigenvalue[i], 0.0))

    return ellipse2d
Esempio n. 22
0
def exercicio3():
    print("Exercicio 3")
    tol = 10**-8
    inicializar()
    k = util.estimarIteracao(n, Matriz, d, tol)
    inicializar()
    y_gauss = gauss.gauss(n, Matriz, d)
    inicializar()
    y_jacobi = jacobi.jacobi(n, Matriz, d, tol, k)

    print("Distância entre y(N) e y* com N=" + str(k) + ": " +
          str(norma.norma(y_gauss, y_jacobi, n)) + "\n")
Esempio n. 23
0
def errcon(n,ievt,se,prax):
    #n - number of phases used to calculate error ellipse (??)
    #ievt - boolean whether depth was fixed or free (do I know this?)
    #se - std error from origin quality
    #prax - Matrix with values:
    #[minorazimuth minorplunge minorlength;
    # interazimuth interplunge interlength;
    # majorazimuth majorplunge majorlength]
    #output - 2x2

    #     /* initialize some values */
    nFree = 8
    tol   = 1.0e-15
    tol2  = 2.0e-15
    m     = 3
    m1    = 2
    m2    = 4

    a = np.zeros((2,2))
    s2  = (nFree + (n-m2)*se*se)/(nFree + n - m2)
    f10 = Fisher10(m, nFree + n - m2)
    fac = 1.0/(m * s2 * f10)

    x = np.zeros((2,1))
    for k in range(0,m):
        ce = np.cos(DEG2RAD * prax[k][1])
        x[0] = -ce  * np.cos(DEG2RAD * prax[k][0])
        x[1] =  ce  * np.sin(DEG2RAD * prax[k][0])
        ce   =  fac * prax[k][2] * prax[k][2]  
        for j in range(0,m1):
            for i in range(0,m1):
                a[j][i] = a[j][i] + ce * x[i] * x[j]
                
    ellipse2d = np.zeros((3,3))
    #we're running into a problem with jacobi - namely, the diagonal values aren't exactly
    #equal (differ at 15th decimal).  We'll round them both to nearest billionth.
    a[0][1] = text.roundToNearest(a[0][1],1e-9)
    a[1][0] = text.roundToNearest(a[0][1],1e-9)
    eigenvalue,eigenvector,sweeps = jacobi.jacobi(a)
    idx = eigenvalue.argsort()[::-1]
    eigenvalue = eigenvalue[idx]
    eigenvector = eigenvector[:,idx]

    for i in range(0,m1):
        ce = 1.0
        if np.fabs(eigenvector[0][i]) + np.fabs(eigenvector[1][i]) > tol2:
            ellipse2d[i][0] = RAD2DEG * np.arctan2(ce * eigenvector[1][i], -ce * eigenvector[0][i])
        if (ellipse2d[i][0] < 0.0):
            ellipse2d[i][0] += 360.0
        ellipse2d[i][2] = np.sqrt(fac * max(eigenvalue[i], 0.0))

    return ellipse2d
    def random_point(self):
        """

        Returns:
            A random point on the curve.
        """
        x = random.randrange(self.p)
        y_square = x**3 + self.a * x + self.b
        while jacobi(y_square, self.p) == -1:
            x = random.randrange(self.p)
            y_square = x**3 + self.a * x + self.b
        y = modsqrt(y_square, self.p)
        return x,
Esempio n. 25
0
    def random_point(self):
        """

        Returns:
            A random point on the curve.
        """
        x = random.randrange(self.p)
        y_square = x**3 + self.a * x + self.b
        while jacobi(y_square, self.p) == -1:
            x = random.randrange(self.p)
            y_square = x**3 + self.a * x + self.b
        y = modsqrt(y_square, self.p)
        return x,
Esempio n. 26
0
def choose_discriminant(n, start=0):
    '''
    First step of Algorithm
    Args:
        n:
        start:

    Returns:
        d: The discriminant
        ms: The possible orders

    '''
    d = gen_discriminant(start)
    uv = cornacchia_smith(n, d)
    jac = jacobi(d, n)
    if jac == 0:
        raise ValueError("n is not prime.")
    while jac != 1 or uv is None:
        if n % d == 0:
            raise ValueError("n is not prime.")
        d = gen_discriminant(d)
        if d < -10**6:
            raise ValueError("Discriminant cannot be found under bound 10^7.")
        uv = cornacchia_smith(n, d)
        jac = jacobi(d, n)
        if jac == 0:
            raise ValueError("n is not prime.")
    u, v = uv

    default = [n+1+u, n+1-u]
    if d == -4:
        ms = default + [n+1+2*v, n+1-2*v]
    elif d == -3:
        ms = default + [n+1+(u+3*v)/2, n+1-(u+3*v)/2, n+1+(u-3*v)/2, n+1-(u-3*v)/2]
    else:
        ms = default

    return d, ms
Esempio n. 27
0
def cb_angles(data):
    global thetas
    global torque_arr
    global last_time
    # thetas = data.data
    thetas[0] = (data.data[0] - ZERO_OFFSET) * POS2RAD
    thetas[1] = (data.data[1] - ZERO_OFFSET) * POS2RAD
    thetas[2] = (data.data[2] - ZERO_OFFSET) * POS2RAD

    j_mat = jacobi(thetas)
    force = force_calc(j_mat, torque_arr, thetas)
    force_msg.data = force
    rospy.loginfo(force_msg)
    pub_torque.publish(force_msg)
Esempio n. 28
0
def jacobiVsGE():
    for i in [10, 25, 70, 100, 500]:
        mat = symmPosDefMat(i)
        vec = [[1] for j in range(i)]
        time0 = time.time()
        x, count = jacobi(mat, vec, vec, .0001, 10000, True)
        print("A matrix of size " + str(i) + " by " + str(i) +
              " takes Jacobi's method " + str(time.time() - time0) +
              " seconds to converge after " + str(count) + " iterations.")
        time1 = time.time()
        x = matGE(mat, vec)
        print("A matrix of size " + str(i) + " by " + str(i) +
              " takes the Gaussian Elimination method " +
              str(time.time() - time1) + " seconds to solve.")
Esempio n. 29
0
def jacobiVsCG():
    for i in [10, 25, 70, 100, 500]:
        mat = symmPosDefMat(i)
        vec = [[1] for j in range(i)]
        time0 = time.time()
        x, count = jacobi(mat, vec, vec, .0001, 10000, True)
        print("A matrix of size " + str(i) + " by " + str(i) +
              " takes Jacobi's method " + str(time.time() - time0) +
              " seconds to converge after " + str(count) + " iterations.")
        time1 = time.time()
        x, count, error = conGradient(mat, vec, vec, .0001, 10000, True)
        print("A matrix of size " + str(i) + " by " + str(i) +
              " takes the Conjugate Gradient method " +
              str(time.time() - time1) + " seconds to converge after " +
              str(count) + " iterations.")
    return
Esempio n. 30
0
def generate_curve(p, d):
    '''
    Essentially Algorithm 7.5.9
    Args:
        p:

    Returns:
        parameters a, b for the curve
    '''
    # calculate quadratic nonresidue
    g = gen_QNR(p, d)
    # find discriminant
    new_d = gen_discriminant(0)
    uv = cornacchia_smith(p, new_d)
    while jacobi(new_d, p) != 1 or uv is None:
        new_d = gen_discriminant(new_d)
        uv = cornacchia_smith(p, new_d)
    u, v = uv   # storing the result of cornacchia. u^2 + v^2 * |D| = 4*p

    # check for -d = 3 or 4
    # Choose one possible output
    # Look at param_gen for comparison.
    answer = []

    if new_d == -3:
        x = -1
        for i in range(0, 6):
            answer.append((0, x))
            x = (x * g) % p
        return answer

    if new_d == -4:
        x = -1
        for i in range(0, 4):
            answer.append((x, 0))
            x = (x * g) % p
        return answer

    # otherwise compute the hilbert polynomial
    _, t, _ = hilbert(new_d)
    s = [i % p for i in t]
    j = equation.root_Fp(s, p) # Find a root for s in Fp. Algorithm 2.3.10
    c = j * inverse(j - 1728, p) % p
    r = -3 * c % p
    s = 2 * c % p

    return [(r, s), (r * g * g % p, s * (g**3) % p)]
Esempio n. 31
0
def cb_angles(data):
    global thetas
    global tourqe_arr
    global last_time
    # thetas = data.data
    thetas[0] = (data.data[0] -
                 ZERO_OFFSET) * POS2RAD  # <TODO> modulo or subtraction ?
    thetas[1] = (data.data[1] - ZERO_OFFSET) * POS2RAD
    thetas[2] = (data.data[2] - ZERO_OFFSET) * POS2RAD

    j_mat = jacobi(thetas)
    force = force_calc(j_mat, tourqe_arr, thetas)
    force_msg.data = force
    rospy.loginfo(force_msg)
    pub_tourqe.publish(force_msg)
    create(force, 'force.csv')  # write to file
    create(tourqe_arr, 'tourqe.csv')  # write to file
Esempio n. 32
0
def deflect(n):

    x, b = load(n)

    A = cstruc(n)

    print(A)

    ya, itr = jacobi(A, b, np.zeros(n))

    #yxv = np.vectorize(yx)

    #ye = yxv(x)

    #con = LA.cond(A, np.inf)

    return x, ya
Esempio n. 33
0
def curve_parameters(d, p):
    '''
    Modified Algorithm 7.5.9 for the use of ecpp
    Args:
        d: discriminant
        p: number for prime proving

    Returns:
        a list of (a, b) parameters for
    '''
    g = gen_QNR(p, d)
    #g = nzmath.ecpp.quasi_primitive(p, d==-3)

    u, v = cornacchia_smith(p, d)
    # go without the check for result of cornacchia because it's done by previous methods.
    if jacobi(d, p) != 1:
        raise ValueError('jacobi(d, p) not equal to 1.')

        # check for -d = 3 or 4
    # Choose one possible output
    # Look at param_gen for comparison.
    answer = []

    if d == -3:
        x = -1 % p
        for i in range(0, 6):
            answer.append((0, x))
            x = (x * g) % p
        return answer

    if d == -4:
        x = -1 % p
        for i in range(0, 4):
            answer.append((x, 0))
            x = (x * g) % p
        return answer

    # otherwise compute the hilbert polynomial
    _, t, _ = hilbert(d)
    s = [int(i % p) for i in t]
    j = equation.root_Fp(s, p) # Find a root for s in Fp. Algorithm 2.3.10
    c = j * inverse(j - 1728, p) % p
    r = -3 * c % p
    s = 2 * c % p

    return [(r, s), (r * g * g % p, s * (g**3) % p)]
Esempio n. 34
0
def test_jacobi_orthogonality(n):
    """
    Tests if the orthogonality is preserved for the eigenvectors calculated by 
    the Jacobi method
    
    Input: 
        n - size of matrix
    """
    A = make_matrix(n, 1)
    eigval_np, teigvec_np = np.linalg.eig(A)
    eigval_J, eigvec_J, a, r, t = jacobi(A)
    err = 1E-5
    assert 1 - np.dot(eigvec_J[0], eigvec_J[0]) <= err
    assert np.dot(eigvec_J[0], eigvec_J[1]) <= err
    assert 1 - np.dot(eigvec_J[3], eigvec_J[3]) <= err
    assert np.dot(eigvec_J[3], eigvec_J[1]) <= err

    print('test_jacobi_eigvec passed')
Esempio n. 35
0
def test_largest_elem(n):
    """
    Tests if the largest element on the non-diagonal that was picked on the 
    last iteration in the Jacobi method was indeed the largest element on the
    rotated matrix
    
    Input: 
        n - size of matrix
    """
    A = make_matrix(n, 1)
    eigval_J, eigvec_J, AMax, r, t = jacobi(A)
    maxelem = 0.0
    for i in range(n):
        for j in range(i + 1, n):
            if abs(A[i, j]) >= maxelem:
                maxelem = abs(A[i, j])
    assert maxelem == AMax
    print('test_largest_elem passed')
Esempio n. 36
0
def cornacchia_smith(p, d):
    '''
    modified Cornacchia's Algorithm to solve a^2 + b^2 |D| = 4p for a and b
    Args:
        p:
        d:

    Returns:
        a, b such that a^2 + b^2 |D| = 4p

    '''
    # check input
    if not -4 * p < d < 0:
        raise ValueError(" -4p < D < 0 not true.")
    elif not (d % 4 in {0, 1}):
        raise ValueError(" D = 0, 1 (mod 4) not true.")

    # case where p=2
    if p == 2:
        r = sqrt(d + 8)
        if r != -1:
            return r, 1
        else:
            return None
    # test for solvability
    if jacobi(d % p, p) < 1:
        return None

    x = modsqrt(d, p)
    if (x % 2) != (d % 2):
        x = p - x
    # euclid chain
    a, b = (2 * p, x)
    c = floorsqrt(4 * p)
    while b > c:
        a, b = b, a % b

    t = 4 * p - b * b
    if t % (-d) != 0:
        return None
    if not issquare(t / (-d)):
        return None
    return b, int(mpmath.sqrt(t / -d))
Esempio n. 37
0
def jacobi_determinant_test():

    #*****************************************************************************80
    #
    ## JACOBI_DETERMINANT_TEST tests JACOBI_DETERMINANT.
    #
    #  Licensing:
    #
    #    This code is distributed under the GNU LGPL license.
    #
    #  Modified:
    #
    #    16 February 2015
    #
    #  Author:
    #
    #    John Burkardt
    #
    from jacobi import jacobi
    from r8mat_print import r8mat_print

    print ''
    print 'JACOBI_DETERMINANT_TEST'
    print '  JACOBI_DETERMINANT computes the determinant of the JACOBI matrix.'
    print ''

    m = 4
    n = m

    a = jacobi(m, n)
    r8mat_print(m, n, a, '  JACOBI matrix:')

    value = jacobi_determinant(n)

    print ''
    print '  Value =  %g' % (value)

    print ''
    print 'JACOBI_DETERMINANT_TEST'
    print '  Normal end of execution.'

    return
Esempio n. 38
0
def jacobi_determinant_test ( ):

#*****************************************************************************80
#
## JACOBI_DETERMINANT_TEST tests JACOBI_DETERMINANT.
#
#  Licensing:
#
#    This code is distributed under the GNU LGPL license.
#
#  Modified:
#
#    16 February 2015
#
#  Author:
#
#    John Burkardt
#
  from jacobi import jacobi
  from r8mat_print import r8mat_print
 
  print ''
  print 'JACOBI_DETERMINANT_TEST'
  print '  JACOBI_DETERMINANT computes the determinant of the JACOBI matrix.'
  print ''

  m = 4
  n = m

  a = jacobi ( m, n )
  r8mat_print ( m, n, a, '  JACOBI matrix:' )

  value = jacobi_determinant ( n )

  print ''
  print '  Value =  %g' % ( value )

  print ''
  print 'JACOBI_DETERMINANT_TEST'
  print '  Normal end of execution.'

  return
Esempio n. 39
0
def test_jacobi_eigvec(n):
    """
    Tests if the Jacobi method yields the same eigenvalues as numpy.linalg.eig
    and the analytical eigenvalues
    
    Input: 
        n - size of matrix
    """
    A = make_matrix(n, 1)
    eigval = analytical_eig(A)
    eigval_np, teigvec_np = np.linalg.eig(A)
    eigval_J, eigvec_J, a, r, t = jacobi(A)
    np.testing.assert_allclose(
        sorted(eigval), sorted(eigval_np), rtol=1e-08,
        atol=0)  #rtol - relative tolerance, atol - absolute tolerance
    np.testing.assert_allclose(sorted(eigval),
                               sorted(eigval_J),
                               rtol=1e-08,
                               atol=0)
    print('test_jacobi_eigvec passed')
Esempio n. 40
0
def choose_point(ec):
    """
    Choose a random point on EC.
    Adapted from random_point function. With the additional check for modsqrt.
    Args:
        ec: an elliptic curve by the equation y^2 = x^3 + a * x + b

    Returns:
        a valid point on the curve.
    """
    x = random.randrange(ec.p)
    y_square = (x**3 + ec.a * x + ec.b) % ec.p
    while jacobi(y_square, ec.p) == -1:
        x = random.randrange(ec.p)
        y_square = (x**3 + ec.a * x + ec.b) % ec.p
    y = modsqrt(y_square, ec.p)

    if (y**2 % ec.p) != y_square:
        raise ValueError("Error computing square root.")

    return x, y
Esempio n. 41
0
def main():
    """Using jacobi's algorithm to estimate the eigenvalues
    of the Hamiltonian for a non-interacting,
    two-electron system with a HO-potential."""
    N = int(eval(input("Number of grid points: ")))
    rho_max = 15.794
    rho = np.linspace(0, rho_max, N)  # step-variable.

    h = (rho[-1]-rho[0])/N  # step size.
    omega_r = int(eval(input("Omega_r: ")))
    e = -1/h**2  # off-diagonal elements.
    d = 2/h**2 + (omega_r**2)*rho[1:-1]**2 + 1/rho[1:-1]  # diagonal elements.
    # creating matrix:
    A = np.diag(d) + sp.diags([e, e], [-1, 1], [N-2, N-2]).toarray()

    mask = np.ones(A.shape, dtype=bool)  # creating mask to conceal diagonal.
    np.fill_diagonal(mask, 0)

    a = np.linalg.norm(A[mask])  # norm of non-diagonal elements.

    A = jac.jacobi(A, mask, a, N-2)  # finding eigenvalues.
    print(np.sort(np.diag(A))[0])  # printing lowest eigenvalue.
Esempio n. 42
0
import jacobi

n = 69
epps = list()
for a in [3, 11, 22, 68]:
    js = jacobi.jacobi(a,n)
    if (js%n != 0) and (a**((n-1)/2)%n == js %n):
        epps.append(a)

print epps
Esempio n. 43
0
#main

import jacobi

M=[[3,1],[1,7]]
print 'matrix som diagonaliseres'
print M
[A,V,c] = jacobi.jacobi(M)
print 'egenvaerdierne'
print A
a1=5+5**0.5
a2=5-5**0.5
print 'The precise eigenvalues are 5+-sqrt(5)='+str(a2)+', '+str(a1)
print 'number of sweeps'
print c
print 'with eps of 1e-12'
M=[[1,2,3],[2,4,-5],[3,-5,6]]

print 'matrix som diagonaliseres'
print M
[A,V,c] = jacobi.jacobi(M)
print 'egenvaerdierne'
print A
print 'antallet af sweeps'
print c