Example #1
0
def amp_md(atoms, nstep, dt):
    from ase import units
    from ase.md.velocitydistribution import MaxwellBoltzmannDistribution
    from ase.md import VelocityVerlet

    traj = ase.io.Trajectory("traj.traj", 'w')

    try:
        calc = Amp.load("amp.amp")
    except FileNotFoundError:
        try:
            calc = Amp.load("amp-untrained-parameters.amp") 
        except FileNotFoundError:
            print("Error: amp-pes.amp file does not exist, input amp-pot file by -p")
            sys.exit(1)

    atoms.set_calculator(calc)
    atoms.get_potential_energy()
    MaxwellBoltzmannDistribution(atoms, 300 * units.kB)
    traj.write(atoms)
    dyn = VelocityVerlet(atoms, dt=dt * units.fs)
    f = open("md.ene", "w")
    f.write("{:^5s} {:^10s} {:^10s} {:^10s}\n".format("time","Etot","Epot","Ekin"))
    for step in range(nstep):
        pot = atoms.get_potential_energy()  # 
        kin = atoms.get_kinetic_energy()
        tot = pot + kin
        f.write("{:5d}{:10.5f}{:10.5f}{:10.5f}\n".format(step, tot, pot, kin))
        print("{}: Total Energy={}, POT={}, KIN={}".format(step, tot, pot, kin))
        dyn.run(2)
        traj.write(atoms)                   # write kinetic energy, but pot is not seen in ase
    f.close()        
Example #2
0
    def update(self, rs, es, fs):
        """
        training data with machine-learning module given by ml_module
        """
        print "Start to train"
        if self.train_endpoints:
            print "End points used for training"
            nimages = self.nimages
            n_offset = 0
            self.train_endpoints = False
        else:
            nimages = self.nimages - 2
            n_offset = 1

        for i in range(nimages):
            self.band.path[i + n_offset].set_positions(rs[i])
            #self.approxPot_replica.set_positions(r)
            #f = f - self.approxPot_replica.get_forces()
            #e = e - self.approxPot_replica.get_potential_energy()

            pseudoAtoms = self.band.path[i + n_offset].copy()
            pseudoAtoms.set_calculator(pseudoCalculator(energy= es[i], \
                                                        forces= fs[i]))
            pseudoAtoms.get_potential_energy()
            pseudoAtoms.get_forces()
            self.training_set.append(pseudoAtoms)
            self.training_traj.write(pseudoAtoms)

        #self.training_set=Trajectory('training.traj','r')
        #os.chdir(workdir)
        if os.path.exists('amp-fingerprint-primes.ampdb'):
            os.system('rm -rf amp-fingerprint-primes.ampdb')
        if os.path.exists('amp-fingerprints.ampdb'):
            os.system('rm -rf amp-fingerprints.ampdb')
        if os.path.exists('amp-fingerprints.ampdb'):
            os.system('rm -rf amp-neighborlists.ampdb')
        #if os.path.exists('amp.amp'):
        #   os.system('rm amp.amp')
        #if os.path.exists('amp-untrained-parameters.amp'):
        #load nn model including lossfunction
        #   os.system('rm amp-untrained-parameters.amp')
        try:
            self.progress_log.write("Train ml model\n")
            self.ml_module.train(images='training.traj', overwrite=True)
        except TrainingConvergenceError:
            os.system('mv amp-untrained-parameters.amp amp.amp')
            pass
        #load ml model
        try:
            ml_calc = Amp.load('amp.amp')
        except:
            ml_calc = Amp.load('amp-untrained-parameters.amp')
            pass

        for i in range(self.nimages):
            self.band_ml.path[i].set_calculator(ml_calc)
Example #3
0
def calc_test_images(test_images,
                     amp_pes,
                     title,
                     suptitle,
                     ncore,
                     Lgraph,
                     val_id=None,
                     nmol=1,
                     Ltwinx=None):
    try:
        calc = Amp.load(amp_pes)
    except FileNotFoundError:
        try:
            calc = Amp.load("amp-untrained-parameters.amp")
        except FileNotFoundError:
            print(
                "Error: amp-pes.amp file does not exist, input amp-pot file by -p"
            )
            sys.exit(1)
    escale = 1  # my_chem.ev2kj
    y = []
    y_bar = []
    #return         # this runs
    for mol in test_images:
        y.append(mol.get_potential_energy() / nmol)
        mol.set_calculator(calc)
        y_bar.append(mol.get_potential_energy() / nmol)

    with open("amp_test.txt", 'w') as f:
        f.write("\ttrue\t\thypothesis\n")
        for y1, ybar1 in zip(y, y_bar):
            f.write(f"{y1:15.5f} {ybar1:15.5f}\n")

    if Lgraph:
        modulename = 'myplot2D'  ### FOR MLET
        if modulename not in sys.modules:
            import myplot2D
        err, res_max = myplot2D.draw_amp_twinx(y,
                                               y_bar,
                                               title,
                                               suptitle,
                                               Ltwinx=Ltwinx,
                                               Ldiff=True)
    else:
        h_conv = np.array(y_bar)  # * escale
        y_conv = np.array(y)  # * escale
        diff = np.subtract(h_conv, y_conv)
        err = np.sqrt((diff**2).mean())
        res_max = abs(max(diff, key=abs))
        #err = rmse(y, y_bar)*escale
    return err, res_max
Example #4
0
def re_train_images(images, HL, E_conv):
    Hidden_Layer=tuple(HL)
    print("Hidden Layer: {}".format(Hidden_Layer))
    print("Energy convergence: {}".format(E_conv))
    calc = Amp.load("amp.amp", cores=20)
    calc.model.lossfunction = LossFunction(convergence={'energy_rmse': E_conv})
    calc.train(images=images, overwrite=True)
Example #5
0
def main():
    calc = Amp.load('amp.amp')
    """Read the reactant coordinates"""
    p1 = read('POSCAR_rs', index=0, format='vasp')
    #    p1.set_cell([[20,0,0],[0,20,0],[0,0,20]],scale_atoms=False)
    #    p1.set_pbc((True, True, True))
    p1.set_calculator(calc)
    """Read the product coordinates"""
    p2 = read('POSCAR_fs', index=0, format='vasp')
    p2.set_calculator(calc)

    nim = 12  # number of images, including end points
    band = neb.ssneb(p1, p2, numImages=nim, method='normal', ss=False)

    # to restart, uncomment the following lines which read the previous optimized images into the band
    #    for i in range(1,nim-1):
    #        filename = str(i)+'.CON'
    #        b = read(filename,format='vasp')
    #        band.path[i].set_positions(b.get_positions())
    #        band.path[i].set_cell(b.get_cell())

    #    opt = neb.qm_ssneb(band, maxmove =0.1, dt=0.05)
    #Uncomment to use fire optimization algorithm
    opt = neb.fire_ssneb(band, maxmove=0.1, dtmax=0.05, dt=0.05)
    opt.minimize(forceConverged=0.10, maxIterations=400)
Example #6
0
def run_md(fdata, atoms):
    from ase import units
    from ase.md.velocitydistribution import MaxwellBoltzmannDistribution
    from ase.md import VelocityVerlet
    fdata = fdata[:-7]

    traj = ase.io.Trajectory(fdata + ".traj", 'w')

    calc = Amp.load("amp.amp")
    atoms.set_calculator(calc)
    atoms.get_potential_energy()
    MaxwellBoltzmannDistribution(atoms,
                                 100. * units.kB)  #Boltzmann constant eV/K
    traj.write(atoms)
    dyn = VelocityVerlet(atoms, dt=1. * units.fs)

    for step in range(200):
        pot = atoms.get_potential_energy()  #
        kin = atoms.get_kinetic_energy()
        with open(fdata + '.txt', 'a') as f:
            f.write("{}: Total Energy={}, POT={}, KIN={}\n".format(
                step, pot + kin, pot, kin))
        dyn.run(5)
        ase.io.write(fdata + '.xyz', ase.io.read(fdata + '.traj'), append=True)
        traj.write(atoms)
Example #7
0
    def get_atomic_electronegativities(self, hash, calc):
        """
        Returns
        -------
        atomic_electronegativity : dict
            Dictionary with keys (index, symbol) and value  (atomic
            electronegativity).
        electronegativity_vector : list
            List of electronegativities.
        """
        atomic_electronegativity = OrderedDict()
        electronegativity_vector = []

        # calculating fingerprints
        self.descriptor.calculate_fingerprints(self.images)
        self.descriptor.fingerprints.open()

        fingerprints = self.descriptor.fingerprints[hash]

        # Load Amp calculator
        nn_calc = Amp.load(self.calc)

        for index, (symbol, afp) in enumerate(fingerprints):
            en = nn_calc.model.calculate_atomic_energy(afp, index, symbol)
            atomic_electronegativity[(index, symbol)] = en
            electronegativity_vector.append(-en)

        electronegativity_vector = np.array(electronegativity_vector)

        return atomic_electronegativity, electronegativity_vector
Example #8
0
def train_test():
    label = 'train_test_g5/calc'
    train_images = generate_data(2)
    elements = ['Pt', 'Cu']
    G = make_symmetry_functions(elements=elements,
                                type='G2',
                                etas=np.logspace(np.log10(0.05),
                                                 np.log10(5.),
                                                 num=4))
    G += make_symmetry_functions(elements=elements,
                                 type='G5',
                                 etas=[0.005],
                                 zetas=[1., 4.],
                                 gammas=[+1., -1.])

    G = {element: G for element in elements}

    calc = Amp(descriptor=Gaussian(Gs=G),
               model=NeuralNetwork(hiddenlayers=(3, 3)),
               label=label,
               cores=1)
    loss = LossFunction(convergence={'energy_rmse': 0.02, 'force_rmse': 0.03})
    calc.model.lossfunction = loss

    calc.train(images=train_images, )
    for image in train_images:
        print("energy = %s" % str(calc.get_potential_energy(image)))
        print("forces = %s" % str(calc.get_forces(image)))

    # Test that we can re-load this calculator and call it again.
    del calc
    calc2 = Amp.load(label + '.amp')
    for image in train_images:
        print("energy = %s" % str(calc2.get_potential_energy(image)))
        print("forces = %s" % str(calc2.get_forces(image)))
Example #9
0
    def create_calc(self, label, dblabel):
        amp_label = os.path.join(self.calc_dir, label)
        amp_dblabel = os.path.join(self.calc_dir, dblabel)
        amp_name = amp_label + ".amp"
        if not os.path.exists(amp_name):
            print("Creating calculator {}...".format(amp_name))
            loss_function = LossFunction(
                convergence=self.convergence,
                energy_coefficient=self.energy_coefficient,
                force_coefficient=self.force_coefficient,
                overfit=self.overfit,
            )
            model = NeuralNetwork(
                hiddenlayers=self.hidden_layers,
                activation=self.activation,
                lossfunction=loss_function,
                weights=None,
                scalings=None,
                prescale=True,
            )
            descriptor = Gaussian(cutoff=self.cutoff, Gs=self.Gs, fortran=True)
            calc = Amp(descriptor=descriptor,
                       model=model,
                       label=amp_label,
                       dblabel=amp_dblabel)

            return calc
        else:
            print("Calculator {} already exists!".format(amp_name))
            calc = Amp.load(amp_name, label=amp_label, dblabel=amp_dblabel)

            return calc
Example #10
0
def run_md(atoms):
    from ase import units
    from ase.md.velocitydistribution import MaxwellBoltzmannDistribution
    from ase.md import VelocityVerlet

    traj = ase.io.Trajectory("traj.traj", 'w')

    calc = Amp.load("amp.amp")
    atoms.set_calculator(calc)
    atoms.get_potential_energy()
    MaxwellBoltzmannDistribution(atoms, 10. * units.kB)
    traj.write(atoms)
    dyn = VelocityVerlet(atoms, dt=1. * units.fs)
    f = open("md.ene", "w")
    f.write("{:^5s}{:^10s}{:^10s}{:^10s}\n".format("time", "Etot", "Epot",
                                                   "Ekin"))
    for step in range(100):
        pot = atoms.get_potential_energy()  #
        kin = atoms.get_kinetic_energy()
        tot = pot + kin
        f.write("{:5d}{:10.5f}{:10.5f}{:10.5f}\n".format(step, tot, pot, kin))
        print("{}: Total Energy={}, POT={}, KIN={}".format(
            step, tot, pot, kin))
        dyn.run(10)
        traj.write(atoms)
    f.close()
Example #11
0
def train_test():
    """Gaussian/KRR train test."""
    label = 'train_test/calc'
    train_images = generate_data(2)
    traj = Trajectory('trainingset.traj', mode='w')

    for image in train_images:
        traj.write(image)

    calc = Amp(descriptor=Gaussian(),
               model=KernelRidge(forcetraining=True, trainingimages='trainingset.traj'),
               label=label,
               cores=1)

    calc.train(images=train_images,)
    for image in train_images:
        print("energy = %s" % str(calc.get_potential_energy(image)))
        print("forces = %s" % str(calc.get_forces(image)))

    # Test that we can re-load this calculator and call it again.
    del calc
    calc2 = Amp.load(label + '.amp')
    for image in train_images:
        print("energy = %s" % str(calc2.get_potential_energy(image)))
        print("forces = %s" % str(calc2.get_forces(image)))
Example #12
0
def run_amp(fdata, job, ndata):

    total_images = ase.io.read(fdata, index=':')
    if job == "train":
        if not ndata:
            #images = ase.io.read(fdata, index=':')
            images = total_images
            print("Start training using all the data %d" % len(total_images))
        else:
            #images = ase.io.read(fdata, index=':ndata')
            images = total_images[:ndata]
            print("number of traing data %d/%d" % (len(images), len(total_images)))
        train_images(images)

    elif job == "test":
        #images = ase.io.read(fdata, index='ndata:')
        images = total_images[ndata:]

        calc = Amp.load("amp.amp")
        #print(images[0])
        y=[]
        y_bar=[]
        for mol in images:
            y.append(mol.get_potential_energy())
            #print(mol.get_potential_energy())
            mol.set_calculator(calc)
            y_bar.append(mol.get_potential_energy())
            #print(mol.get_potential_energy())
        #print(images[0])

        draw(y, y_bar)
    return
Example #13
0
    def update(self, r, e, f):
        """
        training data with machine-learning module given by ml_module
        """
        #workdir = self.cwd+'/training'
        #if not os.path.isdir(workdir):
        #   make_dir(workdir)
        r = r.reshape(-1, 3)
        self.atoms.set_positions(r)
        #self.approxPot_replica.set_positions(r)
        #f = f - self.approxPot_replica.get_forces()
        #e = e - self.approxPot_replica.get_potential_energy()

        pseudoAtoms = self.atoms.copy()
        pseudoAtoms.set_calculator(pseudoCalculator(energy= e, \
                                                    forces= f))
        pseudoAtoms.get_potential_energy()
        pseudoAtoms.get_forces()

        self.training_set.append(pseudoAtoms)
        self.training_traj.write(pseudoAtoms)
        #self.training_set=Trajectory('training.traj','r')
        #os.chdir(workdir)
        if os.path.exists('amp-fingerprint-primes.ampdb'):
            os.system('rm -rf amp-fingerprint-primes.ampdb')
        if os.path.exists('amp-fingerprints.ampdb'):
            os.system('rm -rf amp-fingerprints.ampdb')
        if os.path.exists('amp-fingerprints.ampdb'):
            os.system('rm -rf amp-neighborlists.ampdb')
        #if os.path.exists('amp.amp'):
        #   os.system('rm amp.amp')
        #if os.path.exists('amp-untrained-parameters.amp'):
        #load nn model including lossfunction
        #   os.system('rm amp-untrained-parameters.amp')
        try:
            self.progress_log.write("Train ml model\n")
            self.ml_module.train(images='training.traj', overwrite=True)
        except TrainingConvergenceError:
            os.system('mv amp-untrained-parameters.amp amp.amp')
            pass
        #load ml model
        try:
            self.replica.set_calculator(Amp.load('amp.amp'))
        except:
            self.replica.set_calculator(
                Amp.load('amp-untrained-parameters.amp'))
            pass
Example #14
0
def exe_test_images(images_4test, amp_pes, title, suptitle):
    calc = Amp.load(amp_pes)
    y = []
    y_bar = []
    for mol in images_4test:
        y.append(mol.get_potential_energy())
        mol.set_calculator(calc)
        y_bar.append(mol.get_potential_energy())
    draw_dots_two(y, y_bar, title, suptitle)
def test():
    # LOAD DATA
    path = "/home/unknown/Dropbox/Oscar/Skola/LTU/Project course engineering physics/Results/CNT Capped/data"  # Path to data
    results = [
        y for x in os.walk(path) for y in glob(os.path.join(x[0], '*.db'))
    ]

    print("Files found and imported:")
    for i in results:
        print i

    images = []
    for i in results:
        images.extend(io.read(i, index=':'))

    #images = images[:500]
    print('Total number of images imported:  %i' % len(images))

    # Train the calculator.
    #train_images, test_images = randomize_images(images)
    train_images = images
    #calc = Amp(descriptor=Gaussian(),
    #          model=NeuralNetwork(hiddenlayers=(20, 20)))
    calc = Amp.load('parameters-checkpoint-600.amp')
    #calc.model.lossfunction = LossFunction(
    #    convergence={'energy_rmse': 1,
    #                'force_rmse': 0.01})
    #calc.train(train_images)

    # Plot and test the predictions.
    import matplotlib
    matplotlib.use('Agg')
    from matplotlib import pyplot

    fig, ax = pyplot.subplots()
    #train = open('train.csv','a')
    #test = open('test.csv','a')

    #for image in train_images:
    #    actual_energy = image.get_potential_energy()
    #    predicted_energy = calc.get_potential_energy(image)
    #    ax.plot(actual_energy, predicted_energy, 'b.')
    #    string = "%s,%s\n" %(actual_energy,predicted_energy)
    #    train.write(string)

    #train.close()

    for image in train_images:
        actual_energy = image.get_potential_energy()
        predicted_energy = calc.get_potential_energy(image)
        ax.plot(actual_energy, predicted_energy, 'r.')
        string = "%s,%s\n" % (actual_energy, predicted_energy)

    ax.set_xlabel('Actual energy, eV')
    ax.set_ylabel('Amp energy, eV')

    fig.savefig('parityplot.png')
Example #16
0
def run_amp(fdata, job, ndata, HL, E_conv):
    total_images = ase.io.read(fdata, index=':')
    if job == "train":
        if not ndata:
            #images = ase.io.read(fdata, index=':')
            images = total_images
            print("Start training using all the data %d" % len(total_images))

            #images = ase.io.read(fdata, index=':
            images = total_images[:ndata]
            print("number of traing data %d/%d" %
                  (len(images), len(total_images)))
        train_images(images, HL, E_conv)

    elif job == "test":
        #images = ase.io.read(fdata, index='ndata:')
        images = total_images[ndata:]

        import glob
        amps = glob.glob('*.amp')
        if 'amp.amp' in amps:
            calc = Amp.load("amp.amp")
        else:
            calc = Amp.load("amp-untrained-parameters.amp")
        #print(images[0])
        y = []
        y_bar = []
        for mol in images:
            y.append(mol.get_potential_energy())
            #print(mol.get_potential_energy())
            mol.set_calculator(calc)
            y_bar.append(mol.get_potential_energy())
            #print(mol.get_potential_energy())
        #print(images[0])

        draw(fdata, y, y_bar)
    elif job == 'md':
        if not ndata:
            atoms = ase.io.read(fdata, index='0')
        else:
            atoms = ase.io.read(fdata, index=ndata)
        run_md(fdata, atoms)
    return
Example #17
0
def run_amp(fdata, job, ndata, HL, E_conv):

    total_images = ase.io.read(fdata, index=':')
    if job == "train":
        if not ndata:
            #images = ase.io.read(fdata, index=':')
            images = total_images
            print("Start training using all the data %d" % len(total_images))
        else:
            #images = ase.io.read(fdata, index=':ndata')
            images = total_images[:ndata]
            print("number of training data %d/%d" % (len(images), len(total_images)))
        train_images(images, HL, E_conv)

    elif job == "retrain":
        if not ndata:
            images = total_images
            print("Start re-training using all the data %d" % len(total_images))
        else:
            images = total_images[:ndata]
            print("number of re-training data %d/%d" % (len(images), len(total_images)))
        re_train_images(images, HL, E_conv)

    elif job == "test":
        #images = ase.io.read(fdata, index='ndata:')
        images = total_images[ndata:]

        calc = Amp.load("amp.amp")
        #print(title)
        #print(images[0])
        y=[]
        y_bar=[]
        for mol in images:
            y.append(mol.get_potential_energy())
            #print(mol.get_potential_energy())
            mol.set_calculator(calc)
            y_bar.append(mol.get_potential_energy())
            #print(mol.get_potential_energy())
        #print(images[0])

        h_conv = np.array(y_bar) * kcal2kj
        y_conv = np.array(y) * kcal2kj
        diff =  np.subtract(h_conv,y_conv) 
        rmse = np.sqrt((diff**2).mean())
        max_res = abs(max(diff, key=abs))
        with open("score", 'w') as f:
            f.write("{}\n".format(0.9*max_res+0.1*rmse))

        os.system("cat HL score > ./pop_fit.txt")
        if os.path.isfile('HL'):
            os.remove('HL')
          
      
    return
Example #18
0
def exe_test_images(job, test_images, amp_pes, title, suptitle, val_id=None):
    calc = Amp.load(amp_pes)
    y = []
    y_bar = []
    #return         # this runs
    for mol in test_images:
        y.append(mol.get_potential_energy())
        mol.set_calculator(calc)
        y_bar.append(mol.get_potential_energy())
    return  # this evokes error

    if re.search("te", job):
        draw_dots_two(y, y_bar, title, suptitle)
    elif re.search("va", job):
        err = rmse(y, y_bar)
        print("in job {}-{}: validation error is {}".format(job, val_id, err))
Example #19
0
def generate_data(count, filename='cmd.traj'):
    """Generates test or training data with a simple MD simulation."""
    if os.path.exists(filename):
        return
    traj = io.Trajectory(filename, 'w')
    atoms = io.read('2.xyz')
    atoms.set_calculator(Amp.load('sio2.amp'))
    atoms.get_potential_energy()
    traj.write(atoms)
    mb(atoms, 300. * units.kB)
    #    dyn = vv(atoms, dt=1. * units.fs, logfile='cmd.log')
    dyn = NVTB(atoms,
               timestep=0.5 * units.fs,
               temperature=300,
               taut=2.0 * units.fs,
               logfile='cmd.log')
    for step in range(count - 1):
        dyn.run(1)
        traj.write(atoms)
Example #20
0
def force_integration(images, amp_calc=None):
    """Compute force integration over images using pure ML

    Parameters
    ----------
    images : str
        Path to images.
    amp_calc : str
        Path to .amp file containing information of the machine-learning model.
    """

    # Loading data
    data = Trajectory(images)

    # Computing references E0 can be 0 or a DFT calcualtion of the reference
    E0 = 0
    p0 = data[0].get_positions()

    # Loading Amp calculator
    amp_calc = Amp.load(amp_calc)

    temp = 0
    for index in range(len(data)):
        image = data[index]
        p1 = image.get_positions()

        if index == 0:
            forcesi = amp_calc.get_forces(data[0])
        else:
            p0 = data[index - 1].get_positions()
            forcesi = amp_calc.get_forces(data[index - 1])

        forcesj = amp_calc.get_forces(image)
        forces = (forcesj + forcesi) / 2

        E = 0.
        for atom in range(len(image)):
            driu = p1[atom] - p0[atom]
            temp += forces[atom].dot(driu)

        E = E0 - temp
        print(E)
        return E
Example #21
0
def run_md(atoms):
    from ase import units
    from ase.md.velocitydistribution import MaxwellBoltzmannDistribution
    from ase.md import VelocityVerlet

    traj = ase.io.Trajectory("traj.traj", 'w')

    calc = Amp.load("amp.amp")
    atoms.set_calculator(calc)
    atoms.get_potential_energy()
    MaxwellBoltzmannDistribution(atoms, 300. * units.kB)
    traj.write(atoms)
    dyn = VelocityVerlet(atoms, dt=1. * units.fs)
    for step in range(100):
        pot = atoms.get_potential_energy()  #
        kin = atoms.get_kinetic_energy()
        print("{}: Total Energy={}, POT={}, KIN={}".format(
            step, pot + kin, pot, kin))
        dyn.run(10)
        traj.write(atoms)
Example #22
0
def exe_test_images(job,
                    test_images,
                    amp_pes,
                    title,
                    suptitle,
                    Lgraph,
                    val_id=None):
    calc = Amp.load(amp_pes)
    y = []
    y_bar = []
    #return         # this runs
    for mol in test_images:
        y.append(mol.get_potential_energy())
        mol.set_calculator(calc)
        y_bar.append(mol.get_potential_energy())

    if Lgraph:
        err = draw_dots_two(y, y_bar, title, suptitle)
    else:
        err = rmse(y, y_bar) * my_chem.ev2kj
    return err
Example #23
0
def calc_train_images(images, HL, E_conv, f_conv, f_coeff, ncore, amp_pot=None):
    Hidden_Layer=tuple(HL)
    print("Hidden Layer: {}".format(Hidden_Layer))
    print("Energy convergence: {}".format(E_conv))
    cores={'localhost':ncore}   # 'localhost' depress SSH, communication between nodes
    ### load "amp.amp"
    if amp_pot:
        calc = Amp.load(amp_pot)
    calc = Amp(descriptor=Gaussian(), model=NeuralNetwork(hiddenlayers=Hidden_Layer), cores=cores)
    ### Global Search in Param Space
    Annealer(calc=calc, images=images, Tmax=20, Tmin=1, steps=4000)

    if f_conv <= 0.0:
        E_maxresid = E_conv*3
        #convergence={'energy_rmse': E_conv}
        convergence={'energy_rmse': E_conv, 'energy_maxresid': E_maxresid}
    else:
        convergence={'energy_rmse': E_conv, 'force_rmse':f_conv}
    calc.model.lossfunction = LossFunction(convergence=convergence, force_coefficient=f_coeff)  # setting
    calc.train(images=images, overwrite=True)
    return
Example #24
0
def train_test():
    """Gaussian/Neural train test."""
    label = 'train_test/calc'
    train_images = generate_data(2)

    calc = Amp(descriptor=Gaussian(),
               model=NeuralNetwork(hiddenlayers=(3, 3)),
               label=label,
               cores=1)
    loss = LossFunction(convergence={'energy_rmse': 0.02, 'force_rmse': 0.03})
    calc.model.lossfunction = loss

    calc.train(images=train_images, )
    for image in train_images:
        print("energy = %s" % str(calc.get_potential_energy(image)))
        print("forces = %s" % str(calc.get_forces(image)))

    # Test that we can re-load this calculator and call it again.
    del calc
    calc2 = Amp.load(label + '.amp')
    for image in train_images:
        print("energy = %s" % str(calc2.get_potential_energy(image)))
        print("forces = %s" % str(calc2.get_forces(image)))
Example #25
0
def run_amp(fdata, job, ndata):
    """
    if nsets == 1:
        train_all(images)
    else:
        job = 'test'
        ndata = len(images)
        data_sets = divide_dataset(ndata, nsets)

        images = ase.io.read(fin, index='250:')
    """
    print(ndata)

    if job == "all":
        images = ase.io.read(fdate, index=':')
        train_all(images)
    elif job == "train":
        images = ase.io.read(fdate, index=':ndata')

    ndata = len(images)

    calc = Amp.load("amp.amp")
    #print(images[0])
    y = []
    y_bar = []
    for mol in images:
        y.append(mol.get_potential_energy())
        #print(mol.get_potential_energy())
        mol.set_calculator(calc)
        y_bar.append(mol.get_potential_energy())
        #print(mol.get_potential_energy())
    #print(images[0])

    draw(len(images), y, y_bar)

    return
Example #26
0
        timestep=timestep,
    )

    label = "energy-trained"
    dblabel = label + "-train"
    calc = trn.create_calc(label=label, dblabel=dblabel)
    ann = Annealer(calc=calc,
                   images=train_traj,
                   Tmax=20,
                   Tmin=1,
                   steps=2000,
                   train_forces=False)
    amp_name = trn.train_calc(calc, train_traj)

    label = os.path.join("calcs", "force-trained")
    dblabel = label + "-train"
    calc = Amp.load(amp_name, label=label, dblabel=dblabel)
    convergence = {
        "energy_rmse": 1e-16,
        "force_rmse": 1e-16,
        "max_steps": max_steps
    }
    loss_function = LossFunction(
        convergence=convergence,
        energy_coefficient=1.0,
        force_coefficient=0.1,
        overfit=overfit,
    )
    calc.model.lossfunction = loss_function
    amp_name = trn.train_calc(calc, train_force_traj)
Example #27
0
{% if overwrite %}
overwrite = {{ overwrite }}
{% else %}
overwrite = False
{% endif %}
cores = {{ cores }}

# Set working directory
os.chdir(work_dir)

# Create DB update strings
update_str = "_".join([str(f) for f in framework])
update_key = "nn_" + update_str + "_iter{}".format(iteration)

# Load Amp object
calc = Amp.load(load_path, cores=cores)

# Get atoms from the database
images = []
new_db = os.path.join(os.path.dirname(load_path), "DB.db")
shutil.copyfile(db_path, new_db)
db = connect(new_db)
for d in db.select(selection):
    if not overwrite and update_key in d.key_value_pairs.keys():
        continue

    atoms = db.get_atoms(d.id)
    atoms.set_calculator(calc)
    energy = atoms.get_potential_energy()

    update = {update_key: energy}
Example #28
0
from ase import io
from amp import Amp
from amp.descriptor.gaussian import Gaussian
from amp.model.neuralnetwork import NeuralNetwork
from amp.model import LossFunction
import numpy as np

dirName = './'
x = io.read(dirName + 'train.traj', index=':')[200:400]
#y = io.read(dirName + '../' + 'h3o-spe-1.traj', index=':')[50:100]
test_images = x
nimages = len(test_images)
test_energy = [image.get_potential_energy() for image in test_images]
rmse = []
for namp in range(100, 1500, 100):
    print('Current amp parameters: %d' % namp)
    calc = Amp.load(dirName + 'checkpoint/' + '%d.amp' % namp, cores=1)
    nnp_energy = [calc.get_potential_energy(image) for image in test_images]
    testfile = open(dirName + 'trained-%d.dat' % namp, 'w')
    for i in range(nimages):
        print('%15.8f %15.8f' % (test_energy[i], nnp_energy[i]), file=testfile)
    testfile.close()
    rmse.append(
        np.sqrt(
            np.sum((np.array(test_energy) - np.array(nnp_energy)))**2 * 1.0 /
            nimages))

with open(dirName + 'trained-rmse.dat', 'w') as foo:
    for i, value in enumerate(rmse):
        print('%5d %15.8f' % ((i + 1) * 100, value), file=foo)
import ase.io
from ase.constraints import FixAtoms
from amp import Amp

atoms = ase.io.read("H2O.xyz")

atoms.center(vacuum=5.0)

atoms.set_pbc([True, True, True])
atoms.write("CENTERED.xsf")

atoms.set_pbc([False, False, False])
atoms.set_constraint(FixAtoms(mask=[0]))

calc = Amp.load("amp.amp")

atoms.set_calculator(calc)

from ase.optimize import BFGS
relax = BFGS(atoms, logfile="LOG_relax_bfgs_AMP", trajectory="geoopt_amp.traj")
relax.run()
Example #30
0
    print('NodePlot Training Images')
    nodeplot2.plot(train_images, filename='node_plot_train.pdf')

#############################################################
import numpy as np
if use_cache:
    actual_energy_train, MLIP_energy_train = np.loadtxt('train_energies.txt',
                                                        usecols=[0, 1],
                                                        unpack=True)
    actual_energy_test, MLIP_energy_test = np.loadtxt('test_energies.txt',
                                                      usecols=[0, 1],
                                                      unpack=True)
else:
    from amp import Amp
    from amp.utilities import Logger, make_filename
    MLIP = Amp.load(MLIP_file_name)
    MLIP._log = Logger(make_filename('', log_file))

    def MLIP_eval(image):
        return MLIP.get_potential_energy(image) / len(image)

    from multiprocessing import Pool, cpu_count
    my_pool = Pool(cpu_count())

    print('Training Images...')
    MLIP_energy_train = my_pool.map(MLIP_eval, train_images)
    for i in range(len(train_images)):
        image = train_images[i]
        #if i%100==0: print(i,'/', len(train_images))
        actual_energy_train.append(image.get_potential_energy() / len(image))
        #MLIP_energy_train.append( MLIP.get_potential_energy(image)/len(image))
Example #31
0
#!/home/joonho/anaconda3/bin/python
import numpy as np
from ase.io import read,write
from amp import Amp
from amp.convert import save_to_prophet
import os

#Make PROPHET/lammps potentials
calc = Amp.load('amp.amp', cores = 1)
save_to_prophet(calc)


#Read starting configuration 
atoms = read('starting_configuration.traj')


# Number of atoms to create
natoms = len(atoms)
ntypes = len(set(atoms.get_chemical_symbols()))
symbols = ['H', 'O'] #sort them according to atomic number - not alphabetically - to be consistent with masses
masses = list(set(atoms.get_masses()))
masses.sort()


atom_numbers = {}
for i, symbol in enumerate(symbols):
        atom_numbers[symbol] = i+1

# System cell
cell = atoms.get_cell()