Exemplo n.º 1
0
def mgsi(initial=None, comment=None):
    if initial is None:
        pureAl = bulk('Al', cubic=True) * (N, N, N)
        pureAl = wrap_and_sort_by_position(pureAl)
        tags, _ = get_layers(pureAl, (0, 0, 1))
        success = False
        while not success:
            print("Generating new initial precipitate")
            initial, success = create_precipitate(pureAl.copy(), tags,
                                                  normal_radius)

    db = dataset.connect(DB_NAME)
    ref_tbl = db[REF]
    vac_tbl = db[VAC]
    sol_tbl = db[SOL]
    comment_tbl = db[COMMENT]

    runID = hex(random.randint(0, 2**32 - 1))
    if comment is not None:
        comment_tbl.insert({'runID': runID, 'comment': comment})

    eci = {}
    with open("data/almgsix_normal_ce.json", 'r') as infile:
        data = json.load(infile)
        eci = data['eci']

    settings = settingsFromJSON("data/settings_almgsiX_voldev.json")
    settings.basis_func_type = "binary_linear"
    atoms = attach_calculator(settings, initial.copy(), eci)
    atoms.numbers = initial.numbers
    ref_energy = atoms.get_potential_energy()
    ref_tbl.insert({'runID': runID, 'energy': ref_energy})

    for atom in atoms:
        if atom.symbol in ['Mg', 'Si']:
            pos = atom.position
            sol_tbl.insert({
                'runID': runID,
                'symbol': atom.symbol,
                'X': pos[0],
                'Y': pos[1],
                'Z': pos[2]
            })

    ref, neighbors = neighbor_list('ij', atoms, 3.0)
    for ref, nb in zip(ref, neighbors):
        if atoms[ref].symbol == 'Al' and atoms[nb].symbol in ['Mg', 'Si']:
            atoms[ref].symbol = 'X'
            e = atoms.get_potential_energy()
            atoms[ref].symbol = 'Al'
            pos = atoms[ref].position
            vac_tbl.insert({
                'runID': runID,
                'X': pos[0],
                'Y': pos[1],
                'Z': pos[2],
                'energy': e
            })
    atoms = removeAl(atoms)
def main(argv):
    fname = argv[0]
    chem_pot = argv[1:]
    initial = read(fname)
    db = dataset.connect("sqlite:///data/almgsi_mc_sgc.db")
    tbl = db['local_environ_mgsi']
    runID = hex(random.randint(0, 2**32-1))

    eci = {}
    with open("data/almgsix_normal_ce.json", 'r') as infile:
        data = json.load(infile)
        eci = data['eci']

    cf_names = [k for k in eci.keys() if k[1] == '2']
    settings = settingsFromJSON("data/settings_almgsiX_voldev.json")
    settings.basis_func_type = "binary_linear"
    atoms = attach_calculator(settings, initial.copy(), eci)

    atoms.numbers = initial.numbers
    for i, atom in enumerate(initial):
        atoms[i].tag = atom.tag

    mc = SGCMonteCarlo(atoms, 1000, symbols=['Al', 'X'])

    temps = [1000, 800, 700, 600, 500, 400, 300, 200, 100]

    active_sites = [i for i, atom in enumerate(atoms) if atom.tag != -1]
    constraint = ActiveElementConstraint(atoms, active_sites)
    observer = TaggedSiteSymbol('X', atoms)
    mc.add_constraint(constraint)
    mc.attach(observer)

    snap_fname = f"/work/sophus/local_environ_mc/traj/run{runID}"
    snap = Snapshot(fname=snap_fname, atoms=atoms)
    mc.attach(snap, interval=10*len(atoms))

    chem_pot_dict = {
        'Mg': 0.0,
        'Si': 0.0,
        'X': float(chem_pot[0])
    }
    chem_pot_dict = species_chempot2eci(settings.basis_functions, chem_pot_dict)
    for T in temps:
        mc.T = T
        mc.run(steps=100*len(atoms), chem_pot=chem_pot_dict)
        thermo = mc.get_thermodynamic_quantities()
        thermo['runID'] = runID
        thermo['initial'] = fname
        avgOcupp = {f'occupLayer{k}': v for k, v in observer.averages().items()}
        thermo.update(avgOcupp)
        tbl.insert(thermo)
def plot_dBdP():
    from clease.calculator import CleaseVolDep
    from clease.data_manager import CorrelationFunctionGetter
    with open("data/voldep_fit_resultenergy.json", 'r') as infile:
        data = json.load(infile)
    eci_eng = data['eci']
    with open("data/voldep_fit_resultvolume.json", 'r') as infile:
        data_vol = json.load(infile)
    eci_vol = data_vol['eci']
    settings = settingsFromJSON(settings_file)
    calc = CleaseVolDep(settings, eci_eng, eci_vol)

    corr_func = CorrelationFunctionGetter(
        settings.db_name, table, settings.all_cf_names
    )
    ids = set()
    db = connect(settings.db_name)
    dBdP_db = []
    for row in db.select([('struct_type', '=', 'initial')]):
        ids.add(row.id)
        dBdP_db.append(row.dBdP)
    print(ids)
    cf = corr_func(ids)
    atoms = settings.atoms.copy()
    atoms.set_calculator(calc)

    dBdP = []
    for r in range(0, cf.shape[0]):
        cf_dict = {k: v for k, v in zip(corr_func.names, list(cf[r, :]))}
        dBdP.append(calc.get_dBdP(cf_dict))
    
    fig = plt.figure(figsize=(4, 3))
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(dBdP_db, dBdP, 'o', mfc='none', markersize=2, color='#742d18')
    xmin = min(dBdP)
    xmax = max(dBdP)
    rng = xmax - xmin
    xmin -= 0.01*rng
    xmax += 0.01*rng
    ax.plot([xmin, xmax], [xmin, xmax], color='#1c1c14')
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)

    ax.set_xlabel("$(\u2202 B/\u2202 P)_0$ EMT")
    ax.set_ylabel("$(\u2202 B/\u2202 P)_0$ CE")
    fig.tight_layout()
    fig.savefig("fig/dBdP_proper.png")
Exemplo n.º 4
0
def fixed_comp(conc_array):
    db = dataset.connect("sqlite:///data/almgsi_mc_sgc.db")
    tbl = db['sa_fixed_conc']
    runID = hex(random.randint(0, 2**32 - 1))

    conc = {
        'Mg': float(conc_array[0]),
        'Si': float(conc_array[1]),
        'X': float(conc_array[2])
    }

    eci = {}
    with open("data/almgsix_normal_ce.json", 'r') as infile:
        data = json.load(infile)
        eci = data['eci']

    settings = settingsFromJSON("data/settings_almgsiX_voldev.json")
    settings.basis_func_type = "binary_linear"
    #print(settings.basis_functions)
    #exit()
    atoms = bulk('Al', a=4.05, cubic=True) * (4, 4, 4)
    atoms = attach_calculator(settings, atoms, eci)
    start = 0
    for k, v in conc.items():
        num = int(v * len(atoms))
        for i in range(start, start + num):
            atoms[i].symbol = k
        start += num

    mc = Montecarlo(atoms, 1000)
    temps = [1000, 800, 600, 500, 400, 300, 200, 100]
    for T in temps:
        mc.T = T
        mc.run(steps=10 * len(atoms))
        thermo = mc.get_thermodynamic_quantities()
        thermo['runID'] = runID
        tbl.insert(thermo)

    fname = "data/gs/" + atoms.get_chemical_formula() + str(runID) + ".xyz"
    write(fname, atoms)
Exemplo n.º 5
0
def main(argv):
    db = dataset.connect("sqlite:///data/almgsi_mc_sgc.db")
    tbl = db['random_direction_sa']
    runID = hex(random.randint(0, 2**32 - 1))

    eci = {}
    with open("data/almgsix_normal_ce.json", 'r') as infile:
        data = json.load(infile)
        eci = data['eci']

    cf_names = [k for k in eci.keys() if k[1] == '2']
    settings = settingsFromJSON("data/settings_almgsiX_voldev.json")
    settings.basis_func_type = "binary_linear"
    #print(settings.basis_functions)
    #exit()
    atoms = bulk('Al', a=4.05, cubic=True) * (4, 4, 4)
    atoms = attach_calculator(settings, atoms, eci)

    obs = CorrelationFunctionObserver(atoms.get_calculator(), names=cf_names)

    temps = [1000, 800, 600, 500, 400, 300, 200]
    chem_pot = {
        'Mg': float(argv[0]),
        'Si': float(argv[1]),
        'X': float(argv[2]),
    }
    chem_pot = species_chempot2eci(settings.basis_functions, chem_pot)

    mc = SGCMonteCarlo(atoms, 1000, symbols=['Al', 'Mg', 'Si', 'X'])
    mc.attach(obs, interval=100)
    for T in temps:
        mc.T = T
        mc.run(steps=100 * len(atoms), chem_pot=chem_pot)
        thermo = mc.get_thermodynamic_quantities()
        cfs = obs.get_averages()
        cfs = {k: v for k, v in cfs.items() if 'c2' in k}
        mc.reset()
        thermo.update(cfs)
        thermo['runID'] = runID
        tbl.insert(thermo)
def plot():
    from clease.calculator import CleaseVolDep
    with open(f"data/voldep_fit_resultenergy.json", 'r') as infile:
        data = json.load(infile)
    X = np.array(data['X'])
    y = np.array(data['y'])
    coeff = data['coeff']

    settings = settingsFromJSON(settings_file)
    eci_eng = data['eci']
    with open("data/voldep_fit_resultvolume.json", 'r') as infile:
        data_vol = json.load(infile)
    eci_vol = data_vol['eci']
    calc = CleaseVolDep(settings, eci_eng, eci_vol)

    atoms = settings.atoms.copy()*(2, 2, 2)
    atoms = wrap_and_sort_by_position(atoms)
    #atoms.set_calculator(calc)

    plots_info = [
        {
            'ylabel': 'Energy CE (eV/atom)',
            'xlabel': 'Energy EMT (eV/atom)',
            'fname': 'fig/energy_pred.pdf',
            'factor': 1.0,
        },
        {
            'ylabel': 'Bulk mod. CE (GPa)',
            'xlabel': 'Bulk mod. EMT (GPa)',
            'fname': 'fig/bulk_mod.pdf',
            'factor': 1.0/GPa
        },
        {
            'ylabel': r'$dB/dP$ (CE)',
            'xlabel': r'$dB/dP$ (DFT)',
            'fname': 'fig/dBdP.pdf',
            'factor': 1.0
        }
    ]

    pred = X.dot(coeff)
    for i, info in enumerate(plots_info):
        fig = plt.figure(figsize=(4, 3))
        ax = fig.add_subplot(1, 1, 1)
        start = int(i*len(y)/3)
        end = int((i+1)*len(y)/3)
        dft_data = y[start:end]*info['factor']
        ce_data = pred[start:end]*info['factor']

        xmin = np.min(dft_data)
        xmax = np.max(dft_data)
        rng = xmax - xmin
        if rng < 1e-3:
            rng = 1e-3
        xmin -= 0.01*rng
        xmax += 0.01*rng
        ax.plot([xmin, xmax], [xmin, xmax], color='#1c1c14')
        
        ax.plot(dft_data, ce_data, 'o', mfc='none', color='#742d18', markersize=2)
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)

        # Add out of sample
        # if 'Energy' in info['xlabel']:
        #     out_pred = []
        #     out_ex = []
        #     for i in range(40):
        #         for atom in atoms:
        #             atom.symbol = choice(settings.concentration.basis_elements[0])
        #         emt_calc = EMT()
        #         atoms_cpy = atoms.copy()
        #         atoms_cpy.set_calculator(emt_calc)
        #         out_ex.append(atoms.get_potential_energy()/len(atoms))
        #         out_pred.append(atoms.get_potential_energy()/len(atoms))

            #ax.plot(out_ex, out_pred, 'v')
            
        ax.set_xlabel(info['xlabel'])
        ax.set_ylabel(info['ylabel'])
        if 'Pressure' in info['xlabel']:
            ax.set_xticks([0.0])
        fig.tight_layout()
        fig.savefig(info['fname'])
        fig.savefig(info['fname'].rpartition('.')[0] + '.png')
        print(f"Figure saved to {info['fname']}")
def fit(fit_type="energy"):
    settings = settingsFromJSON(settings_file)
    #print(settings.multiplicity_factor)
    #exit()
    cf_names = settings.all_cf_names
    #cf_names = None
    cf_names = [n for n in cf_names if int(n[1]) < 3]
    print(cf_names)
    order = 5
    if fit_type == "energy":
        data = CorrelationFunctionGetterVolDepECI(
            settings.db_name,
            table,
            cf_names,
            order=order,
            properties=['energy', 'bulk_mod', 'dBdP'],
            cf_order=2
        )
        pressure_data = deepcopy(data)
        pressure_data.properties=('pressure')
    elif fit_type == "volume":
        data = CorrFuncVolumeDataManager(
             settings.db_name,
            table,
            cf_names
        )

    skip_groups = [5, 13, 42, 71, 84, 1490300799, 3797755424]
    scond = [('struct_type', '=', 'initial')]
    for sg in skip_groups:
        scond.append(('name', '!=', f'group{sg}'))
    X, y = data.get_data(scond)

    Xp, yp = pressure_data.get_data(scond)
    Np = int(Xp.shape[0]/2)
    Xp = Xp[Np:, :]
    yp = yp[Np:]

    N = X.shape[0]

    #X[int(N/3):int(2*N/3)] *= 1000.0
    #y[int(N/3):] *= 1000.0

    regressor = PhysicalRidge(normalize=False)
    regressor.add_constraint(Xp, yp)
    groups = data.groups()
    #regressor.sizes = [int(n[1]) for n in data._feat_names]
    regressor.sizes = [sum(int(n[1]) for n in m.split('*')) for m in data._feat_names]
    #print(regressor.sizes)
    #exit()
    prog = re.compile(r"d(\d+)")
    regressor.diameters = []
    for cf_name in data._feat_names:
        result = prog.findall(cf_name)
        if not result:
            regressor.diameters.append(0.0)
        else:
            regressor.diameters.append(sum(float(x) for x in result))

    params = {
            'lamb_dia': np.logspace(-6, 6, 5000).tolist(),
            'lamb_size': np.logspace(-6, 6, 5000).tolist(),
            'size_decay': ['linear', 'exponential', 'poly2', 'poly4', 'poly6'],
            'dia_decay': ['linear', 'exponential', 'poly2', 'poly4', 'poly6']
        }
    res = random_cv_hyper_opt(regressor, params, X, y, cv=5, num_trials=100, groups=groups)

    outfile = f"data/voldep_fit_result{fit_type}.json"
    data = {
        'names': cf_names,
        'coeff': res['best_coeffs'].tolist(),
        'X': X.tolist(),
        'y': y.tolist(),
        'cv': res['best_cv'],
        'eci': {n: c for n, c in zip(data._feat_names, res['best_coeffs'])},
    }

    with open(outfile, 'w') as out:
        json.dump(data, out)
    print(f"Results written to: {outfile}")