def cif(name): path = os.path.join(tmpdir, name) if not os.path.isfile(path): id = int(name[:-4]) atoms = db.get_atoms(id) atoms.write(path) return send_from_directory(tmpdir, name)
def xyz(id): fd = io.StringIO() from ase.io.xyz import write_xyz db = database() write_xyz(fd, db.get_atoms(id)) data = fd.getvalue() return data, '{0}.xyz'.format(id)
def main(): db = ase.db.connect("ce_hydrostatic.db") volumes = [] concs = [] for row in db.select(converged=1): atoms = db.get_atoms(id=row.id) volumes.append(volume(atoms)) concs.append(mg_conc(atoms)) lattice_params = [fcc_lattice_parameter_from_volume_primitive_cell(V,64) for V in volumes] fname = "almg_lattice_parameter.csv" # From J. L. Murray, The Al-Mg system, 1982 data = np.loadtxt( fname, delimiter=",") mg_conc_exp = data[:,0] lattice_param_exp = data[:,1]*10 slope, interscept, r_value, p_value, stderr = linregress( concs, lattice_params ) print (slope,interscept) x = np.linspace(0.0,0.6,10) fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(x,interscept+slope*x) ax.plot( concs, lattice_params, 'o', label="DFT", mfc="none" ) ax.plot( mg_conc_exp, lattice_param_exp, 'x', label="Exp") ax.legend(loc="best", labelspacing=0.05, frameon=False) ax.set_xlabel("Mg concentration") ax.set_ylabel("FCC lattice parameter") ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) plt.show()
def xyz(project, id): fd = io.StringIO() from ase.io.xyz import write_xyz db = databases[project] write_xyz(fd, db.get_atoms(id)) data = fd.getvalue() return data, '{}.xyz'.format(id)
def image(name): path = os.path.join(tmpdir, name) if not os.path.isfile(path): id = int(name[:-4]) atoms = db.get_atoms(id) atoms2png(atoms, path) return send_from_directory(tmpdir, name)
def cif(name): id = int(name[:-4]) name = prefix() + name path = op.join(tmpdir, name) if not op.isfile(path): db = database() atoms = db.get_atoms(id) atoms.write(path) return send_from_directory(tmpdir, name)
def cif(project, name): id = int(name[:-4]) name = project + '-' + name path = op.join(tmpdir, name) if not op.isfile(path): db = databases[project] atoms = db.get_atoms(id) atoms.write(path) return send_from_directory(tmpdir, name)
def image(name): id = int(name[:-4]) name = prefix() + name path = op.join(tmpdir, name) if not op.isfile(path): db = database() atoms = db.get_atoms(id) atoms2png(atoms, path) return send_from_directory(tmpdir, name)
def main(runID): db = ase.db.connect(db_name()) atoms = db.get_atoms(id=runID) row = db.get(id=runID) n_kpt = row.n_kpt cutoff = row.cutoff calc = gp.GPAW(mode=gp.PW(cutoff), xc="PBE", kpts=(n_kpt, n_kpt, n_kpt), nbands="120%") atoms.set_calculator(calc) energy = atoms.get_potential_energy() db.update(runID, trial_energy=energy)
def image(name): path = os.path.join(tmpdir, name).encode() if not os.path.isfile(path): id = int(name[:-4]) atoms = db.get_atoms(id) if atoms: size = atoms.positions.ptp(0) i = size.argmin() rotation = ["-90y", "90x", ""][i] size[i] = 0.0 scale = min(20, 20 / size.max() * 10.0) else: scale = 20 rotation = "" write_png(path, atoms, show_unit_cell=1, rotation=rotation, scale=scale) return send_from_directory(tmpdir, name)
def image(name): path = os.path.join(tmpdir, name).encode() if not os.path.isfile(path): id = int(name[:-4]) atoms = db.get_atoms(id) if atoms: size = atoms.positions.ptp(0) i = size.argmin() rotation = ['-90y', '90x', ''][i] size[i] = 0.0 scale = min(20, 20 / size.max() * 10.0) else: scale = 20 rotation = '' write_png(path, atoms, show_unit_cell=1, rotation=rotation, scale=scale) return send_from_directory(tmpdir, name)
def main(argv): relax_atoms = (argv[1] == "atoms") runID = int(argv[0]) print("Running job: %d" % (runID)) db_name = db_name_atoms #db_name = "/home/ntnu/davidkl/Documents/GPAWTutorials/ceTest.db" db = ase.db.connect(db_name) new_run = not db.get(id=runID).key_value_pairs["started"] # Update the databse db.update(runID, started=True, converged=False) atoms = db.get_atoms(id=runID) calc = EAM(potential="/home/davidkl/Documents/EAM/mg-al-set.eam.alloy") atoms.set_calculator(calc) init_energy = atoms.get_potential_energy() logfile = "CE_eam/ceEAM%d.log" % (runID) traj = "CE_eam/ceEAM%d.traj" % (runID) trajObj = Trajectory(traj, 'w', atoms) if (relax_atoms): relaxer = BFGS(atoms, logfile=logfile) relaxer.attach(trajObj) relaxer.run(fmax=0.025) energy = atoms.get_potential_energy() else: res = minimize(target_function, x0=4.05, args=(atoms, )) a = res["x"] atoms = set_cell_parameter(atoms, a) energy = atoms.get_potential_energy() print("Final energy: {}, final a_la: {}".format(energy, a)) row = db.get(id=runID) del db[runID] kvp = row.key_value_pairs kvp["init_energy"] = init_energy runID = db.write(atoms, key_value_pairs=kvp) db.update(runID, converged=True) print("Energy: %.2E eV/atom" % (energy / len(atoms))) print("Initial energy: %.2E eV/atom" % (init_energy / len(atoms)))
def main(argv): relax_mode = "both" # both, cell, positions system = "AlMg" runID = int(argv[0]) nkpt = int(argv[1]) single_point = False if (len(argv) >= 3): single_point = (int(argv[2]) == 1) print("Running job: %d" % (runID)) db_paths = [ "/home/ntnu/davidkl/GPAWTutorial/CE/almg_fcc_vac.db", "almg_fcc_vac.db", "/home/davidkl/GPAWTutorial/CE/almg_fcc_vac.db" ] for path in db_paths: if (os.path.isfile(path)): db_name = path break #db_name = "almgsi_test_db.db" db = ase.db.connect(db_name) name = db.get(id=runID).key_value_pairs["name"] new_run = not db.get(id=runID).key_value_pairs["started"] # Update the databse db.update(runID, started=True, converged=False) db.update(runID, nkpt=nkpt) atoms = db.get_atoms(id=runID) atoms = delete_vacancies(atoms) if (len(atoms) == 1): nbands = -10 else: nbands = "120%" kpts = (nkpt, nkpt, nkpt) try: restart_name = SaveRestartFiles.restart_name(name) atoms, calc = gp.restart(restart_name) except: calc = gp.GPAW(mode=gp.PW(500), xc="PBE", kpts=kpts, nbands=nbands) atoms.set_calculator(calc) if (single_point): calc = gp.GPAW(mode=gp.PW(500), xc="PBE", kpts=kpts, nbands=nbands) atoms.set_calculator(calc) logfile = "almg_fcc_vac{}.log".format(name) traj = "almg_bcc{}.traj".format(name) db.update(runID, trajfile=traj) trajObj = Trajectory(traj, 'w', atoms) #storeBest = SaveToDB(db_name,runID,name,mode=relax_mode) save_calc = SaveRestartFiles(calc, name) update_db_info = UpdateDBInfo(db_name, runID, atoms) volume = atoms.get_volume() try: precon = Exp(mu=1.0, mu_c=1.0) fmax = 0.025 smax = 0.003 if (relax_mode == "both"): relaxer = PreconLBFGS(atoms, logfile=logfile, use_armijo=True, variable_cell=True) elif (relax_mode == "positions"): #relaxer = SciPyFminCG( atoms, logfile=logfile ) relaxer = BFGS(atoms, logfile=logfile) elif (relax_mode == "cell"): str_f = StrainFilter(atoms, mask=[1, 1, 1, 0, 0, 0]) relaxer = BFGS(str_f, logfile=logfile) fmax = smax * volume relaxer.attach(trajObj) #relaxer.attach( storeBest, interval=1, atoms=atoms ) relaxer.attach(save_calc, interval=1) relaxer.attach(update_db_info, interval=1) if (not single_point): if (relax_mode == "both"): relaxer.run(fmax=fmax, smax=smax) else: relaxer.run(fmax=fmax) energy = atoms.get_potential_energy() orig_atoms = db.get_atoms(runID) single_p_calc = SinglePointCalculator(orig_atoms, energy=energy) orig_atoms.set_calculator(single_p_calc) kvp = db.get(name=name).key_value_pairs del db[runID] newID = db.write(orig_atoms, key_value_pairs=kvp) if (relax_mode == "positions"): db.update(newID, converged_force=True) elif (relax_mode == "cell"): db.update(newID, converged_stress=True) else: db.update(newID, converged_stress=True, converged_force=True) db.update(newID, single_point=single_point) db.update(newID, restart_file=SaveRestartFiles.restart_name(name)) row = db.get(id=newID) conv_force = row.get("converged_force", default=0) conv_stress = row.get("converged_stress", default=0) if ((conv_force == 1) and (conv_stress == 1) and (nkpt == 4)): db.update(newID, converged=True) except Exception as exc: print(exc)
def gui(id): if open_ase_gui: db = database() atoms = db.get_atoms(id) view(atoms) return '', 204, []
def main(argv): relax_mode = "cell" # both, cell, positions system = "AlMg" runID = int(argv[0]) print("Running job: %d" % (runID)) db_paths = [ "/home/ntnu/davidkl/GPAWTutorial/CE/almg_217.db", "almg_217.db", "/home/davidkl/GPAWTutorial/CE/almg_217.db" ] for path in db_paths: if (os.path.isfile(path)): db_name = path break #db_name = "test_db.db" db = ase.db.connect(db_name) con = sq.connect(db_name) cur = con.cursor() cur.execute("SELECT value FROM text_key_values WHERE id=? AND key='name'", (runID, )) name = cur.fetchone()[0] con.close() new_run = not db.get(id=runID).key_value_pairs["started"] # Update the databse db.update(runID, started=True, converged=False) atoms = db.get_atoms(id=runID) calc = gp.GPAW(mode=gp.PW(500), xc="PBE", kpts=(4, 4, 4), nbands="120%") #calc = gp.GPAW( mode=gp.PW(500), xc="PBE", kpts=(4,4,4), nbands=-10 ) atoms.set_calculator(calc) logfile = "almg_bcc%d.log" % (runID) traj = "almg_bcc%d.traj" % (runID) trajObj = Trajectory(traj, 'w', atoms) storeBest = SaveToDB(db_name, runID, name, mode=relax_mode) volume = atoms.get_volume() try: precon = Exp(mu=1.0, mu_c=1.0) fmax = 0.025 smax = 0.003 if (relax_mode == "both"): relaxer = PreconLBFGS(atoms, logfile=logfile, use_armijo=True, precon=precon, variable_cell=True) elif (relax_mode == "positions"): relaxer = SciPyFminCG(atoms, logfile=logfile) #relaxer = BFGS( atoms, logfile=logfile ) elif (relax_mode == "cell"): str_f = StrainFilter(atoms, mask=[1, 1, 1, 0, 0, 0]) relaxer = BFGS(str_f, logfile=logfile) fmax = smax * volume relaxer.attach(trajObj) relaxer.attach(storeBest, interval=1, atoms=atoms) if (relax_mode == "both"): relaxer.run(fmax=fmax, smax=smax) else: relaxer.run(fmax=fmax) energy = atoms.get_potential_energy() if (relax_mode == "positions"): db.update(storeBest.runID, converged_force=True) elif (relax_mode == "cell"): db.update(storeBest.runID, converged_stress=True) else: db.update(storeBest.runID, converged_stress=True, converged_force=True) row = db.get(id=storeBest.runID) conv_force = row.get("converged_force", default=0) conv_stress = row.get("converged_stress", default=0) if ((conv_force == 1) and (conv_stress == 1)): db.update(storeBest.runID, converged=True) except Exception as exc: print(exc)
def main(argv): id = int(argv[0]) db = ase.db.connect("almgsi.db") atoms = db.get_atoms(id=id) view(atoms) atoms.write("almgsi.xyz")
def gui(id): if open_ase_gui: atoms = db.get_atoms(id) view(atoms) return '', 204, []
def xyz(id): fd = io.BytesIO() from ase.io.xyz import write_xyz write_xyz(fd, db.get_atoms(id)) data = fd.getvalue() return data, '{0}.xyz'.format(id)
def main(argv): relaxCell = True system = "AlMg" runID = int(argv[0]) print("Running job: %d" % (runID)) db_paths = [ "/home/ntnu/davidkl/GPAWTutorial/CE/ce_hydrostatic.db", "ce_hydrostatic.db", "/home/davidkl/GPAWTutorial/CE/ce_hydrostatic.db" ] for path in db_paths: if (os.path.isfile(path)): db_name = path break #db_name = "/home/ntnu/davidkl/Documents/GPAWTutorials/ceTest.db" db = ase.db.connect(db_name) con = sq.connect(db_name) cur = con.cursor() cur.execute("SELECT value FROM text_key_values WHERE id=? AND key='name'", (runID, )) name = cur.fetchone()[0] con.close() new_run = not db.get(id=runID).key_value_pairs["started"] # Update the databse db.update(runID, started=True, converged=False) atoms = db.get_atoms(id=runID) if (system == "AlMg" and new_run == False): atoms = change_cell_composition_AlMg(atoms) convergence = {"density": 1E-4, "eigenstates": 4E-8} calc = gp.GPAW(mode=gp.PW(500), xc="PBE", kpts=(4, 4, 4), nbands="120%", convergence=convergence) atoms.set_calculator(calc) logfile = "ceTest%d.log" % (runID) traj = "ceTest%d.traj" % (runID) trajObj = Trajectory(traj, 'w', atoms) storeBest = SaveToDB(db_name, runID, name) try: precon = Exp(mu=1.0, mu_c=1.0) if (relaxCell): uf = UnitCellFilter(atoms, hydrostatic_strain=True) relaxer = PreconLBFGS(uf, logfile=logfile, use_armijo=True, precon=precon) else: relaxer = PreconFIRE(atoms, logfile=logfile, precon=precon) relaxer = SciPyFminCG(atoms, logfile=logfile) relaxer.attach(trajObj) relaxer.attach(storeBest, interval=1, atoms=atoms) if (relaxCell): relaxer.run(fmax=0.025, smax=0.003) else: relaxer.run(fmax=0.025) energy = atoms.get_potential_energy() db.update(storeBest.runID, converged=True) print("Energy: %.2E eV/atom" % (energy / len(atoms))) print("Preconditioner parameters") print("Mu:", precon.mu) print("Mu_c:", precon.mu_c) except Exception as exc: print(exc)
def main(argv): print("Dry-run", gp.dry_run) if (len(argv) > 2): print("Usage: python almg.py paramID") return possible_dbs = { "vilje": "/home/ntnu/davidkl/GPAWTutorial/Exercises/AlMg/AlMg.db", "laptop": "AlMg.db" } # Find which database to use db_name = None for key in possible_dbs: if (os.path.isfile(possible_dbs[key])): db_name = possible_dbs[key] break if (db_name is None): raise RuntimeError("Could not find database") #db_name = "/home/ntnu/davidkl/GPAWTutorial/Exercises/AlMg/AlMg.db" db = ase.db.connect(db_name) runID = int(argv[0]) # Read parameters from the database con = sq.connect(db_name) cur = con.cursor() cur.execute( "SELECT hspacing,relax,atomID,kpts,nbands,latticeConst,cutoff,traj,fmax,tags FROM runs WHERE ID=?", (runID, )) params = cur.fetchall()[0] con.close() save_pov = False run_sim = True swap_atoms = False useOnlyUnitCellFilter = True repeatFCCStructure = True # If False, ASE find_optimal_cell_shape will be used to create the unit cell h_spacing = params[0] relax = params[1] atom_row_id = params[2] Nkpts = params[3] nbands = params[4] cutoff = params[6] old_traj = params[7] fmax = params[8] tags = params[9] # Lattice parameter a = float(params[5]) if (old_traj != "none"): # Read the atoms from the trajectory file print("Reading atoms from trajectory file") traj = Trajectory(old_traj) atoms = traj[-1] elif (atom_row_id < 0): print( "Building supercell using find_optimal_cell_shape_pure_python from ASE" ) # Target primitive cell atoms = build.bulk("Al", crystalstructure="fcc", a=a) # Create a supercell consisting of 32 atoms if (not "test" in tags): # Skip this if the run is a test run. For some reason the target_shape="fcc" does not work # using sc instead if (repeatFCCStructure): atoms = atoms * (4, 4, 2) else: P = build.find_optimal_cell_shape_pure_python( atoms.cell, 32, "sc") atoms = build.make_supercell(atoms, P) # Replace some atoms with Mg atoms n_mg_atoms = int(0.2 * len(atoms)) for i in range(n_mg_atoms): atoms[i].set("symbol", "Mg") else: print("Reading atoms object from the database") # Read atoms from database atoms = db.get_atoms(selection=atom_row_id) if (swap_atoms): from ase.io import write for i in range(0, 2 * len(atoms)): first = np.random.randint(0, len(atoms)) second = np.random.randint(0, len(atoms)) firstSymbol = atoms[first].symbol atoms[first].symbol = atoms[second].symbol atoms[second].symbol = firstSymbol atoms.write("almg_swap.xyz") if (save_pov): from ase.io import write write("Al.pov", atoms * (3, 3, 1), rotation="-10z,-70x") return if (run_sim): kpts = {"size": (Nkpts, Nkpts, Nkpts), "gamma": True} # Monkhorst pack kpts = (Nkpts, Nkpts, Nkpts) if (cutoff > 0): mode = PW(cutoff) else: mode = "fd" #calc = GPAW( mode="fd", h=h_spacing, xc="PBE", nbands=nbands, kpts=kpts, basis="dzp", poissonsolver=PoissonSolver(relax="GS", eps=1E-7) ) densityConv = 1E-2 # Default 1E-4 wfsConv = 5E-3 cnvg = {"density": 1E-2, "eigenstates": 5E-3} calc = GPAW(mode=mode, xc="PBE", nbands=nbands, kpts=kpts) calc.set(convergence=cnvg) atoms.set_calculator(calc) logfile = "none" trajfile = "none" if (relax): from ase.optimize import QuasiNewton, BFGS #from ase.optimize.precon import PreconLBFGS uid = rnd.randint(0, 10000000) # First relax only the unit cell logfile = "relaxation_%d.log" % (uid) trajfile = "trajectory_%d.traj" % (uid) print("Logfile: %s, Trajectory file: %s" % (logfile, trajfile)) traj = Trajectory(trajfile, 'w', atoms) if (not useOnlyUnitCellFilter): for num_kpts in [Nkpts]: kpts = (num_kpts, num_kpts, num_kpts) calc.set(kpts=kpts) energy = atoms.get_potential_energy() # Relax unit cell strfilter = StrainFilter(atoms) relaxer = BFGS(strfilter, logfile=logfile) relaxer.attach(traj) convergence = np.abs(0.01 * energy) relaxer.run( fmax=convergence ) # NOTE: Uses generalized forces = volume*stress # Relax atoms within the unit cell relaxer = BFGS(atoms, logfile=logfile) relaxer.attach(traj) relaxer.run(fmax=fmax) else: # Optimize both simultaneously uf = UnitCellFilter(atoms) relaxer = PreconLBFGS(uf, logfile=logfile) relaxer.attach(traj) relaxer.run(fmax=fmax) energy = atoms.get_potential_energy() print("Energy %.2f eV/atom" % (energy)) lastID = db.write(atoms, relaxed=True) # Update the database con = sq.connect(db_name) cur = con.cursor() cur.execute( "UPDATE runs SET status='finished',resultID=?,logfile=?,traj=? WHERE ID=?", (lastID, logfile, trajfile, runID)) con.commit() con.close()
def gui(project, id): if open_ase_gui: db = databases[project] atoms = db.get_atoms(id) view(atoms) return '', 204, []