#!/usr/bin/env python ################################################################################ # # CDDL HEADER START # # The contents of this file are subject to the terms of the Common Development # and Distribution License Version 1.0 (the "License"). # # You can obtain a copy of the license at # http:# www.opensource.org/licenses/CDDL-1.0. See the License for the # specific language governing permissions and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each file and # include the License file in a prominent location with the name LICENSE.CDDL. # If applicable, add the following below this CDDL HEADER, with the fields # enclosed by brackets "[]" replaced with your own identifying information: # # Portions Copyright (c) [yyyy] [name of copyright owner]. All rights reserved. # # CDDL HEADER END # # Copyright (c) 2017, Regents of the University of Minnesota. # All rights reserved. # # Contributor(s): # Ellad B. Tadmor # ################################################################################ # The docstring below is vc_description '''Check whether a model is invariant with respect to atom permutations that preserve species, i.e. swapping any two atoms with the same species must not change the energy or forces. This must be true for all models. The check is performed for a randomly distorted non-periodic diamond cube base structure. Separate configurations are tested for each species supported by the model, as well as one containing a random distribution of all species. The energy and forces of each configuration are compared with one where each atom is randomly swapped with another atom of the same species. The energy and forces must remain unchanged. The verification check will pass if these conditions are satisfied for all configurations that the model is able to compute. Configurations used for testing are provided as auxiliary files.''' # Python 2-3 compatible code issues from __future__ import print_function try: input = raw_input except NameError: pass from ase.lattice.cubic import Diamond from kimcalculator import KIMCalculator, KIM_get_supported_species_list import kimvc import sys import random import numpy as np import math __version__ = "000" __author__ = "Ellad Tadmor" vc_name = "vc-permutation-symmetry" vc_description = kimvc.vc_stripall(__doc__) vc_category = "mandatory" vc_grade_basis = "passfail" vc_files = [] ################################################################################ # # FUNCTIONS # ################################################################################ ################################################################################ def perform_permutation_symmetry_check(vc, atoms, heading, dashwidth): ''' Perform perfmutation symmetry check for the ASE atoms object in 'atoms' ''' # set comparison tolerance tole = 1e-8 eps_prec = np.finfo(float).eps # compute the energy in the original location energy_orig = atoms.get_potential_energy() forces_orig = atoms.get_forces() # figure out which species are in the structure and create a list of # the indices for the occurences of each species in the structure species = atoms.get_chemical_symbols() unique_species = set(species) spec_indices = {} for spec in unique_species: spec_indices[spec] = [i for i, s in enumerate(species) if s == spec] # randomly switch each atom in the structure with another atom with the # same species. perm_map = [0]*len(atoms) for i in range(0,len(atoms)): spec = atoms[i].symbol # Swap this atom if it hasn't been already been swapped earlier if i in spec_indices[spec]: # choose a random atom of the same species if len(spec_indices[spec])>1: # only do this if there are more than j = i # one of this atom type while j==i: j = random.choice(spec_indices[spec]) perm_map[i] = j perm_map[j] = i spec_indices[spec].remove(i) spec_indices[spec].remove(j) # swap atoms i and j posi_save = atoms[i].position.copy() atoms[i].position = atoms[j].position atoms[j].position = posi_save else: perm_map[i] = i spec_indices[spec].remove(i) # compute the energy in the permuted structure energy_perm = atoms.get_potential_energy() forces_perm = atoms.get_forces() # check if energy is the same up to a numerical tolerance den = max(0.5*(abs(energy_perm) + abs(energy_orig)), eps_prec) passed_energy = abs(energy_perm-energy_orig)/den < tole # report results and return vc.rwrite('') vc.rwrite(heading) vc.rwrite('-'*dashwidth) vc.rwrite('') vc.rwrite('Permutation list = {}'.format(perm_map)) vc.rwrite('') vc.rwrite('Energy requirement:') vc.rwrite('') vc.rwrite( \ 'V(r_(PI 1),...,r_(PI N)) = V(r_1,...,r_N), ' 'where r_i is the position of atom i, V is the potential energy, ') vc.rwrite('and PI is the permutation operator (which randomly swaps all ' 'atoms with other atoms of the same species).') vc.rwrite('') vc.rwrite('V(r_(PI 1),...,r_(PI N)) = {0}'.format(energy_perm)) vc.rwrite('V(r_1,...,r_N) = {0}'.format(energy_orig)) vc.rwrite('') # check forces for inversion symmetry vc.rwrite('Forces requirement:') vc.rwrite('') vc.rwrite( \ 'f_(PI i)(r_(PI 1),...,r_(PI N)) = f_i(r_1,...,r_N), ' 'where r_i is the position of atom i, f_i is the force on atom i ') vc.rwrite('and PI is the permutation operator (which randomly swaps all ' 'atoms with other atoms of the same species).') vc.rwrite('') hfmt = '{:>3}' + ' '*13 + '{}' + ' '*34 + '{}' fmt = '{:>3} ' + '{: .8e} '*3 + '| ' + '{: .8e} '*3 + '{}' vc.rwrite(hfmt.format('i','f_(PI i)(r_(PI 1),...,r_(PI N))', \ 'f_i(r_1,...,r_N)')) vc.rwrite('-'*dashwidth) passed_forces = True for i in range(0,len(atoms)): f_lhs = forces_perm[perm_map[i]] f_rhs = forces_orig[i] den=np.maximum(0.5*(np.absolute(f_lhs)+np.absolute(f_rhs)),eps_prec) force_ok = np.all(np.absolute(f_lhs - f_rhs)/den 10.0: sys.exit(1) # Cannot find a working configuration within a # a reasonable lattice constant range. # Randomize positions save_positions = atoms.get_positions() pert_amp = pert_amp_orig got_randomized_config = False while not got_randomized_config: try: kimvc.randomize_positions(atoms, pert_amp) forces = atoms.get_forces() # make sure forces can be computed got_randomized_config = True except: # Failed to compute forces; reset to original posns and retry atoms.set_positions(save_positions) pert_amp *= 0.5 # cut perturbation amplitude by half # Move atoms around until all forces are sizeable kimvc.perturb_until_all_forces_sizeable(atoms, pert_amp) aux_file = 'config-'+spec+'.xyz' vc_files.append(aux_file) vc.write_aux_ase_atoms(aux_file, atoms, 'xyz') heading = 'MONOATOMIC STRUCTURE -- Species = ' + spec + \ ' (Configuration in file "' + aux_file + '")' try: passed = perform_permutation_symmetry_check(vc, atoms, \ heading, dashwidth) passed_all = passed_all and passed got_atleast_one = True except: pass # Perform numerical derivative check for mixed system if len(species)>1: lattice_constant = lattice_constant_orig while True: atoms = Diamond( size=(ncells_per_side, ncells_per_side, ncells_per_side), latticeconstant=lattice_constant, symbol="H", pbc=False) if len(atoms) < len(species): ncells_per_side += 1 else: break kimvc.randomize_species(atoms, species) calc = KIMCalculator(model) atoms.set_calculator(calc) got_initial_config = False while not got_initial_config: try: kimvc.rescale_to_get_nonzero_forces(atoms, 0.01) got_initial_config = True except: # Initial config failed. This most likely due to an evaluation # outside the legal model range. Increase lattice constant and # try again. lattice_constant += 0.25 if lattice_constant > 10.0: sys.exit(1) # Cannot find a working configuration within a # a reasonable lattice constant range. acell = lattice_constant*ncells_per_side atoms.set_cell([acell, acell, acell],scale_atoms=True) # Randomize positions save_positions = atoms.get_positions() pert_amp = pert_amp_orig got_randomized_config = False while not got_randomized_config: try: kimvc.randomize_positions(atoms, pert_amp) forces = atoms.get_forces() # make sure forces can be computed got_randomized_config = True except: # Failed to compute forces; reset to original posns and retry atoms.set_positions(save_positions) pert_amp *= 0.5 # cut perturbation amplitude by half kimvc.perturb_until_all_forces_sizeable(atoms, pert_amp) aux_file = 'config-'+''.join(species)+'.xyz' vc_files.append(aux_file) vc.write_aux_ase_atoms(aux_file, atoms, 'xyz') heading = 'MIXED STRUCTURE -- Species = ' + ' '.join(species) + \ ' (Configuration in file "' + aux_file + '")' try: passed = perform_permutation_symmetry_check(vc, atoms, \ heading, dashwidth) passed_all = passed_all and passed got_atleast_one = True except: pass if got_atleast_one: # Compute grade vc.rwrite('') vc.rwrite('='*dashwidth) vc.rwrite( \ 'To pass this verification check the model must be invariant ' 'with respect to') vc.rwrite( \ 'perumutation symmetry for all configurations it was able ' 'to compute.') vc.rwrite('') if passed_all: vc_grade = 'P' vc_comment = 'Model energy has permutation symmetry for ' + \ 'all configurations the model was able to compute.' else: vc_grade = 'F' vc_comment = \ 'Model energy does NOT have permutation symmetry for at ' + \ 'least one configuration that the model was able to ' + \ 'compute. This indicates an error in the implementation ' + \ 'of the model.' vc.rwrite('Grade: {}'.format(vc_grade)) vc.rwrite('') vc.rwrite('Comment: '+vc_comment) vc.rwrite('') return vc_grade, vc_comment else: raise RuntimeError('Failed to compute all configuration for the ' 'permutation symmetry verification check.') return None, None ################################################################################ # # MAIN PROGRAM # ############################################################################### if __name__ == '__main__': # Get the model extended KIM ID: model = input("Model Extended KIM ID = ") # Define VC object and do verification check vc = kimvc.vc_object(vc_name, vc_description, __author__) with vc: # Perform verification check and get grade try: vc_grade, vc_comment = do_vc(model, vc) except: vc_grade = "N/A" vc_comment = "Unable to perform verification check due to an error." sys.stderr.write('ERROR: Unable to perform verification check.\n') # Pack results in a dictionary and write VC property instance results = {"vc_name" : vc_name, "vc_description" : vc_description, "vc_category" : vc_category, "vc_grade_basis" : vc_grade_basis, "vc_grade" : vc_grade, "vc_comment" : vc_comment, "vc_files" : vc_files} vc.write_results(results)