Ejemplo n.º 1
0
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)
Ejemplo n.º 2
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")
Ejemplo n.º 4
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)
Ejemplo n.º 5
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
Ejemplo n.º 6
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)
Ejemplo n.º 7
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=",")
Ejemplo n.º 8
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)
Ejemplo n.º 9
0
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)
Ejemplo n.º 10
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)
Ejemplo n.º 11
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()
Ejemplo n.º 12
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)