def LLL(l_basis): ortho = [vector(i) for i in gram_schmidt(l_basis)] k = 1 n = len(ortho) while k < n: for j in range(k - 1, -1, -1): proj = mu(l_basis[k], ortho[j]) if abs(proj) > 1 / 2: l_basis[k] = l_basis[k] - l_basis[j] * round(proj) ortho = gram_schmidt(l_basis) if ortho[k].dot_product( ortho[k]) >= (d - mu(l_basis[k], ortho[k - 1])**2) * ( ortho[k - 1].dot_product(ortho[k - 1])): k += 1 else: l_basis[k], l_basis[k - 1] = l_basis[k - 1], l_basis[k] ortho = gram_schmidt(l_basis) k = max(k - 1, 1) return l_basis
def qr(mat: np.ndarray): # (n, m) Q = gram_schmidt.gram_schmidt(mat) # (n, k) -> Q.T: (k, n) R = np.dot(Q.T, mat) # (k, n) . (n, m): (k, m) return Q, R
def periodogram(t, x, freq): """Returns the Lomb-Scargle periodogram of the data x(t) at frequency freq.""" R = np.zeros((t.size, 2)) R[:, 0] = np.cos(2. * np.pi * freq * t) R[:, 1] = np.sin(2. * np.pi * freq * t) Q = gram_schmidt(R) myperiodogram = np.dot(Q[:, 0], x)**2 + np.dot(Q[:, 1], x)**2 return myperiodogram
def __init__(self, inputs, output, lrmul): super(MappingBlock, self).__init__() with torch.no_grad(): self.fc = ln.Linear(inputs, output, lrmul=lrmul) self.fc.weight.data = self.fc.weight.data.double() self.fc.weight.data = gram_schmidt(self.fc.weight.data) self.fc.bias.data = self.fc.bias.data.double() self.i_fc = ln.Linear(output, inputs, lrmul=lrmul) self.last_activation = None self.alpha = 0.2
def tapered_periodogram(t, x, freq, mywindow): """Returns the Lomb-Scargle periodogram of the data x(t) at frequency freq.""" R = np.zeros((t.size, 2)) taper = tapering_window(t, t[-1] - t[0], mywindow) R[:, 0] = taper * np.cos(2. * np.pi * freq * t) R[:, 1] = taper * np.sin(2. * np.pi * freq * t) Q = gram_schmidt(R) myperiodogram = np.dot(Q[:, 0], x)**2 + np.dot(Q[:, 1], x)**2 return myperiodogram
def periodogram_grid_fixed(t, freq): R = np.zeros((t.size, 2)) R[:, 0] = np.cos(2. * np.pi * freq * t) R[:, 1] = np.sin(2. * np.pi * freq * t) Q = gram_schmidt(R) #mycos2=Q[:,0] #mysin2=Q[:,1] #myperiodogram=np.dot(mycos2,x)**2+np.dot(mysin2,x)**2 return Q
def tapered_periodogram_grid_fixed(t,freq,mywindow): R=np.zeros((t.size,2)) taper=tapering_window(t,t[-1]-t[0],mywindow) R[:,0]=taper*np.cos(2.*np.pi*freq*t) R[:,1]=taper*np.sin(2.*np.pi*freq*t) Q=gram_schmidt(R) #mycos2=Q[:,0] #mysin2=Q[:,1] #myperiodogram=np.dot(mycos2,x)**2+np.dot(mysin2,x)**2 return Q
def image_training_pca(): trained = Path(trained_path) if (trained.is_file()): print('Loaded {}'.format(trained_path)) return np.loadtxt(trained_path) #TRAINING SET images = np.zeros([trnno, areasize]) person = np.zeros([trnno, 1]) imno = 0 per = 0 #Iterate over image person folders for dire in onlydirs: #Iterate over image files for k in range(1, trnperper + 1): #Pixel matrix a = plt.imread(mypath + dire + '/{}'.format(k) + '.pgm') / 255.0 #Reshape to vector for insertion in 'images' images[imno, :] = np.reshape(a, [1, areasize]) person[imno, 0] = dire.split('s')[1] imno += 1 per += 1 #CARA MEDIA #Mean for pixel i using 'images' columns meanimage = np.mean(images, 0) #resto la media images = [images[k, :] - meanimage for k in range(images.shape[0])] A = np.transpose(images) n, m = A.shape L = np.dot(images, A) #A = np.array([[60., 30., 20.], [30., 20., 15.], [20., 15., 12.]]) last_R = np.zeros(A.shape) eig_vec_L = 1 found_eigen = False while not found_eigen: Q, R = gram_schmidt(L) L = np.dot(R, Q) eig_vec_L = np.dot(eig_vec_L, Q) found_eigen = cmp_eigen(last_R, R) last_R = R eig_vec_C = np.dot(A, eig_vec_L) for i in range(m): eig_vec_C[:, i] /= np.linalg.norm(eig_vec_C[:, i]) np.savetxt(trained_path, eig_vec_C, fmt='%s') return eig_vec_C
def problem(): #Initialize parameters of the problem m = 15 n = 100 c = 2006.787453080206 #Initilize matrix A and vector b b = empty(n) A = empty((n, m)) #Calculate A and b according to the parameters i = 0 while i < n: A[i, 0] = 1 A[i, 1] = i / (n - 1) j = 2 while j < m: A[i, j] = power(A[i, 1], j) j = j + 1 b[i] = (1 / c) * exp(sin(4 * A[i, 1])) i = i + 1 print('Matrix A:') print(A) print('\nVector b:') print(b) #Calculate x by solving the least squares problem using the normal equations #NOTE: This won't execute because A is very ill conditioned (det ~= 1E-90) #ne_x = normal_equations(A, b) #print(ne_x) #Calculate x by solving the least squares problem using the Householder tranformations h_x = householder(A, b) print('\nValue of x using Householder:') print(h_x) #Calculate x by solving the least squares problem using the Gram-Schmidt gs_x = gram_schmidt(A, b) print('\nValue of x using Gram-Schmidt:') print(gs_x) #Calculate x by solving the least squares problem using the modified Gram-Schmidt mgs_x = modified_gram_schmidt(A, b) print('\nValue of x using modified Gram-Schmidt:') print(mgs_x) #Calculate x by solving the least squares problem using the SVD decomposition (pseudoinverse) svd_x = svd(A, b) print('\nValue of x using the SVD decomposition (pseudoinverse):') print(svd_x)
def __init__(self, inputs, output, lrmul): super(MappingBlock, self).__init__() with torch.no_grad(): self.fc = ln.Linear(inputs, output, lrmul=lrmul) self.fc.weight.data = self.fc.weight.data.double() # print("Before", torch.norm(self.fc.weight)) self.fc.weight.data = self.fc.weight.data * 0.9 + gram_schmidt( self.fc.weight.data) * 0.1 # print("After", torch.norm(self.fc.weight)) self.fc.bias.data = self.fc.bias.data.double() self.i_fc = ln.Linear(output, inputs, lrmul=lrmul) self.last_activation = None self.alpha = 0.2
def main(): """Script starts here.""" sampling_size = 20000 locations = mu.getlocationofdata() print(locations.__dict__) originscsvs = mu.readlistoffiles(locations.originfiles) filterdcsvs = mu.readlistoffiles(locations.filteredfiles) m_origin = mu.create_matrix_from_filelist(originscsvs, sampling_size) m_filtered = mu.create_matrix_from_filelist(filterdcsvs, sampling_size) q_origin, r_origin = gs.gram_schmidt(m_origin) print(q_origin.shape, r_origin.shape) r_filtered = np.dot(q_origin.T, m_filtered) print("r_filtered:", r_filtered.shape) print("r_origin:", r_origin.shape) for colume in r_origin.T: answer = __find_best_match(colume, r_filtered) print("found:", answer)
def WOSA_matrix(t, freq, beta, D): """Returns the Lomb-Scargle+WOSA periodogram of the data x(t) at frequency freq.""" Q = int(np.floor((t.size - D) / (1. - beta) / float(D))) + 1 weight = np.zeros(t.size) R = np.zeros((t.size, 2)) M2 = np.zeros((t.size, 2 * Q)) myfact = int((1. - beta) * float(D)) for k in range(Q): weight[:] = 0. weight[(k - 1) * myfact:(k - 1) * myfact + D] = 1. R[:, 0] = weight * np.cos(2. * np.pi * freq * t) R[:, 1] = weight * np.sin(2. * np.pi * freq * t) Y = gram_schmidt(R) M2[:, 2 * k] = Y[:, 0] M2[:, 2 * k + 1] = Y[:, 1] M2 /= np.sqrt(float(Q)) return M2
def WOSA_periodogram(t, x, freq, beta, D): """Returns the Lomb-Scargle+WOSA periodogram of the data x(t) at frequency freq.""" Q = int(np.floor((t.size - D) / (1. - beta) / float(D))) + 1 #weight=np.zeros(t.size) R = np.zeros((t.size, 2)) myperiodogram = 0. myfact = int((1. - beta) * float(D)) for k in range(Q): #weight[:]=0. #weight[k*myfact:k*myfact+D]=1. R[:, 0] = weight * np.cos(2. * np.pi * freq * t) R[:, 1] = weight * np.sin(2. * np.pi * freq * t) Y = gram_schmidt(R) mycos2 = Y[:, 0] mysin2 = Y[:, 1] myperiodogram += np.dot(mycos2, x)**2 + np.dot(mysin2, x)**2 myperiodogram /= float(Q) return myperiodogram
def WOSA_periodogram_grid_fixed(t, freq, beta, D, mywindow): # !!! D = nombre de points - c'est un nombre entier! D = int(D) Q = int(np.floor(float(t.size - D) / (1. - beta) / float(D))) + 1 weight = np.zeros(t.size) R = np.zeros((t.size, 2)) myfact = int((1. - beta) * float(D)) W = np.zeros((t.size, 2 * Q)) for k in range(Q): weight[:] = 0. weight[k * myfact:k * myfact + D] = tapering_window( t[k * myfact:k * myfact + D], t[k * myfact + D - 1] - t[k * myfact], mywindow) R[:, 0] = weight * np.cos(2. * np.pi * freq * t) R[:, 1] = weight * np.sin(2. * np.pi * freq * t) Y = gram_schmidt(R) W[:, 2 * k] = Y[:, 0] W[:, 2 * k + 1] = Y[:, 1] #myperiodogram+=np.dot(mycos2,x)**2+np.dot(mysin2,x)**2 #myperiodogram/=float(Q) return W
def vibrational_analysis(file_name): nr_atoms = gaussian.get_nr_atoms(file_name) atom_xyz = gaussian.get_atom_coordinates(file_name, nr_atoms) atom_mass = gaussian.get_atom_masses(file_name, nr_atoms) # construct inertia tensor I = numpy.zeros((3, 3)) for i in range(nr_atoms): m = atom_mass[i] x = atom_xyz[i][0] y = atom_xyz[i][1] z = atom_xyz[i][2] I[0][0] += m*(y*y + z*z) I[1][1] += m*(z*z + x*x) I[2][2] += m*(x*x + y*y) I[0][1] -= m*(x*y) I[1][0] -= m*(x*y) I[0][2] -= m*(x*z) I[2][0] -= m*(x*z) I[1][2] -= m*(y*z) I[2][1] -= m*(y*z) # diagonalize eig, X = numpy.linalg.eig(I) # minus sign to match gaussian X *= -1.0 # construct B vectors 1-6 B = numpy.zeros((6, nr_atoms*3)) A = numpy.zeros(3) k = 0 for i in range(nr_atoms): m = numpy.sqrt(atom_mass[i]) B[0][k+0] = 1.0 B[1][k+1] = 1.0 B[2][k+2] = 1.0 # B[3][k+1] = -atom_xyz[i][2] # B[3][k+2] = atom_xyz[i][1] # B[4][k+0] = atom_xyz[i][2] # B[4][k+2] = -atom_xyz[i][0] # B[5][k+0] = -atom_xyz[i][1] # B[5][k+1] = atom_xyz[i][0] # k += 3 for j in range(3): A[j] = atom_xyz[i][0]*X[0][j] + atom_xyz[i][1]*X[1][j] + atom_xyz[i][2]*X[2][j] for j in range(3): B[3][k] = (A[1]*X[j][2] - A[2]*X[j][1]) B[4][k] = (A[2]*X[j][0] - A[0]*X[j][2]) B[5][k] = (A[0]*X[j][1] - A[1]*X[j][0]) k += 1 # construct matrix of reciprocal mass square roots M = numpy.zeros((nr_atoms*3, nr_atoms*3)) k = 0 for iatom in range(nr_atoms): for ixyz in range(3): M[k][k] = 1.0/numpy.sqrt(atom_mass[iatom]) k += 1 # orthonormalize vectors B = gram_schmidt.gram_schmidt(B, 6) # construct projection matrix P = numpy.eye(nr_atoms*3) - numpy.array(numpy.mat(numpy.transpose(B))*numpy.mat(B)) # read hessian H = gaussian.get_hessian(file_name, nr_atoms) # project out trans-rot H_proj = numpy.array(numpy.mat(numpy.transpose(P))*(numpy.mat(H)*numpy.mat(P))) H_mwc = numpy.array(numpy.mat(M)*(numpy.mat(H_proj)*numpy.mat(M))) freq, L = numpy.linalg.eig(H_mwc) C = numpy.array(numpy.transpose(L)*numpy.mat(M)) reduced_mass = numpy.zeros(nr_atoms*3 - 6) for m in range(nr_atoms*3 - 6): reduced_mass[m] = 1.0/numpy.dot(C[m], C[m]) T = gaussian.get_dipole_derv(file_name, nr_atoms) dip_derv = numpy.array(numpy.mat(C)*numpy.mat(numpy.transpose(T))) I = numpy.zeros(nr_atoms*3 - 6) freq_cm = numpy.zeros(nr_atoms*3 - 6) for m in range(nr_atoms*3 - 6): I[m] = conf.au_to_kmmol*numpy.dot(dip_derv[m], dip_derv[m]) freq_cm[m] = conf.hartree_to_cm*numpy.sqrt(abs(freq[m])/conf.amu_to_au) C_normalized = numpy.zeros((nr_atoms*3 - 6, nr_atoms, 3)) for m in range(nr_atoms*3 - 6): k = 0 for iatom in range(nr_atoms): for ixyz in range(3): C_normalized[m][iatom][ixyz] = C[m][k]*reduced_mass[m]**0.5 k += 1 sort_list = [] for m in range(nr_atoms*3 - 6): sort_list.append([freq_cm[m], m]) sort_list.sort() freq_cm_sorted = numpy.zeros(nr_atoms*3 - 6) I_sorted = numpy.zeros(nr_atoms*3 - 6) reduced_mass_sorted = numpy.zeros(nr_atoms*3 - 6) C_normalized_sorted = numpy.zeros((nr_atoms*3 - 6, nr_atoms, 3)) dip_derv_sorted = numpy.zeros((nr_atoms*3 - 6, 3)) k = 0 for s in sort_list: m = s[1] freq_cm_sorted[k] = freq_cm[m] I_sorted[k] = I[m] reduced_mass_sorted[k] = reduced_mass[m] C_normalized_sorted[k] = C_normalized[m] dip_derv_sorted[k] = dip_derv[m] k += 1 return freq_cm_sorted, I_sorted, reduced_mass_sorted, C_normalized_sorted, dip_derv_sorted
for j in range(3): B[3][k] = (A[1] * X[j][2] - A[2] * X[j][1]) B[4][k] = (A[2] * X[j][0] - A[0] * X[j][2]) B[5][k] = (A[0] * X[j][1] - A[1] * X[j][0]) k += 1 # construct matrix of reciprocal mass square roots M = numpy.zeros((nr_atoms * 3, nr_atoms * 3)) k = 0 for iatom in range(nr_atoms): for ixyz in range(3): M[k][k] = 1.0 / numpy.sqrt(atom_mass[iatom]) k += 1 # orthonormalize vectors B = gram_schmidt.gram_schmidt(B, 6) # construct projection matrix P = numpy.eye(nr_atoms * 3) - numpy.array( numpy.mat(numpy.transpose(B)) * numpy.mat(B)) # read hessian H = numpy.zeros((nr_atoms * 3, nr_atoms * 3)) for line in open('molecular_hessian', 'r').readlines(): i = int(line.split()[0]) j = int(line.split()[1]) f = float(line.split()[2]) H[i][j] = f # symmetrize it fully for i in range(nr_atoms * 3):
for j in range(3): B[3][k] = (A[1]*X[j][2] - A[2]*X[j][1]) B[4][k] = (A[2]*X[j][0] - A[0]*X[j][2]) B[5][k] = (A[0]*X[j][1] - A[1]*X[j][0]) k += 1 # construct matrix of reciprocal mass square roots M = numpy.zeros((nr_atoms*3, nr_atoms*3)) k = 0 for iatom in range(nr_atoms): for ixyz in range(3): M[k][k] = 1.0/numpy.sqrt(atom_mass[iatom]) k += 1 # orthonormalize vectors B = gram_schmidt.gram_schmidt(B, 6) # construct projection matrix P = numpy.eye(nr_atoms*3) - numpy.array(numpy.mat(numpy.transpose(B))*numpy.mat(B)) # read hessian H = numpy.zeros((nr_atoms*3, nr_atoms*3)) for line in open('molecular_hessian', 'r').readlines(): i = int(line.split()[0]) j = int(line.split()[1]) f = float(line.split()[2]) H[i][j] = f # symmetrize it fully for i in range(nr_atoms*3): for j in range(nr_atoms*3):