def equil_and_relax(T, fname="", np_layer=0, nptype="spherical"):
    bc = init_bc(50)
    mc = Montecarlo(bc.atoms, T)
    print ("Running at temperature {}K. Initializing from {}".format(T, fname))
    layer_str = "-".join((str(item) for item in np_layers[np_layer]))
    run_identifier = "{}K_layer{}".format(T, layer_str)
    if fname != "":
        # Initialize atoms object from file
        from ase.io import read
        atoms = read(fname)
        symbs = [atom.symbol for atom in atoms]
        mc.set_symbols(symbs)
        run_identifier = "{}K_{}".format(T, atoms.get_chemical_formula())
    else:
        if nptype == "spherical":
            # Initialize by setting a nano particle at the center
            nanop = get_nanoparticle(layer=np_layer)
        elif nptype == "cubic":
            nanop = get_cubic_nano_particle(layer=np_layer)
            run_identifier += "cubic"
        else:
            raise ValueError("Unknown type {}".format(nanop))
        symbs = insert_nano_particle(bc.atoms.copy(), nanop)
        mc.set_symbols(symbs)
    print("Chemical formula: {}".format(mc.atoms.get_chemical_formula()))
    nsteps = int(4E7)
    camera = Snapshot(atoms=mc.atoms, trajfile=workdir+"/snapshots_equil{}.traj".format(run_identifier))
    energy_evol = EnergyEvolution(mc)
    mc_backup = MCBackup(mc, backup_file=workdir+"/mc_backup{}.pkl".format(run_identifier))
    mc.attach(energy_evol, interval=100000)
    mc.attach(camera, interval=nsteps/20)
    mc.attach(mc_backup, interval=500000)
    mc.runMC(steps=nsteps, equil=False)
    write(workdir+"/equillibriated600K.xyz", mc.atoms)
Esempio n. 2
0
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)
Esempio n. 3
0
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 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 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)
Esempio n. 6
0
    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 _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
Esempio n. 8
0
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)
Esempio n. 9
0
    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
Esempio n. 10
0
def main():
    atoms = get_atoms(cubic=True)

    T = 1500
    mc = Montecarlo(atoms, T)
    mc.insert_symbol_random_places("Mg", num=400, swap_symbs=["Al"])
    mc.insert_symbol_random_places("Si", num=400, swap_symbs=["Al"])
    snap = Snapshot(trajfile="data/mc_digi{}K.traj", atoms=atoms)
    mc.attach(snap, interval=50000)
    mc.runMC(steps=500000)

    T = 293
    mc = Montecarlo(atoms, T)
    snap = Snapshot(trajfile="data/mc_digi{}K.traj", atoms=atoms)
    mc.attach(snap, interval=50000)
    mc.runMC(steps=500000)
Esempio n. 11
0
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=",")
Esempio n. 12
0
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)
Esempio n. 13
0
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 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)
Esempio n. 15
0
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)
Esempio n. 16
0
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)
Esempio n. 17
0
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)
Esempio n. 18
0
    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)
Esempio n. 19
0
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()
Esempio n. 20
0
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)
Esempio n. 21
0
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=(",", ":"))