Example #1
0
def get_eci():
    bc = CEBulk(**bc_kwargs)
    bc.reconfigure_settings()
    cf = CorrFunction(bc)
    cf = cf.get_cf(bc.atoms)
    eci = {key: 0.001 for key in cf.keys()}
    return eci
    def test_network(self):
        if (not available):
            self.skipTest("ASE version does not have CE!")
            return

        msg = ""
        no_throw = True
        try:
            db_name = "test_db_network.db"

            conc = Concentration(basis_elements=[["Al", "Mg"]])
            a = 4.05
            ceBulk = CEBulk(crystalstructure="fcc",
                            a=a,
                            size=[3, 3, 3],
                            concentration=conc,
                            db_name=db_name,
                            max_cluster_size=3,
                            max_cluster_dia=4.5)
            ceBulk.reconfigure_settings()

            cf = CorrFunction(ceBulk)
            atoms = ceBulk.atoms.copy()
            cf = cf.get_cf(atoms)
            eci = {key: 0.001 for key in cf.keys()}
            calc = CE(atoms, ceBulk, eci=eci)
            trans_mat = ceBulk.trans_matrix

            for name, info in ceBulk.cluster_info[0].items():
                if info["size"] == 2:
                    net_name = name
                    break
            obs = NetworkObserver(calc=calc,
                                  cluster_name=[net_name],
                                  element=["Mg"])

            # Several hard coded tests
            calc.update_cf((0, "Al", "Mg"))
            size = 2
            clusters = ceBulk.cluster_info[0][net_name]["indices"]
            for sub_clust in clusters:
                calc.update_cf((sub_clust[0], "Al", "Mg"))
                # Call the observer
                obs(None)

                res = obs.fast_cluster_tracker.get_cluster_statistics_python()
                self.assertEqual(res["cluster_sizes"][0], size)
                size += 1
            obs.get_indices_of_largest_cluster_with_neighbours()
            os.remove("test_db_network.db")

        except Exception as exc:
            msg = "{}: {}".format(type(exc).__name__, str(exc))
            no_throw = False
        self.assertTrue(no_throw, msg=msg)
Example #3
0
def get_ternary_BC(ret_args=False):
    db_name = "test_db_ternary.db"
    max_dia = get_max_cluster_dia_name()
    size_arg = {max_dia: 4.05}
    conc = Concentration(basis_elements=[["Al", "Mg", "Si"]])
    args = dict(crystalstructure="fcc", a=4.05, size=[4,4,4], concentration=conc, \
                db_name=db_name, max_cluster_size=3, **size_arg)
    ceBulk = CEBulk(**args)
    ceBulk.reconfigure_settings()
    if ret_args:
        return ceBulk, args
    return ceBulk
Example #4
0
def get_ternary_BC():
    db_name = "test_db_ternary.db"
    conc_args = {
        "conc_ratio_min_1":[[4,0,0]],
        "conc_ratio_max_1":[[0,4,0]],
        "conc_ratio_min_1":[[2,2,0]],
        "conc_ratio_max_2":[[1,1,2]]
    }
    max_dia = get_max_cluster_dia_name()
    size_arg = {max_dia:4.05}
    ceBulk = CEBulk(crystalstructure="fcc", a=4.05, size=[4,4,4], basis_elements=[["Al","Mg","Si"]], \
                         conc_args=conc_args, db_name=db_name, max_cluster_size=3, **size_arg)
    ceBulk.reconfigure_settings()
    return ceBulk
 def init_bulk_crystal(self):
     conc = Concentration(basis_elements=[["Al", "Mg", "Si"]])
     ceBulk = CEBulk(crystalstructure="fcc",
                     a=4.05,
                     size=[4, 4, 4],
                     concentration=conc,
                     db_name=db_name,
                     max_cluster_size=2,
                     max_cluster_dia=4.0)
     ceBulk.reconfigure_settings()
     ecis = get_example_ecis(bc=ceBulk)
     atoms = ceBulk.atoms.copy()
     calc = CE(atoms, ceBulk, ecis)
     return ceBulk, atoms
Example #6
0
def get_small_BC_with_ce_calc(lat="fcc"):
    db_name = "test_db_{}.db".format(lat)

    a = 4.05
    conc = Concentration(basis_elements=[["Al", "Mg"]])
    ceBulk = CEBulk( crystalstructure=lat, a=a, size=[3,3,3], concentration=conc, \
                     db_name=db_name, max_cluster_size=3, max_cluster_dia=4.5)
    ceBulk.reconfigure_settings()
    cf = CorrFunction(ceBulk)
    corrfuncs = cf.get_cf(ceBulk.atoms)
    eci = {name: 1.0 for name in corrfuncs.keys()}
    calc = CE(ceBulk.atoms.copy(), ceBulk, eci)
    #ceBulk.atoms.set_calculator(calc)
    return ceBulk, calc
Example #7
0
 def init_bulk_crystal(self):
     max_dia_name = get_max_cluster_dia_name()
     size_arg = {max_dia_name: 4.05}
     conc = Concentration(basis_elements=[["Al", "Mg", "Si"]])
     ceBulk = CEBulk(crystalstructure="fcc",
                     a=4.05,
                     size=[3, 3, 3],
                     concentration=conc,
                     db_name=db_name,
                     max_cluster_size=3,
                     **size_arg)
     ceBulk.reconfigure_settings()
     atoms = ceBulk.atoms.copy()
     calc = CE(atoms, ceBulk, ecis)
     #ceBulk.atoms.set_calculator(calc)
     return ceBulk, atoms
Example #8
0
    def test_gs_finder(self):
        if (not has_CE):
            self.skipTest("ASE version does not have CE")
            return
        no_throw = True
        msg = ""
        try:
            db_name = "test_db_gsfinder.db"

            conc_args = {
                "conc_ratio_min_1": [[1, 0]],
                "conc_ratio_max_1": [[0, 1]],
            }
            a = 4.05
            ceBulk = CEBulk( crystalstructure="fcc", a=a, size=[3,3,3], basis_elements=[["Al","Mg"]], conc_args=conc_args, \
            db_name=db_name, max_cluster_size=4)
            cf = CorrFunction(ceBulk)
            cf = cf.get_cf(ceBulk.atoms)
            eci = {key: 1.0 for key in cf.keys()}
            gsfinder = GSFinder()
            comp = {"Al": 0.5, "Mg": 0.5}
            gsfinder.get_gs(ceBulk, eci, composition=comp)
        except Exception as exc:
            msg = str(exc)
            no_throw = False
        self.assertTrue(no_throw, msg=msg)
Example #9
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
Example #10
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
Example #11
0
def get_small_BC_with_ce_calc(lat="fcc"):
    db_name = "test_db_{}.db".format(lat)

    conc_args = {
        "conc_ratio_min_1":[[1,0]],
        "conc_ratio_max_1":[[0,1]],
    }
    a = 4.05
    ceBulk = CEBulk( crystalstructure=lat, a=a, size=[3,3,3], basis_elements=[["Al","Mg"]], conc_args=conc_args, \
    db_name=db_name, max_cluster_size=3)
    ceBulk.reconfigure_settings()
    cf = CorrFunction(ceBulk)
    corrfuncs = cf.get_cf(ceBulk.atoms)
    eci = {name:1.0 for name in corrfuncs.keys()}
    calc = CE( ceBulk, eci )
    ceBulk.atoms.set_calculator(calc)
    return ceBulk
Example #12
0
def get_atoms_with_ce_calc(small_bc,
                           bc_kwargs,
                           eci=None,
                           size=[1, 1, 1],
                           db_name="temp_db.db"):
    """
    Constructs a CE calculator for a supercell.

    First, the correlation function from a small cell is calculated and then
    a supercell is formed. Note that the correlation functions are the same
    for the supercell.

    :param ClusterExpansionSetting small_bc: Settings for small unitcell
    :param dict bc_kwargs: dictionary of the keyword arguments used to
        construct small_bc
    :param dict eci: Effective Cluster Interactions
    :param list size: The atoms in small_bc will be extended by this amount
    :param str db_name: Database to store info in for the large cell

    :return: Atoms object with CE calculator attached
    :rtype: Atoms
    """
    unknown_type = False
    large_bc = small_bc
    init_cf = None
    error_happened = False
    msg = ""

    transfer_floating_point_classifier(bc_kwargs["db_name"], db_name)
    max_size_eci = get_max_size_eci(eci)
    if "max_cluster_size" in bc_kwargs.keys():
        if max_size_eci > bc_kwargs["max_cluster_size"]:
            msg = "ECI specifies a cluster size larger than "
            msg += "ClusterExpansionSetting tracks!"
            raise ValueError(msg)

    atoms = small_bc.atoms.copy()
    calc1 = CE(atoms, small_bc, eci)
    init_cf = calc1.get_cf()
    min_length = small_bc.max_cluster_dia
    bc_kwargs["size"] = size
    size_name = get_max_dia_name()
    bc_kwargs[size_name] = min_length
    bc_kwargs["db_name"] = db_name

    if isinstance(small_bc, CEBulk):
        large_bc = CEBulk(**bc_kwargs)
    elif isinstance(small_bc, CECrystal):
        large_bc = CECrystal(**bc_kwargs)
    else:
        unknown_type = True

    atoms = large_bc.atoms.copy()

    # Note this automatically attach the calculator to the
    # atoms object
    CE(atoms, large_bc, eci, initial_cf=init_cf)
    return atoms
Example #13
0
 def init_bulk_crystal(self):
     conc_args = {
         "conc_ratio_min_1": [[2, 1, 1]],
         "conc_ratio_max_1": [[0, 2, 2]],
     }
     ceBulk = CEBulk(crystalstructure="fcc",
                     a=4.05,
                     size=[4, 4, 4],
                     basis_elements=[["Al", "Mg", "Si"]],
                     conc_args=conc_args,
                     db_name=db_name,
                     max_cluster_size=2,
                     max_cluster_dia=4.0)
     ceBulk.reconfigure_settings()
     ecis = get_example_ecis(bc=ceBulk)
     calc = CE(ceBulk, ecis)
     ceBulk.atoms.set_calculator(calc)
     return ceBulk
Example #14
0
def get_example_ecis(bc=None,bc_kwargs=None):
    if ( bc is not None ):
        cf = CorrFunction(bc)
    else:
        bc = CEBulk(**bc_kwargs)
        cf = CorrFunction(bc)
    cf = cf.get_cf(bc.atoms)
    eci = {key: 0.001 for key in cf.keys()}
    return eci
    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 (ctype == "CECrystal"):
            small_bc = CECrystal(**bc_kwargs)
            small_bc.reconfigure_settings()

        self._check_eci(small_bc, eci)

        calc = get_ce_calc(small_bc, bc_kwargs, eci=eci, size=size)
        calc.set_composition(composition)
        bc = calc.BC
        bc.atoms.set_calculator(calc)

        formula = bc.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(bc.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(bc.atoms, energy=Emin)
        bc.atoms.set_calculator(scalc)

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

        kvp = {
            "Emin": Emin,
            "Emax": Emax,
            "bcfile": outfname,
            "cetype": self.cetype
        }
        data["bc_kwargs"] = bc_kwargs
        data["supercell_size"] = size
        db.write(calc.BC.atoms, key_value_pairs=kvp, data=data)
    def test_no_throw(self):
        no_throw = True
        if not available:
            self.skipTest(reason)
            return
        msg = ""
        # try:
        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_bcnucleationdb.db",
            "max_cluster_size": 3
        }
        ceBulk = CEBulk(**kwargs)
        ceBulk.reconfigure_settings()
        cf = CorrFunction(ceBulk)
        cf = cf.get_cf(ceBulk.atoms)
        ecis = {key: 1.0 for key in cf.keys()}
        calc = CE(ceBulk, ecis)
        ceBulk = calc.BC
        ceBulk.atoms.set_calculator(calc)

        T = 500
        c_mg = 0.4
        comp = {"Mg": c_mg, "Al": 1.0 - c_mg}
        calc.set_composition(comp)
        act_sampler = ActivitySampler(ceBulk.atoms,
                                      T,
                                      moves=[("Al", "Mg")],
                                      mpicomm=comm)
        act_sampler.runMC(mode="fixed", steps=1000)
        act_sampler.get_thermodynamic()
        # except Exception as exc:
        #     msg = str(exc)
        #     no_throw = False
        self.assertTrue(no_throw, msg=msg)
Example #17
0
 def init_bulk_crystal(self):
     conc_args = {
         "conc_ratio_min_1": [[2, 1, 1]],
         "conc_ratio_max_1": [[0, 2, 2]],
     }
     max_dia_name = get_max_cluster_dia_name()
     size_arg = {max_dia_name: 4.05}
     ceBulk = CEBulk(crystalstructure="fcc",
                     a=4.05,
                     size=[3, 3, 3],
                     basis_elements=[["Al", "Mg", "Si"]],
                     conc_args=conc_args,
                     db_name=db_name,
                     max_cluster_size=3,
                     **size_arg)
     ceBulk.reconfigure_settings()
     calc = CE(ceBulk, ecis)
     ceBulk.atoms.set_calculator(calc)
     return ceBulk
Example #18
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]],
            }
            kwargs = {
                "crystalstructure": "fcc",
                "a": 4.05,
                "size": [3, 3, 3],
                "basis_elements": [["Al", "Mg"]],
                "conc_args": conc_args,
                "db_name": "temporary_bcnucleationdb.db",
                "max_cluster_size": 3
            }
            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) )
            calc = get_ce_calc(ceBulk,
                               kwargs,
                               ecis,
                               size=[6, 6, 6],
                               db_name="sc6x6x6.db")
            ceBulk = calc.BC
            ceBulk.atoms.set_calculator(calc)
            chem_pot = {"c1_0": -1.069}

            T = 300
            mc = SGCFreeEnergyBarrier( ceBulk.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(ceBulk.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)
Example #19
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=",")
Example #20
0
    def load_from_dict(backup_data):
        """Rebuild the calculator from dictionary

        :param dict backup_data: All nessecary arguments
        """
        from ase.clease import CEBulk, CECrystal

        classtype = backup_data["setting_kwargs"].pop("classtype")
        if classtype == "CEBulk":
            bc = CEBulk(**backup_data["setting_kwargs"])
        elif classtype == "CECrystal":
            bc = CECrystal(**backup_data["setting_kwargs"])
        else:
            raise ValueError("Unknown setting classtype: {}"
                             "".format(backup_data["setting_kwargs"]))

        for symb in backup_data["symbols"]:
            bc.atoms.symbol = symb
        return CE(bc, eci=backup_data["eci"], initial_cf=backup_data["cf"])
    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..."
            )
Example #22
0
2. Initialize a Cluster Expansion calculator
3. Initialize a the Monte Carlo object
4. Simple use of Monte Carlo observers
"""

# First we import the CEBulk object from ASE
from ase.clease import CEBulk
from util import get_example_ecis

# Initialize the CEBulk object for a 4x4x4 expansion of a
# primitive FCC unitcell
conc_args = {"conc_ratio_min_1": [[0, 1]], "conc_ratio_max_1": [[1, 0]]}
bc = CEBulk(crystalstructure="fcc",
            a=4.05,
            conc_args=conc_args,
            db_name="test_gs_db.db",
            size=[3, 3, 3],
            basis_elements=[["Al", "Mg"]],
            max_cluster_size=3)
bc.reconfigure_settings()  # Nessecary for unittests to pass

# Just use some example ECIs
eci = get_example_ecis(bc=bc)

# Initialize a Cluster Expansion calculator (C++ version is required)
from cemc import CE
calc = CE(bc, eci)
bc.atoms.set_calculator(calc)

# NOTE: At this point all changes to the atoms object has to be done via
# the calculator. The reason is that the calculator keeps track of the
def surface_energy():
    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 = CEBulk(**kwargs)
    eci_file = "data/almgsi_fcc_eci_newconfig.json"
    with open(eci_file, 'r') as infile:
        ecis = json.load(infile)
    size = (8, 8, 8)
    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)
    print(calc.get_energy() / len(calc.atoms))
    ceBulk = calc.BC
    ceBulk.atoms.set_calculator(calc)

    # Get the energy of MgSi
    mgsi = wrap_and_sort_by_position(get_mgsi() * (4, 4, 4))
    symbs = [atom.symbol for atom in mgsi]
    calc.set_symbols(symbs)
    view(calc.atoms)
    mgsi_energy = calc.get_energy() / len(calc.atoms)
    print("Energy MgSi: {} eV/atom".format(mgsi_energy))

    # Get the energy of pure al
    symbs = ["Al" for _ in range(len(mgsi))]
    calc.set_symbols(symbs)
    view(calc.atoms)
    al_energy = calc.get_energy() / len(calc.atoms)
    print("Energy Al: {} eV/atom".format(al_energy))

    # Get the energy of a 50% mixture
    mgsi = wrap_and_sort_by_position(get_mgsi() * (4, 4, 2))
    # mgsi = get_mgsi_surface100_si_si()
    from scipy.spatial import cKDTree as KDTree
    cell = calc.atoms.get_cell()
    tree = KDTree(calc.atoms.get_positions())
    symbs = [atom.symbol for atom in calc.atoms]
    for atom in mgsi:
        pos = np.zeros((1, 3))
        pos[0, :] = atom.position
        wrapped = wrap_positions(pos, cell)
        if not np.allclose(wrapped, atom.position):
            continue
        _, indx = tree.query(atom.position)
        symbs[indx] = atom.symbol
    calc.set_symbols(symbs)
    view(calc.atoms)

    # Surface energy
    mix_energy = calc.get_energy()
    print("Mix energy: {} eV ({} eV/atom)".format(mix_energy, mix_energy /
                                                  len(calc.atoms)))
    num_al = 0
    num_mgsi = 0
    for atom in calc.atoms:
        if atom.symbol == "Al":
            num_al += 1
        elif atom.symbol == "Mg" or atom.symbol == "Si":
            num_mgsi += 1
    assert num_al + num_mgsi == len(calc.atoms)
    dE = mix_energy - num_al * al_energy - num_mgsi * mgsi_energy
    cell = calc.atoms.get_cell()
    a1 = cell[0, :]
    a2 = cell[1, :]
    normal = np.cross(a1, a2)
    area = np.sqrt(normal.dot(normal))

    # Convert units
    surface_tension = dE / area
    mJ = J / 1000.0  # milli joules
    surface_tension *= (m * m / mJ)
    unit_normal = normal / area
    print("Surface tension: {} mJ/m^2".format(surface_tension))
    print("Direction: {}".format(unit_normal))
    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)
Example #25
0
3. Initialize a the Monte Carlo object
4. Simple use of Monte Carlo observers
"""

# First we import the CEBulk object from ASE
from ase.clease import CEBulk
from ase.clease import Concentration
from util import get_example_ecis

# Initialize the CEBulk object for a 4x4x4 expansion of a
# primitive FCC unitcell
conc = Concentration([["Al", "Mg"]])
bc = CEBulk(crystalstructure="fcc",
            a=4.05,
            db_name="test_gs_db.db",
            size=[3, 3, 3],
            concentration=conc,
            max_cluster_size=3,
            max_cluster_dia=4.5)
bc.reconfigure_settings()  # Nessecary for unittests to pass

# Just use some example ECIs
eci = get_example_ecis(bc=bc)

# Initialize a Cluster Expansion calculator (C++ version is required)
from cemc import CE
atoms = bc.atoms.copy()
calc = CE(atoms, bc, eci)

# NOTE: At this point all changes to the atoms object has to be done via
# the calculator. The reason is that the calculator keeps track of the
Example #26
0
def get_ce_calc(small_bc,
                bc_kwargs,
                eci=None,
                size=[1, 1, 1],
                db_name="temp_db.db"):
    """
    Constructs a CE calculator for a supercell.

    First, the correlation function from a small cell is calculated and then
    a supercell is formed. Note that the correlation functions are the same
    for the supercell.

    :param ClusterExpansionSetting small_bc: Settings for small unitcell
    :param dict bc_kwargs: dictionary of the keyword arguments used to
        construct small_bc
    :param dict eci: Effective Cluster Interactions
    :param list size: The atoms in small_bc will be extended by this amount
    :param str db_name: Database to store info in for the large cell

    :return: CE calculator for the large cell
    :rtype: CE
    """
    nproc = num_processors()
    unknown_type = False
    large_bc = small_bc
    init_cf = None
    error_happened = False
    msg = ""

    if not os.path.exists(db_name) and nproc > 1:
        raise IOError("The database has to be prepared prior to calling "
                      "get_ce_calc")
    try:
        max_size_eci = get_max_size_eci(eci)
        if "max_cluster_dia" in bc_kwargs.keys():
            if max_size_eci > bc_kwargs["max_cluster_dia"]:
                msg = "ECI specifies a cluster size larger than "
                msg += "ClusterExpansionSetting tracks!"
                raise ValueError(msg)
            print("Initializing calculator with small BC")

        calc1 = CE(small_bc, eci)
        print("Initialization finished")
        init_cf = calc1.get_cf()
        min_length = small_bc.max_cluster_dia
        bc_kwargs["size"] = size
        size_name = get_max_dia_name()
        bc_kwargs[size_name] = min_length
        bc_kwargs["db_name"] = db_name

        if isinstance(small_bc, CEBulk):
            large_bc = CEBulk(**bc_kwargs)
        elif isinstance(small_bc, CECrystal):
            large_bc = CECrystal(**bc_kwargs)
        else:
            unknown_type = True
    except MemoryError:
        # No default error message here
        error_happened = True
        msg = "Memory Error. Most likely went out "
        msg += " of memory when initializing an array"
    except Exception as exc:
        error_happened = True
        msg = str(exc)
        print(msg)

    # Broad cast the error flag and raise error on all processes
    error_happened = mpi_allreduce(error_happened)
    all_msg = mpi_allgather(msg)
    for item in all_msg:
        if item != "":
            msg = item
            break

    if error_happened:
        raise RuntimeError(msg)

    unknown_type = mpi_bcast(unknown_type, root=0)
    if unknown_type:
        msg = "The small_bc argument has to by of type "
        msg += "CEBulk or CECrystal"
        raise TypeError(msg)
    calc2 = CE(large_bc, eci, initial_cf=init_cf)
    return calc2
# dictionary
kwargs = {
    "crystalstructure":"fcc",
    "a":4.05,
    "size":[3, 3, 3],
    "basis_elements":[["Al","Mg"]],
    "db_name": db_name,
    "conc_args": conc_args,
    "max_cluster_size": 3
}

# In this example, we just 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 unittests 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_ce_calc

calc = get_ce_calc( ceBulk, kwargs, eci=eci, size=mc_cell_size, db_name="mc_obs.db")
ceBulk = calc.BC
ceBulk.atoms.set_calculator(calc)

conc = {
    "Al":0.8,
    "Mg":0.2
}
calc.set_composition(conc)