def PanelIntegrator1(n, a, b): # integrate from a to b with n panels dx = (b - a) / n eta = 0.5 * np.sqrt(0.6) import f # a module that defines f(x) x = np.linspace(a, b, n + 1) #Ik = (dx/18.0)*(5.0*f.f(x+(dx/2.0)-(dx*eta))+8.0*f.f(x+(dx/2.0))+5.0*f.f(x+(dx/2.0)+(dx*eta)))# evaluate f at the point x+dx/2 or x{k+0.5} as dx is constant here Ik = (dx / 6) * (f.f(x) + 4 * f.f(x + (dx / 2.0)) + f.f(x + dx)) I = sum(Ik) # plt.plot(x,f.f(x)) # plt.show() return I # estimate of the integral
def compareTime(n, W, N): my = 0.0 nump = 0.0 for i in range(10): s = rsg.getRandomSignal(n, W, N) start = time.perf_counter() f.f(s) stop = time.perf_counter() my += (stop - start) start = time.perf_counter() np.fft.fft(s) stop = time.perf_counter() nump += (stop - start) return my, nump
def PanelIntegrator(n, a, b): # integrate from a to b with n panels dx = (b - a) / n import f # a module that defines f(x) # ... # I += c*dx*f.f(x) # evaluate f at the point x # ... return f.f(a) # estimate of the integral
def newton(alpha, G_real, G_imag, omega_n, omega, A_initial, C_real_inv, C_imag_inv): import numpy as np import numpy.linalg Nomega = len(omega) Niom = len(omega_n) iterationMax = 100 counter = 0 eps = 0.00001 while (True): counter = counter + 1 if (counter > iterationMax): break function = f.f(alpha, G_real, G_imag, A_initial, omega_n, omega, C_real_inv, C_imag_inv) Jacobian = J.J(alpha, A_initial, omega_n, omega, C_real_inv, C_imag_inv) A_updated = A_initial - numpy.linalg.inv(Jacobian).dot(function) if (nan.array_isnan(A_updated)): A_initial = A_updated break error = diff(A_initial, A_updated) if (error < eps): break print "counter = ", counter, ", diff = ", error A_initial = A_updated return A_initial
def newton(alpha, G, omega_n, omega, A_initial, C_real_inv, C_imag_inv): import numpy as np import numpy.linalg Nomega = len(omega) Niom = len(omega_n) Jacobian = np.zeros((Nomega, Nomega)) function = np.zeros(Nomega) A_updated = np.zeros(Nomega) iterationMax = 100 counter = 0 eps = 0.008 while(True): counter = counter + 1 if (counter > iterationMax): break for i in range(Nomega): for j in range(Nomega): Jacobian[i, j] = J.J(alpha, A_initial, i, j, omega_n, omega, C_real_inv, C_imag_inv) for i in range(Nomega): function[i] = f.f(alpha, G, A_initial, i, omega_n, omega, C_real_inv, C_imag_inv) A_updated[:] = A_initial[:] - numpy.linalg.inv(Jacobian).dot(function)[:] error = diff(A_initial, A_updated) if (error < eps): break print "counter = ", counter, ", diff = ", error A_initial[:] = A_updated[:] return A_initial
def newton(alpha, G_real_rotated, G_imag_rotated, K_real_rotated, K_imag_rotated, omega, A_initial, D, LambdaInverse): import numpy as np Nomega = len(omega) iterationMax = 30 counter = 0 eps = 0.00001 while (True): counter = counter + 1 if (counter > iterationMax): break function = f.f(alpha, G_real_rotated, G_imag_rotated, K_real_rotated, K_imag_rotated, A_initial, D, omega, LambdaInverse) Jacobian = J.J(alpha, A_initial, omega, K_real_rotated, K_imag_rotated, LambdaInverse) A_updated = A_initial - np.linalg.inv(Jacobian).dot(function) for i in range(len(A_updated)): if (A_updated[i] < 0): A_updated[i] = 1.0e-14 if (nan.array_isnan(A_updated)): A_initial = A_updated break error = diff(A_initial, A_updated) if (error < eps): break print "counter = ", counter, ", diff = ", error A_initial = A_updated return A_initial
def newton(x0, y0): count = 0 iterationMax = 20 eps = 1.0e-16 vector = np.zeros(2) J = np.zeros((2, 2)) vector[0] = x0 vector[1] = y0 fg = np.zeros(2) while (count < iterationMax): count = count + 1 old = vector x = vector[0] y = vector[1] J[0, 0] = f.fx(x, y) J[0, 1] = f.fy(x, y) J[1, 0] = g.gx(x, y) J[1, 1] = g.gy(x, y) fg[0] = f.f(x, y) fg[1] = g.g(x, y) diff = np.linalg.solve(J, -fg) vector = diff + old error = np.linalg.norm(diff) #print "count = ", count, ", error = ", error if (error < eps): break return vector
def post(self): serveStart = time.time() try: data = self.request.body try: event = json.loads(data) except: self.set_status(400) self.write('bad POST data: "%s"' % str(data)) return if 'ReportStats' in event: self.write(reportStats()) resetStats() else: invokeStart = time.time() r = f.f(event) globStats['tolSBInvoke'] += (time.time() - invokeStart) * 1000000 globStats['nolSBInvoke'] += 1 self.write(json.dumps(r)) globStats['tServe'] += (time.time() - serveStart) * 1000000 globStats['nServe'] += 1 except Exception as e: self.set_status(500) # internal error self.write(traceback.format_exc())
def adam(alpha, G_real_rotated, G_imag_rotated, K_real_rotated, K_imag_rotated, omega, A_initial, D, LambdaInverse, lambd): eps = 1.0e-8 counter = 0 iterationMax = 1000 rate = -0.01 beta1 = 0.9 beta2 = 0.99 m = np.zeros(len(omega)) v = np.zeros(len(omega)) while (True): counter += 1 if (counter > iterationMax): error = np.linalg.norm(gradient) #print "counter = " + str(counter) + ", norm of gradient = " + str(error) break gradient = f.f(alpha, G_real_rotated, G_imag_rotated, K_real_rotated, K_imag_rotated, A_initial, D, omega, LambdaInverse, lambd) m = beta1 * m + (1 - beta1) * gradient v = beta2 * v + (1 - beta2) * gradient**2 m = m / (1 - beta1**counter) v = v / (1 - beta2**counter) A_initial = A_initial - rate * m / (np.sqrt(v) + eps) for i in range(len(A_initial)): if (A_initial[i] < 0): A_initial[i] = 1.0e-10 #error = np.linalg.norm(gradient) #print "counter = " + str(counter) + ", norm of gradient = " + str(error) #if (error < 1.0e-3): # break return A_initial
def PanelIntegrator(n, a, b): # integrate from a to b with n panels dx = (b - a) / n import f # a module that defines f(x) x = np.linspace(a, b, n + 1) I = sum(dx * f.f(x)) # evaluate f at the point x # plt.plot(x,f.f(x)) # plt.show() return I # estimate of the integral
def P_alph(self,t): X_1 = self.X[0] X_2 = self.X[1] Xff = np.copy(self.X) Xff[0] = self.a0 Xff[1] = self.a1 ft = f(np.insert(Xff,0,t)) term1 = -X_1 term2 = -0.5e0*X_2*(1+ft*math.cos(t))**2 term3 = (1./(2.*math.pi*self.alph**2))*self.get_integral_simp(ft,t) res = term1 + term2 + term3 return res
def post(self): try: data = self.request.body try: event = json.loads(data) except: self.set_status(400) self.write('bad POST data: "%s"' % str(data)) return self.write(json.dumps(f.f(event))) except Exception: self.set_status(500) # internal error self.write(traceback.format_exc())
def get_in_gauss(self,tcap,ft,t): X_f = np.insert(self.X,0,tcap) X_f[1] = self.a0 X_f[2] = self.a1 ftcap = f(X_f) #Splitting the interval #n = 5 #res = np.zeros(n) #for i in range(0,n): #start_scap = i/n*ftcap #end_scap = (i+1)/n*ftcap #res[i] = sci.quadrature(G_int,start_scap,end_scap, \ #args=(tcap,ft,t),vec_func=False)[0] #return np.sum(res) #Without splitting res = sci.quadrature(G_int,0.,ftcap, \ args=(tcap,ft,t),vec_func=False)[0] return res
def post(self): # we don't import this until we get a request; this is a # safeguard in case f is malicious (we don't # want it to interfere with ongoing setup, such as the # move to the new cgroups) import f try: data = self.request.body try : event = json.loads(data) except: self.set_status(400) self.write('bad POST data: "%s"'%str(data)) return self.write(json.dumps(f.f(event))) except Exception: self.set_status(500) # internal error self.write(traceback.format_exc())
def encrypt(self, message, kys, decrypt): """Function f operates on two blocks: a data block of 32 bits (rn_minus1) and a key (Kn) of 48 bits to produce a block of 32 bits. Args: message: The n minus one permutation of the right hand side of the message block. kys: The nth iteration of the key. decrypt: A boolean to set if the message is to be encrypted or decrypted. Returns: A block of 32 bits. """ d = 15 if decrypt else 0 bin_encryption = "" # split the message into 64bit blocks for x in range(0, len(message), 64): bit64 = message[x:x+64] # initial_permutation (ip) substitution initial_permutation = substitution(self.ip, bit64) # Divide the permuted block IP into a left and right half of 32 bits. ln, rn = 0, 0 ln_minus_1 = int(initial_permutation[:32], 2) rn_minus_1 = int(initial_permutation[32:], 2) # 16 iterations of: Ln = Rn-1, Rn = Ln-1 + f(Rn-1,Kn) for y in range(0, 16): ln = rn_minus_1 rn = ln_minus_1 ^ (f(rn_minus_1, kys[abs(d - y)], self.e_bit_table, self.__sbox, self.p_table)) ln_minus_1 = ln rn_minus_1 = rn bit64 = bin(rn)[2:].zfill(32) + bin(ln)[2:].zfill(32) bin_encryption += substitution(self.ip_1, bit64) hex_translation = self.bin_to_hex(bin_encryption) return bin_encryption, hex_translation
def solver(alpha, G_real_rotated, G_imag_rotated, K_real_rotated, K_imag_rotated, omega, A_initial, D, LambdaInverse, lambd): eps = 1.0e-7 counter = 0 iterationMax = 30 while (True): counter = counter + 1 if (counter > iterationMax): #result = adam(alpha, G_real_rotated, G_imag_rotated, K_real_rotated, K_imag_rotated, omega, A_initial, D, LambdaInverse, lambd) #return result break Jacobian = J.J(alpha, A_initial, omega, K_real_rotated, K_imag_rotated, LambdaInverse, lambd) function = f.f(alpha, G_real_rotated, G_imag_rotated, K_real_rotated, K_imag_rotated, A_initial, D, omega, LambdaInverse, lambd) #solution = conjugateGradient.conjugateGradient(-Jacobian, function) #eigenvalues = np.linalg.eigvals(-Jacobian) #eigen_max = max(eigenvalues) #eigen_min = min(eigenvalues) #print "max and min of eigenvalues of Hessian matrix are " + str(eigen_max) + ", " + str(eigen_min) #if (abs(eigen_max) > 1.0e-3 and abs(eigen_min) > 1.0e-3): #if False: # solution = np.linalg.inv(-Jacobian).dot(function) #else: # solution = conjugateGradient.conjugateGradient(-Jacobian, function) solution = np.linalg.solve(-Jacobian, function) #error = np.linalg.norm(solution) error = np.linalg.norm(function) #print "counter = ", counter, ", norm of gradient = ", np.linalg.norm(function) #, ", error = ", error #print "counter = ", counter, ", error = ", error, ", det of Hessian matrix = ", det, ", norm of gradient = ", np.linalg.norm(function) if (error < eps): break A_updated = A_initial + solution for i in range(len(A_updated)): if (A_updated[i] < 0): A_updated[i] = 1.0e-10 A_initial = A_updated return A_initial
def solver(alpha, G_real_rotated, G_imag_rotated, K_real_rotated, K_imag_rotated, omega, A_initial, D, LambdaInverse): eps = 1.0e-5 counter = 0 iterationMax = 20 while(True): counter = counter + 1 if (counter > iterationMax): break Jacobian = J.J(alpha, A_initial, omega, K_real_rotated, K_imag_rotated, LambdaInverse) function = f.f(alpha, G_real_rotated, G_imag_rotated, K_real_rotated, K_imag_rotated, A_initial, D, omega, LambdaInverse) #solution = conjugateGradient.conjugateGradient(-Jacobian, function) solution = np.linalg.inv(-Jacobian).dot(function) error = conjugateGradient.norm(solution) print "counter = ", counter, ", error = ", error if (error < eps): break A_updated = A_initial + solution for i in range(len(A_updated)): if (A_updated[i] < 0): A_updated[i] = 1.0e-10 A_initial = A_updated return A_initial
def kronrod_test03 ( ): #*****************************************************************************80 # ## KRONROD_TEST03 uses the program to estimate an integral. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 30 April 2013 # # Author: # # John Burkardt # from f import f from kronrod import kronrod exact = 1.5643964440690497731 print '' print 'KRONROD_TEST03' print ' Call Kronrod to estimate the integral of a function.' print ' Keep trying until the error is small.' # # TOL just tells KRONROD how carefully it must compute X, W1 and W2. # It is NOT a statement about the accuracy of your integral estimate! # tol = 0.000001 # # Start the process with a 1 point rule. # n = 1 while ( 1 ): [ x, w1, w2 ] = kronrod ( n, tol ) # # Compute the estimates. # There are two complications here: # # 1) Both rules use all the points. However, the lower order rule uses # a zero weight for the points it doesn't need. # # 2) The points X are all positive, and are listed in descending order. # this means that 0 is always in the list, and always occurs as the # last member. Therefore, the integral estimates should use the # function value at 0 once, and the function values at the other # X values "twice", that is, once at X and once at -X. # i1 = w1[n+1-1] * f ( x[n+1-1] ) i2 = w2[n+1-1] * f ( x[n+1-1] ) for i in range ( 1, n + 1 ): i1 = i1 + w1[i-1] * ( f ( - x[i-1] ) + f ( x[i-1] ) ) i2 = i2 + w2[i-1] * ( f ( - x[i-1] ) + f ( x[i-1] ) ) if ( abs ( i1 - i2 ) < 0.0001 ): print '' print ' Error tolerance satisfied with N = %d' % ( n ) print ' Coarse integral estimate = %14.6g' % ( i1 ) print ' Fine integral estimate = %14.6g' % ( i2 ) print ' Error estimate = %g' % ( abs ( i2 - i1 ) ) print ' Actual error = %g' % ( abs ( exact - i2 ) ) break if ( 25 < n ): print '' print ' Error tolerance failed even for n = %d' % ( n ) print ' Canceling iteration, and accepting bad estimates!' print ' Coarse integral estimate = %14.6g' % ( i1 ) print ' Fine integral estimate = %14.6g' % ( i2 ) print ' Error estimate = %g' % ( abs ( i2 - i1 ) ) print ' Actual error = %g' % ( abs ( exact - i2 ) ) break n = 2 * n + 1 return
def test_assertOdd(): assert f() % 2 == 0, "value was odd, should be even"
def main(): import os import sys import numpy as np import numpy.linalg if (len(sys.argv) == 1): print "a0 = sys.argv[1], b0 = sys.argv[2]. alpha = a0*exp(-i*b0). " return -1 if (len(sys.argv) == 2): a0 = float(sys.argv[1]) b0 = 0.05 if (len(sys.argv) == 3): a0 = float(sys.argv[1]) b0 = float(sys.argv[2]) Greal = "G_cc_real.txt" Gimag = "G_cc_imag.txt" omega_n, G_real, G_imag = readFiles(Greal, Gimag) Niom = len(omega_n) N = 101 omega_lower = -8 omega_upper = -omega_lower domega = (omega_upper - omega_lower) / float(N) omega = np.zeros(N + 1) for i in range(N + 1): omega[i] = omega_lower + i * domega Nomega = len(omega) A_initial = np.zeros(Nomega) model = np.zeros(Nomega) for i in range(Nomega): model[i] = default.D(omega[i]) printFile.printFile(omega, model, "model.txt") if (not os.path.exists("A_initial.txt")): for i in range(len(A_initial)): A_initial[i] = default.D(omega[i]) printFile.printFile(omega, A_initial, "A_initial.txt") else: omega, A_initial = read_spectral("A_initial.txt") Nomega = len(omega) C_real = np.zeros((Niom, Niom)) C_imag = np.zeros((Niom, Niom)) ifile = open("CM_cc_real.txt", "r") for (index, string) in enumerate(ifile): a = string.split() rowIndex = int(a[0]) - 1 colIndex = int(a[1]) - 1 if (True): C_real[rowIndex, colIndex] = float(a[2]) ifile.close() ifile = open("CM_cc_imag.txt", "r") for (index, string) in enumerate(ifile): a = string.split() rowIndex = int(a[0]) - 1 colIndex = int(a[1]) - 1 if (True): C_imag[rowIndex, colIndex] = float(a[2]) ifile.close() eig = 0.01 ofile = open("eig.txt", "w") ofile.write(str(eig) + "\n") ofile.close() for i in range(Niom): C_real[i, i] = eig**2 C_imag[i, i] = eig**2 C_real_inv = numpy.linalg.inv(C_real) C_imag_inv = numpy.linalg.inv(C_imag) printFile.printMatrix(C_real_inv, "C_real_inv.txt") if (False): alpha = 1.0 function = f.f(alpha, G_real, G_imag, A_initial, omega_n, omega, C_real_inv, C_imag_inv) Jacobian = J.J(alpha, A_initial, omega_n, omega, C_real_inv, C_imag_inv) print function printFile.printMatrix(Jacobian, "J.txt") return 0 if (True): alpha = [] for i in range(30): alpha.append(a0 * np.exp(-i * b0)) ofile = open("alpha.txt", "a") for i in range(len(alpha)): A_updated = newton.newton(alpha[i], G_real, G_imag, omega_n, omega, A_initial, C_real_inv, C_imag_inv) if (nan.array_isnan(A_updated)): omega, A_initial = read_spectral("A_initial.txt") continue output = "A_updated_alpha_" + str(alpha[i]) + ".txt" printFile.printFile(omega, A_updated, output) os.system("cp " + output + " A_initial.txt") ofile.write(str(alpha[i]) + "\n") print "alpha = ", alpha[i] A_initial = A_updated ofile.close() else: alpha = 0.01 print "alpha = ", alpha A_updated = newton(alpha, G, omega_n, omega, A_initial, C_real_inv, C_imag_inv) if (nan.array_isnan(A_updated)): printFile.printFile(omega, A_updated, "A_updated_alpha_" + str(alpha) + ".txt") os.system("cp A_updated_alpha_" + str(alpha) + ".txt" + "A_initial.txt") return 0
def run(): return f()
def test_function(): assert f() == 4
pass print("10 - Уточнить дополнительные функции.\n0 - EXIT") ch = input() try: ch = int(ch) except: ch = 35 if (ch == 1): print("Введите имя карты.") name = input() elif (ch == 2): print("Введите описание карты.") descrpition = input() elif (ch == 3): import f func[numm] = f.f() elif (ch == 4): types = [TYPEE] types.extend(TYPE(TYPEE)) types = tuple(types) elif (ch == 5): if (TYPEE == "TREASURE"): if (name) and (descrpition) and (func) and ( len(types) >= 2) and (fpath) and (bpath): card = Card(name, descrpition, types, power=func, cost=cost, image=(fpath, bpath), play=time)
import matplotlib import matplotlib.pyplot as plt import numpy as np import rsg import f import additionalTask as at n = 12 W = 2400 N = 1024 time = range(N) signal = rsg.getRandomSignal(n, W, N) s = f.f(signal) my, nump = at.compareTime(n, W, N) print("my fft: ", my, ", numpy fft: ", nump) fig, (ax1, ax2) = plt.subplots(2, 1) fig.suptitle('Lab 2.2') ax1.plot(signal, linewidth=0.8) ax1.set_title('Generated signal') ax1.set(xlabel='time', ylabel='generated signal') ax2.plot(s, color='r', linewidth=0.8) ax2.set_title('Fast Fourier transform') ax2.set(xlabel='p', ylabel='F(p)') fig.savefig("lab2.2.png") plt.show()