def check_simple(self): a = [[1, 2], [3, 4]] a_inv = inv(a) assert_array_almost_equal(numpy.dot(a, a_inv), [[1, 0], [0, 1]]) a = [[1, 2, 3], [4, 5, 6], [7, 8, 10]] a_inv = inv(a) assert_array_almost_equal(numpy.dot(a, a_inv), [[1, 0, 0], [0, 1, 0], [0, 0, 1]])
def check_random_complex(self): n = 20 for i in range(4): a = random([n, n]) + 2j * random([n, n]) for i in range(n): a[i, i] = 20 * (0.1 + a[i, i]) a_inv = inv(a) assert_array_almost_equal(numpy.dot(a, a_inv), numpy.identity(n))
def check_nils_20Feb04(self): n = 2 A = random([n, n]) + random([n, n]) * 1j X = zeros((n, n), "D") Ainv = inv(A) R = identity(n) + identity(n) * 0j for i in arange(0, n): r = R[:, i] X[:, i] = solve(A, r) assert_array_almost_equal(X, Ainv)
def lu_check_consistency(): """ A test for the LU inversion solver. Returns ------- passed : bool If the LU-inverter is self-consistent. """ print("\n\nTest: LU inversion Self Consistency") # random diagonal matrix is known to be invertible diag = np.random.randint(1, 30, 30) * np.random.choice([-1, 1]) mat = np.diag(diag) inv = linalg.inv(linalg.lu_solve, mat) # check for differences in error and value id_guess = inv.dot(mat) e = np.abs(np.identity(30) - id_guess) passed = np.all(e < 1e-7) print("Passed {}".format(passed)) return passed
>>> A = np.array([[1,2],[3,4]]) >>> a [48, 45, 42, 39, 36, 33, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, '3k'] >>> A array([[1, 2], [3, 4]]) >>> A.T array([[1, 3], [2, 4]]) >>> from scipy import linalg Traceback (most recent call last): File "<pyshell#179>", line 1, in <module> from scipy import linalg ModuleNotFoundError: No module named 'scipy' >>> from scipy import linalg >>> B = linalg.inv(A) >>> B array([[-2. , 1. ], [ 1.5, -0.5]]) >>> A.dot(B) array([[1.0000000e+00, 0.0000000e+00], [8.8817842e-16, 1.0000000e+00]]) >>> import functools >>> import pandas SyntaxError: unexpected indent >>> import pandas Traceback (most recent call last): File "<pyshell#186>", line 1, in <module> import pandas ModuleNotFoundError: No module named 'pandas'
def __new__(subtype, eval_fun, base_mesh, obs_mesh, obs_taus, withsigma = False, withtau = False, lintrans = None, **params): # You may need to reshape these so f2py doesn't puke. subtype.base_mesh = base_mesh subtype.obs_mesh = obs_mesh subtype.obs_taus = obs_taus subtype.withsigma = withsigma subtype.withtau = withtau subtype.lintrans = lintrans subtype.params = params subtype.eval_fun = eval_fun # Call the covariance evaluation function length = (base_mesh.shape)[0] subtype.data = zeros((length,length), dtype=float) eval_fun(subtype.data, base_mesh, base_mesh, symm=True, **params) # Condition condition(subtype.data, eval_fun, base_mesh, obs_mesh, **params) if withsigma: # Try Cholesky factorization try: subtype.sigma = cholesky(subtype.data) # If there's a small eigenvalue, diagonalize except linalg.linalg.LinAlgError: subtype.eigval, subtype.eigvec = eigh(subtype.data) subtype.sigma = subtype.eigvec * sqrt(subtype.eigval) if withtau: # Make this faster. subtype.tau = inv(subtype.data) # Return the data return subtype.data.view(subtype) def __array__(self): return self.data def __call__(self, point_1, point_2): value = zeros((1,1),dtype=float) # Evaluate the covariance self.eval_fun(value,point_1,point_2,**self.params) if not obs_mesh: return value[0,0] # Condition on the observed values nobs = shape(obs_mesh)[0] ndim = shape(obs_mesh)[1] Q = zeros((1,1),dtype=float) RF = zeros((2,1),dtype=float) base_mesh = vstack([point_1,point_2]) for i in range(len(obs_mesh)): om_now = reshape(obs_mesh[i,:],(1,ndim)) eval_fun(Q,om_now,om_now,**params) eval_fun(RF,base_mesh,om_now,**params) value -= RF[0]*RF[1]/Q return value[0,0]
def check_simple_complex(self): a = [[1, 2], [3, 4j]] a_inv = inv(a) assert_array_almost_equal(numpy.dot(a, a_inv), [[1, 0], [0, 1]])
def solve(self, err, init_temp=0, verbose=False, show=False, kp_linalg=False, cds=False): """ The iterative method for solving the heat equation across the system with the relaxation method. Convergence criterion is the updating step across the area of the system with material 1 (processor). 200 additional iterations ensure robustness against extrema due to overshooting. Initial temperatures can improve convergence if the guess is good. Parameters ---------- err : float The mean temperature difference across processor between two iterations which is considered sufficient for convergence. init_temp : float, optional The temperature to which the non-air components are initialised. The default is 0. verbose : bool, optional If True, print status every 100 iterations. The default is False. show : bool, optional If True, plot system temp after solving. The default is False. kp_linalg: bool, optional If karim's python linear algebra should be used. The default is False. cds: bool, optional, DEPRECATED(Not Recommended, see report) If the central difference scheme should be used instead of the forward difference scheme. The default is False. Returns ------- float. The mean steady-state temperature across the processor. """ # ===================================================================== # For this method it is fastest to first invert the matrix, as the # same matrix is always used over and over again. # ===================================================================== if kp_linalg: # manually implemented solver, uses LU-decomposition and inversion self.inv = linalg.inv(linalg.jac_solve, self.mat) else: # exact numpy inversion self.inv = np.linalg.inv(self.mat) # keep a copy of temperature to use as convergence reference t_0 = self.temp # initial temperatures improve convergence in some cases for i in self.map: self.temp[i] = init_temp # initialise one higher to start iterating t_1 = t_0 + 1 i = 0 j = 0 # use to prevent convergence to an extremum # get the initial error e = np.mean(np.abs(t_1[self.core] - t_0[self.core])) start_time = t.time() # even if updating error low, keep going for 200 iters to avoid # convergence while j < 200: # keep copies and update temperature t_0 = np.copy(t_1) self.update_temp(cds) t_1 = self.temp i += 1 # get error e = np.mean(np.abs(t_1[self.core] - t_0[self.core])) # user output every 100 iterations as this iterates A LOT if verbose and i % 100 == 0: print("Iteration: {} \t Updating/Error: {} \t Max Temp: {}". format(i, round(e, 3), round(np.max(t_0) + 20, 3))) # start counting up j once error threshold is reached if e < err: j += 1 # if we do diverge again, reset j to 0 else: j = 0 # calculations done in relative temperature, results returned in °C self.temp += 20 # Return to °C dt = t.time() - start_time # show heat map if required if show: self.show(err) print("\n\nRuntime: {} / Iterations: {} / Time/Iteration: {} \ \nFinal Processor Temp: {} / Final Updating Error: {}".format( dt, i, dt / i, np.mean(self.temp[self.core]), e)) return np.mean(self.temp[self.core])