def sa(al_comp, kwargs, eci, db_name, size, lattice): comp = {"Al": al_comp, "Zn": 1.0 - al_comp} bc = BulkCrystal(**kwargs) calc = get_ce_calc(bc, kwargs, eci, size) bc = calc.BC bc.atoms.set_calculator(calc) temperatures = [800, 700, 600, 500, 400, 300, 200, 100] N = len(bc.atoms) if rank == 0: print("Supercell has {} atoms".format(N)) # Define parameters for equillibration equil_params = {"maxiter": 10 * N, "mode": "fixed"} nsteps = 100 * N calc.set_composition(comp) for T in temperatures: mc = Montecarlo(bc.atoms, T, mpicomm=comm) mc.runMC(mode="fixed", steps=nsteps, equil_params=equil_params) thermo = mc.get_thermodynamic() thermo["converged"] = True thermo["al_conc"] = al_comp thermo["temperature"] = T if rank == 0: db = dataset.connect("sqlite:///{}".format(db_name)) tbl = db["results"] tbl.insert(thermo) if rank == 0: fname = "data/atoms_{}_{}.xyz".format(lattice, bc.atoms.get_chemical_formula()) write(fname, bc.atoms)
def test_no_throw(self): if not available: self.skipTest(skipMsg) no_throw = True msg = "" try: bc = get_ternary_BC() eci = get_example_ecis(bc) atoms = bc.atoms.copy() CE(atoms, bc, eci=eci) mc = Montecarlo(atoms, 1000) mc.insert_symbol_random_places("Mg", num=10, swap_symbs=["Al"]) # Note: convergence_factor should never be # set to a negative value! Here it is done # to make the test converged after one step bias = AdaptiveBiasReactionPathSampler( mc_obj=mc, react_crd_init=DummyReacCrdInit(), react_crd=[-1.0, 1.0], convergence_factor=-1.0) bias.run() except Exception as exc: msg = str(exc) no_throw = False self.assertTrue(no_throw, msg=msg)
def run(T, mg_conc, si_conc, precs): conc_args = { "conc_ratio_min_1": [[64, 0, 0]], "conc_ratio_max_1": [[24, 40, 0]], "conc_ratio_min_2": [[64, 0, 0]], "conc_ratio_max_2": [[22, 21, 21]] } orig_spin_dict = { "Mg": 1.0, "Si": -1.0, "Al": 0.0 } kwargs = { "crystalstructure": "fcc", "a": 4.05, "size": [4, 4, 4], "basis_elements": [["Mg", "Si", "Al"]], "conc_args": conc_args, "db_name": "data/almgsi.db", "max_cluster_size": 4 } ceBulk = BulkCrystal(**kwargs) ceBulk.spin_dict = orig_spin_dict ceBulk.basis_functions = ceBulk._get_basis_functions() ceBulk._get_cluster_information() eci_file = "data/almgsi_fcc_eci.json" with open(eci_file, 'r') as infile: ecis = json.load(infile) print(ecis) #calc = CE( ceBulk, ecis, size=(3,3,3) ) calc = get_ce_calc(ceBulk, kwargs, ecis, size=[10, 10, 10]) ceBulk = calc.BC ceBulk.atoms.set_calculator(calc) comp = { "Mg": mg_conc, "Si": si_conc, "Al": 1.0 - mg_conc - si_conc } calc.set_composition(comp) for temp, prec in zip(T, precs): print("Current temperature {}K".format(temp)) mc_obj = Montecarlo(ceBulk.atoms, temp, mpicomm=comm) mode = "prec" mc_obj.runMC(mode=mode, prec=prec) thermo = mc_obj.get_thermodynamic() thermo["temperature"] = temp thermo["prec"] = prec thermo["internal_energy"] = thermo.pop("energy") thermo["converged"] = True thermo["prec"] = prec if (rank == 0): db = dataset.connect("sqlite:///{}".format(mc_db_name)) tbl = db["results"] thermo["sysID"] = sysID tbl.insert(thermo)
def main(): energies = [] sizes = list(range(1, 6)) atoms = get_atoms() two_atoms(atoms) exit() insert_np(6, atoms) mc = Montecarlo(atoms, 0.1) camera = Snapshot(atoms=mc.atoms, trajfile="/work/sophus/nuc_cluster.traj") db = dataset.connect("sqlite:////work/sophus/mgsi_nuc_barrier_kamijo.db") tbl = db["systems"] mc.attach(camera, interval=100 * len(atoms)) num_mg = sum(1 for atom in atoms if atom.symbol == "Mg") while num_mg > 2: print(atoms.get_chemical_formula()) mc.runMC(mode="fixed", equil=False, steps=100 * len(atoms)) thermo = mc.get_thermodynamic() tbl.insert(thermo) # Remove one Mg atom and one Si atom symbols = [a.symbol for a in atoms] for i in range(20): i = symbols.index("Si") symbols[i] = "Al" i = symbols.index("Mg") symbols[i] = "Al" mc.set_symbols(symbols) num_mg = sum(1 for atom in atoms if atom.symbol == "Mg")
def pure_phase_entropy(small_bc): from cemc.mcmc import Montecarlo from ase.clease.tools import wrap_and_sort_by_position from ase.io import read from cemc.mcmc import SiteOrderParameter, Snapshot import dataset T = [1, 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 420, 440, 460, 480, 500] calc = get_ce_calc(small_bc, kwargs, ecis, size=[10, 10, 10], db_name="data/db10x10x10Al3Mg.db") bc = calc.BC bc.atoms.set_calculator(calc) atoms = read("data/al3mg_template.xyz") atoms = wrap_and_sort_by_position(atoms) symbs = [atom.symbol for atom in atoms] calc.set_symbols(symbs) site_order = SiteOrderParameter(bc.atoms) db = dataset.connect("sqlite:///data/pure_al3mg3.db") syst = db["thermodynamic"] camera = Snapshot(trajfile="data/pure_phase_entropy.traj", atoms=bc.atoms) for temp in T: print("Current temperature: {}K".format(temp)) site_order.reset() mc = Montecarlo(bc.atoms, temp) mc.attach(site_order) mc.attach(camera, interval=50000) equil_param = {"window_length": 100000, "mode": "fixed"} mc.runMC(mode="fixed", steps=500000, equil=True, equil_params=equil_param) mean, stddev = site_order.get_average() thermo = mc.get_thermodynamic() thermo["site_order"] = mean thermo["site_order_std"] = stddev syst.insert(thermo)
def _estimate_internal_energy(self, conc, sweeps=2): """ Estimates the internal energy of one structure """ try: self.atoms._calc.set_composition(conc) mc = Montecarlo(self.atoms, self.temperature) mc.runMC(mode="fixed", steps=sweeps * len(self.atoms), equil=False) energy = mc.get_thermodynamic()["energy"] except TooFewElementsError as exc: energy = 1.0 return energy
def test_no_throw(self): if not available: self.skipTest(import_msg) ceBulk, atoms = self.init_bulk_crystal() mc = Montecarlo(atoms, 100.0) mc.insert_symbol_random_places("Mg", num=5, swap_symbs=["Al"]) mc.insert_symbol_random_places("Si", num=5, swap_symbs=["Al"]) par_temp = ParallelTempering(mc_obj=mc, Tmax=100.0, Tmin=0.001) mc_args = {"steps": 100, "equil": False} par_temp.run(mc_args=mc_args, num_exchange_cycles=3) os.remove("temp_scheme.csv")
def test_run(self): if not available: self.skipTest(reason) bc = get_ternary_BC() eci = get_example_ecis(bc) atoms = bc.atoms.copy() calc = CE(atoms, bc, eci=eci) mc = Montecarlo(atoms, 1000000) mc.insert_symbol_random_places("Mg", swap_symbs=["Al"], num=3) performance_monitor = MultithreadPerformance(4) performance_monitor.run(mc, 100)
def main(size, T): atoms = create_surface(size) atoms = wrap_and_sort_by_position(atoms) conc_args = { "conc_ratio_min_1": [[64, 0, 0]], "conc_ratio_max_1": [[24, 40, 0]], "conc_ratio_min_2": [[64, 0, 0]], "conc_ratio_max_2": [[22, 21, 21]] } kwargs = { "crystalstructure": "fcc", "a": 4.05, "size": [4, 4, 4], "basis_elements": [["Al", "Mg", "Si"]], "conc_args": conc_args, "db_name": "data/almgsi.db", "max_cluster_size": 4 } ceBulk = BulkCrystal(**kwargs) eci_file = "data/almgsi_fcc_eci_newconfig.json" with open(eci_file, 'r') as infile: ecis = json.load(infile) db_name = "large_cell_db{}x{}x{}.db".format(size[0], size[1], size[2]) calc = get_ce_calc(ceBulk, kwargs, ecis, size=size, db_name=db_name) ceBulk = calc.BC ceBulk.atoms.set_calculator(calc) mc = Montecarlo(ceBulk.atoms, T) symbs = [atom.symbol for atom in atoms] mc.set_symbols(symbs) # Write a copy of the current atoms object from ase.io import write shape_str = "-".join((str(item) for item in size)) uid_str = "{}K_{}".format(T, shape_str) write(WORKDIR + "initial_config{}.xyz".format(uid_str), mc.atoms) backup = MCBackup(mc, backup_file=WORKDIR + "backup{}.xyz".format(uid_str), db_name=WORKDIR + "mc_surface.db") camera = Snapshot(atoms=mc.atoms, trajfile=WORKDIR + "surface{}.traj".format(uid_str)) evol = EnergyEvolution(mc) nsteps = int(10E6) mc.attach(backup, interval=100000) mc.attach(camera, interval=int(nsteps / 20)) mc.attach(evol, interval=10 * len(mc.atoms)) mc.runMC(mode="fixed", steps=nsteps, equil=False) write(WORKDIR + "final_config{}.xyz".format(uid_str), mc.atoms)
def run(maxT, minT, n_temp, mg_conc): T = np.linspace(minT, maxT, n_temp)[::-1] conc_args = { "conc_ratio_min_1": [[1, 0]], "conc_ratio_max_1": [[0, 1]], } kwargs = { "crystalstructure": "fcc", "a": 4.05, "size": [4, 4, 4], "basis_elements": [["Al", "Mg"]], "conc_args": conc_args, "db_name": "data/temporary_bcdb.db", "max_cluster_size": 4 } ceBulk = BulkCrystal(**kwargs) print(ceBulk.basis_functions) eci_file = "data/ce_hydrostatic.json" with open(eci_file, 'r') as infile: ecis = json.load(infile) print(ecis) #calc = CE( ceBulk, ecis, size=(3,3,3) ) calc = get_ce_calc(ceBulk, kwargs, ecis, size=[10, 10, 10]) ceBulk = calc.BC ceBulk.atoms.set_calculator(calc) comp = {"Al": 1.0 - mg_conc, "Mg": mg_conc} calc.set_composition(comp) print("Number of atoms: {}".format(len(ceBulk.atoms))) for temp in T: print("Current temperature {}K".format(temp)) mc_obj = Montecarlo(ceBulk.atoms, temp, mpicomm=comm) mode = "prec" prec = 1E-5 mc_obj.runMC(mode=mode, prec=prec) thermo = mc_obj.get_thermodynamic() thermo["temperature"] = temp thermo["prec"] = prec thermo["internal_energy"] = thermo.pop("energy") thermo["converged"] = True if (rank == 0): db = connect(mc_db_name) db.write(ceBulk.atoms, key_value_pairs=thermo)
def test_no_throw(self): if not available: self.skipTest(import_msg) msg = "" no_throw = True try: ceBulk = self.init_bulk_crystal() mc = Montecarlo(ceBulk.atoms, 100.0) mc.insert_symbol_random_places("Mg", num=5, swap_symbs=["Al"]) mc.insert_symbol_random_places("Si", num=5, swap_symbs=["Al"]) par_temp = ParallelTempering(mc_obj=mc, Tmax=100.0, Tmin=0.001) mc_args = {"steps": 100, "equil": False} par_temp.run(mc_args=mc_args, num_exchange_cycles=3) os.remove("temp_scheme.csv") except Exception as exc: msg = "{}: {}".format(type(exc).__name__, str(exc)) no_throw = False self.assertTrue(no_throw, msg=msg)
def perform_mc(uid): from ase.io import read from cemc.mcmc import Montecarlo db = dataset.connect(PHASE_DIAG_DB) tbl = db["simulation_plan"] row = tbl.find_one(id=uid) print(row) temperatures = list(np.arange(1, 600, 50)) ceBulk = get_ce_with_calc() swap_symbs = row["swap_new"].split("-") current = 0 if row["phase"] == "mgsi": atoms = read("data/ground_stateMgSi.xyz") symbols = [atom.symbol for atom in atoms] else: symbols = ["Al" for _ in range(len(ceBulk.atoms))] num_inserted = np.zeros(len(swap_symbs)) for i in range(len(symbols)): if symbols[i] == row["swap_old"]: symbols[i] = swap_symbs[current] num_inserted[current] += 1 if num_inserted[-1] >= row["num_insert"]: break elif num_inserted[current] >= row["num_insert"]: current += 1 elif num_inserted[current] >= row["num_insert"]: current += 1 ceBulk.atoms.get_calculator().set_symbols(symbols) result_tab = db["simulations"] for T in temperatures: print("Current temperature: {}".format(T)) mc = Montecarlo(ceBulk.atoms, T) equil_params = {"mode": "fixed", "maxiter": 10000} mc.runMC(steps=1000 * len(symbols), equil_params=equil_params) thermo = mc.get_thermodynamic() thermo["runID"] = uid result_tab.insert(thermo)
def get_thermodynamic(self): """ Override the thermodynamics function. Normalization of the averagers: The values in average track should represent the ratio between partition functions when one have one extra of the inserted atom and one less of the removed atom. In the high temperature limit this is given by Z_{n+1} = N!/((n+1)!(N-n-1)!) and Z_n = N!/(n!(N-n)!) where N is the overall number of atoms of the two atoms being swapped. Hence, the ratio becomes Z_{n+1}/Z_n = (N-n)/(n+1), the sums are normalized such that they results in this value at high temperatures. :return: dict with the thermodynamical properties """ self.collect_results() res = {} res = Montecarlo.get_thermodynamic(self) at_count = self.count_atoms() # Inser the insertion enegies for move in self.insertion_moves: key = self.get_key(move[0], move[1]) name = "insert_energy_{}".format(key) N = self.averager_track[key].num_samples inf_temp = float(at_count[move[0]]) / (at_count[move[1]] + 1) E0 = self.averager_track[key].ref_value res[name] = E0 - kB * self.T * \ np.log(self.averager_track[key].average * inf_temp) name = "raw_insert_energy_{}".format(key) res[name] = self.raw_insertion_energy[key] / N name = "boltzmann_avg_insert_energy_{}".format(key) res[name] = self.boltzmann_weight_ins_energy[key].average / \ self.averager_track[key].average name = "boltzmann_avg_insert_energy_sq_{}".format(key) res[name] = self.boltzmann_weight_ins_eng_sq[key].average / \ self.averager_track[key].average return res
def _accept(self, system_changes): """Accept trial move. :param list system_changes: Proposed changes :return: True/False, if True the move is accepted :rtype: bool """ move_accepted = Montecarlo._accept(self, system_changes) if not self.move_ok(): return False return move_accepted
def _get_trial_move(self): """Perform a trial move.""" if not self.nuc_sampler.is_in_window(self.network): self.network(None) msg = "System is outside the window before the trial move " msg += "is performed!\n" raise RuntimeError(msg) #stat = self.network.get_statistics() #num_clusters = stat["number_of_clusters"] #max_size = stat["max_size"] #lower,upper = self.nuc_sampler.get_window_boundaries(self.nuc_sampler.current_window) #msg += "Num. clusters: {}. Max size: {}. Window limits: [{},{})".format(num_clusters,max_size,lower,upper) return Montecarlo._get_trial_move(self)
def get_gs(self, BC, ecis=None, composition=None, temps=None, n_steps_per_temp=1000, atoms=None): """ Computes the ground states :param BC: Instance of *CEBulk* or *CECrystal* from ASE :param ecis: Dictionary with the Effecitve Cluster Interactions :param composition: Dictionary with compositions (i.e. {"Mg":0.2,"Al":0.8}) :param temps: List of cooling temperatures :param n_steps_per_temp: Number of MC steps per temperature """ if atoms is None: atoms = BC.atoms.copy() if atoms.get_calculator() is None: if ecis is None: raise ValueError("When a calculator is not attached " "the ECIs has to be given!") calc = CE(atoms, BC, ecis) else: calc = atoms.get_calculator() #print (calc.get_cf()) if (temps is None): temps = np.linspace(1, 1500, 30)[::-1] if (composition is not None): calc.set_composition(composition) minimum_energy = LowestEnergyStructure(calc, None) for T in temps: print("Temperature {}".format(T)) mc_obj = Montecarlo(atoms, T) mc_obj.constraints = self.constraints minimum_energy.mc_obj = mc_obj mc_obj.attach(minimum_energy) mc_obj.runMC(steps=n_steps_per_temp, verbose=False, equil=False) thermo = mc_obj.get_thermodynamic() result = { "atoms": minimum_energy.atoms, "energy": minimum_energy.lowest_energy, "cf": minimum_energy.lowest_energy_cf } return result
def sa(au_comp, kwargs, eci, db_name, size): bc = CEBulk(**kwargs) atoms = get_atoms_with_ce_calc(bc, kwargs, eci, size) temperatures = [800, 700, 600, 500, 400, 300, 200, 100, 50, 25, 10] N = len(bc.atoms) # Define parameters for equillibration equil_params = { "maxiter": 10 * N, "mode": "fixed" } comps = [0.05, 0.1, 0.15, 0.2, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95] nsteps = 100 * N calc = atoms.get_calculator() for au_comp in comps: comp = { "Au": au_comp, "Cu": 1.0-au_comp } calc.set_composition(comp) for T in temperatures: mc = Montecarlo(atoms, T) mc.runMC(mode="fixed", steps=nsteps, equil_params=equil_params) thermo = mc.get_thermodynamic() thermo["converged"] = True thermo["au_conc"] = au_comp thermo["temperature"] = T cf = calc.get_cf() db = dataset.connect("sqlite:///{}".format(db_name)) tbl = db["results"] uid = tbl.insert(thermo) cf_tbl = db["corrfunc"] cf["runID"] = uid cf_tbl.insert(cf) fname = "data/atoms_{}.xyz".format(atoms.get_chemical_formula()) write(fname, atoms)
def runMC(self, steps=100000, init_cluster=True, elements={}, equil=False): """ Run Monte Carlo for fixed nucleus size :param int steps: Number of Monte Carlo steps :param bool init_cluster: If True initialize a cluster, If False it is assumed that a cluster of the correct size already exists in the system :param dict elements: Elements in the cluster """ if init_cluster: self._check_nucleation_site_exists() self.grow_cluster(elements) self.network.collect_statistics = False # Call one time self.network([]) if self.network.num_root_nodes() > 1: raise ValueError("Something went wrong during construction! " "the system has more than one cluster!") self.update_current_energy() Montecarlo.runMC(self, steps=steps, equil=equil)
def run(N, T): bc = init_bc(N) mc = Montecarlo(bc.atoms, T) nanop = get_nanoparticle() symbs = insert_nano_particle(bc.atoms.copy(), nanop) mc.set_symbols(symbs) order_param = SiteOrderParameter(mc.atoms) nsteps = int(1E6) equil_params = {"mode": "fixed", "window_length": int(1E5)} mc.attach(order_param) mc.runMC(steps=nsteps, equil=True, equil_params=equil_params) thermo = mc.get_thermodynamic() mean, std = order_param.get_average() thermo["order_param_mean"] = mean thermo["order_param_std"] = std thermo.update(equil_params) db = dataset.connect("sqlite:///{}".format(mc_db_name)) tbl = db["cluster_stability"] tbl.insert(thermo) fname = workdir + "/final_structure{}K.xyz".format(T) write(fname, mc.atoms)
def test_ignore_atoms(self): if not has_ase_with_ce: self.skipTest("ASE does not have CE") from cemc.mcmc import FixedElement no_trow = True msg = "" try: from copy import deepcopy conc = Concentration(basis_elements=[['V', 'Li'], ['O']]) kwargs = { "crystalstructure": "rocksalt", "concentration": conc, "a": 4.12, 'size': [2, 2, 2], 'cubic': True, "max_cluster_size": 4, "max_cluster_dia": 4.12, "db_name": 'database.db', 'basis_function': 'sluiter', 'ignore_background_atoms': True } fix_elem = FixedElement(element="O") kw_args_cpy = deepcopy(kwargs) ceBulk = CEBulk(**kw_args_cpy) ecis = get_example_ecis(ceBulk) atoms = get_atoms_with_ce_calc(ceBulk, kwargs, eci=ecis, size=[3, 3, 3], db_name="ignore_test_large.db") calc = atoms.get_calculator() # Insert some Li atoms num_li = 5 symbols = [atom.symbol for atom in atoms] num_inserted = 0 for i in range(0, len(symbols)): if symbols[i] == "V": symbols[i] = "Li" num_inserted += 1 if num_inserted >= num_li: break calc.set_symbols(symbols) mc = Montecarlo(atoms, 800) mc.add_constraint(fix_elem) mc.runMC(steps=100, equil=False, mode="fixed") # Clean up files os.remove("ignore_test_large.db") os.remove("database.db") except Exception as exc: no_trow = False msg = str(exc) self.assertTrue(no_trow, msg=msg)
def plot_evolution(fname): mc = Montecarlo.load(fname) atoms_fname = fname.rpartition(".")[0]+"_final_atoms.xyz" write(atoms_fname, mc.atoms) energy_obs = None for obs in mc.observers: if obs[1].name == "EnergyEvolution": energy_obs = obs[1] if energy_obs is None: raise RuntimeError("Did not find an energy evolution observer!") energy = energy_obs.energies fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(energy) plt.show()
def _accept(self, system_changes): """Accept trial move. :param list system_changes: Proposed changes :return: True/False, if True the move is accepted :rtype: bool """ # Note that we have to call the parent's accept first, # as the _mc_step function assumes that an energy # evaluation have been performed, prior to accepting # or rejecting the move move_accepted = Montecarlo._accept(self, system_changes) if self.network.move_creates_new_cluster(system_changes): return False # if not self.move_ok(): # return False return move_accepted
def sa(au_comp, kwargs, eci, db_name, size): bc = CEBulk(**kwargs) atoms = get_atoms_with_ce_calc(bc, kwargs, eci, size, db_name="cu-au_quad.db") temperatures = [1500, 1400, 1300, 1200, 1100, 1000, 900, 800, 700, 600, 500, 400, 300, 200, 100, 50, 25, 10] N = len(atoms) gs = wrap_and_sort_by_position(read("data/atoms_Au250Cu750.xyz")) symbs = [atom.symbol for atom in gs] atoms.get_calculator().set_symbols(symbs) print(atoms.get_calculator().get_energy()) exit() # Define parameters for equillibration equil_params = { "maxiter": 10 * N, "mode": "fixed" } nsteps = 200 * N calc = atoms.get_calculator() comp = {"Au": au_comp, "Cu": 1.0-au_comp} calc.set_composition(comp) energies = [] for T in temperatures: mc = Montecarlo(atoms, T, accept_first_trial_move_after_reset=True) energy_obs = EnergyEvolution(mc) energies.append(energy_obs.energies) mc.attach(energy_obs, interval=100) mc.runMC(mode="fixed", steps=nsteps, equil_params=equil_params) thermo = mc.get_thermodynamic() thermo["converged"] = True thermo["temperature"] = T cf = calc.get_cf() db = dataset.connect("sqlite:///{}".format(db_name)) tbl = db["results"] uid = tbl.insert(thermo) cf_tbl = db["corrfunc"] cf["runID"] = uid cf_tbl.insert(cf) fname = "data/atoms_{}_{}.xyz".format(atoms.get_chemical_formula(), thermo['energy']) write(fname, atoms) np.savetxt("data/energy_evolution_{}.csv".format(atoms.get_chemical_formula()), np.array(energies).T, delimiter=",")
def gs_mgsi(): atoms = get_atoms(cubic=True) symbs = ["Mg" for _ in range(len(atoms))] for i in range(int(len(symbs) / 2)): symbs[i] = "Si" atoms.get_calculator().set_symbols(symbs) T = [ 1500, 1400, 1300, 1200, 1100, 1000, 900, 800, 600, 500, 400, 300, 200, 100, 50 ] snap = Snapshot(trajfile="mgsi_gs_search.traj", atoms=atoms) for temp in T: print("Temperature {}K".format(temp)) mc = Montecarlo(atoms, temp) mc.attach(snap, interval=10 * len(atoms)) mc.runMC(mode="fixed", steps=100 * len(atoms), equil=False)
def run_huge(): conc_args = { "conc_ratio_min_1":[[64,0,0]], "conc_ratio_max_1":[[24,40,0]], "conc_ratio_min_2":[[64,0,0]], "conc_ratio_max_2":[[22,21,21]] } kwargs = { "crystalstructure":"fcc", "size":[4,4,4], "basis_elements":[["Al","Mg","Si"]], "conc_args":conc_args, "db_name":"some_db.db", "max_cluster_size":4, "a":4.05, "ce_init_alg":"fast" } ceBulk = BulkCrystal( **kwargs ) with open(eci_file, 'r') as infile: eci = json.load(infile) calc = get_ce_calc(ceBulk, kwargs, eci=eci, size=[50,50,50]) calc.BC.atoms.set_calculator(calc) print(calc.BC.basis_functions) comp = { "Al":0.9, "Mg":0.05, "Si":0.05 } calc.set_composition(comp) T = 150 T = [2000, 1500, 1200, 1000, 800, 600, 400, 293] camera = Snapshot(trajfile=traj_file, atoms=calc.BC.atoms) for temp in T: print("Current temperature {}K".format(temp)) mc = Montecarlo(calc.BC.atoms, temp) mc.attach(camera, interval=125000*20) mc.runMC(mode="fixed", steps=125000*100, equil=False)
def run(T,mg_conc): conc_args = { "conc_ratio_min_1":[[1,0]], "conc_ratio_max_1":[[0,1]], } kwargs = { "crystalstructure":"fcc", "a":4.05, "size":[4,4,4], "basis_elements":[["Al","Mg"]], "conc_args":conc_args, "db_name":"data/temporary_bcdb.db", "max_cluster_size":4 } ceBulk = BulkCrystal( **kwargs ) print (ceBulk.basis_functions) eci_file = "data/ce_hydrostatic.json" with open( eci_file, 'r' ) as infile: ecis = json.load( infile ) print (ecis) #calc = CE( ceBulk, ecis, size=(3,3,3) ) calc = get_ce_calc( ceBulk, kwargs, ecis, size=[10,10,10], free_unused_arrays_BC=True ) ceBulk = calc.BC ceBulk.atoms.set_calculator( calc ) comp = { "Al":1.0-mg_conc, "Mg":mg_conc } calc.set_composition(comp) mc_obj = Montecarlo( ceBulk.atoms, T, mpicomm=comm ) pairs = PairCorrelationObserver( calc ) network = NetworkObserver( calc=calc, cluster_name="c2_1414_1", element="Mg", nbins=100 ) mode = "fixed" camera = Snapshot( "data/precipitation.traj", atoms=ceBulk.atoms ) mc_obj.attach( camera, interval=10000 ) mc_obj.attach( pairs, interval=1 ) mc_obj.attach( network, interval=500 ) mc_obj.runMC( mode=mode, steps=10000, equil=True ) pair_mean = pairs.get_average() pair_std = pairs.get_std() if ( rank == 0 ): data = { "pairs":pair_mean, "pairs_std":pair_std, "mg_conc":mg_conc, "temperature":T } pairfname = "data/precipitation_pairs/precipitation_pairs_{}_{}K.json".format(int(1000*mg_conc),int(T)) with open(pairfname,'w') as outfile: json.dump(data,outfile,indent=2, separators=(",",":")) print ( "Thermal averaged pair correlation functions written to {}".format(pairfname) ) atoms = network.get_atoms_with_largest_cluster() data = network.get_statistics() # This collects the histogram data from all processors size,occurence = network.get_size_histogram() data["histogram"] = {} data["histogram"]["size"] = size.tolist() data["histogram"]["occurence"] = occurence.tolist() data["temperature"] = T data["mg_conc"] = mg_conc cluster_fname = "data/cluster_statistics_{}_{}K.json".format(int(1000*mg_conc),int(T)) atoms_fname = "data/largest_cluster_{}_{}K.cif".format( int(1000*mg_conc), int(T) ) if ( rank == 0 ): print (occurence) if ( rank == 0 ): try: with open( cluster_fname,'r') as infile: data = json.load(infile) old_size = np.array(data["histogram"]["size"]) old_hist = np.array(data["histogram"]["occurence"]) if ( np.allclose(old_size,size) ): occurence += old_hist data["histogram"]["occurence"] = occurence.tolist() except Exception as exc: print (str(exc)) with open( cluster_fname, 'w' ) as outfile: json.dump( data, outfile, indent=2, separators=(",",":") ) print ("Cluster statistics written to {}".format(cluster_fname) ) write( atoms_fname, atoms ) print ("Atoms with largest cluster written to {}".format(atoms_fname)) #view(atoms) #plt.plot( network.size_histogram, ls="steps") #plt.show() print ("Proc: {} reached final barrier".format(rank)) comm.barrier()
def thermodynamic_integration(phase): alat = 3.8 conc_args = {} conc_args['conc_ratio_min_1'] = [[1, 0]] conc_args['conc_ratio_max_1'] = [[0, 1]] kwargs = { "crystalstructure": 'fcc', "a": 3.8, "size": [10, 10, 10], "basis_elements": [['Cu', 'Au']], "conc_args": conc_args, "db_name": 'temp_sgc.db', "max_cluster_size": 3, "max_cluster_dist": 1.5 * alat } bc1 = BulkCrystal(**kwargs) bf = bc1._get_basis_functions()[0] with open("data/eci_aucu.json", 'r') as infile: eci = json.load(infile) db = dataset.connect("sqlite:///{}".format(canonical_db)) tbl = db["corrfunc"] if phase == "Au" or phase == "Cu": atoms1 = bc1.atoms for atom in atoms1: atom.symbol = phase cf1 = get_pure_cf(eci, bf[phase]) else: atoms = read(phase) row = tbl.find_one(runID=gs[phase]) row.pop("id") row.pop("runID") cf1 = row # TODO: Fix this when running with a pure phase symbs = [atom.symbol for atom in atoms] cf1 = get_pure_cf(eci, bf[bc1.atoms[0].symbol]) atoms = bc1.atoms calc = CE(bc1, eci=eci, initial_cf=cf1) calc.set_symbols(symbs) atoms.set_calculator(calc) sgc_db = dataset.connect("sqlite:///{}".format(sgc_db_name)) tbl = sgc_db["results"] tbl_cf = sgc_db["corr_func"] mu = 0.223 nsteps = 100 * len(atoms) equil_param = {"mode": "fixed", "maxiter": 10 * len(atoms)} order_param = SiteOrderParameter(atoms) T = np.linspace(100, 600, 40) # mu = np.linspace(0.223, 0.19, 20).tolist() mu = [0.223] for temp in T: for m in mu: chemical_potential = {"c1_0": m} # mc = SGCMonteCarlo(atoms, temp, mpicomm=comm, symbols=["Au", "Cu"]) mc = Montecarlo(atoms, temp) mc.attach(order_param) init_formula = atoms.get_chemical_formula() # mc.runMC(steps=nsteps, equil_params=equil_param, # chem_potential=chemical_potential) mc.runMC(steps=nsteps, equil_params=equil_param) # thermo = mc.get_thermodynamic(reset_ecis=True) thermo = mc.get_thermodynamic() thermo["init_formula"] = init_formula thermo["final_formula"] = atoms.get_chemical_formula() avg, std = order_param.get_average() thermo["order_avg"] = avg thermo["order_std"] = std thermo["valid"] = True thermo["integration_path"] = "NN" if rank == 0: uid = tbl.insert(thermo) cf = calc.get_cf() cf["runID"] = uid tbl_cf.insert(cf)
def run(mg_conc): bs_kwargs = { "conc_args": { "conc_ratio_min_1": [[1, 0]], "conc_ratio_max_1": [[0, 1]] }, "basis_elements": [["Al", "Mg"], ["Al", "Mg"], ["Al", "Mg"], ["Al", "Mg"]], "cellpar": [10.553, 10.553, 10.553, 90, 90, 90], "basis": [(0, 0, 0), (0.324, 0.324, 0.324), (0.3582, 0.3582, 0.0393), (0.0954, 0.0954, 0.2725)], "spacegroup": 217, "max_cluster_size": 4, "db_name": "trial_217.db", "size": [1, 1, 1], "grouped_basis": [[0, 1, 2, 3]] } bs = BulkSpacegroup(**bs_kwargs) eci_file = "data/almg_217_eci.json" with open(eci_file, 'r') as infile: ecis = json.load(infile) calc = get_ce_calc(bs, bs_kwargs, ecis, size=[3, 3, 3]) bs = calc.BC bs.atoms.set_calculator(calc) comp = {"Al": 1.0 - mg_conc, "Mg": mg_conc} calc.set_composition(comp) print("Number of atoms: {}".format(len(bs.atoms))) high_temps = [10000, 9000, 8000, 7000, 6000, 5000, 4000, 3000, 2000, 1000] low_temps = range(200, 1000, 50)[::-1] T = np.array(high_temps + low_temps) #T = np.array([10000,9000,8000,7000,6000,5000,4000,3000,2000,1000,800,700,600,500,400,375,350,325,300,275,250,225,200,175,150]) #T = np.array([1E6,100000]) precs = np.zeros(len(T)) + 1E-4 #precs[T<=500] = 1E-5 print(bs.atoms.get_chemical_formula()) mc_obj = Montecarlo(bs.atoms, T[0], mpicomm=comm) mc_obj.accept_first_trial_move_after_reset = False for prec, temp in zip(precs, T): mc_obj.T = temp mc_obj.reset() #if ( temp==T[0] ): # mc_obj.is_first = False # Do not accept the first move print("Current temperature {}K".format(temp)) mode = "fixed" mc_obj.runMC(mode=mode, prec=prec, steps=1000000) thermo = mc_obj.get_thermodynamic() thermo["temperature"] = temp thermo["prec"] = prec thermo["internal_energy"] = thermo.pop("energy") thermo["converged"] = True if (rank == 0): cf = calc.get_cf() db = connect(mc_db_name) thermo.update(cf) db.write(bs.atoms, key_value_pairs=thermo) if (rank == 0 and run_mfa): # At this point a ground state should have been reached mfa = CanonicalMeanField(atoms=bs.atoms, T=T) mfa.relax() res = mfa.calculate() formula = bs.atoms.get_chemical_formula() fname = "data/mfa217/{}mfa.json".format(formula) with open(fname, 'w') as outfile: json.dump(res, outfile, indent=2, separators=(",", ":"))
def _accept(self, system_changes): move_accepted = Montecarlo._accept(self, system_changes) in_window = self.nuc_sampler.is_in_window(self.network) return move_accepted and in_window
def free_energy_vs_layered(T, mod): from cemc.mcmc import AdaptiveBiasReactionPathSampler from cemc.mcmc import ReactionCrdRangeConstraint from cemc.mcmc import DiffractionObserver from cemc.mcmc import MinimalEnergyPath from ase.geometry import get_layers atoms = get_atoms(cubic=True) atoms_cpy = atoms.copy() layers, dist = get_layers(atoms, (0, 1, 0)) for atom in atoms_cpy: if layers[atom.index] % 2 == 0: atom.symbol = "Mg" else: atom.symbol = "Si" symbols = [atom.symbol for atom in atoms_cpy] atoms.get_calculator().set_symbols(symbols) lamb = 4.05 k = 2.0 * np.pi / lamb workdir = "data/diffraction" # Have to perform only insert moves mc = Montecarlo(atoms, T) k_vec = [k, 0, 0] observer = DiffractionObserver(atoms=atoms, active_symbols=["Si"], all_symbols=["Mg", "Si"], k_vector=k_vec, name="reflection") if T < 250: mc.max_attempts = 5 nsteps = 100 * len(atoms) mep = MinimalEnergyPath(mc_obj=mc, observer=observer, value_name="reflection", relax_steps=nsteps, search_steps=nsteps, traj_file="{}/mep_diffract{}K.traj".format( workdir, T), max_reac_crd=1999.0) mep.run() mep.save(fname="{}/mep_mep_diffract_path{}.csv".format(workdir, T)) else: conc_cnst = ReactionCrdRangeConstraint(observer, value_name="reflection") conc_cnst.update_range([0, 0.5]) mc.add_constraint(conc_cnst) reac_path = AdaptiveBiasReactionPathSampler( mc_obj=mc, react_crd=[0.0, 0.5], observer=observer, n_bins=500, data_file="{}/layered_bias{}K.h5".format(workdir, T), mod_factor=mod, delete_db_if_exists=True, mpicomm=None, db_struct="{}/layered_bias_struct{}K.db".format(workdir, T), react_crd_name="reflection", ignore_equil_steps=False, smear=2000) reac_path.run() reac_path.save()