def check_hessian_bonds(name, tol=1e-3 * kjmol / angstrom**2): with log.section('NOSETST', 2): system, ref = read_system(name) set_ffatypes(system, 'highest') valence = ValenceFF(system, Settings()) for term in valence.iter_terms('BONDHARM'): inonzero, izero = get_indices_zero_nonzero(term, len(system.numbers)) rv = np.random.uniform(low=1.00, high=2.00) * angstrom fc = np.random.uniform(low=1000, high=3000) * kjmol / angstrom**2 ref, num = get_analytic_numeric_hessian(valence, term, fc=fc, rv0=rv) #assert that hessian elements of atoms not part of the current bond #are zero if len(izero[0]) > 0: assert (abs(ref[izero])).max() < 1e-12 * kjmol / angstrom**2 assert (abs(num[izero])).max() < 1e-12 * kjmol / angstrom**2 M = (abs(ref - num)).max() iM, jM = np.where(abs(ref - num) == M)[0][0], np.where( abs(ref - num) == M)[1][0] print( '%25s (random FC=%8.3f kjmol/A^2 RV=%7.3f A ): MaxDev(%2i,%2i)=%.3e kjmol/A^2' % (term.basename, fc / (kjmol / angstrom**2), rv / angstrom, iM, jM, M / (kjmol / angstrom**2))) assert M < tol del system, valence, ref, num
def check_hessian_dihedrals(name, tol=1e-3 * kjmol / angstrom**2): with log.section('NOSETST', 2): system, ref = read_system(name) set_ffatypes(system, 'highest') valence = ValenceFF(system, Settings()) ref, num = None, None for term in valence.iter_terms('TORS'): psi0 = get_dihedral_angle(term, system) inonzero, izero = get_indices_zero_nonzero(term, len(system.numbers)) rv = np.random.uniform(low=0, high=180) * deg #q0 fc = np.random.uniform(low=10, high=50) * kjmol ref, num = get_analytic_numeric_hessian(valence, term, fc=fc, rv0=rv) #assert that hessian elements of atoms not part of the current dihedral #are zero if len(izero[0]) > 0: assert (abs(ref[izero])).max() < 1e-12 * kjmol / angstrom**2 assert (abs(num[izero])).max() < 1e-12 * kjmol / angstrom**2 M = (abs(ref - num)).max() iM, jM = np.where(abs(ref - num) == M)[0][0], np.where( abs(ref - num) == M)[1][0] print( '%25s (eq=%.1f deg random FC=%8.3f kjmol RV=%7.3f deg): MaxDev(%2i,%2i)=%.3e kjmol/A^2' % (term.basename, psi0 / deg, fc / kjmol, rv / deg, iM, jM, M / (kjmol / angstrom**2))) assert M < tol del system, valence, ref, num
def test_h2(): #frequency of H2 stretch mode in gaussian.fchk calculation is 4416.656/cm #and an equilibrium bond length of 0.7442380 A. This test checks if the #force field predicts the same values r0 = 0.7442380*angstrom freq = (2*np.pi)*4416.65640485*lightspeed/centimeter mass = pt['H'].mass/2 #reduced mass for the H2 stretch mode #Load system, model and pert. theory and estimate ff with log.section('NOSETST', 2): system, ai = read_system('H2/gaussian.fchk') set_ffatypes(system, 'low') program = DeriveFF(system, ai, Settings()) program.do_pt_generate() program.do_pt_estimate() K_pt, rv_pt = program.valence.get_params(0, only='all') program.do_hc_estimatefc(['HC_FC_DIAG']) K_hc, rv_hc = program.valence.get_params(0, only='all') #print results print '' print 'AI : K = %.3f kjmol/A^2 q0 = %.6f A' %(mass*freq**2/(kjmol/angstrom**2), r0/angstrom) print 'FF (PT): K = %.3f kjmol/A^2 q0 = %.6f A' %(K_pt/(kjmol/angstrom**2), rv_pt/angstrom) print 'FF (HC): K = %.3f kjmol/A^2 q0 = %.6f A' %(K_hc/(kjmol/angstrom**2), rv_hc/angstrom) print '' #perform assertion checks assert abs(K_pt/(mass*freq**2)-1.0) < 1e-3 assert abs(rv_pt/r0-1.0) < 1e-3 assert abs(K_hc/(mass*freq**2)-1.0) < 1e-3 assert abs(rv_hc/r0-1.0) < 1e-3 assert abs(K_hc/K_pt-1.0) < 1e-6 assert abs(rv_hc/rv_pt-1.0) < 1e-6
def test_uio66zrbrick_crossterms(): with log.section('NOSETEST', 2): # Load input data for a ficticious system of an isolated # UiO-66 brick with path('quickff.data.systems.uio66-zr-brick', 'system.chk') as fn: data = load_chk(fn) system = System(data['numbers'],data['pos'],charges=data['charges'], ffatypes=data['ffatypes'],bonds=data['bonds'],radii=data['radii']) system.set_standard_masses() ai = SecondOrderTaylor('ai', coords=system.pos.copy(), grad=data['gradient'], hess=data['hessian']) # Run QuickFF with tmpdir('test_uio66') as dn: fn_yaff = os.path.join(dn, 'pars_cov.txt') fn_sys = os.path.join(dn, 'system.chk') fn_log = os.path.join(dn, 'quickff.log') program = DeriveFF(system, ai, Settings(consistent_cross_rvs=True, remove_dysfunctional_cross=True,fn_yaff=fn_yaff,fn_sys=fn_sys,log_file=fn_log)) program.run() # Check force constants of cross terms and corresponding diagonal terms print("%50s %15s %15s"%("Basename","Cross FC","Diag FC")) for term in program.valence.terms: if not term.is_master(): continue if term.basename.startswith('Cross'): fc = program.valence.get_params(term.index, only='fc') for i in [0,1]: fc_diag = program.valence.get_params(term.diag_term_indexes[i], only='fc') print("%50s %15.6f %15.6f %50s" % (term.basename,fc,fc_diag,program.valence.terms[term.diag_term_indexes[i]].basename)) if fc_diag==0.0: assert fc==0.0
def test_methane_consistent_crossterms(): with log.section('NOSETEST', 2): system, ai = read_system('methane/gaussian.fchk') set_ffatypes(system, 'high') for consistent in [False, True]: with tmpdir('test_methane_%s'%('consistent' if consistent else 'inconsistent')) as dn: fn_yaff = os.path.join(dn, 'pars_cov.txt') fn_sys = os.path.join(dn, 'system.chk') program = DeriveFF(system, ai, Settings(consistent_cross_rvs=consistent, fn_yaff=fn_yaff,fn_sys=fn_sys,do_cross_DSS=True,do_cross_DSD=True, do_cross_DAA=True,do_cross_DAD=True)) program.run() compare_crossterm_rest_values(program,equal=consistent)
def run(self): with log.section('PROGRAM', 2): #deriving diagonal force field self.do_pt_generate() self.do_pt_estimate() self.average_pars() self.do_hc_estimatefc(['HC_FC_DIAG']) #adding and fitting cross terms self.do_cross_init() self.do_hc_estimatefc(['HC_FC_CROSS_ASS', 'HC_FC_CROSS_ASA'], logger_level=1) #write output self.make_output() #settings with log.section('INIT', 2, timer='Initialization'): settings = Settings(fn_yaff='pars_cov.txt', plot_traj='All', xyz_traj=True) #load Gaussian Formatted Checkpoint file fchk = FCHKFile('gaussian.fchk') numbers = fchk.fields.get('Atomic numbers') energy = fchk.fields.get('Total Energy') coords = fchk.fields.get('Current cartesian coordinates').reshape([len(numbers), 3]) grad = fchk.fields.get('Cartesian Gradient').reshape([len(numbers), 3]) hess = fchk.get_hessian().reshape([len(numbers), 3, len(numbers), 3]) #Construct Yaff System file system = System(numbers, coords) system.detect_bonds() system.set_standard_masses() #Construct a QuickFF SecondOrderTaylor object containing the AI reference
def check_terms(name): 'Check whether all ICs are present in ValenceFF instance' #TODO: CROSS terms with log.section('NOSETST', 2): system, ref = read_system(name) set_ffatypes(system, 'high') valence = ValenceFF(system, Settings()) #check if every bond is present and harmonic for bond in system.iter_bonds(): found = False for term in valence.iter_terms('BONDHARM'): at0, at1 = term.get_atoms() if bond[0]==at0 and bond[1]==at1 \ or bond[0]==at1 and bond[1]==at0: assert not found, 'BondHarm term %s was already found!' % str( bond) found = True assert found, 'No BondHarm term found for bond %s' % str(bond) #check if every bend is present for angle in system.iter_angles(): found = False for term in valence.iter_terms('BENDAHARM'): at0, at1, at2 = term.get_atoms() if angle[0]==at0 and angle[1]==at1 and angle[2]==at2 \ or angle[0]==at2 and angle[1]==at1 and angle[2]==at0: assert not found, 'BendAHarm term %s was already found!' % str( angle) found = True assert found, 'No BendAHarm term found for bond %s' % str(angle) #check if every dihedral is present for dihed in system.iter_dihedrals(): found = False for term in valence.iter_terms('Tors'): at0, at1, at2, at3 = term.get_atoms() if dihed[0]==at0 and dihed[1]==at1 and dihed[2]==at2 and dihed[3]==at3\ or dihed[0]==at3 and dihed[1]==at2 and dihed[2]==at1 and dihed[3]==at0: assert not found, 'Torsion term %s was already found!' % str( dihed) found = True assert found, 'No Torsion term found for bond %s' % str(dihed) #check if every oop distance is present and Harm for rv of 0 and SQHARM else for oop in system.iter_oops(): found = False for term in valence.iter_terms('^OOPDIST/.*$', use_re=True): at0, at1, at2, at3 = term.get_atoms() for p0, p1, p2 in permutations([at0, at1, at2]): if oop[0] == p0 and oop[1] == p1 and oop[2] == p2 and oop[ 3] == at3: assert not found, 'OopDist term %s was already found!' % str( oop) found = True for term in valence.iter_terms('SQOOPDIST'): at0, at1, at2, at3 = term.get_atoms() for p0, p1, p2 in permutations([at0, at1, at2]): if oop[0] == p0 and oop[1] == p1 and oop[2] == p2 and oop[ 3] == at3: assert not found, 'SqOopDist term %s was already found!' % str( oop) found = True assert found, 'No (Sq)OopDist term found for bond %s (which is %s)' % ( str(oop), ' '.join([ system.ffatypes[system.ffatype_ids[i]] for i in [at0, at1, at2, at3] ]))
def test_output_charmm22(): with log.section('NOSETST', 2): system, ai = read_system('ethanol/gaussian.fchk') set_ffatypes(system, 'low') with tmpdir('test_output_charmm22') as dn: fn_yaff = os.path.join(dn, 'pars_cov.txt') fn_charmm22_prm = os.path.join(dn, 'test.prm') fn_charmm22_psf = os.path.join(dn, 'test.psf') fn_sys = os.path.join(dn, 'system.chk') settings = Settings( do_cross_ASS=False, do_cross_ASA=False, fn_yaff=fn_yaff, fn_sys=fn_sys, fn_charmm22_prm=fn_charmm22_prm, fn_charmm22_psf=fn_charmm22_psf, ) program = DeriveFF(system, ai, settings) program.run() assert os.path.isfile(fn_yaff) assert os.path.isfile(fn_charmm22_prm) assert os.path.isfile(fn_charmm22_psf) assert os.path.isfile(fn_sys) # Count the number of BOND, ANGLES and DIHEDRAL lines in the PRM file. counts = {} with open(fn_charmm22_prm, 'r') as f: for line in f: print line line = line[:line.find('!')].strip() if len(line) == 0: continue if line in ['BONDS','ANGLES', 'DIHEDRALS', 'IMPROPER']: key = line counts[key] = 0 else: counts[key] += 1 assert counts['BONDS'] == 4 assert counts['ANGLES'] == 5 assert counts['DIHEDRALS'] == 2 assert counts['IMPROPER'] == 0 # Count the number atoms, bonds, angles and dihedrals in the PSF file and # check for consistency. with open(fn_charmm22_psf, 'r') as f: natom = 0 assert f.next() == 'PSF\n' for line in f: if '!NATOM' in line: natom = int(line.split()[0]) break assert natom == system.natom for iatom in xrange(natom+1): f.next() line = f.next() assert '!NBOND: bonds' in line nbond = int(line.split()[0]) nline = int(np.ceil(nbond/4.0)) numbers = (''.join([f.next() for iline in xrange(nline)])).split() assert len(numbers) == nbond*2 f.next() line = f.next() assert '!NTHETA: angles' in line ntheta = int(line.split()[0]) nline = int(np.ceil(ntheta/3.0)) numbers = (''.join([f.next() for iline in xrange(nline)])).split() assert len(numbers) == ntheta*3 f.next() line = f.next() assert '!NPHI: dihedrals' in line nphi = int(line.split()[0]) nline = int(np.ceil(nphi/2.0)) numbers = (''.join([f.next() for iline in xrange(nline)])).split() assert len(numbers) == nphi*4 f.next() line = f.next() assert '!NIMPHI: impropers' in line nimphi = int(line.split()[0]) assert nimphi == 0
def qff(args=None): if args is None: args = qff_parse_args() else: args = qff_parse_args(args) #define logger verbosity = None if args.silent: verbosity = 'silent' else: if args.very_verbose: verbosity = 'highest' elif args.verbose: verbosity = 'high' #get settings kwargs = { 'fn_traj': args.fn_traj, 'only_traj': args.only_traj, 'program_mode': args.program_mode, 'plot_traj': args.plot_traj, 'xyz_traj': args.xyz_traj, 'suffix': args.suffix, 'log_level': verbosity, 'log_file': args.logfile, 'ffatypes': args.ffatypes, 'ei': args.ei, 'ei_rcut': args.ei_rcut, 'vdw': args.vdw, 'vdw_rcut': args.vdw_rcut, 'covres': args.covres, } settings = Settings(fn=args.config_file, **kwargs) with log.section('INIT', 1, timer='Initializing'): log.dump('Initializing system') #read system and ab initio reference system = None energy = 0.0 grad = None hess = None pbc = None rvecs = None for fn in args.fn: if fn.endswith('.fchk') or fn.endswith('.xml'): numbers, coords, energy, grad, hess, masses, rvecs, pbc = read_abinitio( fn) if system is None: system = System(numbers, coords, rvecs=rvecs, charges=None, radii=None, masses=masses) else: system.pos = coords.copy() system.cell = Cell(rvecs) system.numbers = numbers.copy() if masses is not None: system.masses = masses.copy() system._init_derived() elif fn.endswith('.chk'): sample = load_chk(fn) if 'energy' in list(sample.keys()): energy = sample['energy'] if 'grad' in list(sample.keys()): grad = sample['grad'] elif 'gradient' in list(sample.keys()): grad = sample['gradient'] if 'hess' in list(sample.keys()): hess = sample['hess'] elif 'hessian' in list(sample.keys()): hess = sample['hessian'] if 'rvecs' in list(sample.keys()): pbc = [1, 1, 1] else: pbc = [0, 0, 0] if system is None: system = System.from_file(fn) else: if 'pos' in list(sample.keys()): system.pos = sample['pos'] elif 'coords' in list(sample.keys()): system.pos = sample['coords'] if 'rvecs' in list(sample.keys()): system.cell = Cell(sample['rvecs']) elif 'cell' in list(sample.keys()): system.cell = Cell(sample['cell']) if 'bonds' in list(sample.keys()): system.bonds = sample['bonds'] if 'ffatypes' in list(sample.keys()): system.ffatypes = sample['ffatypes'] if 'ffatype_ids' in list(sample.keys()): system.ffatype_ids = sample['ffatype_ids'] system._init_derived() else: raise NotImplementedError('File format for %s not supported' % fn) assert system is not None, 'No system could be defined from input' assert grad is not None, 'No ab initio gradient found in input' assert hess is not None, 'No ab initio hessian found in input' #complete the system information if system.bonds is None: system.detect_bonds() if system.masses is None: system.set_standard_masses() if system.ffatypes is None: if settings.ffatypes is not None: set_ffatypes(system, settings.ffatypes) else: raise AssertionError('No atom types defined') if settings.do_hess_negfreq_proj: log.dump( 'Projecting negative frequencies out of the mass-weighted hessian.' ) with log.section('SYS', 3, 'Initializing'): hess = project_negative_freqs(hess, system.masses) #construct ab initio reference ai = SecondOrderTaylor('ai', coords=system.pos.copy(), energy=energy, grad=grad, hess=hess, pbc=pbc) #detect a priori defined contributions to the force field refs = [] if settings.ei is not None: if rvecs is None: if settings.ei_rcut is None: rcut = 50 * angstrom else: rcut = settings.ei_rcut ff = ForceField.generate(system, settings.ei, rcut=rcut) else: if settings.ei_rcut is None: rcut = 20 * angstrom else: rcut = settings.ei_rcut ff = ForceField.generate(system, settings.ei, rcut=rcut, alpha_scale=3.2, gcut_scale=1.5, smooth_ei=True) refs.append(YaffForceField('EI', ff)) if settings.vdw is not None: ff = ForceField.generate(system, settings.vdw, rcut=settings.vdw_rcut) refs.append(YaffForceField('vdW', ff)) if settings.covres is not None: ff = ForceField.generate(system, settings.covres) refs.append(YaffForceField('Cov res', ff)) #define quickff program assert settings.program_mode in allowed_programs, \ 'Given program mode %s not allowed. Choose one of %s' %( settings.program_mode, ', '.join([prog for prog in allowed_programs if not prog=='BaseProgram']) ) mode = program_modes[settings.program_mode] program = mode(system, ai, settings, ffrefs=refs) #run program program.run() return program