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_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 detect_ffatypes(self, ffatypes=None, ffatype_rules=None, ffatype_level=None): ''' Define atom types by explicitely giving them through the ffatypes keyword, defining atype rules using the ATSELECT language implemented in Yaff (see the Yaff documentation at http://molmod.github.io/yaff/ug_atselect.html) or by specifying the ffatype_level employing the built-in routine in QuickFF. ''' numbers = np.array([pt[symbol].number for symbol in self.structure.get_chemical_symbols()]) if self.structure.cell is None: system = System(numbers, self.structure.positions.copy()*angstrom) else: system = System(numbers, self.structure.positions.copy()*angstrom, rvecs=self.structure.cell*angstrom) system.detect_bonds() if not sum([ffatypes is None, ffatype_rules is None, ffatype_level is None]) == 2: raise IOError('Exactly one of ffatypes, ffatype_rules and ffatype_level should be defined') if ffatypes is not None: assert ffatype_rules is None, 'ffatypes and ffatype_rules cannot be defined both' system.ffatypes = ffatypes system.ffatype_ids = None system._init_derived_ffatypes() if ffatype_rules is not None: system.detect_ffatypes(ffatype_rules) if ffatype_level is not None: set_ffatypes(system, ffatype_level) self.ffatypes = system.ffatypes.copy() self.ffatype_ids = system.ffatype_ids.copy()
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_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 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 check_hessian_bends(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('BENDAHARM'): inonzero, izero = get_indices_zero_nonzero(term, len(system.numbers)) rv = np.random.uniform(low=10, high=170)*deg fc = np.random.uniform(low=100, high=1000)*kjmol/rad**2 ref, num = get_analytic_numeric_hessian(valence, term, fc=fc, rv0=rv) #assert that hessian elements of atoms not part of the current bend #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/rad^2 RV=%7.3f deg): MaxDev(%2i,%2i)=%.3e kjmol/A^2' %(term.basename, fc/(kjmol/rad**2), rv/deg, iM, jM, M/(kjmol/angstrom**2))) assert M<tol del system, valence, ref, num
def check_hessian_oops(name, tol=1e-3*kjmol/angstrom**2): with log.section('PROGRAM', 2): system, ref = read_system(name) set_ffatypes(system, 'highest') valence = ValenceFF(system, Settings()) for term in valence.iter_terms('/OOPDIST'): inonzero, izero = get_indices_zero_nonzero(term, len(system.numbers)) rv = 0.0 fc = np.random.uniform(low=500, high=5000)*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 oop #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 ref, num for term in valence.iter_terms('SQOOPDIST'): inonzero, izero = get_indices_zero_nonzero(term, len(system.numbers)) rv = np.random.uniform(low=0.01, high=0.1)*angstrom**2 fc = np.random.uniform(low=500, high=5000)*kjmol/angstrom**4 ref, num = get_analytic_numeric_hessian(valence, term, fc=fc, rv0=rv) #assert that hessian elements of atoms not part of the current oop #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^4 RV=%7.3f A^2): MaxDev(%2i,%2i)=%.3e kjmol/A^2' %(term.basename, fc/(kjmol/angstrom**4), rv/angstrom**2, iM, jM, M/(kjmol/angstrom**2))) assert M<tol del ref, num del system, valence
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 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
def qff_input_ei(args=None): if args is None: args = qff_input_ei_parse_args() else: args = qff_input_ei_parse_args(args) # Load system file if args.fn_sys.endswith('.fchk'): numbers, coords, energy, grad, hess, masses, rvecs, pbc = read_abinitio( args.fn_sys, do_hess=False) system = System(numbers, coords, rvecs=None, charges=None, radii=None, masses=masses) system.detect_bonds() else: system = System.from_file(args.fn_sys) # Guess atom types if needed if args.ffatypes is not None: set_ffatypes(system, args.ffatypes) ffatypes = [system.ffatypes[i] for i in system.ffatype_ids] # Load atomic charges fn_charges, _, path = args.charges.partition(':') if fn_charges.endswith('.h5'): with h5.File(fn_charges, 'r') as f: if not path in f: raise IOError( 'Given HDF5 file %s does not contain a dataset %s' % (fn_charges, path)) charges = f[path][:] radii = None if args.gaussian: path_radii = os.path.join(os.path.dirname(path), 'radii') if 'radii' in f[path]: radii = average(f['%s/radii' % path][:], ffatypes, fmt='dict') else: radii = average(get_ei_radii(system.numbers), ffatypes, fmt='dict') elif fn_charges.endswith('.chk'): sample = load_chk(fn_charges) if path in list(sample.keys()): charges = sample[path] else: raise IOError( 'Given CHK file %s does not contain a dataset with label %s' % (fn_charges, path)) radii = None if args.gaussian: if 'radii' in list(sample.keys()): radii = average(sample['radii'], ffatypes, fmt='dict') else: raise IOError( 'Invalid extension, fn_charges should be a HDF5 or a CHK file.') # Derive charge parameters if args.bci: constraints = {} if args.bci_constraints is not None: constraints = read_bci_constraints(args.bci_constraints) bcis = charges_to_bcis(charges, ffatypes, system.bonds, constraints=constraints, verbose=args.verbose) make_yaff_ei(args.fn_out, None, bcis=bcis, radii=radii) else: charges = average(charges, ffatypes, fmt='dict', verbose=args.verbose) make_yaff_ei(args.fn_out, charges, radii=radii)
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'] == 3 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 next(f) == 'PSF\n' for line in f: if '!NATOM' in line: natom = int(line.split()[0]) break assert natom == system.natom for iatom in range(natom+1): next(f) line = next(f) assert '!NBOND: bonds' in line nbond = int(line.split()[0]) nline = int(np.ceil(nbond/4.0)) numbers = (''.join([next(f) for iline in range(nline)])).split() assert len(numbers) == nbond*2 next(f) line = next(f) assert '!NTHETA: angles' in line ntheta = int(line.split()[0]) nline = int(np.ceil(ntheta/3.0)) numbers = (''.join([next(f) for iline in range(nline)])).split() assert len(numbers) == ntheta*3 next(f) line = next(f) assert '!NPHI: dihedrals' in line nphi = int(line.split()[0]) nline = int(np.ceil(nphi/2.0)) numbers = (''.join([next(f) for iline in range(nline)])).split() assert len(numbers) == nphi*4 next(f) line = next(f) assert '!NIMPHI: impropers' in line nimphi = int(line.split()[0]) assert nimphi == 0
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] ]))
#!/usr/bin/env python import numpy as np from yaff import System, angstrom, ForceField from quickff.tools import set_ffatypes # system_cluster = System.from_file('system_mbisgauss.chk') # system_cluster.ffatypes # rvecs = np.diag([25.832]*3)*angstrom rvecs = np.identity(3) * 25.832 * angstrom system = System.from_file('IRMOF-1.xyz', rvecs=rvecs) system.detect_bonds() set_ffatypes(system, "high") # system.set_standard_masses() system.to_file('init.chk') # ff = ForceField.generate(system, 'pars_yaff_mbisgauss.txt')
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