Beispiel #1
1
def fit1d(tup_in):

    x, y, err, rho, fit_tol, sigmas, method = tup_in
    nx = len(x)

#    if y.all() == 0:
#        yfit = np.zeros(nx)
#        confid = np.zeros(nx)
#        out = np.append(yfit, y)
#        out = np.append(out, confid)
#        return out

    if fit_tol == 0:
        ind = np.isfinite(y)
        yfit = np.interp(rho, x[ind], y[ind])
        confid = np.zeros(nx)
    else:
        if method == 'rec_spl':
            yfit, y = rec_spline1d.spline_rec1d(x, y, rho, \
                 y_err=err, fit_tol=fit_tol, sigmas=sigmas)
            confid = np.zeros(nx)
        elif method == 'gauss':
            ind = np.isfinite(err)
            yfit, confid = gauss.gauss(x[ind], y[ind], err[ind], rho, fit_tol=fit_tol)

    out = np.append(yfit, y)
    out = np.append(out, confid)

    return out
Beispiel #2
1
def main():
	A = sympy.Matrix([[3, 11], [22, 6]])
	b = sympy.Matrix([0, 0])
	print("Исходная матрица A:")
	sympy.pprint(A)
	x = gauss.gauss(A, b)
	if x:
		print("\nРезультат:", x)
Beispiel #3
1
def main():
	A = sympy.Matrix([[7, 1, 7], [-1, 7, 1], [7, -1, 7]])
	b = sympy.Matrix([15, 5, 13])
	print("Исходная матрица A:")
	sympy.pprint(A)
	print("\nВектор b:")
	sympy.pprint(b)
	x = gauss.gauss(A, b)
	if x:
		print("\nРезультат:", x)
Beispiel #4
1
def main():
	A = sympy.Matrix([[1, -3, -1], [2, -2, 1], [3, -1, 2]])
	b = sympy.Matrix([-11, -7, -4])
	print("Исходная матрица A:")
	sympy.pprint(A)
	print("\nВектор b:")
	sympy.pprint(b)
	x = gauss.gauss(A, b)
	if x:
		print("\nРезультат:", x)
Beispiel #5
1
def main():
	A = sympy.Matrix([[3, 4, 5], [1, -1, -2], [2, 1, 2], [3, -3, 1], [1, 2, 2]])
	b = sympy.Matrix([7, 0, 3, 0, 5])
	print("Исходная матрица A:")
	sympy.pprint(A)
	print("\nВектор b:")
	sympy.pprint(b)
	x = gauss.gauss(A, b)
	if x:
		print("\nРезультат:", x)
Beispiel #6
1
def main():
	a = sympy.Symbol('a')
	A = sympy.Matrix([[3, a, -3], [a, -3, 1], [5, -1, -2]])
	print("Исходная матрица A:")
	sympy.pprint(A)
	aVal = sympy.solve(sympy.Eq(A.det(), 0), a)
	print("\nЗначение а:", aVal)
	for i in aVal:
		print("\nПри а =", i)
		Asubs = A.subs(a, i)
		b = sympy.zeros(1, A.rows)
		x = gauss.gauss(Asubs, b)
		if x:
			print("\nРезультат:", x)
Beispiel #7
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)))
Beispiel #8
0
def newton(f, x, NIT, E1, E2, M):
    print('{:>5}'.format("k"), '{:>15}'.format("d1"), '{:>15}'.format("d2"))
    F = [0] * len(x)
    k = 1
    while k <= NIT:
        for i in range(len(x)):
            F[i] = -f[i](x)
        J = jcount(f, x, M)
        dx = gauss(J, F, len(x))
        x_k = [0] * len(x)
        for i in range(len(x)):
            x_k[i] = x[i] + dx[i]
        d1 = abs(f[0](x))
        for i in range(1, len(x)):
            d1 = max(d1, abs(f[i](x)))
        if x_k[0] < 1:
            d2 = abs(x_k[0] - x[0])
        else:
            d2 = abs((x_k[0] - x[0]) / x_k[0])
        for i in range(1, len(x)):
            if x_k[i] < 1:
                d2 = max(abs(x_k[i] - x[i]), d2)
            else:
                d2 = max(abs((x_k[i] - x[i]) / x_k[i]), d2)
        x = x_k
        print('{:>5}'.format(k), '{:>15}'.format(format(d1, '.9f')),
              '{:>15}'.format(format(d2, '.9f')))
        if d1 <= E1 and d2 <= E2:
            break
        if k == NIT:
            exit("IER = 2")
        k += 1
    print("\n")
    return x
Beispiel #9
0
def ex1():
    inicializar()
    print("Imprimindo matriz A:")

    for i in range(3):
        for j in range(3):
            print(str(Matriz[i][j]))
        print("")

    y[0] = util.somaProdFuncoes(f1,x,n)
    round(y[0], 30)
    y[1] = util.somaProdFuncoes(f2,x,n)
    round(y[1], 30)
    y[2] = util.somaProdFuncoes(f3,x,n)
    round(y[2], 30)

    print("Imprimindo vetor Y (yi = <fi,xi>)")
    for i in range(3):
        print("Y[" + str(i) + "]: " + str(y[i]) + "\n")

    alfa = gauss.gauss(3,Matriz,y)

    print("Imprimindo vetor x (xi=alfa_i)")
    for i in range(3):
        print("X[" + str(i) + "]: " + str(alfa[i]) + "\n")

    print("Resultado para o valor de g: " + str(2.0*alfa[2]) + " m/s²")
Beispiel #10
0
def lsm(inp, polynom_degree=1):
   
    N = inp.shape[0]#count of coordinates

    mas = np.zeros(shape=(polynom_degree + 1, N))
    vec = np.zeros(shape=(N))

    for m in range(polynom_degree + 1):
        for a in range(N):
            mas[m][a] = np.sum(inp[i][RO_ID] * inp[i][X_ID] ** (m + a) for i in range(N))

        vec[m] = np.sum(np.prod([inp[i][X_ID] ** m, inp[i][Y_ID], inp[i][RO_ID]]) for i in range(N))

    coefs = gauss.gauss(mas, vec)
    
    xs_for_approx=[]
    for k in range(polynom_degree + 1):
        index = int(k / polynom_degree * (N - 1))
        xs_for_approx.append(inp[index][X_ID])
    xs_for_approx=np.array(xs_for_approx)

    ys_by_coefs = np.zeros(shape=(polynom_degree + 1))
    for i in range(polynom_degree + 1):
        y = 0.0
        for k in range(polynom_degree + 1):         
            y+=coefs[k] * xs_for_approx[i] ** k
        ys_by_coefs[i] = y          

    return xs_for_approx, ys_by_coefs
Beispiel #11
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 plot_histogram(col: list[float],
                   name: str = '',
                   low=None,
                   high=None,
                   continuous=False,
                   density=False) -> None:
    col = sorted(col)
    n = int(1 + log(len(col), 2))
    arr = plt.hist(col, bins=n, density=density)
    for i in range(n):
        plt.text(arr[1][i], arr[0][i],
                 str(int(arr[0][i])) if not density else f'{arr[0][i]:.4f}')

    title = name

    if continuous:
        mean = float(np.mean(col))  # матожидание
        variance = float(np.var(col))  # дисперсия

        if variance < 1e-5:
            return

        title += f'\nmean = {mean:.2f} variance = {variance:.2f}'

        dist = gauss(mean, variance)
        plt.plot(col, list(map(dist, col)))

    if low and high:
        plt.axvline(x=low)
        plt.axvline(x=high)

    plt.title(title)
Beispiel #13
0
def interInversa(x,fx,p):
    x = np.vander(x,increasing = True)
    a = g.gauss(x,fx,True)
    s = ''
    print(a)
    for i in range(p.size):
        print('Para f(x) = ',p[i])
Beispiel #14
0
def Newtons_method(equ_system, derivs, e,
                   aproximation: np.ndarray) -> np.ndarray:
    iter_count = 0
    # фальшивое дельта, чтобы первый раз while сработал
    delta = np.fromiter((i + 1 for i in range(len(equ_system))), float,
                        len(equ_system))

    while iter_count < MAX_ITER_COUNT and np.linalg.norm(delta) > e:
        # рассчет левой части системы уравнений
        A = tuple(
            tuple(d_xy(*aproximation) for d_xy in dF_list)
            for dF_list in derivs)
        A = np.array(
            A)  # преобразование в numpy, т.к. функция м. гаусса работает с ним

        B = tuple(-equation(*aproximation) for equation in equ_system)
        B = np.array(
            B)  # преобразование в numpy, т.к. функция м. гаусса работает с ним

        delta = gauss(A, B)
        aproximation += delta

        iter_count += 1

    assert iter_count > 0

    return aproximation, iter_count
Beispiel #15
0
def minimosQuadrados(points, fpoints, power=4):
    """essa funcao recebe os pontos, seus respectivos valores em f(x), e o grau do polinomio desejado"""

    n = int(power) + 1
    m = len(points)

    matrixA = [[0 for col in range(n)] for row in range(n)]
    vectorB = [0] * n

    xks = [0] * ((2 * power) + 1)
    xks[0] = m

    for x in range(1, 2 * power +
                   1):  #montando os valores que vao entrar na matriz A
        xks[x] = sum([pow(i, x) for i in points])

    for x in range(n):
        for y in range(n):  #colocando os valores achados na matriz A
            matrixA[x][y] = xks[x + y]

    for x in range(n):  #montando o vetor B
        vectorB[x] = sum([pow(points[j], x) * fpoints[j] for j in range(m)])

    auxA = tuple([tuple(x) for x in matrixA])
    auxB = tuple(vectorB)

    coefs = gauss(auxA, auxB)

    def func(x):
        func = 0
        for count in range(power):
            func = func + coefs[count] * pow(x, count)
        return func

    return func, coefs
Beispiel #16
0
def SSR(img, sigma, kernel):
    if (cv2_gaussblur):
        return np.log10(img) - np.log10(cv2.GaussianBlur(img, kernel, sigma))

    out = np.zeros(img.shape)
    for i in range(img.shape[2]):
        out[:, :, i] = gauss(img[:, :, i], kernel, sigma)
    out = out + 1  #prevent division by zero
    return np.log10(img) - np.log10(out)
Beispiel #17
0
    def slider_changed(self, value):
        
        self.std_val = value
        
        if self.fit_obj.number_of_peaks != 0:
            import gauss
            self.draw()
            self.axis.plot(self.fit_obj.xline, gauss.gauss(self.fit_obj.xline, self.fit_obj.amps[-1], self.fit_obj.means[-1], self.std_val),  color='grey', linestyle=':')

        return
Beispiel #18
0
def find_l_multi(x, A, e, *, l0=None, g1=None, e1=None):
    new_x = None
    old_x = np.copy(x)
    go = True
    time_to_time_period = 1

    #
    if e1 is not None and g1 is not None:
        old_x -= (np.dot(old_x, g1) / np.dot(e1, g1)) * e1

    # первый шаг
    if l0 == None:
        new_x = A @ old_x
    else:
        A = A - l0 * np.identity(len(A))
        new_x = gauss(A, old_x)

    new_l = np.dot(new_x, old_x) / np.dot(old_x, old_x)

    count_of_iter = 0

    while go:
        count_of_iter += 1
        old_x = new_x
        old_l = new_l
        # нормируем вектор время от времени
        if count_of_iter % time_to_time_period == 0:
            norm_x = norm_vector(old_x)
            old_x = np.divide(old_x, norm_x)
            #
            if e1 is not None and g1 is not None:
                old_x -= (np.dot(old_x, g1) / np.dot(e1, g1)) * e1

        if l0 == None:
            new_x = A @ old_x
        else:
            new_x = gauss(A, old_x)
        new_l = np.dot(new_x, old_x) / np.dot(old_x, old_x)
        have_answr = abs(old_l - new_l) < e

        go = count_of_iter < ITER_MAX_COUNT and not have_answr
    return new_x, count_of_iter, new_l
Beispiel #19
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")
def integral_equation(K, f, a, b, n=5, use_python_libs=False):
    x, w = roots_legendre_interval(n, a, b, use_python_libs=use_python_libs)
    matrix = zeros((n, n + 1))
    for i in range(n):
        for j in range(n):
            matrix[i, j] = w[j] * K(x[i], x[j])
        matrix[i, n] = f(x[i])
    y = solve(matrix[:,
                     0:-1], matrix[:,
                                   -1]) if use_python_libs else gauss(matrix)
    assert len(x) == len(y), f'len(x) = {len(x)}, len(y) = {len(y)}'
    result = CubicSpline(x, y)
    return result, cond(matrix)
Beispiel #21
0
def main():
    start = 0
    end = math.pi / 2
    num = 8
    integral = ct.compound_trapezoid(start, end, num)
    print('9点复化梯形公式计算结果:')
    print(integral)
    num = 8
    integral = cs.compound_simpson(start, end, num)
    print('9点复化辛普森公式计算结果:')
    print(integral)
    num = 3
    integral = gs.gauss(start, end, num)
    print('3点高斯公式计算结果是:')
    print(integral)
    num = 4
    integral = gs.gauss(start, end, num)
    print('4点高斯公式计算结果是:')
    print(integral)
    integral = rb.romberg(start, end, k=4)
    print('龙贝格方法计算结果是:')
    print(integral)
Beispiel #22
0
def gauss_piv(A):
    n = A.shape[0]
    piv = np.zeros(n - 1, int)
    for k in range(n - 1):
        mu = int(np.argmax(np.abs(A[k:, k])))
        swap(A[k, k:], A[mu, k:])
        piv[k] = mu

        if A[k, k] != 0:
            t = gauss(A[k:, k])
            A[k + 1:, k] = t
            A[k:, k + 1:] = gauss_app(A[k:, k + 1:], t)

    return piv
Beispiel #23
0
def newtonRaphson(funcMatrix, x0, epsilon=0.0001, niteMax=10):
    """o metodo de newton raphson"""
    xk = [0] * (niteMax+1)
    xk[0] = x0
    
    for k in range(niteMax):
        if norm(evaluate(funcMatrix, xk[k])) < epsilon:
            break
        else:
            fxk = [i*-1 for  i in evaluate(funcMatrix,xk[k])]
            jxk = jacobian(funcMatrix, xk[k])
            dx = gauss(jxk, fxk)
            xk[k+1] = sumMatrices(xk[k], dx)
    
    return xk[k]
Beispiel #24
0
def exercicio1_2():
    print("Exercicios 1")
    inicializar()
    M = gauss.gauss(n,Matriz,d)
    print("Parametro M")
    print(str(np.array(M)))
    A = parametros.parametroA(x,M,h,n)
    print("Parametro A")
    print(str(np.array(A)))
    B = parametros.parametroB(x,M,h,n)
    print("Parametro B")
    print(str(np.array(B)))

    valoresDeTeste = np.zeros(n);
    valoresDeTeste[0] = (t[1] + t[0]) / 2

    print("Valores de t")
    for i in range(1, n, 1):
        valoresDeTeste[i] = valoresDeTeste[i - 1] + (1.0/60)
    print(str(np.array(valoresDeTeste)))

    print("Teste do polinomio")
    spline = np.zeros(n)
    for i in range(0, n, 1):
        spline[i] = util.splineCubico(valoresDeTeste[i],M,h,A,B,t,n)
    print(str(np.array(spline)))

    print("Teste da primeira derivada")
    derivada1 = np.zeros(n)
    for i in range(0, n, 1):
        derivada1[i] = util.derivadaSC(valoresDeTeste[i],M,h,A,B,t,n)
    print(str(np.array(derivada1)))

    print("Teste da segunda derivada")
    derivada2 = np.zeros(n)
    for i in range(0, n, 1):
        derivada2[i] = util.segundaDerivadaSC(valoresDeTeste[i],M,h,A,B,t,n)
    print(str(np.array(derivada2)))

    print("O intervalo escolhido é [t19, t20]")

    print("Exercicio 2")

    print("O chute será 0.333")

    raiz = newton.newton(0.333,M,h,A,B,t,n,10**-10,n)

    print("O t é: " + str(raiz))
Beispiel #25
0
def lin_leastsq(x, y):
    """Linear Least Squares curve fit (manual method).
  """
    n = len(x)
    sx = sy = sx2 = sy2 = sxy = 0.0
    for i in range(0, n):
        sx += x[i]
        sy += y[i]
        sx2 += x[i] * x[i]
        sy2 += y[i] * y[i]
        sxy += x[i] * y[i]

    C = [[n, sx, sy], [sx, sx2, sxy]]
    coeff = gauss.gauss(C)
    a = coeff[0]
    b = coeff[1]
    r = (a * sy + b * sxy - (sy * sy) / n) / (sy2 - (sy * sy) / n)
    return coeff, r
Beispiel #26
0
def Nt(t, p):

    X = [-1, 3, -1, -10, -20, -35]
    dX = [0] * len(X)
    dx_x = 1

    while dx_x >= EPSILON:

        for i in range(len(X)):
            X[i] += dX[i]

        gamma = dt.dichotomy(0, 3, lambda g: Gamma(g, t, X), EPSILON)
        k = K(t, gamma)
        alpha = 0.285 * 10**-11 * (gamma * t)**3

        expV = math.exp(X[0])
        expX1 = math.exp(X[1])
        expX2 = math.exp(X[2])
        expX3 = math.exp(X[3])
        expX4 = math.exp(X[4])
        expX5 = math.exp(X[5])

        lnK0 = math.log(k[0])
        lnK1 = math.log(k[1])
        lnK2 = math.log(k[2])
        lnK3 = math.log(k[3])

        z_right = Z[1]*expX2 + Z[2]*expX3 + Z[3]*expX4 + Z[4]*expX5 - expV
        a_right = expV + expX1 + expX2 + expX3 + expX4 + expX5 - alpha - p*7243/t;

        eqsystem = [
            [      1,           -1,            1,            0,            0,            0,  lnK0 + X[1] - X[2] - X[0]],
            [      1,            0,           -1,            1,            0,            0,  lnK1 + X[2] - X[3] - X[0]],
            [      1,            0,            0,           -1,            1,            0,  lnK2 + X[3] - X[4] - X[0]],
            [      1,            0,            0,            0,           -1,            1,  lnK3 + X[4] - X[5] - X[0]],
            [   expV,  -Z[0]*expX1,  -Z[1]*expX2,  -Z[2]*expX3,  -Z[3]*expX4,  -Z[4]*expX5,                    z_right],
            [  -expV,       -expX1,       -expX2,       -expX3,       -expX4,       -expX5,                    a_right]
        ]
        
        dX = gs.gauss(eqsystem)
        dx_x = max([ (dX[i] / X[i]) for i in range(len(X)) ])
    
    return sum([math.exp(x) for x in X])
Beispiel #27
0
def exercicio4_5():
    print("Exercicios 4 e 5")
    inicializar()
    M = gauss.gauss(n, 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")

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

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

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

    print("M: ")
    for i in range(n):
        print(str(M[i]))
    print("A: ")
    for i in range(n):
        print(str(A[i]))
    print("B: ")
    for i in range(n):
        print(str(B[i]))
    print("\n")
Beispiel #28
0
    iteration_d = {"gauss": [], "jacobi": [], "sor": []}

    time_d = {"gauss": [], "jacobi": [], "sor": []}

    spectral_d = {"gauss": [], "jacobi": [], "sor": []}

    for dim in range(10, 100, 5):

        a = np.random.rand(dim, dim)
        A = (a + a.T) / 2
        A = np.add(dim * np.identity(dim), A)

        b = np.random.rand(dim)

        print("Running Gaussian")
        x_gauss, iteration_gauss, total_time_gauss, all_x_gauss, spectral_radius_gauss = gauss(
            A, b, None, 1E-15, 1000000)
        print("Running Jacobi")
        x_jacobi, iteration_jacobi, total_time_jacobi, all_x_jacobi, spectral_radius_jacobi = jacobi(
            A, b, None, 1E-15, 1000000)
        print("Running Sor")
        x_sor, iteration_sor, total_time_sor, all_x_sor, spectral_radius_sor = SOR(
            A, b, None, 1E-15, 1000000, optimal_w(A))

        iteration_d["gauss"].append(iteration_gauss)
        iteration_d["jacobi"].append(iteration_jacobi)
        iteration_d["sor"].append(iteration_sor)

        time_d["gauss"].append(total_time_gauss)
        time_d["jacobi"].append(total_time_jacobi)
        time_d["sor"].append(total_time_sor)
Beispiel #29
0
def solver(a, v, b, n):
    tol = 0.001
    resultados = gauss.gauss(a, b, n, tol)
    for i in range(n):
        print(v[i] + " = " + str(resultados[i]))
Beispiel #30
0
def pt2():
    n = 10
    log_mi = np.zeros(n)
    log_hi = np.zeros(n)
    log_ETn = np.zeros(n)
    log_ESn = np.zeros(n)
    Y = np.zeros(2)
    X = np.zeros(2)
    M = np.zeros((2, 2))

    print("Supondo uma aproximacao y=ax+b onde temos: ")
    print("y = log10(ETn) ou log10(ESn)")
    print("x = log10(h)")

    for i in range(n):
        log_mi[i] = 1.0

    print("log10(h)")
    for i in range(10, 101, 10):
        log_hi[int((i - 10) / 10)] = math.log10(1 / i)
        print(str(log_hi[int((i - 10) / 10)]))

    print("log10(ETn)")
    for i in range(10, 101, 10):
        log_ETn[int((i - 10) / 10)] = math.log10(
            np.abs(np.exp(1) - np.exp(0) - util.Tn(0, 1, i)))
        print(str(log_ETn[int((i - 10) / 10)]))

    print("log10(ETn)")
    for i in range(10, 101, 10):
        log_ESn[int((i - 10) / 10)] = math.log10(
            np.abs(np.exp(1) - np.exp(0) - util.Sn(0, 1, i)))
        print(str(log_ESn[int((i - 10) / 10)]))

    print("Minimos quadrados")

    f1f1 = util.somaProdFuncoes(log_mi, log_mi, n)
    f1f2 = util.somaProdFuncoes(log_mi, log_hi, n)
    f2f2 = util.somaProdFuncoes(log_hi, log_hi, n)

    print("Coeficientes da Matriz:")
    print("<f1, f1> = " + str(f1f1))
    print("<f1, f2> = " + str(f1f2))
    print("<f1, f3> = " + str(f2f2))

    print("Coeficientes do vetor de entrada:")

    Y[0] = util.somaProdFuncoes(log_mi, log_ETn, n)
    Y[1] = util.somaProdFuncoes(log_hi, log_ETn, n)
    print("<f1, log(ETn)> = " + str(Y[0]))
    print("<f2, log(ETn)> = " + str(Y[1]))

    M[0][0] = f1f1
    M[0][1] = f1f2
    M[1][0] = f1f2
    M[1][1] = f2f2

    X = gauss.gauss(2, M, Y)

    print("Coeficientes para a reta log(ETn)")
    print("Angular: " + str(X[1]))
    print("Linear: " + str(X[0]))

    print("Coeficientes do vetor de entrada:")

    Y[0] = util.somaProdFuncoes(log_mi, log_ESn, n)
    Y[1] = util.somaProdFuncoes(log_hi, log_ESn, n)
    print("<f1, log(ESn)> = " + str(Y[0]))
    print("<f2, log(ESn)> = " + str(Y[1]))

    M[0][0] = f1f1
    M[0][1] = f1f2
    M[1][0] = f1f2
    M[1][1] = f2f2

    X = gauss.gauss(2, M, Y)

    print("Coeficientes para a reta log(ESn)")
    print("Angular: " + str(X[1]))
    print("Linear: " + str(X[0]))
Beispiel #31
0
def square_root(A, b):
    U = cholesky(A)
    y = gauss(U, b)
    x = gauss(transpose(U), y)
    return x
Beispiel #32
0
def calc(point_list, element_list, load_list, method='gauss', ite=5000):

    element_list, point_list = calcSenCos(element_list, point_list)
    matrix_list = []
    for i in element_list:
        matrix_list.append(matrixMaker(i))
    superMatrix = superMatrixMaker(matrix_list, len(point_list))

    v_carregamento = []
    contador = 0
    for i in point_list:
        if i.name == load_list[contador].point:
            v_carregamento.append([int(load_list[contador].intensity_x)])
            v_carregamento.append([int(load_list[contador].intensity_y)])
            contador += 1
        else:
            v_carregamento.append([0])
            v_carregamento.append([0])
    v_carregamento = np.array(v_carregamento, dtype=float)
    v_deslocamento = []
    for i in point_list:
        linha = []
        if i.x_fixed:
            linha.append(0)
            v_deslocamento.append(linha)
            linha = []
        else:
            linha.append(-1)
            v_deslocamento.append(linha)
            linha = []
        if i.y_fixed:
            linha.append(0)
            v_deslocamento.append(linha)
            linha = []
        else:
            linha.append(-1)
            v_deslocamento.append(linha)
            linha = []
    v_deslocamento = np.array(v_deslocamento, dtype=float)
    for i in range(0, len(v_deslocamento)):
        if v_deslocamento[i][0] == 0:
            v_carregamento[i][0] = -0.001
    matrixContorno, v_carregamento_contorno = contornoMaker(
        superMatrix, v_deslocamento, v_carregamento)

    if method == 'gauss':
        v_deslocamento_metodo = gauss(ite, 0.0001, matrixContorno,
                                      v_carregamento_contorno)
    else:
        v_deslocamento_metodo = gauss(ite, 0.0001, matrixContorno,
                                      v_carregamento_contorno)

    contador = 0

    for i in range(0, len(v_deslocamento)):
        if v_deslocamento[i][0] != 0:
            v_deslocamento[i][0] = v_deslocamento_metodo[contador]
            contador += 1
    contador = 0
    for i in point_list:
        i.x_displacement = v_deslocamento[contador][0]
        contador += 1
        i.y_displacement = v_deslocamento[contador][0]
        contador += 1
    lista_tensao, lista_deformacao = strain_stressMaker(element_list)

    contador = 0
    for i in element_list:
        i.strain = lista_tensao[contador]
        i.stress = lista_deformacao[contador]
        contador += 1

    lista_reactions, v_carregamento = reactionsMaker(superMatrix,
                                                     v_deslocamento,
                                                     v_carregamento)

    contador = 0
    for i in point_list:
        if i.x_fixed:
            i.x_reaction = round(lista_reactions[contador][0], 4)
            contador += 1
        if i.y_fixed:
            i.y_reaction = round(lista_reactions[contador][0], 4)
            contador += 1

    return point_list, element_list, load_list
print('2-SET -> Cramer: x1={:e}'.format(X2[0]), 'x2={:e}'.format(X2[1]))
print("Error: ", abs(X1_exact - X2))
print("-" * 10, "\n")

# Matrix inverse:
X1 = dot(inv(A1), b1)
X2 = dot(inv(A2), b2)
print("Matrix inverse: ")
print('1-SET -> Cramer: x1={:e}'.format(X1[0][0]), 'x2={:e}'.format(X1[1][0]))
print("Error: ", abs(X1_exact - transpose(X1)))
print('2-SET -> Cramer: x1={:e}'.format(X2[0][0]), 'x2={:e}'.format(X2[1][0]))
print("Error: ", abs(X1_exact - transpose(X2)))
print("-" * 10, "\n")

# Gauss elimination:
X1 = gauss(A1.copy(), b1.copy())
X2 = gauss(A2.copy(), b2.copy())
print("Gauss: ")
print('1-SET -> Cramer: x1={:e}'.format(X1[0][0]), 'x2={:e}'.format(X1[1][0]))
print("Error: ", abs(X1_exact - transpose(X1)))
print('2-SET -> Cramer: x1={:e}'.format(X2[0][0]), 'x2={:e}'.format(X2[1][0]))
print("Error: ", abs(X1_exact - transpose(X2)))
print("-" * 10, "Using NumPy:", "\n")
X1 = solve(A1.copy(), b1.copy())
X2 = solve(A2.copy(), b2.copy())
print('1-SET -> Cramer: x1={:e}'.format(X1[0][0]), 'x2={:e}'.format(X1[1][0]))
print("Error: ", abs(X1_exact - transpose(X1)))
print('2-SET -> Cramer: x1={:e}'.format(X2[0][0]), 'x2={:e}'.format(X2[1][0]))
print("Error: ", abs(X1_exact - transpose(X2)))
print("-" * 10, "\n")
Beispiel #34
0
errorG = zeros(1000)
errorT[0] = errorG[0] = 1
errorT[1] = errorG[1] = 1

for f in fs:
    #eT = eG = 0
    #eTn = eGn = 0
    for n in range(2, 1000):
        errorT[n] = abs(trapezoidal(f, lower, upper, n+1) - trapezoidal(f, lower, upper, n))
        #eT += 1
        #eTn = n
        #if errorT[n] < tol:
        #    break

    for n in range(2, 1000):
        errorG[n] = abs(gauss(f, n+1) - gauss(f, n))
        #eG += 1
        #eGn = n
        #if errorG[n] < tol:
        #    break

    i += 1
    n = linspace(0, 1000, 1000)

    print("\ntrapezoidal:")
    #print("The trapezoidal rule on function " + str(i) + " required " + str(eT) + " evaluations with n=2,3,..," + str(eTn) + " trapezoids to satisfy the error tolerance " + str(tol) + ".")
    print(errorT)
    pyplot.figure(i-1)
    pyplot.loglog(n, n**(-1), n, n**(-2), n, n**(-3), n, errorT)
    pyplot.xlabel('n')
    pyplot.ylabel('error')
Beispiel #35
0
from gauss import gauss, residuo
from gauss_seidel import gauss_seidel, converges
from matrix import create_matrix, n

import numpy as np

A, b = create_matrix()

g_res = gauss(A, b)

g_mres = max(abs(residuo(A, b, g_res)))

print('A1:')
print('Primeira:', g_res[0])
print('Última:', g_res[-1])
print('Resíduo máximo:', g_mres)

print('\nA2:')
print('Operações em ponto flutuante:', (4 * n**3 + 9 * n**2 - n - 6) // 6)

criteria = 1e-4

print('\nB1:')

if converges(A):
    print('O sistema possui diagonal dominante e sempre irá convergir. '
          'Podemos acelerar o cálculo usando um fator de sobre-relaxação.')
else:
    print('O sistema não possui diagonal dominante e '
          'talvez não venha a convergir')
Beispiel #36
0
def methods_logic(method, size):
    if size > 10:
        abort(404)

    if method == 0:
        if size > 4:
            abort(404)

    if request.method == 'POST':
        if request.form.get('rand'):
            A, B = generate_rand(size, -10, 10)
        else:
            B = [int(i) for i in request.form.getlist('mat_b')]
            A = [int(i) for i in request.form.getlist('mat_a')]
            A = [A[i:i + len(B)] for i in range(0, len(A), len(B))]

        rd = int(request.form.get('round'))
        if not rd:
            rd = 3
        file = request.files['fil']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            size, A, B = parse_file('upload/' + filename)

        X = None
        haveAnswer = True
        if method == 0:
            X = kramer(A.copy(), B.copy(), rd)
        elif method == 1:
            X = gauss(A.copy(), B.copy(), rd)
        elif method == 2:
            it = int(request.form.get('iter'))
            haveAnswer, X = zadel(A.copy(), B.copy(), rd, it)
        elif method == 3:
            X = jordan_gauss(A.copy(), B.copy(), rd)
        elif method == 4:
            it = int(request.form.get('iter'))
            haveAnswer, X = jacobi(A.copy(), B.copy(), rd, it)

        if X == -1:
            answer = 'Matrix is degenerate'
        elif not haveAnswer:
            answer = generateErrors(X, methods[method])
        else:
            answer = [f' X{i} = {x} <br>' for i, x in enumerate(X)]
            answer = ''.join(answer)
            if request.form.get('checkRoots'):
                if checkRoots(A, B, X):
                    answer += '<br>Roots is true'
                else:
                    answer += '<br>Roots is false'

        return render_template('method.html',
                               text=generate_form(size,
                                                  method=method,
                                                  A=A,
                                                  B=B,
                                                  rd=rd),
                               title=methods[method],
                               answer=answer)
    else:
        return render_template('method.html',
                               text=generate_form(size, method=method),
                               title=methods[method])
Beispiel #37
0
    def M2M(self, params, kcorr=0.):
        """
      Calculate RM distribution, then apply the transformation from 
      log(M_star) directly to m_obs.
      self.M2M_kernel should be a dictionary, whose keys are (logMlo,logMhi)
      denoting the boundary of each stellar mass bin, and the values are
      a tuple (X0, p(X) or sigma_X)---sigma_X being the scatter of a 
      Gaussian around X0 *in magnitudes*. The conversion between M1500 and 
      logM is

      M1500 = (-2.5/a) * logM + X
      
      params are in (alpha_m, logMstar_m, logR0, sigma, beta_m)
      """
        # Strategy: convert R-M distribution into R-m (apparent magnitude)
        # distribution using the "X factor" and the magnitude correction at
        # each redshift z.
        bivmodel_RL = zeros(self.npix)
        # the kernel width in the X dimension
        kw = self.M2M_kernel['kwidth']
        # kw is in pixels
        X_ref = self.M2M_kernel['xref']
        # a reference value for X. I will shift RM distribution by X_ref first,
        # and then shift the kernel in each bin to center around the respective
        # X values.
        # if 'type' == 'distribution': not yet implemented...
        if self.M2M_kernel['type'] == 'distribution':
            # the correction is M1500 = -log10(M_star) + X, with X a random
            # variable following probability distribution p(X)
            # First, convert logM into m (apparent magnitude) and calculate the
            # uncorrected R-m distribution converted from RM distribution.
            # Pixel size is unchanged.
            raise ValueError, "distribution-type M2M kernels not yet implemented..."
            mstar_ref = -1. * params[1] + X_ref + kcorr
            m0_ref = -1. * self.logM0 + X_ref + kcorr
            params_ref = params.copy()
            params_ref[1] = mstar_ref
            #print "params_ref", params_ref
            #print "m0_ref", m0_ref
            model0 = self.bivariate_RM_0(params_ref,
                                         self.limits,
                                         pixdx=self.pixdx,
                                         logM0=m0_ref,
                                         xdirection=1,
                                         a=1)
            #print "max(model0)", max(model0.ravel())
            # Now apply relative shifts for each kernel (relative to X_ref) as
            # well as smearing around X0 in each bin.
            for k in self.M2M_kernel['kernels'].keys():
                if k[1] < self.limits_m[0][1]:
                    continue
                elif k[0] > self.limits_m[0][0]:
                    continue
                #print "k", k
                X0 = self.M2M_kernel['kernels'][k][0]
                # the reference X of this bin
                logMlo = k[0]
                logMhi = k[1]
                # The limits in M1500 of this stellar mass bin before smearing
                mobs_hi = -1. * logMlo + X0 + kcorr
                mobs_lo = -1. * logMhi + X0 + kcorr
                j0 = round((mobs_lo - self.limits[0][0]) / self.pixdx[0])
                j0 = maximum(int(j0), 0)
                j1 = round((mobs_hi - self.limits[0][0]) / self.pixdx[0])
                j1 = minimum(int(j1), self.npix[0] - 1)
                #print "k, j0, j1", k, j0, j1
                if j1 <= j0:
                    continue
                model_RL_k = model0.copy()
                # Copy the section in this log(M_star) bin onto the M1500 grid
                #model_RL_k[j0:j1] = model_RM_k[i0:i1].copy()
                model_RL_k[:j0, :] = 0.
                model_RL_k[j1:, :] = 0.
                # Now smear the model
                X_shift = X0 - X_ref
                # the relative shift between X0 and X_ref---this will be the mean
                # of the Gaussian distribution of this kernel
                X_shift_pix = X_shift / self.pixdx[0]
                #if type(self.M2M_kernel[k][1]) == type(1.0):
                # A Gaussian kernel, with sigma given in magnitude
                sigma_X = self.M2M_kernel['kernels'][k][1]
                # sigma_X is in magnitudes
                sigma_X_pix = sigma_X / self.pixdx[0]
                # sigma_X_pix is in pixels
                if kw % 2 == 1:
                    xarr = arange(-(kw - 1) / 2., (kw + 1) / 2.)
                else:
                    xarr = arange(kw) - kw / 2.
                if sigma_X > 0:
                    kernel = gauss.gauss(xarr, X_shift_pix, sigma_X_pix)
                else:
                    # a delta-function kernel
                    kernel = zeros(kw)
                    kernel[int(kw / 2 + X_shift_pix)] = 1.0
                #else:
                #   # the 1-D smearing kernel
                #   kernel = self.M2M_kernel[k][1].copy()
                # Make kernel into a 2D array (pad with 0 on both sides) for
                # convolution
                kernel2d = zeros((len(kernel), 3))
                kernel2d[:, 1] = kernel
                # smear with p(X)
                model_RL_k = hconvolve(model_RL_k, kernel2d)
                # paste back onto bivmodel_M1500
                bivmodel_RL = bivmodel_RL + model_RL_k
        elif self.M2M_kernel['type'] == 'equation':
            # Uses a linear equation M1500 = -a * log(M_star) + b, and a Gaussian
            # spread around this equation (the uncertainty is the same throughout)
            # all stellar mass bins.
            # If dm is given by self.pixdx[0], then dlogM needs to be rescaled
            # to self.pixdx[0]/a
            a, b, sigma_X = self.M2M_kernel['kernels']
            sigma_X_pix = sigma_X / self.pixdx[0]
            # if M2M_kernel['type']=='equation', then M2M_kernel['kernels']
            # should contain a list of three numbers: a, b, and sigma_X. The
            # transformation now is M1500 = -a * log(M_star) + b, and sigma_X
            # smears the model in the magnitude direction.
            mstar_ref = (-2.5 / a) * params[1] + b + kcorr
            m0_ref = (-2.5 / a) * self.logM0 + b + kcorr
            params_ref = params.copy()
            params_ref[1] = mstar_ref
            #print "params_ref", params_ref
            #print "m0_ref", m0_ref
            model0 = self.bivariate_RM1500_0(params,
                                             self.limits,
                                             pixdx=self.pixdx,
                                             logM0=self.logM0,
                                             a=abs(a),
                                             b=b,
                                             kcorr=kcorr)
            #return model0
            # Now apply the smearing due to uncertain M/L
            if kw % 2 == 1:
                xarr = arange(-(kw - 1) / 2., (kw + 1) / 2.)
            else:
                xarr = arange(kw) - kw / 2.
            if sigma_X > 0:
                kernel = gauss.gauss(xarr, 0., sigma_X_pix)
            else:
                # a delta-function kernel
                kernel = zeros(kw)
                kernel[int(kw / 2)] = 1.0
            kernel2d = zeros((len(kernel), 3))
            kernel2d[:, 1] = kernel
            # smear with p(X)
            bivmodel_RL = hconvolve(model0, kernel2d)

        return bivmodel_RL