Exemple #1
0
def get_atoms(cubic=False):
    conc = Concentration(basis_elements=[["Al", "Mg", "Si"]])

    kwargs = {
        "crystalstructure": "fcc",
        "a": 4.05,
        "size": [2, 2, 2],
        "concentration": conc,
        "db_name": "data/almgsi_free_eng.db",
        "max_cluster_size": 4,
        "max_cluster_dia": [7.8, 5.0, 5.0],
        "cubic": cubic
    }
    N = 10
    ceBulk = CEBulk(**kwargs)
    print(ceBulk.basis_functions)
    eci_file = "data/almgsi_fcc_eci.json"
    eci_file = "data/eci_almgsi_aicc.json"
    eci_file = "data/eci_bcs.json"
    eci_file = "data/eci_almgsi_loocv.json"
    eci_file = "data/eci_l1.json"
    with open(eci_file, 'r') as infile:
        ecis = json.load(infile)
    db_name = "large_cell_db{}x{}x{}.db".format(N, N, N)
    atoms = get_atoms_with_ce_calc(ceBulk,
                                   kwargs,
                                   ecis,
                                   size=[N, N, N],
                                   db_name=db_name)
    return atoms
Exemple #2
0
def atoms_with_calc(N):
    conc = Concentration(basis_elements=[["Al", "Mg", "Si"]])

    kwargs = {
        "crystalstructure": "fcc",
        "a": 4.05,
        "size": [4, 4, 4],
        "concentration": conc,
        "db_name": "data/almgsi_10dec.db",
        "max_cluster_size": 4
    }

    ceBulk = CEBulk(**kwargs)
    eci_file = "data/almgsi_fcc_eci_newconfig_dec10.json"
    with open(eci_file, 'r') as infile:
        ecis = json.load(infile)
    db_name = "large_cell_db{}x{}x{}_dec10.db".format(N, N, N)
    #ecis = {"c1_0": 1.0}
    atoms = get_atoms_with_ce_calc(ceBulk, kwargs, ecis, size=[N, N, N], db_name=db_name)

    symbs = [atom.symbol for atom in atoms]
    diag = atoms.get_cell().T.dot([0.5, 0.5, 0.5])
    pos = atoms.get_positions() - diag
    lengths = np.sum(pos**2, axis=1)
    indx = np.argmin(lengths)
    symbs[indx] = "Mg"
    atoms.get_calculator().set_symbols(symbs)
    return atoms
    def insert_atoms( self, bc_kwargs, size=[1,1,1], composition=None, cetype="CEBulk", \
                      T=None, n_steps_per_temp=10000, eci=None ):
        """
        Insert a new atoms object into the database
        """
        if (composition is None):
            raise TypeError("No composition given")
        allowed_ce_types = ["CEBulk", "CECrystal"]
        if (not cetype in allowed_ce_types):
            raise ValueError(
                "cetype has to be one of {}".format(allowed_ce_types))
        self.cetype = cetype

        if (eci is None):
            raise ValueError(
                "No ECIs given! Cannot determine required energy range!")

        if (cetype == "CEBulk"):
            small_bc = CEBulk(**bc_kwargs)
            small_bc.reconfigure_settings()
        elif (cetype == "CECrystal"):
            small_bc = CECrystal(**bc_kwargs)
            small_bc.reconfigure_settings()

        self._check_eci(small_bc, eci)

        atoms = get_atoms_with_ce_calc(small_bc, bc_kwargs, eci=eci, size=size)
        calc = atoms.get_calculator()
        calc.set_composition(composition)

        formula = atoms.get_chemical_formula()
        if (self.template_atoms_exists(formula)):
            raise AtomExistsError(
                "An atom object with the specified composition already exists in the database"
            )

        Emin, Emax = self._find_energy_range(atoms, T, n_steps_per_temp)
        cf = calc.get_cf()
        data = {"cf": cf}
        # Store this entry into the database
        db = connect(self.wl_db_name)
        scalc = SinglePointCalculator(atoms, energy=Emin)
        atoms.set_calculator(scalc)

        outfname = "BC_wanglandau_{}.pkl".format(atoms.get_chemical_formula())
        with open(outfname, 'wb') as outfile:
            pck.dump((calc.BC, atoms), outfile)

        kvp = {
            "Emin": Emin,
            "Emax": Emax,
            "bcfile": outfname,
            "cetype": self.cetype
        }
        data["bc_kwargs"] = small_bc.kwargs
        data["supercell_size"] = size
        db.write(atoms, key_value_pairs=kvp, data=data)
Exemple #4
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)
Exemple #5
0
    def test_self_interactions(self):
        if not has_ase_with_ce:
            self.skipTest("ASE does not have CE")

        from cemc.ce_calculator import SelfInteractionError

        a = 4.05
        conc = Concentration(basis_elements=[["Au", "Cu", "Ti"]])
        db_name = "test_self_interactoins.db"
        kwargs = dict(crystalstructure="fcc", a=a, size=[3, 3, 3],
                      concentration=conc, db_name=db_name,
                      max_cluster_size=2, max_cluster_dia=5.0)

        ceBulk = CEBulk(**kwargs)
        atoms = get_atoms_with_ce_calc(ceBulk, kwargs, eci={'c0': 1.0},
                                       size=[8, 8, 8], db_name=db_name)

        with self.assertRaises(SelfInteractionError):
            atoms = get_atoms_with_ce_calc(ceBulk, kwargs, eci={'c0': 1.0},
                                           size=[1, 1, 1], db_name=db_name)
        os.remove(db_name)
Exemple #6
0
    def test_no_throw(self):
        if (not has_CE):
            self.skipTest("ASE version does not have ASE")
            return
        no_throw = True
        msg = ""
        try:
            conc_args = {
                "conc_ratio_min_1": [[1, 0]],
                "conc_ratio_max_1": [[0, 1]],
            }
            conc = Concentration(basis_elements=[["Al", "Mg"]])
            kwargs = {
                "crystalstructure": "fcc",
                "a": 4.05,
                "size": [3, 3, 3],
                "concentration": conc,
                "db_name": "temporary_bcnucleationdb.db",
                "max_cluster_size": 3,
                "max_cluster_dia": 4.5
            }
            ceBulk = CEBulk(**kwargs)
            cf = CorrFunction(ceBulk)
            cf_dict = cf.get_cf(ceBulk.atoms)
            ecis = {key: 1.0 for key, value in cf_dict.items()}

            #calc = CE( ceBulk, ecis, size=(3,3,3) )
            atoms = get_atoms_with_ce_calc(ceBulk,
                                           kwargs,
                                           ecis,
                                           size=[6, 6, 6],
                                           db_name="sc6x6x6.db")
            chem_pot = {"c1_0": -1.069}

            T = 300
            mc = SGCFreeEnergyBarrier( atoms, T, symbols=["Al","Mg"], \
            n_windows=5, n_bins=10, min_singlet=0.5, max_singlet=1.0 )
            mc.run(nsteps=100, chem_pot=chem_pot)
            mc.save(fname="free_energy_barrier.json")

            # Try to load the object stored
            mc = SGCFreeEnergyBarrier.load(atoms, "free_energy_barrier.json")
            mc.run(nsteps=100, chem_pot=chem_pot)
            mc.save(fname="free_energy_barrier.json")
            os.remove("sc6x6x6.db")
        except Exception as exc:
            msg = str(exc)
            no_throw = False
        self.assertTrue(no_throw, msg=msg)
    def test_covariance_observer(self):
        """Test the covariance observer."""
        if not available:
            self.skipTest("ASE version does not have CE!")

        msg = ""
        no_throw = True
        from cemc.mcmc import FixEdgeLayers
        from cemc.mcmc import CovarianceMatrixObserver
        bc, args = get_ternary_BC(ret_args=True)
        ecis = get_example_ecis(bc=bc)
        atoms = get_atoms_with_ce_calc(bc, args, eci=ecis, size=[8, 8, 8], db_name="covariance_obs.db")

        T = 200
        nn_names = [name for name in bc.cluster_family_names
                    if int(name[1]) == 2]

        mc = FixedNucleusMC(
            atoms, T, network_name=nn_names,
            network_element=["Mg", "Si"])

        fixed_layers = FixEdgeLayers(atoms=mc.atoms, thickness=3.0)
        mc.add_constraint(fixed_layers)
        elements = {"Mg": 6, "Si": 6}
        mc.insert_symbol_random_places("Mg", num=1, swap_symbs=["Al"])
        mc.grow_cluster(elements)

        cov_obs = CovarianceMatrixObserver(atoms=mc.atoms, cluster_elements=["Mg", "Si"])
        mc.attach(cov_obs)
        for _ in range(10):
            mc.runMC(steps=100, elements=elements, init_cluster=False)

            obs_I = cov_obs.cov_matrix
            indices = []
            for atom in mc.atoms:
                if atom.symbol in ["Mg", "Si"]:
                    indices.append(atom.index)
            cluster = mc.atoms[indices]
            pos = cluster.get_positions()
            com = np.mean(pos, axis=0)
            pos -= com
            cov_matrix = np.zeros((3, 3))
            for i in range(pos.shape[0]):
                x = pos[i, :]
                cov_matrix += np.outer(x, x)
            self.assertTrue(np.allclose(obs_I, cov_matrix))
        os.remove("covariance_obs.db")
Exemple #8
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=",")
    def get_atoms(self, atomID, eci):
        """
        Returns an instance of the atoms object requested
        """
        db = connect(self.wl_db_name)
        row = db.get(id=atomID)
        bcfname = row.key_value_pairs["bcfile"]
        init_cf = row.data["cf"]
        try:
            with open(bcfname, 'rb') as infile:
                bc, atoms = pck.load(infile)
            calc = CE(atoms, bc, eci, initial_cf=init_cf)
            return atoms
        except IOError as exc:
            print(str(exc))
            print("Will try to recover the CEBulk object")
            bc_kwargs = row.data["bc_kwargs"]
            cetype = row.key_value_pairs["cetype"]
            if (cetype == "CEBulk"):
                small_bc = CEBulk(**bc_kwargs)
                small_bc.reconfigure_settings()
            else:
                small_bc = CECrystal(**bc_kwargs)
                small_bc.reconfigure_settings()
            size = row.data["supercell_size"]
            atoms = get_atoms_with_ce_calc(small_bc,
                                           bc_kwargs,
                                           eci=eci,
                                           size=size)
            calc = atoms.get_calculator()

            # Determine the composition
            count = row.count_atoms()
            for key in count.keys():
                count /= float(row.natoms)
            calc.set_composition(count)
            return atoms
        except:
            raise RuntimeError(
                "Did not manage to return the atoms object with the proper calculator attached..."
            )
Exemple #10
0
    def test_supercell(self):
        if not has_ase_with_ce:
            self.skipTest("ASE version does not have CE")
            return

        atoms, ceBulk, eci = self.get_calc("fcc")
        calc = atoms.get_calculator()
        db_name = "test_db_fcc_super.db"

        conc = Concentration(basis_elements=[["Al", "Mg"]])
        kwargs = {
            "crystalstructure": "fcc",
            "a": 4.05,
            "size":[3, 3, 3],
            "concentration": conc,
            "db_name": db_name,
            "max_cluster_size": 3,
            "max_cluster_dia": 6.0
        }

        kwargs_template = copy.deepcopy(kwargs)
        kwargs_template["size"] = [4, 4, 4]
        kwargs_template["db_name"] = "template_bc.db"
        template_supercell_bc = CEBulk(**kwargs_template)
        template_supercell_bc.reconfigure_settings()

        ceBulk = CEBulk(**kwargs)
        ceBulk.reconfigure_settings()
        atoms_sc = get_atoms_with_ce_calc(ceBulk, kwargs, eci, size=[4, 4, 4],
                                          db_name="sc4x4x.db")
        calc_sc = atoms_sc.get_calculator()
        corr_func = CorrFunction(template_supercell_bc)
        for i in range(10):
            calc_sc.calculate(atoms_sc, ["energy"], [(i, "Al", "Mg")])
            updated_cf = calc_sc.get_cf()
            brute_force = corr_func.get_cf_by_cluster_names(
                atoms_sc, list(updated_cf.keys()))

            for key, value in brute_force.items():
                self.assertAlmostEqual(value, updated_cf[key])
        os.remove("sc4x4x.db")
Exemple #11
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)
}

# Use some example ecis
eci = get_example_ecis(bc_kwargs=kwargs)

# Initialize a template CEBulk Object
ceBulk = CEBulk(**kwargs)
ceBulk.reconfigure_settings()  # Nessecary for the unittest to pass

# Now we want to get a Cluster Expansion calculator for a big cell
mc_cell_size = [10, 10, 10]
from cemc import get_atoms_with_ce_calc

atoms = get_atoms_with_ce_calc(ceBulk,
                               kwargs,
                               eci=eci,
                               size=mc_cell_size,
                               db_name="sgc_large.db")

# In the SGC ensemble the simulation is run at fixed chemical potential
# The chemical potentials are subtracted from the singlet terms
# Those are ECIs starting with c1.
# In a binary system there is only one singlet term, so there is only one
# chemical potential to specify
chem_pot = {"c1_0": -1.04}

# Speciy the temperature
T = 400

from cemc.mcmc import SGCMonteCarlo
    def test_no_throw(self):
        if not available:
            self.skipTest("ASE version does not have CE!")
            return
        no_throw = True
        msg = ""
        try:
            db_name = "temp_nuc_db.db"
            if os.path.exists(db_name):
                os.remove(db_name)
            conc = Concentration(basis_elements=[["Al", "Mg"]])
            kwargs = {
                "crystalstructure": "fcc", "a": 4.05,
                "size": [3, 3, 3],
                "concentration": conc, "db_name": db_name,
                "max_cluster_size": 3,
                "max_cluster_dia": 4.5
            }
            ceBulk = CEBulk(**kwargs)
            ceBulk.reconfigure_settings()
            cf = CorrFunction(ceBulk)
            cf = cf.get_cf(ceBulk.atoms)

            ecis = {key: 0.001 for key in cf.keys()}
            atoms = get_atoms_with_ce_calc(ceBulk, kwargs, ecis, size=[5, 5, 5],
                               db_name="sc5x5x5.db")

            chem_pot = {"c1_0": -1.0651526881167124}
            sampler = NucleationSampler(
                size_window_width=10,
                chemical_potential=chem_pot, max_cluster_size=20,
                merge_strategy="normalize_overlap")

            nn_name = get_network_name(ceBulk.cluster_family_names_by_size)
            mc = SGCNucleation(
                atoms, 30000, nucleation_sampler=sampler,
                network_name=[nn_name],  network_element=["Mg"],
                symbols=["Al", "Mg"], chem_pot=chem_pot)
            mc.runMC(steps=2, equil=False)
            sampler.save(fname="test_nucl.h5")

            mc = CanonicalNucleationMC(
                atoms, 300, nucleation_sampler=sampler,
                network_name=[nn_name],  network_element=["Mg"],
                concentration={"Al": 0.8, "Mg": 0.2}
                )
            symbs = [atom.symbol for atom in atoms]
            symbs[0] = "Mg"
            symbs[1] = "Mg"
            mc.set_symbols(symbs)
            #mc.runMC(steps=2)
            sampler.save(fname="test_nucl_canonical.h5")
            elements = {"Mg": 6}
            calc = atoms.get_calculator()
            calc.set_composition({"Al": 1.0, "Mg": 0.0})
            mc = FixedNucleusMC(atoms, 300,
                                network_name=[nn_name], network_element=["Mg"])
            mc.insert_symbol_random_places("Mg", num=1, swap_symbs=["Al"])
            mc.runMC(steps=2, elements=elements, init_cluster=True)
            os.remove("sc5x5x5.db")
        except Exception as exc:
            msg = str(exc)
            msg += "\n" + traceback.format_exc()
            no_throw = False
        self.assertTrue(no_throw, msg=msg)