def test_al_mohy_higham_2012_experiment_1_funm_log(self): # The raw funm with np.log does not complete the round trip. # Note that the expm leg of the round trip is badly conditioned. A = _get_al_mohy_higham_2012_experiment_1() A_funm_log, info = funm(A, np.log, disp=False) A_round_trip = expm(A_funm_log) assert_(not np.allclose(A_round_trip, A, rtol=1e-5, atol=1e-14))
def __init__(self,mol,mints): mult = mol.multiplicity() nelec = get_nelec(mol) self.conv = get_conv() self.Na = int( 0.5*(nelec+mult-1) ) self.Nb = nelec - self.Na V = np.array( mints.ao_potential() ) T = np.array( mints.ao_kinetic() ) G = np.array( mints.ao_eri() ) self.S = np.array( mints.ao_overlap() ) self.Hcore = T + V self.G = G.transpose((0,2,1,3)) self.X = np.matrix( la.funm(self.S, lambda x : x**(-0.5) ) ) self.Vnu = mol.nuclear_repulsion_energy() ## alpha and beta density matrices self.Da = np.random.rand(*self.X.shape) self.Da = self.Da + self.Da.T self.Db = np.random.rand(*self.X.shape) self.Db = self.Db + self.Db.T self.E = 0.0
def angs(self): """ return the geometry in Angstroms """ if self.units == "Bohr": self.geom = la.funm(self.geom, lambda x : x/1.889725989).round(15) self.units = "Angstrom" return self.geom
def bohr(self): """ return the geometry in bohr """ if self.units == "Angstrom": self.geom = la.funm(self.geom, lambda x : x* 1.889725989).round(15) self.units == "Bohr" return self.geom
def get_occupations(self): T = np.matrix( la.funm( self.S, lambda x: x**0.5 ) ) n, tC = la.eigh(T*(self.Da+self.Db)*T) self.occ = sorted(n,reverse=True) print("\nUHF Natural Orbital Occupations") for i,j in enumerate(self.occ): print("{:2} {:>21.7}".format(i,j.round(8)) ) return self.occ
def test_al_mohy_higham_2012_experiment_1(self): # Fractional powers of a tricky upper triangular matrix. A = _get_al_mohy_higham_2012_experiment_1() # Test remainder matrix power. A_funm_sqrt, info = funm(A, np.sqrt, disp=False) A_sqrtm, info = sqrtm(A, disp=False) A_rem_power = _matfuncs_inv_ssq._remainder_matrix_power(A, 0.5) A_power = fractional_matrix_power(A, 0.5) assert_array_equal(A_rem_power, A_power) assert_allclose(A_sqrtm, A_power) assert_allclose(A_sqrtm, A_funm_sqrt) # Test more fractional powers. for p in (1/2, 5/3): A_power = fractional_matrix_power(A, p) A_round_trip = fractional_matrix_power(A_power, 1/p) assert_allclose(A_round_trip, A, rtol=1e-2) assert_allclose(np.tril(A_round_trip, 1), np.tril(A, 1))
def __init__(self,mol,mints): """ initialize rhf class takes objects: 1. mol: a psi4 molecule, get_active_molecule() 2. mints: molecular integrals from libmints in psi4 """ self.docc = get_docc(mol) self.nbf = get_nbf(mints) self.conv = get_conv() self.maxiter = get_maxiter() self.S = np.matrix(mints.ao_overlap() ) self.X = np.matrix(la.funm(self.S,lambda x : x**(-0.5))) self.T = np.matrix(mints.ao_kinetic() ) self.V = np.matrix(mints.ao_potential() ) self.H = self.T+self.V self.G = np.array(mints.ao_eri() ).swapaxes(1,2) self.D = np.zeros((self.nbf,self.nbf)) self.Vnu = mol.nuclear_repulsion_energy() self.E = 0
def test_cosfunction(self): '''Test routines to compute the matrix cosine.''' from scipy.linalg import funm from numpy import cos # Starting Matrix matrix1 = self.create_matrix() self.write_matrix(matrix1, self.input_file) # Check Matrix dense_check = funm(matrix1.todense(), lambda x: cos(x)) self.CheckMat = csr_matrix(dense_check) # Result Matrix input_matrix = nt.Matrix_ps(self.input_file, False) cos_matrix = nt.Matrix_ps(self.mat_dim) permutation = nt.Permutation(input_matrix.GetLogicalDimension()) permutation.SetRandomPermutation() self.fsp.SetLoadBalance(permutation) nt.TrigonometrySolvers.Cosine(input_matrix, cos_matrix, self.fsp) cos_matrix.WriteToMatrixMarket(result_file) comm.barrier() self.check_result()
def test_squareroot(self): '''Test routines to compute the square root of matrices.''' from scipy.linalg import funm from numpy import sqrt # Starting Matrix. Care taken to make sure eigenvalues are positive. matrix1 = self.create_matrix(SPD=True) self.write_matrix(matrix1, self.input_file) # Check Matrix dense_check = funm(matrix1.todense(), lambda x: sqrt(x)) self.CheckMat = csr_matrix(dense_check) # Result Matrix input_matrix = nt.Matrix_ps(self.input_file, False) root_matrix = nt.Matrix_ps(self.mat_dim) permutation = nt.Permutation(input_matrix.GetLogicalDimension()) permutation.SetRandomPermutation() self.isp.SetLoadBalance(permutation) nt.SquareRootSolvers.SquareRoot(input_matrix, root_matrix, self.isp) root_matrix.WriteToMatrixMarket(result_file) comm.barrier() self.check_result()
def test_exponentialfunction(self): '''Test routines to compute the matrix exponential.''' from scipy.linalg import funm from numpy import exp # Starting Matrix matrix1 = 8 * self.create_matrix(scaled=True) self.write_matrix(matrix1, self.input_file) # Check Matrix dense_check = funm(matrix1.todense(), lambda x: exp(x)) self.CheckMat = csr_matrix(dense_check) # Result Matrix input_matrix = nt.Matrix_ps(self.input_file, False) exp_matrix = nt.Matrix_ps(self.mat_dim) permutation = nt.Permutation(input_matrix.GetLogicalDimension()) permutation.SetRandomPermutation() self.fsp.SetLoadBalance(permutation) nt.ExponentialSolvers.ComputeExponential(input_matrix, exp_matrix, self.fsp) exp_matrix.WriteToMatrixMarket(result_file) comm.barrier() self.check_result()
def __init__(self,mol,mints): self.nbf = get_nbf(mints) self.norb = 2* self.nbf self.nocc = get_nocc(mol) self.conv = get_conv() self.maxiter = get_maxiter() m = self.nbf N = self.norb # overlap matrix S = mints.ao_overlap() self.Z = block_oei(S) self.X = np.matrix(la.funm(self.Z,lambda x : x**(-0.5))) # KE matrix T = mints.ao_kinetic() self.T = block_oei(T) # PE matrix V = mints.ao_potential() self.V = block_oei(V) self.Vnu = mol.nuclear_repulsion_energy() # Hcore self.H = self.T + self.V # ERI matrix G = np.array( mints.ao_eri() ) #### mxmxmxm tensor self.G = block_tei(G) self.g = self.G.swapaxes(1,2) #### ( m n | r s ) -> < m r | n s > # Density matrix self.D = np.matrix(np.zeros(self.Z.shape)) self.E = 0.0
def test_logarithmfunction(self): '''Test routines to compute the matrix logarithm.''' from scipy.linalg import funm from numpy import log # Starting Matrix. Care taken to make sure eigenvalues are positive. matrix1 = self.create_matrix(scaled=True, diag_dom=True) self.write_matrix(matrix1, self.input_file) # Check Matrix dense_check = funm(matrix1.todense(), lambda x: log(x)) self.CheckMat = csr_matrix(dense_check) # Result Matrix input_matrix = nt.Matrix_ps(self.input_file, False) log_matrix = nt.Matrix_ps(self.mat_dim) permutation = nt.Permutation(input_matrix.GetLogicalDimension()) permutation.SetRandomPermutation() self.fsp.SetLoadBalance(permutation) nt.ExponentialSolvers.ComputeLogarithm(input_matrix, log_matrix, self.fsp) log_matrix.WriteToMatrixMarket(result_file) comm.barrier() self.check_result()
def exact0_single_step(rho_, *, h1e, mf, ovlp, inv_ovlp, mu, **kwargs): h = h1e + mf.get_veff(mf.mol, rho_) rho = ovlp @ linalg.funm(inv_ovlp @ h, lambda _: _ <= mu) return rho
def exact_single_step(rho_, *, h1e, mf, beta, inv_ovlp, ovlp, mu, **kwargs): h = h1e + mf.get_veff(mf.mol, rho_) rho = ovlp @ linalg.funm( inv_ovlp @ h, lambda _: np.exp(-beta * (_ - mu)) / (1 + np.exp(-beta * (_ - mu)))) return rho
############################################################################################## # # Linear HF model (only core H) # ############################################################################################## core_spect = linalg.eigvalsh(h1e, ovlp) num_electrons = 10 index = int(num_electrons / 2) mu = (core_spect[index] + core_spect[index - 1]) / 2 print(core_spect) print(mu) beta = 1 dbeta = beta / 10000 ferm_exact = ovlp @ linalg.funm( inv_ovlp @ h1e, lambda _: np.exp(-beta * (_ - mu)) / (1 + np.exp(-beta * (_ - mu)))) gc = CAdaptive_GC_RK4(ovlp=ovlp, H=h1e, mu=mu, dbeta=dbeta, epsilon=1e-1) gc.propagate(beta) plt.title("Populations") plt.plot(linalg.eigvalsh(gc.rho, ovlp)[::-1], '*-', label="GC") plt.plot(linalg.eigvalsh(ferm_exact, ovlp)[::-1], '*-', label="FD") plt.legend(numpoints=1) plt.show() plt.title("Variable step method in action") plt.plot(gc.beta_increments, '*-') plt.xlabel('steps')
def phi2m(A): return la.funm(A, _phi2)
def exact_function(rho_, h1e, gcp): h = h1e + gcp.mf.get_veff(gcp.mf.mol, rho_) arg = gcp.inv_ovlp@h return ovlp @ linalg.funm(arg, lambda _: 1/(1+np.exp(gcp.beta*(_ - mu))))
linalg.expm(A_non_sq) linalg.logm(A_non_sq) # Trigonometric functions - sinm, cosm, tanm linalg.sinm(A_sq) linalg.sinm(A_non_sq) # Hyperbolic trigonometric functions - sinhm, coshm, tanhm linalg.sinhm(A_sq) linalg.sinhm(A_non_sq) # Arbitrary function from scipy import special, random, linalg np.random.seed(1234) A = random.rand(3, 3) B = linalg.funm(A, lambda x: special.jv(0, x)) A B linalg.eigvals(A) special.jv(0, linalg.eigvals(A)) linalg.eigvals(B) # ----------------------------------------------------------------------------- # SPARSE EIGENVALUE PROBLEMS WITH ARPACK # Can be used to find only smallest/largest/real/complex part eigenvalues from scipy.linalg import eig, eigh from scipy.sparse.linalg import eigs, eigsh
def huckel_hamiltonian(alpha, gamma, size): H = sparse.diags([gamma, alpha, gamma], [-1, 0, 1], shape=(size, size)).toarray() H[0][size - 1] = gamma H[size - 1][0] = gamma return H H = huckel_hamiltonian(alpha, gamma, size) # define a chemical potential mu mu = 0.45 beta = 300 ferm_exact = linalg.funm( H, lambda _: np.exp(-beta * (_ - mu)) / (1 + np.exp(-beta * (_ - mu)))) numsteps = 10000 dbeta = beta / numsteps ovlp = np.identity(H.shape[0]) gcp = CAdaptive_GC_RK4(ovlp=ovlp, H=H, mu=mu, dbeta=dbeta, epsilon=1e-1) s_gcp = CAdaptive_GC_RK4_S(ovlp=ovlp, H=H, mu=mu, dbeta=dbeta, epsilon=1e-1) start = time.time() gcp.propagate(beta) end = time.time() print("Dense ver: " + str(end - start)) start = time.time()
generate.py a program to generate a random graph's exponential. Usage: python generate.py number_of_nodes matrix_file exponential_file """ from sys import argv from networkx import erdos_renyi_graph, to_scipy_sparse_matrix from scipy.linalg import funm from scipy.io import mmwrite from scipy.sparse import csr_matrix from numpy import exp ############################################################################### if __name__ == "__main__": # Generate a random directed graph nodes = int(argv[1]) prob = 0.05 graph = erdos_renyi_graph(nodes, prob, directed=True) matrix = to_scipy_sparse_matrix(graph).todense() for i in range(0, matrix.shape[0]): for j in range(0, matrix.shape[1]): if matrix[i, j] != 0 and matrix[j, i] != 0: matrix[i, j] = 0 # Compute The Exponential emat = funm(matrix, lambda x: exp(x)) # Write To File mmwrite(argv[2], csr_matrix(matrix * 1.0)) mmwrite(argv[3], csr_matrix(emat))
palsercp_rho = palser_cp(num_electrons, H, nsteps) print("Palser Idempotency: ", np.linalg.norm(palsercp_rho.dot(palsercp_rho) - palsercp_rho, np.inf)) pcp_eigs = np.linalg.eigvalsh(palsercp_rho) print("Palser Energy: ", np.sum(palsercp_rho * H.T)) palsergcp_rho = palser_gcp(mu, H, nsteps) pgcp_eigs = np.linalg.eigvalsh(palsergcp_rho) #Exact density matrix via heaviside step function #Compare mu for palser cp and our cp methods #temp = palsercp_rho.dot(identity - palsercp_rho) #p_alpha = np.sum(H*temp.T)/temp.trace() p_alpha = np.trace(H)/size print("Palser mu: ", str(p_alpha)) scaled_H = p_alpha*identity-H p_alpha_ex = linalg.funm(scaled_H, lambda _: np.heaviside(_.real, 0.5)) alpha = cp_dmm.get_mu() scaled_H = alpha*identity-H cphs_rho = linalg.funm(scaled_H, lambda _: np.heaviside(_.real, 0.5)) print("Our mu: ", str(alpha)) scaled_H = mu*identity - H hs_rho = linalg.funm(scaled_H, lambda _: np.heaviside(_.real, 0.5)) #Plot exact solution plt.figure(1) plt.subplot(111) plt.ylabel('P_ij') plt.xlabel('|i-j|') plt.title("CP Comparisons")
def phi3m(A): return la.funm(A, _phi3)
def phi1m(A): return la.funm(A, _phi1)
from functools import partial if __name__ == "__main__": #process input parameters for i in range(1, len(sys.argv), 2): argument = sys.argv[i] argument_value = sys.argv[i + 1] if argument == '--hamiltonian': hamiltonian_file = argument_value if argument == '--chemical_potential': chemical_potential = float(argument_value) if argument == '--rows': rows = int(argument_value) elif argument == '--density_file_out': density_file = argument_value #compute heaviside step function of mu*I-H hamiltonian = mmread(hamiltonian_file).toarray() scaled_H = chemical_potential * np.identity( hamiltonian[0].size) - hamiltonian rho = linalg.funm(scaled_H, lambda _: np.heaviside(_.real, 0.5)) #print(np.linalg.eigvalsh(rho)) try: density_file except NameError: density_file = "scipy_density.mtx" mmwrite(density_file, sparse.coo_matrix(rho))