def read_input(cwd, input_file_path): # Read parameter from input.in file cfg = configparser.ConfigParser(delimiters=('=', ':'), comment_prefixes=('#', ';')) cfg.read(input_file_path) # Read file par = dict(cfg.items("Settings", raw=False)) # Get rid of inline comments [0] and strip spaces for p in par: par[p] = par[p].split("#", 1)[0].strip(" ") # Check for ab initio interface file xxx.sh abinit_file = "ABINITIO/{}".format(par['abinitio']) ab_initio_file_path = os.path.join(cwd, abinit_file) if (not os.path.isfile(ab_initio_file_path)): error_exit(5, " ") try: par['natoms'] par['nstates'] par['maxsteps'] par['init_state'] par['abinitio'] except KeyError as ke: error_exit(12, str(ke)) return (par, ab_initio_file_path)
def calc_prob(instate, outstate, pot_eners_array, dt): """ Calculate probability for all posible hops PHYSICAL REVIEW A 84, 014701 (2011) Nonadiabatic nuclear dynamics of atomic collisions based on branching classical trajectories Andrey K. Belyaev1,2 and Oleg V. Lebedev1 """ #print("Instate {}, Outstate {}".format(instate, outstate)) # energy gap in time T-DT [0], T [1], T+DT [2] prob = 0.0000 Z = [(abs(pot_eners_array[step][instate] - pot_eners_array[step][outstate])) for step in range(0,3)] #print("Z[-dt]: {:.4f} Z[t]: {:.4f} Z[dt]: {:.4f}".format(Z[0],Z[1],Z[2])) # three point minima of adiaabatic splitting Zjk if Z[0] > Z[1] and Z[1] < Z[2]: sec_der = ((Z[2] - 2 * Z[1] + Z[0]) / (dt ** 2)) prob = math.exp(-math.pi/(2 * HBAR_AU) * (math.sqrt(Z[1] ** 3 / sec_der))) if prob > 1.00: error_exit(6) print("Z({}->{}) minimum with".format(instate, outstate), "dE/a.u. = {}. ".format(Z[1]), #"Second derivative at minima: {},".format(sec_der), #"Z**3: {}".format( Z[1]**3), "Probability: {}".format(prob)) return([instate, outstate, Z[1], prob])
def read_geoms(natoms, geom_file_path): #if restart == 1 : read last two geoms x = np.zeros(natoms, dtype=np.float64) y = np.zeros(natoms, dtype=np.float64) z = np.zeros(natoms, dtype=np.float64) at_names = [] # READ INITIAL POSITIONS: with open(geom_file_path, 'r') as igf: # igf input geom file atoms = igf.readline() # first line in geom file is number of atoms try: int(atoms) except ValueError as VE: error_exit(14, str(VE)) if not (int(atoms) == natoms): error_exit(2, " ") igf.readline() # comment line for iat in range(0, natoms): line = igf.readline().split() at_names.append(capitalize_2th(str(line[0]))) x[iat] = np.float64(line[1]) * ANG_BOHR # atomic units : Bohr y[iat] = np.float64(line[2]) * ANG_BOHR z[iat] = np.float64(line[3]) * ANG_BOHR igf.close() return (at_names, x, y, z)
def calc_energies( step, natoms, am, state, pot_eners, vx, vy, vz, Etot_init, Etot_prev, ener_thresh): Ekin = calc_ekin(natoms, am, vx, vy, vz) Epot = pot_eners[state] # state 0(GS), 1 (1.ex. state),.. Etot = Ekin + Epot dE = (Etot - Etot_init) dE_step = (Etot - Etot_prev) if abs(dE * AU_EV) >= ener_thresh and step > 1: error_exit(7, "Total energy change since start {} larger then threshold {}.".format(dE * AU_EV, ener_thresh)) return(Ekin, Epot, Etot, dE, dE_step)
def file_check(cwd): # input files names - these are defaults otherwise not found veloc_file = "veloc.in" geom_file = "geom.in" input_file = "input.in" # absolute path to the files input_file_path = os.path.join(cwd, input_file) geom_file_path = os.path.join(cwd, geom_file) vel_file_path = os.path.join(cwd, veloc_file) if (not os.path.isfile(input_file_path)): error_exit(0, " ") if (not os.path.isfile(geom_file_path)): error_exit(1, " ") if (not os.path.isfile(vel_file_path)): init_vel = 0 else: init_vel = 1 return (input_file_path, geom_file_path, vel_file_path, init_vel)
def read_velocs(init_vel, natoms, vel_file_path): vx = np.zeros(natoms, dtype=np.float64) vy = np.zeros(natoms, dtype=np.float64) vz = np.zeros(natoms, dtype=np.float64) if init_vel: with open(vel_file_path, 'r') as ivf: atoms = ivf.readline() # first line is number of atoms try: int(atoms) except ValueError as VE: error_exit(14, str(VE)) if not (int(atoms) == natoms): error_exit(2, " ") garbage = ivf.readline() # second comment line for iat in range(0, natoms): line = ivf.readline().split() vx[iat] = float(line[1]) vy[iat] = float(line[2]) vz[iat] = float(line[3]) ivf.close() return (vx, vy, vz)
def check_restart_files(restart, cwd): rst_file = "restart.in" rst_file_path = os.path.join(cwd, rst_file) if restart < 0: error_exit(11, "(restart < 0)") # elif restart == 0 dealt in check_output_files #elif restart == 1: # rst_file_path = os.path.join(cwd, rst_file) # if (os.path.isfile(rst_file_path)): # print("Restart={}, start from the last completed".format(restart), # "step.\nRestart file {} found.".format(rst_file)) # else: # error_exit(10, "({})".format(rst_file)) elif restart > 0: rst_file = "restart_{}.in".format(restart) rst_file_path = os.path.join(cwd, rst_file) if (os.path.isfile(rst_file_path)): print("Restart={}".format(restart), "\nRestart file {} found".format(rst_file)) else: error_exit(10, "({})".format(rst_file)) return (rst_file_path)
import os import sys try: from constants import * from errors import error_exit except ImportError as ime: error_exit(19, "Module {} in {} not found.".format(ime, current_module)) try: tera_mpi = int(os.environ['MPI_TERA']) except KeyError as ke: print( "MPI_TERA variable was not exported, assuming MPI_TERA=0. Warning: this may cause deadlock if MPI has been already initiated" ) tera_mpi = 0 if tera_mpi: from tera_propagates import global_except_hook sys.excepthook = global_except_hook # --------------------------------------------------------------------------------------------------------------------------------------------- def print_positions(step, sim_time, natoms, at_names, x, y, z, mov_file): mov = mov_file header = ("{} \n".format(natoms)) mov.write(header) comment = ("Step: {} Time_fs: {}\n".format(step, sim_time)) mov.write(comment) xx = (x * BOHR_ANG).tolist() yy = (y * BOHR_ANG).tolist() zz = (z * BOHR_ANG).tolist() for iat in range(0, natoms):
def read_restart(rst_file_path, natoms, nstates, tera_mpi): # TO DO: should be done with far less condiotion, however there would have to be another convertion from disctionary to variables of different types print("Reading restart data...") err = "0" rst_file = rst_file_path #step, state, Ekin, Epot, Etot, Etot_init, pnum, vnum, fnum, peanum, blob_size, civec_size, nbf_size, monum, civecnum, blobnum = None with open(rst_file_path, 'r') as rstf: for num, line in enumerate(rstf): if re.search(r'Step', str(line)): step = int(line.split()[1]) if re.search(r'State', str(line)): state = int(line.split()[1]) if re.search(r'Ekin', str(line)): Ekin = float(line.split()[1]) if re.search(r'Epot', str(line)): Epot = float(line.split()[1]) if re.search(r'Etot', str(line)): Etot = float(line.split()[1]) if re.search(r'Etot_init', str(line)): Etot_init = float(line.split()[1]) if re.search(r'Positions', str(line)): pnum = num if re.search(r'Velocities', str(line)): vnum = num if re.search(r'Forces', str(line)): fnum = num if re.search(r'Pot_eners_array', str(line)): peanum = num # TC WF if re.search(r'blob_size', str(line)): blob_size = int(line.split()[1]) if re.search(r'civec_size', str(line)): civec_size = int(line.split()[1]) if re.search(r'nbf_size', str(line)): nbf_size = int(line.split()[1]) if re.search(r'MO', str(line)): monum = num if re.search(r'CiVecs', str(line)): civecnum = num if (re.search(r'Blob:$', str(line))): blobnum = num try: if not None in (step, state, Ekin, Epot, Etot, Etot_init, pnum, vnum, fnum, peanum, blob_size, civec_size, nbf_size, monum, civecnum, blobnum): print("- all restart options found.") except Exception as ne: error_exit(17, str(ne)) try: atnames = np.genfromtxt(rst_file, dtype=np.dtype('str'), skip_header=pnum + 1, max_rows=natoms, usecols=[0]) at_names = atnames.tolist() pot_eners_array = np.genfromtxt(rst_file, dtype=np.float64, skip_header=peanum + 1, max_rows=2, usecols=(x for x in range(nstates))) fx = np.genfromtxt(rst_file, dtype=np.float64, skip_header=fnum + 1, max_rows=natoms, usecols=[1]) fy = np.genfromtxt(rst_file, dtype=np.float64, skip_header=fnum + 1, max_rows=natoms, usecols=[2]) fz = np.genfromtxt(rst_file, dtype=np.float64, skip_header=fnum + 1, max_rows=natoms, usecols=[3]) x = np.genfromtxt(rst_file, dtype=np.float64, skip_header=pnum + 1, max_rows=natoms, usecols=[1]) y = np.genfromtxt(rst_file, dtype=np.float64, skip_header=pnum + 1, max_rows=natoms, usecols=[2]) z = np.genfromtxt(rst_file, dtype=np.float64, skip_header=pnum + 1, max_rows=natoms, usecols=[3]) vx = np.genfromtxt(rst_file, dtype=np.float64, skip_header=vnum + 1, max_rows=natoms, usecols=[1]) vy = np.genfromtxt(rst_file, dtype=np.float64, skip_header=vnum + 1, max_rows=natoms, usecols=[2]) vz = np.genfromtxt(rst_file, dtype=np.float64, skip_header=vnum + 1, max_rows=natoms, usecols=[3]) if tera_mpi: #CiVecs = np.zeros((civec_size, nstates),dtype=np.float64) CiVecs = np.genfromtxt(rst_file, dtype=np.float64, skip_header=civecnum + 1, max_rows=civec_size, usecols=(x for x in range(nstates))) #MO = np.zeros((nbf_size, nbf_size),dtype=np.float64) MO = np.genfromtxt(rst_file, dtype=np.float64, skip_header=monum + 1, max_rows=nbf_size, usecols=(x for x in range(nbf_size))) #blob = np.zeros((blob_size),dtype=np.float64) blob = np.genfromtxt(rst_file, dtype=np.float64, skip_header=blobnum + 1, max_rows=blob_size, usecols=0) else: CiVecs, MO, blob = 0, 0, 0 except Exception as expt: error_exit(16, str(expt)) else: print("- all restart data read.") rstf.closed #pot_eners_array = np.loadtxt(rst_file, dtype=np.float64, delimiter=None, skiprows=8) np.set_printoptions(precision=10, formatter={'float': '{: 0.8f}'.format}) #print(at_names) #print("XYZ:\n{}".format(np.dstack((x,y,z)))) #print("VX VY VZ:\n{}".format(np.dstack((vx,vy,vz)))) #print("FX FY FZ:\n{}".format(np.dstack((fx,fy,fz)))) #print("Pot ener step-1/step \n{}".format(pot_eners_array)) return (step, at_names, state, x, y, z, vx, vy, vz, fx, fy, fz, Ekin, Epot, Etot, Etot_init, pot_eners_array, CiVecs, MO, blob, civec_size, nbf_size, blob_size)
print_positions, print_velocities, print_snafu, print_state, print_energies, print_pes) from propagates import ( # main MD routines calc_forces, calc_energies, update_velocities, update_positions, rescale_velocities, adjust_velocities, calc_ekin) from landauzener import ( # LZ Hopping algorithm calc_hopp) from restarts import ( # all restart routines print_restart, check_restart_files, read_restart) from constants import * # conversion factors, e.g. BOHR to ANG units from defaults import * # default values for the code, import only here except ImportError as ime: # if some of the following imports fails during in-modules-import: ImportError raise None # module could have been removed or different module name, e.g. renamed in module file if ime.name is None: error_exit(19, "Import or internal error in some module {}.".format(ime)) else: print("Module {} not found!!!".format(ime.name), "Make sure that {} contains snafu folder".format(SNAFU_EXE), "with: {}.".format('\n'.join(modules_files)), "\nOr check import in the wrong module") error_exit(19, "Some python file probably missing {}".format(ime)) else: print_snafu() print("\nAll modules loaded.") # ---------------INITIALIZATION PART - READING INPUTS-------------------------------------------------------- if __name__ == "__main__": print( "Simulation started at: {}".format(startTime), "\nPython: {} version {}".format(sys.base_exec_prefix,
def check_output_file(cwd, natoms, restart, init_step, write_freq): if (restart == 1): backup_output_files(cwd, restart) elif (restart > 1): backup_output_files(cwd, restart) truncate_output_files( init_step - 1, write_freq, natoms ) # -1 because init_step is set for restart (MD) loop with step +1 elif (restart == 0): if (os.path.isfile("movie.xyz")): error_exit(8, "movie.xyz") if (os.path.isfile("velocities.xyz")): error_exit(8, "velocities.xyz") if (os.path.isfile("energies.dat")): error_exit(8, "energies.dat") if (os.path.isfile("PES.dat")): error_exit(8, "PES.dat") if (os.path.isfile("state.dat")): error_exit(8, "state.dat") if (os.path.isfile("restart.in")): error_exit(8, "restart.in") return ()
def calc_forces(step, at_names, state, nstates, x, y, z, fx_new, fy_new, fz_new, pot_eners, ab_initio_file_path, tera_mpi, comm, sim_time, MO, CiVecs, NAC, blob, SMatrix, civec_size, nbf_size, blob_size, qmcharges, TDip, Dip): """ Call external script to calculate ab initio properties (force, energies) state = current state at current PES """ natoms = len(x) grad = -1 if not tera_mpi: # GRADIENT/FORCES check if re.search(r'g09', ab_initio_file_path) or re.search(r'gaus', ab_initio_file_path) or re.search(r'forces', ab_initio_file_path): grad = 1 # gaus exports forces -1 # Create geom file for which the forces will be calculated abinit_geom_file = "abinit_geom.xyz" with open (abinit_geom_file, "w") as agf: for iat in range(0,natoms): line = ("".join("%2s %2.16e %2.16e %2.16e\n" % (at_names[iat],x[iat]/ANG_BOHR,y[iat]/ANG_BOHR,z[iat]/ANG_BOHR))) agf.write(line) agf.closed # CALL EXTERNAL AB-INITIO CALCULATIONS abinit_inputs = "{} {} {} {} {} {}".format(ab_initio_file_path, abinit_geom_file, natoms, state, nstates, step) try: subprocess.run(abinit_inputs, stdout=None, stderr=subprocess.PIPE, shell = True, check = True) except subprocess.CalledProcessError as cpe: #print( error_exit(4,str("Return code: {}\nError: {}".format(cpe.returncode, cpe.stderr))) try: with open ("gradients.dat", "r") as gef: for st in range(0, nstates): pot_eners[st] = float(gef.readline()) for iat in range(0, natoms): line = gef.readline().split(" ") # FX FY FZ, gradient to forces fx_new[iat] = grad*np.float64(line[0]) fy_new[iat] = grad*np.float64(line[1]) fz_new[iat] = grad*np.float64(line[2]) gef.closed except: error_exit(4, "Ancaught error in ab initio. Check output file.") # e.g. molpro exit status might be overwritten by files procedures else: try: send_tera(comm, natoms, nstates, state, sim_time, x ,y, z, MO, CiVecs, blob, civec_size, nbf_size, blob_size) fx_new, fy_new, fz_new, pot_eners, MO, CiVecs, blob = receive_tera(comm, natoms, nstates, state, pot_eners, fx_new, fy_new, fz_new, MO, CiVecs, blob, SMatrix, NAC, TDip, Dip, qmcharges, civec_size, nbf_size, blob_size) fx_new = grad*fx_new fy_new = grad*fy_new fz_new = grad*fz_new except Exception as excpt: try: finish_tera(comm) print("Error during sending/receive TC data {}".format(excpt)) finally: exit_tera() return(fx_new , fy_new, fz_new, pot_eners, MO, CiVecs, blob)