def runspbertha(pberthaopt): sys.path.insert(0, pberthaopt.berthamodpath) import berthamod print("Options: ") for att in [a for a in dir(pberthaopt) if not a.startswith('__')]: print(att, " = ", getattr(pberthaopt, att)) print("") print("") if not os.path.isfile(pberthaopt.wrapperso): print("SO File ", pberthaopt.wrapperso, " does not exist") exit(1) verbosity = pberthaopt.verbosity dumpfiles = int(pberthaopt.dumpfiles) bertha = berthamod.pybertha(pberthaopt.wrapperso) bertha.set_thresh(pberthaopt.thresh) bertha.set_verbosity(verbosity) bertha.set_dumpfiles(dumpfiles) bertha.set_densitydiff(1) bertha.init() ndim = bertha.get_ndim() nshift = bertha.get_nshift() nocc = bertha.get_nocc() sfact = bertha.get_sfact() nopen = bertha.get_nopen() print("Verbosity : ", verbosity) print("Dumpfiles : ", dumpfiles) print("") print("Matrix dimension: ", ndim) print(" nocc: ", nocc) print(" nshift: ", nshift) print(" nopen: ", nopen) print(" level shift: ", sfact) print("") start = time.time() cstart = time.process_time() ovapm, eigemfirst, fockm, eigen = bertha.run() end = time.time() cend = time.process_time() print("Totaltime: ", end - start, " (CPU time: ", cend - cstart, ") s ") print("MainRun Time: ", bertha.get_mainruntime() , \ " (CPU time: " , bertha.get_mainrunctime(), ") s ") sys.stdout.flush() if (fockm is None) or (eigen is None) or (fockm is None) \ or (eigen is None): print("Error in bertha run") exit(-1) print("") print("Final results ") for i in range(nocc + nopen): print("eigenvalue %5d %20.8f" % (i + 1, eigen[i + nshift] - sfact)) print(" lumo %20.8f" % (eigen[i + nshift + 1])) erep = bertha.get_erep() etotal = bertha.get_etotal() ecoul = bertha.get_eecoul() exc = bertha.get_eexc() print("") print("total electronic energy = %30.15f" % (etotal - (sfact * nocc))) print("nuclear repulsion energy = %30.15f" % (erep)) print("total energy = %30.15f" % (etotal + erep - (sfact * nocc))) print("coulomb energy = %30.15f" % (ecoul)) print("Exc energy = %30.15f" % (exc)) bertha.finalize() print("\n\nSTART second RUN \n\n") bertha.set_thresh(pberthaopt.thresh) bertha.set_verbosity(verbosity) bertha.set_dumpfiles(dumpfiles) bertha.set_densitydiff(1) bertha.init() ndim = bertha.get_ndim() nshift = bertha.get_nshift() nocc = bertha.get_nocc() sfact = bertha.get_sfact() nopen = bertha.get_nopen() print("Verbosity : ", verbosity) print("Dumpfiles : ", dumpfiles) print("") print("Matrix dimension: ", ndim) print(" nocc: ", nocc) print(" nshift: ", nshift) print(" nopen: ", nopen) print(" level shift: ", sfact) print("") start = time.time() cstart = time.process_time() ovapm, eigem, fockm, eigen = bertha.run(eigemfirst) end = time.time() cend = time.process_time() print("Totaltime: ", end - start, " (CPU time: ", cend - cstart, ") s ") print("MainRun Time: ", bertha.get_mainruntime() , \ " (CPU time: " , bertha.get_mainrunctime(), ") s ") sys.stdout.flush() if (fockm is None) or (eigen is None) or (fockm is None) \ or (eigen is None): print("Error in bertha run") exit(-1) print("") print("Final results ") for i in range(nocc + nopen): print("eigenvalue %5d %20.8f" % (i + 1, eigen[i + nshift] - sfact)) print(" lumo %20.8f" % (eigen[i + nshift + 1])) erep = bertha.get_erep() etotal = bertha.get_etotal() ecoul = bertha.get_eecoul() exc = bertha.get_eexc() print("") print("total electronic energy = %30.15f" % (etotal - (sfact * nocc))) print("nuclear repulsion energy = %30.15f" % (erep)) print("total energy = %30.15f" % (etotal + erep - (sfact * nocc))) print("coulomb energy = %30.15f" % (ecoul)) print("Exc energy = %30.15f" % (exc)) bertha.finalize()
def normal_run(args): print("Options: ") print(args) print("") print("") if not os.path.isfile(args.wrapperso): print("SO File ", args.wrapperso, " does not exist") return False bertha = berthamod.pybertha(args.wrapperso) ovapm, eigem, fockm, eigen = single_point (args, bertha) if ovapm is None: return False ndim = bertha.get_ndim() nshift = bertha.get_nshift() nocc = bertha.get_nocc() bertha.realtime_init() print("Start RT") debug = args.debug dt = args.dt t_int = args.totaltime niter = int(t_int/dt) print("Debug: ", debug) print("dt : ", dt) print("Total time : ", t_int) print("Number of iterations: ", niter) sys.stdout.flush() ene_list = [] dip_list = [] weight_list = [] imp_list = [] Enuc_list = [] C = eigem D_0 = numpy.zeros((ndim,ndim), dtype=numpy.complex128) for num in range(nocc): D_0[num+nshift,num+nshift]=1.0+0.0j fo = sys.stderr if debug: fo = open("debug_info.txt", "w") #print type(eigem) #C_inv used to backtransform D(AO) try: C_inv = numpy.linalg.inv(eigem) except LinAlgError: print("Error in numpy.linalg.inv of eigem") return False if debug: test = numpy.matmul(C_inv, eigem) fo.write("Check if atol is 1.e-14 for inversion of C: %s\n"% \ numpy.allclose(numpy.eye((ndim),dtype=numpy.complex128), \ test,atol=1.e-14)) if debug: diff = test - numpy.eye((ndim),dtype=numpy.complex128) mdiff = numpy.max(diff) fo.write(" maxdiff is: %.12e %.12e\n"%(mdiff.real, mdiff.imag)) if debug: test = numpy.matmul(numpy.conjugate(C.T),numpy.matmul(ovapm,C)) fo.write("Check orthonormal orbitals (atol = 1.e-14): %s\n"% \ numpy.allclose(numpy.eye((ndim),dtype=numpy.complex128), \ test, atol=1.e-14)) diff = test - numpy.eye((ndim),dtype=numpy.complex128) mdiff = numpy.max(diff) fo.write(" maxdiff is: %.12e %.12e\n"%(mdiff.real, mdiff.imag)) #build density in ao basis occeigv = numpy.zeros((ndim,nocc), dtype=numpy.complex128) iocc = 0 for i in range(ndim): if i >= nshift and iocc < nocc: for j in range(ndim): occeigv[j, iocc] = eigem[j, i] iocc = iocc + 1 Da = numpy.matmul(occeigv,numpy.conjugate(occeigv.transpose())) print("") print("Dump ground state density density0.cube") bertha.density_to_cube(Da.T, "density0.cube",margin=5.0) print("Done") if debug: #check trace(S Da) trace_ds = numpy.trace(numpy.matmul(Da,ovapm)) trace_dsfock = numpy.trace(numpy.matmul(Da,fockm)) fo.write("Density matrix trace at t0: %.12e %.12e \n"%(trace_ds.real,trace_ds.imag)) fo.write("Trace of fock*density at t0: %.12e %.12e \n"%(trace_dsfock.real, trace_dsfock.imag)) normalise = 1 dip_mat = None dipx_mat, dipy_mat, dipz_mat = \ bertha.get_realtime_dipolematrix (0, normalise) if (args.direction == 4): dip_mat = dipx_mat elif (args.direction == 3): dip_mat = dipy_mat elif (args.direction == 2): dip_mat = dipz_mat if debug: fockmh = numpy.conjugate(fockm.T) diff_fockmh = fockm-fockmh mdiff = numpy.max(diff_fockmh) fo.write("Check max diff fockm-fockmh: %.12e %.12e\n"%\ (mdiff.real, mdiff.imag)) fo.write("Fockm (t=0) is hermitian: %s \n"%numpy.allclose(fockm,fockmh,atol=1.e-15)) molist = args.select.split("&") occlist = molist[0].split(";") occlist = [int(m) for m in occlist] virtlist = molist[1].split(";") virtlist = [int(m) for m in virtlist] if (args.pulse == "analytic"): Amp=args.pulseFmax # to check dipz_mo=numpy.matmul(numpy.conjugate(C.T),numpy.matmul(dip_mat,C)) if args.select_pert: dipz_mo=rtutil.dipole_selection(dipz_mo,nshift,nocc,occlist,virtlist,fo,debug) print(" Perturb with analytic kick ") u0=rtutil.exp_opmat(dipz_mo,numpy.float_(-Amp),debug,fo) Dp_init=numpy.matmul(u0,numpy.matmul(D_0,numpy.conjugate(u0.T))) #transform back Dp_int Da=numpy.matmul(C,numpy.matmul(Dp_init,numpy.conjugate(C.T))) D_0=Dp_init print("Start first mo_fock_mid_forwd_eval ") fock_mid_init = rtutil.mo_fock_mid_forwd_eval(bertha,Da,fockm,0,numpy.float_(dt),\ dip_mat,C,C_inv,ovapm,ndim, debug, fo, args.pulse, args.pulseFmax, args.pulsew, args.t0, args.pulseS, args.propthresh) if (fock_mid_init is None): print("Error accurs in mo_fock_mid_forwd_eval") return False if debug: fock_mid_h=numpy.conjugate(fock_mid_init.T) diff_fock_mid_h=fock_mid_init-fock_mid_h fo.write("Max diff fock_mid_init-fock_mid_h"%(numpy.max(diff_fock_mid_h))) fo.write('Fockm (t=1/2) is hermitian: %s\n'% numpy.allclose(fock_mid_init,fock_mid_h,atol=1.e-14)) fockp_mid_init=numpy.matmul(numpy.conjugate(C.T),numpy.matmul(fock_mid_init,C)) u=rtutil.exp_opmat(fockp_mid_init,numpy.float_(dt),debug,fo) #u=rtutil.exp_opmat(fockp_mid_init,numpy.float_(dt),debug,fo) #u=scila.expm(-1.j*fockp_mid_init*dt) temp=numpy.matmul(D_0,numpy.conjugate(u.T)) Dp_t1=numpy.matmul(u,temp) #check u if unitary if debug: test_u=numpy.matmul(u,numpy.conjugate(u.T)) fo.write('U is unitary : %s' % numpy.allclose(test_u,numpy.eye(u.shape[0]),atol=1.e-14)) #backtrasform Dp_t1 D_t1=numpy.matmul(C,numpy.matmul(Dp_t1,numpy.conjugate(C.T))) if debug: diff = D_t1 - Da mdiff = numpy.max(diff) fo.write("Max diff density: %.12e %.12e \n"%(mdiff.real, mdiff.imag)) dip_list.append(numpy.trace(numpy.matmul(Da,dip_mat))) dip_list.append(numpy.trace(numpy.matmul(D_t1,dip_mat))) if (args.pulse == "analytic"): if (occlist[0] != -2): #dipoleanalysis res=rtutil.dipoleanalysis(dipz_mo,D_0,occlist,virtlist,nshift,fo,debug) weight_list.append(res) res=rtutil.dipoleanalysis(dipz_mo,Dp_t1,occlist,virtlist,nshift,fo,debug) weight_list.append(res) if debug: fo.write("Dipole: %.12e\n"%(numpy.trace(numpy.matmul(Da,dip_mat))).real) fo.write("Dipole: %.12e\n"%(numpy.trace(numpy.matmul(D_t1,dip_mat))).real) if debug: tfock = numpy.trace(numpy.matmul(D_t1,fockm)) fo.write("Trace fock*density t1: %.12e, %.12e\n"%(tfock.real, tfock.imag)) trace_ds=numpy.trace(numpy.matmul(D_t1,ovapm)) fo.write(" Traceds: %.12e %.12ei\n" % (trace_ds.real,trace_ds.imag)) Ndip_z=0.0 #estrarre le 3 componenti del dipolo nucleare D_ti=D_t1 Dp_ti=Dp_t1 #aggiungere repulsione nucleare #Enuc_list.append(-func_t0*Ndip_z+Nuc_rep) #just in case of non-zero nuclear dipole start = time.time() cstart = time.process_time() fockm_ti=bertha.get_realtime_fock(D_ti.T) end = time.time() cend = time.process_time() print("RealTime Fock Time: %15.5f"%(end-start), " (CPU: %15.5f"%(cend-cstart), " ) s") print("RealTime Fock Time Without Py: %15.5f"%(bertha.get_focktime()), \ " (CPU: %15.5f"%(bertha.get_fockctime()), " ) s") print("") ene_list.append(numpy.trace(numpy.matmul(Da,fockm))) ene_list.append(numpy.trace(numpy.matmul(D_ti,fockm_ti))) print("Starting iterations ...") print("") fock_mid_backwd = numpy.copy(fock_mid_init) return run_iterations_from_to (1, niter, bertha, args, fock_mid_backwd, \ dt, dip_mat, C, C_inv, ovapm, ndim, debug, Dp_ti, dip_list, ene_list, \ weight_list, fo, D_ti, occlist)
def runspberthaembedrt(pberthaopt): sys.path.insert(0, pberthaopt.berthamodpath) import berthamod print("Options: ") for att in [a for a in dir(pberthaopt) if not a.startswith('__')]: print(att, " = ", getattr(pberthaopt, att)) print("") print("") print("") if not os.path.isfile(pberthaopt.wrapperso): print("SO File ", pberthaopt.wrapperso, " does not exist") exit(1) bertha = berthamod.pybertha(pberthaopt.wrapperso) fittcoefffname = pberthaopt.fitcoefffile vctfilename = pberthaopt.vctfile ovapfilename = pberthaopt.ovapfile fnameinput = pberthaopt.inputfile if not os.path.isfile(fnameinput): print("File ", fnameinput, " does not exist") exit(1) fittfname = pberthaopt.fittfile if not os.path.isfile(fittfname): print("File ", fittfname, " does not exist") exit(1) verbosity = pberthaopt.verbosity dumpfiles = int(pberthaopt.dumpfiles) bertha.set_fittcoefffname(fittcoefffname) bertha.set_ovapfilename(ovapfilename) bertha.set_vctfilename(vctfilename) bertha.set_fnameinput(fnameinput) bertha.set_fittfname(fittfname) bertha.set_thresh(pberthaopt.thresh) bertha.set_verbosity(verbosity) bertha.set_dumpfiles(dumpfiles) bertha.set_densitydiff(1) bertha.init() ndim = bertha.get_ndim() nshift = bertha.get_nshift() nocc = bertha.get_nocc() sfact = bertha.get_sfact() nopen = bertha.get_nopen() print("Verbosity : ", verbosity) print("Dumpfiles : ", dumpfiles) print("") print("Matrix dimension: ", ndim) print(" nocc: ", nocc) print(" nshift: ", nshift) print(" nopen: ", nopen) print(" level shift: ", sfact) print("") #generate a sample grid """ npoints = 10 grid = numpy.zeros((npoints, 4)) grid = numpy.ascontiguousarray(grid, dtype=numpy.double) pot = numpy.zeros(npoints) pot = numpy.ascontiguousarray(pot, dtype=numpy.double) x = -1.0 y = -100.0 z = -1000.0 w = 1.0 for i in range(npoints): grid[i,0] = x grid[i,1] = y grid[i,2] = z grid[i,3] = w pot[i] = x*y*z*w x += 1.0 y += 1.0 z += 1.0 w += 0.1 """ #read a real grid grid = berthamod.read_grid_file("ADFGRID") if grid is None: print("ERROR in reading gridfile") exit(1) grid, pot = berthamod.read_grid_ampot_file("EMBPOT_PYEMBED_ADFGRID_H2O") if grid is None or pot is None: print("ERROR in reading gridpotfile") exit(1) npoints = grid.shape[0] start = time.time() cstart = time.process_time() print("Type grid", type(grid), grid.shape) print("Type pot", type(pot), pot.shape) bertha.set_embpot_on_grid(grid, pot) print("Type pot", pot) #main run here ovapm, eigem, fockm, eigen = bertha.run() density = bertha.get_density_on_grid(grid) # TEST density on grid # print("TEST density on grid") # print("Type density", type(density), density.shape) # print("Scalar product" , "density.weigt", numpy.dot(density,grid[:,3])) # print("Dip x" , "density.weigt", numpy.dot(density*grid[:,3],grid[:,0])) # print("Dip y" , "density.weigt", numpy.dot(density*grid[:,3],grid[:,1])) # print("Dip z" , "density.weigt", numpy.dot(density*grid[:,3],grid[:,2])) """ for i in range(npoints): val = grid[i,0] * grid[i,1] * grid[i,2] * grid[i,3] print("Python L: %15.5f vs %15.5f"%(density[i], val)) """ end = time.time() cend = time.process_time() print("Totaltime: ", end - start, " (CPU time: ", cend - cstart, ") s ") print("MainRun Time: ", bertha.get_mainruntime() , \ " (CPU time: ", bertha.get_mainrunctime(), ") s ") bertha.realtime_init() normalise = 1 dip_mat = None dipx_mat, dipy_mat, dipz_mat = \ bertha.get_realtime_dipolematrix (0, normalise) occeigv = numpy.zeros((ndim, nocc), dtype=numpy.complex128) iocc = 0 for i in range(ndim): if i >= nshift and iocc < nocc: for j in range(ndim): occeigv[j, iocc] = eigem[j, i] iocc = iocc + 1 Da = numpy.matmul(occeigv, numpy.conjugate(occeigv.transpose())) dipx_ref = numpy.trace(numpy.matmul(Da, dipx_mat)).real dipy_ref = numpy.trace(numpy.matmul(Da, dipy_mat)).real dipz_ref = numpy.trace(numpy.matmul(Da, dipz_mat)).real print("Dipx ", dipx_ref) print("Dipy ", dipy_ref) print("Dipz ", dipz_ref) # TEST density on grid bertha.finalize() bertha.set_fittcoefffname(fittcoefffname) bertha.set_ovapfilename(ovapfilename) bertha.set_vctfilename(vctfilename) bertha.set_fnameinput(fnameinput) bertha.set_fittfname(fittfname) bertha.set_thresh(pberthaopt.thresh) bertha.set_verbosity(verbosity) bertha.set_dumpfiles(dumpfiles) bertha.set_densitydiff(1) bertha.init() field = 0.00001 pot = grid[:, 0] * field bertha.set_embpot_on_grid(grid, pot) ovapm, eigem, fockm, eigen = bertha.run() etotal1 = bertha.get_etotal() bertha.finalize() bertha.set_fittcoefffname(fittcoefffname) bertha.set_ovapfilename(ovapfilename) bertha.set_vctfilename(vctfilename) bertha.set_fnameinput(fnameinput) bertha.set_fittfname(fittfname) bertha.set_thresh(pberthaopt.thresh) bertha.set_verbosity(verbosity) bertha.set_dumpfiles(dumpfiles) bertha.set_densitydiff(1) bertha.init() pot = grid[:, 0] * (-field) bertha.set_embpot_on_grid(grid, pot) ovapm, eigem, fockm, eigen = bertha.run() etotal2 = bertha.get_etotal() dipx = (etotal2 - etotal1) / (2 * field) print("Dipole moment analitical: Tr(D dip_mat)") print("Dip x ", dipx_ref) print("Dip y ", dipy_ref) print("Dip z ", dipz_ref) print("TEST dipole moment from density on grid numerical integration") print(" ") print("Type density", type(density), density.shape) print("Scalar product", "density.weigt", numpy.dot(density, grid[:, 3])) print("Dip x", "density.weigt", numpy.dot(density * grid[:, 3], grid[:, 0])) print("Dip y", "density.weigt", numpy.dot(density * grid[:, 3], grid[:, 1])) print("Dip z", "density.weigt", numpy.dot(density * grid[:, 3], grid[:, 2])) print(" ") print("TEST one electron potential (embedding) in g-spinor") print("Potential used -x*E and x*E evaluating dipole via finite field") print("Dip x", "from finite field", dipx) sys.stdout.flush()
help="cube margin parameter (default = 10.0)", required=False, type=numpy.float64, default=10.0) args = parser.parse_args() print("Options: ") print(args) print("") print("") if not os.path.isfile(args.wrapperso): print("SO File ", args.wrapperso, " does not exist") exit(1) bertha = berthamod.pybertha(args.wrapperso) fittcoefffname = args.fitcoefffile vctfilename = args.vctfile ovapfilename = args.ovapfile fnameinput = args.inputfile if not os.path.isfile(fnameinput): print("File ", fnameinput, " does not exist") exit(1) fittfname = args.fittfile if not os.path.isfile(fittfname): print("File ", fittfname, " does not exist") exit(1)
def restart_run(args): fp = open(args.restartfile, 'r') json_data = json.load(fp) fp.close() jstart = int(json_data["j"]) ndim = int(json_data["ndim"]) niter = int(json_data["niter"]) fock_mid_backwd_REAL = numpy.float_(json_data["fock_mid_backwd_REAL"]) fock_mid_backwd_IMAG = numpy.float_(json_data["fock_mid_backwd_IMAG"]) dip_mat_REAL = numpy.float_(json_data["dip_mat_REAL"]) dip_mat_IMAG = numpy.float_(json_data["dip_mat_IMAG"]) C_REAL = numpy.float_(json_data["C_REAL"]) C_IMAG = numpy.float_(json_data["C_IMAG"]) C_inv_REAL = numpy.float_(json_data["C_inv_REAL"]) C_inv_IMAG = numpy.float_(json_data["C_inv_IMAG"]) ovapm_REAL = numpy.float_(json_data["ovapm_REAL"]) ovapm_IMAG = numpy.float_(json_data["ovapm_IMAG"]) Dp_ti_REAL = numpy.float_(json_data["Dp_ti_REAL"]) Dp_ti_IMAG = numpy.float_(json_data["Dp_ti_IMAG"]) D_ti_REAL = numpy.float_(json_data["D_ti_REAL"]) D_ti_IMAG = numpy.float_(json_data["D_ti_IMAG"]) fock_mid_backwd = check_and_covert (fock_mid_backwd_REAL , fock_mid_backwd_IMAG, ndim) dip_mat = check_and_covert (dip_mat_REAL, dip_mat_IMAG, ndim) C = check_and_covert (C_REAL, C_IMAG, ndim) C_inv = check_and_covert (C_inv_REAL, C_inv_IMAG, ndim) ovapm = check_and_covert (ovapm_REAL, ovapm_IMAG, ndim) Dp_ti = check_and_covert (Dp_ti_REAL, Dp_ti_IMAG, ndim) D_ti = check_and_covert (D_ti_REAL, D_ti_IMAG, ndim) ene_list_REAL = numpy.float_(json_data["ene_list_REAL"]) ene_list_IMAG = numpy.float_(json_data["ene_list_IMAG"]) dip_list_REAL = numpy.float_(json_data["dip_list_REAL"]) dip_list_IMAG = numpy.float_(json_data["dip_list_IMAG"]) if ((ene_list_REAL.shape != ene_list_IMAG.shape) or (dip_list_REAL.shape != dip_list_IMAG.shape) or (ene_list_REAL.shape != dip_list_IMAG.shape)): return False ene_list = [] dip_list = [] for i in range(ene_list_REAL.shape[0]): ene_list.append(numpy.complex128(complex(ene_list_REAL[i], ene_list_IMAG[i]))) dip_list.append(numpy.complex128(complex(dip_list_REAL[i], dip_list_IMAG[i]))) weight_list_REAL = numpy.float_(json_data["weight_list_REAL"]) weight_list_IMAG = numpy.float_(json_data["weight_list_IMAG"]) weight_list = [] if len(weight_list_REAL) != len(weight_list_IMAG): print("ERROR in weight_list size") exit(1) for i in range(len(weight_list_REAL)): if len(weight_list_REAL[i]) != len(weight_list_IMAG[i]): print("ERROR in weight_list size") exit(1) row = numpy.zeros(len(weight_list_REAL[i]), dtype=numpy.complex128) for j in range(len(weight_list_REAL[i])): row[j] = numpy.complex128(complex(weight_list_REAL[i][j], weight_list_IMAG[i][j])) weight_list.append(row) args.pulse = json_data['pulse'] args.pulseFmax = json_data['pulseFmax'] args.pulsew = json_data['pulsew'] args.dt = json_data['dt'] args.inputfile = json_data['inputfile'] args.fittfile = json_data["fittfile"] args.fitcoefffile = json_data["fitcoefffile"] args.vctfile = json_data["vctfile"] args.ovapfile = json_data["ovapfile"] args.dumpfiles = json_data["dumpfiles"] args.direction = json_data["direction"] totaltime = json_data["totaltime"] if args.totaltime < totaltime: args.totaltime = json_data["totaltime"] else: niter = int(args.totaltime/args.dt) args.debug = json_data["debug"] args.verbosity = json_data["verbosity"] args.iterations = json_data["iterations"] args.select = json_data["select"] args.select_pert = json_data["select_pert"] args.propthresh = json_data["propthresh"] args.thresh = json_data["thresh"] args.wrapperso = json_data["wrapperso"] args.dumprestartnum = json_data["dumprestartnum"] args.pulseS = json_data["pulseS"] args.t0 = json_data["t0"] molist = args.select.split("&") occlist = molist[0].split(";") occlist = [int(m) for m in occlist] virtlist = molist[1].split(";") virtlist = [int(m) for m in virtlist] print("Options: ") print(args) print("") print("") if not os.path.isfile(args.wrapperso): print("SO File ", args.wrapperso, " does not exist") return False bertha = berthamod.pybertha(args.wrapperso) # TODO to remove full run ovapm, eigem, fockm, eigen = single_point (args, bertha) if ovapm is None: return False ndim = bertha.get_ndim() nshift = bertha.get_nshift() nocc = bertha.get_nocc() bertha.realtime_init() print("Start RT") debug = args.debug dt = args.dt t_int = args.totaltime print("Debug: ", debug) print("dt : ", dt) print("Total time : ", t_int) print("Number of iterations: ", niter) sys.stdout.flush() fo = sys.stderr if debug: fo = open("debug_info.txt", "w") return run_iterations_from_to (jstart+1, niter, bertha, args, fock_mid_backwd, \ dt, dip_mat, C, C_inv, ovapm, ndim, debug, Dp_ti, dip_list, ene_list, \ weight_list, fo, D_ti, occlist)
def runspbertha(pberthaopt): sys.path.insert(0, pberthaopt.berthamodpath) import berthamod #import os, psutil #process = psutil.Process(os.getpid()) #print(process.memory_info()) # in bytes print("Options: ") for att in [a for a in dir(pberthaopt) if not a.startswith('__')]: print(att, " = ", getattr(pberthaopt, att)) print("") print("") if not os.path.isfile(pberthaopt.wrapperso): print("SO File ", pberthaopt.wrapperso, " does not exist") exit(1) bertha = berthamod.pybertha(pberthaopt.wrapperso) fittcoefffname = pberthaopt.fitcoefffile vctfilename = pberthaopt.vctfile ovapfilename = pberthaopt.ovapfile fnameinput = pberthaopt.inputfile if not os.path.isfile(fnameinput): print("File ", fnameinput, " does not exist") exit(1) fittfname = pberthaopt.fittfile if not os.path.isfile(fittfname): print("File ", fittfname, " does not exist") exit(1) verbosity = pberthaopt.verbosity dumpfiles = int(pberthaopt.dumpfiles) bertha.set_fittcoefffname(fittcoefffname) bertha.set_ovapfilename(ovapfilename) bertha.set_vctfilename(vctfilename) bertha.set_fnameinput(fnameinput) bertha.set_fittfname(fittfname) bertha.set_thresh(pberthaopt.thresh) bertha.set_verbosity(verbosity) bertha.set_dumpfiles(dumpfiles) bertha.set_densitydiff(0) bertha.init() #print(process.memory_info()) # in bytes ndim = bertha.get_ndim() nshift = bertha.get_nshift() nocc = bertha.get_nocc() sfact = bertha.get_sfact() nopen = bertha.get_nopen() print("Verbosity : ", verbosity) print("Dumpfiles : ", dumpfiles) print("") print("Matrix dimension: ", ndim) print(" nocc: ", nocc) print(" nshift: ", nshift) print(" nopen: ", nopen) print(" level shift: ", sfact) print("") start = time.time() cstart = time.process_time() #print(process.memory_info()) # in bytes if pberthaopt.gridfilename != "" and \ pberthaopt.potfilename != "": if os.path.isfile(pberthaopt.gridfilename) and \ os.path.isfile(pberthaopt.potfilename): grid = berthamod.read_sgrid_file(pberthaopt.gridfilename) pot = berthamod.read_pot_file(pberthaopt.potfilename) if (pot is not None) and (grid is not None): if grid.shape[0] == pot.shape[0]: bertha.set_embpot_on_grid(grid, pot) else: print("ERROR: grid and pot files are not compatible") exit(1) else: print("ERROR: " + pberthaopt.gridfilename + " and/or " + pberthaopt.potfilename + " do not exist") exit(1) ovapm, eigem, fockm, eigen = bertha.run() end = time.time() cend = time.process_time() print("Totaltime: ", end - start, " (CPU time: ", cend - cstart, ") s ") print("MainRun Time: ", bertha.get_mainruntime() , \ " (CPU time: " , bertha.get_mainrunctime(), ") s ") sys.stdout.flush() if (fockm is None) or (eigen is None) or (fockm is None) \ or (eigen is None): print("Error in bertha run") exit(-1) """ counter = 0 for i in range(ndim): print "i ==> ", i+1, eigen[i] for j in range(ndim): sys.stdout.write("(%20.10f %20.10fi) \n"%( eigenvctbu[counter], eigenvctbu[counter+1])) counter = counter + 2 print "" """ print("") print("Final results ") for i in range(nocc + nopen): print("eigenvalue %5d %20.8f" % (i + 1, eigen[i + nshift] - sfact)) print(" lumo %20.8f" % (eigen[i + nshift + 1])) erep = bertha.get_erep() etotal = bertha.get_etotal() ecoul = bertha.get_eecoul() exc = bertha.get_eexc() print("") print("total electronic energy = %30.15f" % (etotal - (sfact * nocc))) print("nuclear repulsion energy = %30.15f" % (erep)) print("total energy = %30.15f" % (etotal + erep - (sfact * nocc))) print("coulomb energy = %30.15f" % (ecoul)) print("Exc energy = %30.15f" % (exc)) occeigv = numpy.zeros((ndim, nocc), dtype=numpy.complex128) etotal = etotal + erep - (sfact * nocc) iocc = 0 for i in range(ndim): if i >= nshift and iocc < nocc: for j in range(ndim): occeigv[j, iocc] = eigem[j, i] iocc = iocc + 1 if pberthaopt.eda_nocv_info: encoder.FLOAT_REPR = lambda o: format(o, '.25E') json_data = get_json_data(pberthaopt, etotal, erep, ecoul, exc, ndim, nocc, occeigv) with open(pberthaopt.eda_nocv_frag_file, 'w') as fp: json.dump(json_data, fp, sort_keys=True, indent=4) """ for i in range(nocc): print "i ==> ", i+1, eigen[i+nshift] for j in range(ndim): sys.stdout.write("(%20.10f %20.10fi)\n"%( occeigv[j, i].real, occeigv[j, i].imag)) print "" """ print("") print("Compute density matrix ") density = numpy.matmul(occeigv, numpy.conjugate(occeigv.transpose()), out=None) density = numpy.matmul(density, ovapm) print("Trace ") trace = density.trace() print("(%20.10f, %20.10fi)" % (trace.real, trace.imag)) drx = pberthaopt.deltax dry = pberthaopt.deltay drz = pberthaopt.deltaz margin = pberthaopt.lmargin if (pberthaopt.cube == True): bertha.density_to_cube((density).T, "density.cube", margin, drx, dry, drz) if (pberthaopt.cubebox == True): bertha.density_to_cube_limit((density).T, "densitybox.cube", \ (pberthaopt.xmin, pberthaopt.ymin, \ pberthaopt.zmin), (pberthaopt.xmax, \ pberthaopt.ymax, pberthaopt.zmax), \ drx, dry, drz ) bertha.realtime_init() normalise = 1 numofatom = bertha.get_natoms() print("Num of atoms: ", numofatom) for i in range(numofatom): print(bertha.get_coords(i)) """ outep = open("eps.txt", "w") griddim = 50 xmin = 9.0 xmax = 12.0 ymin = 6.0 ymax = 10.0 zmax = 7.0 zmin = -3.0 dx = (xmax - xmin)/float(griddim) dy = (ymax - ymin)/float(griddim) x = xmin for i in range(griddim): y = ymin for j in range(griddim): z = 0.0 eps = bertha.get_eps (x, y, z) outep.write (" %10.5e %10.5e %10.5e \n"%(x, y, eps)) y = y + dy x = x + dx dz = (zmax - zmin)/float(griddim) z = zmin for i in range(griddim): eps = bertha.get_eps (0.0, 0.0, z) outep.write (" %10.5e %10.5e \n"%(z, eps)) z = z + dz """ bertha.finalize() """
def runspberthaembed(pberthaopt, restart=False, stdoutprint=True): ovapm = None eigem = None fockm = None eigen = None verbosity = -1 verbosity = pberthaopt.verbosity if not stdoutprint: verbosity = 0 import berthamod import pyembmod if stdoutprint: print("Options: ") for att in [a for a in dir(pberthaopt) if not a.startswith('__')]: print(att, " = ", getattr(pberthaopt, att)) print("") print("") print("") if not os.path.isfile(pberthaopt.wrapperso): raise Exception("SO File ", pberthaopt.wrapperso, " does not exist") fittcoefffname = pberthaopt.fitcoefffile vctfilename = pberthaopt.vctfile ovapfilename = pberthaopt.ovapfile fnameinput = pberthaopt.inputfile if not os.path.isfile(fnameinput): raise Exception("File ", fnameinput, " does not exist") fittfname = pberthaopt.fittfile if not os.path.isfile(fittfname): raise Exception("File ", fittfname, " does not exist") dumpfiles = int(pberthaopt.dumpfiles) static_field = pberthaopt.static_field fmax = pberthaopt.fmax fdir = pberthaopt.fdir nofde = pberthaopt.nofde eigem = None rho = None Da0 = None etotal = 0.0 dipx_ref = 0.0 dipy_ref = 0.0 dipz_ref = 0.0 bertha = berthamod.pybertha(pberthaopt.wrapperso) if not restart: try: os.remove(pberthaopt.restartfname) except OSError: pass bertha.set_fittcoefffname(fittcoefffname) bertha.set_ovapfilename(ovapfilename) bertha.set_vctfilename(vctfilename) bertha.set_fnameinput(fnameinput) bertha.set_fittfname(fittfname) bertha.set_thresh(pberthaopt.thresh) bertha.set_verbosity(verbosity) bertha.set_dumpfiles(dumpfiles) bertha.set_densitydiff(1) bertha.init() ndim = bertha.get_ndim() nshift = bertha.get_nshift() nocc = bertha.get_nocc() sfact = bertha.get_sfact() nopen = bertha.get_nopen() if stdoutprint: print("Verbosity : ", verbosity) print("Dumpfiles : ", dumpfiles) print("") print("Matrix dimension: ", ndim) print(" nocc: ", nocc) print(" nshift: ", nshift) print(" nopen: ", nopen) print(" level shift: ", sfact) print("") ovapm, eigem, fockm, eigen = bertha.run() if pberthaopt.dumpfiles: os.rename(vctfilename, 'unpert_vct.txt') if (fockm is None) or (eigen is None) or (fockm is None) \ or (eigen is None): raise Exception("Error in bertha run") if stdoutprint: sys.stdout.flush() print("") print("Final results ") for i in range(nocc + nopen): print("eigenvalue %5d %20.8f" % (i + 1, eigen[i + nshift] - sfact)) print(" lumo %20.8f" % (eigen[i + nshift + 1])) erep = bertha.get_erep() etotal = bertha.get_etotal() ecoul = bertha.get_eecoul() exc = bertha.get_eexc() if stdoutprint: print("") print("total electronic energy = %30.15f" % (etotal - (sfact * nocc))) print("nuclear repulsion energy = %30.15f" % (erep)) print("total energy = %30.15f" % (etotal + erep - (sfact * nocc))) print("coulomb energy = %30.15f" % (ecoul)) print("Exc energy = %30.15f" % (exc)) else: if stdoutprint: print("Restart: ") my_file = Path(pberthaopt.restartfname) if not my_file.is_file(): raise Exception(pberthaopt.restartfname + " does not exist restart=on") alldata = numpy.load(pberthaopt.restartfname) eigem = alldata["eigem"] Da0 = alldata["Da0"] rho = alldata["rho"] etotalnpa = alldata["etotalnpa"] etotal = etotalnpa[0] dipx_ref = etotalnpa[1] dipy_ref = etotalnpa[2] dipz_ref = etotalnpa[3] activefname = pberthaopt.activefile if not os.path.isfile(activefname): raise Exception("File ", activefname, " does not exist") envirofname = pberthaopt.envirofile if not os.path.isfile(envirofname): raise Exception("File ", envirofname, " does not exist") embfactory = pyembmod.pyemb(activefname, envirofname, 'adf') #jobtype='adf' is default de facto #grid_param =[50,110] # psi4 grid parameters (see Psi4 grid table) #embfactory.set_options(param=grid_param, \ embfactory.set_options(param=pberthaopt.param, \ gtype=pberthaopt.gtype, basis=pberthaopt.basis) embfactory.set_enviro_func(pberthaopt.excfuncenv) embfactory.set_thresh_conv(pberthaopt.thresh_conv) embfactory.set_grid_filename(pberthaopt.gridfname) # several paramenters to be specified in input- e.g AUG/ADZP for ADF, aug-cc-pvdz for psi4 if (pberthaopt.debug): import uuid filename = "adfout_" + str(uuid.uuid4()) + ".txt" embfactory.set_adf_filenameout(filename) filename = "psi4out_" + str(uuid.uuid4()) + ".txt" embfactory.set_psi4_filenameout(filename) if stdoutprint: print("embfactory Options:") print(embfactory.get_options()) embfactory.initialize() grid = embfactory.get_grid() if (pberthaopt.debug): numpy.savetxt("grid.txt", grid) if not restart: rho = bertha.get_density_on_grid(grid) if stdoutprint: print("Grid dimensions : ", grid.shape) print(" Rho dimensions : ", rho.shape) density = numpy.zeros((rho.shape[0], 10)) density[:, 0] = rho fpot = None pot = embfactory.get_potential(density) if (pberthaopt.debug): numpy.savetxt("initialpot.txt", pot) #DEBUG #pot=numpy.zeros(rho.shape[0]) if static_field: fpot = grid[:, fdir] * fmax fpot = numpy.ascontiguousarray(fpot, dtype=numpy.double) if (pberthaopt.debug): numpy.savetxt("initialfpot.txt", fpot) if not restart: if stdoutprint: #print("TEST density on grid") #print("Type density", type(density), density.shape) print("Scalar product", "density.weigt", numpy.dot(density[:, 0], grid[:, 3])) print("Dip x", "density.weigt", -1. * numpy.dot(density[:, 0] * grid[:, 3], grid[:, 0])) print("Dip y", "density.weigt", -1. * numpy.dot(density[:, 0] * grid[:, 3], grid[:, 1])) print("Dip z", "density.weigt", -1. * numpy.dot(density[:, 0] * grid[:, 3], grid[:, 2])) bertha.realtime_init() normalise = 1 dipx_mat, dipy_mat, dipz_mat = \ bertha.get_realtime_dipolematrix (0, normalise) occeigv = numpy.zeros((ndim, nocc), dtype=numpy.complex128) iocc = 0 for i in range(ndim): if i >= nshift and iocc < nocc: for j in range(ndim): occeigv[j, iocc] = eigem[j, i] iocc = iocc + 1 Da0 = numpy.matmul(occeigv, numpy.conjugate(occeigv.transpose())) if stdoutprint: print("Dump ground state unperturbed density " + pberthaopt.densityzero) if pberthaopt.densityzero != "": bertha.density_to_cube(Da0.T, pberthaopt.densityzero, \ drx=pberthaopt.drx, dry=pberthaopt.dry, drz=pberthaopt.drz, \ margin=pberthaopt.margin) dipx_ref = numpy.trace(numpy.matmul(Da0, dipx_mat)).real dipy_ref = numpy.trace(numpy.matmul(Da0, dipy_mat)).real dipz_ref = numpy.trace(numpy.matmul(Da0, dipz_mat)).real bertha.finalize() etotalnpa = numpy.zeros((4)) etotalnpa[0] = etotal etotalnpa[1] = dipx_ref etotalnpa[2] = dipy_ref etotalnpa[3] = dipz_ref numpy.savez(pberthaopt.restartfname, eigem=eigem, \ Da0=Da0, rho=rho, etotalnpa=etotalnpa) if stdoutprint: print("unperturbed Dip x ", dipx_ref) print("unperturbed Dip y ", dipy_ref) print("unperturbed Dip z ", dipz_ref) #if lin_emb=True, a single scf is performed at constant Vemb maxiter = 20 Dold = Da0 Da = Da0 Eold = etotal lin_emb = pberthaopt.linemb dipx_val = 0.0 dipy_val = 0.0 dipz_val = 0.0 dipx_mat = None dipy_mat = None dipz_mat = None for out_iter in range(maxiter): time_iter_start = time.time() process_time_iter_start = time.process_time() bertha.set_fnameinput(fnameinput) bertha.set_fittfname(fittfname) bertha.set_thresh(pberthaopt.thresh) bertha.set_verbosity(verbosity) bertha.set_dumpfiles(dumpfiles) bertha.set_densitydiff(1) bertha.init() ndim = bertha.get_ndim() nshift = bertha.get_nshift() nocc = bertha.get_nocc() sfact = bertha.get_sfact() nopen = bertha.get_nopen() # run with Vemb included if static_field: totpot = pot + fpot if nofde: totpot = fpot totpot = numpy.ascontiguousarray(totpot, dtype=numpy.double) if (pberthaopt.debug): numpy.savetxt("fullpot%d.txt" % (out_iter), totpot) bertha.set_embpot_on_grid(grid, totpot) else: if (pberthaopt.debug): numpy.savetxt("fullpot%d.txt" % (out_iter), pot) if nofde: pot = numpy.zeros_like(pot) bertha.set_embpot_on_grid(grid, pot) ovapm, eigem, fockm, eigen = bertha.run(eigem) etotal2 = bertha.get_etotal() # save the extern pot used in the scf run # pot_in = pot # the avg associated to pot emb_avg_in = numpy.dot(density[:, 0] * grid[:, 3], pot) #print if stdoutprint: print("") print( "total electronic energy = %30.15f ... outer iteration :%i" % ((etotal2 - (sfact * nocc)), (out_iter + 1))) print( "mean value of embed pot = %30.15f ... outer iteration :%i" % ((emb_avg_in), (out_iter + 1))) erep = bertha.get_erep() etotal = bertha.get_etotal() ecoul = bertha.get_eecoul() exc = bertha.get_eexc() if stdoutprint: print("outer iteration : ", out_iter + 1) print("total electronic energy = %30.15f" % (etotal - (sfact * nocc))) print("nuclear repulsion energy = %30.15f" % (erep)) print("total energy = %30.15f" % (etotal + erep - (sfact * nocc))) print("coulomb energy = %30.15f" % (ecoul)) print("Exc energy = %30.15f" % (exc)) if lin_emb: #rho = bertha.get_density_on_grid(grid) #density=numpy.zeros((rho.shape[0],10)) #density[:,0] = rho occeigv = numpy.zeros((ndim, nocc), dtype=numpy.complex128) iocc = 0 for i in range(ndim): if i >= nshift and iocc < nocc: for j in range(ndim): occeigv[j, iocc] = eigem[j, i] iocc = iocc + 1 Da = numpy.matmul(occeigv, numpy.conjugate(occeigv.transpose())) if stdoutprint: print("Dump ground state perturbed density " + pberthaopt.density) if pberthaopt.density != "": bertha.density_to_cube(Da.T, pberthaopt.density, drx=pberthaopt.drx, \ dry=pberthaopt.dry, drz=pberthaopt.drz, margin=pberthaopt.margin) bertha.realtime_init() normalise = 1 dipx_mat, dipy_mat, dipz_mat = \ bertha.get_realtime_dipolematrix (0, normalise) numofatom = bertha.get_natoms() tmpcoords = [] tmpz = [] for i in range(numofatom): tmpcoords.append(list(bertha.get_coords(i))[0:3]) tmpz.append(list(bertha.get_coords(i))[3]) matcoords = numpy.array(tmpcoords) vecZ = numpy.array(tmpz) vec_nuc_dip = numpy.matmul(vecZ.T, matcoords) nucdipx = vec_nuc_dip[0] nucdipy = vec_nuc_dip[1] nucdipz = vec_nuc_dip[2] bertha.finalize() break #if out_iter == (maxiter - 1): # bertha.finalize() # raise Exception("Maximum number of SCF cycles reached.\n") # calculate the embedding potential corresponding to the new density time_get_density_on_grid_start = time.time() process_time_get_density_on_grid_start = time.process_time() rho = bertha.get_density_on_grid(grid) time_get_density_on_grid_end = time.time() process_time_get_density_on_grid_end = time.process_time() print("Fitted density on grid time: %15.5f"%(time_get_density_on_grid_end - time_get_density_on_grid_start), \ " (CPU time: %15.5f"%(process_time_get_density_on_grid_end - process_time_get_density_on_grid_start), ") s ") density = numpy.zeros((rho.shape[0], 10)) density[:, 0] = rho pot_old = pot time_start = time.time() process_time_start = time.process_time() pot = embfactory.get_potential(density) time_end = time.time() process_time_end = time.process_time() print("Vemb pot on grid: embfactory.get_potential: %15.5f"%(time_end - time_start), \ " (CPU time: %15.5f"%(process_time_end - process_time_start), ") s ") #DEBUG #pot=numpy.zeros_like(rho) # the avg associated to new embed pot emb_avg = numpy.dot(density[:, 0] * grid[:, 3], pot) # form the density matrix occeigv = numpy.zeros((ndim, nocc), dtype=numpy.complex128) iocc = 0 #debug if stdoutprint: print("ndim : %i\n" % ndim) print("nshift : %i\n" % nshift) for i in range(ndim): if i >= nshift and iocc < nocc: for j in range(ndim): occeigv[j, iocc] = eigem[j, i] iocc = iocc + 1 Da = numpy.matmul(occeigv, numpy.conjugate(occeigv.transpose())) diffD = Da - Dold diffE = etotal2 - Eold norm_pot = numpy.sqrt(numpy.sum((pot - pot_old)**2)) norm_D = numpy.linalg.norm(diffD, 'fro') if stdoutprint: print("2-norm of diffD = ", norm_D, " ... outer iteration :%i" % (out_iter + 1)) print("E(actual)-E(prev)= ", diffE, " ... outer iteration :%i" % (out_iter + 1)) print("DE_emb(actual-prev) = %30.15f ... outer iteration :%i" % ((emb_avg_in - emb_avg), (out_iter + 1))) print("norm_pot(actual-prev) = %30.15f ... outer iteration :%i" % ((norm_pot), (out_iter + 1))) if (norm_D < (1.0e-6) and norm_pot < (1.0e-4)): #not needed? #iocc = 0 #for i in range(ndim): # if i >= nshift and iocc < nocc: # for j in range(ndim): # occeigv[j, iocc] = eigem[j, i] # iocc = iocc + 1 #Da = numpy.matmul(occeigv,numpy.conjugate(occeigv.transpose())) if stdoutprint: print("Dump ground state perturbed density density.cube") bertha.realtime_init() dipx_mat, dipy_mat, dipz_mat = bertha.get_realtime_dipolematrix( 0, normalise) if pberthaopt.density != "": bertha.density_to_cube(Da.T, pberthaopt.density, drx=pberthaopt.drx, \ dry=pberthaopt.dry, drz=pberthaopt.drz, margin=pberthaopt.margin) bertha.finalize() break time_iter_end = time.time() process_time_iter_end = time.process_time() print(" Time for each extrenal iteration: %15.5f"%(time_iter_end - time_iter_start), \ " (CPU time: %15.5f"%(process_time_iter_end - process_time_iter_start), ") s ") if out_iter == maxiter - 1: if pberthaopt.density != "": bertha.density_to_cube(Da.T, pberthaopt.density, drx=pberthaopt.drx, \ dry=pberthaopt.dry, drz=pberthaopt.drz, margin=pberthaopt.margin) Dold = Da Eold = etotal2 bertha.realtime_init() normalise = 1 dipx_mat, dipy_mat, dipz_mat = \ bertha.get_realtime_dipolematrix (0, normalise) """ Calculation of the Nuclear dipole (a.u) """ ##### print("Compute nuclear dipole (a.u.)") numofatom = bertha.get_natoms() tmpcoords = [] tmpz = [] for i in range(numofatom): tmpcoords.append(list(bertha.get_coords(i))[0:3]) tmpz.append(list(bertha.get_coords(i))[3]) matcoords = numpy.array(tmpcoords) vecZ = numpy.array(tmpz) vec_nuc_dip = numpy.matmul(vecZ.T, matcoords) nucdipx = vec_nuc_dip[0] nucdipy = vec_nuc_dip[1] nucdipz = vec_nuc_dip[2] bertha.finalize() dipx_val = numpy.trace(numpy.matmul(Da, dipx_mat)).real dipy_val = numpy.trace(numpy.matmul(Da, dipy_mat)).real dipz_val = numpy.trace(numpy.matmul(Da, dipz_mat)).real if stdoutprint: print("") print("Dip x ", dipx_val) print("Dip y ", dipy_val) print("Dip z ", dipz_val) print("MOLECULAR PROPERTIES of ACTIVE SYSTEM IN EMBEDDING:...") print(" ") print("Dipole Moment: ") print( "Axis electronic dipole (a.u.) nuclear dipole (a.u.) Total dipole (a.u.) Total dipole (Debye) " ) print(" x %20.10f %20.10f %20.10f %20.10f " % (dipx_val, nucdipx, dipx_val + nucdipx, (dipx_val + nucdipx) * 2.541580)) print(" y %20.10f %20.10f %20.10f %20.10f " % (dipy_val, nucdipy, dipy_val + nucdipy, (dipy_val + nucdipy) * 2.541580)) print(" z %20.10f %20.10f %20.10f %20.10f " % (dipz_val, nucdipz, dipz_val + nucdipz, (dipz_val + nucdipz) * 2.541580)) print(" ") tot_dip_vec = numpy.array( [dipx_val + nucdipx, dipy_val + nucdipy, dipz_val + nucdipz]) print("Molecular dipole module: %20.10f (a.u.) %20.10f (Debye) " % (numpy.linalg.norm(tot_dip_vec), numpy.linalg.norm(tot_dip_vec) * 2.541580)) print( "MOLECULAR PROPERTIES of ACTIVE SYSTEM WITHOUT EMBEDDING (free active system):..." ) print(" ") print("Dipole Moment: ") print( "Axis electronic dipole (a.u.) nuclear dipole (a.u.) Total dipole (a.u.) Total dipole (Debye) " ) print(" x %20.10f %20.10f %20.10f %20.10f " % (dipx_ref, nucdipx, dipx_ref + nucdipx, (dipx_ref + nucdipx) * 2.541580)) print(" y %20.10f %20.10f %20.10f %20.10f " % (dipy_ref, nucdipy, dipy_ref + nucdipy, (dipy_ref + nucdipy) * 2.541580)) print(" z %20.10f %20.10f %20.10f %20.10f " % (dipz_ref, nucdipz, dipz_ref + nucdipz, (dipz_ref + nucdipz) * 2.541580)) print(" ") tot_dip_vec = numpy.array( [dipx_ref + nucdipx, dipy_ref + nucdipy, dipz_ref + nucdipz]) print("Molecular dipole module: %20.10f (a.u.) %20.10f (Debye) " % (numpy.linalg.norm(tot_dip_vec), numpy.linalg.norm(tot_dip_vec) * 2.541580)) if stdoutprint: print("Dipole moment analitical: Tr(D dip_mat)") print("dipX_mat dim: %i,%i\n" % (dipx_mat.shape)) print("dipY_mat dim: %i,%i\n" % (dipy_mat.shape)) print("dipZ_mat dim: %i,%i\n" % (dipz_mat.shape)) print("Da dim: %i,%i\n" % (Da.shape)) print("TEST dipole moment from density on grid numerical integration") print(" ") #print("Type density", type(density), density.shape) print("Scalar product", "density.weigt", numpy.dot(density[:, 0], grid[:, 3])) print("Dip x", "density.weigt", -1. * numpy.dot(density[:, 0] * grid[:, 3], grid[:, 0])) print("Dip y", "density.weigt", -1. * numpy.dot(density[:, 0] * grid[:, 3], grid[:, 1])) print("Dip z", "density.weigt", -1. * numpy.dot(density[:, 0] * grid[:, 3], grid[:, 2])) print(" ") sys.stdout.flush() print("Final results of SplitSCF") for i in range(nocc + nopen): print("eigenvalue %5d %20.8f" % (i + 1, eigen[i + nshift] - sfact)) print(" lumo %20.8f" % (eigen[i + nshift + 1])) return ovapm, eigem, fockm, eigen, pot
import ctypes import numpy import sys import re import os.path from numpy.linalg import eigvalsh from scipy.linalg import eigh sys.path.insert(0, '../src/') import berthamod bertha = berthamod.pybertha("../../lib/bertha_wrapper.so") fittcoefffname = "fitcoeff.txt" vctfilename = "vct.txt" ovapfilename = "ovap.txt" fnameinput = "input.inp" fittfname = "fitt2.inp" verbosity = -1 dumpfiles = 1 bertha.set_fittcoefffname(fittcoefffname) bertha.set_ovapfilename(ovapfilename) bertha.set_vctfilename(vctfilename) bertha.set_fnameinput(fnameinput) bertha.set_fittfname(fittfname) bertha.set_verbosity(verbosity)
def normal_run(pberthaopt, args): import pyembmod print("Options: ") print(args) print("") print("") if not os.path.isfile(pberthaopt.wrapperso): print("SO File ", pberthaopt.wrapperso, " does not exist") return False ovapm, eigem, fockm, eigen, pot = pyberthaembed.runspberthaembed( pberthaopt, restart=False, stdoutprint=True) print("CHECK") print("eigem dim: %i,%i\n" % (eigem.shape[0], eigem.shape[1])) if ovapm is None: return False # emfactory -> embedding potential corresponding to Da activefname = pberthaopt.activefile if not os.path.isfile(activefname): raise Exception("File ", activefname, " does not exist") envirofname = pberthaopt.envirofile if not os.path.isfile(envirofname): raise Exception("File ", envirofname, " does not exist") embfactory = pyembmod.pyemb(activefname, envirofname, 'adf') #jobtype='adf' is default de facto #grid_param =[50,110] # psi4 grid parameters (see Psi4 grid table) #embfactory.set_options(param=grid_param, \ embfactory.set_options(param=pberthaopt.param, \ gtype=pberthaopt.gtype, basis=pberthaopt.basis) embfactory.set_enviro_func(pberthaopt.excfuncenv) # several paramenters to be specified in input- e.g AUG/ADZP for ADF, aug-cc-pvdz for psi4 embfactory.initialize() grid = embfactory.get_grid() bertha = berthamod.pybertha(pberthaopt.wrapperso) bertha.init() ndim = bertha.get_ndim() nshift = bertha.get_nshift() nocc = bertha.get_nocc() # just an additional restart, so we can call bertha.realtime_init() bertha.set_embpot_on_grid(grid, pot) #the newly converged eigem and rho ovapm, eigem, fockm, eigen = bertha.run(eigem) rho = bertha.get_density_on_grid(grid) density = numpy.zeros((rho.shape[0], 10)) density[:, 0] = rho # the embedding potential from converged density pot = embfactory.get_potential(density) bertha.set_embpot_on_grid(grid, pot) bertha.realtime_init() print("Start RT") debug = args.debug dt = args.dt t_int = args.totaltime niter = int(t_int / dt) print("Debug: ", debug) print("dt : ", dt) print("ndim : ", ndim) print("nocc : ", nocc) print("Total time : ", t_int) print("Number of iterations: ", niter) sys.stdout.flush() ene_list = [] dip_list = [] weight_list = [] imp_list = [] Enuc_list = [] C = eigem D_0 = numpy.zeros((ndim, ndim), dtype=numpy.complex128) for num in range(nocc): D_0[num + nshift, num + nshift] = 1.0 + 0.0j fo = sys.stderr if debug: fo = open("debug_info.txt", "w") #print type(eigem) #C_inv used to backtransform D(AO) try: C_inv = numpy.linalg.inv(eigem) except LinAlgError: print("Error in numpy.linalg.inv of eigem") return False if debug: test = numpy.matmul(C_inv, eigem) fo.write("Check if atol is 1.e-14 for inversion of C: %s\n"% \ numpy.allclose(numpy.eye((ndim),dtype=numpy.complex128), \ test,atol=1.e-14)) if debug: diff = test - numpy.eye((ndim), dtype=numpy.complex128) mdiff = numpy.max(diff) fo.write(" maxdiff is: %.12e %.12e\n" % (mdiff.real, mdiff.imag)) if debug: test = numpy.matmul(numpy.conjugate(C.T), numpy.matmul(ovapm, C)) fo.write("Check orthonormal orbitals (atol = 1.e-14): %s\n"% \ numpy.allclose(numpy.eye((ndim),dtype=numpy.complex128), \ test, atol=1.e-14)) diff = test - numpy.eye((ndim), dtype=numpy.complex128) mdiff = numpy.max(diff) fo.write(" maxdiff is: %.12e %.12e\n" % (mdiff.real, mdiff.imag)) #build density in ao basis occeigv = numpy.zeros((ndim, nocc), dtype=numpy.complex128) iocc = 0 for i in range(ndim): if i >= nshift and iocc < nocc: for j in range(ndim): occeigv[j, iocc] = eigem[j, i] iocc = iocc + 1 Da = numpy.matmul(occeigv, numpy.conjugate(occeigv.transpose())) print("") print("Dump ground state density density0.cube") bertha.density_to_cube(Da.T, "density0.cube", margin=5.0) print("Done") if debug: #check trace(S Da) trace_ds = numpy.trace(numpy.matmul(Da, ovapm)) trace_dsfock = numpy.trace(numpy.matmul(Da, fockm)) fo.write("Density matrix trace at t0: %.12e %.12e \n" % (trace_ds.real, trace_ds.imag)) fo.write("Trace of fock*density at t0: %.12e %.12e \n" % (trace_dsfock.real, trace_dsfock.imag)) normalise = 1 dip_mat = None dipx_mat, dipy_mat, dipz_mat = \ bertha.get_realtime_dipolematrix (0, normalise) if (args.direction == 4): dip_mat = dipx_mat elif (args.direction == 3): dip_mat = dipy_mat elif (args.direction == 2): dip_mat = dipz_mat if debug: fockmh = numpy.conjugate(fockm.T) diff_fockmh = fockm - fockmh mdiff = numpy.max(diff_fockmh) fo.write("Check max diff fockm-fockmh: %.12e %.12e\n"%\ (mdiff.real, mdiff.imag)) fo.write("Fockm (t=0) is hermitian: %s \n" % numpy.allclose(fockm, fockmh, atol=1.e-15)) molist = args.select.split("&") occlist = molist[0].split(";") occlist = [int(m) for m in occlist] virtlist = molist[1].split(";") virtlist = [int(m) for m in virtlist] if (args.pulse == "analytic"): Amp = args.pulseFmax # to check dipz_mo = numpy.matmul(numpy.conjugate(C.T), numpy.matmul(dip_mat, C)) if args.select_pert: dipz_mo = rtutil.dipole_selection(dipz_mo, nshift, nocc, occlist, virtlist, fo, debug) print(" Perturb with analytic kick ") u0 = rtutil.exp_opmat(dipz_mo, numpy.float_(-Amp), debug, fo) Dp_init = numpy.matmul(u0, numpy.matmul(D_0, numpy.conjugate(u0.T))) #transform back Dp_int Da = numpy.matmul(C, numpy.matmul(Dp_init, numpy.conjugate(C.T))) D_0 = Dp_init print("Start first mo_fock_mid_forwd_eval ") print("CHECK") print("C dim : %i,%i\n" % (C.shape[0], C.shape[1])) print("C^-1 dim : %i,%i\n" % (C_inv.shape[0], C_inv.shape[1])) fock_mid_init = rtutil.mo_fock_mid_forwd_eval(bertha,Da,fockm,0,numpy.float_(dt),\ dip_mat,C,C_inv,ovapm,ndim, debug, fo, args.pulse, args.pulseFmax, args.pulsew, args.t0, args.pulseS, args.propthresh) if (fock_mid_init is None): print("Error accurs in mo_fock_mid_forwd_eval") return False if debug: fock_mid_h = numpy.conjugate(fock_mid_init.T) diff_fock_mid_h = fock_mid_init - fock_mid_h fo.write("Max diff fock_mid_init-fock_mid_h" % (numpy.max(diff_fock_mid_h))) fo.write('Fockm (t=1/2) is hermitian: %s\n' % numpy.allclose(fock_mid_init, fock_mid_h, atol=1.e-14)) fockp_mid_init = numpy.matmul(numpy.conjugate(C.T), numpy.matmul(fock_mid_init, C)) u = rtutil.exp_opmat(fockp_mid_init, numpy.float_(dt), debug, fo) #u=rtutil.exp_opmat(fockp_mid_init,numpy.float_(dt),debug,fo) #u=scila.expm(-1.j*fockp_mid_init*dt) temp = numpy.matmul(D_0, numpy.conjugate(u.T)) Dp_t1 = numpy.matmul(u, temp) #check u if unitary if debug: test_u = numpy.matmul(u, numpy.conjugate(u.T)) fo.write('U is unitary : %s' % numpy.allclose(test_u, numpy.eye(u.shape[0]), atol=1.e-14)) #backtrasform Dp_t1 D_t1 = numpy.matmul(C, numpy.matmul(Dp_t1, numpy.conjugate(C.T))) if debug: diff = D_t1 - Da mdiff = numpy.max(diff) fo.write("Max diff density: %.12e %.12e \n" % (mdiff.real, mdiff.imag)) dip_list.append(numpy.trace(numpy.matmul(Da, dip_mat))) dip_list.append(numpy.trace(numpy.matmul(D_t1, dip_mat))) if (args.pulse == "analytic"): if (occlist[0] != -2): #dipoleanalysis res = rtutil.dipoleanalysis(dipz_mo, D_0, occlist, virtlist, nshift, fo, debug) weight_list.append(res) res = rtutil.dipoleanalysis(dipz_mo, Dp_t1, occlist, virtlist, nshift, fo, debug) weight_list.append(res) if debug: fo.write("Dipole: %.12e\n" % (numpy.trace(numpy.matmul(Da, dip_mat))).real) fo.write("Dipole: %.12e\n" % (numpy.trace(numpy.matmul(D_t1, dip_mat))).real) if debug: tfock = numpy.trace(numpy.matmul(D_t1, fockm)) fo.write("Trace fock*density t1: %.12e, %.12e\n" % (tfock.real, tfock.imag)) trace_ds = numpy.trace(numpy.matmul(D_t1, ovapm)) fo.write(" Traceds: %.12e %.12ei\n" % (trace_ds.real, trace_ds.imag)) Ndip_z = 0.0 #estrarre le 3 componenti del dipolo nucleare D_ti = D_t1 Dp_ti = Dp_t1 #aggiungere repulsione nucleare #Enuc_list.append(-func_t0*Ndip_z+Nuc_rep) #just in case of non-zero nuclear dipole start = time.time() cstart = time.process_time() fockm_ti = bertha.get_realtime_fock(D_ti.T) end = time.time() cend = time.process_time() print("RealTime Fock Time: %15.5f" % (end - start), " (CPU: %15.5f" % (cend - cstart), " ) s") print("RealTime Fock Time Without Py: %15.5f"%(bertha.get_focktime()), \ " (CPU: %15.5f"%(bertha.get_fockctime()), " ) s") print("") ene_list.append(numpy.trace(numpy.matmul(Da, fockm))) ene_list.append(numpy.trace(numpy.matmul(D_ti, fockm_ti))) print("Starting iterations ...") print("") fock_mid_backwd = numpy.copy(fock_mid_init) return run_iterations_from_to (1, niter, bertha, embfactory, args, fock_mid_backwd, \ dt, dip_mat, C, C_inv, ovapm, ndim, debug, Dp_ti, dip_list, ene_list, \ weight_list, fo, D_ti, occlist)
def runspberthaembedrt(pberthaopt): sys.path.insert(0, pberthaopt.berthamodpath) import berthamod print("Options: ") for att in [a for a in dir(pberthaopt) if not a.startswith('__')]: print(att, " = ", getattr(pberthaopt, att)) print("") print("") print("") if not os.path.isfile(pberthaopt.wrapperso): print("SO File ", pberthaopt.wrapperso, " does not exist") exit(1) bertha = berthamod.pybertha(pberthaopt.wrapperso) fittcoefffname = pberthaopt.fitcoefffile vctfilename = pberthaopt.vctfile ovapfilename = pberthaopt.ovapfile fnameinput = pberthaopt.inputfile if not os.path.isfile(fnameinput): print("File ", fnameinput, " does not exist") exit(1) fittfname = pberthaopt.fittfile if not os.path.isfile(fittfname): print("File ", fittfname, " does not exist") exit(1) verbosity = pberthaopt.verbosity dumpfiles = int(pberthaopt.dumpfiles) bertha.set_fittcoefffname(fittcoefffname) bertha.set_ovapfilename(ovapfilename) bertha.set_vctfilename(vctfilename) bertha.set_fnameinput(fnameinput) bertha.set_fittfname(fittfname) bertha.set_thresh(pberthaopt.thresh) bertha.set_verbosity(verbosity) bertha.set_dumpfiles(dumpfiles) bertha.set_densitydiff(1) bertha.init() ndim = bertha.get_ndim() nshift = bertha.get_nshift() nocc = bertha.get_nocc() sfact = bertha.get_sfact() nopen = bertha.get_nopen() print("Verbosity : ", verbosity) print("Dumpfiles : ", dumpfiles) print("") print("Matrix dimension: ", ndim) print(" nocc: ", nocc) print(" nshift: ", nshift) print(" nopen: ", nopen) print(" level shift: ", sfact) print("") #generate a sample grid npoints = 10 grid = numpy.zeros((npoints, 4)) grid = numpy.ascontiguousarray(grid, dtype=numpy.double) pot = numpy.zeros(npoints) pot = numpy.ascontiguousarray(pot, dtype=numpy.double) x = -1.0 y = -100.0 z = -1000.0 w = 1.0 for i in range(npoints): grid[i, 0] = x grid[i, 1] = y grid[i, 2] = z grid[i, 3] = w x += 1.0 y += 1.0 z += 1.0 w += 0.1 start = time.time() cstart = time.process_time() bertha.set_embpot_on_grid(grid, pot) #main run here ovapm, eigem, fockm, eigen = bertha.run() density = bertha.get_density_on_grid(grid) for i in range(npoints): val = grid[i, 0] * grid[i, 1] * grid[i, 2] * grid[i, 3] print("Python L: %15.5f vs %15.5f" % (density[i], val)) end = time.time() cend = time.process_time() print("Totaltime: ", end - start, " (CPU time: ", cend - cstart, ") s ") print("MainRun Time: ", bertha.get_mainruntime() , \ " (CPU time: " , bertha.get_mainrunctime(), ") s ") sys.stdout.flush()