def test_atoms(self): for d in self.good_data: m = Molecule(d[1]) for (symbol, count) in d[3]: self.assertEqual(count, m.atoms(symbol), msg="atom {} in {}".format(symbol, m))
def read_molecule(r): """ (reader) -> Molecule Read a single molecule from r and return it or return None to signal end of file """ # if there isnt another line, we're at the end of the file line = r.readline() if not line: return None # name of the molecule: "COMPND name" key, name = line.split() # other lines are either "END" or "ATOM num kind x y z" molecule = Molecule(name) reading = True while reading: line = r.readline() if line.startswith('END'): reading = False else: key, num, kind, x, y, z = line.split() molecule.add(Atom(num, kind, float(x), float(y), float(z))) return molecule
def read_xyz(path, name, spg, a, b, c, alpha, beta, gamma): """ from C21 database.txt extract infomation to form 21(22) molecules/fragemets in a unit cell and return a list of them """ with open(path, "r") as data: line = data.readline().strip() line = data.readline().strip() line = data.readline().strip() mol = Molecule() while line: info = [] for part in line.split(" "): if len(part) > 0: info.append(part) mol.addAtom( Atom(typ=info[0], coordinate=np.array( [float(info[1]), float(info[2]), float(info[3])]))) line = data.readline().strip() mol.setCellpara(a, b, c, alpha, beta, gamma) mol.setSpg(spg) mol.setName(name) return mol
def read_molecule(r): """ (reader) -> Molecule Read a single molecule from r and return it, or return None to signal end of file. """ # If there isn't another line, we're at the end of the file. line = r.readline() if not line: return None # Name of the molecule: "COMPND name" key, name = line.split() # Other lines are either "END" or "ATOM num kind x y z" molecule = Molecule(name) reading = True while reading: line = r.readline() if line.startswith('END'): reading = False else: key, num, kind, x, y, z = line.split() molecule.add(Atom(num, kind, float(x), float(y), float(z))) return molecule
def __init__(self): Molecule.__init__(self) self.molid = Molecule.molid self.nor = 0 # Number of residues in a ligand; WILL ALWAYS BE 1 self.resids = [] # List of residue ids of a ligand self.atmidx = [] # List of atom indices from the input file self.residue = {} # Information about each residue. Key: Residue id.
def createMolecules(arr,params): retarr=[] for elem in arr: mol=Molecule() mol.RDMol=elem["RDMol"] retarr.append(mol) return retarr
def randomsample(input_molecule, iterations, save_data=False): """ Creates multiple Molecule objects based on inputted molecule with a random configuration and returns the configuration with the best score. It requires a Molecule object, the amount of configurations that should be created and optionally a boolean to indicate whether the resulting data should be saved. """ # produce list with max amount of possible stabilities, to count solutions solutions = [[-i, 0] for i in range(len(input_molecule.sequence))] # placeholder molecule for best solution best_solution = input_molecule # create random molecules for i in range(iterations): molecule = Molecule(input_molecule.sequence, 'random') solutions[-molecule.stability()][1] += 1 # save molecule with best stability if molecule.stability() < best_solution.stability(): best_solution = molecule # write data to csv file if save option was chosen if save_data: header = [ 'stability', 'solutions found', datetime.datetime.now(), f'sequence = {input_molecule.sequence}' ] write_csv("randomsample", header, solutions) return best_solution
class LeastSquaresCharges(LeastSquaresBasic): def __init__(self, data): self.molecule = Molecule(atoms=data['atoms']) self.grid = Grid(data) self.setA() reference = self.grid.get_properties(property_name=data['property'],\ theory='%s_%s' % (data['theory'], data['basis'])) LeastSquaresBasic.__init__(self, A=self.A, b=reference) def setA(self): n_p = len(self.grid.points) n_s = len(self.molecule.sites_noneq) self.A = np.zeros((n_p, n_s)) for i in xrange(n_p): proton = Site(coordinates=self.grid.points[i].coordinates, name='H+',index=1) for j, name in enumerate(self.molecule.sites_names_noneq): for site in self.molecule.get_sites(name=name): self.A[i,j] += 1/site.distance_to(proton) def setA_fast(self): grid_coordinates = self.grid.get_coordinates() sites_coordinates = self.molecule.get_coordinates() self.A = fast.set_inversed(grid_coordinates, sites_coordinates, \ len(self.molecule.sites_names_eq), self.molecule.sym_sites) @property def charges(self): charges = {} for q, name in zip(self.solution, self.molecule.sites_names): charges[name] = q return charges
def test_mass(self): for d in self.good_data: m = Molecule(d[1]) self.assertAlmostEqual(d[2], m.mass(), msg="mass of {} {} incorrect".format( d[0], d[1]))
def parse_lines(): #f = open(filename,'r') isParsing = True mol = None line_counter = 0 n_atoms = 0 mol = Molecule("") title = "" to_angs = False datas = [] for line in fileinput.input(): data = line.split() if isParsing: line_counter += 1 if line_counter == 1: n_atoms = int(data[0]) if line_counter == 2: uline = line.upper() to_angs = "AU" in uline if line_counter > 2: toangs = 1.0 if to_angs: toangs = 0.529177249 char = data[0] data = map(float, data[1:]) atom = Atom(char, data[0]*toangs, data[1]*toangs, data[2]*toangs) if mol is not None: mol.addAtom(atom) #f.close() return mol
def test_replace1(self): if self.pretest: self.test_no_super_class() self._assertMethod('replace') for d in self.good_data: m = Molecule(d[1]) mr = m.replace("C","Si", 1) self.assertTrue( isinstance( mr, Molecule ) ) self.assertEqual(d[1].replace("C","Si", 1), str(mr) )
def __init__(self): Molecule.__init__(self) self.molid = Molecule.molid self.nor = 0 # Number of residues in a protein self.resids = [] # List of residue ids of a protein self.atmidx = [] # List of atom indices self.residue = {} # Information about each residue. Key: Residue id. self.chain_break = False # This will be True if chain breaks are encountered
def get_optimized_energies(self, method, basis, cp, tag): """ Returns a list of pairs of [molecule, energies] where energies is an array of the form [E0, ...] of molecules in the database with the given method, basis, cp and tag and optimized geometries % can be used as a wildcard to stand in for any method, basis, cp, or tag. Args: method - retrieve only energies computed with this method basis - retrieve only energies computed with this basis cp - retrieve only energies computed with this coutnerpoise correction tag - retrieve only energies with this tag Returns: a generator of [molecule, [E0, E1, E2, E01, ...]] pairs from the calculated energies in this database using the given model and tag of optimized geometries """ # get a list of all calculations that have the appropriate method, basis, and cp calculation_ids = [ elements[0] for elements in self.cursor.execute( "SELECT ROWID FROM Calculations WHERE model_id=(SELECT ROWID FROM Models WHERE method LIKE ? AND basis LIKE ? AND cp LIKE ? AND tag LIKE ? AND optimized=?)", (method, basis, cp, tag, 1)).fetchall() ] for calculation_id in calculation_ids: # get the molecule id corresponding to this calculation molecule_id = self.cursor.execute( "SELECT molecule_id FROM Calculations WHERE ROWID=?", (calculation_id, )).fetchone()[0] # Reconstruct the molecule from the information in this database molecule = Molecule() # loop over all rows in the Fragments table that correspond to this molecule for fragment_id, charge, spin in self.cursor.execute( "SELECT ROWID, charge, spin FROM Fragments WHERE molecule_id=?", (molecule_id, )).fetchall(): fragment = Fragment(charge, spin) # loop over all rows in the Atoms table that correspond to this fragment for symbol, x, y, z in self.cursor.execute( "SELECT symbol, x, y, z FROM Atoms WHERE fragment_id=?", (fragment_id, )).fetchall(): fragment.add_atom(Atom(symbol, x, y, z)) molecule.add_fragment(fragment) # get the energies corresponding to this calculation energies = [ energy_index_value_pair[1] for energy_index_value_pair in sorted( self.cursor.execute( "SELECT energy_index, energy FROM Energies WHERE calculation_id=?", (calculation_id, )).fetchall()) ] yield molecule, energies
def test_mass_keyerror(self): badwater = Molecule('Yz2O') try: badwater.mass() except KeyError: pass except Exception as ex: self.fail("Wrong exception {} should be KeyError".format( type(ex).__name__))
def binary_naming(s): m = Molecule(s) elements = [not x.metal for x in m.iterelements()] if all(elements): return binary_nonmetal(m) else: return binary_metal(m)
def test_atomix(self): if self.pretest: self.test_no_super_class() self._assertMethod('atomix') for d in self.good_data: m = Molecule(d[1]) for am in m.atomix(): self.assertTrue( isinstance( am, Molecule ), "Molecule.atomix() should generate Molecules" ) self.assertSequenceEqual(d[4], list(map(str,m.atomix())), "Molecule({}).atomix() should generate {}".format(m,d[4]))
def test_get_num_atoms(self): molecule = Molecule() # get_num_atoms() should return 0 before any atoms added to molecule self.assertEqual(molecule.get_num_atoms(), 0) fragment0 = Fragment(-1, 2) atom0 = Atom("F", 0, 0, 0) fragment0.add_atom(atom0) molecule.add_fragment(fragment0) # get_num_fragments() should return 1 after 1 atom added to molecule self.assertEqual(molecule.get_num_atoms(), 1) fragment1 = Fragment(-1, 2) atom1 = Atom("F", 0, 0, 3) atom2 = Atom("Cl", 0, 0, 0) fragment1.add_atom(atom1) fragment1.add_atom(atom2) molecule.add_fragment(fragment1) # get_num_fragments() should return 3 after 3 atoms added to molecule self.assertEqual(molecule.get_num_atoms(), 3)
def form_molecule(self, other): if self.molecule: if other.molecule: if other.molecule != self.molecule: self.molecule.merge(other.molecule) return self.molecule.add(other) elif other.molecule: other.molecule.add(self) else: self.molecule = Molecule(self) self.molecule.add(other)
def pdb_handle(self): # check whether pdb file exists and create object of class Molecule # return this object or exit the program self.input_chains = list(self.input_chains) M = Molecule() try: M.import_pdb(self.input_file) except: raise Exception('ERROR: file %s not found!' % self.input_file) print 'Exiting program ...' sys.exit(1) return M
def rem(self, ids): def select(location, id, ids, locations): if id in ids: locations.append(str(location)) locations = [] Molecule.foreach( self, lambda data: select(data[0][1], data[1][1], ids, locations) ) Molecule.rem(self, ",".join(locations))
def test_unit_conversion_symmetry(self): """ Does converting back and forth between bohrs and angstroms introduce and compound rounding errors? Each operation should exactly reverse its counterpart. """ with open('../../extra-files/molecule.xyz', 'r') as file1: mol1 = Molecule(file1.read()) mol2 = mol1.copy() for count in range(10000): mol2.to_bohr() mol2.to_angstrom() self.assertEqual(mol1.geom, mol2.geom)
def test_unit_conversion_symmetry(self): """ Does converting back and forth between bohrs and angstroms introduce and compound rounding errors? Each operation should exactly reverse its counterpart. """ with open('../../extra-files/molecule.xyz', 'r') as file1: mol1 = Molecule(file1.read()) mol2 = mol1.copy() for count in range(10000) : mol2.to_bohr() mol2.to_angstrom() self.assertEqual(mol1.geom, mol2.geom)
def test_unit_conversion_accuracy(self): """ 1.0 Angstrom is approximately 1.889725989 Bohr. Is this conversion (and its reverse) carried out correctly? """ with open('../../extra-files/molecule.xyz', 'r') as file1: mol1 = Molecule(file1.read()) mol2 = mol1.copy() mol2.to_bohr() for i in range(mol1.natom) : self.assertAlmostEqual(mol1.geom[i][0] * 1.889725989, mol2.geom[i][0]) self.assertAlmostEqual(mol1.geom[i][1] * 1.889725989, mol2.geom[i][1]) self.assertAlmostEqual(mol1.geom[i][2] * 1.889725989, mol2.geom[i][2])
def read_cartesian(self,fname): molc=Molecule() f = open(fname,'r') while (True): str = f.readline() if (str==''): break sp = str.split() if (len(sp) != 4): continue molc.add_atom(Atom(sp[0].lower(),0,float(sp[1]),float(sp[2]),float(sp[3]))) self.mol = molc return molc
def test_add(self): if self.pretest: self.test_no_super_class() self._assertMethod('__add__') for d1 in self.good_data: m1 = Molecule(d1[1]) for d2 in self.good_data: m2 = Molecule(d2[1]) s3 = d1[1] + d2[1] m3 = m1 + m2 self.assertTrue( isinstance( m3, Molecule ), "Molecule({0}) + Molecule({1}) is not a Molecule".format( d1[1], d2[1] ))
def solve(mol_path, hess_path): with open(mol_path, 'r') as f: molecule = Molecule(f.read()) molecule.to_angstrom() with open(hess_path, 'r') as f: str = (f.read()).replace("\n",";") while str[-1] == ';' : str = str[:-1] mat = matrix(str) output_frequencies(molecule, mat)
def reset(self): oh = Molecule(atom_string='oh', S=0.0, D=0.) # pH proxy x = Molecule(atom_string='x', S=1.0, D=0.01) # amphiphile xx = Molecule(atom_string='xx', S=0.0, D=0.99) # precursor self.subsets = {'env': [oh, xx]} self.define_molecules([x, xx, oh]) self.change_conc_for_all_testtubes(xx, 1E0) self.add_reaction(Reaction([xx, oh], [x, x], 0.05, 0.0)) self.add_reaction(Reaction([x], [], 0.1, 0.0)) self.generate_ode_fn() self.graph()
def test_user_can_calculate_eeq_atomic_charges(): with tempfile.NamedTemporaryFile(mode="w+", encoding="utf-8") as f: f.write("$coord" + s) f.write("0 0 0 li" + s) f.write("0 0 2 h" + s) f.write("0 0 4 h" + s) f.write("$end") f.flush() fileObject = open(f.name, "r+") atoms = ksr.read(fileObject) molecule = Molecule(symbols=atoms) eeq = molecule.get_eeq(charge=0) want = [0.51925854, -0.35007273, -0.16918582] difference = sum([a - b for a, b in zip(want, eeq)]) assert difference < 1e-6
def getSubstructureFromPath(refmol: Molecule, path: np.ndarray) -> Molecule: """Create a molecules object from a substructure of given molecule.""" # initialize refat = refmol.get_atomic_numbers() refxyz = refmol.get_positions() # atoms from complex excluding old substrate atoms = [] for elem in path: atom = Atom(symbol=refat[elem], position=refxyz[elem, :]) atoms.append(atom) # create molecule from atoms return Molecule(symbols=atoms)
def __init__(self, name=None, ff=None, sym=False, g_settings=None, m_settings=None, multipoles=None, ls_jobs=['w', 'non-w']): GM_logger.info("Creating MoleculeOnGrid instance") Molecule.__init__(self, name=name, ff=ff, sym=sym, settings=m_settings, multipoles=multipoles) self.grid = grid.Grid(molecule_name=name, settings=g_settings) self.grid_coordinates = self.grid.get_coordinates() reference = {} reference['non-w'] = self.grid.get_properties(property_name='esp', theory='reference') try: reference['w']= reference['non-w']*np.sqrt(self.grid.weights) except AttributeError: pass self.A = {} self.set_A(ls_jobs) self.LS = {} for key, A in self.A.items(): self.LS[key] = LeastSquares(name=key, A=A, b=reference[key])
def load_input(self, input_file): """ Load a Psi4 input file. Exmaple: memory 12 gb molecule { 0 1 H 0 0 1 H 0 0 2 units angstrom no_reorient symmetry c1 } set globals {{ basis 6-31+g* freeze_core True guess sad scf_type df print 1 }} set_num_threads(1) gradient('mp2') """ found_gradient = False self.template = "" self.molecule = Molecule() with open(input_file) as infile: for line in infile: line = line.strip
def __init__(self, data): self.molecule = Molecule(atoms=data['atoms']) self.grid = Grid(data) self.setA() reference = self.grid.get_properties(property_name=data['property'],\ theory='%s_%s' % (data['theory'], data['basis'])) LeastSquaresBasic.__init__(self, A=self.A, b=reference)
def _add_atom(molecule): if molecule.num_atom < 1: return molecule temp_node_list = molecule.node_list # print(len(temp_node_list)) temp_expand_adj = molecule.expand_mat # print(temp_expand_adj.shape[0]) temp_adj = molecule.adj temp_elements = deconfig.temp_elements atom_index = np.random.choice(deconfig.length_elements, 1)[0] atom = temp_elements[atom_index] mask_row = mask(temp_expand_adj) if len(mask_row) < 1: return molecule mask_index = np.random.choice(mask_row, 1)[0] goal_length = molecule.num_atom + 1 goal_adj = np.zeros([goal_length, goal_length]) goal_adj[:goal_length - 1, :goal_length - 1] = temp_adj goal_adj[goal_length - 1, mask_index] = goal_adj[mask_index, goal_length - 1] = 1 temp_node_list.append(atom) goal_node_list = temp_node_list goal_mol = adj2mol(goal_node_list, goal_adj.astype(int), deconfig.possible_bonds) goal_smiles = Chem.MolToSmiles(goal_mol) return Molecule(goal_smiles, deconfig)
def _add_bond(molecule): if molecule.num_atom < 2: return molecule temp_expand_adj = molecule.expand_mat temp_adj = molecule.adj mask_row = mask(temp_expand_adj) goal_mol = None goal_smiles = None for i in mask_row: row = temp_adj[i] for j in range(len(row)): if row[j] > 0 and j in mask_row: temp_adj[i][j] += 1 temp_adj[j][i] += 1 goal_adj = temp_adj goal_node_list = molecule.node_list goal_mol = adj2mol(goal_node_list, goal_adj.astype(int), deconfig.possible_bonds) goal_smiles = Chem.MolToSmiles(goal_mol) break if goal_mol != None: break if goal_mol != None: return Molecule(goal_smiles, deconfig) else: return molecule
def _add_atom_between_bond(molecule): temp_elements = deconfig.temp_elements atom_index = np.random.choice(deconfig.length_elements, 1)[0] atom = temp_elements[atom_index] temp_adj = molecule.adj length = molecule.num_atom insert_index1 = np.random.choice(length, 1) insert_row = temp_adj[insert_index1][0] insert_index2 = 0 for i in range(len(insert_row)): if insert_row[i] > 0: insert_index2 = i temp_adj[insert_index1, insert_index2] = temp_adj[insert_index2, insert_index1] = 0 goal_adj = np.zeros([length + 1, length + 1]) goal_adj[:length, :length] = temp_adj goal_adj[length, insert_index1] = goal_adj[insert_index1, length] = 1 goal_adj[insert_index2, length] = goal_adj[length, insert_index2] = 1 temp_node_list = molecule.node_list temp_node_list.append(atom) goal_node_list = temp_node_list goal_mol = adj2mol(goal_node_list, goal_adj.astype(int), deconfig.possible_bonds) goal_smiles = Chem.MolToSmiles(goal_mol) return Molecule(goal_smiles, deconfig)
def __init__(self,file_name,tracer='C',name='化合物名称',peak_area='面积',type='xls',derivated=True): if type=='xls': p=pd.read_excel(file_name) elif type=='csv': p=pd.read_csv(file_name) if derivated==True: self.form='derive_formula' else: self.form='formula' self.metabolite=Metabolite().metabolites self.molecules={} self.data={} self.file_name=file_name for index,i in p.iterrows(): molecule_name=i[name] area=i[peak_area] try: names_list=re.findall(r'([0-9a-zA-Z\-]+?)\s[Mm]\+(\d+)',molecule_name)[0] except: if molecule_name=='C13': continue if names_list[0].lower() in self.data: self.data[names_list[0].lower()][int(names_list[1])]=area else : self.data[names_list[0].lower()]={int(names_list[1]):area} for i in self.data: self.molecules[i]=Molecule(i,self.metabolite[i][self.form],self.data[i],tracer=tracer)
def get_molecules(self): for i in self.all_peaks: name=i formula=self.metabolite[i][self.type] peaks=self.all_peaks[i] self.molecules[i]=Molecule(name,formula,peaks) return self.molecules
def main(): Mqc = Molecule(sys.argv[2]) psifrqs, psimodes, _, __ = read_frq_psi(sys.argv[1]) qcfrqs, qcmodes = read_frq_qc(sys.argv[2]) gaufrqs, gaumodes = read_frq_gau(sys.argv[3]) for i, j, ii, jj, iii, jjj in zip(psifrqs, psimodes, qcfrqs, qcmodes, gaufrqs, gaumodes): print "PsiFreq:", i, "QCFreq", ii, "GauFreq", iii print "PsiMode:", np.linalg.norm(j) print_mode(Mqc, j) print "QCMode:", np.linalg.norm(jj) if np.linalg.norm(j - jj) < np.linalg.norm(j + jj): print_mode(Mqc, jj) else: print_mode(Mqc, -1 * jj) print "GauMode:", np.linalg.norm(jjj) if np.linalg.norm(j - jjj) < np.linalg.norm(j + jjj): print_mode(Mqc, jjj) else: print_mode(Mqc, -1 * jjj) print "DMode (QC-Gau):", if np.linalg.norm(jj - jjj) < np.linalg.norm(jj + jjj): print np.linalg.norm(jj - jjj) print_mode(Mqc, jj - jjj) else: print np.linalg.norm(jj + jjj) print_mode(Mqc, jj + jjj) print "DMode (QC-Psi):", if np.linalg.norm(jj - j) < np.linalg.norm(jj + j): print np.linalg.norm(jj - j) print_mode(Mqc, jj - j) else: print np.linalg.norm(jj + j) print_mode(Mqc, jj + j)
def test_random_molecule(self): m = Molecule.random_molecule(12, 16) assert m.__class__ == Molecule assert m.r.x <= 12 assert m.r.y <= 16 assert m.v.x <= 3 assert m.v.y <= 4
def test_copy_function(self): """ Does the copy function correctly initialize all variables of a new molecule? Also, is the new molecule truly a different object? (ie: changing properties of the original does not affect the copy and vice versa)? """ with open('../../extra-files/molecule.xyz', 'r') as file1: mol1 = Molecule(file1.read()) mol2 = mol1.copy() self.assertEqual(mol1.units, mol2.units, 'checking units') self.assertEqual(mol1.natom, mol2.natom, 'checking natom') self.assertEqual(mol1.labels, mol2.labels, 'checking labels') self.assertEqual(mol1.masses, mol2.masses, 'checking masses') self.assertEqual(mol1.charges, mol2.charges, 'checking charges') self.assertEqual(mol1.geom, mol2.geom, 'checking geometry') mol2.to_bohr() self.assertNotEqual(mol1.units, mol2.units) self.assertNotEqual(mol1.geom, mol2.geom)
def test_random_molecules(self): ms = Molecule.random_molecules(100, 12, 16) assert len(ms) == 100 for m in ms: assert m.__class__ == Molecule assert m.r.x <= 12 assert m.r.y <= 16 assert m.v.x <= 3 assert m.v.y <= 4
def filterByActivity(arr,params): retarr=[] discard=[0,0,0,0,0,0,0,0] mols={} for line in arr: #print(line) if not line[u'bioactivity_type'] == u'IC50': discard[0]+=1 continue if line[u"target_confidence"]<7: discard[1]+=1 continue if line[u"units"]!=u"nM": discard[2]+=1 continue value=0.0 try: value=float(line[u"value"]) except ValueError: discard[3]+=1 continue if value > 1000: discard[4]+=1 continue mol=Molecule(line[u'parent_cmpd_chemblid']) #mol.id=line[u'ingredient_cmpd_chemblid'] if(mol.id in mols): discard[5]+=1 continue else: mols[mol.id]=True mol.pIC=-math.log(value) retarr.append(mol) discard[6]+=1 print(discard) return retarr
def harvest_zmat(zmat): """Parses the contents of the Cfour ZMAT file into array and coordinate information. The coordinate info is converted into a rather dinky Molecule (no fragment, but does read charge, mult, unit). Return qcdb.Molecule. Written for findif zmat* where geometry always Cartesian and Bohr. """ zmat = zmat.splitlines()[1:] # skip comment line Nat = 0 readCoord = True isBohr = '' charge = 0 mult = 1 molxyz = '' cgeom = [] for line in zmat: if line.strip() == '': readCoord = False elif readCoord: lline = line.split() molxyz += line + '\n' Nat += 1 else: if line.find('CHARGE') > -1: idx = line.find('CHARGE') charge = line[idx + 7:] idxc = charge.find(',') if idxc > -1: charge = charge[:idxc] charge = int(charge) if line.find('MULTIPLICITY') > -1: idx = line.find('MULTIPLICITY') mult = line[idx + 13:] idxc = mult.find(',') if idxc > -1: mult = mult[:idxc] mult = int(mult) if line.find('UNITS=BOHR') > -1: isBohr = ' bohr' molxyz = '%d%s\n%d %d\n' % (Nat, isBohr, charge, mult) + molxyz mol = Molecule.init_with_xyz(molxyz, no_com=True, no_reorient=True, contentsNotFilename=True) return mol
def jajo2mol(jajodic): """Returns a Molecule from entries in dictionary *jajodic* extracted from JAINDX and JOBARC. """ map = jajodic['MAP2ZMAT'] elem = jajodic['ATOMCHRG'] coord = jajodic['COORD '] Nat = len(elem) molxyz = '%d bohr\n\n' % (Nat) # TODO chgmult, though not really necessary for reorientation for at in range(Nat): posn = map[at] - 1 el = 'GH' if elem[posn] == 0 else z2el[elem[posn]] posn *= 3 molxyz += '%s %21.15f %21.15f %21.15f\n' % (el, coord[posn], coord[posn + 1], coord[posn + 2]) mol = Molecule.init_with_xyz(molxyz, no_com=True, no_reorient=True, contentsNotFilename=True) return mol
def harvest_GRD(grd): """Parses the contents *grd* of the Cfour GRD file into the gradient array and coordinate information. The coordinate info is converted into a rather dinky Molecule (no charge, multiplicity, or fragment), but this is these coordinates that govern the reading of molecule orientation by Cfour. Return qcdb.Molecule and gradient array. """ grd = grd.splitlines() Nat = int(grd[0].split()[0]) molxyz = '%d bohr\n\n' % (Nat) grad = [] for at in range(Nat): mline = grd[at + 1].split() el = 'GH' if int(float(mline[0])) == 0 else z2el[int(float(mline[0]))] molxyz += '%s %16s %16s %16s\n' % (el, mline[-3], mline[-2], mline[-1]) lline = grd[at + 1 + Nat].split() grad.append([float(lline[-3]), float(lline[-2]), float(lline[-1])]) mol = Molecule.init_with_xyz(molxyz, no_com=True, no_reorient=True, contentsNotFilename=True) return mol, grad
def __init__(self, file, reportInterval, simulation, xyzfile, pbc=True, pmegrid=None, tinkerpath = ''): """Create a TinkerReporter. Parameters: - tinkerpath (string) The - file (string) The file to write to - reportInterval (int) The interval (in time steps) at which to write frames """ print "Initializing Tinker Reporter" self._reportInterval = reportInterval self._openedFile = isinstance(file, str) if self._openedFile: self._out = open(file, 'w') else: self._out = file self._pbc = pbc self._pmegrid = pmegrid self._tinkerpath = tinkerpath self._simulation = simulation self.xyzfile = xyzfile self.pdbfile = os.path.splitext(xyzfile)[0] + '.pdb' self.keyfile = os.path.splitext(xyzfile)[0] + '.key' #self.prmfile = os.path.splitext(xyzfile)[0] + '.prm' self.dynfile = os.path.splitext(xyzfile)[0] + '.dyn' print "Loading Tinker xyz file" if not os.path.exists(self.xyzfile): raise IOError('You need a Tinker .xyz') if not os.path.exists(self.keyfile): raise IOError('You need a Tinker .key file with the same base name as the .xyz file') #if not os.path.exists(self.prmfile): # raise IOError('You need a Tinker .prm file with the same base name as the .xyz file') if not os.path.exists(self.pdbfile): raise IOError('You need a .pdb file with the same base name as the .xyz file (the same one you used to start the simulation)') self.M = Molecule(self.xyzfile,ftype='tinker') self.comm = open(self.xyzfile).readlines()[0] print "Done"
# This is the main program, which completes each part of the assignment using # the modules "molecule" and "vib". import numpy as np from vib import IntCoVibAnalysis from molecule import Molecule # build HOOH and DOOD Molecule objects hooh = Molecule( """ H O 1 0.9625 O 2 1.4535 1 99.64 H 3 0.9625 2 99.64 1 113.7 """ ) dood = Molecule( """ D O 1 0.9625 O 2 1.4535 1 99.64 D 3 0.9625 2 99.64 1 113.7 """ ) # build peroxide F matrix in C2-symmetrized internal coordinate basis F = np.array( # s1, s2, s3, s4, s5, s6 [[ 8.201,-0.128,-0.021, 0.023, 0, 0], # s1 [-0.128, 4.660, 0.825,-0.011, 0, 0], # s2 [-0.021, 0.825, 1.035, 0.048, 0, 0], # s3
def init_sample_molecules(): SampleMolecules = globals()['SampleMolecules'] SampleMolecules["quantum water"] = Molecule.from_z_matrix( """ O H 1 1.0 H 2 1.0 1 90.0 """ ) SampleMolecules["H2O"] = \ SampleMolecules["water"] =\ SampleMolecules["Water"] = Molecule( description = "CCSD(T)/aug-cc-pVTZ Water", xyz_string = """ 3 O 0.000000 0.000000 0.118154 H 0.000000 0.758734 -0.472614 H 0.000000 -0.758734 -0.472614 """ ) SampleMolecules["H2"] = Molecule( description = "CCSD(T)/aug-cc-pVTZ H2", xyz_string = """ 2 H 0.000000 0.000000 0.000000 H 0.000000 0.000000 0.743000 """ ) SampleMolecules["CO2"] = \ SampleMolecules["Carbon Dioxide"] = Molecule( description="Carbon Dioxide from NIH CIR server.", xyz_string = """ 3 O -1.20800000 -0.00000000 -0.00000000 O 1.20800000 -0.00000000 -0.00000000 C -0.00000000 0.00000000 0.00000000 """ ) SampleMolecules["benzene"] = \ SampleMolecules["Benzene"] = Molecule( description="B3LYP/cc-pVTZ Benzene", xyz_string = """ 12 C 0.000000 1.390732 0.000000 C 1.204409 0.695366 0.000000 C 1.204409 -0.695366 0.000000 C 0.000000 -1.390732 0.000000 C -1.204409 -0.695366 0.000000 C -1.204409 0.695366 0.000000 H 0.000000 2.472794 0.000000 H 2.141502 1.236397 0.000000 H 2.141502 -1.236397 0.000000 H 0.000000 -2.472794 0.000000 H -2.141502 -1.236397 0.000000 H -2.141502 1.236397 0.000000 """ ) SampleMolecules['ethylene'] = \ SampleMolecules['C2H4'] = Molecule( description="Ethylene from NIH CIR server.", xyz_string = """ 6 C 0.65500000 0.00000000 0.00000000 C -0.65500000 0.00000000 -0.00000000 H 1.19500000 -0.93530000 0.00000000 H 1.19500000 0.93530000 0.00000000 H -1.19500000 0.93530000 -0.00000000 H -1.19500000 -0.93530000 -0.00000000 """ ) SampleMolecules['methane'] = \ SampleMolecules['CH4'] = Molecule( description="CCSD(T) aug-cc-pVTZ methane from CCCBDB", xyz_string = """ 5 C 0.000000 0.000000 0.000000 H 0.629271 0.629271 0.629271 H -0.629271 -0.629271 0.629271 H -0.629271 0.629271 -0.629271 H 0.629271 -0.629271 -0.629271 """ )
from molecule import Molecule h2o = Molecule( """ O H 1 1.09520 H 1 1.09520 2 109.0000 """ ) print( h2o.compute_g_matrix() )
class TinkerReporter(object): """TinkerReporter To use it, create a TinkerReporter, then add it to the Simulation's list of reporters. """ def __init__(self, file, reportInterval, simulation, xyzfile, pbc=True, pmegrid=None, tinkerpath = ''): """Create a TinkerReporter. Parameters: - tinkerpath (string) The - file (string) The file to write to - reportInterval (int) The interval (in time steps) at which to write frames """ print "Initializing Tinker Reporter" self._reportInterval = reportInterval self._openedFile = isinstance(file, str) if self._openedFile: self._out = open(file, 'w') else: self._out = file self._pbc = pbc self._pmegrid = pmegrid self._tinkerpath = tinkerpath self._simulation = simulation self.xyzfile = xyzfile self.pdbfile = os.path.splitext(xyzfile)[0] + '.pdb' self.keyfile = os.path.splitext(xyzfile)[0] + '.key' #self.prmfile = os.path.splitext(xyzfile)[0] + '.prm' self.dynfile = os.path.splitext(xyzfile)[0] + '.dyn' print "Loading Tinker xyz file" if not os.path.exists(self.xyzfile): raise IOError('You need a Tinker .xyz') if not os.path.exists(self.keyfile): raise IOError('You need a Tinker .key file with the same base name as the .xyz file') #if not os.path.exists(self.prmfile): # raise IOError('You need a Tinker .prm file with the same base name as the .xyz file') if not os.path.exists(self.pdbfile): raise IOError('You need a .pdb file with the same base name as the .xyz file (the same one you used to start the simulation)') self.M = Molecule(self.xyzfile,ftype='tinker') self.comm = open(self.xyzfile).readlines()[0] print "Done" def describeNextReport(self, simulation): """Get information about the next report this object will generate. Parameters: - simulation (Simulation) The Simulation to generate a report for Returns: A five element tuple. The first element is the number of steps until the next report. The remaining elements specify whether that report will require positions, velocities, forces, and energies respectively. """ steps = self._reportInterval - simulation.currentStep%self._reportInterval return (steps, True, True, True, True) def report(self, simulation, state): """Generate a report. Parameters: - simulation (Simulation) The Simulation to generate a report for - state (State) The current state of the simulation """ RunDynamic = 0 pos = state.getPositions() / angstrom if RunDynamic: # Write a dyn file. dynout = open(self.dynfile,'w') print >> dynout, ' Number of Atoms and Title :' print >> dynout, self.comm, print >> dynout, ' Periodic Box Dimensions :' print >> dynout, pvec([state.getPeriodicBoxVectors()[i][i] / angstrom for i in range(3)]) print >> dynout, pvec([90,90,90]) print >> dynout, ' Current Atomic Positions :' for i in range(len(pos)): print >> dynout, pvec(pos[i]) print >> dynout, ' Current Atomic Velocities :' vel = state.getVelocities() / angstrom * picosecond for i in range(len(vel)): print >> dynout, pvec(vel[i]) print >> dynout, ' Current Atomic Accelerations :' for i in range(len(vel)): print >> dynout, pvec([0,0,0]) print >> dynout, ' Alternate Atomic Accelerations :' for i in range(len(vel)): print >> dynout, pvec([0,0,0]) dynout.close() o = _exec('%s %s 1 1e-5 1 1' % (os.path.join(self._tinkerpath,'dynamic'), self.xyzfile), print_command = False) for line in o.split('\n'): if 'Total Energy' in line: total = float(line.split()[2]) * 4.184 elif 'Potential Energy' in line: pot = float(line.split()[2]) * 4.184 elif 'Kinetic Energy' in line: kin = float(line.split()[2]) * 4.184 elif 'Temperature' in line: temp = float(line.split()[1]) elif 'Pressure' in line: pres = float(line.split()[1]) elif 'Density' in line: dens = float(line.split()[1]) * 1000 print "(Tinker dynamic) % 13.5f % 13.5f % 13.5f % 13.5f % 13.5f" % (temp, pot, kin, total, pres) RunAnalyze = 1 RunGrad = 1 if RunAnalyze or RunGrad: # Write a xyz file. self.M.xyzs = [pos] self.M.boxes = [[state.getPeriodicBoxVectors()[0][0] / angstrom,state.getPeriodicBoxVectors()[1][1] / angstrom,state.getPeriodicBoxVectors()[2][2] / angstrom]] self.M.write('temp.xyz',ftype='tinker') keyout = open('temp.key','w') for line in open(self.keyfile).readlines(): if 'a-axis' in line.lower(): pass elif 'b-axis' in line.lower(): pass elif 'c-axis' in line.lower(): pass elif 'pme-grid' in line.lower(): pass else: print >> keyout, line, if self._pbc: print >> keyout, 'a-axis % .6f' % (state.getPeriodicBoxVectors()[0][0] / angstrom) print >> keyout, 'b-axis % .6f' % (state.getPeriodicBoxVectors()[1][1] / angstrom) print >> keyout, 'c-axis % .6f' % (state.getPeriodicBoxVectors()[2][2] / angstrom) if self._pmegrid != None: print >> keyout, 'pme-grid %i %i %i' % (self._pmegrid[0], self._pmegrid[1], self._pmegrid[2]) keyout.close() #shutil.copy(self.prmfile,'temp.prm') if RunAnalyze: # Actually I should use testgrad for this (maybe later.) print "Running TINKER analyze program" o = _exec('%s temp.xyz E' % os.path.join(self._tinkerpath,'analyze'), print_command = False) # This is a dictionary of TINKER energy terms to OpenMM energy terms # I'm making the assumption that OpenMM energy terms are less finely divided. T2O = OrderedDict([('Total Potential Energy', 'Potential Energy'), ('Bond Stretching','AmoebaBondForce'), ('Angle Bending','AmoebaAngleForce'), ('Stretch-Bend','AmoebaStretchBendForce'), ('Out-of-Plane Bend','AmoebaOutOfPlaneBendForce'), ('Torsional Angle','PeriodicTorsionForce'), ('Urey-Bradley','HarmonicBondForce'), ('Van der Waals','AmoebaVdwForce'), ('Atomic Multipoles','AmoebaMultipoleForce'), ('Polarization','AmoebaMultipoleForce')]) Tinker_Energy_Terms = defaultdict(float) for line in o.split('\n'): s = line.split() for TTerm, OTerm in T2O.items(): # Very strict parsing. tts = TTerm.split() if len(s) == len(tts) + 2 and s[:len(tts)] == tts: Tinker_Energy_Terms[OTerm] += float(s[len(tts)]) * 4.184 elif TTerm == 'Total Potential Energy' and s[:len(tts)] == tts: Tinker_Energy_Terms[OTerm] = float(s[4]) * 4.184 OpenMM_Energy_Terms = EnergyDecomposition(self._simulation) PrintDict = OrderedDict() for key, val in OpenMM_Energy_Terms.items(): o = val t = Tinker_Energy_Terms[key] PrintDict[key] = " % 13.5f - % 13.5f = % 13.5f" % (o, t, o-t) printcool_dictionary(PrintDict, title="Energy Terms (kJ/mol): %13s - %13s = %13s" % ("OpenMM", "Tinker", "Difference")) if RunGrad: TFrc = OrderedDict() TFrcO = OrderedDict() TFrcTypes = [] Mode = 0 TFrcNum = 0 print "Running TINKER testgrad program" o = _exec('%s temp.xyz Y N Y' % os.path.join(self._tinkerpath,'testgrad'), print_command = False) # The following is copied over from TINKER source code. # c desum total energy Cartesian coordinate derivatives # c deb bond stretch Cartesian coordinate derivatives # c dea angle bend Cartesian coordinate derivatives # c deba stretch-bend Cartesian coordinate derivatives # c deub Urey-Bradley Cartesian coordinate derivatives # c deaa angle-angle Cartesian coordinate derivatives # c deopb out-of-plane bend Cartesian coordinate derivatives # c deopd out-of-plane distance Cartesian coordinate derivatives # c deid improper dihedral Cartesian coordinate derivatives # c deit improper torsion Cartesian coordinate derivatives # c det torsional Cartesian coordinate derivatives # c dept pi-orbital torsion Cartesian coordinate derivatives # c debt stretch-torsion Cartesian coordinate derivatives # c dett torsion-torsion Cartesian coordinate derivatives # c dev van der Waals Cartesian coordinate derivatives # c dec charge-charge Cartesian coordinate derivatives # c decd charge-dipole Cartesian coordinate derivatives # c ded dipole-dipole Cartesian coordinate derivatives # c dem multipole Cartesian coordinate derivatives # c dep polarization Cartesian coordinate derivatives # c der reaction field Cartesian coordinate derivatives # c des solvation Cartesian coordinate derivatives # c delf metal ligand field Cartesian coordinate derivatives # c deg geometric restraint Cartesian coordinate derivatives # c dex extra energy term Cartesian coordinate derivatives T2O = OrderedDict([('EB', 'AmoebaBondForce'), ('EA', 'AmoebaAngleForce'), ('EUB','HarmonicBondForce'), ('EV', 'AmoebaVdwForce'), ('EM', 'AmoebaMultipoleForce'), ('EP', 'AmoebaMultipoleForce')]) for line in o.split('\n'): if "Cartesian Gradient Breakdown by Individual Components" in line: Mode = 1 elif "Cartesian Gradient Breakdown over Individual Atoms" in line: Mode = 0 if Mode: if 'd E' in line: for wrd in re.findall("d E[A-Z]+",line): TFrc[wrd.split()[1]] = [] TFrcTypes.append(wrd.split()[1]) else: s = line.split() for w in s: if isfloat(w) and not isint(w): TFrc[TFrcTypes[TFrcNum%len(TFrcTypes)]].append(float(w)) TFrcNum += 1 for TFrcType in TFrc: TFrcArray = np.array(TFrc[TFrcType]) MaxF = max(abs(TFrcArray)) if MaxF != 0.0 and TFrcType not in T2O: raise Exception('Oopsh! The Tinker force type %s needs to correspond to one of the AMOEBA forces.' % TFrcType) if 'Total Force' in TFrcO: TFrcO['Total Force'] += -41.84*TFrcArray.copy() else: TFrcO['Total Force'] = -41.84*TFrcArray.copy() if TFrcType in T2O: if T2O[TFrcType] in TFrcO: #print "Incrementing Tinker Force %s into OpenMM Force %s" % (TFrcType, T2O[TFrcType]) TFrcO[T2O[TFrcType]] += -41.84*TFrcArray.copy() else: #print "Copying Tinker Force %s into OpenMM Force %s" % (TFrcType, T2O[TFrcType]) TFrcO[T2O[TFrcType]] = -41.84*TFrcArray.copy() OFrc = ForceDecomposition(self._simulation) for key, val in OFrc.items(): Fo = val.reshape(-1,3) Ft = TFrcO[key].reshape(-1,3) rmsf = np.sqrt(np.mean(TFrcO[key] ** 2)) rmse = np.sqrt(np.mean((TFrcO[key]-val) ** 2)) maxa = 0 maxdf = 0 ErrThresh = 1e-2 BadAtoms = [] ForceDev = [] for a in range(len(Fo)): fo = Fo[a] ft = Ft[a] df = fo-ft ForceDev.append(df) if np.linalg.norm(df) > maxdf: maxdf = np.linalg.norm(df) maxa = a if np.linalg.norm(df) / rmsf > ErrThresh: BadAtoms.append(a) ForceDev = np.array(ForceDev) ForceMax = np.max(np.max(np.abs(ForceDev))) ForceDev /= ForceMax printcool("Checking Force : %s" % key) print "RMS Force = % .6f" % rmsf print "RMS error = % .6f (%.4f%%)" % (rmse, 100*rmse/rmsf) print "Max error = % .6f (%.4f%%) on atom %i" % (maxdf, 100*maxdf/rmsf, maxa) if len(BadAtoms) > 0 and key != 'Total Force': MBad = self.M[0] print "Printing coordinates and force errors..." MBad.write('%s.%04i.coord.xyz' % (key,self._simulation.currentStep)) MBad.xyzs = [ForceDev] MBad.write('%s.%04i.dforce.xyz' % (key,self._simulation.currentStep)) # Total Potential Energy : -11774.66948293 Kcal/mole # Energy Component Breakdown : Kcal/mole Interactions # Bond Stretching 700.95903376 2048 # Angle Bending 280.53183695 1024 # Urey-Bradley -17.15154506 1024 # Van der Waals 6125.15094324 444788 # Atomic Multipoles -14366.63061078 216556 # Polarization -4497.52914104 216556 def __del__(self): if self._openedFile: self._out.close()
##mol_file_copy = output_path + os.sep + os.path.basename(mol_file_name) ##shutil.copy2(mol_file_name, mol_file_copy) print 'Working on the following files' print 'Mol file: '+ mol_file_name print 'SCF file: ' + scf_file_name print 'Output folder: ' + output_path #end of file creation/manipulation module #write the files try: #assemble input #the template should be static, as the periodic table template = Template() molecule = Molecule(mol_input) scf = Scf(scf_input, molecule.atoms) #if we are runing an inptest, call dirac and change the molecule if scf.getModule(template.dirac).getProperty(template, template.inptest): dirac = Dirac(scf_file_name, mol_file_name, molecule) dirac.run() #get the output of running Dirac and reset the molecule molecule.resetMolecule(dirac.parse()) #remove the inptest and continue with the calculations scf.getModule(template.dirac).removeProperty(template.inptest) #print the description of each atom for atom in molecule.atoms: atom.print_mol_file(output_path) atom.print_inp_file(periodic_table, scf, template, output_path)
def test_kinetic_energy(self): m = Molecule(V(1.0, 1.0), V(3.0, 4.0)) print m.kinetic_energy() assert m.kinetic_energy() == 12.5
path = directory + '/{:d}{:d}_{:d}{:d}'.format(coords, coordd, ks, kd) lines = open(path + '/input.out').readlines() energy = 0.0 for line in reversed(lines): if line[:23] == ep: energy = float(line.split()[-1]) return energy raise Exception('Cannot find energy in ' + path) H = np.zeros((3*natom, 3*natom)) for A in range(3*natom): # calculates matrix elements of hessian for B in range(3*natom): if A == B: H[A,A] = (E(A,0,+1,0,ep) + E(A,0,-1,0,ep) - 2 * E(0,0,0,0,ep))/(disp_size**2) else: H[A,B] = (E(A,B,+1,+1,ep) + E(A,B,-1,-1,ep) - E(A,B,+1,0,ep) - E(A,B,-1,0,ep) \ - E(A,B,0,+1,ep) - E(A,B,0,-1,ep) + 2*E(0,0,0,0,ep))/(2*(disp_size**2)) np.savetxt('hessian.dat', H) # writes hessian to hessian.dat return H # testing if __name__=='__main__': mol = Molecule.from_file('../../extra-files/molecule.xyz') # building molecule from molecule.xyz template = open('../../extra-files/template.dat').read() # reads initial template generate_inputs(mol, template, 0.005, 'DISPS') run_jobs(mol, '/Users/boyi/bin/psi4/obj/stage/usr/local/bin/psi4', 'DISPS') build_hessian(mol,' @DF-RHF Final Energy:', 0.005, 'DISPS') frequencies.get_freqs(mol, 'hessian.dat') # calling frequencies function
#!/usr/bin/env python3 import numpy as np import sys sys.path.insert(0, '../extra-files') sys.path.insert(0, '../../0/jevandezande') from masses import get_mass from molecule import Molecule # Create a molecule mol = Molecule(open('../extra-files/molecule.xyz').read(), 'Bohr') mol.to_angstrom() # Read the Hessian H = np.genfromtxt('../extra-files/hessian.dat') # Mass weight Hessian # Build W = M^{-1/2} weights = [] for atom in mol.atoms: w = 1/np.sqrt(get_mass(atom)) weights += [w, w, w] W = np.diag(weights) # \Tilde H = M^{-1/2} H M^{-1/2} Ht = W @ H @ W # Diagonalize the Hessian # \Tilde H = L \Lambda L^T k, L = np.linalg.eigh(Ht)
def make_Hessian(self): self.run_disps() h, N = self.h, self.N E0 = self.find_E(0,0,0,0) self.H = np.zeros((3*self.N, 3*self.N)) for i in range(3*N): for i in range(3*N): self.H[i,i]= (self.find_E(i,0,1,0)+self.find_E(i,0,-1,0)-2*E0)/(h**2) for j in range(0,i): self.H[i,j] = (self.find_E(i,j,1,1)+self.find_E(i,j,-1,-1)-self.find_E(i,0,1,0)-self.find_E(j,0,1,0)-self.find_E(j,0,-1,0)-self.find_E(i,0,-1,0)+2*E0) self.H[i,j] /= 2*h**2 self.H[j,i] = self.H[i,j] def write_Hessian(self): """ write Hessian matrix to hessian.dat file """ self.make_Hessian() np.savetxt("hessian.dat",self.H,"%15.7f"," ","\n") if __name__ == "__main__": mol = Molecule(open("/Users/avery/git/summer-program/extra-files/molecule.xyz","r").read() ) mol.bohr() hessian = Hessian(mol,"template.dat") hessian.write_Hessian()
def fgrad(x, indicate = False): """ Calculate the objective function and its derivatives. """ # If the optimization algorithm tries to calculate twice for the same point, do nothing. # if x == fgrad.x0: return xyz = independent_vars_to_xyz(x) # these methods require 3d input xyzlist = np.array([xyz]) my_bonds = core.bonds(xyzlist, ibonds).flatten() my_angles = core.angles(xyzlist, iangles).flatten() my_dihedrals = core.dihedrals(xyzlist, idihedrals, anchor=dihedrals).flatten() # Deviations of internal coordinates from ideal values. d1 = w1*(my_bonds - bonds) d2 = w2*(my_angles - angles) d3 = w3*(my_dihedrals - dihedrals) # Include an optional term if we have an anchor point. if xrefi != None: d4 = (x - xrefi).flatten() * w1 * w_xref fgrad.error = np.r_[d1, d2, np.arctan2(np.sin(d3), np.cos(d3)), d4] else: fgrad.error = np.r_[d1, d2, np.arctan2(np.sin(d3), np.cos(d3))] # The objective function contains another contribution from the Morse potential. fgrad.X = np.dot(fgrad.error, fgrad.error) d1s = np.dot(d1, d1) d2s = np.dot(d2, d2) d3s = np.dot(d3, d3) M = Molecule() M.elem = elem M.xyzs = [np.array(xyz)*10] if w_morse != 0.0: EMorse, GMorse = PairwiseMorse(M) EMorse = EMorse[0] GMorse = GMorse[0] else: EMorse = 0.0 GMorse = np.zeros((n_atoms, 3), dtype=float) if indicate: if fgrad.X0 != None: print ("LSq: %.4f (%+.4f) Distance: %.4f (%+.4f) Angle: %.4f (%+.4f) Dihedral: %.4f (%+.4f) Morse: % .4f (%+.4f)" % (fgrad.X, fgrad.X - fgrad.X0, d1s, d1s - fgrad.d1s0, d2s, d2s - fgrad.d2s0, d3s, d3s - fgrad.d3s0, EMorse, EMorse - fgrad.EM0)), else: print "LSq: %.4f Distance: %.4f Angle: %.4f Dihedral: %.4f Morse: % .4f" % (fgrad.X, d1s, d2s, d3s, EMorse), fgrad.X0 = fgrad.X fgrad.d1s0 = d1s fgrad.d2s0 = d2s fgrad.d3s0 = d3s fgrad.EM0 = EMorse fgrad.X += w_morse*EMorse # Derivatives of internal coordinates w/r.t. Cartesian coordinates. d_bonds = core.bond_derivs(xyz, ibonds) * w1 d_angles = core.angle_derivs(xyz, iangles) * w2 d_dihedrals = core.dihedral_derivs(xyz, idihedrals) * w3 if xrefi != None: # the derivatives of the internal coordinates wrt the cartesian # this is 2d, with shape equal to n_internal x n_cartesian d_internal = np.vstack([gxyz_to_independent_vars(d_bonds.reshape((len(ibonds), -1))), gxyz_to_independent_vars(d_angles.reshape((len(iangles), -1))), gxyz_to_independent_vars(d_dihedrals.reshape((len(idihedrals), -1))), np.eye(len(x)) * w1 * w_xref]) else: # the derivatives of the internal coordinates wrt the cartesian # this is 2d, with shape equal to n_internal x n_cartesian d_internal = np.vstack([gxyz_to_independent_vars(d_bonds.reshape((len(ibonds), -1))), gxyz_to_independent_vars(d_angles.reshape((len(iangles), -1))), gxyz_to_independent_vars(d_dihedrals.reshape((len(idihedrals), -1)))]) # print fgrad.error.shape, d_internal.shape # print d_internal.shape # print xyz_to_independent_vars(d_internal).shape fgrad.G = 2*np.dot(fgrad.error, d_internal) fgrad.G += xyz_to_independent_vars(w_morse*GMorse.flatten())
raise RuntimeError if gmx_acharge != amb_acharge: print "Atomic charges don't match for", resname, gmx_atom, amb_atom raise RuntimeError # Print the atoms that are renamed # if gmx_aname != amb_aname: # print "%s (AMBER) %s <-> %s (GMX)" % (resname, amb_aname, gmx_aname) gmx_amb_amap.setdefault(resname, OrderedDict())[gmx_aname] = amb_aname amb_gmx_amap.setdefault(resname, OrderedDict())[amb_aname] = gmx_aname amber_atomnames = OrderedDict([(k, set(v.keys())) for k, v in amb_gmx_amap.items()]) max_reslen = max([len(v) for v in amber_atomnames.values()]) # Begin with an AMBER-compatible PDB file # Please ensure by hand :) pdb = Molecule(sys.argv[1], build_topology=False) gmx_pdb = copy.deepcopy(pdb) del gmx_pdb.Data['elem'] # Convert to a GROMACS-compatible PDB file # This mainly involves renaming atoms and residues, # notably hydrogen names. # List of atoms in the current residue anameInResidue = [] anumInResidue = [] anirs = [] for i in range(gmx_pdb.na): # Rename the ions residue names to be compatible with Gromacs
#! /usr/bin/python3 import sys sys.path.insert(0, '../extra-files') sys.path.insert(0, '../../0/aewiens') import masses from molecule import Molecule import numpy as np from scipy import linalg as la ##### Read in the molecule f = open("../extra-files/molecule.xyz").readlines() mol = Molecule(f,"Bohr") mol.angs() N = mol.__len__() ##### Read in the Hessian g = open("../extra-files/hessian.dat","r") H0 = np.matrix([i.split() for i in g.readlines()],float) ##### Construct M^{-1/2} (diagonal matrix) m = [] for i in mol.atoms: m += [1/(masses.get_mass(i))**0.5]*3 M = np.diag(m)