Example #1
0
    def test_pair_observer(self):
        if not available:
            self.skipTest(skip_msg)

        no_throw = True
        msg = ""

        bc = get_ternary_BC()
        ecis = get_example_ecis(bc=bc)
        atoms = bc.atoms.copy()
        calc = CE(atoms, bc, eci=ecis)
        atoms.set_calculator(calc)

        T = 1000
        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"])
        mc.insert_symbol_random_places("Mg", swap_symbs=["Al"])
        elements = {"Mg": 3, "Si": 3}
        mc.grow_cluster(elements)
        obs = PairObserver(mc.atoms, cutoff=4.1, elements=["Mg", "Si"])
        mc.attach(obs)
        mc.runMC(steps=200)
        self.assertEqual(obs.num_pairs, obs.num_pairs_brute_force())
        self.assertTrue(obs.symbols_is_synced())
    def test_with_covariance_reac_crd(self):
        if not available:
            self.skipTest("ASE version does not have CE!")

        msg = ""
        no_throw = True
        try:
            bc = get_ternary_BC()
            atoms = bc.atoms.copy()
            ecis = get_example_ecis(bc=bc)
            calc = CE(atoms, bc, eci=ecis)
            #bc.atoms.set_calculator(calc)

            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"])

            elements = {"Mg": 4, "Si": 4}
            mc.insert_symbol_random_places("Mg", num=1, swap_symbs=["Al"])
            mc.grow_cluster(elements)
            conc_init = CovarianceCrdInitializer(
                fixed_nucl_mc=mc, matrix_element="Al",
                cluster_elements=["Mg", "Si"])
            
            mc.runMC(steps=100, init_cluster=False)

            match, match_msg = self._spherical_nano_particle_matches(conc_init)
            self.assertTrue(match, msg=match_msg)
        except Exception as exc:
            no_throw = False
            msg = str(exc)

        self.assertTrue(no_throw, msg=msg)
def run(N, use_bias):
    #network_name=["c2_4p050_3", "c2_2p864_2"]
    bc = init_bc(N)
    mc = FixedNucleusMC(
        bc.atoms, T, network_name=["c2_2p864_2"],
        network_element=["Mg", "Si"], mpicomm=comm,
        max_constraint_attempts=1E6)
    #mc.max_allowed_constraint_pass_attempts = 1
    nanop = get_nanoparticle()
    symbs = insert_nano_particle(bc.atoms.copy(), nanop)
    mc.set_symbols(symbs)
    mc.init_cluster_info()
 
    formula = "(I1+I2)/(2*I3)" # Needle
    #formula = "2*I1/(I2+I3)" # Plate
    inert_init = InertiaCrdInitializer(
        fixed_nucl_mc=mc, matrix_element="Al", cluster_elements=["Mg", "Si"],
        formula=formula)
 
    inert_rng_constraint = InertiaRangeConstraint(
        fixed_nuc_mc=mc, inertia_init=inert_init, verbose=True)

    if use_bias:
        bias = InertiaBiasPotential.load(fname=inertia_bias_file)
        bias.inertia_range = inert_rng_constraint
        mc.add_bias(bias)

    nsteps = 100000

    if rank == 0:
        snap = Snapshot(atoms=bc.atoms, trajfile="{}/inertia.traj".format(workdir))
        mc.attach(snap, interval=100000)
    # reac_path = ReactionPathSampler(
    #     mc_obj=mc, react_crd=[0.05, 0.9], react_crd_init=inert_init,
    #     react_crd_range_constraint=inert_rng_constraint, n_windows=30,
    #     n_bins=10, data_file=h5file)
    # reac_path.run(nsteps=nsteps)
    # reac_path.save()

    inert_rng_constraint.range = [0.0, 0.9]
    fix_layer = FixEdgeLayers(thickness=5.0, atoms=mc.atoms)
    mc.add_constraint(inert_rng_constraint)
    mc.add_constraint(fix_layer)

    reac_path = AdaptiveBiasReactionPathSampler(
        mc_obj=mc, react_crd=[0.0, 0.9], react_crd_init=inert_init, 
        n_bins=100, data_file="{}/adaptive_bias.h5".format(workdir),
        mod_factor=1E-5, delete_db_if_exists=True, mpicomm=None,
        db_struct="{}/adaptive_bias_struct.db".format(workdir))
    reac_path.run()
    reac_path.save()
    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)
    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")
Example #6
0
def main(option="relax", size=8):
    from copy import deepcopy
    ceBulk = BulkCrystal( **kwargs )
    bc_copy = deepcopy(ceBulk)

    print (ecis)
    al,mg = get_pure_energies(ecis)
    print ("Al energy: {} eV/atom".format(al))
    print ("Mg energy: {} eV/atom".format(mg))
    #exit()
    #calc = CE( ceBulk, ecis, size=(3,3,3) )
    calc = get_ce_calc(ceBulk, kwargs, ecis, size=[15,15,15])
    ceBulk = calc.BC
    ceBulk.atoms.set_calculator( calc )
    #pure_energy = calc.get_energy()
    #print (pure_energy)
    #energy = calc.calculate( ceBulk.atoms, ["energy"],[(0,"Al","Mg")])
    #print (energy)
    #energy = calc.calculate( ceBulk.atoms, ["energy"], [()])
    #exit()

    if option == "heat":
        print("Running with cluser size {}".format(size))
        mc = FixedNucleusMC( ceBulk.atoms, 293, network_name=["c2_4p050_3"], network_element=["Mg"] )
        cluster_entropy(mc, size=size)
        return
    elif option == "pure_phase":
        pure_phase_entropy(bc_copy)
        return
    else:
        sizes = range(3,51)
        #sizes = np.arange(3, 51)
        energies = []
        cell = ceBulk.atoms.get_cell()
        diag = 0.5*(cell[0, :] + cell[1, :] + cell[2, :])
        pos = ceBulk.atoms.get_positions()
        pos -= diag
        lengths = np.sum(pos**2, axis=1)
        indx = np.argmin(lengths)
        symbs = [atom.symbol for atom in ceBulk.atoms]
        symbs[indx] = "Mg"
        print("Orig energy: {}".format(calc.get_energy()))
        calc.set_symbols(symbs)
        print("One atom: {}".format(calc.get_energy()))
        exit()

        for size in sizes:
            elements = {"Mg": size}
            T = np.linspace(50,1000,40)[::-1]

            # Reset the symbols to only Mg
            calc.set_symbols(symbs)
            mc = FixedNucleusMC( ceBulk.atoms, T, network_name=["c2_4p050_3"], network_element=["Mg"] )
            mc.grow_cluster(elements)
            mc.current_energy = calc.get_energy()
            low_en = LowestEnergyStructure( calc, mc, verbose=True )
            mc.attach( low_en )
            for temp in T:
                print ("Temperature {}K".format(temp))
                mc.T = temp
                mc.runMC(steps=10000, init_cluster=False)
                mc.reset()
                mc.is_first = False
            # atoms,clust = mc.get_atoms( atoms=low_en.atoms )
            write( "{}cluster{}_all.cif".format(folder,size), low_en.atoms )
            # write( "{}cluster{}_cluster.cif".format(folder,size), clust )
            energies.append(low_en.lowest_energy)
            print (sizes,energies)
        data = np.vstack((sizes,energies)).T
        np.savetxt( "{}energies_run2.txt".format(folder), data, delimiter=",")
Example #7
0
def main():
    atoms = atoms_with_calc(50)
    # mc = SoluteChainMC(atoms, 350, cluster_elements=["Mg", "Si"], 
    #     cluster_names=["c2_01nn_0"])

    T = [10]
    snapshot = Snapshot(trajfile="data/solute_chain{}_nostrain.traj".format(T[0]), atoms=atoms)
    first = True
    nano_part = get_nanoparticle()
    for temp in T:
        print("Current temperature {}".format(T))
        mc = FixedNucleusMC(
            atoms, temp, network_name=["c2_01nn_0"],
            network_element=["Mg", "Si"],
            max_constraint_attempts=1E6)
        backup = MCBackup(mc, overwrite_db_row=False, db_name="data/mc_solute_no_strain.db")
        mc.attach(backup, interval=20000)
        strain = get_strain_observer(mc)
        mc.add_bias(strain)

        if first:
            first = False
            #mc.grow_cluster({"Mg": 1000, "Si": 1000})
            symbs = insert_nano_particle(atoms.copy(), nano_part)
            mc.set_symbols(symbs)
            tag_by_layer_type(mc.atoms)
            cnst = ConstrainElementByTag(atoms=mc.atoms, element_by_tag=[["Mg", "Al"], ["Si", "Al"]])
            mc.add_constraint(cnst)

        #mc.build_chain({"Mg": 500, "Si": 500})
        fix_layer = FixEdgeLayers(thickness=5.0, atoms=mc.atoms)
        mc.add_constraint(fix_layer)
        mc.attach(snapshot, interval=20000)
        mc.runMC(steps=19000, init_cluster=False)