def __init__( self, images, descriptor, cores, forcetraining, lj_data=None, envcommand=None ): self.images = images self.descriptor = descriptor self.atom_images = self.images self.forcetraining = forcetraining self.lj = False if lj_data is not None: self.lj_energies = np.squeeze(lj_data[0]) self.lj_forces = np.squeeze(lj_data[1]) self.num_atoms = np.array(lj_data[2]) self.lj = True if isinstance(images, str): extension = os.path.splitext(images)[1] if extension != (".traj" or ".db"): self.atom_images = ase.io.read(images, ":") self.hashed_images = hash_images(self.atom_images) self.parallel = {"cores": cores} if cores > 1: self.parallel = {"cores": assign_cores(cores), "envcommand": envcommand} print("Calculating fingerprints...") self.descriptor.calculate_fingerprints( self.hashed_images, parallel=self.parallel, calculate_derivatives=forcetraining, ) print("Fingerprints Calculated!") self.fprange = calculate_fingerprints_range(self.descriptor, self.hashed_images) self.unique_atoms, self.fingerprint_dataset, self.energy_dataset, \ self.num_of_atoms, self.sparse_fprimes, self.forces_dataset, \ self.scalings = ( self.preprocess_data())
def train_data(images, setup_only=False): label = 'nodeplot_test/calc' train_images = images calc = Amp(descriptor=Gaussian(), model=NeuralNetwork(hiddenlayers=(5, 5)), label=label, cores=1) loss = LossFunction(convergence={'energy_rmse': 0.02, 'force_rmse': 0.02}) calc.model.lossfunction = loss if not setup_only: calc.train(images=train_images, ) for image in train_images: print("energy =", calc.get_potential_energy(image)) print("forces =", calc.get_forces(image)) else: images = hash_images(train_images) calc.descriptor.calculate_fingerprints(images=images, log=calc._log, parallel={'cores': 1}, calculate_derivatives=False) calc.model.fit(trainingimages=images, descriptor=calc.descriptor, log=calc._log, parallel={'cores': 1}, only_setup=True) return calc
def train_data(images, setup_only=False): label = 'nodeplot_test/calc' train_images = images calc = Amp(descriptor=Gaussian(), model=NeuralNetwork(hiddenlayers=(5, 5)), label=label, cores=1) loss = LossFunction(convergence={'energy_rmse': 0.02, 'force_rmse': 0.02}) calc.model.lossfunction = loss if not setup_only: calc.train(images=train_images, ) for image in train_images: print "energy =", calc.get_potential_energy(image) print "forces =", calc.get_forces(image) else: images = hash_images(train_images) calc.descriptor.calculate_fingerprints(images=images, log=calc.log, cores=1, calculate_derivatives=False) calc.model.fit(trainingimages=images, descriptor=calc.descriptor, log=calc.log, cores=1, only_setup=True) return calc
def test(): """Rotational/translational invariance.""" for descriptor in [ Gaussian(fortran=False), ]: # Non-rotated atomic configuration atoms = Atoms([ Atom('Pt', (0., 0., 0.)), Atom('Pt', (0., 0., 1.)), Atom('Pt', (0., 2., 1.)) ]) images = hash_images([atoms], ordered=True) descriptor1 = descriptor descriptor1.calculate_fingerprints(images) fp1 = descriptor1.fingerprints[list(images.keys())[0]] # Randomly Rotated (and translated) atomic configuration rot = [random.random(), random.random(), random.random()] for i in range(1, len(atoms)): (atoms[i].x, atoms[i].y, atoms[i].z) = rotate_atom(atoms[i].x, atoms[i].y, atoms[i].z, rot[0] * np.pi, rot[1] * np.pi, rot[2] * np.pi) disp = [random.random(), random.random(), random.random()] for atom in atoms: atom.x += disp[0] atom.y += disp[1] atom.z += disp[2] images = hash_images([atoms], ordered=True) descriptor2 = descriptor descriptor2.calculate_fingerprints(images) fp2 = descriptor2.fingerprints[list(images.keys())[0]] for (element1, afp1), (element2, afp2) in zip(fp1, fp2): assert element1 == element2, 'rotated atoms test broken!' for _, __ in zip(afp1, afp2): assert (abs(_ - __) < 10 ** (-10.)), \ 'rotated atoms test broken!'
def test(): for descriptor in [Gaussian(fortran=False), ]: # Non-rotated atomic configuration atoms = Atoms([Atom('Pt', (0., 0., 0.)), Atom('Pt', (0., 0., 1.)), Atom('Pt', (0., 2., 1.))]) images = hash_images([atoms], ordered=True) descriptor1 = descriptor descriptor1.calculate_fingerprints(images) fp1 = descriptor1.fingerprints[images.keys()[0]] # Randomly Rotated (and translated) atomic configuration rot = [random.random(), random.random(), random.random()] for i in range(1, len(atoms)): (atoms[i].x, atoms[i].y, atoms[i].z) = rotate_atom(atoms[i].x, atoms[i].y, atoms[i].z, rot[0] * np.pi, rot[1] * np.pi, rot[2] * np.pi) disp = [random.random(), random.random(), random.random()] for atom in atoms: atom.x += disp[0] atom.y += disp[1] atom.z += disp[2] images = hash_images([atoms], ordered=True) descriptor2 = descriptor descriptor2.calculate_fingerprints(images) fp2 = descriptor2.fingerprints[images.keys()[0]] for (element1, afp1), (element2, afp2) in zip(fp1, fp2): assert element1 == element2, 'rotated atoms test broken!' for _, __ in zip(afp1, afp2): assert (abs(_ - __) < 10 ** (-10.)), \ 'rotated atoms test broken!'
def test_radial_G2(self): atoms = molecule('H2O') atoms.cell = 100 * np.eye(3) # Amp setup sf = { 'H': make_symmetry_functions(['H', 'O'], 'G2', [0.05, 1.0]), 'O': make_symmetry_functions(['H', 'O'], 'G2', [0.05, 1.0]) } descriptor = Gaussian(Gs=sf) images = hash_images([atoms], ordered=True) descriptor.calculate_fingerprints(images) fparray = [] for index, hash in enumerate(images.keys()): for fp in descriptor.fingerprints[hash]: fparray += [fp[1]] fparray = np.array(fparray) # This module setup positions = atoms.positions cell = atoms.cell atom_mask = [[1] for atom in atoms] numbers = list(np.unique(atoms.numbers)) species_mask = np.stack([[atom.number == el for atom in atoms] for el in numbers], axis=1).astype(int) config = {'cutoff_radius': 6.5} d, _ = get_distances(positions, cell, config['cutoff_radius']) g0 = G2(0, 0.05, 0.0) g1 = G2(1, 0.05, 0.0) g2 = G2(0, 1.0, 0.0) g3 = G2(1, 1.0, 0.0) # This builds the array of fingerprints this = np.concatenate( (g0(config, d, atom_mask, species_mask), g1(config, d, atom_mask, species_mask), g2(config, d, atom_mask, species_mask), g3(config, d, atom_mask, species_mask)), axis=1) npt.assert_almost_equal(fparray, this, 5)
def test(): """Zernike fingerprints consistency. Tests that pure-python and fortran, plus different number of cores give same results. """ images = make_images() images = hash_images(images, ordered=True) ref_fps = {} ref_fp_primes = {} count = 0 for fortran in [True, False]: for ncores in range(1, 3): cores = assign_cores(ncores) descriptor = Zernike(fortran=fortran, dblabel='Zernike-%s-%d' % (fortran, ncores)) descriptor.calculate_fingerprints(images, parallel={ 'cores': cores, 'envcommand': None }, log=None, calculate_derivatives=True) for hash, image in images.items(): if count == 0: ref_fps[hash] = descriptor.fingerprints[hash] ref_fp_primes[hash] = descriptor.fingerprintprimes[hash] else: fps = descriptor.fingerprints[hash] # Checking consistency between fingerprints for (element1, afp1), \ (element2, afp2) in zip(ref_fps[hash], fps): assert element1 == element2, \ 'fortran-python consistency for Zernike ' 'fingerprints broken!' for _, __ in zip(afp1, afp2): assert (abs(_ - __) < (10 ** (-10.))), \ 'fortran-python consistency for Zernike ' 'fingerprints broken!' # Checking consistency between fingerprint primes fpprime = descriptor.fingerprintprimes[hash] for key, value in ref_fp_primes[hash].items(): for _, __ in zip(value, fpprime[key]): assert (abs(_ - __) < (10 ** (-10.))), \ 'fortran-python consistency for Zernike ' 'fingerprint primes broken!' count += 1
def test(): images = make_images() images = hash_images(images, ordered=True) ref_fps = {} ref_fp_primes = {} count = 0 for fortran in [True, False]: for cores in range(1, 2): descriptor = Zernike(fortran=fortran, dblabel='Zernike-%s-%d' % (fortran, cores)) descriptor.calculate_fingerprints(images, cores=cores, fortran=fortran, log=None, calculate_derivatives=True) for hash, image in images.items(): if count == 0: ref_fps[hash] = descriptor.fingerprints[hash] ref_fp_primes[hash] = descriptor.fingerprintprimes[hash] else: fps = descriptor.fingerprints[hash] # Checking consistency between fingerprints for (element1, afp1), \ (element2, afp2) in zip(ref_fps[hash], fps): assert element1 == element2, \ 'fortran-python consistency for Zernike ' 'fingerprints broken!' for _, __ in zip(afp1, afp2): assert (abs(_ - __) < (10 ** (-10.))), \ 'fortran-python consistency for Zernike ' 'fingerprints broken!' # Checking consistency between fingerprint primes fpprime = descriptor.fingerprintprimes[hash] for key, value in ref_fp_primes[hash].items(): for _, __ in zip(value, fpprime[key]): assert (abs(_ - __) < (10 ** (-10.))), \ 'fortran-python consistency for Zernike ' 'fingerprint primes broken!' count += 1
def __init__(self, images, descriptor, calc=None, charge=None, Ei=None, Alpha=None, Jii=None): images = Trajectory(images) self.images = hash_images(images) self.descriptor = descriptor self.calc = calc self.charge = charge self.Ei = Ei self.Alpha = Alpha self.Jii = Jii if self.charge is None: self.training = True else: self.training = False
nn1_ = nn1.copy() nn1_.rotate([0, 0, 1], ang1) nn2_ = nn2.copy() nn2_.rotate([0, 0, 1], ang2) nn2_.positions = nn2_.positions + np.array([3.0, 0.0, 0.0]) for atom in nn2_: nn1_.append(atom) images.append(nn1_) view(images) # # Fingerprint using Amp. descriptor = Gaussian() images = hash_images(images, ordered=True) descriptor.calculate_fingerprints(images) def barplot(hash, name, title): """Makes a barplot of the fingerprint about the O atom.""" fp = descriptor.fingerprints[hash][0] fig, ax = pyplot.subplots() ax.bar(range(len(fp[1])), fp[1]) ax.set_title(title) ax.set_ylim(0., 2.) ax.set_xlabel('fingerprint') ax.set_ylabel('value') fig.savefig(name)
def calculate_numerical_forces(self, atoms, d=0.001, parallel=True): """Calculate numerical forces using finite difference. All atoms will be displaced by +d and -d in all directions.""" if (str(self.__class__) == "<class 'amp.Amp'>"): if (str(self.model.__class__) == "<class 'amp.model.tflow.NeuralNetwork'>"): disp_atoms = self.generate_disp(atoms, d=d) atomic_energies = self.calculateE_bunch(disp_atoms, parallel=parallel) atomic_energies = np.array( np.split( np.array(np.split(atomic_energies, len(atoms) * 3)), len(atoms))) forces = np.zeros((len(atoms), 3)) for i in range(len(atoms)): for j in range(3): forces [i][j] = \ -1 * ( atomic_energies[i][j][1] - atomic_energies[i][j][0] ) / (2 * d) return forces else: Calculator.calculate(self, atoms) disp_atoms = self.generate_disp(atoms, d=d) log = self._log log('Calculation requested.') from amp.utilities import hash_images images, seq_keys = hash_images(disp_atoms, list_seq=True) keys = list(images.keys())[0] ############### load neighborlist file list most recently used if hasattr(self, "neighborlist_keys"): n_keys = self.neighborlist_keys else: n_keys = None if hasattr(self, "fingerprints_keys"): f_keys = self.fingerprints_keys else: f_keys = None ############# update neighborlists & fingerprints file lists self.neighborlist_keys, self.fingerprints_keys = \ self.descriptor.calculate_fingerprints( images=images, log=log, calculate_derivatives=False, neighborlist_keys = n_keys, fingerprints_keys = f_keys, parallel = self._parallel if parallel else None, ) log('Calculating potential energy...', tic='pot-energy') seq_keys = np.array( np.split( np.array(np.split(np.array(seq_keys), len(atoms) * 3)), len(atoms))) forces = np.zeros((len(atoms), 3)) for a in range(len(atoms)): for i in range(3): eplus = self.model.calculate_energy( self.descriptor.fingerprints[seq_keys[a][i][1]]) self.descriptor.fingerprints.close() eminus = self.model.calculate_energy( self.descriptor.fingerprints[seq_keys[a][i][0]]) self.descriptor.fingerprints.close() forces[a][i] = (eminus - eplus) / (2 * d) log('Potential energy calc ended...', toc='pot-energy') return forces else: return np.array( [[self.numeric_force(atoms, a, i, d) for i in range(3)] for a in range(len(atoms))])