diff --git "a/data/dataset_Computational_Biochemistry.csv" "b/data/dataset_Computational_Biochemistry.csv" new file mode 100644--- /dev/null +++ "b/data/dataset_Computational_Biochemistry.csv" @@ -0,0 +1,44056 @@ +"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" +"Computational Biochemistry","rmera/gochem","atomicdata.go",".go","3454","157","/* + * atomicdata.go, part of gochem. + * + * + * Copyright 2021 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + * goChem is currently developed at the Universidad de Santiago de Chile + * (USACH) + * + */ + +package chem + +// A map for assigning mass to elements. +// Note that just common ""bio-elements"" are present +var symbolMass = map[string]float64{ + ""H"": 1.0, + ""C"": 12.01, + ""O"": 16.00, + ""N"": 14.01, + ""P"": 30.97, + ""S"": 32.06, + ""Se"": 78.96, + ""K"": 39.1, + ""Ca"": 40.08, + ""Mg"": 24.30, + ""Cl"": 35.45, + ""Na"": 22.99, + ""Cu"": 63.55, + ""Zn"": 65.38, + ""Co"": 58.93, + ""Fe"": 55.84, + ""Mn"": 54.94, + ""Cr"": 51.996, + ""Si"": 28.08, + ""Be"": 9.012, + ""F"": 18.998, + ""Br"": 79.904, + ""I"": 126.90, +} + +// A map for assigning covalent radii to elements +// Values from Cordero et al., 2008 (DOI:10.1039/B801115J) +// Note that just common ""bio-elements"" are present +var symbolCovrad = map[string]float64{ + ""H"": 0.4, // 0.31 I altered this one. Since H always has only one bond, it doesn't matter if I set a longer radius, the extra bonds will get eliminated later. + ""C"": 0.76, //the sp3 radius + ""O"": 0.66, + ""N"": 0.71, + ""P"": 1.07, + ""S"": 1.05, + ""Se"": 1.2, + ""K"": 2.03, + ""Ca"": 1.76, + ""Mg"": 1.41, + ""Cl"": 1.02, + ""Na"": 1.66, + ""Cu"": 1.32, + ""Zn"": 1.22, + ""Co"": 1.5, // hs + ""Fe"": 1.52, //hs + ""Mn"": 1.61, //hs + ""Cr"": 1.39, + ""Si"": 1.11, + ""Be"": 0.96, + ""F"": 0.57, + ""Br"": 1.2, + ""I"": 1.39, +} + +// A map for assigning van der Waals radii to elements +// Values from 10.1021/j100785a001 and 10.1021/jp8111556 +// metal radii from 10.1023/A:1011625728803 +// Note that just common ""bio-elements"" are present +var symbolVdwrad = map[string]float64{ + ""H"": 1.10, // 0.31 I altered this one. Since H always has only one bond, it doesn't matter if I set a longer radius, the extra bonds will get eliminated later. + ""C"": 1.70, //the sp3 radius + ""O"": 1.52, + ""N"": 1.55, + ""P"": 1.80, + ""S"": 1.80, + ""Se"": 1.90, + ""K"": 2.75, + ""Ca"": 2.31, + ""Mg"": 1.73, + ""Cl"": 1.75, + ""Na"": 2.27, + ""Cu"": 2.00, + ""Zn"": 2.02, + ""Co"": 1.95, + ""Fe"": 1.96, + ""Mn"": 1.96, + ""Cr"": 1.97, + ""Si"": 2.10, + ""Be"": 1.53, + ""F"": 1.47, + ""Br"": 1.83, + ""I"": 1.98, +} + +// A map for checking that atoms don't +// have too many bonds. A value of 0 means +// undefined, i.e. that this atom shouldn't +// be checked for max bonds. I decided not to define it +var symbolMaxBonds = map[string]int{ + ""H"": 1, //this is the only one truly important. + ""C"": 4, + ""O"": 2, + ""N"": 0, //undefined + ""P"": 0, + ""S"": 0, + ""Se"": 0, + ""Be"": 0, + ""F"": 1, + ""Br"": 1, + ""I"": 1, +} + +var Three2OneLetter = map[string]string{ + ""SER"": ""S"", + ""THR"": ""T"", + ""ASN"": ""N"", + ""GLN"": ""Q"", + ""SEC"": ""U"", //Selenocysteine! + ""CYS"": ""C"", + ""GLY"": ""G"", + ""PRO"": ""P"", + ""ALA"": ""A"", + ""VAL"": ""V"", + ""ILE"": ""I"", + ""LEU"": ""L"", + ""MET"": ""M"", + ""PHE"": ""F"", + ""TYR"": ""Y"", + ""TRP"": ""W"", + ""ARG"": ""R"", + ""HIS"": ""H"", + ""LYS"": ""K"", + ""ASP"": ""D"", + ""GLU"": ""E"", +} +","Go" +"Computational Biochemistry","rmera/gochem","handy.go",".go","29609","915","/* + * handy.go, part of gochem. + * + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + * + */ + +package chem + +import ( + ""fmt"" + ""math"" + ""strings"" + + v3 ""github.com/rmera/gochem/v3"" +) + +// NegateIndexes, given a set of indexes and the length of a molecule, produces +// a set of all the indexes _not_ in the original set. +func NegateIndexes(indexes []int, length int) []int { + ret := make([]int, 0, length-len(indexes)) + for i := 0; i < length; i++ { + if !isInInt(indexes, i) { + ret = append(ret, i) + + } + } + return ret +} + +const allchains = ""*ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"" + +// FixGromacsPDB fixes the problem that Gromacs PDBs have when there are more than 10000 residues +// Gromacs simply restarts the numbering. Since solvents (where this is likely to happen) don't have +// chain ID in Gromacs, it's impossible to distinguish between the water 1 and the water 10001. FixGromacsPDB +// Adds a chain ID to the newly restrated residue that is the letter/symbol coming after the last seen chain ID +// in the constant allchains defined in this file. The current implementation does nothing if a chain ID is already +// defined, even if it is wrong (if 9999 and the following 0 residue have the same chain). +func FixGromacsPDB(mol Atomer) { + // fmt.Println(""FIXING!"") + previd := 999999 + const pdbmaxresidue = 9999 + lastchain := ""*"" + j := 1 + for i := 0; i < mol.Len(); i++ { + at := mol.Atom(i) + if at.MolID > pdbmaxresidue { + at.MolID = j + if j == pdbmaxresidue { + j = 0 + } + j++ + } + if at.Chain == "" "" { + if previd > at.MolID { + index := strings.Index(allchains, lastchain) + 1 + // fmt.Println(""new chain index:"", index) + lastchain = string(allchains[index]) + } + at.Chain = lastchain + // fmt.Println(lastchain) ///////// + } else { + lastchain = at.Chain + } + previd = at.MolID + + //a fix for Martini Waters + if at.MolName == ""WN"" || at.MolName == ""WN "" || at.MolName == "" WN"" { + at.MolName = ""WNN"" + } + + } +} + +// Molecules2Atoms gets a selection list from a list of residues. +// It select all the atoms that form part of the residues in the list. +// It doesnt return errors. If a residue is out of range, no atom will +// be returned for it. Atoms are also required to be part of one of the chains +// specified in chains, but a nil ""chains"" can be given to select all chains. +func Molecules2Atoms(mol Atomer, residues []int, chains []string) []int { + atlist := make([]int, 0, len(residues)*3) + for key := 0; key < mol.Len(); key++ { + at := mol.Atom(key) + if isInInt(residues, at.MolID) && (isInString(chains, at.Chain) || len(chains) == 0) { + atlist = append(atlist, key) + } + } + return atlist + +} + +// EasyShape takes a matrix of coordinates, a value for epsilon (a number close to +// zero, the closer, the more +// strict the orthogonality requriements are) and an (optative) masser and returns +// two shape indicators based on the elipsoid of inertia (or it massless equivalent) +// a linear and circular distortion indicators, as percentages, and an error or +// nil (in that order). If you give a negative number as epsilon, the default +// (quite strict) will be used. +func EasyShape(coords *v3.Matrix, epsilon float64, mol ...Masser) (float64, float64, error) { + var masses []float64 + var err2 error + var err error + if len(mol) == 0 { + masses = nil + } else { + masses, err = mol[0].Masses() + if err != nil { + masses = nil + err2 = err + } + } + moment, err := MomentTensor(coords, masses) + if err != nil { + return -1, -1, err + } + rhos, err := Rhos(moment, epsilon) + if err != nil { + return -1, -1, err + } + linear, circular, err := RhoShapeIndexes(rhos) + if err != nil { + return -1, -1, err + } + return linear, circular, err2 +} + +// MolIDNameChain2Index takes a molID (residue number), atom name, chain index and a molecule Atomer. +// it returns the index associated with the atom in question in the Ref. The function returns also an error (if failure of warning) +// or nil (if succses and no warnings). Note that this function is not efficient to call several times to retrieve many atoms. +func MolIDNameChain2Index(mol Atomer, molID int, name, chain string) (int, error) { + var ret int = -1 + var err error + if mol == nil { + return -1, CError{""goChem: Given a nil chem.Atomer"", []string{""MolIDNameChain2Index""}} + } + for i := 0; i != mol.Len(); i++ { + a := mol.Atom(i) + if a.Name == """" && err == nil { + err = CError{""Warning: The Atoms does not seem to contain PDB-type information"", []string{""MolIDNameChain2Index""}} //We set this error but will still keep running the function in case the data is present later in the molecule. + } + if a.MolID == molID && a.Name == name && a.Chain == chain { + ret = i + break + } + + } + if ret == -1 { + var p string + if err != nil { + p = err.Error() + } + err = CError{fmt.Sprintf(""%s, No atomic index found in the Atomer given for the given MolID, atom name and chain. %s %d"", p, chain, molID), []string{""MolIDNameChain2Index""}} + } + return ret, err +} + +// OnesMass returns a column matrix with lenght rosw. +// This matrix can be used as a dummy mass matrix +// for geometric calculations. +func OnesMass(lenght int) *v3.Matrix { + return v3.Dense2Matrix(gnOnes(lenght, 1)) +} + +// Super determines the best rotation and translations to superimpose the coords in test +// considering only the atoms present in the slices of int slices indexes. +// The first indexes slices will be assumed to contain test indexes and the second, template indexes. +// If you give only one, it will be assumed to correspond to test, if test has more atoms than +// elements on the indexes set, or templa, otherwise. If no indexes are given, all atoms on each system +// will be superimposed. The number of atoms superimposed on both systems must be equal. +// Super modifies the test matrix, but template and indexes are not touched. +func Super(test, templa *v3.Matrix, indexes ...[]int) (*v3.Matrix, error) { + var ctest *v3.Matrix + var ctempla *v3.Matrix + if len(indexes) == 0 || indexes[0] == nil || len(indexes[0]) == 0 { //If you put the date in the SECOND slice, you are just messing with me. + ctest = test + ctempla = templa + } else if len(indexes) == 1 { + if test.NVecs() > len(indexes[0]) { + ctest = v3.Zeros(len(indexes[0])) + ctest.SomeVecs(test, indexes[0]) + ctempla = templa + } else if templa.NVecs() > len(indexes[0]) { + ctempla = v3.Zeros(len(indexes[0])) + ctempla.SomeVecs(templa, indexes[0]) + } else { + return nil, fmt.Errorf(""chem.Super: Indexes don't match molecules"") + } + } else { + ctest = v3.Zeros(len(indexes[0])) + ctest.SomeVecs(test, indexes[0]) + ctempla = v3.Zeros(len(indexes[1])) + ctempla.SomeVecs(templa, indexes[1]) + } + + if ctest.NVecs() != ctempla.NVecs() { + return nil, fmt.Errorf(""chem.Super: Ill formed coordinates for Superposition"") + } + + _, rotation, trans1, trans2, err1 := RotatorTranslatorToSuper(ctest, ctempla) + if err1 != nil { + return nil, errDecorate(err1, ""Super"") + } + test.AddVec(test, trans1) + // fmt.Println(""test1"",test, rotation) /////////////77 + test.Mul(test, rotation) + // fmt.Println(""test2"",test) /////////// + test.AddVec(test, trans2) + // fmt.Println(""test3"",test) /////// + return test, nil +} + +// RotateAbout about rotates the coordinates in coordsorig around by angle radians around the axis +// given by the vector axis. It returns the rotated coordsorig, since the original is not affected. +// Uses Clifford algebra. +func RotateAbout(coordsorig, ax1, ax2 *v3.Matrix, angle float64) (*v3.Matrix, error) { + coordsLen := coordsorig.NVecs() + coords := v3.Zeros(coordsLen) + translation := v3.Zeros(ax1.NVecs()) + translation.Copy(ax1) + axis := v3.Zeros(ax2.NVecs()) + axis.Sub(ax2, ax1) // the rotation axis + f := func() { coords.SubVec(coordsorig, translation) } + if err := gnMaybe(gnPanicker(f)); err != nil { + return nil, CError{err.Error(), []string{""v3.Matrix.SubVec"", ""RotateAbout""}} + } + Rot := v3.Zeros(coordsLen) + Rot = Rotate(coords, Rot, axis, angle) + g := func() { Rot.AddVec(Rot, translation) } + if err := gnMaybe(gnPanicker(g)); err != nil { + return nil, CError{err.Error(), []string{""v3.Matrix.AddVec"", ""RotateAbout""}} + + } + return Rot, nil +} + +// MatchAxes returns a rotated version of mol such that the vectors ax1 and ax2 are superimposed +// mol is, by default, centered on center (which should be the origin of both ax1 and ax2) +// unless recenter is given and true, in which case, it is not modified. +func MatchAxes(mol, ax1, ax2, center *v3.Matrix, recenter ...bool) (*v3.Matrix, error) { + r2, c2 := ax2.Dims() + if c2 != 3 || r2 != 1 { + panic(""Wrong ax2 vector"") + } + + r1, c1 := ax1.Dims() + if c1 != 3 || r1 != 1 { + panic(""Wrong ax1 vector"") + } + //let's center all in 'center' + ax1.Sub(ax1, center) + ax2.Sub(ax2, center) + mol.Sub(mol, center) + normal := v3.Zeros(1) + normal.Cross(ax1, ax2) //this vector should be the axis of rotation. + angle := Angle(ax1, ax2) + zero := v3.Zeros(1) + rot, err := RotateAbout(mol, normal, zero, angle) + if err != nil { + return nil, err + } + //we now undo the centering for all of our vectors + ax1.Add(ax1, center) + ax2.Add(ax2, center) + if len(recenter) > 0 && recenter[0] { + mol.Add(mol, center) + } + rot.Add(rot, center) + return rot, nil +} + +// EulerRotateAbout uses Euler angles to rotate the coordinates in coordsorig around by angle +// radians around the axis given by the vector axis. It returns the rotated coordsorig, +// since the original is not affected. It seems more clunky than the RotateAbout, which uses Clifford algebra. +// I leave it for benchmark, mostly, and might remove it later. There is no test for this function! +func EulerRotateAbout(coordsorig, ax1, ax2 *v3.Matrix, angle float64) (*v3.Matrix, error) { + r, _ := coordsorig.Dims() + coords := v3.Zeros(r) + translation := v3.Zeros(ax1.NVecs()) + translation.Copy(ax1) + axis := v3.Zeros(ax2.NVecs()) + axis.Sub(ax2, ax1) //now it became the rotation axis + f := func() { coords.SubVec(coordsorig, translation) } + if err := gnMaybe(gnPanicker(f)); err != nil { + return nil, CError{err.Error(), []string{""v3.Matrix.Subvec"", ""EulerRotateAbout""}} + + } + Zswitch := RotatorToNewZ(axis) + coords.Mul(coords, Zswitch) //rotated + Zrot, err := RotatorAroundZ(angle) + if err != nil { + return nil, errDecorate(err, ""EulerRotateAbout"") + } + // Zsr, _ := Zswitch.Dims() + // RevZ := v3.Zeros(Zsr) + RevZ, err := gnInverse(Zswitch, nil) + if err != nil { + return nil, errDecorate(err, ""EulerRotateAbout"") + } + coords.Mul(coords, Zrot) //rotated + coords.Mul(coords, RevZ) + coords.AddVec(coords, translation) + return coords, nil +} + +// Corrupted is a convenience function to check that a reference and a trajectory have the same number of atoms +func Corrupted(X Traj, R Atomer) error { + if X.Len() != R.Len() { + return CError{""Mismatched number of atoms/coordinates"", []string{""Corrupted""}} + } + return nil +} + +//Some internal convenience functions. + +// isInInt is a helper for the RamaList function, +// returns true if test is in container, false otherwise. +func isInInt(container []int, test int) bool { + if container == nil { + return false + } + for _, i := range container { + if test == i { + return true + } + } + return false +} + +// Same as the previous, but with strings. +func isInString(container []string, test string) bool { + if container == nil { + return false + } + for _, i := range container { + if test == i { + return true + } + } + return false +} + +// ""caps"" the atom tocap (which must be part of mol) with an H atom. +// The reference atom, if not nil, is employed to define the new bond as opposite to +func CapWithH(mol *Molecule, tocap int, position *v3.Matrix, atomIndex, bondIndex int) *Molecule { + if atomIndex < 0 { + for i := 0; i < mol.Len(); i++ { + in := mol.Atom(i).Index() + if in > atomIndex { + atomIndex = in + } + } + atomIndex++ //one more than the last one + } + if bondIndex < 0 { + for _, v := range mol.Bonds { + in := v.Index + if in > bondIndex { + bondIndex = in + } + } + bondIndex++ + } + for i := 0; i < mol.Len(); i++ { + if mol.Atom(i).Index() == tocap { + tocap = i + break + } + } + cp := &Atom{Symbol: ""H"", index: atomIndex, ID: mol.Len(), Name: ""H""} + //We'll use a _very_ naive way of determining the position of the new atom, of not given. + //Hopefully it's good enough that it can be fixed by optimization. + if position == nil { + r := mol.Coords[0].VecView(tocap) + position = v3.Zeros(0) + position.Set(0, 0, r.At(0, 0)) + position.Set(0, 1, r.At(0, 1)) + position.Set(0, 2, r.At(0, 2)+CHDist) + } + bond := &Bond{At1: mol.Atom(tocap), At2: cp, Dist: CHDist, Index: bondIndex} + cp.Bonds = []*Bond{bond} + mol.Atom(tocap).Bonds = append(mol.Atom(tocap).Bonds, bond) + mol.Atoms = append(mol.Atoms, cp) + mol.Bonds = append(mol.Bonds, bond) + r := v3.Zeros(1) + r.Copy(mol.Coords[0].VecView(tocap)) + ScaleBond(r, position, CHDist) //Check that this works. + ncoords := v3.Zeros(mol.Len()) + ncoords.StackVec(mol.Coords[0], position) + mol.Coords[0] = ncoords + return mol +} + +// ScaleBond moves the atom at2 (in place) so the distance between it and a1 is the one given (newdist). +// CAUTION: I have only tested it for the case where the original distance>bond, although I expect it to also work in the other case. +func ScaleBond(a1, a2 *v3.Matrix, newdist float64) { + Odist := v3.Zeros(1) + Odist.Sub(a1, a2) + distance := Odist.Norm(2) + // println(""dists"", distance, newdist) ///////////////////////// + scaling := math.Abs(distance-newdist) / distance + if distance < newdist { + scaling = 1 / scaling + } + Odist.Scale(scaling, Odist) + a2b := v3.Zeros(1) + a2b.Copy(a2) + a2.Add(a2b, Odist) + //DEBUG + // Odist.Sub(a1, a2) + // distance = Odist.Norm(2) + // println(""distsfinal"", distance, newdist) ///////////////////////// + +} + +// MakeWater Creates a water molecule at distance Angstroms from a2, in a direction that is angle radians from the axis defined by a1 and a2. +// Notice that the exact position of the water is not well defined when angle is not zero. One can always use the RotateAbout +// function to move the molecule to the desired location. If oxygen is true, the oxygen will be pointing to a2. Otherwise, +// one of the hydrogens will. +func MakeWater(a1, a2 *v3.Matrix, distance, angle float64, oxygen bool) *v3.Matrix { + water := v3.Zeros(3) + const WaterOHDist = 0.96 + const WaterAngle = 52.25 + const deg2rad = 0.0174533 + w := water.VecView(0) //we first set the O coordinates + w.Copy(a2) + w.Sub(w, a1) + w.Unit(w) + dist := v3.Zeros(1) + dist.Sub(a1, a2) + a1a2dist := dist.Norm(2) + // fmt.Println(""ala2dist"", a1a2dist, distance) ////////////////7777 + w.Scale(distance+a1a2dist, w) + w.Add(w, a1) + for i := 0; i <= 1; i++ { + o := water.VecView(0) + w = water.VecView(i + 1) + w.Copy(o) + // fmt.Println(""w1"", w) //////// + w.Sub(w, a2) + // fmt.Println(""w12"", w) /////////////// + w.Unit(w) + // fmt.Println(""w4"", w) + w.Scale(WaterOHDist+distance, w) + // fmt.Println(""w3"", w, WaterOHDist, distance) + o.Sub(o, a2) + t, _ := v3.NewMatrix([]float64{0, 0, 1}) + upp := v3.Zeros(1) + upp.Cross(w, t) + // fmt.Println(""upp"", upp, w, t) + upp.Add(upp, o) + upp.Add(upp, a2) + //water.SetMatrix(3,0,upp) + w.Add(w, a2) + o.Add(o, a2) + sign := 1.0 + if i == 1 { + sign = -1.0 + } + temp, _ := RotateAbout(w, o, upp, deg2rad*WaterAngle*sign) + w.SetMatrix(0, 0, temp) + } + var v1, v2 *v3.Matrix + if angle != 0 { + v1 = v3.Zeros(1) + v2 = v3.Zeros(1) + v1.Sub(a2, a1) + v2.Copy(v1) + v2.Set(0, 2, v2.At(0, 2)+1) //a ""random"" modification. The idea is that its not colinear with v1 + v3 := cross(v1, v2) + v3.Add(v3, a2) + water, _ = RotateAbout(water, a2, v3, angle) + } + if oxygen { + return water + } + //we move things so an hydrogen points to a2 and modify the distance acordingly. + e1 := water.VecView(0) + e2 := water.VecView(1) + e3 := water.VecView(2) + if v1 == nil { + v1 = v3.Zeros(1) + } + if v2 == nil { + v2 = v3.Zeros(1) + } + v1.Sub(e2, e1) + v2.Sub(e3, e1) + axis := cross(v1, v2) + axis.Add(axis, e1) + water, _ = RotateAbout(water, e1, axis, deg2rad*(180-WaterAngle)) + v1.Sub(e1, a2) + v1.Unit(v1) + v1.Scale(WaterOHDist, v1) + water.AddVec(water, v1) + return water +} + +// FixNumbering will put the internal numbering+1 in the atoms and residue fields, so they match the current residues/atoms +// in the molecule +func FixNumbering(r Atomer) { + resid := 0 + prevres := -1 + for i := 0; i < r.Len(); i++ { + at := r.Atom(i) + at.ID = i + 1 + if prevres != at.MolID { + prevres = at.MolID + resid++ + } + at.MolID = resid + } +} + +// CutBackRef takes a list of lists of residues and selects +// from r all atoms in each the list list[i] and belonging to the chain chain[i]. +// It caps the N and C terminal +// of each list with -COH for the N terminal and NH2 for C terminal. +// the residues on each sublist should be contiguous to each other. +// for instance, {6,7,8} is a valid sublist, {6,8,9} is not. +// This is NOT currently checked by the function!. It returns the list of kept atoms +func CutBackRef(r Atomer, chains []string, list [][]int) ([]int, error) { + //i:=r.Len() + if len(chains) != len(list) { + return nil, CError{fmt.Sprintf(""Mismatched chains (%d) and list (%d) slices"", len(chains), len(list)), []string{""CutBackRef""}} + } + var ret []int //This will be filled with the atoms that are kept, and will be returned. + for k, v := range list { + nter := v[0] + cter := v[len(v)-1] + nresname := """" + cresname := """" + for j := 0; j < r.Len(); j++ { + if r.Atom(j).MolID == nter && r.Atom(j).Chain == chains[k] { + nresname = r.Atom(j).MolName + break + } + } + if nresname == """" { + //we will protest if the Nter is not found. If Cter is not found we will just + //cut at the real Cter + return nil, CError{fmt.Sprintf(""list %d contains residue numbers out of boundaries"", k), []string{""CutBackRef""}} + + } + for j := 0; j < r.Len(); j++ { + curr := r.Atom(j) + if curr.Chain != chains[k] { + continue + } + if curr.MolID == cter { + cresname = curr.MolName + } + if curr.MolID == nter-1 { + makeNcap(curr, nresname) + } + if curr.MolID == cter+1 { + makeCcap(curr, cresname) + } + } + } + for _, i := range list { + t := Molecules2Atoms(r, i, chains) + // fmt.Println(""t"", len(t)) + ret = append(ret, t...) + } + // j:=0 + // for i:=0;;i++{ + // index:=i-j + // if index>=r.Len(){ + // break + // } + // if !isInInt(ret, i){ + // r.DelAtom(index) + // j++ + // } + // } + return ret, nil +} + +func makeNcap(at *Atom, resname string) { + if !isInString([]string{""C"", ""O"", ""CA""}, at.Name) { + return + } + at.MolID = at.MolID + 1 + at.MolName = resname + if at.Name == ""C"" { + at.Name = ""CTZ"" + } + if at.Name == ""CA"" { + at.Name = ""HCZ"" + at.Symbol = ""H"" + } +} + +func makeCcap(at *Atom, resname string) { + if !isInString([]string{""N"", ""H"", ""CA""}, at.Name) { + return + } + at.MolID = at.MolID - 1 + at.MolName = resname + if at.Name == ""N"" { + at.Name = ""NTZ"" + } + if at.Name == ""CA"" { + at.Name = ""HNZ"" + at.Symbol = ""H"" + } +} + +/* +//Takes a list of lists of residues and produces a new set of coordinates +//whitout any atom not in the lists or not from the chain chain. It caps the N and C terminal +//of each list with -COH for the N terminal and NH2 for C terminal. +//the residues on each sublist should be contiguous to each other. +//for instance, {6,7,8} is a valid sublist, {6,8,9} is not. +//This is NOT currently checked by the function! +//In addition, the Ref provided should have already been processed by +//CutBackRef, which is not checked either. +func CutBackCoords(r Ref, coords *v3.Matrix, chain string, list [][]int) (*v3.Matrix, error) { + //this is actually a really silly function. So far I dont check for errors, but I keep the return balue + //In case I do later. + var biglist []int + for _, i := range list { + smallist := Molecules2Atoms(r, i, []string{chain}) + biglist = append(biglist, smallist...) + } + NewVecs := v3.Zeros(len(biglist), 3) + NewVecs.SomeVecs(coords, biglist) + return NewVecs, nil + +} +*/ + +// CutLateralRef will return a list with the atom indexes of the lateral chains of the residues in list +// for each of these residues it will change the alpha carbon to oxygen and change the residue number of the rest +// of the backbone to -1. +func CutBetaRef(r Atomer, chain []string, list []int) []int { + // pairs := make([][]int,1,10) + // pairs[0]=make([]int,0,2) + for i := 0; i < r.Len(); i++ { + curr := r.Atom(i) + if isInInt(list, curr.MolID) && isInString(chain, curr.Chain) { + if curr.Name == ""CB"" { + // pairs[len(pairs)-1][1]=i //I am assuming that CA will show before CB in the PDB, which is rather weak + // paairs=append(pairs,make([]int,1,2)) + } + if curr.Name == ""CA"" { + curr.Name = ""HB4"" + curr.Symbol = ""H"" + // pairs[len(pairs)-1]=append(pairs[len(pairs)-1],i) + } else if isInString([]string{""C"", ""H"", ""HA"", ""O"", ""N""}, curr.Name) { //change the res number of the backbone so it is not considered + curr.MolID = -1 + } + + } + } + newlist := Molecules2Atoms(r, list, chain) + return newlist +} + +// CutAlphaRef will return a list with the atoms in the residues indicated by list, in the chains given. +// The carbonyl carbon and amide nitrogen for each residue will be transformer into hydrogens. The MolID of the +// other backbone atoms will be set to -1 so they are no longer considered. +func CutAlphaRef(r Atomer, chain []string, list []int) []int { + for i := 0; i < r.Len(); i++ { + curr := r.Atom(i) + if isInInt(list, curr.MolID) && isInString(chain, curr.Chain) { + if curr.Name == ""C"" { + curr.Name = ""HA2"" + curr.Symbol = ""H"" + } else if curr.Name == ""N"" { + curr.Name = ""HA3"" + curr.Symbol = ""H"" + } else if isInString([]string{""H"", ""O""}, curr.Name) { //change the res number of the backbone so it is not considered + curr.MolID = -1 + } + + } + } + newlist := Molecules2Atoms(r, list, chain) + return newlist +} + +// TagAtomsByName will tag all atoms with a given name in a given list of atoms. +// return the number of tagged atoms +func TagAtomsByName(r Atomer, name string, list []int) int { + tag := 0 + for i := 0; i < r.Len(); i++ { + curr := r.Atom(i) + if isInInt(list, i) && curr.Name == name { + curr.Tag = 1 + tag++ + } + } + return tag +} + +// ScaleBonds scales all bonds between atoms in the same residue with names n1, n2 to a final lenght finallengt, by moving the atoms n2. +// the o0, only the cone in the plane vector direction. +// the 'initial' argument allows the construction of a truncate cone with a radius of initial. +func SelCone(B, selection *v3.Matrix, angle, distance, thickness, initial float64, whatcone int) []int { + A := v3.Zeros(B.NVecs()) + A.Copy(B) //We will be altering the input so its better to work with a copy. + ar, _ := A.Dims() + selected := make([]int, 0, 3) + neverselected := make([]int, 0, 30000) //waters that are too far to ever be selected + nevercutoff := distance / math.Cos(angle) //cutoff to be added to neverselected + A, _, err := MassCenter(A, selection, nil) //Centrate A in the geometric center of the selection, Its easier for the following calculations + if err != nil { + panic(PanicMsg(err.Error())) + } + selection, _, _ = MassCenter(selection, selection, nil) //Centrate the selection as well + plane, err := BestPlane(selection, nil) //I have NO idea which direction will this vector point. We might need its negative. + if err != nil { + panic(PanicMsg(err.Error())) + } + for i := thickness / 2; i <= distance; i += thickness { + maxdist := math.Tan(angle)*i + initial //this should give me the radius of the cone at this point + for j := 0; j < ar; j++ { + if isInInt(selected, j) || isInInt(neverselected, j) { //we dont scan things that we have already selected, or are too far + continue + } + atom := A.VecView(j) + proj := Projection(atom, plane) + norm := proj.Norm(2) + //Now at what side of the plane is the atom? + angle := Angle(atom, plane) + if whatcone > 0 { + if angle > math.Pi/2 { + continue + } + } else if whatcone < 0 { + if angle < math.Pi/2 { + continue + } + } + if norm > i+(thickness/2.0) || norm < (i-thickness/2.0) { + continue + } + proj.Sub(proj, atom) + projnorm := proj.Norm(2) + if projnorm <= maxdist { + selected = append(selected, j) + } + if projnorm >= nevercutoff { + neverselected = append(neverselected, j) + } + } + } + return selected +} + +func ext(s string) string { + s2 := strings.Split(s, ""."") + return strings.ToLower(s2[len(s2)-1]) +} + +// Attemps to open a using the file extension +// to guess the format among the supported molecule file format. Returns a Molecule +// and an error which will be non nil if the reading fails or if the extension does not +// belong to a supported format. +func MoleculeFileRead(name string) (mol *Molecule, err error) { + switch ext(name) { + case ""pdb"": + mol, err = PDBFileRead(name, true) + case ""gro"": + mol, err = GroFileRead(name) + case ""pdbx"": + mol, err = PDBxFileRead(name) + case ""cif"": + mol, err = PDBxFileRead(name) + case ""xyz"": + mol, err = XYZFileRead(name) + default: + err = fmt.Errorf(""goChem/MoleculeFileRead: Extension %s not supported"", ext(name)) + } + return +} + +// Creates a map from the old position of a set of atoms, to their new position. It takes the full lenght of the molecule, +// so the indexes not present in oripos or newpos are assigned their same original position. +// if an atom A appears in oripos and the atom B appears in the equivalent place in newpos, a map entry A->B will be created. +// if no entry in oripos contains B, then an additional entry B->A will be created. +func SwitchMap(oripos, newpos []int, fulllen int) map[int]int { + m := make(map[int]int) + for i, v := range oripos { + m[v] = newpos[i] + } + //if not given in the list, we also need to ensure that for every a that goes to b, the b element goes to a + //of course you might want a go to be, b go to c, c go to a. You need to give those explicitly in that case. + for i, v := range newpos { + if _, ok := m[v]; ok { + continue + } + m[v] = oripos[i] + } + //Finally, whatever wasn't mentioned in neither oripos nor newpos, keeps its place + for i := 0; i < fulllen; i++ { + if _, ok := m[i]; ok { + continue + } + m[i] = i + } + + return m +} + +// Switches each atom in mol from position i to position switchmap[i] for each i in the switchmap keys. +// Returns a modified topology. mol itself is not affected (its atoms remain in the same order) but the Indexes and IDs +// of the atoms, are, since SwitchAtoms doesn't make copies and resets IDs and Indexes to match the atoms's positions +// in the returned topology. +func SwitchAtoms(switchmap map[int]int, mol Atomer) *Topology { + ret := NewTopology(0, 1) + ret.Atoms = make([]*Atom, mol.Len()) + for i := 0; i < mol.Len(); i++ { + at := mol.Atom(i) + j, ok := switchmap[i] + if !ok { + j = i + } + ret.Atoms[j] = at + } + for i, v := range ret.Atoms { + if v == nil { + panic(fmt.Sprintf(""The indexes were such that position %d ended up empty/nil"", i)) + } + } + ret.FillIndexes() + ret.ResetIDs() + return ret +} + +// Switches each atom in mol from position i to position switchmap[i] for each i in the switchmap keys, +// returning the modified matrix. The original vec is not affected. +func SwitchCoords(switchmap map[int]int, vec *v3.Matrix) *v3.Matrix { + ret := v3.Zeros(vec.Len()) + finalpos := make([]int, ret.Len()) + for i, _ := range finalpos { + n, ok := switchmap[i] + if ok { + finalpos[i] = n + } else { + finalpos[i] = i + } + + } + ret.SetVecs(vec, finalpos) + return ret +} +","Go" +"Computational Biochemistry","rmera/gochem","doc.go",".go","1076","31","/* + * doc.go, part of gochem. + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + */ + +/*This is the main package of the goChem library. +It provides atom and molecule structures, facilities for reading and +writing some files used in computational chemistry and functions for +geometric manipulations and shape, among others indicators. + +See www.gochem.org for more information. + +*/ +package chem +","Go" +"Computational Biochemistry","rmera/gochem","chem.go",".go","26233","877","/* + * chem.go, part of gochem. + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + */ + +package chem + +import ( + ""fmt"" + ""sort"" + + v3 ""github.com/rmera/gochem/v3"" +) + +//import ""strings"" + +/* Many funcitons here panic instead of returning errors. This is because they are ""fundamental"" + * functions. I considered that if something goes wrong here, the program is way-most likely wrong and should + * crash. Most panics are related to using the funciton on a nil object or trying to access out-of bounds + * fields + */ + +// Atom contains the information to represent an atom, except for the coordinates, which will be in a separate *v3.Matrix +// and the b-factors, which are in a separate slice of float64. +type Atom struct { + Name string //PDB name of the atom + ID int //The PDB index of the atom + index int //The place of the atom in a set. I won't make it accessible to ensure that it does correspond to the ordering. + Tag int //Just added this for something that someone might want to keep that is not a float. + MolName string //PDB name of the residue or molecule (3-letter code for residues) + MolName1 byte //the one letter name for residues and nucleotids + Char16 byte //Whatever is in the column 16 (counting from 0) in a PDB file, anything. + MolID int //PDB index of the corresponding residue or molecule + Chain string //One-character PDB name for a chain. + Mass float64 //hopefully all these float64 are not too much memory + Occupancy float64 //a PDB crystallographic field, often used to store values of interest. + Vdw float64 //radius + Charge float64 //Partial charge on an atom + Symbol string + Het bool // is the atom an hetatm in the pdb file? (if applicable) + Bonds []*Bond //The bonds connecting the atom to others. +} + +//Atom methods + +// Copy puts in the receiver a copy of A +func (N *Atom) Copy(A *Atom) { + if A == nil || N == nil { + panic(ErrNilAtom) + } + N.Name = A.Name + N.ID = A.ID + N.Tag = A.Tag + N.MolName = A.MolName + N.MolName1 = A.MolName1 + N.MolID = A.MolID + N.Chain = A.Chain + N.Mass = A.Mass + N.Occupancy = A.Occupancy + N.Vdw = A.Vdw + N.Charge = A.Charge + N.Symbol = A.Symbol + N.Het = A.Het +} + +// Index returns the index of the atom +func (N *Atom) Index() int { + return N.index +} + +// Index returns the index of the atom +func (N *Atom) SetIndex(i int) { + N.index = i +} + +/*****Topology type***/ + +// Topology contains information about a molecule which is not expected to change in time (i.e. everything except for coordinates and b-factors) +type Topology struct { + Atoms []*Atom + Bonds []*Bond //This field is new, for convenience. + charge int + multi int +} + +// NewTopology returns topology with ats atoms, +// charge charge and multi multiplicity. +// It doesnt check for consitency across slices, correct charge +// or unpaired electrons. +func NewTopology(charge, multi int, ats ...[]*Atom) *Topology { + top := new(Topology) + if len(ats) == 0 || ats[0] == nil { + top.Atoms = make([]*Atom, 0, 0) //return nil, fmt.Errorf(""Supplied a nil Topology"") + } else { + top.Atoms = ats[0] + } + top.charge = charge + top.multi = multi + return top +} + +/*Topology methods*/ + +// Charge returns the total charge of the topology +func (T *Topology) Charge() int { + return T.charge +} + +// Multi returns the multiplicity in the topology +func (T *Topology) Multi() int { + return T.multi +} + +// SetCharge sets the total charge of the topology to i +func (T *Topology) SetCharge(i int) { + T.charge = i +} + +// SetMulti sets the multiplicity in the topology to i +func (T *Topology) SetMulti(i int) { + T.multi = i +} + +// FillMasses tries to get fill the masses for atom that don't have one +// by getting it from the symbol. Only a few common elements are supported +func (T *Topology) FillMasses() { + for _, val := range T.Atoms { + if val.Symbol != """" && val.Mass == 0 { + val.Mass = symbolMass[val.Symbol] //Not error checking + } + } +} + +// FillsIndexes sets the Index value of each atom to that cooresponding to its +// place in the molecule. + +func (T *Topology) SetIndexes() { + T.FillIndexes() +} + +func (T *Topology) FillIndexes() { + for key, val := range T.Atoms { + val.index = key + } + +} + +// FillVdw tries to get fill the van der Waals radii for the atoms in the molecule +// from a symbol->radii map. Only a few common elements are supported +func (T *Topology) FillVdw() { + for _, val := range T.Atoms { + if val.Symbol != """" && val.Vdw == 0 { + val.Vdw = symbolVdwrad[val.Symbol] //Not error checking + //I'm not super sure about this. + } + } +} + +// ResetIDs sets the current order of atoms as ID and the order of molecules as +// MolID for all atoms +func (T *Topology) ResetIDs() { + currid := 1 + currid2 := 1 + for key, val := range T.Atoms { + T.Atoms[key].ID = key + 1 + if currid == val.MolID { + continue + } + if currid == val.MolID-1 { //We hit a new molecule + currid2++ + currid++ + continue + } + //change of residue after fixing one that didnt match position + if currid2 != val.MolID { + currid2 = T.Atoms[key].MolID + T.Atoms[key].MolID = currid + 1 + currid = currid + 1 + continue + } + //A residue's index doesnt match its position + T.Atoms[key].MolID = currid + + } +} + +// CopyAtoms copies the atoms form A into the receiver topology. This is a deep copy, so the receiver must have +// at least as many atoms as A. +func (T *Topology) CopyAtoms(A Atomer) { + //T := new(Topology) + if len(T.Atoms) < A.Len() { + T.Atoms = make([]*Atom, A.Len()) + for i, _ := range T.Atoms { + T.Atoms[i] = new(Atom) + } + } + for key := 0; key < A.Len(); key++ { + T.Atoms[key].Copy(A.Atom(key)) + } +} + +// Atom returns the Atom corresponding to the index i +// of the Atom slice in the Topology. Panics if +// out of range. +func (T *Topology) Atom(i int) *Atom { + if i >= T.Len() { + panic(ErrAtomOutOfRange) + } + return T.Atoms[i] +} + +// SetAtom sets the (i+1)th Atom of the topology to aT. +// Panics if out of range +func (T *Topology) SetAtom(i int, at *Atom) { + if i >= T.Len() { + panic(ErrAtomOutOfRange) + } + T.Atoms[i] = at +} + +// AppendAtom appends an atom at the end of the reference +func (T *Topology) AppendAtom(at *Atom) { + /*newmol, ok := T.CopyAtoms().(*Topology) + if !ok { + panic(""cant happen"") + } + newmol.Atoms = append(newmol.Atoms, at)*/ + T.Atoms = append(T.Atoms, at) +} + +// SelectAtoms puts the subset of atoms in T that have +// indexes in atomlist into the receiver. Panics if problem. +func (R *Topology) SomeAtoms(T Atomer, atomlist []int) { + var ret []*Atom + lenatoms := T.Len() + for k, j := range atomlist { + if j > lenatoms-1 { + err := fmt.Sprintf(""goChem: Atom requested (Number: %d, value: %d) out of range"", k, j) + panic(PanicMsg(err)) + } + ret = append(ret, T.Atom(j)) + } + R.Atoms = ret +} + +// SelectAtomsSafe puts the atoms of T +// with indexes in atomlist into the receiver. Returns error if problem. +func (R *Topology) SomeAtomsSafe(T Atomer, atomlist []int) error { + f := func() { R.SomeAtoms(T, atomlist) } + return gnMaybe(gnPanicker(f)) +} + +// DelAtom Deletes atom i by reslicing. +// This means that the copy still uses as much memory as the original T. +func (T *Topology) DelAtom(i int) { + if i >= T.Len() { + panic(ErrAtomOutOfRange) + } + if i == T.Len()-1 { + T.Atoms = T.Atoms[:i] + } else { + T.Atoms = append(T.Atoms[:i], T.Atoms[i+1:]...) + } +} + +// Len returns the number of atoms in the topology. +func (T *Topology) Len() int { + //if T.Atoms is nil, return len(T.Atoms) will panic, so I will let that happen for now. + // if T.Atoms == nil { + // panic(ErrNilAtoms) + // } + return len(T.Atoms) +} + +// Masses returns a slice of float64 with the masses of the atoms in the topology, or nil and an error if they have not been calculated +func (T *Topology) Masses() ([]float64, error) { + mass := make([]float64, T.Len()) + for i := 0; i < T.Len(); i++ { + thisatom := T.Atom(i) + if thisatom.Mass == 0 { + return nil, CError{fmt.Sprintf(""goChem: Not all the masses have been obtained: %d %v"", i, thisatom), []string{""Topology.Masses""}} + } + mass[i] = thisatom.Mass + } + return mass, nil +} + +func (T *Topology) RemoveBonds() { + T.Bonds = nil + for _, v := range T.Atoms { + v.Bonds = nil + } +} + +// AssignBonds assigns bonds to a molecule based on a simple distance +// criterium, similar to that described in DOI:10.1186/1758-2946-3-33 +func (T *Topology) AssignBonds(coord *v3.Matrix) error { + T.RemoveBonds() + // might get slow for + //large systems. It's really not thought + //for proteins or macromolecules. + //For this reason, this method is not called automatically when building a new topology. + //Well, that and that it requires a Matrix object, which would mean changing the + //signature of the NewTopology function. + var t1, t2 *v3.Matrix + var at1, at2 *Atom + T.FillIndexes() + t3 := v3.Zeros(1) + bonds := make([]*Bond, 0, T.Len()) + tot := T.Len() + var nextIndex int + for i := 0; i < tot; i++ { + t1 = coord.VecView(i) + at1 = T.Atoms[i] + cov1 := symbolCovrad[at1.Symbol] + if cov1 == 0 { + err := new(CError) + err.msg = fmt.Sprintf(""Couldn't find the covalent radii for %s %d"", at1.Symbol, i) + err.Decorate(""AssignBonds"") + return err + } + for j := i + 1; j < tot; j++ { + t2 = coord.VecView(j) + at2 = T.Atoms[j] + cov2 := symbolCovrad[at2.Symbol] + if cov2 == 0 { + err := new(CError) + err.msg = fmt.Sprintf(""Couldn't find the covalent radii for %s %d"", at2.Symbol, j) + err.Decorate(""AssignBonds"") + return err + } + + t3.Sub(t2, t1) + d := t3.Norm(2) + if d < cov1+cov2+bondtol && d > tooclose { + b := &Bond{Index: nextIndex, Dist: d, At1: at1, At2: at2} + at1.Bonds = append(at1.Bonds, b) + at2.Bonds = append(at2.Bonds, b) + bonds = append(bonds, b) //just to easily keep track of them. + nextIndex++ + } + + } + } + + //Now we check that no atom has too many bonds. + for i := 0; i < tot; i++ { + at := T.Atoms[i] + max := symbolMaxBonds[at.Symbol] + if max == 0 { //means there is not a specified number of bonds for this atom. + continue + } + sort.Slice(at.Bonds, func(i, j int) bool { return at.Bonds[i].Dist < at.Bonds[j].Dist }) + //I am hoping this will remove bonds until len(at.Bonds) is not + //greater than max. + for i := len(at.Bonds); i > max; i = len(at.Bonds) { + err := at.Bonds[len(at.Bonds)-1].Remove() //we remove the longest bond + bonds = bondsliceremoval(bonds, at.Bonds[len(at.Bonds)-1].Index) //we also remove it from the bonds slice + if err != nil { + return errDecorate(err, ""AssignBonds"") + } + } + + } + T.Bonds = bonds + return nil +} + +func bondsliceremovalMaybeCheaper(bonds []*Bond, RemIndex int) []*Bond { + indexrem := -1 + ret := make([]*Bond, 0, len(bonds)-1) + for i, v := range bonds { + if v.Index == RemIndex { + indexrem = i + } + } + ret = append(ret, bonds[:indexrem]...) + if indexrem < len(bonds)-1 { + ret = append(ret, bonds[indexrem+1:]...) + } + return ret +} + +func bondsliceremoval(bonds []*Bond, RemIndex int) []*Bond { + ret := make([]*Bond, 0, len(bonds)-1) + for _, v := range bonds { + if v.Index == RemIndex { + continue + } + ret = append(ret, v) + } + return ret +} + +/**Type Molecule**/ + +// Molecule contains all the info for a molecule in many states. The info that is expected to change between states, +// Coordinates and b-factors are stored separately from other atomic info. +type Molecule struct { + *Topology + Coords []*v3.Matrix + Bfactors [][]float64 + XYZFileData []string //This can be anything. The main rationale for including it is that XYZ files have a ""comment"" + //line after the first one. This line is sometimes used to write the energy of the structure. + //So here the line can be kept for each XYZ frame, and parse later + current int +} + +// NewMolecule makes a molecule with ats atoms, coords coordinates, bfactors b-factors +// charge charge and unpaired unpaired electrons, and returns it. It doesnt check for +// consitency across slices or correct charge or unpaired electrons. +func NewMolecule(coords []*v3.Matrix, ats Atomer, bfactors [][]float64) (*Molecule, error) { + if ats == nil { + return nil, CError{""Supplied a nil Reference"", []string{""NewMolCule""}} + } + if coords == nil { + return nil, CError{""Supplied a nil Coord slice"", []string{""NewMolCule""}} + } + // if bfactors == nil { + // return nil, fmt.Errorf(""Supplied a nil Bfactors slice"") + // } + mol := new(Molecule) + atcopy := func() { + mol.Topology = NewTopology(9999, -1, make([]*Atom, 0, ats.Len())) //I use 9999 for charge and -1 or multi to indicate that they are not truly set. So far NewTopology never actually returns any error so it's safe to ignore them. + for i := 0; i < ats.Len(); i++ { + mol.Atoms = append(mol.Atoms, ats.Atom(i)) + } + } + switch ats := ats.(type) { //for speed + case *Topology: + mol.Topology = ats + case AtomMultiCharger: + atcopy() + mol.SetMulti(ats.Multi()) + mol.SetCharge(ats.Charge()) + default: + atcopy() + } + mol.Coords = coords + mol.Bfactors = bfactors + return mol, nil +} + +//The molecule methods: + +// DelCoord deletes the coodinate i from every frame of the molecule. +func (M *Molecule) DelCoord(i int) error { + //note: Maybe this shouldn't be exported. Unexporting it could be a reasonable API change. + r, _ := M.Coords[0].Dims() + for j := 0; j < len(M.Coords); j++ { + tmp := v3.Zeros(r - 1) + tmp.DelVec(M.Coords[j], i) + M.Coords[j] = tmp + } + return nil +} + +// Del Deletes atom i and its coordinates from the molecule. +func (M *Molecule) Del(i int) error { + if i >= M.Len() { + panic(ErrAtomOutOfRange) + } + M.DelAtom(i) + err := M.DelCoord(i) + return err +} + +// Copy puts in the receiver a copy of the molecule A including coordinates +func (M *Molecule) Copy(A *Molecule) { + if err := A.Corrupted(); err != nil { + panic(err.Error()) + } + r, _ := A.Coords[0].Dims() + //mol := new(Molecule) + M.Topology = new(Topology) + for i := 0; i < A.Len(); i++ { + at := new(Atom) + at.Copy(A.Atom(i)) + M.Topology.Atoms = append(M.Topology.Atoms, at) + + } + // M.CopyAtoms(A) + M.Coords = make([]*v3.Matrix, 0, len(A.Coords)) + M.Bfactors = make([][]float64, 0, len(A.Bfactors)) + for key, val := range A.Coords { + tmp := v3.Zeros(r) + tmp.Copy(val) + M.Coords = append(M.Coords, tmp) + tmp2 := copyB(A.Bfactors[key]) + M.Bfactors = append(M.Bfactors, tmp2) + } + if err := M.Corrupted(); err != nil { + panic(PanicMsg(fmt.Sprintf(""goChem: Molecule creation error: %s"", err.Error()))) + } +} + +func copyB(b []float64) []float64 { + r := make([]float64, len(b), len(b)) + for k, v := range b { + r[k] = v + } + return r +} + +// AddFrame akes a matrix of coordinates and appends them at the end of the Coords. +// It checks that the number of coordinates matches the number of atoms. +func (M *Molecule) AddFrame(newframe *v3.Matrix) { + if newframe == nil { + panic(ErrNilFrame) + } + r, c := newframe.Dims() + if c != 3 { + panic(ErrNotXx3Matrix) + } + if M.Len() != r { + panic(PanicMsg(fmt.Sprintf(""goChem: Wrong number of coordinates (%d)"", newframe.NVecs()))) + } + if M.Coords == nil { + M.Coords = make([]*v3.Matrix, 1, 1) + } + M.Coords = append(M.Coords, newframe) +} + +// AddManyFrames adds the array of matrices newfames to the molecule. It checks that +// the number of coordinates matches the number of atoms. +func (M *Molecule) AddManyFrames(newframes []*v3.Matrix) { + if newframes == nil { + panic(ErrNilFrame) + } + if M.Coords == nil { + M.Coords = make([]*v3.Matrix, 1, len(newframes)) + } + for key, val := range newframes { + f := func() { M.AddFrame(val) } + err := gnMaybe(gnPanicker(f)) + if err != nil { + panic(PanicMsg(fmt.Sprintf(""goChem: %s in frame %d"", err.Error(), key))) + } + } +} + +// Coord returns the coords for the atom atom in the frame frame. +// panics if frame or coords are out of range. +func (M *Molecule) Coord(atom, frame int) *v3.Matrix { + if frame >= len(M.Coords) { + panic(PanicMsg(fmt.Sprintf(""goChem: Frame requested (%d) out of range"", frame))) + } + r, _ := M.Coords[frame].Dims() + if atom >= r { + panic(PanicMsg(fmt.Sprintf(""goChem: Requested coordinate (%d) out of bounds (%d)"", atom, M.Coords[frame].NVecs()))) + } + ret := v3.Zeros(1) + empt := M.Coords[frame].VecView(atom) + ret.Copy(empt) + return ret +} + +// Current returns the number of the next read frame +func (M *Molecule) Current() int { + if M == nil { + return -1 + } + return M.current +} + +// SetCurrent sets the value of the frame nex to be read +// to i. +func (M *Molecule) SetCurrent(i int) { + if i < 0 || i >= len(M.Coords) { + panic(PanicMsg(fmt.Sprintf(""goChem: Invalid new value for current frame: %d Current frames: %d"", i, len(M.Coords)))) + } + M.current = i +} + +/* +//SetCoords replaces the coordinates of atoms in the positions given by atomlist with the gnOnes in NewVecs (in order) +//If atomlist contains a single element, it replaces as many coordinates as given in NewVecs, starting +//at the element in atomlist. In the latter case, the function checks that there are enough coordinates to +//replace and returns an error if not. +func (M *Molecule) SetCoords(NewVecs *CoordMA, atomlist []int, frame int) { + if frame >= len(M.Coords) { + panic(fmt.Sprintf(""Frame (%d) out of range!"", frame)) + } + //If supplies a list with one number, the NewVecs will replace the old coords + //Starting that number. We do check that you don't put more coords than spaces we have. + if len(atomlist) == 1 { + if NewVecs.Rows() > M.Coords[frame].Rows()-atomlist[0]-1 { + panic(fmt.Sprintf(""Cant replace starting from position %d: Not enough atoms in molecule"", atomlist[0])) + } + M.Coords[frame].SetMatrix(atomlist[0], 0, NewVecs) + return + } + //If the list has more than one atom + lenatoms := M.Len() + for k, j := range atomlist { + if j > lenatoms-1 { + panic(fmt.Sprintf(""Requested position number: %d (%d) out of range"", k, j)) + } + M.Coords[frame].SetMatrix(j, 0, NewVecs.GetRowVector(k)) + } +} + +*/ + +// Corrupted checks whether the molecule is corrupted, i.e. the +// coordinates don't match the number of atoms. It also checks +// That the coordinate matrices have 3 columns. +func (M *Molecule) Corrupted() error { + var err error + if M.Bfactors == nil { + M.Bfactors = make([][]float64, 0, len(M.Coords)) + M.Bfactors = append(M.Bfactors, make([]float64, M.Len())) + } + lastbfac := len(M.Bfactors) - 1 + for i := range M.Coords { + r, c := M.Coords[i].Dims() + if M.Len() != r || c != 3 { + err = CError{fmt.Sprintf(""Inconsistent coordinates/atoms in frame %d: Atoms %d, coords: %d"", i, M.Len(), M.Coords[i].NVecs()), []string{""Molecule.Corrupted""}} + break + } + //Since bfactors are not as important as coordinates, we will just fill with + //zeroes anything that is lacking or incomplete instead of returning an error. + + if lastbfac < i { + bfacs := make([]float64, M.Len()) + M.Bfactors = append(M.Bfactors, bfacs) + } + bfr := len(M.Bfactors[i]) + if bfr < M.Len() { + M.Bfactors[i] = make([]float64, M.Len(), 1) + } + } + return err +} + +// NFrames returns the number of frames in the molecule +func (M *Molecule) NFrames() int { + return len(M.Coords) +} + +//Implementaiton of the sort.Interface + +// Swap function, as demanded by sort.Interface. It swaps atoms, coordinates +// (all frames) and bfactors of the molecule. +func (M *Molecule) Swap(i, j int) { + M.Atoms[i], M.Atoms[j] = M.Atoms[j], M.Atoms[i] + for k := 0; k < len(M.Coords); k++ { + M.Coords[k].SwapVecs(i, j) + t1 := M.Bfactors[k][i] + t2 := M.Bfactors[k][j] + M.Bfactors[k][i] = t2 + M.Bfactors[k][j] = t1 + } +} + +// Less returns true if the value in the Bfactors for +// atom i are less than that for atom j, and false otherwise. +func (M *Molecule) Less(i, j int) bool { + return M.Bfactors[0][i] < M.Bfactors[0][j] +} + +//Len is implemented in Topology + +//End sort.Interface + +/****************************************** +//The following implement the Traj interface +**********************************************/ + +// Checks that the molecule exists and has some existent +// Coordinates, in which case returns true. +// It returns false otherwise. +// The coordinates could still be empty +func (M *Molecule) Readable() bool { + if M != nil && M.Coords != nil && M.current < len(M.Coords) { + + return true + } + return false +} + +// Next puts the next frame into V and returns an error or nil +// The box argument is never used. +func (M *Molecule) Next(V *v3.Matrix, box ...[]float64) error { + if M.current >= len(M.Coords) { + return newlastFrameError("""", len(M.Coords)-1) + } + // fmt.Println(""CURR"", M.current, len(M.Coords), V.NVecs(), M.Coords[M.current].NVecs()) //////////////// + M.current++ + if V == nil { + return nil + } + V.Copy(M.Coords[M.current-1]) + return nil +} + +// InitRead initializes molecule to be read as a traj (not tested!) +func (M *Molecule) InitRead() error { + if M == nil || len(M.Coords) == 0 { + return CError{""Bad molecule"", []string{""InitRead""}} + } + M.current = 0 + return nil +} + +// NextConc takes a slice of bools and reads as many frames as elements the list has +// form the trajectory. The frames are discarted if the corresponding elemetn of the slice +// is false. The function returns a slice of channels through each of each of which +// a *matrix.DenseMatrix will be transmited +func (M *Molecule) NextConc(frames []*v3.Matrix) ([]chan *v3.Matrix, error) { + toreturn := make([]chan *v3.Matrix, 0, len(frames)) + used := false + + for _, val := range frames { + if val == nil { + M.current++ + toreturn = append(toreturn, nil) + continue + } + if M.current >= len(M.Coords) { + lastframe := newlastFrameError("""", len(M.Coords)-1) + if used == false { + return nil, lastframe + } else { + return toreturn, lastframe + } + } + used = true + toreturn = append(toreturn, make(chan *v3.Matrix)) + go func(a *v3.Matrix, pipe chan *v3.Matrix) { + pipe <- a + }(M.Coords[M.current], toreturn[len(toreturn)-1]) + M.current++ + } + return toreturn, nil +} + +// Close just sets the ""current"" counter to 0. +// If you are using it as a trajectory, you can always just discard the molecule +// and let the CG take care of it, as there is nothing on disk linked to it.. +func (M *Molecule) Close() { + M.current = 0 +} + +/**End Traj interface implementation***********/ + +//End Molecule methods + +//Traj Error + +type lastFrameError struct { + fileName string + frame int + deco []string +} + +// Error returns an error message string. +func (E *lastFrameError) Error() string { + return ""EOF"" //: Last frame in mol-based trajectory from file %10s reached at frame %10d"", E.fileName, E.frame) +} + +// Format returns the format used by the trajectory that returned the error. +func (E *lastFrameError) Format() string { + return ""mol"" +} + +// Frame returns the frame at which the error was detected. +func (E *lastFrameError) Frame() int { + return E.frame +} + +func (E *lastFrameError) Critical() bool { + return false +} + +// FileName returns the name of the file from where the trajectory that gave the error is read. +func (E *lastFrameError) FileName() string { + return E.fileName +} + +// NormalLastFrameTermination does nothing, it is there so we can have an interface unifying all +// ""normal termination"" errors so they can be filtered out by type switch. +func (E *lastFrameError) NormalLastFrameTermination() { +} + +// Decorate will add the dec string to the decoration slice of strings of the error, +// and return the resulting slice. +func (E *lastFrameError) Decorate(dec string) []string { + if dec == """" { + return E.deco + } + E.deco = append(E.deco, dec) + return E.deco +} + +func newlastFrameError(filename string, frame int) *lastFrameError { + e := new(lastFrameError) + e.fileName = filename + e.frame = frame + return e +} + +//End Traj Error + +//The general concrete error type for the package + +// CError (Concrete Error) is the concrete error type +// for the chem package, that implements chem.Error +type CError struct { + msg string + deco []string +} + +//func (err CError) NonCritical() bool { return err.noncritical } + +func (err CError) Error() string { return err.msg } + +// Decorate will add the dec string to the decoration slice of strings of the error, +// and return the resulting slice. +func (err CError) Decorate(dec string) []string { + if dec == """" { + return err.deco + } + err.deco = append(err.deco, dec) + return err.deco +} + +// errDecorate predates the Go ""errors"" package, so it implemented +// a way to add informations to errors. It has been now modified to just +// use the %w directive under the hood. +func errDecorate(err error, caller string) error { + if err == nil { + return nil + } + return fmt.Errorf(""%s: %w"", caller, err) +} + +// PanicMsg is the type used for all the panics raised in the chem package +// so they can be easily recovered if needed. goChem only raises panics +// for programming errors: Attempts to to out of a matrice's bounds, +// dimension mismatches in matrices, etc. +type PanicMsg string + +// Error returns a string with an error message +func (v PanicMsg) Error() string { return string(v) } + +const ( + ErrNilData = PanicMsg(""goChem: Nil data given "") + ErrInconsistentData = PanicMsg(""goChem: Inconsistent data length "") + ErrNilMatrix = PanicMsg(""goChem: Attempted to access nil v3.Matrix or gonum/mat64.Dense"") + ErrNilAtoms = PanicMsg(""goChem: Topology has a nil []*Atom slice"") + ErrNilAtom = PanicMsg(""goChem: Attempted to copy from or to a nil Atom"") + ErrAtomOutOfRange = PanicMsg(""goChem: Requested/Attempted setting Atom out of range"") + ErrNilFrame = PanicMsg(""goChem: Attempted to acces nil frame"") + ErrNotXx3Matrix = PanicMsg(""goChem: A v3.Matrix should have 3 columns"") + ErrCliffordRotation = PanicMsg(""goChem-Clifford: Target and Result matrices must have the same dimensions. They cannot reference the same matrix"") //the only panic that the Clifford functions throw. +) +","Go" +"Computational Biochemistry","rmera/gochem","matrixhelp.go",".go","5034","187","/* + * matrixhelp.go, part of gochem. + * + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + * + */ + +package chem + +//A munch of unexported mathematical functions, most of them just for convenience. + +import ( + ""fmt"" + ""math"" + + ""github.com/rmera/gochem/v3"" + ""gonum.org/v1/gonum/mat"" +) + +const appzero float64 = 0.000000000001 //used to correct floating point +//errors. Everything equal or less than this is considered zero. This probably sucks. + +//Computes the inverse matrix of F and puts it in target. If target is nil, it alloactes +//a new one. Returns target. +func gnInverse(F, target *v3.Matrix) (*v3.Matrix, error) { + if target == nil { + r := F.NVecs() + target = v3.Zeros(r) + } + err := target.Dense.Inverse(F.Dense) + if err != nil { + err = CError{err.Error(), []string{""mat.Inverse"", ""gnInverse""}} + } + return target, err +} + +//cross Takes 2 3-len column or row vectors and returns a column or a row +//vector, respectively, with the Cross product of them. +//should panic +func cross(a, b *v3.Matrix) *v3.Matrix { + c := v3.Zeros(1) + c.Cross(a, b) + return c +} + +//invSqrt return the inverse of the square root of val, or zero if +//|val| + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + * + */ + +package chem + +import v3 ""github.com/rmera/gochem/v3"" + +/*The plan is equate PDBs XTCs and in the future DCDs. One needs to separate the molecule methods between actual molecule methods, that requires atoms and coordinates, []atom methods, and DenseMatrix + * methods. Then one must implements objects for Xtc trajs that are more or less equivalent to molecules and set up an interface so many analyses can be carried out exactly the same from + * multiPDB or XTC or (eventually) DCD*/ + +// Traj is an interface for any trajectory object, including a Molecule Object +type Traj interface { + + //Is the trajectory ready to be read? + Readable() bool + + //reads the next frame and returns it as DenseMatrix if keep==true, or discards it if false + //it can also fill the (optional) box with the box vectors, it present in the frame. + Next(output *v3.Matrix, box ...[]float64) error + + //Returns the number of atoms per frame + Len() int +} + +// ConcTraj is an interface for a trajectory that can be read concurrently. +type ConcTraj interface { + Traj + + /*NextConc takes a slice of bools and reads as many frames as elements the list has + form the trajectory. The frames are discarted if the corresponding elemetn of the slice + is false. The function returns a slice of channels through each of each of which + a *matrix.DenseMatrix will be transmited*/ + NextConc(frames []*v3.Matrix) ([]chan *v3.Matrix, error) +} + +// TrjWrite is a trajectory to which new frames can be written +type TrjWrite interface { + WNext(*v3.Matrix, ...[]float64) error + Close() +} + +// Atomer is the basic interface for a topology. +type Atomer interface { + + //Atom returns the Atom corresponding to the index i + //of the Atom slice in the Topology. Should panic if + //out of range. + Atom(i int) *Atom + + Len() int +} + +// AtomChargerMultier is atomer but also gives a +// charge and multiplicity +type AtomMultiCharger interface { + Atomer + + //Charge gets the total charge of the topology + Charge() int + + //Multi returns the multiplicity of the topology + Multi() int +} + +// Masser can return a slice with the masses of each atom in the reference. +type Masser interface { + + //Returns a column vector with the massess of all atoms + Masses() ([]float64, error) +} + +//Errors + +//This error predates the ""wrapping"" error system of Go (i.e. the ""%w"" directive and the errors package). We should avoid +//using the Decorate method and/or make it use the ""%w"" directive internally. + +// Error is the interface for errors that all packages in this library implement. The Decorate method allows to add and retrieve info from the +// error, without changing it's type or wrapping it around something else. +type Error interface { + Error() string + Decorate(string) []string //This is the new thing for errors. It allows you to add information when you pass it up. Each call also returns the ""decoration"" slice of strins resulting from the current call. If passed an empty string, it should just return the current value, not add the empty string to the slice. + //The decorate slice should contain a list of functions in the calling stack, plus, for each function any relevant information, or nothing. If information is to be added to an element of the slice, it should be in this format: ""FunctionName: Extra info"" +} + +// TrajError is the nterface for errors in trajectories +type TrajError interface { + Error + Critical() bool + FileName() string + Format() string +} + +// LastFrameError has a useless function to distinguish the harmless errors (i.e. last frame) so they can be +// filtered in a typeswith that looks for this interface. +type LastFrameError interface { + TrajError + NormalLastFrameTermination() //does nothing, just to separate this interface from other TrajError's + +} +","Go" +"Computational Biochemistry","rmera/gochem","bonds.go",".go","15835","460","/* + * atomicdata.go, part of gochem. + * + * + * Copyright 2021 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + * + */ + +package chem + +import ( + ""fmt"" + ""slices"" + ""sort"" + + v3 ""github.com/rmera/gochem/v3"" +) + +// constants from DOI:10.1186/1758-2946-3-33 +const ( + tooclose = 0.63 + bondtol = 0.045 //the reference actually says 0.45 A but I strongly suspect that is a typo. +) + +// Bond represents a chemical, covalent bond. +type Bond struct { + Index int + At1 *Atom + At2 *Atom + Dist float64 + Energy float64 //One might prefer to use energy insteaf of order. + //NOTE + //I'm not sure if I leave just the order and let the user ""Abuse"" that field for energy + //or anything else they want, or if I keep this extra field. + Order float64 //Order 0 means undetermined +} + +// Copies B into the receiver +func (b *Bond) Copy(B *Bond) { + b.Index = B.Index + b.At1 = B.At1 + b.At2 = B.At2 + b.Dist = B.Dist + b.Energy = B.Energy //One might prefer to use energy insteaf of order. + //NOTE + //I'm not sure if I leave just the order and let the user ""Abuse"" that field for energy + //or anything else they want, or if I keep this extra field. + b.Order = B.Order //Order 0 means undetermined +} + +// Cross returns the atom bonded to the origin atom +// bond in the receiver. +func (B *Bond) Cross(origin *Atom) *Atom { + if origin.index == B.At1.index { + return B.At2 + } + if origin.index == B.At2.index { + return B.At1 + } + panic(""Trying to cross a bond: The origin atom given is not present in the bond!"") //I think this got to be a programming error, so a panic is warranted. + +} + +// Remove removes the receiver bond from the the Bond slices in the corresponding atoms +func (b *Bond) Remove() error { + lenb1 := len(b.At1.Bonds) + lenb2 := len(b.At2.Bonds) + b.At1.Bonds = takefromslice(b.At1.Bonds, b.Index) + b.At2.Bonds = takefromslice(b.At2.Bonds, b.Index) + err := new(CError) + errs := 0 + err.msg = fmt.Sprintf(""Failed to remove bond Index:%d"", b.Index) + if len(b.At1.Bonds) == lenb1 { + err.msg = err.msg + fmt.Sprintf(""from atom. Index:%d"", b.At1.index) + err.Decorate(""RemoveBond"") + errs++ + } + if len(b.At2.Bonds) == lenb2 { + err := new(CError) + if errs > 0 { + err.msg = err.msg + "" and"" + } + err.msg = err.msg + fmt.Sprintf(""from atom. Index:%d"", b.At2.index) + err.Decorate(""RemoveBond"") + errs++ + } + if errs > 0 { + return err + } + return nil +} + +// returns a new *Bond slice with the element id removed +func takefromslice(bonds []*Bond, id int) []*Bond { + newb := make([]*Bond, len(bonds)-1) + for _, v := range bonds { + if v.Index != id { + newb = append(newb, v) + } + } + return newb +} + +// BondedOptions contains options for the BondePaths function +type BondedOptions struct { + OnlyShortest bool //Only return the shortest path between the atoms + F func(*Bond) bool //Only bonds for which this function returns true are considered + path []int // +} + +func DefaultBondedOptions() *BondedOptions { + return &BondedOptions{OnlyShortest: false, F: func(*Bond) bool { return true }} +} + +/****** +**** The following is commented out and excluded from the API, as I don't think it is needed. +**** In any case, adding this function, or any other, wouldn't break the API, so it's best +**** to exclude when in doubt. Of course this is in itself an API break, but the bond functionality +**** is still very new, so the break is very unlikely to affect anyone. +//SetAlreadyWalkedPath set the unexported field ""path"" in BondedOptions to p. +//the path field represents the already-walked path, so you almost never +//want to set it. The exception is definidng your own function that calls +//BondedPath recursively, as I do here. This method was added to allow +//for such use. +func (B *BondedOptions)SetAlreadyWalkedPath(p []int){ + B.path=p +} +******/ + +/* +// BondedPaths determines the paths between at and the atom with +// Index targetIndex. It returns a slice of slices of int, where each sub-slice contains all the atoms +// in between at and the target (including the index of at) +// If there is no valid path, it returns nil. +// In the options structure BondeOption, OnlyShortest set to true causes only the shortest of the found paths to +// be returned. All atoms in the molecule need to have the ""index"" field filled. +// If the targetIndex is the same as that of the current atom, and the path is not given, nil, or +// of len 0, the function will search for a cyclic path back to the initial atom. +// if onlyshortest is true, only the shortest path will be returned (the other elements of the slice will be nil) +// This can be useful if you want to save memory on a very intrincate molecule. +func BondedPaths(at *Atom, targetIndex int, options ...*BondedOptions) [][]int { + if len(options) == 0 { + options = []*BondedOptions{{OnlyShortest: false, path: nil}} + } + onlyshortest := options[0].OnlyShortest + path := [][]int{options[0].path} + //I am not completely sure about this function signature. It is a candidate for API change. + if len(path) > 0 && len(path[0]) > 1 && path[0][len(path[0])-2] == at.index { + return nil //We are back to the atom we just had visited, not a valid path. We have to check this before checking if we completed the ""quest"" + //or, by just going back via the same bond, it would seem like we are at the finishing line. + } + if len(path) == 0 { + path = append(path, []int{at.index}) + } else if path[0] == nil { + path[0] = []int{at.index} + + } else { + path[0] = append(path[0], at.index) + } + + if at.index == targetIndex && len(path[0]) > 1 { + return [][]int{path[0]} //We arrived! Note that if the starting node is the same as the target, we will + //only settle for a ""cyclic"" path that goes through at least another atom (really, at least 2 more atoms). + // We will not immediately return success on the first node. This is enforced by the len(path[0]>1 condition. + } + //Here we check that we are not back to an atom we previously visited. This checks for loops, and has to be performed + //after we check if we got to the goal, since the goal could be the same starting atom (if we look for a cyclic path). + if len(path[0]) > 1 && isInInt(path[0][:len(path[0])-1], at.index) { + return nil //means we took the same bond back to the previous node, or got trapped in a loop. not a valid path. + } + if len(at.Bonds) <= 1 { + return nil //means that we hit an end of the road. There is only one bond in the atom (i.e. the one leading to the previous node) + } + rets := make([][]int, 0, len(at.Bonds)) + for _, v := range at.Bonds { + path2 := make([]int, len(path[0])) + copy(path2, path[0]) + rets = append(rets, BondedPaths(v.Cross(at), targetIndex, &BondedOptions{OnlyShortest: onlyshortest, path: path2})...) //scary stuff + } + rets2 := make([][]int, 0, len(at.Bonds)) + for _, v := range rets { + if v != nil { + rets2 = append(rets2, v) + } + } + if len(rets2) == 0 { + return nil + } + sort.Slice(rets2, func(i, j int) bool { return len(rets2[i]) < len(rets2[j]) }) + if onlyshortest { + return [][]int{rets2[0]} + } + return rets2 + +} +*/ + +// BondedPaths determines the paths between at and the atom with +// Index targetIndex. It returns a slice of slices of int, where each sub-slice contains all the atoms +// in between at and the target (including the index of at) +// If there is no valid path, it returns nil. +// In the options structure BondeOption, OnlyShortest set to true causes only the shortest of the found paths to +// be returned. All atoms in the molecule need to have the ""index"" field filled. +// If the targetIndex is the same as that of the current atom, and the path is not given, nil, or +// of len 0, the function will search for a cyclic path back to the initial atom. +// if onlyshortest is true, only the shortest path will be returned (the other elements of the slice will be nil) +// This can be useful if you want to save memory on a very intrincate molecule. +// Only bonds for which the function in options returns true are considered for the search (in the default options, +// this function always returns true, so all bonds are consiered). +func BondedPaths(at *Atom, targetIndex int, options ...*BondedOptions) [][]int { + if len(options) == 0 { + options = append(options, DefaultBondedOptions()) + } + onlyshortest := options[0].OnlyShortest + path := [][]int{options[0].path} + if len(path) > 0 && len(path[0]) > 1 && path[0][len(path[0])-2] == at.index { + return nil //We are back to the atom we just had visited, not a valid path. We have to check this before checking if we completed the ""quest"" + //or, by just going back via the same bond, it would seem like we are at the finishing line. + //This really shouldn't happen, but I'm paranoid. + } + if len(path) == 0 { + path = append(path, []int{at.index}) + } else if path[0] == nil { + path[0] = []int{at.index} + + } else { + path[0] = append(path[0], at.index) + } + + if at.index == targetIndex && len(path[0]) > 1 { + return [][]int{path[0]} //We arrived! Note that if the starting node is the same as the target, we will + //only settle for a ""cyclic"" path that goes through at least another atom (really, at least 2 more atoms). + // We will not immediately return success on the first node. This is enforced by the len(path[0]>1 condition. + } + //Here we check that we are not back to an atom we previously visited. This checks for loops, and has to be performed + //after we check if we got to the goal, since the goal could be the same starting atom (if we look for a cyclic path). + if len(path[0]) > 1 && isInInt(path[0][:len(path[0])-1], at.index) { + return nil //means we took the same bond back to the previous node, or got trapped in a loop. not a valid path. + } + if len(at.Bonds) <= 1 { + return nil //means that we hit an end of the road. There is only one bond in the atom (i.e. the one leading to the previous node) + } + rets := make([][]int, 0, len(at.Bonds)) + for _, v := range at.Bonds { + if !options[0].F(v) { + continue + } + path2 := make([]int, len(path[0])) + copy(path2, path[0]) + rets = append(rets, BondedPaths(v.Cross(at), targetIndex, &BondedOptions{OnlyShortest: onlyshortest, path: path2, F: options[0].F})...) //scary stuff + } + rets2 := make([][]int, 0, len(at.Bonds)) + for _, v := range rets { + if v != nil { + rets2 = append(rets2, v) + } + } + if len(rets2) == 0 { + return nil + } + sort.Slice(rets2, func(i, j int) bool { return len(rets2[i]) < len(rets2[j]) }) + if onlyshortest { + return [][]int{rets2[0]} + } + return rets2 + +} + +// Ring represents a molecular cycle. +type Ring struct { + Atoms []int + planarity float64 +} + +// Contains returns true or false depending on whether +// the atom with the given index is part of the ring +func (R *Ring) Contains(index int) bool { + return isInInt(R.Atoms, index) +} + +func (R *Ring) IsIn(index int) bool { + return R.Contains(index) +} + +// Size returns the number of atoms in the ring +func (R *Ring) Size() int { + return len(R.Atoms) +} + +// Planarity returns the planarity percentage of the receiver ring +// coords is the set of coordinates for the _entire_ molecule of which +// the ring is part. Planarity does not check that coords indeed corresponds +// to the correct molecule, so, doing so is the user's responsibility. +func (R *Ring) Planarity(coord *v3.Matrix, temp ...*v3.Matrix) float64 { + if R.planarity != 0 { + return R.planarity + } + var c *v3.Matrix + if len(temp) > 0 && temp[0] != nil && temp[0].Len() == len(R.Atoms) { + c = temp[0] + } else { + c = v3.Zeros(len(R.Atoms)) + } + c.SomeVecs(coord, R.Atoms) + _, plan, err := EasyShape(c, 0.01) + if err != nil { + R.planarity = -1 + return -1 + } + R.planarity = plan + return plan + +} + +// AddHs Adds to the ring the H atoms bonded to its members +// mol is the _entire_ molecule of which the receiver ring is part. +// It will panic if an atom of the ring is not +// found in mol, or is not bonded to anything +func (R *Ring) AddHs(mol Atomer) { + newind := make([]int, 0, 6) + for _, v := range R.Atoms { + at := mol.Atom(v) //this can panic if you give the wrong mol object + for _, w := range at.Bonds { + at2 := w.Cross(at) + if at2.Symbol == ""H"" { + newind = append(newind, at2.index) + } + + } + } + R.Atoms = append(R.Atoms, newind...) +} + +// API CHANGE +// InWhichRing returns the indexes of all rings top which at belongs +// or nil if it doesn't belong to any ring. +func InWhichRing(at *Atom, rings []*Ring) []int { + if len(rings) == 0 { + return nil + } + var ret []int + for i, v := range rings { + if v.IsIn(at.index) { + ret = append(ret, i) + } + } + return ret + +} + +type RingOptions struct { + AddHs bool + MinPlanarity float64 + FusedRings bool + MaxRing int //maximum ring size + Coords *v3.Matrix + F func(*Bond) bool +} + +func DefaultRingOptions() *RingOptions { + f := func(*Bond) bool { return true } + return &RingOptions{MinPlanarity: -1, Coords: nil, AddHs: false, MaxRing: 6, F: f} + +} + +// Identifies and returns all rings in mol, by +// searching for cyclic paths. if at least 1 element is given for addHs +// and the first element of those give is true, the Hs bound to the atoms in the rings +// will also be added to the ring. +func FindRings(mol Atomer, Opts ...*RingOptions) []*Ring { + var o *RingOptions + if len(Opts) > 0 { + o = Opts[0] + } else { + o = DefaultRingOptions() + } + L := mol.Len() + var rings []*Ring + for i := 0; i < L; i++ { + at := mol.Atom(i) + //Here I nullified the requirement that at is not in a previous ring, if fused rings are wanted. + //This is because, say you have 2 fused rings, A and B, with the 'metaring', the fusing of both, named C. + //you detect first A and its 'metaring' C, but then you don't detect B as all its atoms are part of C, + //and thys gets excluded byt the (InWhichRing(at, rings) == nil) condition + if o.FusedRings || (InWhichRing(at, rings) == nil) { + paths := BondedPaths(at, at.index, &BondedOptions{OnlyShortest: !o.FusedRings, F: o.F}) + if len(paths) == 0 || (len(paths[0][1:]) > o.MaxRing && o.MaxRing > 0) { + continue + } + + //NOTE: I added an additional loop here + //to allow for 'fused rings' i.e. longer paths connecting the same atoms. + //it should only matter if o.FusedRings is set to true, as, otherwise, len(paths)==1 + for _, p := range paths { + r := &Ring{Atoms: p[1:]} //NOTE: it was originally paths[0], so, if something breaks + //look here. I think the previous behavior was buggy, since the first atom of the ring will be repeated + //as the last atom, giving a wrong number for the ring's length. + if o.Coords == nil || o.MinPlanarity < 0 || r.Planarity(o.Coords) > o.MinPlanarity { + if o.AddHs { + r.AddHs(mol) + } + rings = append(rings, r) + } + } + } + + } + + return removeRepeatedRings(rings) +} + +// 2 rings are equal if they contain the same atoms, whether in the same +// order, or not. +func ringIsEqual(a, b *Ring) bool { + if len(a.Atoms) != len(b.Atoms) { + return false + } + hasall := true + for _, v := range a.Atoms { + if !slices.Contains(b.Atoms, v) { + hasall = false + break + } + } + return hasall +} + +func removeRepeatedRings(set []*Ring) []*Ring { + ret := make([]*Ring, 0, 1) + for _, v := range set { + rep := false + for _, w := range ret { + if ringIsEqual(v, w) { + rep = true + break + } + } + if !rep { + ret = append(ret, v) + } + } + return ret +} +","Go" +"Computational Biochemistry","rmera/gochem","conversion.go",".go","1440","53","/* + * conversion.go, part of gochem. + * + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + */ + +package chem + +//Useful conversion factors and other constants + +// Conversions +const ( + Deg2Rad = 0.0174533 + Rad2Deg = 1 / Deg2Rad + H2Kcal = 627.509 //HArtree 2 Kcal/mol + Kcal2H = 1 / H2Kcal + Kcal2KJ = 4.184 + KJ2Kcal = 1 / Kcal2KJ + A2Bohr = 1.889725989 + Bohr2A = 1 / A2Bohr + EV2Kcal = 23.061 + Kcal2EV = 1 / EV2Kcal + A2NM = 0.1 //It's more for documentation, really. + NM2A = 10 +) + +// Others +const ( + CHDist = 1.098 //C(sp3)--H distance in A + KBkJ = 1.380649e-26 // Boltzmann constant kJ/K + KB = KBkJ * KJ2Kcal + RkJ = 8.31446261815324e-3 // kJ/(K*mol) + NA = 6.02214076e+23 + R = RkJ * KJ2Kcal //1.9872042586408e-3 //kcal/mol +) +","Go" +"Computational Biochemistry","rmera/gochem","pdbx.go",".go","13863","484","/* + * mmcif.go, part of gochem. + * + * + * Copyright 2024 rmeraaatacademicosdotutadotcl + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * goChem is developed at Universidad de Tarapaca (UTA) + * + * + */ + +package chem + +import ( + ""bufio"" + ""fmt"" + ""io"" + ""log"" + ""os"" + ""strconv"" + ""strings"" + + v3 ""github.com/rmera/gochem/v3"" +) + +var tl func(string) string = strings.ToLower + +// PDBRRead reads a pdb file from an io.Reader. Returns a Molecule. If there is one frame in the PDB +// the coordinates array will be of lenght 1. It also returns an error which is not +// really well set up right now. +// read_additional is now ""deprecated"", it will be set to true regardless. I have made it into +func PDBxRead(pdb io.Reader) (*Molecule, error) { + bufiopdb := bufio.NewReader(pdb) + mol, err := pdbBufIORead(bufiopdb) + return mol, errDecorate(err, ""PDBReaderREad"") +} + +// PDBFileRead reads a pdb file from an io.Reader. Returns a Molecule. If there is one frame in the PDB +// the coordinates array will be of lenght 1. It also returns an error which is not +// really well set up right now. read_additional is now deprecated. The reader will just read +func PDBxFileRead(pdbname string) (*Molecule, error) { + pdbxfile, err := os.Open(pdbname) + if err != nil { + //fmt.Println(""Unable to open file!!"") + return nil, err + } + defer pdbxfile.Close() + pdb := bufio.NewReader(pdbxfile) + mol, err := pdbxBufIORead(pdb) + return mol, err +} + +func pdbxNextLoop(pdb *bufio.Reader) (*bufio.Reader, string, error) { + for { + line, err := pdb.ReadString('\n') + if err != nil { + return pdb, line, err + } + if strings.HasPrefix(tl(line), ""loop_"") { + return pdb, line, nil + } + } + +} + +type pdbxmap map[string]int + +// adds i to the map[string] entry, if it exists. If not, +// does nothing. Returns the map. +func (m pdbxmap) add(s string, i int) pdbxmap { + s = strings.TrimSpace(s) + s = strings.Replace(s, ""\n"", """", -1) + if _, ok := m[s]; ok { + m[s] = i + } + return m +} + +// returns the integaer corresponding to the given string in the map +// or -1 if the string is not a key in the map. +func (m pdbxmap) get(s string) int { + if i, ok := m[s]; ok { + return i + } + return -1 +} + +func pdbxFillAtom(at *Atom, data []string, m pdbxmap) error { + do := func(at *Atom, s string, data []string, m pdbxmap, f func(*Atom, string) error) error { + s = strings.TrimSpace(s) //just in case I make a mistake + // fmt.Println(data, m, s) + k := m.get(s) + if k >= 0 { + if k >= len(data) { + return fmt.Errorf(""Index out of range: %d, %v"", k, data) + } + // println(""DATA"", k, data[k]) ///////////////////// + err := f(at, data[k]) + return err + } + return nil + } + //We start with the simpler string fields + //symbol + f := func(a *Atom, s string) error { + a.Symbol = s + return nil + } + do(at, ""_atom_site.type_symbol"", data, m, f) + //name + f = func(a *Atom, s string) error { + a.Name = s + return nil + } + //println(""NAME"", at.Name) ///////////////////////// + do(at, ""_atom_site.auth_atom_id"", data, m, f) + if at.Symbol == """" { + at.Symbol, _ = symbolFromName(at.Name) + } + //molname + f = func(a *Atom, s string) error { + a.MolName = s + return nil + } + do(at, ""_atom_site.auth_comp_id"", data, m, f) + at.MolName1 = three2OneLetter[at.MolName] + + //char16 + f = func(a *Atom, s string) error { + a.Char16 = s[0] + return nil + } + do(at, ""_atom_site.label_alt_id"", data, m, f) + //chain + f = func(a *Atom, s string) error { + a.Chain = s + return nil + } + do(at, ""_atom_site.auth_asym_id"", data, m, f) + + //Now the integer fields + //ID + f = func(a *Atom, s string) error { + n, err := strconv.Atoi(s) + if err != nil { + return fmt.Errorf(""pdbxFillAtom: Couldn't parse ID from %s: %w"", s, err) + } + a.ID = n + return nil + } + err := do(at, ""_atom_site.id"", data, m, f) + if err != nil { + return err + } + //molID + f = func(a *Atom, s string) error { + n, err := strconv.Atoi(s) + if err != nil { + return fmt.Errorf(""pdbxFillAtom: Couldn't parse MolID from %s: %w"", s, err) + } + a.MolID = n + return nil + } + err = do(at, ""_atom_site.auth_seq_id"", data, m, f) + if err != nil { + return err + } + //Now the floating point fields, except for the coordinates and b-factors + //occupancy + f = func(a *Atom, s string) error { + n, err := strconv.ParseFloat(s, 64) + if err != nil { + return fmt.Errorf(""pdbxFillAtom: Couldn't parse Occupancy from %s: %w"", s, err) + } + a.Occupancy = n + return nil + } + err = do(at, ""_atom_site.occupancy"", data, m, f) + if err != nil { + return err + } + //Charge, but we won't do anything if we somehow can't read it. + f = func(a *Atom, s string) error { + n, err := strconv.ParseFloat(s, 64) + if err != nil { + return nil + } + a.Charge = n + return nil + } + do(at, ""_atom_site.pdbx_formal_charge "", data, m, f) + //And, finally, the boolean field + f = func(a *Atom, s string) error { + if s != ""ATOM"" { + a.Het = true + } else { + a.Het = false + } + return nil + } + do(at, ""_atom_site.group_pdb"", data, m, f) + return nil +} + +func pdbxFillBfac(data []string, bf []float64, m pdbxmap) ([]float64, error) { + v := ""_atom_site.b_iso_or_equiv"" + if m[v] >= 0 && m[v] < len(data) { + fl, err := strconv.ParseFloat(data[m[v]], 64) + if err != nil { + return bf, fmt.Errorf(""pdbxFillBfac: Couldn't parse bfactor from %s: %w"", data[m[v]], err) + } + bf = append(bf, fl) + } else { + return bf, fmt.Errorf(""pdbxFillBfac: Field %s not present in data %v"", v, data) + } + return bf, nil +} + +func pdbxFillCoords(data []string, coord []float64, m pdbxmap) ([]float64, error) { + c := []string{""_atom_site.cartn_x"", ""_atom_site.cartn_y"", ""_atom_site.cartn_z""} + for j, v := range c { + if m[v] >= 0 && m[v] < len(data) { + fl, err := strconv.ParseFloat(data[m[v]], 64) + if err != nil { + return coord, fmt.Errorf(""pdbxFillCoord: Couldn't parse %d cartesian coordinate from %s: %w"", j, data[m[v]], err) + } + coord = append(coord, fl) + } else { + return coord, fmt.Errorf(""pdbxFillCoord: Field %s not present in data %v"", v, data) + } + } + return coord, nil +} + +func pdbxBufIORead(pdb *bufio.Reader) (*Molecule, error) { + m := pdbxmap(ma) + molecule := make([]*Atom, 0) + coords := make([][]float64, 1, 1) + coords[0] = make([]float64, 0, 3) + bfactors := make([][]float64, 1, 1) + bfactors[0] = make([]float64, 0) + currentmodel := 1 + var reading bool + var field int = 0 + var havebfactors bool = true + hp := strings.HasPrefix + trimall := func(s string) string { return strings.TrimSpace(strings.Replace(s, ""\n"", """", -1)) } + + for { + line, err := pdb.ReadString('\n') + if err != nil { + break + } + if hp(line, ""#"") || hp(line, "";"") || trimall(line) == """" { + continue + } + if !reading && strings.HasPrefix(tl(line), ""_atom_site"") { + reading = true + field = 0 + } + if !reading { + pdb, line, err = pdbxNextLoop(pdb) + if err != nil { + break + } + continue + } + if strings.HasPrefix(line, ""loop_"") { //new section + reading = false + continue + } + // We shouldn't be here if reading is false + if strings.HasPrefix(line, ""_"") { + if !hp(line, ""_atom_site"") || hp(line, ""_atom_site_anisotrop"") { //a new section started + reading = false + continue + } + // fmt.Println(""This is reading!!"", line, field) /////////// + + m.add(tl(line), field) + field++ + } else { + //Here we should be reading the content lines. + //we first see if we have a model number, and whether + fields := strings.Fields(line) + modkey := m.get(""_atom_site.pdbx_pdb_model_num"") + if modkey >= 0 { + if modkey >= len(fields) { + return nil, fmt.Errorf(""pdbxBufIORead: Model field out of range: %d (index) %d (len), %v"", modkey, len(fields), fields) + } + mod := fields[modkey] + model, err := strconv.Atoi(mod) + if err != nil { + return nil, fmt.Errorf(""pdbxBufIORead: Couldn't parse model number from %s: %w"", mod, err) + } + if model > currentmodel { + nats := len(coords[len(coords)-1]) + coords = append(coords, make([]float64, 0, nats)) + bfactors = append(bfactors, make([]float64, 0, nats)) + currentmodel = model + } + } + //we don't read the atoms again for the next models. + if currentmodel == 1 { + at := new(Atom) + err := pdbxFillAtom(at, fields, m) + if err != nil { + return nil, fmt.Errorf(""pdbxBufIORead: Couldn't read atom %d: %w"", len(molecule)+1, err) + } + molecule = append(molecule, at) + } + //The following we always try to read. + c := len(coords) - 1 + b := len(bfactors) - 1 //c and b should be equal, but not sure if its critical enough to check it. + coords[c], err = pdbxFillCoords(fields, coords[c], m) + if err != nil { + return nil, fmt.Errorf(""pdbxBufIORead: Couldn't read %d th coordinates for frame %d: %w"", len(coords[c])+1, currentmodel, err) + } + bfactors[b], err = pdbxFillBfac(fields, bfactors[b], m) + if err != nil && havebfactors { + //I might remove this, but not before more testing. + //It can very well be that the PDB just doesn't contain b-factors. + log.Printf(""pdbxBufIORead: Couldn't read %d th bfactors for frame %d: %v"", len(bfactors[b])+1, currentmodel, err) + havebfactors = false + + } + } + + } + top := NewTopology(0, 1, molecule) + var err error + frames := len(coords) + mcoords := make([]*v3.Matrix, frames, frames) //Final thing to return + for i := 0; i < frames; i++ { + mcoords[i], err = v3.NewMatrix(coords[i]) + if err != nil { + return nil, fmt.Errorf(""pdbBufIORead: Couldn't transfor coordinates from frame %d: %w"", i, err) + } + } + //if something happened during the process + if err != nil { + return nil, fmt.Errorf(""pdbBufIORead: %w"", err) + + } + if !havebfactors { + bfactors = nil + } + returned, err := NewMolecule(mcoords, top, bfactors) + if err != nil { + return returned, fmt.Errorf(""pdbBufIORead: %w"", err) + } + return returned, nil +} + +func PDBxFileWrite(name string, coords []*v3.Matrix, mol Atomer, bfact [][]float64) error { + pdb, err := os.Create(name) + if err != nil { + return fmt.Errorf(""PDBxFileWrite: %w"", err) + } + defer pdb.Close() + return PDBxWrite(pdb, coords, mol, bfact, false, strings.Replace(name, "".pdb"", """", -1)) +} + +func PDBxCompactFileWrite(name string, coords []*v3.Matrix, mol Atomer, bfact [][]float64) error { + pdb, err := os.Create(name) + if err != nil { + return fmt.Errorf(""PDBxFileWrite: %w"", err) + } + defer pdb.Close() + return PDBxWrite(pdb, coords, mol, bfact, true, strings.Replace(name, "".pdb"", """", -1)) +} + +func PDBxWrite(out io.Writer, coords []*v3.Matrix, mol Atomer, bfact [][]float64, save bool, name ...string) error { + n := ""gochem"" + if len(name) > 0 && name[0] != """" { + n = name[0] + } + out.Write([]byte(fmt.Sprintf(""data_%s\n#\n"", n))) + for i, v := range coords { + cr, _ := v.Dims() + if cr != mol.Len() { + return fmt.Errorf(""pdbxWrite: Reference (%d) and Coords (%d) don't have the same number of atoms"", mol.Len(), cr) + } + model := i + 1 + if model == 1 || save { + out.Write([]byte(""loop_\n"")) + } + if model == 1 { + out.Write([]byte(""_atom_site.type_symbol\n"")) + out.Write([]byte(""_atom_site.auth_atom_id\n"")) + out.Write([]byte(""_atom_site.auth_comp_id\n"")) + out.Write([]byte(""_atom_site.label_alt_id\n"")) + out.Write([]byte(""_atom_site.auth_asym_id\n"")) + out.Write([]byte(""_atom_site.id\n"")) + out.Write([]byte(""_atom_site.auth_seq_id\n"")) + out.Write([]byte(""_atom_site.occupancy\n"")) + out.Write([]byte(""_atom_site.pdbx_formal_charge\n"")) + out.Write([]byte(""_atom_site.group_PDB\n"")) + } + if model == 1 || save { + out.Write([]byte(""_atom_site.pdbx_PDB_model_num\n"")) + out.Write([]byte(""_atom_site.Cartn_x\n_atom_site.Cartn_y\n_atom_site.Cartn_z\n"")) + if len(bfact) > i && len(bfact[i]) > mol.Len() { + out.Write([]byte(""_atom_site.B_iso_or_equiv\n"")) + } + } + + for j := 0; j < mol.Len(); j++ { + line := """" + if model == 1 || !save { + a := mol.Atom(j) + het := ""ATOM"" + if a.Het { + het = ""HETATM"" + } + c16 := checkChar16(a.Char16) + line = fmt.Sprintf(""%s %s %s %s %s %d %d %4.2f %3.1f %s "", a.Symbol, a.Name, a.MolName, string(c16), a.Chain, a.ID, a.MolID, a.Occupancy, a.Charge, het) + } + line += fmt.Sprintf(""%d %5.3f %5.3f %5.3f "", model, v.At(j, 0), v.At(j, 1), v.At(j, 2)) + if len(bfact) > i && len(bfact[i]) > mol.Len() { + line += fmt.Sprintf(""%5.3f\n"", bfact[i][j]) + } else { + line += fmt.Sprintf(""\n"") + + } + out.Write([]byte(line)) + } + if save { + out.Write([]byte(""#\n"")) + } + } + out.Write([]byte(""#\n\n"")) + return nil + +} + +func checkChar16(c byte) byte { + valid := ""ABCDEFGHIJKLMNOPQRSTUVWXYZ"" + for i := range valid { + if c == valid[i] { + return c + } + } + return '?' +} + +var ma map[string]int = map[string]int{ + ""_atom_site.group_pdb"": -1, + ""_atom_site.id"": -1, + ""_atom_site.type_symbol"": -1, + ""_atom_site.label_atom_id"": -1, + ""_atom_site.label_alt_id"": -1, + ""_atom_site.label_comp_id"": -1, + ""_atom_site.label_asym_id"": -1, + ""_atom_site.label_entity_id"": -1, + ""_atom_site.label_seq_id"": -1, + ""_atom_site.pdbx_pdb_ins_code"": -1, + ""_atom_site.cartn_x"": -1, + ""_atom_site.cartn_y"": -1, + ""_atom_site.cartn_z"": -1, + ""_atom_site.occupancy"": -1, + ""_atom_site.b_iso_or_equiv"": -1, + ""_atom_site.pdbx_formal_charge"": -1, + ""_atom_site.auth_seq_id"": -1, + ""_atom_site.auth_comp_id"": -1, + ""_atom_site.auth_asym_id"": -1, + ""_atom_site.auth_atom_id"": -1, + ""_atom_site.pdbx_pdb_model_num"": -1, +} +","Go" +"Computational Biochemistry","rmera/gochem","gochem_test.go",".go","19556","636","/* + * gochem_test.go + * + * Copyright 2013 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + +package chem + +import ( + ""fmt"" + ""os"" + ""runtime"" + ""testing"" + + v3 ""github.com/rmera/gochem/v3"" + ""gonum.org/v1/gonum/mat"" +) + +//import ""runtime"" + +func TestPDBxIO(Te *testing.T) { + mol, err := PDBxFileRead(""test/2c9v.cif"") + if err != nil { + Te.Error(err) + } + fmt.Println("":O"", mol.Len(), len(mol.Coords)) + fmt.Println(mol.Atom(3), mol.Coords[0].VecView(3)) + c := v3.Zeros(mol.Len()) + c.Copy(mol.Coords[0]) + mol.Coords = append(mol.Coords, c) //simulating 2 states + err = PDBxFileWrite(""test/test.cif"", mol.Coords, mol, mol.Bfactors) + if err != nil { + Te.Error(err) + } + mol, err = PDBxFileRead(""test/test.cif"") + if err != nil { + Te.Error(err) + } + fmt.Println("":O"", mol.Len(), len(mol.Coords)) + fmt.Println(mol.Atom(3), mol.Coords[0].VecView(3)) + err = PDBxCompactFileWrite(""test/testcompact.cif"", mol.Coords, mol, mol.Bfactors) + if err != nil { + Te.Error(err) + } + mol, err = PDBxFileRead(""test/testcompact.cif"") + if err != nil { + Te.Error(err) + } + fmt.Println(""Compact!"", mol.Len(), len(mol.Coords)) + fmt.Println(mol.Atom(3), mol.Coords[0].VecView(3)) + +} + +func TestSymbolError(Te *testing.T) { + _, err := PDBFileRead(""test/SymbolErrorTest.pdb"") + if err != nil { + Te.Error(err) + } +} + +func TestGROIO(Te *testing.T) { + mol, err := GroFileRead(""test/test.gro"") + if err != nil { + Te.Error(err) + } + fmt.Println(""NO WEI"", mol.Len(), len(mol.Coords)) + fmt.Println(mol.Atom(3), mol.Coords[0].VecView(3)) + err = PDBFileWrite(""test/testgro.pdb"", mol.Coords[0], mol, nil) + if err != nil { + Te.Error(err) + } + err = GroFileWrite(""test/testgro.gro"", mol.Coords, mol) + if err != nil { + Te.Error(err) + } + +} + +// TestMultiXYZ tests that multi-XYZ files are opened and read correctly. +func TestXYZIO(Te *testing.T) { + mol, err := XYZFileRead(""test/sample.xyz"") + if err != nil { + fmt.Println(""There was an error!"", err.Error()) + Te.Error(err) + } + fmt.Println(""XYZ read!"") + XYZFileWrite(""test/sampleFirst.xyz"", mol.Coords[0], mol) +} + +func TestPDBIO(Te *testing.T) { + mol, err := PDBFileRead(""test/2c9v.pdb"", true) + if err != nil { + Te.Error(err) + } + fmt.Println(""NO WEI"") + err = PDBFileWrite(""test/2c9vIO.pdb"", mol.Coords[0], mol, mol.Bfactors[0]) + if err != nil { + Te.Error(err) + } + //for the 3 residue I should get -131.99, 152.49. +} + +// TestChangeAxis reads the PDB 2c9v.pdb from the test directory, collects +// The CA and CB of residue D124 of the chain A, and uses Clifford algebra to rotate the +// whole molecule such as the vector defined by these 2 atoms is +// aligned with the Z axis. The new molecule is written +// as 2c9v_aligned.pdb to the test folder. +func TestChangeAxis(Te *testing.T) { + //runtime.GOMAXPROCS(2) /////////////////////////// + mol, err := PDBFileRead(""test/2c9v.pdb"", true) + if err != nil { + Te.Error(err) + } + PDBFileWrite(""test/2c9v-Readtest.pdb"", mol.Coords[0], mol, nil) + //The selection thing + orient_atoms := [2]int{0, 0} + for index := 0; index < mol.Len(); index++ { + atom := mol.Atom(index) + if atom.Chain == ""A"" && atom.MolID == 124 { + if atom.Name == ""CA"" { + orient_atoms[0] = index + } else if atom.Name == ""CB"" { + orient_atoms[1] = index + } + } + } + //Get the axis of rotation + //ov1:=mol.Coord(orient_atoms[0], 0) + ov2 := mol.Coord(orient_atoms[1], 0) + //now we center the thing in the beta carbon of D124 + mol.Coords[0].SubVec(mol.Coords[0], ov2) + PDBFileWrite(""test/2c9v-translated.pdb"", mol.Coords[0], mol, nil) + //Now the rotation + ov1 := mol.Coord(orient_atoms[0], 0) //make sure we have the correct versions + ov2 = mol.Coord(orient_atoms[1], 0) //same + orient := v3.Zeros(ov2.NVecs()) + orient.Sub(ov2, ov1) + // PDBWrite(mol,""test/2c9v-124centered.pdb"") + Z, _ := v3.NewMatrix([]float64{0, 0, 1}) + axis := cross(orient, Z) + angle := Angle(orient, Z) + oldcoords := v3.Zeros(mol.Coords[0].NVecs()) + oldcoords.Copy(mol.Coords[0]) + mol.Coords[0] = Rotate(oldcoords, mol.Coords[0], axis, angle) + if err != nil { + Te.Error(err) + } + PDBFileWrite(""test/2c9v-aligned.pdb"", mol.Coords[0], mol, nil) + fmt.Println(""bench1"") +} + +func TestMolidNameChain2Index(Te *testing.T) { + //runtime.GOMAXPROCS(2) /////////////////////////// + mol, err := PDBFileRead(""test/2c9v.pdb"", true) + if err != nil { + Te.Error(err) + } + index, err := MolIDNameChain2Index(mol, 46, ""ND1"", ""A"") + if err != nil { + Te.Error(err) + } + fmt.Println(""this should print the index and the Atom object for H46, chain A: "", index, mol.Atom(index)) + +} + +// TestOldChangeAxis reads the PDB 2c9v.pdb from the test directory, collects +// The CA and CB of residue D124 of the chain A, and rotates the +// whole molecule such as the vector defined by these 2 atoms is +// aligned with the Z axis. The new molecule is written +// as 2c9v_aligned.pdb to the test folder. +func TestOldChangeAxis(Te *testing.T) { + viej, _ := os.Open(""test/2c9v.pdb"") + mol, err := PDBRead(viej, true) + if err != nil { + Te.Error(err) + } + orient_atoms := [2]int{0, 0} + for index := 0; index < mol.Len(); index++ { + atom := mol.Atom(index) + if atom.Chain == ""A"" && atom.MolID == 124 { + if atom.Name == ""CA"" { + orient_atoms[0] = index + } else if atom.Name == ""CB"" { + orient_atoms[1] = index + } + } + } + ov1 := mol.Coord(orient_atoms[0], 0) + ov2 := mol.Coord(orient_atoms[1], 0) + //now we center the thing in the beta carbon of D124 + mol.Coords[0].SubVec(mol.Coords[0], ov2) + //Now the rotation + ov1 = mol.Coord(orient_atoms[0], 0) //make sure we have the correct versions + ov2 = mol.Coord(orient_atoms[1], 0) //same + orient := v3.Zeros(ov2.NVecs()) + orient.Sub(ov2, ov1) + rotation := RotatorToNewZ(orient) + cr, cc := mol.Coords[0].Dims() + fmt.Println(""rotation: "", rotation, cr, cc) //////////////////////////////////////////////////////// + mol.Coords[0].Mul(mol.Coords[0], rotation) + // fmt.Println(orient_atoms[1], mol.Atom(orient_atoms[1]),mol.Atom(orient_atoms[0])) + if err != nil { + Te.Error(err) + } + PDBFileWrite(""test/2c9v-old-aligned.pdb"", mol.Coords[0], mol, nil) + fmt.Println(""bench2"") +} + +// Aligns the main plane of a molecule with the XY-plane. +// Here XYZRead and XYZWrite are tested +func TestPutInXYPlane(Te *testing.T) { + myxyz, _ := os.Open(""test/sample_plane.xyz"") + mol, err := XYZRead(myxyz) + if err != nil { + Te.Error(err) + } + indexes := []int{0, 1, 2, 3, 23, 22, 21, 20, 25, 44, 39, 40, 41, 42, 61, 60, 59, 58, 63, 5} + some := v3.Zeros(len(indexes)) + some.SomeVecs(mol.Coords[0], indexes) + //for most rotation things it is good to have the molecule centered on its mean. + mol.Coords[0], _, _ = MassCenter(mol.Coords[0], some, nil) + //The test molecule is not completely planar so we use a subset of atoms that are contained in a plane + //These are the atoms given in the indexes slice. + some.SomeVecs(mol.Coords[0], indexes) + //The strategy is: Take the normal to the plane of the molecule (os molecular subset), and rotate it until it matches the Z-axis + //This will mean that the plane of the molecule will now match the XY-plane. + best, err := BestPlane(some, nil) + if err != nil { + err2 := err.(Error) + fmt.Println(err2.Decorate("""")) + Te.Errorf(err.Error()) + // panic(err.Error()) + } + z, _ := v3.NewMatrix([]float64{0, 0, 1}) + zero, _ := v3.NewMatrix([]float64{0, 0, 0}) + fmt.Println(""Best Plane"", best, z) + axis := v3.Zeros(1) + axis.Cross(best, z) + fmt.Println(""axis"", axis) + //The main part of the program, where the rotation actually happens. Note that we rotate the whole + //molecule, not just the planar subset, this is only used to calculate the rotation angle. + // fmt.Println(""DATA"", mol.Coords[0], zero, axis, Angle(best, z)) + mol.Coords[0], err = RotateAbout(mol.Coords[0], zero, axis, Angle(best, z)) + if err != nil { + Te.Error(err) + } + // fmt.Println(""after!"", mol.Coords[0], err) + //Now we write the rotated result. + outxyz, _ := os.Create(""test/Rotated.xyz"") //This is the XYZWrite written file + XYZWrite(outxyz, mol.Coords[0], mol) +} + +func TestDelete(Te *testing.T) { + mol, err := XYZFileRead(""test/ethanol.xyz"") + if err != nil { + Te.Error(err) + } + fmt.Println(""Calling with 8"") + mol.Del(8) + XYZFileWrite(""test/ethanolDel8.xyz"", mol.Coords[0], mol) + mol2, err := XYZFileRead(""test/ethanol.xyz"") + if err != nil { + Te.Error(err) + } + fmt.Println(""Calling with 4"") + mol2.Del(4) + XYZFileWrite(""test/ethanolDel4.xyz"", mol2.Coords[0], mol2) + +} + +func TestWater(Te *testing.T) { + // runtime.GOMAXPROCS(2) /////////////////////////// + mol, err := XYZFileRead(""test/sample.xyz"") + if err != nil { + Te.Error(err) + } + for i := 0; i < 6; i++ { + s := new(Atom) + if i == 0 || i == 3 { + s.Symbol = ""O"" + } else { + s.Symbol = ""H"" + } + mol.AppendAtom(s) + } + mol.SetCharge(1) + mol.SetMulti(1) + c2 := v3.Zeros(mol.Len()) + v := v3.Zeros(6) + l, _ := mol.Coords[0].Dims() + fmt.Println(l, mol.Len()) + c2.Stack(mol.Coords[0], v) + mol.Coords[0] = c2 + c := mol.Coords[0].VecView(43) + h1 := mol.Coords[0].VecView(42) + coords := v3.Zeros(mol.Len()) + coords.Copy(mol.Coords[0]) + w1 := MakeWater(c, h1, 2, Deg2Rad*30, true) + w2 := MakeWater(c, h1, 2, Deg2Rad*-30, false) + tmp := v3.Zeros(6) + tmp.Stack(w1, w2) + fmt.Println(""tmp water"", w1, w2, tmp, c, h1) + coords.SetMatrix(mol.Len()-6, 0, tmp) + XYZFileWrite(""test/WithWater.xyz"", coords, mol) + fmt.Println(""Done TestWater"") +} + +func TesstFixPDB(Te *testing.T) { + mol, err := PDBFileRead(""test/2c9vbroken.pdb"", true) + if err != nil { + Te.Error(err) + } + FixNumbering(mol) + PDBFileWrite(""test/2c9vfixed.pdb"", mol.Coords[0], mol, nil) + fmt.Println(""DoneTestFixPDB"") +} + +// will fail if reduce is not installed! +func TTTestReduce(Te *testing.T) { //silenced + fmt.Println(""Start TestReduce"") + mol, err := PDBFileRead(""test/2c9v.pdb"", true) + if err != nil { + Te.Error(err) + } + logger, err := os.Create(""test/reducereport.log"") + if err != nil { + Te.Error(err) + } + defer logger.Close() + mol2, err := Reduce(mol, mol.Coords[0], 2, logger, """") + if err != nil { + Te.Error(err) + } + PDBFileWrite(""test/2c9vHReduce.pdb"", mol2.Coords[0], mol2, nil) + fmt.Println(""END TestReduce"") +} + +func TTestShape(Te *testing.T) { + myhandle, _ := os.Open(""test/2c9v.pdb"") + mol1, err := PDBRead(myhandle, true) //true means that we try to read the symbol from the PDB file. + masses, err := mol1.Masses() + if err != nil { + Te.Error(err) + } + moment, err := MomentTensor(mol1.Coords[0], masses) + if err != nil { + Te.Error(err) + } + rhos, err := Rhos(moment) + if err != nil { + Te.Error(err) + } + linear, circular, err := RhoShapeIndexes(rhos) + if err != nil { + Te.Error(err) + } + fmt.Println(""liner,circular distortion:"", linear, circular) + lin2, circ2, err := EasyShape(mol1.Coords[0], -1, mol1) + if err != nil { + Te.Error(err) + } + fmt.Println(""Easier way linear,circular:"", lin2, circ2) + mol2, _ := XYZFileRead(""test/sample_plane.xyz"") + lin3, circ3, err := EasyShape(mol2.Coords[0], -1, mol2) + if err != nil { + Te.Error(err) + } + fmt.Println(""sample_plane.xyz shape indicators; linear,circular:"", lin3, circ3) + //now the shapetests batterty! + mol2, _ = XYZFileRead(""test/shapetests/porphyrin.xyz"") + lin3, circ3, err = EasyShape(mol2.Coords[0], -1, mol2) + if err != nil { + Te.Error(err) + } + fmt.Println(""porphyrin.xyz shape indicators; linear,circular:"", lin3, circ3) + mol2, _ = XYZFileRead(""test/shapetests/2-mesoporphyrin.xyz"") + lin3, circ3, err = EasyShape(mol2.Coords[0], -1, mol2) + if err != nil { + Te.Error(err) + } + fmt.Println(""2-mesoporphyrin.xyz shape indicators; linear,circular:"", lin3, circ3) + mol2, _ = XYZFileRead(""test/shapetests/4-mesoporphyrin.xyz"") + lin3, circ3, err = EasyShape(mol2.Coords[0], -1, mol2) + if err != nil { + Te.Error(err) + } + fmt.Println(""4-mesoporphyrin.xyz shape indicators; linear,circular:"", lin3, circ3) + mol2, _ = XYZFileRead(""test/shapetests/heptane.xyz"") + lin3, circ3, err = EasyShape(mol2.Coords[0], -1, mol2) + if err != nil { + Te.Error(err) + } + fmt.Println(""heptane.xyz shape indicators; linear,circular:"", lin3, circ3) + mol2, _ = XYZFileRead(""test/shapetests/decane.xyz"") + lin3, circ3, err = EasyShape(mol2.Coords[0], -1, mol2) + if err != nil { + Te.Error(err) + } + fmt.Println(""decane.xyz shape indicators; linear,circular:"", lin3, circ3) + mol2, _ = XYZFileRead(""test/shapetests/phenantrene.xyz"") + lin3, circ3, err = EasyShape(mol2.Coords[0], -1, mol2) + if err != nil { + Te.Error(err) + } + fmt.Println(""phenantrene.xyz shape indicators; linear,circular:"", lin3, circ3) + mol2, _ = XYZFileRead(""test/shapetests/methylphenantrene.xyz"") + lin3, circ3, err = EasyShape(mol2.Coords[0], -1, mol2) + if err != nil { + Te.Error(err) + } + fmt.Println(""methylphenantrene shape indicators; linear,circular:"", lin3, circ3) + mol2, _ = XYZFileRead(""test/shapetests/tbutylphenantrene.xyz"") + lin3, circ3, err = EasyShape(mol2.Coords[0], -1, mol2) + if err != nil { + Te.Error(err) + } + fmt.Println(""tbutylphenantrene shape indicators; linear,circular:"", lin3, circ3) + mol2, _ = XYZFileRead(""test/shapetests/fullerene20.xyz"") + lin3, circ3, err = EasyShape(mol2.Coords[0], -1, mol2) + if err != nil { + Te.Error(err) + } + fmt.Println(""fullerene20.xyz shape indicators; linear,circular:"", lin3, circ3) + mol2, _ = XYZFileRead(""test/shapetests/fullerene60.xyz"") + lin3, circ3, err = EasyShape(mol2.Coords[0], 0.0001, mol2) //maybe it's too symmetrical for the default epsilon? + if err != nil { + Te.Error(err) + } + fmt.Println(""fullerene60.xyz shape indicators; linear,circular:"", lin3, circ3) + +} + +// Here PDBRead and PDBWrite are tested +func TTestSuper(Te *testing.T) { + backbone := []string{""CA"", ""C"", ""N""} //The PDB name of the atoms in the backbone. + myhandle, _ := os.Open(""test/2c9v.pdb"") + mol1, err := PDBRead(myhandle, true) //true means that we try to read the symbol from the PDB file. + mol2, err2 := PDBFileRead(""test/1uxm.pdb"", true) + if err != nil || err2 != nil { + panic(""Unable to open input files!"") + } + mols := []*Molecule{mol1, mol2} + superlist := make([][]int, 2, 2) + //We collect the atoms that are part of the backbone. + for molnumber, mol := range mols { + for atomindex, atom := range mol.Atoms { + if isInString(backbone, atom.Name) && atom.Chain == ""A"" { + superlist[molnumber] = append(superlist[molnumber], atomindex) + // fmt.Println(atom) + } + } + } + fmt.Println(""superlists!!"", len(superlist[0]), len(superlist[1])) + mol1.Coords[0], err = Super(mol1.Coords[0], mol2.Coords[0], superlist[0], superlist[1]) + rmsd1, _ := rMSD(mol1.Coords[0], mol2.Coords[0], superlist[0], superlist[1]) + rmsd2, _ := RMSD(mol1.Coords[0], mol2.Coords[0], superlist[0], superlist[1]) + fmt.Println(""RMSDs for proteins!"", rmsd2, rmsd1) + fmt.Println(""Atoms superimposed:"", len(superlist[0])) + if err != nil { + panic(err.Error()) + } + newname := ""test/2c9v_super.pdb"" //This is the PDBWrite written file + pdbout, _ := os.Create(newname) + PDBWrite(pdbout, mol1.Coords[0], mol1, nil) + //Now for a full molecule + ptest, _ := XYZFileRead(""test/Rotated.xyz"") + ptempla, _ := XYZFileRead(""test/sample_plane.xyz"") + newp, err := Super(ptest.Coords[0], ptempla.Coords[0], nil, nil) + rmsd2, _ = RMSD(newp, ptempla.Coords[0]) + rmsd3, _ := RMSD(newp, ptempla.Coords[0], nil, nil) + rmsd1, _ = rMSD(newp, ptempla.Coords[0], nil, nil) + fmt.Println(""RMSD mol (should be 0):"", rmsd1, rmsd2, rmsd3) + if err != nil { + panic(err.Error()) + } + XYZFileWrite(""test/SuperPlane.xyz"", newp, ptest) + +} + +func TestRotateBz(Te *testing.T) { + runtime.GOMAXPROCS(2) + fmt.Println(""Here we go!"") + mol, err := XYZFileRead(""test/BZ.xyz"") + if err != nil { + panic(err.Error()) + } + carbonIn := []int{} + bzIn := []int{} + for i := 0; i < mol.Len(); i++ { + at := mol.Atom(i) + if at.Symbol == ""C"" { + bzIn = append(bzIn, i) + carbonIn = append(carbonIn, i) + } else if at.Symbol == ""H"" { + bzIn = append(bzIn, i) + } + } + coordsI := mol.Coords[0] + carbons := v3.Zeros(6) + bz := v3.Zeros(12) + carbons.SomeVecs(coordsI, carbonIn) + coords := v3.Zeros(mol.Len()) + coords, _, _ = MassCenter(coordsI, carbons, nil) + bz.SomeVecs(coords, bzIn) + carbons.SomeVecs(coords, carbonIn) + planevec, err := BestPlane(carbons, nil) + if err != nil { + if e, ok := err.(Error); ok { + fmt.Println(""DEcoration:"", e.Decorate("""")) + } + Te.Errorf(err.Error()) + } + basename := ""BZ"" + newcoords := v3.Zeros(mol.Len()) + origin := v3.Zeros(1) + bzcopy := v3.Zeros(12) + bzcopy2 := v3.Zeros(12) //testing + rot := v3.Zeros(12) + rot3 := v3.Zeros(12) + for _, angle := range []float64{0, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 180} { + bzcopy.Copy(bz) + bzcopy2.Copy(bz) //testing + rot = Rotate(bzcopy, rot, planevec, Deg2Rad*angle) + rot3 = RotateSer(bzcopy, rot, planevec, Deg2Rad*angle) + rot2, _ := EulerRotateAbout(bzcopy2, origin, planevec, Deg2Rad*angle) //should be the same as the previous + if !mat.EqualApprox(rot, rot2, 0.01) { + Te.Errorf(""Rotors Rotate and EulerRotate not equal for angle %3.2f"", angle) + } else if !mat.EqualApprox(rot2, rot3, 0.01) { + Te.Errorf(""Rotors RotateSer and EulerRotate not equal for angle %3.2f"", angle) + + } else { + fmt.Println(""Rotors EQUAL for angle"", angle) + + } + fmt.Println(""rot"", rot, ""rot2"", rot2) + newcoords.Copy(coords) + newcoords.SetVecs(rot, bzIn) + //test + // tempcoords.Stack(planevec,origin) + // testxyz.Stack(newcoords,tempcoords) + //end + XYZFileWrite(fmt.Sprintf(""test/%s-%3.1f.xyz"", basename, angle), newcoords, mol) + + } + // fmt.Println(mol, planevec) +} + +func TestProjectionAndAntiProjection(Te *testing.T) { + A := v3.Zeros(1) + A.Set(0, 0, 2.0) + B, _ := v3.NewMatrix([]float64{1, 1, 0}) + C := AntiProjection(A, B) + D := Projection(B, A) + fmt.Println(""Projection of B on A (D)"", D) + fmt.Println(""Anti-projection of A on B (C):"", C) + fmt.Println(""Norm of C: "", C.Norm(2), "" Norm of A,B: "", A.Norm(2), B.Norm(2), ""Norm of D:"", D.Norm(2)) +} + +func TestBondsBz(Te *testing.T) { + runtime.GOMAXPROCS(2) + fmt.Println(""Bonds a la carga!"") + mol, err := XYZFileRead(""test/BZBonds.xyz"") + if err != nil { + panic(err.Error()) + } + var C *Atom + + for i := 0; i < mol.Len(); i++ { + C = mol.Atoms[i] + if C.Symbol == ""C"" { + break + } + } + mol.AssignBonds(mol.Coords[0]) + for i, v := range mol.Atoms { + fmt.Printf(""Atom %d index %d %s has %d bonds. It's bonded to atoms:\n"", i, v.index, v.Symbol, len(v.Bonds)) + for _, w := range v.Bonds { + a := w.Cross(v) + fmt.Printf(""Atom: %d %s\n"", a.index, a.Symbol) + } + fmt.Printf(""\n"") + + } + + path := BondedPaths(C, C.index, &BondedOptions{OnlyShortest: true}) + if path == nil { + Te.Errorf(""No path found!"") + } + fmt.Printf(""Path %v has %d nodes\n"", path, len(path)) + +} + +func TestBondsPorf(Te *testing.T) { + runtime.GOMAXPROCS(2) + fmt.Println(""A por las tienoporfi!"") + mol, err := XYZFileRead(""test/sample_plane.xyz"") + if err != nil { + panic(err.Error()) + } + var S *Atom + + for i := 0; i < mol.Len(); i++ { + S = mol.Atoms[i] + if S.Symbol == ""S"" { + break + } + } + mol.AssignBonds(mol.Coords[0]) + + spath := BondedPaths(S, S.index) + if spath == nil { + Te.Errorf(""No short path found!"") + } + fmt.Printf(""Short path %v has %d nodes\n"", spath[0], len(spath[0])) + paths := BondedPaths(S, S.index) + fmt.Printf(""Long path %v has %d nodes\n"", paths[len(paths)-1], len(paths[len(paths)-1])) + +} +","Go" +"Computational Biochemistry","rmera/gochem","hydrogens.go",".go","4114","145","/* + * hydrogens.go, part of gochem. + * + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + * + */ + +package chem + +import ( + ""bufio"" + ""fmt"" + ""os"" + ""os/exec"" + ""strings"" + + v3 ""github.com/rmera/gochem/v3"" + // ""runtime"" ///////// + // ""fmt"" /////////// +) + +// Reduce uses the Reduce program (Word, et. al. (1999) J. Mol. Biol. 285, +// 1735-1747. For more information see http://kinemage.biochem.duke.edu) +// To protonate a protein and flip residues. It writes the report from Reduce +// to a file called Reduce.err in the current dir. The Reduce executable can be given, +// in ""executable"", otherwise it will be assumed that it is a file called ""reduce"" and it is in the PATH. +func Reduce(mol Atomer, coords *v3.Matrix, build int, report *os.File, executable string) (*Molecule, error) { + //runtime.GOMAXPROCS(2) //////////////////// + flip := ""-NOFLIP"" + if build == 1 { + flip = ""-FLIP"" + } else if build > 1 { + flip = ""-BUILD"" + } + if executable == """" { + executable = ""reduce"" + } + reduce := exec.Command(executable, flip, ""-"") // , pdbname) + inp, err := reduce.StdinPipe() + if err != nil { + return nil, err + } + out, err := reduce.StdoutPipe() + if err != nil { + return nil, CError{err.Error(), []string{""exec.StdoutPipe"", ""Reduce""}} + } + out2, err := reduce.StderrPipe() + if err != nil { + return nil, CError{err.Error(), []string{""exec.StderrPipe"", ""Reduce""}} + + } + + if err := reduce.Start(); err != nil { + return nil, CError{err.Error(), []string{""exec.Start"", ""Reduce""}} + } + + PDBWrite(inp, coords, mol, nil) + inp.Close() + + bufiopdb := bufio.NewReader(out) + if report == nil { + report, err = os.Create(""Reduce.log"") + if err != nil { + return nil, CError{err.Error(), []string{""os.Create"", ""Reduce""}} + + } + defer report.Close() + } + repio := bufio.NewWriter(report) //The reports of Reduce, which are written mostly to StdErr but also to StdOut will be compiled here. + var stder_ready = make(chan error) + /** + In the following lines I am forced to use a gorutine to read the StdErr, as I need its contents, and reduce + does not like them to be read serially. Apparently each of them get stuck at some point if you don't read the other, + hence, I need to do it concurrently. + **/ + go func() { + defer repio.Flush() + if _, err := repio.ReadFrom(out2); err != nil { + out2.Close() + stder_ready <- CError{err.Error(), []string{""bufio.ReadFrom"", ""Reduce""}} + } + out2.Close() + stder_ready <- nil + }() + + //I'm forced to use this buffer and later write to the report file to prevent a data race with the gorutine + //reading StdErr. + reportBuffer := make([]string, 0, 200) + dashes := 0 + for { + s, err := bufiopdb.ReadString('\n') + if err != nil { + return nil, fmt.Errorf(""Reduce: %w"", err) + } + reportBuffer = append(reportBuffer, s) + + if strings.Contains(s, ""USER MOD ---------------------------------------------------"") { + dashes++ + if dashes > 1 { + break + } + } + } + + mol2, err := pdbBufIORead(bufiopdb, false) + if err != nil { + return nil, fmt.Errorf(""Reduce: %w"", err) + } + out.Close() + err = <-stder_ready + //Here we don't need the buffering so we write directly to report (the file) instead of to repio. + for _, v := range reportBuffer { + _, err := report.Write([]byte(v)) + if err != nil { + return mol2, err + } + } + if err != nil { + return mol2, err + } + + return mol2, nil + +} +","Go" +"Computational Biochemistry","rmera/gochem","ramacalc.go",".go","5719","172","/* + * ramacalc.go, part of gochem. + * + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + * + */ +package chem + +import ( + ""fmt"" + ""strings"" + + v3 ""github.com/rmera/gochem/v3"" +) + +//A structure with the data for obtaining one pair of Ramachandran angles. +type RamaSet struct { + Cprev int + N int + Ca int + C int + Npost int + MolID int + MolName string +} + +// RamaCalc Obtains the values for the phi and psi dihedrals indicated in []Ramaset, for the +// structure M. The angles are in *degrees*. It returns a slice of 2-element slices, one for the phi the next for the psi +// dihedral, a and an error or nil. +func RamaCalc(M *v3.Matrix, dihedrals []RamaSet) ([][]float64, error) { + if M == nil || dihedrals == nil { + return nil, CError{string(ErrNilData), []string{""RamaCalc""}} + } + r, _ := M.Dims() + Rama := make([][]float64, 0, len(dihedrals)) + for _, j := range dihedrals { + if j.Npost >= r { + return nil, CError{""Data out of range"", []string{""RamaCalc""}} + } + Cprev := M.VecView(j.Cprev) + N := M.VecView(j.N) + Ca := M.VecView(j.Ca) + C := M.VecView(j.C) + Npost := M.VecView(j.Npost) + phi := DihedralRama(Cprev, N, Ca, C) + psi := DihedralRama(N, Ca, C, Npost) + temp := []float64{phi * Rad2Deg, psi * Rad2Deg} + Rama = append(Rama, temp) + } + return Rama, nil +} + +// RamaResidueFilter filters the set of a slice of RamaSet (i.e. a set of Ramachandran angles to be calculated) +//by residue.(ex. only GLY, everything but GLY) +// The 3 letter code of the residues to be filtered in or out is in filterdata, whether they are filter in +// or out depends on shouldBePresent. It returns the filtered data and a slice containing the indexes in +// the new data of the residues in the old data, when they are included, or -1 when they are not included. +func RamaResidueFilter(dihedrals []RamaSet, filterdata []string, shouldBePresent bool) ([]RamaSet, []int) { + RetList := make([]RamaSet, 0, 0) + Index := make([]int, len(dihedrals)) + var added int + for key, val := range dihedrals { + isPresent := isInString(filterdata, val.MolName) + if isPresent == shouldBePresent { + RetList = append(RetList, val) + Index[key] = added + added++ + } else { + Index[key] = -1 + } + } + return RetList, Index +} + +// RamaList takes a molecule and returns a slice of RamaSet, which contains the +// indexes for each dihedral to be included in a Ramachandran plot. It gets the dihedral +// indices for all residues in the range resran. if resran has 2 elements defining the +// boundaries. Otherwise, returns dihedral lists for the residues included in +// resran. If resran has 2 elements and the last is -1, RamaList will +// get all the dihedral for residues from resran[0] to the end of the chain. +// It only obtain dihedral lists for residues belonging to a chain included in chains. +func RamaList(M Atomer, chains string, resran []int) ([]RamaSet, error) { + RamaList := make([]RamaSet, 0, 0) + if len(resran) == 2 { + if resran[1] == -1 { + resran[1] = 999999999 //should work! + } + } + if M == nil { + return nil, CError{""Nil data given"", []string{""RamaList""}} + } + C := -1 + N := -1 + Ca := -1 + Cprev := -1 + Npost := -1 + chainprev := ""NOTAVALIDCHAIN"" //any non-valid chain name + for num := 0; num < M.Len(); num++ { + at := M.Atom(num) + //First get the indexes we need. Change: If you give RamaList an empty string for ""chains"", it will + //include all chains in the chem.Atomer. + if strings.Contains(chains, string(at.Chain)) || at.Chain == "" "" || chains == """" { + if at.Chain != chainprev { + chainprev = at.Chain + C = -1 + N = -1 + Ca = -1 + Cprev = -1 + Npost = -1 + } + if at.Name == ""C"" && Cprev == -1 { + Cprev = num + } + if at.Name == ""N"" && Cprev != -1 && N == -1 && at.MolID > M.Atom(Cprev).MolID { + N = num + } + if at.Name == ""C"" && Cprev != -1 && at.MolID > M.Atom(Cprev).MolID { + C = num + } + if at.Name == ""CA"" && Cprev != -1 && at.MolID > M.Atom(Cprev).MolID { + Ca = num + } + if at.Name == ""N"" && Ca != -1 && at.MolID > M.Atom(Ca).MolID { + Npost = num + } + //when we have them all, we save + if Cprev != -1 && Ca != -1 && N != -1 && C != -1 && Npost != -1 { + //We check that the residue ids are what they are supposed to be + r1 := M.Atom(Cprev).MolID + r2 := M.Atom(N).MolID + r2a := M.Atom(Ca).MolID + r2b := M.Atom(C).MolID + r3 := M.Atom(Npost).MolID + if (len(resran) == 2 && (r2 >= resran[0] && r2 <= resran[1])) || isInInt(resran, r2) { + if r1 != r2-1 || r2 != r2a || r2a != r2b || r2b != r3-1 { + return nil, CError{fmt.Sprintf(""Incorrect backbone Cprev: %d N-1: %d CA: %d C: %d Npost-1: %d"", r1, r2-1, r2a, r2b, r3-1), []string{""RamaList""}} + } + temp := RamaSet{Cprev, N, Ca, C, Npost, r2, M.Atom(Ca).MolName} + RamaList = append(RamaList, temp) + } + N = Npost + Ca = -1 + Cprev = C + C = -1 + Npost = -1 + } + } + } + // fmt.Println(""Rama"",Rama, ""failed"", failed) + return RamaList, nil +} +","Go" +"Computational Biochemistry","rmera/gochem","clifford.go",".go","15012","387","/* + * Clifford.go, part of gochem. + * + * + * Copyright 2012 Janne Pesonen + * and Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + * + */ + +package chem + +import ( + ""math"" + ""runtime"" + + v3 ""github.com/rmera/gochem/v3"" +) + +//import ""fmt"" //debug + +type paravector struct { + Real float64 + Imag float64 + Vreal *v3.Matrix + Vimag *v3.Matrix +} + +//creates a new paravector +func makeParavector() *paravector { + R := new(paravector) + R.Real = 0 //I shouldnt need this + R.Imag = 0 + R.Vreal = v3.Zeros(1) + R.Vimag = v3.Zeros(1) + return R +} + +//Takes a vector and creates a paravector. Uses copy so the vector is not affected +//By future changes to the paravector. +func paravectorFromVector(A, B *v3.Matrix) *paravector { + R := new(paravector) + R.Real = 0 //I shouldnt need this + R.Imag = 0 + R.Vreal = A + R.Vimag = B + return R +} + +//Puts a copy fo the paravector P in the receiver +func (R *paravector) Copy(P *paravector) { + R.Real = P.Real + R.Imag = P.Imag + R.Vreal.Copy(P.Vreal) + R.Vimag.Copy(P.Vimag) +} + +//Puts the reverse of paravector P in the received +func (R *paravector) reverse(P *paravector) { + if P != R { + R.Copy(P) + } + R.Vimag.Scale(-1, R.Vimag) +} + +//Puts the normalized version of P in the receiver. If R and P are the same, +func (R *paravector) unit(P *paravector) { + norm := 0.0 + norm += math.Pow(P.Real, 2) + math.Pow(P.Imag, 2) + for i := 0; i < 3; i++ { + norm += math.Pow(P.Vreal.At(0, i), 2) + math.Pow(P.Vimag.At(0, i), 2) + } + //fmt.Println(""norm"", norm) + R.Real = P.Real / math.Sqrt(norm) + R.Imag = P.Imag / math.Sqrt(norm) + for i := 0; i < 3; i++ { + R.Vreal.Set(0, i, P.Vreal.At(0, i)/math.Sqrt(norm)) + R.Vimag.Set(0, i, P.Vimag.At(0, i)/math.Sqrt(norm)) + } + //fmt.Println(""normalized"", R) +} + +//Clifford product of 2 paravectors, the imaginary parts are simply set to zero, since this is the case +//when rotating 3D real vectors. The proper Cliffor product is in fullCliProduct +func (R *paravector) cliProduct(A, B *paravector) { + R.Real = A.Real*B.Real - A.Imag*B.Imag + for i := 0; i < 3; i++ { + R.Real += (A.Vreal.At(0, i)*B.Vreal.At(0, i) - A.Vimag.At(0, i)*B.Vimag.At(0, i)) + } + R.Imag = A.Real*B.Imag + A.Imag*B.Real + for i := 0; i < 3; i++ { + R.Imag += (A.Vreal.At(0, i)*B.Vimag.At(0, i) + A.Vimag.At(0, i)*B.Vreal.At(0, i)) + } + //Now the vector part + //First real + R.Vreal.Set(0, 0, A.Real*B.Vreal.At(0, 0)+B.Real*A.Vreal.At(0, 0)-A.Imag*B.Vimag.At(0, 0)-B.Imag*A.Vimag.At(0, 0)+ + A.Vimag.At(0, 2)*B.Vreal.At(0, 1)-A.Vimag.At(0, 1)*B.Vreal.At(0, 2)+A.Vreal.At(0, 2)*B.Vimag.At(0, 1)- + A.Vreal.At(0, 1)*B.Vimag.At(0, 2)) + //Second real + R.Vreal.Set(0, 1, A.Real*B.Vreal.At(0, 1)+B.Real*A.Vreal.At(0, 1)-A.Imag*B.Vimag.At(0, 1)-B.Imag*A.Vimag.At(0, 1)+ + A.Vimag.At(0, 0)*B.Vreal.At(0, 2)-A.Vimag.At(0, 2)*B.Vreal.At(0, 0)+A.Vreal.At(0, 0)*B.Vimag.At(0, 2)- + A.Vreal.At(0, 2)*B.Vimag.At(0, 0)) + //Third real + R.Vreal.Set(0, 2, A.Real*B.Vreal.At(0, 2)+B.Real*A.Vreal.At(0, 2)-A.Imag*B.Vimag.At(0, 2)-B.Imag*A.Vimag.At(0, 2)+ + A.Vimag.At(0, 1)*B.Vreal.At(0, 0)-A.Vimag.At(0, 0)*B.Vreal.At(0, 1)+A.Vreal.At(0, 1)*B.Vimag.At(0, 0)- + A.Vreal.At(0, 0)*B.Vimag.At(0, 1)) + /* + //First imag + R.Vimag.Set(0,0,A.Real*B.Vimag.At(0,0) + B.Real*A.Vimag.At(0,0) + A.Imag*B.Vreal.At(0,0) - B.Imag*A.Vreal.At(0,0) + + A.Vreal.At(0,1)*B.Vreal.At(0,2) - A.Vreal.At(0,2)*B.Vreal.At(0,1) + A.Vimag.At(0,2)*B.Vimag.At(0,1) - + A.Vimag.At(0,1)*B.Vimag.At(0,2)) + //Second imag + R.Vimag.Set(0,1,A.Real*B.Vimag.At(0,1) + B.Real*A.Vimag.At(0,1) + A.Imag*B.Vreal.At(0,1) - B.Imag*A.Vreal.At(0,1) + + A.Vreal.At(0,2)*B.Vreal.At(0,0) - A.Vreal.At(0,0)*B.Vreal.At(0,2) + A.Vimag.At(0,0)*B.Vimag.At(0,2) - + A.Vimag.At(0,2)*B.Vimag.At(0,0)) + //Third imag + R.Vimag.Set(0,2,A.Real*B.Vimag.At(0,2) + B.Real*A.Vimag.At(0,2) + A.Imag*B.Vreal.At(0,2) - B.Imag*A.Vreal.At(0,2) + + A.Vreal.At(0,0)*B.Vreal.At(0,1) - A.Vreal.At(0,1)*B.Vreal.At(0,0) + A.Vimag.At(0,1)*B.Vimag.At(0,0) - + A.Vimag.At(0,0)*B.Vimag.At(0,1)) + */ + //fmt.Println(""R slido del horno"", R) + // A.Real, B.Vimag.At(0,0), ""g2"", B.Real,A.Vimag.At(0,0),""g3"", A.Imag, B.Vreal.At(0,0),""g4"" ,B.Imag,A.Vreal.At(0,0), + //""g5"", A.Vreal.At(0,2), B.Vreal.At(0,1), -1*A.Vreal.At(0,1)*B.Vreal.At(0,2), A.Vimag.At(0,2)*B.Vimag.At(0,1), -1* + //A.Vimag.At(0,1)*B.Vimag.At(0,2)) + // return R +} + +//cliRotation uses Clifford algebra to rotate a paravector Aby angle radians around axis. Returns the rotated +//paravector. axis must be normalized. +func (R *paravector) cliRotation(A, axis, tmp, tmp2 *paravector, angle float64) { + // R := makeParavector() + R.Real = math.Cos(angle / 2.0) + for i := 0; i < 3; i++ { + R.Vimag.Set(0, i, math.Sin(angle/2.0)*axis.Vreal.At(0, i)) + } + R.reverse(R) + // tmp:=makeParavector() + // tmp2:=makeParavector() + tmp.cliProduct(R, A) + tmp2.cliProduct(tmp, R) + R.Copy(tmp2) +} + +//RotateSer takes the matrix Target and uses Clifford algebra to rotate each of its rows +//by angle radians around axis. Axis must be a 3D row vector. Target must be an N,3 matrix. +//The Ser in the name is from ""serial"". ToRot will be overwritten and returned +func RotateSer(Target, ToRot, axis *v3.Matrix, angle float64) *v3.Matrix { + cake := v3.Zeros(10) //Better ask for one chunk of memory than allocate 10 different times. + R := cake.VecView(0) + Rrev := cake.VecView(1) + tmp := cake.VecView(2) + Rotated := cake.VecView(3) + itmp1 := cake.VecView(4) + itmp2 := cake.VecView(5) + itmp3 := cake.VecView(6) + itmp4 := cake.VecView(7) + itmp5 := cake.VecView(8) + itmp6 := cake.VecView(9) + RotateSerP(Target, ToRot, axis, tmp, R, Rrev, Rotated, itmp1, itmp2, itmp3, itmp4, itmp5, itmp6, angle) + return ToRot +} + +//RotateSerP takes the matrix Target and uses Clifford algebra to rotate each of its rows +//by angle radians around axis. Axis must be a 3D row vector. Target must be an N,3 matrix. +//The Ser in the name is from ""serial"". ToRot will be overwritten and returned. RotateSerP only allocates some floats but not +//any v3.Matrix. Instead, it takes the needed intermediates as arguments, hence the ""P"" for ""performance"" If performance is not an issue, +//use RotateSer instead, it will perform the allocations for you and call this function. Notice that if you use this function directly +//you may have to zero at least some of the intermediates before reusing them. +func RotateSerP(Target, ToRot, axis, tmpv, Rv, Rvrev, Rotatedv, itmp1, itmp2, itmp3, itmp4, itmp5, itmp6 *v3.Matrix, angle float64) { + tarr, _ := Target.Dims() + torotr := ToRot.NVecs() + if tarr != torotr || Target.Dense == ToRot.Dense { + panic(ErrCliffordRotation) + } + //Make the paravectors from the passed vectors: + tmp := paravectorFromVector(tmpv, itmp3) + R := paravectorFromVector(Rv, itmp4) + Rrev := paravectorFromVector(Rvrev, itmp5) + Rotated := paravectorFromVector(Rotatedv, itmp6) + //That is with the building of temporary paravectors. + paxis := paravectorFromVector(axis, itmp1) + paxis.unit(paxis) + R.Real = math.Cos(angle / 2.0) + for i := 0; i < 3; i++ { + R.Vimag.Set(0, i, math.Sin(angle/2.0)*paxis.Vreal.At(0, i)) + } + Rrev.reverse(R) + for i := 0; i < tarr; i++ { + rowvec := Target.VecView(i) + tmp.cliProduct(Rrev, paravectorFromVector(rowvec, itmp2)) + Rotated.cliProduct(tmp, R) + ToRot.SetMatrix(i, 0, Rotated.Vreal) + } +} + +func getChunk(cake *v3.Matrix, i, j, r, c int) *v3.Matrix { + ret := cake.View(i, j, r, c) + return ret + +} + +//Rotate takes the matrix Target and uses Clifford algebra to _concurrently_ rotate each +//of its rows by angle radians around axis. Axis must be a 3D row vector. +//Target must be an N,3 matrix. The result is put in Res, which is also returned. +//This is a low-level function. Most commonly, you'll want to use RotateAbout instead. +func Rotate(Target, Res, axis *v3.Matrix, angle float64) *v3.Matrix { + // runtime.GOMAXPROCS(3) + gorut := runtime.GOMAXPROCS(-1) + rows := Target.NVecs() + // println(""rows and goruts"", rows,gorut) ///// + if gorut > rows { + gorut = rows + } + cake := v3.Zeros(5 + gorut*4) + Rv := cake.VecView(0) + Rvrev := cake.VecView(1) + itmp1 := cake.VecView(2) + itmp2 := cake.VecView(3) + itmp3 := cake.VecView(4) + tmp1 := getChunk(cake, 5, 0, gorut, 3) + tmp2 := getChunk(cake, 5+gorut, 0, gorut, 3) + tmp3 := getChunk(cake, 5+2*gorut, 0, gorut, 3) + tmp4 := getChunk(cake, 5+3*gorut, 0, gorut, 3) + RotateP(Target, Res, axis, Rv, Rvrev, tmp1, tmp2, tmp3, tmp4, itmp1, itmp2, itmp3, angle, gorut) + return Res +} + +//RotateP takes the matrix Target and uses Clifford algebra to _concurrently_ rotate each +//of its rows by angle radians around axis. Axis must be a 3D row vector. +//Target must be an N,3 matrix. +func RotateP(Target, Res, axis, Rv, Rvrev, tmp1, tmp2, tmp3, tmp4, itmp1, itmp2, itmp3 *v3.Matrix, angle float64, gorut int) { + //fmt.Println(""Enter RotateP"")////////////// + // gorut := runtime.GOMAXPROCS(-1) //Do not change anything, only query + rows := Target.NVecs() + rrows := Res.NVecs() + if rrows != rows || Target.Dense == Res.Dense { + panic(ErrCliffordRotation) + } + paxis := paravectorFromVector(axis, itmp1) //alloc + paxis.unit(paxis) + R := paravectorFromVector(Rv, itmp2) // makeParavector() //build the rotor (R) //alloc + R.Real = math.Cos(angle / 2.0) + for i := 0; i < 3; i++ { + R.Vimag.Set(0, i, math.Sin(angle/2.0)*paxis.Vreal.At(0, i)) + } + Rrev := paravectorFromVector(Rvrev, itmp3) // makeParavector() //R-dagger //alloc + Rrev.reverse(R) + // if gorut > rows { + // gorut = rows + // } + ended := make(chan bool, gorut) + //If the gorutines are more than the rows, we will have problems afterwards, as we try to split the rows + //among the available gorutines, some gorutines are going to get invalid matrix positions. + fragmentlen := int(math.Floor(float64(rows) / float64(gorut))) //len of the fragment of target that each gorutine will handle + // println(""fragmentlen"", fragmentlen, rows, gorut, Target.String()) ////////// + // println(""gorutines!!!"", gorut) /////// + for i := 0; i < gorut; i++ { + //These are the limits of the fragment of Target in which the gorutine will operate + ini := i * fragmentlen + end := i*fragmentlen + (fragmentlen - 1) + if i == gorut-1 { + end = rows - 1 //The last fragment may be smaller than fragmentlen + } + go func(ini, end, i int) { + t1 := tmp1.VecView(i) + //r,c:=tmp2.Dims()/// + //this ""print"" causes a data race but it shouldn't matter, as it's only for debugging purposes. + //removing the print removes the race warning, so there isn't apparently any data race going on. + //fmt.Println(""WTF"",r,c,i,tmp2,""\n"") ///////// + //fmt.Println("""") //////////// + t2 := tmp2.VecView(i) + t4 := tmp4.VecView(i) + pv := paravectorFromVector(t2, t4) + t3 := tmp3.VecView(i) + for j := ini; j <= end; j++ { + //Here we simply do R^dagger A R, and assign to the corresponding row. + Rotated := paravectorFromVector(Res.VecView(j), t3) + targetparavec := paravectorFromVector(Target.VecView(j), t1) + pv.cliProduct(Rrev, targetparavec) + Rotated.cliProduct(pv, R) + } + ended <- true + return + }(ini, end, i) + } + //Takes care of the concurrency + for i := 0; i < gorut; i++ { + <-ended + } + //fmt.Println(""YEY!, funcion ql!!!!"")//////////////////////////// + return +} + +/* + rows, _ := Target.Dims() + paxis := paravectorFromVector(axis,v3.Zeros(1)) + paxis.unit(paxis) + R := makeParavector() //build the rotor (R) + R.Real = math.Cos(angle / 2.0) + for i := 0; i < 3; i++ { + R.Vimag.Set(0, i, math.Sin(angle/2.0)*paxis.Vreal.At(0, i)) + } + + Rrev := R.reverse() // R-dagger + Res := v3.Zeros(rows) + ended := make(chan bool, rows) + for i := 0; i < rows; i++ { + go func(i int) { + //Here we simply do R^dagger A R, and assign to the corresponding row. + targetrow := Target.VecView(i) + tmp := cliProduct(Rrev, paravectorFromVector(targetrow,v3.Zeros(1))) + Rotated := cliProduct(tmp, R) + //a,b:=Res.Dims() //debug + //c,d:=Rotated.Vreal.Dims() + //fmt.Println(""rows"",a,c,""cols"",b,d,""i"",""rowss"",) + Res.SetMatrix(i, 0, Rotated.Vreal) + ended <- true + return + }(i) + } + //Takes care of the concurrency + for i := 0; i < rows; i++ { + <-ended + } + return Res +} +*/ + +//Clifford product of 2 paravectors. +func fullCliProduct(A, B *paravector) *paravector { + R := makeParavector() + R.Real = A.Real*B.Real - A.Imag*B.Imag + for i := 0; i < 3; i++ { + R.Real += (A.Vreal.At(0, i)*B.Vreal.At(0, i) - A.Vimag.At(0, i)*B.Vimag.At(0, i)) + } + R.Imag = A.Real*B.Imag + A.Imag*B.Real + for i := 0; i < 3; i++ { + R.Imag += (A.Vreal.At(0, i)*B.Vimag.At(0, i) + A.Vimag.At(0, i)*B.Vreal.At(0, i)) + } + //Now the vector part + //First real + R.Vreal.Set(0, 0, A.Real*B.Vreal.At(0, 0)+B.Real*A.Vreal.At(0, 0)-A.Imag*B.Vimag.At(0, 0)-B.Imag*A.Vimag.At(0, 0)+ + A.Vimag.At(0, 2)*B.Vreal.At(0, 1)-A.Vimag.At(0, 1)*B.Vreal.At(0, 2)+A.Vreal.At(0, 2)*B.Vimag.At(0, 1)- + A.Vreal.At(0, 1)*B.Vimag.At(0, 2)) + //Second real + R.Vreal.Set(0, 1, A.Real*B.Vreal.At(0, 1)+B.Real*A.Vreal.At(0, 1)-A.Imag*B.Vimag.At(0, 1)-B.Imag*A.Vimag.At(0, 1)+ + A.Vimag.At(0, 0)*B.Vreal.At(0, 2)-A.Vimag.At(0, 2)*B.Vreal.At(0, 0)+A.Vreal.At(0, 0)*B.Vimag.At(0, 2)- + A.Vreal.At(0, 2)*B.Vimag.At(0, 0)) + //Third real + R.Vreal.Set(0, 2, A.Real*B.Vreal.At(0, 2)+B.Real*A.Vreal.At(0, 2)-A.Imag*B.Vimag.At(0, 2)-B.Imag*A.Vimag.At(0, 2)+ + A.Vimag.At(0, 1)*B.Vreal.At(0, 0)-A.Vimag.At(0, 0)*B.Vreal.At(0, 1)+A.Vreal.At(0, 1)*B.Vimag.At(0, 0)- + A.Vreal.At(0, 0)*B.Vimag.At(0, 1)) + //First imag + R.Vimag.Set(0, 0, A.Real*B.Vimag.At(0, 0)+B.Real*A.Vimag.At(0, 0)+A.Imag*B.Vreal.At(0, 0)-B.Imag*A.Vreal.At(0, 0)+ + A.Vreal.At(0, 1)*B.Vreal.At(0, 2)-A.Vreal.At(0, 2)*B.Vreal.At(0, 1)+A.Vimag.At(0, 2)*B.Vimag.At(0, 1)- + A.Vimag.At(0, 1)*B.Vimag.At(0, 2)) + //Second imag + R.Vimag.Set(0, 1, A.Real*B.Vimag.At(0, 1)+B.Real*A.Vimag.At(0, 1)+A.Imag*B.Vreal.At(0, 1)-B.Imag*A.Vreal.At(0, 1)+ + A.Vreal.At(0, 2)*B.Vreal.At(0, 0)-A.Vreal.At(0, 0)*B.Vreal.At(0, 2)+A.Vimag.At(0, 0)*B.Vimag.At(0, 2)- + A.Vimag.At(0, 2)*B.Vimag.At(0, 0)) + //Third imag + R.Vimag.Set(0, 2, A.Real*B.Vimag.At(0, 2)+B.Real*A.Vimag.At(0, 2)+A.Imag*B.Vreal.At(0, 2)-B.Imag*A.Vreal.At(0, 2)+ + A.Vreal.At(0, 0)*B.Vreal.At(0, 1)-A.Vreal.At(0, 1)*B.Vreal.At(0, 0)+A.Vimag.At(0, 1)*B.Vimag.At(0, 0)- + A.Vimag.At(0, 0)*B.Vimag.At(0, 1)) + //fmt.Println(""R slido del horno"", R) + // A.Real, B.Vimag.At(0,0), ""g2"", B.Real,A.Vimag.At(0,0),""g3"", A.Imag, B.Vreal.At(0,0),""g4"" ,B.Imag,A.Vreal.At(0,0), + //""g5"", A.Vreal.At(0,2), B.Vreal.At(0,1), -1*A.Vreal.At(0,1)*B.Vreal.At(0,2), A.Vimag.At(0,2)*B.Vimag.At(0,1), -1* + //A.Vimag.At(0,1)*B.Vimag.At(0,2)) + + return R +} +","Go" +"Computational Biochemistry","rmera/gochem","cg.go",".go","5622","180","/* + * cg.go, part of gochem + * + * Copyright 2020 Raul Mera A. (raulpuntomeraatusachpuntocl) + * + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 2.1 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . + * + * +*/ + +package chem + +import ( + ""fmt"" + ""log"" + + v3 ""github.com/rmera/gochem/v3"" + ""gonum.org/v1/gonum/mat"" +) + +func errorDec(err error, frame int) error { + if err, ok := err.(Error); ok { + err.Decorate(fmt.Sprintf(""BackboneCGize: Error processing %d th residue"", frame)) + } + return err + +} + +// returns a slice with the masses and an error or nil. If usecom is not given, +// a slice of 1s and nil will be returned (i.e. a slice that can be +// used to calculate the COG). +// if the usecom IS given, but the masses are not found, a slice of 1s +// and an error will be returned. +func masses(top *Topology, usecom ...bool) ([]float64, error) { + var err error + var mass []float64 + if len(usecom) > 0 && usecom[0] { + mass, err = top.Masses() + if err == nil { + return mass, nil + } + } + mass = make([]float64, 0, top.Len()) + for i := 0; i < top.Len(); i++ { + mass = append(mass, 1) + } + return mass, err +} + +// BackboneCGize takes a coord and a mol for a protein, and returns a new set of coordinates +// each of which cooresponds to the center of mass of the backbone of the corresponding residue +// in the original molecule. If top is true, it also returns a topology where each atom corrsponds +// to the center of mass, with the name ""BB"", and the correct residue name and ID. Otherwise it returns +// an empty topology. +// In other words, it takes a protein and returns a CG model for its backbone, in the currect conformation. +// If centroid is given and true, the geometric center is used instead of the center of mass. +func BackboneCGize(coord *v3.Matrix, mol Atomer, top bool, com ...bool) (*v3.Matrix, *Topology, error) { + topol := NewTopology(0, 1) + residues := countResidues(mol) //sorry + res4vec := 0 + retcoord := v3.Zeros(residues) + bb := v3.Zeros(4) //atoms in the backbone + bbtop := NewTopology(0, 1) + resid := 0 //the first residue is 1, not 0! + for i := 0; i < mol.Len(); i++ { //Note that MolIDs are the PDB residue ID, so they are counted from 1 + atom := mol.Atom(i) + if resid == atom.MolID { + continue + } + resid = atom.MolID + bbin := molecules2BBAtoms(mol, []int{resid}, []string{atom.Chain}) + if len(bbin) == 0 { + continue //not a protein residue, perhaps a ligand + } + // fmt.Println(len(bbin), bbin) //////////////// + if len(bbin) != bb.NVecs() { + bb = v3.Zeros(len(bbin)) + if len(bbin) != 4 { + log.Printf(""Abnormal backbone detected in residue %s %d: %d atoms in backbone. Will obtain BB bead with the position of those atoms"", atom.MolName, atom.MolID, len(bbin)) + } + } + bb.SomeVecs(coord, bbin) + bbtop.SomeAtoms(mol, bbin) + if len(com) != 0 { + com = append(com, true) + } + var mass, err = masses(bbtop, com...) + if err != nil { + return nil, nil, errorDec(err, i) + } + com, err := CenterOfMass(bb, mat.NewDense(len(mass), 1, mass)) + if err != nil { + return nil, nil, errorDec(err, i) + } + retcoord.SetVecs(com, []int{res4vec}) + res4vec++ + if top { + at := new(Atom) + at.Copy(atom) + at.ID = resid + at.Name = ""BB"" + topol.AppendAtom(at) + } + + } + if top && topol.Len() != retcoord.NVecs() { + rc2 := v3.Zeros(topol.Len()) + ri := make([]int, topol.Len()) + for i := 0; i < topol.Len(); i++ { + ri[i] = i + } + rc2.SomeVecs(retcoord, ri) + retcoord = rc2 + } + return retcoord, topol, nil +} + +func countResidues(mol Atomer) int { + resid := 0 + ret := 0 + for i := 0; i < mol.Len(); i++ { + at := mol.Atom(i) + if resid != at.MolID { + ret++ + resid = at.MolID + } + } + return ret + +} + +// molecules2BBAtoms returns the indexes for the BB atoms in a given set for residues +// of course, it only works for aminoacidic residues. +func molecules2BBAtoms(mol Atomer, residues []int, chains []string) []int { + atlist := make([]int, 0, len(residues)*3) + bb := []string{""N"", ""CA"", ""C"", ""O"", ""OC1"", ""OC2""} //OC1 and OC2 are for C-terminal residues which have 2 O. + for key := 0; key < mol.Len(); key++ { + at := mol.Atom(key) + if isInInt(residues, at.MolID) && (isInString(chains, at.Chain) || len(chains) == 0) { + if isInString(bb, at.Name) { + atlist = append(atlist, key) + } + } + } + return atlist +} + +// Returns COM or COG (default) coordinates for the beads constructed each from the atoms +// with indexes (in mol) given in the respective slice of beads, and with coordinates coords. +func At2CGCoords(coords *v3.Matrix, mol *Topology, beads [][]int, usecom ...bool) (*v3.Matrix, error) { + ret := v3.Zeros(len(beads)) + for i, v := range beads { + tmp := v3.Zeros(len(v)) + tmpt := NewTopology(0, 1) + tmp.SomeVecs(coords, v) + tmpt.SomeAtoms(mol, v) + mass, err := masses(tmpt, usecom...) + if err != nil { + return nil, fmt.Errorf(""Error assigning masses: %w"", err) + } + com, err := CenterOfMass(tmp, mat.NewDense(len(mass), 1, mass)) + if err != nil { + return nil, fmt.Errorf(""Couldn't obtain the COM or centroid: %w"", err) + } + ret.SetVecs(com, []int{i}) + } + return ret, nil +} +","Go" +"Computational Biochemistry","rmera/gochem","files.go",".go","34905","999","/* + * files.go, part of gochem. + * + * + * Copyright 2012 Raul Mera rauldotmeraatusachdotcl + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * goChem is developed at Universidad de Santiago de Chile (USACH) + * + * + */ + +package chem + +import ( + ""bufio"" + ""fmt"" + ""io"" + ""log"" + ""os"" + ""strconv"" + ""strings"" + + v3 ""github.com/rmera/gochem/v3"" +) + +//PDB_read family + +// A map between 3-letters name for aminoacidic residues to the corresponding 1-letter names. +var three2OneLetter = map[string]byte{ + ""SER"": 'S', + ""THR"": 'T', + ""ASN"": 'N', + ""GLN"": 'Q', + ""SEC"": 'U', //Selenocysteine! + ""CYS"": 'C', + ""GLY"": 'G', + ""PRO"": 'P', + ""ALA"": 'A', + ""VAL"": 'V', + ""ILE"": 'I', + ""LEU"": 'L', + ""MET"": 'M', + ""PHE"": 'F', + ""TYR"": 'Y', + ""TRP"": 'W', + ""ARG"": 'R', + ""HIS"": 'H', + ""LYS"": 'K', + ""ASP"": 'D', + ""GLU"": 'E', +} + +// This tries to guess a chemical element symbol from a PDB atom name. Mostly based on AMBER names. +// It only deals with some common bio-elements. +func symbolFromName(name string) (string, error) { + symbol := """" + if len(name) == 1 { + symbol = name //should work + } else if len(name) == 4 || name[0] == 'H' { //I thiiink only Hs can have 4-char names in amber. + symbol = ""H"" + //it name has more than one character but less than four. + } else if name[0] == 'C' { + if name[0:2] == ""CU"" { + symbol = ""Cu"" + } else if name == ""CO"" { + symbol = ""Co"" + } else if name == ""CL"" { + symbol = ""Cl"" + } else { + symbol = ""C"" + } + } else if name[0] == 'B' { + if name == ""BE"" { + symbol = ""Be"" + } + } else if name[0] == 'N' { + if name == ""NA"" { + symbol = ""Na"" + } else { + symbol = ""N"" + } + } else if name[0] == 'O' { + symbol = ""O"" + } else if name[0] == 'P' { + symbol = ""P"" + } else if name[0] == 'S' { + if name == ""SE"" { + symbol = ""Se"" + } else { + symbol = ""S"" + } + } else if name[0:2] == ""ZN"" { + symbol = ""Zn"" + } + if symbol == """" { + return name, CError{fmt.Sprintf(""Couldn't guess symbol from PDB name. Will set the 'symbol' field to the name %s"", name), []string{""symbolFromName""}} + } + return symbol, nil +} + +// read_full_pdb_line parses a valid ATOM or HETATM line of a PDB file, returns an Atom +// object with the info except for the coordinates and b-factors, which are returned +// separately as an array of 3 float64 and a float64, respectively +func read_full_pdb_line(line string, read_additional bool, contlines int) (*Atom, []float64, float64, error) { + err := make([]error, 7, 7) //accumulate errors to check at the end of the readed line. + coords := make([]float64, 3, 3) + atom := new(Atom) + atom.Het = strings.HasPrefix(line, ""HETATM"") //this is called twice in the worst case. should fix + atom.ID, err[0] = strconv.Atoi(strings.TrimSpace(line[6:12])) + atom.Name = strings.TrimSpace(line[12:16]) + atom.Char16 = line[16] + //PDB says that pos. 17 is for other thing but I see that is + //used for residue name in many cases*/ + atom.MolName = line[17:20] + atom.MolName1 = three2OneLetter[atom.MolName] + atom.Chain = string(line[21]) + atom.MolID, err[1] = strconv.Atoi(strings.TrimSpace(line[22:30])) + //Here we shouldn't need TrimSpace, but I keep it just in case someone + // doesn's use all the fields when writting a PDB*/ + coords[0], err[2] = strconv.ParseFloat(strings.TrimSpace(line[30:38]), 64) + coords[1], err[3] = strconv.ParseFloat(strings.TrimSpace(line[38:46]), 64) + coords[2], err[4] = strconv.ParseFloat(strings.TrimSpace(line[46:54]), 64) + var bfactor float64 + //Every correct PDB should include occupancy and b-factor, but _of course_ writing + //correct PDBs is too hard for some programs (and by ""some programs"" I mean OPLS LigParGen. Get it together, guys). + //so I add this conditional to allow goChem to still read these wrong PDB files. + if len(line) >= 60 { + atom.Occupancy, err[5] = strconv.ParseFloat(strings.TrimSpace(line[54:60]), 64) + bfactor, err[6] = strconv.ParseFloat(strings.TrimSpace(line[60:66]), 64) + } + //we try to read the additional only if indicated and if it is there + // In this part we don't catch errors. If something is missing we + // just ommit it + if read_additional && len(line) >= 79 { + atom.Symbol = strings.TrimSpace(line[76:78]) + atom.Symbol = strings.Title(strings.ToLower(atom.Symbol)) + if len(line) >= 80 { + var errcharge error + atom.Charge, errcharge = strconv.ParseFloat(strings.TrimSpace(line[78:78]), 64) + if errcharge == nil { + + if strings.Contains(line[79:79], ""-"") { + atom.Charge = -1.0 * atom.Charge + } + } else { + //we dont' report an error here, just set the charge to 0 (the default) + atom.Charge = 0.0 + } + } + } + + //This part tries to guess the symbol from the atom name, if it has not been read + //No error checking here, just fills symbol with the empty string the function returns + var symbolerr error + if len(atom.Symbol) == 0 { + atom.Symbol, symbolerr = symbolFromName(atom.Name) + } + + for i := range err { + if err[i] != nil { + //Here I should add the line number to the returned error. + return nil, nil, 0, CError{err[i].Error(), []string{""strconv.Atoi/ParseFloat"", ""read_full_pdb_line""}} + } + } + if atom.Symbol != """" { + atom.Mass = symbolMass[atom.Symbol] //Not error checking + } + //if we couldn't read the symbol, we'll still return the atom and coords + //but with an error + return atom, coords, bfactor, symbolerr +} + +// read_onlycoords_pdb_line parses an ATOM/HETATM PDB line returning only the coordinates and b-factors +func read_onlycoords_pdb_line(line string, contlines int) ([]float64, float64, error) { + coords := make([]float64, 3, 3) + err := make([]error, 4, 4) + var bfactor float64 + coords[0], err[0] = strconv.ParseFloat(strings.TrimSpace(line[30:38]), 64) + coords[1], err[1] = strconv.ParseFloat(strings.TrimSpace(line[38:46]), 64) + coords[2], err[2] = strconv.ParseFloat(strings.TrimSpace(line[46:54]), 64) + bfactor, err[3] = strconv.ParseFloat(strings.TrimSpace(line[60:66]), 64) + for i := range err { + if err[i] != nil { + //Here I should add the line number to the returned error. + return nil, 0, CError{err[i].Error(), []string{""strconv.ParseFloat"", ""read_onlycoords_pdb_line""}} + + } + } + return coords, bfactor, nil +} + +// PDBRRead reads a pdb file from an io.Reader. Returns a Molecule. If there is one frame in the PDB +// the coordinates array will be of lenght 1. It also returns an error which is not +// really well set up right now. +// read_additional is now ""deprecated"", it will be set to true regardless. I have made it into +func PDBRead(pdb io.Reader, read_additional ...bool) (*Molecule, error) { + bufiopdb := bufio.NewReader(pdb) + mol, err := pdbBufIORead(bufiopdb, read_additional...) + return mol, errDecorate(err, ""PDBReaderREad"") +} + +// PDBFileRead reads a pdb file from an io.Reader. Returns a Molecule. If there is one frame in the PDB +// the coordinates array will be of lenght 1. It also returns an error which is not +// really well set up right now. read_additional is now deprecated. The reader will just read +func PDBFileRead(pdbname string, read_additional ...bool) (*Molecule, error) { + pdbfile, err := os.Open(pdbname) + if err != nil { + //fmt.Println(""Unable to open file!!"") + return nil, err + } + defer pdbfile.Close() + pdb := bufio.NewReader(pdbfile) + mol, err := pdbBufIORead(pdb, read_additional...) + return mol, err +} + +// pdbBufIORead reads the atomic entries for a PDB bufio.IO, reads a pdb file from an io.Reader. +// Returns a Molecule. If there is one frame in the PDB the coordinates array will be of lenght 1. +// It also returns an error which is not really well set up right now. +// The read_additional_opt allows not reading the last fields of a PDB, if you know they are wrong. +// if true (the default), the fields are read if they are available. Otherwise we attempt to figure +// out the symbol from the atom name, which doesn't always work. +func pdbBufIORead(pdb *bufio.Reader, read_additional_opt ...bool) (*Molecule, error) { + read_additional := true + if len(read_additional_opt) > 0 { + read_additional = read_additional_opt[0] + } + var symbolerrorlogged bool + molecule := make([]*Atom, 0) + modelnumber := 0 //This is the number of frames read + coords := make([][]float64, 1, 1) + coords[0] = make([]float64, 0) + bfactors := make([][]float64, 1, 1) + bfactors[0] = make([]float64, 0) + first_model := true //are we reading the first model? if not we only save coordinates + contlines := 1 //count the lines read to better report errors + for { + line, err := pdb.ReadString('\n') + if err != nil { + //fmt.Println(""PDB reading complete"") /***change this to stderr************/ + break + // contlines++ //count all the lines even if empty. This is unreachable but I'm not sure at this point if it's better this way! goChem does read PDBs correctly as far as I can see. + } + if len(line) < 4 { + continue + } + //here we start actually reading + /*There might be a bug for not copying the string (symbol, name, etc) but just assigning the slice + * which is a reference. Check!*/ + var c = make([]float64, 3, 3) + var bfactemp float64 //temporary bfactor + var atomtmp *Atom + // var foo string // not really needed + if strings.HasPrefix(line, ""ATOM"") || strings.HasPrefix(line, ""HETATM"") { + if !first_model { + c, bfactemp, err = read_onlycoords_pdb_line(line, contlines) + if err != nil { + return nil, errDecorate(err, ""pdbBufIORead"") + } + } else { + atomtmp = new(Atom) + atomtmp, c, bfactemp, err = read_full_pdb_line(line, read_additional, contlines) + if err != nil { + //It would be better to pass this along, but that would create a big mess + //I think, at least for now, I have to just keep it here. + if strings.Contains(err.Error(), ""Couldn't guess symbol from PDB name"") { + if !symbolerrorlogged { //to avoid logging this many times + log.Printf(""Error: %s. If the structure contains coarse-grained beads, this error is meaningless. Will continue"", err.Error()) + symbolerrorlogged = true + } + err = nil + } else { + + return nil, errDecorate(err, ""pdbBufIORead"") + } + } + //atom data other than coords is the same in all models so just read for the first. + molecule = append(molecule, atomtmp) + } + //coords are appended for all the models + //we add the coords to the latest frame of coordinaates + coords[len(coords)-1] = append(coords[len(coords)-1], c[0], c[1], c[2]) + bfactors[len(bfactors)-1] = append(bfactors[len(bfactors)-1], bfactemp) + } else if strings.HasPrefix(line, ""MODEL"") { + modelnumber++ //,_=strconv.Atoi(strings.TrimSpace(line[6:])) + if modelnumber > 1 { //will be one for the first model, 2 for the second. + first_model = false + coords = append(coords, make([]float64, 0)) //new bunch of coords for a new frame + bfactors = append(bfactors, make([]float64, 0)) + } + } + } + //This could be done faster if done in the same loop where the coords are read + //Instead of having another loop just for them. + top := NewTopology(0, 1, molecule) + var err error + frames := len(coords) + mcoords := make([]*v3.Matrix, frames, frames) //Final thing to return + for i := 0; i < frames; i++ { + mcoords[i], err = v3.NewMatrix(coords[i]) + if err != nil { + return nil, errDecorate(err, ""pdbBufIORead"") + } + } + //if something happened during the process + if err != nil { + return nil, errDecorate(err, ""pdbBufIORead"") + } + returned, err := NewMolecule(mcoords, top, bfactors) + return returned, errDecorate(err, ""pdbBufIORead"") +} + +//End PDB_read family + +// correctBfactors check that coords and bfactors have the same number of elements. +func correctBfactors(coords []*v3.Matrix, bfactors [][]float64) bool { + if len(coords) != len(bfactors) || bfactors == nil { + return false + } + for key, coord := range coords { + cr, _ := coord.Dims() + br := len(bfactors[key]) + if cr != br { + return false + } + } + return true +} + +// writePDBLine writes a line in PDB format from the data passed as a parameters. It takes the chain of the previous atom +// and returns the written line, the chain of the just-written atom, and error or nil. +func writePDBLine(atom *Atom, coord *v3.Matrix, bfact float64, chainprev string) (string, string, error) { + var ter string + var out string + if atom.Chain != chainprev { + ter = fmt.Sprint(out, ""TER\n"") + chainprev = atom.Chain + } + first := ""ATOM"" + if atom.Het { + first = ""HETATM"" + } + formatstring := ""%-6s%5d %-3s %-4s%1s%4d %8.3f%8.3f%8.3f%6.2f%6.2f %2s \n"" + //4 chars for the atom name are used when hydrogens are included. + //This has not been tested + if len(atom.Name) == 4 { + formatstring = strings.Replace(formatstring, ""%-3s "", ""%-4s"", 1) + } else if len(atom.Name) > 4 { + return """", chainprev, CError{""Cant print PDB line"", []string{""writePDBLine""}} + } + //""%-6s%5d %-3s %3s %1c%4d %8.3f%8.3f%8.3f%6.2f%6.2f %2s \n"" + out = fmt.Sprintf(formatstring, first, atom.ID, atom.Name, atom.MolName, atom.Chain, + atom.MolID, coord.At(0, 0), coord.At(0, 1), coord.At(0, 2), atom.Occupancy, bfact, atom.Symbol) + out = strings.Join([]string{ter, out}, """") + return out, chainprev, nil +} + +// PDBFileWrite writes a PDB for the molecule mol and the coordinates Coords to a file name pdbname. +func PDBFileWrite(pdbname string, coords *v3.Matrix, mol Atomer, Bfactors []float64) error { + out, err := os.Create(pdbname) + if err != nil { + return CError{err.Error(), []string{""os.Create"", ""PDBFileWrite""}} + } + defer out.Close() + fmt.Fprintf(out, ""REMARK WRITTEN WITH GOCHEM :-) \n"") + err = PDBWrite(out, coords, mol, Bfactors) + if err != nil { + return errDecorate(err, ""PDBFileWrite"") + } + return nil +} + +// PDBWrite writes a PDB formatted sequence of bytes to an io.Writer for a given reference, coordinate set and bfactor set, which must match each other. Returns error or nil. +func PDBWrite(out io.Writer, coords *v3.Matrix, mol Atomer, bfact []float64) error { + err := pdbWrite(out, coords, mol, bfact) + if err != nil { + errDecorate(err, ""PDBWrite"") + } + _, err = out.Write([]byte{'\n'}) //This function is just a wrapper to add the newline to what pdbWrite does. + if err != nil { + return CError{""Failed to write in io.Writer"", []string{""io.Write.Write"", ""PDBWrite""}} + + } + return nil +} + +func pdbWrite(out io.Writer, coords *v3.Matrix, mol Atomer, bfact []float64) error { + if bfact == nil { + bfact = make([]float64, mol.Len()) + } + cr, _ := coords.Dims() + br := len(bfact) + if cr != mol.Len() || cr != br { + return CError{""Ref and Coords and/or Bfactors dont have the same number of atoms"", []string{""pdbWrite""}} + } + chainprev := mol.Atom(0).Chain //this is to know when the chain changes. + var outline string + var err error + iowriteError := func(err error) error { + return CError{""Failed to write in io.Writer"" + err.Error(), []string{""io.Write.Write"", ""pdbWrite""}} + } + for i := 0; i < mol.Len(); i++ { + // r,c:=coords.Dims() + // fmt.Println(""IIIIIIIIIIIi"", i,coords,r,c, ""lllllll"") + writecoord := coords.VecView(i) + outline, chainprev, err = writePDBLine(mol.Atom(i), writecoord, bfact[i], chainprev) + if err != nil { + return errDecorate(err, ""pdbWrite ""+fmt.Sprintf(""Could not print PDB line: %d"", i)) + } + _, err := out.Write([]byte(outline)) + if err != nil { + return iowriteError(err) + } + } + _, err = out.Write([]byte(""TER\n"")) // New Addition, should help to recognize the end of the chain. + _, err = out.Write([]byte(""END"")) //no newline, this is in case the write is part of a PDB and one needs to write ""ENDMDEL"". + if err != nil { + return iowriteError(err) + } + return nil +} + +// PDBStringWrite writes a string in PDB format for a given reference, coordinate set and bfactor set, which must match each other +// returns the written string and error or nil. +func PDBStringWrite(coords *v3.Matrix, mol Atomer, bfact []float64) (string, error) { + if bfact == nil { + bfact = make([]float64, mol.Len()) + } + cr, _ := coords.Dims() + br := len(bfact) + if cr != mol.Len() || cr != br { + return """", CError{""Ref and Coords and/or Bfactors dont have the same number of atoms"", []string{""PDBStringWrite""}} + } + chainprev := mol.Atom(0).Chain //this is to know when the chain changes. + var outline string + var outstring string + var err error + for i := 0; i < mol.Len(); i++ { + // r,c:=coords.Dims() + // fmt.Println(""IIIIIIIIIIIi"", i,coords,r,c, ""lllllll"") + writecoord := coords.VecView(i) + outline, chainprev, err = writePDBLine(mol.Atom(i), writecoord, bfact[i], chainprev) + if err != nil { + return """", errDecorate(err, ""PDBStringWrite ""+fmt.Sprintf(""Could not print PDB line: %d"", i)) + } + outstring = strings.Join([]string{outstring, outline}, """") + } + outstring = strings.Join([]string{outstring, ""END\n""}, """") + return outstring, nil +} + +// MultiPDBWrite writes a multiPDB for the molecule mol and the various coordinate sets in CandB, to the io.Writer given. +// CandB is a list of lists of *matrix.DenseMatrix. If it has 2 elements or more, the second will be used as +// Bfactors. If it has one element, all b-factors will be zero. +// Returns an error if fails, or nil if succeeds. +func MultiPDBWrite(out io.Writer, Coords []*v3.Matrix, mol Atomer, Bfactors [][]float64) error { + if !correctBfactors(Coords, Bfactors) { + Bfactors = make([][]float64, len(Coords), len(Coords)) + } + iowriterError := func(err error) error { + return CError{""Failed to write in io.Writer"" + err.Error(), []string{""io.Writer.Write"", ""MultiPDBWrite""}} + } + + _, err := out.Write([]byte(""REMARK WRITTEN WITH GOCHEM :-)"")) //The model number starts with one + if err != nil { + return iowriterError(err) + } + //OK now the real business. + for j := range Coords { + _, err := out.Write([]byte(fmt.Sprintf(""MODEL %d\n"", j+1))) //The model number starts with one + if err != nil { + return iowriterError(err) + } + err = pdbWrite(out, Coords[j], mol, Bfactors[j]) + if err != nil { + return errDecorate(err, ""MultiPDBWrite"") + } + _, err = out.Write([]byte(""MDL\n"")) + if err != nil { + return iowriterError(err) + } + + } + + _, err = out.Write([]byte(""END\n"")) + if err != nil { + return iowriterError(err) + } + + return nil +} + +/***End of PDB part***/ + +// XYZFileRead Reads an xyz or multixyz file (as produced by Turbomole). Returns a Molecule and error or nil. +func XYZFileRead(xyzname string) (*Molecule, error) { + xyzfile, err := os.Open(xyzname) + if err != nil { + //fmt.Println(""Unable to open file!!"") + return nil, CError{err.Error(), []string{""os.Open"", ""XYZFileRead""}} + } + defer xyzfile.Close() + mol, err := XYZRead(xyzfile) + if err != nil { + err = errDecorate(err, ""XYZFileRead ""+fmt.Sprintf(strings.Join([]string{""error in file "", xyzname}, """"))) + } + return mol, err + +} + +// XYZRead Reads an xyz or multixyz formatted bufio.Reader (as produced by Turbomole). Returns a Molecule and error or nil. +func XYZRead(xyzp io.Reader) (*Molecule, error) { + snaps := 1 + xyz := bufio.NewReader(xyzp) + var err error + var top *Topology + var molecule []*Atom + Coords := make([]*v3.Matrix, 1, 1) + Data := make([]string, 1, 1) + + for { + //When we read the first snapshot we collect also the topology data, later + //only coords are collected. + if snaps == 1 { + Coords[0], molecule, Data[0], err = xyzReadSnap(xyz, nil, true) + if err != nil { + return nil, errDecorate(err, ""XYZRead"") + } + top = NewTopology(0, 1, molecule) + if err != nil { + return nil, errDecorate(err, ""XYZRead"") + } + snaps++ + continue + } + tmpcoords, _, data, err := xyzReadSnap(xyz, nil, false) + if err != nil { + //An error here simply means that there are no more snapshots + errm := err.Error() + if strings.Contains(errm, ""Empty"") || strings.Contains(errm, ""header"") { + err = nil + break + } + return nil, errDecorate(err, ""XYZRead"") + } + Coords = append(Coords, tmpcoords) + Data = append(Data, data) + } + bfactors := make([][]float64, len(Coords), len(Coords)) + for key, _ := range bfactors { + bfactors[key] = make([]float64, top.Len()) + } + returned, err := NewMolecule(Coords, top, bfactors) + returned.XYZFileData = Data + return returned, errDecorate(err, ""XYZRead"") +} + +// XYZTraj is a trajectory-like representation of an XYZ File. +type XYZTraj struct { + natoms int + xyz *bufio.Reader //The DCD file + frames int + xyzfile *os.File + readable bool + comments []string + firstframe *v3.Matrix +} + +// Readable returns true if the trajectory is fit to be read, false otherwise. +func (X *XYZTraj) Readable() bool { + return X.readable +} + +func (X *XYZTraj) Len() int { + return X.natoms +} + +func (X *XYZTraj) NComments(i int) int { + return len(X.comments) +} + +// Returns the 'comment' (second line) for the ith (zero-based) frame, or for the last frame if i<0 +func (X *XYZTraj) Comment(i int) string { + if i < 0 { + i = len(X.comments) - 1 + } + return X.comments[i] +} + +// xyztrajerror returns a LastFrameError if the given error message contains certain keywords. +// otherwise, returns the original error. +func (X *XYZTraj) xyztrajerror(err error) error { + errm := err.Error() + X.xyzfile.Close() + X.readable = false + if strings.Contains(errm, ""Empty"") || strings.Contains(errm, ""header"") { + return newlastFrameError("""", X.frames) + } else { + return err + } + +} + +// Next reads the next snapshot of the trajectory into coords, or discards it, if coords +// is nil. It can take a box slice of floats, but won't do anything with it +// (only for compatibility with the Traj interface). +func (X *XYZTraj) Next(coords *v3.Matrix, box ...[]float64) error { + if coords == nil { + _, _, data, err := xyzReadSnap(X.xyz, coords, false) + if err != nil { + //An error here probably means that there are no more snapshots + return X.xyztrajerror(err) + } + X.comments = append(X.comments, data) + X.frames++ + return nil + } + if X.frames == 0 { + coords.Copy(X.firstframe) //slow, but I don't want to mess with the pointer I got. + X.frames++ + X.firstframe = nil + return nil + } + + _, _, data, err := xyzReadSnap(X.xyz, coords, false) + if err != nil { + //An error here probably means that there are no more snapshots + return X.xyztrajerror(err) + } + X.comments = append(X.comments, data) + X.frames++ + return err +} + +// Reads a multi-xyz file. Returns the first snapshot as a molecule, and the other ones as a XYZTraj +func XYZFileAsTraj(xyzname string) (*Molecule, *XYZTraj, error) { + xyzfile, err := os.Open(xyzname) + if err != nil { + //fmt.Println(""Unable to open file!!"") + return nil, nil, CError{err.Error(), []string{""os.Open"", ""XYZFileRead""}} + } + xyz := bufio.NewReader(xyzfile) + //the molecule first + coords, atoms, data, err := xyzReadSnap(xyz, nil, true) + top := NewTopology(0, 1, atoms) + bfactors := make([][]float64, 1, 1) + bfactors[0] = make([]float64, top.Len()) + returned, err := NewMolecule([]*v3.Matrix{coords}, top, bfactors) + //now the traj + traj := new(XYZTraj) + traj.xyzfile = xyzfile + traj.xyz = xyz + traj.natoms = returned.Len() + traj.readable = true + traj.firstframe = coords + traj.comments = append(traj.comments, data) + return returned, traj, nil +} + +// xyzReadSnap reads an xyz file snapshot from a bufio.Reader, returns a slice of Atom +// objects, which will be nil if ReadTopol is false, +// a slice of matrix.DenseMatrix and an error or nil. +func xyzReadSnap(xyz *bufio.Reader, toplace *v3.Matrix, ReadTopol bool) (*v3.Matrix, []*Atom, string, error) { + line, err := xyz.ReadString('\n') + if err != nil { + return nil, nil, """", CError{fmt.Sprintf(""Empty XYZ File: %s"", err.Error()), []string{""bufio.Reader.ReadString"", ""xyzReadSnap""}} + } + natoms, err := strconv.Atoi(strings.TrimSpace(line)) + if err != nil { + return nil, nil, """", CError{fmt.Sprintf(""Wrong header for an XYZ file %s"", err.Error()), []string{""strconv.Atoi"", ""xyzReadSnap""}} + } + var molecule []*Atom + if ReadTopol { + molecule = make([]*Atom, natoms, natoms) + } + var coords []float64 + if toplace == nil { + coords = make([]float64, natoms*3, natoms*3) + } else { + coords = toplace.RawSlice() + } + data, err := xyz.ReadString('\n') //The text in ""data"" could be anything, including just ""\n"" + if err != nil { + return nil, nil, """", CError{fmt.Sprintf(""Ill formatted XYZ file: %s"", err.Error()), []string{""bufio.Reader.ReadString"", ""xyzReadSnap""}} + + } + errs := make([]error, 3, 3) + for i := 0; i < natoms; i++ { + line, errs[0] = xyz.ReadString('\n') + if errs[0] != nil { //inefficient, (errs[1] can be checked once before), but clearer. + if strings.Contains(errs[0].Error(), ""EOF"") && i == natoms-1 { //This allows that an XYZ ends without a newline + errs[0] = nil + } else { + break + } + } + fields := strings.Fields(line) + if len(fields) < 4 { + errs[0] = fmt.Errorf(""Line number %d ill formed: %s"", i, line) + break + } + if ReadTopol { + molecule[i] = new(Atom) + molecule[i].Symbol = strings.Title(fields[0]) + molecule[i].Mass = symbolMass[molecule[i].Symbol] + molecule[i].MolName = ""UNK"" + molecule[i].Name = molecule[i].Symbol + } + coords[i*3], errs[0] = strconv.ParseFloat(fields[1], 64) + coords[i*3+1], errs[1] = strconv.ParseFloat(fields[2], 64) + coords[i*3+2], errs[2] = strconv.ParseFloat(fields[3], 64) + } + //This could be done faster if done in the same loop where the coords are read + //Instead of having another loop just for them. + for _, i := range errs { + if i != nil { + // fmt.Println(""line"", line, k) + return nil, nil, """", CError{i.Error(), []string{""strconv.ParseFloat"", ""xyzReadSnap""}} + } + } + //this should be fine even if I had a toplace matrix. Both toplace and mcoord should just point to the same data. + mcoords, err := v3.NewMatrix(coords) + return mcoords, molecule, data, errDecorate(err, ""xyzReadSnap"") +} + +// XYZWrite writes the mol Ref and the Coord coordinates in an XYZ file with name xyzname which will +// be created fot that. If the file exist it will be overwritten. +func XYZFileWrite(xyzname string, Coords *v3.Matrix, mol Atomer) error { + out, err := os.Create(xyzname) + if err != nil { + return CError{err.Error(), []string{""os.Create"", ""XYZFileWrite""}} + } + defer out.Close() + err = XYZWrite(out, Coords, mol) + if err != nil { + return errDecorate(err, ""XYZFileWrite"") + } + return nil +} + +// XYZStringWrite writes the mol Ref and the Coord coordinates in an XYZ-formatted string. +func XYZStringWrite(Coords *v3.Matrix, mol Atomer) (string, error) { + var out string + if mol.Len() != Coords.NVecs() { + return """", CError{""Ref and Coords dont have the same number of atoms"", []string{""XYZStringWrite""}} + } + c := make([]float64, 3, 3) + out = fmt.Sprintf(""%-4d\n\n"", mol.Len()) + //towrite := Coords.Arrays() //An array of array with the data in the matrix + for i := 0; i < mol.Len(); i++ { + //c := towrite[i] //coordinates for the corresponding atoms + c = Coords.Row(c, i) + temp := fmt.Sprintf(""%-2s %12.6f%12.6f%12.6f \n"", mol.Atom(i).Symbol, c[0], c[1], c[2]) + out = strings.Join([]string{out, temp}, """") + } + return out, nil +} + +// XYZWrite writes the mol Ref and the Coords coordinates to a io.Writer, in the XYZ format. +func XYZWrite(out io.Writer, Coords *v3.Matrix, mol Atomer) error { + iowriterError := func(err error) error { + return CError{""Failed to write in io.Writer"" + err.Error(), []string{""io.Writer.Write"", ""XYZWrite""}} + } + if mol.Len() != Coords.NVecs() { + return CError{""Ref and Coords dont have the same number of atoms"", []string{""XYZWrite""}} + } + c := make([]float64, 3, 3) + _, err := out.Write([]byte(fmt.Sprintf(""%-4d\n\n"", mol.Len()))) + if err != nil { + return iowriterError(err) + } + //towrite := Coords.Arrays() //An array of array with the data in the matrix + for i := 0; i < mol.Len(); i++ { + //c := towrite[i] //coordinates for the corresponding atoms + c = Coords.Row(c, i) + temp := fmt.Sprintf(""%-2s %12.6f%12.6f%12.6f \n"", mol.Atom(i).Symbol, c[0], c[1], c[2]) + _, err := out.Write([]byte(temp)) + if err != nil { + return iowriterError(err) + } + } + return nil +} + +// GroFileRead reads a file in the Gromacs gro format, returning a molecule. +func GroFileRead(groname string) (*Molecule, error) { + grofile, err := os.Open(groname) + if err != nil { + //fmt.Println(""Unable to open file!!"") + return nil, CError{err.Error(), []string{""os.Open"", ""GroFileRead""}} + } + defer grofile.Close() + snaps := 1 + gro := bufio.NewReader(grofile) + var top *Topology + var molecule []*Atom + Coords := make([]*v3.Matrix, 1, 1) + + for { + //When we read the first snapshot we collect also the topology data, later + //only coords are collected. + if snaps == 1 { + Coords[0], molecule, err = groReadSnap(gro, true) + if err != nil { + return nil, errDecorate(err, ""GroFileRead"") + } + top = NewTopology(0, 1, molecule) + if err != nil { + return nil, errDecorate(err, ""GroFileRead"") + } + snaps++ + continue + } + //fmt.Println(""how manytimes?"") ///////////////////// + tmpcoords, _, err := groReadSnap(gro, false) + if err != nil { + break //We just ignore errors after the first snapshot, and simply read as many snapshots as we can. + /* + //An error here may just mean that there are no more snapshots + errm := err.Error() + if strings.Contains(errm, ""Empty"") || strings.Contains(errm, ""EOF"") { + err = nil + break + } + return nil, errDecorate(err, ""GroRead"") + */ + } + Coords = append(Coords, tmpcoords) + } + returned, err := NewMolecule(Coords, top, nil) + // fmt.Println(""2 return!"", top.Atom(1), returned.Coords[0].VecView(2)) /////////////////////// + return returned, errDecorate(err, ""GroRead"") +} + +func groReadSnap(gro *bufio.Reader, ReadTopol bool) (*v3.Matrix, []*Atom, error) { + nm2A := 10.0 + chains := ""ABCDEFGHIJKLMNOPQRSTUVWXYZ"" + line, err := gro.ReadString('\n') //we don't care about this line,but it has to be there + if err != nil { + return nil, nil, CError{fmt.Sprintf(""Empty gro File: %s"", err.Error()), []string{""bufio.Reader.ReadString"", ""groReadSnap""}} + } + line, err = gro.ReadString('\n') + if err != nil { + return nil, nil, CError{fmt.Sprintf(""Malformed gro File: %s"", err.Error()), []string{""bufio.Reader.ReadString"", ""groReadSnap""}} + } + + natoms, err := strconv.Atoi(strings.TrimSpace(line)) + if err != nil { + return nil, nil, CError{fmt.Sprintf(""Wrong header for a gro file %s"", err.Error()), []string{""strconv.Atoi"", ""groReadSnap""}} + } + var molecule []*Atom + if ReadTopol { + molecule = make([]*Atom, 0, natoms) + } + coords := make([]float64, 0, natoms*3) + prevres := 0 + chainindex := 0 + for i := 0; i < natoms; i++ { + line, err = gro.ReadString('\n') + if err != nil { + return nil, nil, CError{fmt.Sprintf(""Failure to read gro File: %s"", err.Error()), []string{""bufio.Reader.ReadString"", ""groReadSnap""}} + } + fields := strings.Fields(line) + if len(fields) < 4 { + break //meaning this line contains the unit cell vectors, and it is the last line of the snapshot + } + if ReadTopol { + atom, c, err := read_gro_line(line) + if err != nil { + return nil, nil, CError{fmt.Sprintf(""Failure to read gro File: %s"", err.Error()), []string{""bufio.Reader.ReadString"", ""groReadSnap""}} + } + if atom.MolID < prevres { + chainindex++ + } + prevres = atom.MolID + if chainindex >= len(chains) { + chainindex = 0 //more chains inthe molecule than letters in the alphabet! + } + atom.Chain = string(chains[chainindex]) + molecule = append(molecule, atom) + coords = append(coords, c...) + // fmt.Println(atom, c) ////////////////// + continue + + } + c := make([]float64, 3, 3) + for i := 0; i < 3; i++ { + c[i], err = strconv.ParseFloat(strings.TrimSpace(line[20+(i*8):28+(i*8)]), 64) + if err != nil { + return nil, nil, err + } + c[i] = c[i] * nm2A //gro uses nm, goChem uses A. + } + coords = append(coords, c...) + + } + mcoords, err := v3.NewMatrix(coords) + // fmt.Println(molecule) //, mcoords) //////////////////////// + return mcoords, molecule, nil +} + +// read_gro_line Parses a valid ATOM or HETATM line of a PDB file, returns an Atom +// object with the info except for the coordinates and b-factors, which are returned +// separately as an array of 3 float64 and a float64, respectively +func read_gro_line(line string) (*Atom, []float64, error) { + coords := make([]float64, 3, 3) + atom := new(Atom) + nm2A := 10.0 + var err error + atom.MolID, err = strconv.Atoi(strings.TrimSpace(line[0:5])) + if err != nil { + return nil, nil, err + } + atom.MolName = strings.TrimSpace(line[5:10]) + atom.MolName1 = three2OneLetter[atom.MolName] + atom.Name = strings.TrimSpace(line[10:15]) + atom.ID, err = strconv.Atoi(strings.TrimSpace(line[15:20])) + // fmt.Printf(""%s|%s|%s|%s|\n"", line[0:5], line[5:10], line[10:15], line[15:20]) //////////// + if err != nil { + return nil, nil, err + } + for i := 0; i < 3; i++ { + coords[i], err = strconv.ParseFloat(strings.TrimSpace(line[20+(i*8):28+(i*8)]), 64) + if err != nil { + return nil, nil, err + } + coords[i] = coords[i] * nm2A //gro uses nm, goChem uses A. + } + + atom.Symbol, _ = symbolFromName(atom.Name) + return atom, coords, nil +} + +// GoFileWrite writes the molecule described by mol and Coords into a file in the Gromacs +// gro format. If Coords has more than one elements, it will write a multi-state file. +func GroFileWrite(outname string, Coords []*v3.Matrix, mol Atomer) error { + out, err := os.Create(outname) + if err != nil { + return CError{""Failed to write open file"" + err.Error(), []string{""os.Create"", ""GroFileWrite""}} + } + defer out.Close() + for _, v := range Coords { + err := GroSnapWrite(v, mol, out) + if err != nil { + return errDecorate(err, ""GoFileWrite"") + } + } + return nil +} + +// GroSnapWrite writes a single snapshot of a molecule to an io.Writer, in the Gro format. +func GroSnapWrite(coords *v3.Matrix, mol Atomer, out io.Writer) error { + A2nm := 0.1 + iowriterError := func(err error) error { + return CError{""Failed to write in io.Writer"" + err.Error(), []string{""io.Writer.Write"", ""GroSnapWrite""}} + } + if mol.Len() != coords.NVecs() { + return CError{""Ref and Coords dont have the same number of atoms"", []string{""GroSnapWrite""}} + } + c := make([]float64, 3, 3) + _, err := out.Write([]byte(fmt.Sprintf(""Written with goChem :-)\n%-4d\n"", mol.Len()))) + if err != nil { + return iowriterError(err) + } + //towrite := Coords.Arrays() //An array of array with the data in the matrix + for i := 0; i < mol.Len(); i++ { + //c := towrite[i] //coordinates for the corresponding atoms + c = coords.Row(c, i) + at := mol.Atom(i) + //velocities are set to 0 + temp := fmt.Sprintf(""%5d%-5s%5s%5d%8.3f%8.3f%8.3f%8.4f%8.4f%8.4f\n"", at.MolID, at.MolName, at.Name, at.ID, c[0]*A2nm, c[1]*A2nm, c[2]*A2nm, 0.0, 0.0, 0.0) + _, err := out.Write([]byte(temp)) + if err != nil { + return iowriterError(err) + } + + } + //the box vectors at the end of the snappshot + _, err = out.Write([]byte(""0.0 0.0 0.0\n"")) + if err != nil { + return iowriterError(err) + } + return nil +} +","Go" +"Computational Biochemistry","rmera/gochem","geometric.go",".go","26534","758","/* + * geometric.go, part of gochem + * + * Copyright 2012 Raul Mera + * + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 2.1 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + * +*/ + +package chem + +import ( + ""fmt"" + ""math"" + ""sort"" + + v3 ""github.com/rmera/gochem/v3"" + ""gonum.org/v1/gonum/mat"" +) + +//NOTE: For many of these functions we could ask for a buffer vector in the arguments in order to reduce +//memory allocation. + +// Angle takes 2 vectors and calculate the angle in radians between them +// It does not check for correctness or return errors! +func Angle(v1, v2 *v3.Matrix) float64 { + normproduct := v1.Norm(2) * v2.Norm(2) + dotprod := v1.Dot(v2) + argument := dotprod / normproduct + //Take care of floating point math errors + if math.Abs(argument-1) <= appzero { + argument = 1 + } else if math.Abs(argument+1) <= appzero { + argument = -1 + } + //fmt.Println(dotprod/normproduct,argument) //dotprod/normproduct, dotprod, normproduct,v1.TwoNorm(),v2.TwoNorm()) + angle := math.Acos(argument) + if math.Abs(angle) <= appzero { + return 0.00 + } + return angle +} + +// RotatorAroundZToNewY takes a set of coordinates (mol) and a vector (y). It returns +// a rotation matrix that, when applied to mol, will rotate it around the Z axis +// in such a way that the projection of newy in the XY plane will be aligned with +// the Y axis. +func RotatorAroundZToNewY(newy *v3.Matrix) (*v3.Matrix, error) { + nr, nc := newy.Dims() + if nc != 3 || nr != 1 { + return nil, CError{""Wrong newy vector"", []string{""RotatorAroundZtoNewY""}} + } + if nc != 3 { + return nil, CError{""Wrong mol vector"", []string{""RotatorAroundZtoNewY""}} //this one doesn't seem reachable + + } + gamma := math.Atan2(newy.At(0, 0), newy.At(0, 1)) + singamma := math.Sin(gamma) + cosgamma := math.Cos(gamma) + operator := []float64{cosgamma, singamma, 0, + -singamma, cosgamma, 0, + 0, 0, 1} + return v3.NewMatrix(operator) + +} + +// RotatorAroundZ returns an operator that will rotate a set of +// coordinates by gamma radians around the z axis. +func RotatorAroundZ(gamma float64) (*v3.Matrix, error) { + singamma := math.Sin(gamma) + cosgamma := math.Cos(gamma) + operator := []float64{cosgamma, singamma, 0, + -singamma, cosgamma, 0, + 0, 0, 1} + return v3.NewMatrix(operator) + +} + +// RotatorToNewZ takes a matrix a row vector (newz). +// It returns a linear operator such that, when applied to a matrix mol ( with the operator on the right side) +// it will rotate mol such that the z axis is aligned with newz. +func RotatorToNewZ(newz *v3.Matrix) *v3.Matrix { + r, c := newz.Dims() + if c != 3 || r != 1 { + panic(""Wrong newz vector"") + } + normxy := math.Sqrt(math.Pow(newz.At(0, 0), 2) + math.Pow(newz.At(0, 1), 2)) + theta := math.Atan2(normxy, newz.At(0, 2)) //Around the new y + phi := math.Atan2(newz.At(0, 1), newz.At(0, 0)) //First around z + psi := 0.000000000000 // second around z + sinphi := math.Sin(phi) + cosphi := math.Cos(phi) + sintheta := math.Sin(theta) + costheta := math.Cos(theta) + sinpsi := math.Sin(psi) + cospsi := math.Cos(psi) + operator := []float64{cosphi*costheta*cospsi - sinphi*sinpsi, -sinphi*cospsi - cosphi*costheta*sinpsi, cosphi * sintheta, + sinphi*costheta*cospsi + cosphi*sinpsi, -sinphi*costheta*sinpsi + cosphi*cospsi, sintheta * sinphi, + -sintheta * cospsi, sintheta * sinpsi, costheta} + finalop, _ := v3.NewMatrix(operator) //we are hardcoding opperator so it must have the right dimensions. + return finalop + +} + +// RotatorTranslatorToSuper superimposes the set of cartesian coordinates given as the rows of the matrix test on the gnOnes of the rows +// of the matrix templa. Returns the transformed matrix, the rotation matrix, 2 translation row vectors +// For the superposition plus an error. In order to perform the superposition, without using the transformed +// the first translation vector has to be added first to the moving matrix, then the rotation must be performed +// and finally the second translation has to be added. +// This is a low level function, although one can use it directly since it returns the transformed matrix. +// The math for this function is by Prof. Veronica Jimenez-Curihual, UNAB, Chile. +func RotatorTranslatorToSuper(test, templa *v3.Matrix) (*v3.Matrix, *v3.Matrix, *v3.Matrix, *v3.Matrix, error) { + tmr, tmc := templa.Dims() + tsr, tsc := test.Dims() + if tmr != tsr || tmc != 3 || tsc != 3 { + return nil, nil, nil, nil, CError{""goChem: Ill-formed matrices"", []string{""RotatorTranslatorToSuper""}} + } + var Scal float64 + Scal = float64(1.0) / float64(tmr) + j := gnOnes(tmr, 1) //Mass is not important for this matter so we'll just use this. + ctest, distest, err := MassCenter(test, test, j) + if err != nil { + return nil, nil, nil, nil, errDecorate(err, ""RotatorTranslatorToSuper"") + } + ctempla, distempla, err := MassCenter(templa, templa, j) + if err != nil { + return nil, nil, nil, nil, errDecorate(err, ""RotatorTranslatorToSuper"") + + } + Mid := gnEye(tmr) + jT := gnT(j) + ScaledjProd := gnMul(j, jT) + ScaledjProd.Scale(Scal, ScaledjProd) + aux2 := gnMul(gnT(ctempla), Mid) + r, _ := aux2.Dims() + Maux := v3.Zeros(r) + Maux.Mul(aux2, ctest) + Maux = Maux.TrRet() //Dont understand why this is needed + svd := new(mat.SVD) + if ok := svd.Factorize(v3.Matrix2Dense(Maux), mat.SVDFull); !ok { + return nil, nil, nil, nil, errDecorate(fmt.Errorf(""mat.SVD failed""), ""RotatorTranslatorToSuper"") + } + + //matrix Maux dimensions must be 3x3 + Ud := mat.NewDense(3, 3, make([]float64, 9)) + Vd := mat.NewDense(3, 3, make([]float64, 9)) + svd.UTo(Ud) + svd.VTo(Vd) + U := v3.Dense2Matrix(Ud) //These will panic if the matrices were not 3x3 + V := v3.Dense2Matrix(Vd) + /***** OLD + factors := mat.SVD(v3.Matrix2Dense(Maux), appzero, math.SmallestNonzeroFloat64, true, true) + U := factors.U + V := factors.V + ****/ + // if err != nil { + // return nil, nil, nil, nil, err //I'm not sure what err is this one + // } + U.Scale(-1, U) + V.Scale(-1, V) + //SVD gives different results here than in numpy. U and V are multiplide by -1 in one of them + //and gomatrix gives as V the transpose of the matrix given as V by numpy. I guess is not an + //error, but don't know for sure. + vtr, _ := V.Dims() + Rotation := v3.Zeros(vtr) + Rotation.Mul(V, gnT(U)) + Rotation = Rotation.TrRet() //Don't know why does this work :( + RightHand := gnEye(3) + if det(Rotation) < 0 { + RightHand.Set(2, 2, -1) + Rotation.Mul(V, RightHand) + Rotation.Mul(Rotation, gnT(U)) //If I get this to work Ill arrange so gnT(U) is calculated once, not twice as now. + Rotation.Tr() //TransposeTMP contains the transpose of the original Rotation //Same, no ide why I need this + //return nil, nil, nil, nil, fmt.Errorf(""Got a reflection instead of a translations. The objects may be specular images of each others"") + } + jT.Scale(Scal, jT) + subtempla := v3.Zeros(tmr) + subtempla.Copy(ctempla) + sub := v3.Zeros(ctest.NVecs()) + sub.Mul(ctest, Rotation) + subtempla.Sub(subtempla, sub) + jtr, _ := jT.Dims() + Translation := v3.Zeros(jtr) + Translation.Mul(jT, subtempla) + Translation.Add(Translation, distempla) + //This alings the transformed with the original template, not the mean centrate one + transformed := v3.Zeros(ctest.NVecs()) + transformed.Mul(ctest, Rotation) + transformed.AddVec(transformed, Translation) + //end transformed + distest.Scale(-1, distest) + return transformed, Rotation, distest, Translation, nil +} + +/* +//I keep this just in case I manage to fix it at some point +func rmsd_fail(test, template *matrix.DenseMatrix) (float64, error) { + ctempla := template.Copy() + err := ctempla.Subtract(test) + if err != nil { + return 9999999, err + } + dev := matrix.ParallelProduct(ctempla.Transpose(), ctempla) + RMSDv := dev.Trace() + RMSDv = math.Sqrt(RMSDv) + return RMSDv, nil +} +*/ + +// RMSD calculates the RMSD between test and template, considering only the atoms +// present in the slices of int slices indexes. The first indexes slices will +// be assumed to contain test indexes and the second, template indexes. +// If you give only one, it will be assumed to correspondo to whatever molecule +// that has more atoms than the elements in the slice. The same number of atoms +// has to be considered for superposition in both systems. +// The objects are not superimposed before the calculation. +func RMSD(test, templa *v3.Matrix, indexes ...[]int) (float64, error) { + var L int + if len(indexes) == 0 || indexes[0] == nil || len(indexes[0]) == 0 { + L = test.NVecs() + } else { + L = len(indexes[0]) + } + tmp := v3.Zeros(L) + //We don't test anything in-house. All the testing in done by MemRMSD + rmsd, err := MemRMSD(test, templa, tmp, indexes...) + return rmsd, err +} + +// MemRMSD calculates the RMSD between test and template, considering only the atoms +// present in the slices of int slices indexes. The first indexes slices will +// be assumed to contain test indexes and the second, template indexes. +// If you give only one (it must be the first one), it will be assumed to correspond to whatever molecule +// that has more atoms than the elements in the slice. Giving a nil or 0-lenght first slice and a non-nil second +// slice will cause MemRMSD to not consider neither of them. +// The same number of atoms +// has to be considered for the calculation in both systems. +// It does not superimpose the objects. +// To save memory, it asks for the temporary matrix it needs to be supplied: +// tmp must be Nx3 where N is the number +// of elements in testlst and templalst +// NOTE: This function should ask for 3 tmp matrices, not just 1 +func MemRMSD(test, templa, tmp *v3.Matrix, indexes ...[]int) (float64, error) { + var ctest *v3.Matrix + var ctempla *v3.Matrix + if len(indexes) == 0 || indexes[0] == nil || len(indexes[0]) == 0 { + ctest = test + ctempla = templa + } else if len(indexes) == 1 { + if test.NVecs() > len(indexes[0]) { + ctest = v3.Zeros(len(indexes[0])) + ctest.SomeVecs(test, indexes[0]) + ctempla = templa + } else if templa.NVecs() > len(indexes[0]) { + ctempla = v3.Zeros(len(indexes[0])) + ctempla.SomeVecs(templa, indexes[0]) + } else { + return -1, fmt.Errorf(""chem.memRMSD: Indexes don't match molecules"") + } + } else { + ctest = v3.Zeros(len(indexes[0])) + ctest.SomeVecs(test, indexes[0]) + ctempla = v3.Zeros(len(indexes[1])) + ctempla.SomeVecs(templa, indexes[1]) + } + if ctest.NVecs() != ctempla.NVecs() || tmp.NVecs() != ctest.NVecs() { + return -1, fmt.Errorf(""chem.memRMSD: Ill formed matrices for memRMSD calculation"") + } + tmp.Sub(ctest, ctempla) + rmsd := tmp.Norm(2) + return rmsd / math.Sqrt(float64(ctest.NVecs())), nil + +} + +// MemMSD calculates the MSDs between test and templa, considering only the atoms +// present in the slices of int slices indexes. If given. If only one set of indexes +// is given, it will be assumed to beling to test, if it has less elements than that +// system, or to templa,otherwise. +func MemPerAtomRMSD(test, templa, ctest, ctempla, tmp *v3.Matrix, indexes ...[]int) ([]float64, error) { + if len(indexes) == 0 || indexes[0] == nil || len(indexes[0]) == 0 { + ctest = test + ctempla = templa + } else if len(indexes) == 1 { + if test.NVecs() > len(indexes[0]) { + ctest.SomeVecs(test, indexes[0]) + ctempla = templa + } else if templa.NVecs() > len(indexes[0]) { + ctempla.SomeVecs(templa, indexes[0]) + } else { + return nil, fmt.Errorf(""chem.memMSD: Indexes don't match molecules"") + } + } else { + ctest.SomeVecs(test, indexes[0]) + ctempla.SomeVecs(templa, indexes[1]) + } + if ctest.NVecs() != ctempla.NVecs() || tmp.NVecs() != ctest.NVecs() { + return nil, fmt.Errorf(""chem.memMSD: Ill formed matrices for memMSD calculation: cest: %d ctempla: %d tmp: %d"", ctest.NVecs(), ctempla.NVecs(), tmp.NVecs()) + } + tmp.Sub(ctest, ctempla) + msds := make([]float64, ctest.NVecs()) + for i := 0; i < tmp.NVecs(); i++ { + v := tmp.VecView(i) + msds[i] = v.Norm(2) + } + return msds, nil +} + +// rMSD returns the RSMD (root of the mean square deviation) for the sets of cartesian +// coordinates in test and template, only considering the template and test atoms in +// the lists testlst and templalst, respectively. Since it is very explicit I leave it here for testing. +func rMSD(test, template *v3.Matrix, testlst, templalst []int) (float64, error) { + //This is a VERY naive implementation. + lists := [][]int{testlst, templalst} + var ctest *v3.Matrix + var ctempla *v3.Matrix + if testlst == nil || len(testlst) == 0 { + ctest = test + } else { + ctest = v3.Zeros(len(lists[0])) + ctest.SomeVecs(test, lists[0]) + } + if templalst == nil || len(templalst) == 0 { + ctempla = template + } else { + ctempla = v3.Zeros(len(lists[1])) + ctempla.SomeVecs(template, lists[1]) + } + tmr, tmc := ctempla.Dims() + tsr, tsc := ctest.Dims() + if tmr != tsr || tmc != 3 || tsc != 3 { + return -1, fmt.Errorf(""RMSD: Ill formed matrices for RMSD calculation"") + } + tr := tmr + ctempla2 := v3.Zeros(ctempla.NVecs()) + ctempla2.Copy(ctempla) + //the maybe thing might not be needed since we check the dimensions before. + f := func() { ctempla2.Sub(ctempla2, ctest) } + if err := gnMaybe(gnPanicker(f)); err != nil { + return -1, CError{err.Error(), []string{""v3.Matrix.Sub"", ""RMSD""}} + } + var RMSD float64 + for i := 0; i < ctempla.NVecs(); i++ { + temp := ctempla2.VecView(i) + RMSD += math.Pow(temp.Norm(2), 2) + } + RMSD = RMSD / float64(tr) + RMSD = math.Sqrt(RMSD) + return RMSD, nil +} + +// ImproperAlt calculates the improper dihedral between the points a, b,c,d +// as the angle between the plane defined by a,b,c and the cd vector +func ImproperAlt(a, b, c, d *v3.Matrix) float64 { + all := []*v3.Matrix{a, b, c, d} + for number, point := range all { + pr, pc := point.Dims() + if point == nil { + panic(PanicMsg(fmt.Sprintf(""goChem-Improper: Vector %d is nil"", number))) + } + if pr != 1 || pc != 3 { + panic(PanicMsg(fmt.Sprintf(""goChem-Improper: Vector %d has invalid shape"", number))) + } + } + //bma=b minus a + amb := v3.Zeros(1) + cmb := v3.Zeros(1) + dmc := v3.Zeros(1) + amb.Sub(b, a) + cmb.Sub(c, b) + dmc.Sub(d, c) + plane := cross(amb, cmb) + angle := Angle(plane, dmc) + return math.Pi/2.0 + angle + /* if angle <= math.Pi/2.0 { + + // return math.Pi/2.0 - angle + return math.Pi/2.0 + angle + } else { + //return (angle - math.Pi/2.0) + } + */ +} + +// Improper calculates the improper dihedral between the points a, b,c,d +// as the angle between the plane defined by a,b,c and that defined by the plane bcd +func Improper(a, b, c, d *v3.Matrix) float64 { + all := []*v3.Matrix{a, b, c, d} + for number, point := range all { + pr, pc := point.Dims() + if point == nil { + panic(PanicMsg(fmt.Sprintf(""goChem-Improper: Vector %d is nil"", number))) + } + if pr != 1 || pc != 3 { + panic(PanicMsg(fmt.Sprintf(""goChem-Improper: Vector %d has invalid shape"", number))) + } + } + //bma=b minus a + amb := v3.Zeros(1) + cmb := v3.Zeros(1) + dmc := v3.Zeros(1) + bmc := v3.Zeros(1) + amb.Sub(a, b) //canged from Sub(b,a) + cmb.Sub(c, b) + bmc.Sub(b, c) + dmc.Sub(d, c) + plane1 := cross(amb, cmb) + plane2 := cross(bmc, dmc) + angle := Angle(plane1, plane2) + return angle + /* if angle <= math.Pi/2.0 { + + // return math.Pi/2.0 - angle + return math.Pi/2.0 + angle + } else { + //return (angle - math.Pi/2.0) + } + */ +} + +// DihedralAlt calculates the dihedral between the points a, b, c, d, where the first plane +// is defined by abc and the second by bcd. +// It is exactly the same as Dihedral, only kept for API stability. +func DihedralAlt(a, b, c, d *v3.Matrix) float64 { + return Dihedral(a, b, c, d) +} + +// Dihedral calculates the dihedral between the points a, b, c, d, where the first plane +// is defined by abc and the second by bcd. The ouputs are defined between 0 and pi, so +// it shouldn't be used for Ramachandran angles. Use RamaDihedral for that. +func Dihedral(a, b, c, d *v3.Matrix) float64 { + all := []*v3.Matrix{a, b, c, d} + for number, point := range all { + pr, pc := point.Dims() + if point == nil { + panic(PanicMsg(fmt.Sprintf(""goChem-Dihedral: Vector %d is nil"", number))) + } + if pr != 1 || pc != 3 { + panic(PanicMsg(fmt.Sprintf(""goChem-Dihedral: Vector %d has invalid shape"", number))) + } + } + //bma=b minus a + amb := v3.Zeros(1) + cmb := v3.Zeros(1) + bmc := v3.Zeros(1) + dmc := v3.Zeros(1) + amb.Sub(a, b) + cmb.Sub(c, b) + bmc.Sub(b, c) + dmc.Sub(d, c) + v1 := cross(amb, cmb) + v2 := cross(dmc, bmc) + dihedral := Angle(v1, v2) + // dihedral := math.Atan2(first, second) + return dihedral +} + +// Similar to the Dihedral funcion, obatins the dihedral angle between 2 points. The difference is that the outputs for this functions are defined between -pi and pi, while Dihedral's outputs are defined between 0 and pi. +func DihedralRama(a, b, c, d *v3.Matrix) float64 { + all := []*v3.Matrix{a, b, c, d} + for number, point := range all { + pr, pc := point.Dims() + if point == nil { + panic(PanicMsg(fmt.Sprintf(""goChem-Dihedral: Vector %d is nil"", number))) + } + if pr != 1 || pc != 3 { + panic(PanicMsg(fmt.Sprintf(""goChem-Dihedral: Vector %d has invalid shape"", number))) + } + } + //bma=b minus a + bma := v3.Zeros(1) + cmb := v3.Zeros(1) + dmc := v3.Zeros(1) + bmascaled := v3.Zeros(1) + bma.Sub(b, a) + cmb.Sub(c, b) + dmc.Sub(d, c) + bmascaled.Scale(cmb.Norm(2), bma) + first := bmascaled.Dot(cross(cmb, dmc)) + v1 := cross(bma, cmb) + v2 := cross(cmb, dmc) + second := v1.Dot(v2) + dihedral := math.Atan2(first, second) + return dihedral +} + +/***Shape indicator functions***/ +//const appzero float64 = 0.0000001 //used to correct floating point +//errors. Everything equal or less than this is considered zero. + +//point comparisons + +// RhoShapeIndexes Get shape indices based on the axes of the elipsoid of inertia. +// linear and circular distortion, in that order, and error or nil. +// Based on the work of Taylor et al., .(1983), J Mol Graph, 1, 30 +// This function has NOT been tested thoroughly in the sense of the appropiateness of the indexes definitions. +func RhoShapeIndexes(rhos []float64) (float64, float64, error) { + if rhos == nil || len(rhos) < 3 { + return -1, -1, CError{""goChe: Not enough or nil rhos"", []string{""RhoShapeIndexes""}} + } + // print(rhos[0],rhos[1],rhos[2]) //////////////////////// + // Are these definitions reasonable? + linear_distortion := (1 - (rhos[1] / rhos[0])) * 100 //Prolate + circular_distortion := ((1 - (rhos[2] / rhos[1])) * 100) //Oblate + return linear_distortion, circular_distortion, nil +} + +// Rhos returns the semiaxis of the elipoid of inertia given the the moment of inertia tensor. +func Rhos(momentTensor *v3.Matrix, epsilon ...float64) ([]float64, error) { + var e float64 + if len(epsilon) == 0 { + e = -1 + } else { + e = epsilon[0] + } + _, evals, err := v3.EigenWrap(momentTensor, e) + if err != nil { + return nil, errDecorate(err, ""Rhos"") + } + rhos := sort.Float64Slice{evals[0], evals[1], evals[2]} //invSqrt(evals[0]), invSqrt(evals[1]), invSqrt(evals[2])} + if evals[2] <= appzero { + return rhos[:], CError{""goChem: Molecule colapsed to a single point. Check for blackholes"", []string{""Rhos""}} + } + sort.Sort(rhos[:]) + //This loop reversing loop is almost verbatin from Effective Go + //(http://golang.org/doc/effective_go.html) + for i, j := 0, len(rhos)-1; i < j; i, j = i+1, j-1 { + rhos[i], rhos[j] = rhos[j], rhos[i] + } + return rhos[:], nil +} + +/**Other geometrical**/ + +// BestPlaneP takes sorted evecs, according to the eval,s and returns a row vector that is normal to the +// Plane that best contains the molecule. Notice that the function can't possibly check +// that the vectors are sorted. The P at the end of the name is for Performance. If +// That is not an issue it is safer to use the BestPlane function that wraps this one. +func BestPlaneP(evecs *v3.Matrix) (*v3.Matrix, error) { + evr, evc := evecs.Dims() + if evr != 3 || evc != 3 { + return evecs, CError{""goChem: Eigenvectors matrix must be 3x3"", []string{""BestPlaneP""}} //maybe this should be a panic + } + v1 := evecs.VecView(2) + v2 := evecs.VecView(1) + normal := v3.Zeros(1) + normal.Cross(v1, v2) + return normal, nil +} + +// BestPlane returns a row vector that is normal to the plane that best contains the molecule +// if passed a nil Masser, it will simply set all masses to 1. If more than one Masser is passed +// Only the first will be considered +func BestPlane(coords *v3.Matrix, mol ...Masser) (*v3.Matrix, error) { + var err error + var Mmass []float64 + cr, _ := coords.Dims() + if len(mol) != 0 && mol[0] != nil { + Mmass, err = mol[0].Masses() + if err != nil { + return nil, errDecorate(err, ""BestPlane"") + } + if len(Mmass) != cr { + return nil, CError{fmt.Sprintf(""Inconsistent coordinates(%d)/atoms(%d)"", len(Mmass), cr), []string{""BestPlane""}} + } + } else { + Mmass = nil + } + moment, err := MomentTensor(coords, Mmass) + if err != nil { + return nil, errDecorate(err, ""BestPlane"") + } + evecs, _, err := v3.EigenWrap(moment, appzero) + if err != nil { + return nil, errDecorate(err, ""BestPlane"") + } + normal, err := BestPlaneP(evecs) + if err != nil { + return nil, errDecorate(err, ""BestPlane"") + } + //MomentTensor(, mass) + return normal, err +} + +// returns a float64 slice of the size requested filed with ones +func ones(size int) []float64 { + slice := make([]float64, size, size) + for k, _ := range slice { + slice[k] = 1.0 + } + return slice +} + +// CenterOfMass returns the center of mass the atoms represented by the coordinates in geometry +// and the masses in mass, and an error. If no mass is given, it calculates the geometric center +func CenterOfMass(geometry *v3.Matrix, massS ...*mat.Dense) (*v3.Matrix, error) { + var mass *mat.Dense + if geometry == nil { + return nil, CError{""goChem: nil matrix to get the center of mass"", []string{""CenterOfMass""}} + } + gr, _ := geometry.Dims() + if len(massS) == 0 || massS[0] == nil { //just obtain the geometric center + tmp := ones(gr) + mass = mat.NewDense(gr, 1, tmp) //gnOnes(gr, 1) + } else { + mass = massS[0] + } + tmp2 := ones(gr) + gnOnesvector := mat.NewDense(1, gr, tmp2) //gnOnes(1, gr) + + ref := v3.Zeros(gr) + ref.ScaleByCol(geometry, mass) + ref2 := v3.Zeros(1) + ref2.Mul(gnOnesvector, ref) + ref2.Scale(1.0/mat.Sum(mass), ref2) + return ref2, nil +} + +// MassCenterMem centers in in the center of mass of oref, putting the result in ret. Mass must be +// A column vector. Returns the centered matrix and the displacement matrix. +func MassCenterMem(in, oref, ret *v3.Matrix, massS ...*mat.Dense) (*v3.Matrix, error) { + or, _ := oref.Dims() + var mass *mat.Dense + if len(massS) == 0 || massS[0] == nil { //just obtain the geometric center + tmp := ones(or) + mass = mat.NewDense(or, 1, tmp) //gnOnes(or, 1) + } else { + mass = massS[0] + } + ref := v3.Zeros(or) + ref.Copy(oref) + gnOnesvector := gnOnes(1, or) + f := func() { ref.ScaleByCol(ref, mass) } + if err := gnMaybe(gnPanicker(f)); err != nil { + return nil, CError{err.Error(), []string{""v3.Matrix.ScaleByCol"", ""MassCenter""}} + } + ref2 := v3.Zeros(1) + g := func() { ref2.Mul(gnOnesvector, ref) } + if err := gnMaybe(gnPanicker(g)); err != nil { + return nil, CError{err.Error(), []string{""v3.gOnesVector"", ""MassCenter""}} + } + ref2.Scale(1.0/mat.Sum(mass), ref2) + ret.Copy(in) + ret.SubVec(ret, ref2) + /* for i := 0; i < ir; i++ { + if err := returned.GetRowVector(i).Subtract(ref2); err != nil { + return nil, nil, err + } + } + */ + return ref2, nil +} + +// MassCenter centers in in the center of mass of oref. Mass must be +// A column vector. Returns the centered matrix and the displacement matrix. +func MassCenter(in, oref *v3.Matrix, massS ...*mat.Dense) (*v3.Matrix, *v3.Matrix, error) { + or, _ := oref.Dims() + ir, _ := in.Dims() + var mass *mat.Dense + if len(massS) == 0 || massS[0] == nil { //just obtain the geometric center + tmp := ones(or) + mass = mat.NewDense(or, 1, tmp) //gnOnes(or, 1) + } else { + mass = massS[0] + } + ref := v3.Zeros(or) + ref.Copy(oref) + gnOnesvector := gnOnes(1, or) + f := func() { ref.ScaleByCol(ref, mass) } + if err := gnMaybe(gnPanicker(f)); err != nil { + return nil, nil, CError{err.Error(), []string{""v3.Matrix.ScaleByCol"", ""MassCenter""}} + } + ref2 := v3.Zeros(1) + g := func() { ref2.Mul(gnOnesvector, ref) } + if err := gnMaybe(gnPanicker(g)); err != nil { + return nil, nil, CError{err.Error(), []string{""v3.gOnesVector"", ""MassCenter""}} + } + ref2.Scale(1.0/mat.Sum(mass), ref2) + returned := v3.Zeros(ir) + returned.Copy(in) + returned.SubVec(returned, ref2) + /* for i := 0; i < ir; i++ { + if err := returned.GetRowVector(i).Subtract(ref2); err != nil { + return nil, nil, err + } + } + */ + return returned, ref2, nil +} + +// MomentTensor returns the moment tensor for a matrix A of coordinates and a column +// vector mass with the respective massess. +func MomentTensor(A *v3.Matrix, massslice ...[]float64) (*v3.Matrix, error) { + ar, ac := A.Dims() + var err error + var mass *mat.Dense + if len(massslice) == 0 || massslice[0] == nil { + mass = gnOnes(ar, 1) + } else { + mass = mat.NewDense(ar, 1, massslice[0]) + // if err != nil { + // return nil, err + // } + } + center, _, err := MassCenter(A, v3.Dense2Matrix(gnCopy(A)), mass) + if err != nil { + return nil, errDecorate(err, ""MomentTensor"") + } + sqrmass := gnZeros(ar, 1) + // sqrmass.Pow(mass,0.5) + pow(mass, sqrmass, 0.5) //the result is stored in sqrmass + // fmt.Println(center,sqrmass) //////////////////////// + center.ScaleByCol(center, sqrmass) + // fmt.Println(center,""scaled center"") + centerT := gnZeros(ac, ar) + centerT.Copy(center.T()) + moment := gnMul(centerT, center) + return v3.Dense2Matrix(moment), nil +} + +// Projection returns the projection of test in ref. +func Projection(test, ref *v3.Matrix) *v3.Matrix { + rr, _ := ref.Dims() + Uref := v3.Zeros(rr) + Uref.Unit(ref) + scalar := test.Dot(Uref) //math.Abs(la)*math.Cos(angle) + Uref.Scale(scalar, Uref) + return Uref +} + +// AntiProjection returns a vector in the direction of ref with the magnitude of +// a vector A would have if |test| was the magnitude of its projection +// in the direction of test. +func AntiProjection(test, ref *v3.Matrix) *v3.Matrix { + rr, _ := ref.Dims() + testnorm := test.Norm(2) + Uref := v3.Zeros(rr) + Uref.Unit(ref) + scalar := test.Dot(Uref) + scalar = (testnorm * testnorm) / scalar + Uref.Scale(scalar, Uref) + return Uref +} +","Go" +"Computational Biochemistry","rmera/gochem","voro/voronoi_test.go",".go","1270","49","package voro + +import ( + ""fmt"" + ""testing"" + + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" + // ""github.com/rmera/scu"" +) + +func TestVoronoi(t *testing.T) { + mol, err := chem.PDBFileRead(""../test/2c9vIOH.pdb"", true) + if err != nil { + panic(err.Error()) + } + const cutoff = 4 + mol.FillVdw() + // resA := []int{148, 149, 150, 151, 152, 153} + // resB := []int{48, 49, 50, 51, 52} + res := []int{} + for i := 1; i <= 153; i++ { + res = append(res, i) + } + indexA := chem.Molecules2Atoms(mol, res, []string{""A""}) + indexB := chem.Molecules2Atoms(mol, res, []string{""F""}) + coord := mol.Coords[0] + planes := GetPlanes(coord, mol, cutoff, true) + var ABConts []int + // testatoms := indexA[2:6] //////// + for _, v := range indexA { + for _, w := range indexB { + angles := DefaultAngleScan() //this is the cutoff for inter-atom distances, so half of it is about right for atom-plane + if planes.VdwContact(coord, mol, v, w, angles) { + ABConts = append(ABConts, v, w) + } + } + } + if len(ABConts) == 0 { + t.Fatal(""No contact found"") + } + fmt.Println(""Contacts: "", len(ABConts)) + icoord := v3.Zeros(len(ABConts)) + icoord.SomeVecs(coord, ABConts) + imol := chem.NewTopology(0, 1) + imol.SomeAtoms(mol, ABConts) + chem.PDBFileWrite(""../test/inter.pdb"", icoord, imol, nil) +} +","Go" +"Computational Biochemistry","rmera/gochem","voro/voronoi.go",".go","11207","352","/* + * voronoi.go, part of gochem. + * + * + * Copyright 2021 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + * goChem is currently developed at the Universidad de Santiago de Chile + * (USACH) + * + */ + +/** +voro offers Voronoi polyhedra-based functionality for goChem, allowing to determine whether 2 atoms +are in contact. + +Unfortunately, due to the author's lack of knowledge on comptuational geometry, and the lack of implementations +of 3D-Voronoi polyhedra construction in Go, this library is extremely naive, un-sophisticated and +heavily brute-force, in addition to incomplete. It uses a series of rather dirty tricks invoking physical and +chemical knowledge to alliviate the performance problems caused by the previous, but they are still here. +Also, the heavy numerical character of voro is sure to cause inaccuracies when compared to a proper, +analytical implementation. Still, it does work in my tests. + +**/ + +package voro + +import ( + ""fmt"" + ""log"" + ""os"" + + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" + ""gonum.org/v1/gonum/stat/combin"" +) + +const ( + defOffset float64 = 1.4 + defVdwFactor float64 = 1.2 + defMaxAngle float64 = 87 + defAngleStep float64 = 5 +) + +// AngleScan contains options to perform angle scans to see if there is an angle in which 2 atoms +// are in direct contact (i.e. if part of the plane bisecting them is part of the Voronoi polihedra for the system). +type AngleScan struct { + VdwFactor float64 + Offset float64 + Angles []float64 //last angle, step between angles, in degrees. A full scan would be 0 to 90 + Cutoff float64 //distance cutoff, if the vectors at the given angle are farther than this, the angle is ignored. + Test bool //for debugging +} + +// DefaultAngleScan returns the default setting for an AngleScan +func DefaultAngleScan() *AngleScan { + return &AngleScan{Offset: defOffset, VdwFactor: defVdwFactor, Angles: []float64{defMaxAngle, defAngleStep}} +} + +//This is a naive, unoptimal, simple and incomplete implementation +//of 3D Voronoi polihedra. + +// The plane bisecting 2 atoms +// With all the info we might want from it. +type VPlane struct { + Atoms []int //indexes of the 2 atoms. + Distance float64 //The plane is equidistant from both atoms, so there is only one distance + Normal *v3.Matrix + Offset *v3.Matrix + NotContact bool //true if this plane is a confirmed non-contact +} + +// OtherAtom, given the index of one of the atoms bisected by the plane,returns the index of the other atom. +func (V *VPlane) OtherAtom(i int) int { + if V.Atoms[0] == i { + return V.Atoms[1] + } else if V.Atoms[1] == i { + return V.Atoms[0] + } + panic(fmt.Sprintf(""Plane is not related to atom %d"", i)) //I think this is fair enough. This should always be a bug in the program. +} + +// DistanceInterVector obtains the distance from a point o to the plane in the direction of d. +// It returns -1 if the vector never intersects the plane. +func (V *VPlane) DistanceInterVector(o, d *v3.Matrix) float64 { + p := v3.Zeros(1) + p.Sub(d, o) + dot := V.Normal.Dot(p) + if dot == 0 { + return -1 //vector and plane never intersect + //The other corner case, where the vector is contained in the plane, should not happen here! + } + n := V.Normal + a := V.Offset + c := func(v *v3.Matrix, i int) float64 { return v.At(0, i) } + t := (c(n, 0)*(c(o, 0)-c(a, 0)) + c(n, 1)*(c(o, 1)-c(a, 1)) + c(n, 2)*(c(o, 2)-c(a, 2))) / (c(n, 0)*c(d, 0) + c(n, 1)*c(d, 1) + c(n, 2)*c(d, 2)) + x := c(o, 0) + c(d, 0)*t + y := c(o, 1) + c(d, 1)*t + z := c(o, 2) + c(d, 2)*t + p.Set(0, 0, x) + p.Set(0, 1, y) + p.Set(0, 2, z) + p2 := v3.Zeros(1) + p2.Sub(p, o) + return p2.Norm(2) +} + +// VPSlice contains a slice to pointers to VPlane. +type VPSlice []*VPlane + +// AtomPlanes returns all the planes that bisect the atom with index i, and any other atom. +func (P VPSlice) AtomPlanes(i int) VPSlice { + ret := make([]*VPlane, 0, len(P)/10) //the cap value is just a wild guess + for _, v := range P { + if v.Atoms[0] == i || v.Atoms[1] == i { + ret = append(ret, v) + } + } + return VPSlice(ret) +} + +// PairPlane returns the plane bisecting the atoms with indexes i and j. +func (P VPSlice) PairPlane(i, j int) *VPlane { + for _, v := range P { + if (v.Atoms[0] == i && v.Atoms[1] == j) || (v.Atoms[0] == j && v.Atoms[1] == i) { + return v + } + } + return nil +} + +// Determines whether 2 atoms are in contact, using the sum of their vdW radii (multiplied by an optional +// factor, 1.2 by default), as a cutoff. +func (P VPSlice) VdwContact(coords *v3.Matrix, mol chem.Atomer, i, j int, scan ...*AngleScan) bool { + if len(scan) <= 0 { + scan = append(scan, DefaultAngleScan()) //1.4 is the vdW radius of water + + } + vdwsum := mol.Atom(i).Vdw + mol.Atom(j).Vdw + scan[0].Cutoff = vdwsum*scan[0].VdwFactor + scan[0].Offset + return P.Contact(coords, i, j, scan[0]) + +} + +func distance(coords *v3.Matrix, i, j int) float64 { + vi := coords.VecView(i) + vj := coords.VecView(j) + d := v3.Zeros(1) + d.Sub(vi, vj) + return d.Norm(2) +} + +// Determines whether vectors i and j from coords are in contact, by checking that no plane is closer to i +// than the plane bisecting the ij vector, along some direction with an angle smaller than 90 degrees from the +// direction along the ij vector. +// This function is safe for concurrent use. +func (P VPSlice) Contact(coords *v3.Matrix, i, j int, anglest ...*AngleScan) bool { + var angles []float64 //if given, should contain 3 values. First angle, last angle, and step (all in degrees). + cutoff := 6.0 //some default (rather permisive) cutoff + if len(anglest) == 0 { + angles = []float64{1, 2} //these values ensure that only one angle 0 deg is tested. + } else { + angles = anglest[0].Angles + cutoff = anglest[0].Cutoff + + } + if distance(coords, i, j) > anglest[0].Cutoff { + return false //profiling is good! This made everything over an order of magnitude faster xD + + } + ref := P.PairPlane(i, j) + if ref == nil { + return false //the plane was never created, probably above the initial distance cutoff + } + //no need to test things that are too far anyway. + planes := P.AtomPlanes(i) + notcontact := make([]bool, len(planes)) + for k, v := range planes { + if v.Distance > anglest[0].Cutoff/2 { + notcontact[k] = true + // planes[k].NotContact = true + } else { + notcontact[k] = false + // planes[k].NotContact = false + } + } + ati := coords.VecView(i) + atj := coords.VecView(j) + for i, v := range planes { + if v.Atoms[1] == j || v.Atoms[0] == j { + continue //shouldn't be needed, really + } + if notcontact[i] { + continue + } + var fname []string + if len(anglest) > 0 && anglest[0].Test { + fname = append(fname, fmt.Sprintf(""test_%d_%d.xyz"", i, j)) //test/debug + } + blocked := ConeBlock(ref, v, ati, atj, cutoff, angles, fname...) + if blocked { + return false + } + } + return true +} + +// returns a crappy xyz string from the slice of 1x3 vectors provided +// for testing purposes only +func writetestxyzstring(vec ...*v3.Matrix) string { + form := fmt.Sprintf + elem := []string{""O"", ""C"", ""N"", ""H"", ""P"", ""F"", ""I"", ""Br"", ""Zn"", ""Cu""} + str := form(""%d\n\n"", len(vec)) + for i, v := range vec { + str += form(""%s %5.3f %5.3f %5.3f\n"", elem[i], v.At(0, 0), v.At(0, 1), v.At(0, 2)) + } + return str + +} + +// Test if the path between ati and the ref plane is blocked by the test plane +// it will scan cones at increasing angles from the ati-atj vector(from 0 to angles[0] degrees, where angles[0] should be <90) +// in angle[1] steps. +// This is a brute-force, very slow and clumsy system. But hey, I'm a chemist. I'll change it when a) there is a pure Go 3D-Voronoi +// library or b) I find the time to study computational geometry. +func ConeBlock(ref, test *VPlane, ati, atj *v3.Matrix, cutoff float64, angles []float64, testname ...string) bool { + var xyz string + refdist := ref.Distance + axis := v3.Zeros(1) + aux := v3.Zeros(1) + ax2 := v3.Zeros(1) + aux.Set(0, 1, 0) //any vector + axis.Sub(atj, ati) + aux.Sub(axis, aux) //just to ensure axis (defined as atj-ati) is not colinear with aux + ax2.Cross(axis, aux) + if angles[0] >= 90 { //this will never intersect the ref plane! + angles[0] = 89 + } + for ang := 0.0; ang <= angles[0]; ang += angles[1] { + if ang == 0 { + refdist = ref.Distance + Dij_k := test.DistanceInterVector(ati, atj) + if Dij_k > refdist || Dij_k < 0 { + return false + } + } + //now the cone + dir, err := chem.RotateAbout(atj, ati, ax2, ang*chem.Deg2Rad) + if err != nil { + panic(err.Error()) //I am not 100% sure about panicking over this, but it seems like it has to be a bug in the caller + } + for rot := 0.0; rot < 360; rot += angles[1] { + ndir, err := chem.RotateAbout(dir, ati, atj, rot) + if err != nil { + panic(err.Error()) + } + if len(testname) > 0 { + xyz += writetestxyzstring(ati, atj, ndir) + } + refdist = ref.DistanceInterVector(ati, ndir) + if refdist > cutoff/2 && refdist < 0 { + return true + } + + Dij_k := test.DistanceInterVector(ati, ndir) + if Dij_k > refdist || Dij_k < 0 { //a distance <0 means that the vector never intersects the plane. + writetest(xyz, testname) + return false + } + } + } + //for debugging + writetest(xyz, testname) + return true + +} + +// debug function, to be called on testing. +func writetest(xyz string, name []string) { + if len(name) > 0 { + f, err := os.Create(name[0]) + if err != nil { + log.Println(err.Error()) + } + f.WriteString(xyz) + f.Close() + + } + +} + +func PlaneBetweenAtoms(at1, at2 *v3.Matrix, i, j int) *VPlane { + ret := &VPlane{} + ret.Atoms = []int{i, j} + ret.Normal = v3.Zeros(1) + ret.Normal.Sub(at2, at1) + ret.Distance = ret.Normal.Norm(2) / 2.0 + ret.Offset = v3.Zeros(1) + ret.Offset.Add(at1, at2) + ret.Offset.Scale(0.5, ret.Offset) //I'm actually not 100% sure about this! + return ret +} + +// get all planes between all possible pairs of atoms +// which are not farther away from each other than cutoff +func GetPlanes(atoms *v3.Matrix, mol chem.Atomer, cutoff float64, noHs ...bool) VPSlice { + var noH bool //false by default (it's zero-value) + if len(noHs) != 0 { + noH = noHs[0] + } + var ai, aj *v3.Matrix + //ai := v3.Zeros(1) + //aj := v3.Zeros(1) + tot := atoms.NVecs() + planes := make([]*VPlane, 0, combin.Binomial(tot, 2)/2) //I couldn't resist adding the binomial coefficient, sorry. + for i := 0; i < tot; i++ { + ai = atoms.VecView(i) + ati := mol.Atom(i) + if noH && ati.Symbol == ""H"" { + continue + } + for j := i + 1; j < tot; j++ { + aj = atoms.VecView(j) + atj := mol.Atom(j) + if noH && atj.Symbol == ""H"" { + continue + } + t := PlaneBetweenAtoms(ai, aj, i, j) + if t.Distance*2.0 > cutoff { + continue + } + planes = append(planes, t) + + } + } + return VPSlice(planes) +} +","Go" +"Computational Biochemistry","rmera/gochem","traj/stf/doc.go",".go","4125","80","/* + * doc.go, part of gochem. + * + * Copyright 2021 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + * / + +//package stf implements the simple trajectory format, an internal trajectory format for goChem. +//stf aimst to produce reasonably small files and to be very easy to read and write, so readers/writers +//can be easily implemented in other programing languages / for other libraries or programs, while +//also being reasonably fast to write and, especially, to read. + +//By my test, stf files are ~60% larger than the equivalent XTC file at equivalent precision (and about +30% larger at the lower default stf precision), while being about half the size of a an equivalent DCD file + + +/******************** Format Specification *************************************************** + + +An STF file has the extension stf, and it is compressed with z-standard (zstd). + +A STF file may only contain ASCII symbols. + +A STF file has a ""header"" starting in the first line, and ending with a line that starts with the +characters ""**"" followed by one or more spaces, and the number of atoms per frame. + +Each line of the header must be a pair key=value. It a trajectory includes topology, this may be +included in the header with the key ""topology"" and a jsons string, describing the topology as an +array of atoms, as defined in github.com/rmera/gochem/chemjson, as a value. Implementations are +not required to support reading/writing of topologies. The precision (an integer greater than 0, +see below) must be included in the header, with the corresponding key ""prec"". For example, +a 'precision' line could be: + +prec=2 + +Note that the header must have at least one line, marking the precison. The 'default' precision +to be used if the user does not supply one is left to the implementation, though we do note that +the implementation in this package uses a default precision of 1. + +After the header, the file has one line per atom, per frame. Each line contains 3 numbers, +corresponding to the x y and z cartesian coordinates, respectively, and nothing more. Each +of these 3 number contains the respective coordinate in Angstrom, multiplied by 10 to the +power of (precision), where precision is 1, or whatever positive integer given in the header +(see above) and rounded to make it an integer. Since the default precision is +1, the numbers go multiplied by 10, unless a different value is given in the header, and rounded +to an integer. + +Each frame ends with a line starting with the character ""*"" (no whitespaces before) , optionally +followed by: one or more whitespace and 9 floating-point numbers separated by spaces (precision +unspecified). If present, these number correspond to the vectors defining the simulation box, in Angstrom + +The ""**"" sequence may only be used as a header termination, as described above and can not appear +anywhere else in the file. + +Z-standard allows several 'levels' of compression that represent different tradeoffs between +compression/decompression speed and final file size. The naming of those levels is implementation +dependent. The level used in stf is left to the implementation, but at least a default level must +be provided. If an implementation does _not_ give the user an option to control the level used +(we recommend, but do not require, that such option is given), we request lack of option to be +clearly documented. + +***************************************************************************************************/ + +package stf +","Go" +"Computational Biochemistry","rmera/gochem","traj/stf/stf_test.go",".go","4836","209","/* + * dcd_test.go + * + * Copyright 2012 Raul Mera Adasme + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + */ +/* + * + * + */ + +package stf + +import ( + ""fmt"" + + ""testing"" + + chem ""github.com/rmera/gochem"" + ""github.com/rmera/gochem/traj/dcd"" + ""github.com/rmera/gochem/traj/xtc"" + + v3 ""github.com/rmera/gochem/v3"" +) + +var rootdirtest string = ""../../test"" + +//var rootdirtest string = ""/run/media/rmera/Fondecyt1TB"" + +// Tests the writing capabilities. +func TestSTFWrite(Te *testing.T) { + var err error + fmt.Println(""STF write test!"") + _, err = chem.PDBFileRead(""../../test/test_stf.pdb"", false) + if err != nil { + Te.Error(err) + } + rtraj, err := xtc.New(""../../test/test.xtc"") + if err != nil { + Te.Error(err) + } + wtraj, err := NewWriter(rootdirtest+""/test_stf.stf"", rtraj.Len(), nil) + if err != nil { + Te.Error(err) + } + defer rtraj.Close() + i := 0 + mat := v3.Zeros(rtraj.Len()) + box := make([]float64, 9) + for ; ; i++ { + if i%1 == 0 { + err = rtraj.Next(mat, box) + } else { + err = rtraj.Next(nil) + } + if err != nil { + if _, ok := err.(chem.LastFrameError); ok { + break + } + Te.Error(err) + break + } + // fmt.Println(box) ////////////////////////// + if i%1 == 0 { + wtraj.WNext(mat, box) + } + } + wtraj.Close() + //now let's see if the whole thing actually worked by producing something I can easily read in pymol + fmt.Println(""Over! frames read and written:"", i) + rrtraj, _, err := New(""../../test/test_stf.stf"") + if err != nil { + Te.Error(err) + } + wwtraj, err := dcd.NewWriter(rootdirtest+""/test_stf_read.dcd"", rrtraj.Len()) + if err != nil { + Te.Error(err) + } + defer rtraj.Close() + + i = 0 + mat = v3.Zeros(rrtraj.Len()) + box = make([]float64, 9) + for ; ; i++ { + if i%1 == 0 { + err = rrtraj.Next(mat, box) + } else { + err = rrtraj.Next(nil) + } + if err != nil { + if _, ok := err.(chem.LastFrameError); ok { + break + } + Te.Error(err) + break + } + // fmt.Println(box) ////////////////////////// + if i%1 == 0 { + wwtraj.WNext(mat, box) + } + } + wwtraj.Close() + fmt.Println(""Wrote the trajectory for analysis"") +} + +var readfromtest string = ""./python"" + +// Now the read +func TestSTF(Te *testing.T) { + fmt.Println(""STF read test!"") + + _, err := chem.PDBFileRead(readfromtest+""/prod.pdb"", false) + if err != nil { + Te.Error(err) + } + rtraj, _, err := New(readfromtest + ""/prod.stf"") + if err != nil { + Te.Error(err) + } + wtraj, err := dcd.NewWriter(readfromtest+""/test_stf.dcd"", rtraj.Len()) + if err != nil { + Te.Error(err) + } + defer rtraj.Close() + i := 0 + mat := v3.Zeros(rtraj.Len()) + box := make([]float64, 9) + for ; ; i++ { + err := rtraj.Next(mat, box) + if err != nil { + if _, ok := err.(chem.LastFrameError); ok { + break + } + Te.Error(err) + break + } + wtraj.WNext(mat) + fmt.Println(""box"", box, mat.VecView(6)) + } + fmt.Println(""Over! frames read:"", i) +} + +func TestSTFConc(Te *testing.T) { + fmt.Println(""Concurrency test!"") + traj, _, err := New(rootdirtest + ""/test_stf.stf"") + if err != nil { + Te.Error(err) + } + frames := make([]*v3.Matrix, 3, 3) + for i, _ := range frames { + frames[i] = v3.Zeros(traj.Len()) + } + // frames[1] = nil /////Just a test + results := make([][]chan *v3.Matrix, 0, 0) + for i := 0; ; i++ { + results = append(results, make([]chan *v3.Matrix, 0, len(frames))) + coordchans, err := traj.NextConc(frames) + if err != nil { + if _, ok := err.(chem.LastFrameError); ok { + break + } + Te.Error(err) + break + } + for key, channel := range coordchans { + results[len(results)-1] = append(results[len(results)-1], make(chan *v3.Matrix)) + go LastRow(channel, results[len(results)-1][key], len(results)-1, key) + } + res := len(results) - 1 + for frame, k := range results[res] { + if k == nil { + fmt.Println(frame, ""should be zeros!"") + continue + } + fmt.Println(res, frame, <-k, ""res 1 should be 0s"") + } + } +} + +func LastRow(channelin, channelout chan *v3.Matrix, current, other int) { + var vector *v3.Matrix + if channelin != nil { + temp := <-channelin + viej := v3.Zeros(1) + if temp != nil { + vector = temp.VecView(temp.Len() - 1) + viej.Copy(vector) + } + fmt.Println(""sending througt"", channelin, channelout, viej, current, other) + channelout <- vector + } else { + channelout <- nil + } + return +} +","Go" +"Computational Biochemistry","rmera/gochem","traj/stf/stf.go",".go","17145","612","package stf + +import ( + ""bufio"" + ""compress/flate"" + ""compress/gzip"" + ""compress/lzw"" + ""fmt"" + ""io"" + ""log"" + ""math"" + ""os"" + ""strconv"" + ""strings"" + ""unsafe"" + + ""github.com/klauspost/compress/s2"" + ""github.com/klauspost/compress/zstd"" + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" + ""gonum.org/v1/gonum/mat"" +) + +const ( + lzwLitwidth int = 8 +) + +// Write! +type StfW struct { + f *os.File + h io.WriteCloser + natoms int + filename string + writeable bool + framebuffer *v3.Matrix + prec int +} + +func (S *StfW) Close() { + + if S == nil { + return + } + if S.writeable { + S.h.Close() + S.f.Close() + } + S.writeable = false + return +} + +func (S *StfW) Len() int { + return S.natoms +} + +// compatibility with Gonum +func (S *StfW) WNextDense(dcoord *mat.Dense) error { + coord := v3.Dense2Matrix(dcoord) + err := S.WNext(coord) + if err != nil { + err = errDecorate(err, ""WNextDense"") + } + return err +} + +// Writes a frame to the trajectory. Will panic if the trjectory is nil or closed. +func (S *StfW) WNext(coord *v3.Matrix, box ...[]float64) error { + //centroid, err := chem.MassCenterMem(coord, coord, S.framebuffer) //not actually the CoM, but the geometric center. + //if err == nil { + // coord = S.framebuffer //we won't say anything in case of error, sorry. + //} + + if S == nil { + return Error{""Nil trajectory"", """", []string{""WNext""}, true} + } + + if S == nil || !S.writeable { + return Error{TrajUnIniWrite, S.filename, []string{""WNext""}, true} + } + if coord == nil { + return Error{NilCoordinates, S.filename, []string{""WNext""}, true} + } + v := coord.NVecs() + if v != S.natoms { + return Error{fmt.Sprintf(""%d coordinates given, but %d expected"", v, S.natoms), S.filename, []string{""WNext""}, true} + } + // strs := make([]string, 4) //old code + var temp [3]int + var floats [3]float64 + var str string + // prec = 2 //default + for i := 0; i < v; i++ { + floats[0] = coord.At(i, 0) + floats[1] = coord.At(i, 1) + floats[2] = coord.At(i, 2) + + str = coordsEncode(floats, temp, S.prec) + + S.h.Write([]byte(str)) + } + if len(box) > 0 && len(box[0]) >= 9 { + b := box[0] + //if we did do the centroid thing, we should also displace the box vectors. + // if centroid != nil { + // for in := 0; in < 3; in++ { + // b[(3*in)+0] -= centroid.At(0, 0) //I like it better with the parenthesis :-D + // b[(3*in)+1] -= centroid.At(0, 1) + // b[(3*in)+2] -= centroid.At(0, 2) + // + // } + // } + S.h.Write([]byte(fmt.Sprintf(""* %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f %4.2f\n"", b[0], + b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8]))) + + } else { + S.h.Write([]byte(""*\n"")) + } + // println(""Wrote a frame!"") /////////////////////////// + return nil +} + +/* + 1 = zstd.SpeedFastest + 2 = zstd.SpeedDefault + 3 = zstd.SpeedBetterCompression + 4 = zstd.SpeedBestCompression +*/ + +type WriterOptions struct { + // Precision int //How many decimals for each coordinate, in Angstroms + CompressionLevel int // 1: Fastest/Worst compression to 4: Slowest/Best compression +} + +func DefaultWriterOptions() *WriterOptions { + O := new(WriterOptions) + // O.Precision = 1 + O.CompressionLevel = 1 // 1 to 4 from fastest/larger file to slower/smaller file + return O +} + +func (O *WriterOptions) Fix() { + // if O.Precision < 1 { + // O.Precision = 1 + // log.Printf(""Invalid precision for trajectory. Will use the default"") + + // } + if O.CompressionLevel < 1 || O.CompressionLevel > 4 { + O.CompressionLevel = 1 + } + +} + +// For zstandard (stf) compression levels are progressively slower but offering better compression +// as compressionLevel increases from 1 to 4 (other numbers will result in '1' or fastest compression). +// If the precision is specified in the header, that overwrites whatever is in the options. +func NewWriter(name string, natoms int, header map[string]string, Opts ...*WriterOptions) (*StfW, error) { + var O *WriterOptions + if len(Opts) > 0 { + O = Opts[1] + O.Fix() + } else { + O = DefaultWriterOptions() + } + S := new(StfW) + var err error + S.f, err = os.Create(name) + if err != nil { + return nil, err + } + S.framebuffer = v3.Zeros(natoms) + format := strings.ToLower(name)[len(name)-1] + zwriter := func(a io.Writer) (io.WriteCloser, error) { + r, err := flate.NewWriter(a, O.CompressionLevel) + return r, err + } + // zl := newzlevs() + gzipwriter := func(a io.Writer) (io.WriteCloser, error) { return gzip.NewWriterLevel(a, O.CompressionLevel) } + zstdwriter := func(a io.Writer) (io.WriteCloser, error) { + return zstd.NewWriter(a, zstd.WithEncoderLevel(zstd.EncoderLevel(O.CompressionLevel))) //zstd.SpeedBetterCompression)) + } + s2writer := func(a io.Writer) (io.WriteCloser, error) { return s2.NewWriter(a), nil } //s2.WriterSnappyCompat()), nil } + + var AnyNewWriter func(io.Writer) (io.WriteCloser, error) + switch format { + case 'l': + AnyNewWriter = func(a io.Writer) (io.WriteCloser, error) { return lzw.NewWriter(a, lzw.MSB, lzwLitwidth), nil } + case 'f': + AnyNewWriter = zstdwriter + case 'z': + AnyNewWriter = gzipwriter + case 's': + AnyNewWriter = s2writer + case 'r': + AnyNewWriter = zwriter + default: + AnyNewWriter = zstdwriter + } + + S.h, err = AnyNewWriter(S.f) + if err != nil { + return nil, Error{""Can't read header "" + err.Error(), S.filename, []string{""NewWriter""}, true} + } + + // S.h = AnyNewWriter(S.f) + S.natoms = natoms + S.filename = name + S.writeable = true + const DEFAULT_PRECISION int = 1 + S.prec = DEFAULT_PRECISION + if header == nil { + header = make(map[string]string) + } + if _, ok := header[""prec""]; !ok { + header[""prec""] = fmt.Sprintf(""%d"", S.prec) + } + headerstr := """" + for k, v := range header { + headerstr += fmt.Sprintf(""%s=%v\n"", k, v) + } + S.h.Write([]byte(headerstr)) + + S.h.Write([]byte(fmt.Sprintf(""** %d\n"", S.natoms))) + return S, nil +} + +// Read! +type StfR struct { + f *os.File + lzw io.ReadCloser + h *bufio.Reader + intermediate *bufio.Reader + // framebuffer *v3.Matrix + natoms int + filename string + prec int + readable bool +} + +// This will cause additional indirections +// but I suppose it won't matter, as each call will +// take enough time to make those delays irrelevant. +// Also, why couldn't *zstd.Decoder implement io.ReadCloser? :-( +type stdql struct { + closeql func() //The things I have to do xD + *zstd.Decoder +} + +// Close Closes the object. It can not be used after this call +func (s stdql) Close() error { + s.closeql() + return nil +} + +// same, but for s2/snappy. +type s2ql struct { + closeql func() //The things I have to do xD + *s2.Reader +} + +// Close Closes the object. It can not be used after this call +func (s s2ql) Close() error { + s.closeql() + return nil +} + +func coordsEncode(f [3]float64, temp [3]int, prec int) string { + p := 100.0 + if prec > 0 { + p = math.Pow(10.0, float64(prec)) + } + // fmt.Println(""ori"", f) /////////////////////////////////////////////////////////////////////// + for i, v := range f { + temp[i] = int(math.RoundToEven(v * p)) + } + return fmt.Sprintf(""%d %d %d\n"", temp[0], temp[1], temp[2]) +} + +// New opens a STF trajectory for reading, and returns a pointer +// to the handle, a map with the metadata (or nil, if no metadata is found) +// and error or nil. +func New(name string) (*StfR, map[string]string, error) { + S := new(StfR) + S.natoms = -1 //just so we know if things don't work + m := make(map[string]string) + var err error + S.filename = name + S.f, err = os.Open(S.filename) + if err != nil { + return nil, nil, err + } + var AnyNewReader func(io.Reader) (io.ReadCloser, error) + zreader := func(a io.Reader) (io.ReadCloser, error) { + r := flate.NewReader(a) + return r, nil + } + zstdreader := func(a io.Reader) (io.ReadCloser, error) { + r, err := zstd.NewReader(a, zstd.WithDecoderConcurrency(0)) + var ql *stdql + ql = &stdql{r.Close, r} + + return ql, err + } + s2reader := func(a io.Reader) (io.ReadCloser, error) { + r := s2.NewReader(a) + var ql *s2ql + //will try to close the file + cl := func() { + if ac, ok := a.(io.ReadCloser); ok { + ac.Close() + } + } + ql = &s2ql{cl, r} + + return ql, err + + } + + gzreader := func(a io.Reader) (io.ReadCloser, error) { return gzip.NewReader(a) } + switch strings.ToLower(name)[len(name)-1] { + case 'l': + AnyNewReader = func(a io.Reader) (io.ReadCloser, error) { return lzw.NewReader(a, lzw.MSB, 8), nil } + case 'f': + AnyNewReader = zstdreader + case 'z': + AnyNewReader = gzreader + case 's': + AnyNewReader = s2reader + case 'r': + AnyNewReader = zreader + + default: + AnyNewReader = zstdreader + + } + + S.intermediate = bufio.NewReader(S.f) + S.lzw, err = AnyNewReader(S.intermediate) + if err != nil { + return nil, nil, Error{""Can't read header "" + err.Error(), S.filename, []string{""NewStfR""}, true} + } + S.h = bufio.NewReader(S.lzw) + for { + str, err := S.h.ReadString('\n') + if err != nil { + return nil, nil, Error{""Can't read header "" + err.Error(), S.filename, []string{""NewStfR""}, true} + } + str = strings.TrimSuffix(str, ""\n"") + // str = string([]byte(str)[0 : len(str)-1]) //This should work for ASCII, which is fine for Stf. It removes the last '\n' + if strings.Contains(str, ""**"") { + nat := strings.Fields(str) + if len(nat) < 2 { + return nil, nil, Error{fmt.Sprintf(""Can't read atom number from '%s': %s"", str, err.Error()), S.filename, []string{""NewStfR""}, true} + } + nat[1] = strings.TrimSuffix(nat[1], ""\n"") + S.natoms, err = strconv.Atoi(nat[1]) + if err != nil { + return nil, nil, Error{fmt.Sprintf(""Can't read atom number from '%s': %s"", nat[1], err.Error()), S.filename, []string{""NewStfR""}, true} + + } + break + } + kv := strings.Split(str, ""="") + if len(kv) != 2 { + return nil, nil, Error{""Malformed header"" + err.Error(), S.filename, []string{""NewStfR""}, true} + } + m[kv[0]] = kv[1] + } + // S.framebuffer = v3.Zeros(S.natoms) + S.readable = true + S.prec = 1 + if len(m) != 0 { + if p, ok := m[""prec""]; ok { + prec, err := strconv.Atoi(p) + if err != nil { + S.prec = prec + } else { + log.Printf(""Invalid precision for trajectory %s. Will assume the default"", S.filename) + } + } + + } + return S, m, nil +} + +// Readabe returns true if the handle is readable (if it is possible to call Next on it) +func (S *StfR) Readable() bool { + return S.readable +} + +func coordsDecode(str string, temp *[3]float64, prec int) error { + p := 100.0 + if prec > 0 { + p = math.Pow(10.0, float64(prec)) + + } + s := strings.Fields(str) + if len(s) < 3 { + return fmt.Errorf(""Ill formated coordinates line in stf: Too few fields: %s"", str) + } + if len(s) > 3 { + return fmt.Errorf(""Ill formated coordinates line in stf: Too many fields: %s"", str) + } + for i, v := range s { + f, err := strconv.Atoi(v) + if err != nil { + return fmt.Errorf(""Can't parse coordinate %d (%s). Error: %s"", i, v, err.Error()) + } + temp[i] = float64(f) / p + } + return nil +} + +// Next puts in the given matrix (c) the coordinates for the next frame of the trajectory +// and, if given, and the information is present, puts the box vector information in box +// Returns error if the operation is not successful. If the error is EOF, the end of the +// trajectory has been reached, not an actual error. +func (S *StfR) Next(c *v3.Matrix, box ...[]float64) error { + // var tmpstr string + // var prec int = 2 + // var pointplace int + var temp [3]float64 + var err error + for i := 0; i < S.natoms; i++ { + b, err := S.h.ReadBytes('\n') + if err != nil { + // EOF should only happen when reading the first atom + if err.Error() == ""EOF"" && (strings.Contains(err.Error(), ""EOF"")) && i == 0 { + //nothing bad happened here, the trajectory just ended. + S.Close() + return newlastFrameError(S.filename, ""Next"") + } else { + return Error{message: err.Error(), filename: S.filename, critical: true} + } + + } + err = coordsDecode(string(b[:len(b)-1]), &temp, S.prec) + if err != nil { + return Error{message: err.Error(), filename: S.filename, critical: true} + } + + if c == nil { + continue //We ignore this whole frame, reading the content but not saving it. + //Note that we still check the frame for correctness. + } + for j, v := range temp { + c.Set(i, j, v) + } + + } + s, err := S.h.ReadString('\n') + if err != nil { + return Error{""Can't read the frame termination mark"" + err.Error(), S.filename, []string{""Next""}, true} + } + if s[0] != '*' { + return Error{""Wrong number of atoms in frame"" + err.Error(), S.filename, []string{""Next""}, true} + } + + //This part reads the + if len(box) > 0 && len(box[0]) >= 9 { + fields := strings.Fields(strings.TrimSpace(s)) //we get rid of that last ""\n"" + if len(fields) >= 10 { // The ""*"" and the 9 numbers + var errbox error + for j, v := range fields[1:] { + //This should be replaced for a call to bytesconv.BytesToString when I update the compiler. + box[0][j], errbox = strconv.ParseFloat(*(*string)(unsafe.Pointer(&v)), 64) + if errbox != nil { + break + } + } + //If we got an error reading any of the values, we just set the whole thing to zero + //and log, no error returned. + if errbox != nil { + log.Printf(""Failed to read box in a frame from %s"", S.filename) //just a head-up + for i, _ := range box[0] { + box[0][i] = 0.0 + } + } + + } else { + log.Printf(""Trajectory file %s does not contain (correct) box information: %s"", S.filename, fields) //just a head-up + } + } + + return nil +} + +// Close closes the object, and marks it as unreadable +func (S *StfR) Close() { + if !S.readable { + return + } + S.lzw.Close() + S.readable = false + return +} + +// Len returns the number of atoms in each frame of the trajectory. +func (S *StfR) Len() int { + return S.natoms +} + +// NextConc takes a slice of bools and reads as many frames as elements the list has +// form the trajectory. The frames are discarted if the corresponding elemetn of the slice +// is false. The function returns a slice of channels through each of each of which +// a *matrix.DenseMatrix will be transmited +func (D *StfR) NextConc(frames []*v3.Matrix) ([]chan *v3.Matrix, error) { + if !D.Readable() { + return nil, Error{TrajUnIniRead, D.filename, []string{""NextConc""}, true} + } + framechans := make([]chan *v3.Matrix, len(frames)) //the slice of chans that will be returned + for key, v := range frames { + if err := D.Next(v); err != nil { + return nil, errDecorate(err, ""NextConc"") + } + framechans[key] = make(chan *v3.Matrix) + go func(keep *v3.Matrix, pipe chan *v3.Matrix) { + pipe <- keep + }(v, framechans[key]) + } + return framechans, nil +} + +//Errors + +//Errors + +// errDecorate is a helper function that asserts that the error is +// implements chem.Error and decorates the error with the caller's name before returning it. +// if used with a non-chem.Error error, it will cause a panic. +func errDecorate(err error, caller string) error { + err2 := err.(chem.Error) //I know that is the type returned byt initRead + err2.Decorate(caller) + return err2 +} + +// Error is the general structure for DCD trajectory errors. It fullfills chem.Error and chem.TrajError +type Error struct { + message string + filename string //the input file that has problems, or empty string if none. + deco []string + critical bool +} + +func (err Error) Error() string { + return fmt.Sprintf(""stf file %s error: %s"", err.filename, err.message) +} + +// Decorate Adds new information to the error +func (E Error) Decorate(deco string) []string { + //Even thought this method does not use a pointer as a receiver, and tries to alter the received, + //it should work, since E.deco is a slice, and hence a pointer itself. + + if deco != """" { + E.deco = append(E.deco, deco) + } + return E.deco +} + +// Filename returns the file to which the failing trajectory was associated +func (err Error) FileName() string { return err.filename } + +// Format returns the format of the file (always ""dcd"") associated to the error +func (err Error) Format() string { return ""dcd"" } + +// Critical returns true if the error is critical, false otherwise +func (err Error) Critical() bool { return err.critical } + +const ( + TrajUnIniRead = ""Traj object uninitialized to read"" + TrajUnIniWrite = ""Traj object uninitialized to read"" + ReadError = ""Error reading frame"" + UnableToOpen = ""Unable to open file"" + SecurityCheckFailed = ""Failed Security Check"" + NilCoordinates = ""Given nil coordinates"" + WrongFormat = ""Wrong format in the STF file or frame"" + NotEnoughSpace = ""Not enough space in passed blocks"" + EOF = ""EOF"" +) + +// lastFrameError implements chem.LastFrameError +type lastFrameError struct { + deco []string + fileName string +} + +// lastFrameError does nothing +func (E lastFrameError) NormalLastFrameTermination() {} + +func (E lastFrameError) FileName() string { return E.fileName } + +func (E lastFrameError) Error() string { return ""EOF"" } + +func (E lastFrameError) Critical() bool { return false } + +func (E lastFrameError) Format() string { return ""dcd"" } + +func (E lastFrameError) Decorate(deco string) []string { + //Even thought this method does not use a pointer as a receiver, and tries to alter the received, + //it should work, since E.deco is a slice, and hence a pointer itself. + if deco != """" { + E.deco = append(E.deco, deco) + } + return E.deco +} + +func newlastFrameError(filename string, caller string) *lastFrameError { + e := new(lastFrameError) + e.fileName = filename + e.deco = []string{caller} + return e +} +","Go" +"Computational Biochemistry","rmera/gochem","traj/stf/python/stf_pymol.py",".py","1607","51","#!/usr/bin/env python +from pymol import cmd +import stf +import copy + +res2code={""SER"":""S"", ""THR"":""T"", ""ASN"":""N"", ""GLN"":""Q"", ""SEC"":""U"", ""CYS"":""C"", ""GLY"":""G"", ""PRO"":""P"", ""ALA"":""A"", ""VAL"": ""V"", ""ILE"": ""I"", ""LEU"":""L"", ""MET"":""M"", ""PHE"":""F"", ""TYR"":""Y"", ""TRP"":""W"", ""ARG"":""R"", ""HIS"":""H"", ""LYS"":""K"", ""ASP"":""D"", ""GLU"":""E"", ""HIP"":""H"", ""HID"":""H"", ""HIE"":""H""} + + +#This is a fairly slow function, I assume, because of the +#pure-python stf implementatoin that backs it up. +def loadstf(filename,objname="""",skip=0,begin=0): + if objname=="""": + objname=filename.replace("".stf"","""") + t=stf.rtraj(filename) + fr=0 + st=0 + skip=int(skip) + d={} + while True: + bskip=False + if fr%(skip+1)!=0 or fr+1=9: + line=i.rstrip().split() + if len(line)>=10: + for i,v in enumerate(line[1:]): + box[i]=float(v) + self.frames_read+=1 + return self.frame + if not skip: + n=i.rstrip(""\n"").split() + self.frame[r][0]=float(n[0])/self.prec + self.frame[r][1]=float(n[1])/self.prec + self.frame[r][2]=float(n[2])/self.prec + r+=1 + raise EOFError #I guess not the best one. + def next_list(self,skip=False): + f=self.next(skip) + return f.tolist() + def get_header(self): + return self.header + def get_natoms(self): + return self.natoms + def get_frames_read(self): + return self.frames_read + def close(self): + if self.readable: + self.traj.close() + self.readable=False + + +#wtraj is a write-mode trajectory. It requires the name of the file +#And natoms, the number of atoms per frame +#d is a dictionary of strings. +class wtraj: + def __init__(self, filename,natoms,compressionlevel=9,d=None): + def_prec=1 + # Precision is always written to the file, so if no dictionary is given, + # a dictionary containing only the precision is made. If a dictionary + # _is_ given but the ""prec"" + # key is not present, it's added. Same if the key is present, but not + # a positive integer. In all these cases, the default value def_prec is + # used. + if not d: + d={""prec"":str(def_prec)} + elif not ""prec"" in d or not d[""prec""].isdigit(): + d[""prec""]=str(def_prec) + precision=int(d[""prec""]) + self.prec=pow(10,precision) + self.natoms=natoms + self.file=open(filename,'wb') + self.cctx=zstd.ZstdCompressor(level=compressionlevel) + self.traj=self.cctx.stream_writer(self.file) + for k,v in d.items(): + self.traj.write(b""%s=%s\n""%(str(k).encode(""utf-8""),str(v).encode(""utf-8""))) #I'll attempt converting things to string, but it's your responsibility to ensure that is possible. + self.traj.write(b""** %d\n""%natoms) + #Writes the next frame from data, which needs to be an Nx3 numpy array. + def wnext(self, data, box=[0]): + if len(data)=9: + #We center the box on the mean, also + #for i in (0,1,2): + # box[3*i+0]-=mean[0] + # box[3*i+1]-=mean[1] + # box[3*i+2]-=mean[2] + + bstr=b""* %5.3f %5.3f %5.3f %5.3f %5.3f %5.3f %5.3f %5.3f %5.3f\n""%(box[0],box[1], + box[2],box[3],box[4],box[5],box[6],box[7],box[8]) + self.traj.write(bstr) + def close(self): + self.traj.close() + + +","Python" +"Computational Biochemistry","rmera/gochem","traj/amberold/crd_test.go",".go","1793","77","package amberold + +import ( + ""flag"" + ""fmt"" + + // ""fmt"" + ""os"" + ""testing"" + + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" + // ""github.com/rmera/gochem/xtc"" + // ""github.com/rmera/scu"" + // ""gonum.org/v1/gonum/mat"" + // ""math"" + // ""sort"" + // ""strconv"" +) + +////use: program [-skip=number -begin=number2] pdbfile trajname +func TestAmberold(Te *testing.T) { + //The skip options + skip := 0 // flag.Int(""skip"", 0, ""How many frames to skip between reads."") + begin := 1 //flag.Int(""begin"", 1, ""The frame from where to start reading."") + end := 100 + + flag.Parse() + // println(""SKIP"", *skip, *begin, args) /////////////////////////// + mol, err := chem.PDBFileRead(""../../test/310K.pdb"", false) + if err != nil { + Te.Error(err) + + } + var traj chem.Traj + fmt.Println(""atoms:"", mol.Len()) + trajname := ""../../test/MDCuII_1_7000.crd"" + traj, err = New(trajname, mol.Len(), true) //false) + if err != nil { + Te.Error(err) + } + Coords := make([]*v3.Matrix, 0, 0) + var coords *v3.Matrix + lastread := -1 + for i := 0; i < end; i++ { + if lastread < 0 || (i >= lastread+(skip) && i >= (begin)-1) { + coords = v3.Zeros(traj.Len()) + } + err := traj.Next(coords) //Obtain the next frame of the trajectory. + if err != nil { + _, ok := err.(chem.LastFrameError) + if ok { + break //We processed all frames and are ready, not a real error. + + } else { + Te.Error(err) + } + } + if (lastread >= 0 && i < lastread+(skip)) || i < (begin)-1 { //not so nice check for this twice + continue + } + lastread = i + Coords = append(Coords, coords) + coords = nil // Not sure this works + } + pdbname := ""../../test/MDCuII_1_7000.pdb"" + fout, err := os.Create(pdbname) + if err != nil { + Te.Error(err) + } + defer fout.Close() + err = chem.MultiPDBWrite(fout, Coords, mol, nil) + if err != nil { + Te.Error(err) + } +} +","Go" +"Computational Biochemistry","rmera/gochem","traj/amberold/crd.go",".go","12199","425","/* + * crd.go, part of gochem + * + * Copyright 2018 Raul Mera Adasme + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 2.1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +/* + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + * + */ +/***Dedicated to the long life of the Ven. Khenpo Phuntzok Tenzin Rinpoche***/ + +package amberold + +import ( + ""bufio"" + ""fmt"" + ""os"" + ""strconv"" + ""strings"" + + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" +) + +//Container for an old-Amber/pDynamo trajectory file. +type CrdObj struct { + natoms int + readLast bool //Have we read the last frame? + readable bool //Is it ready to be read? + filename string + nnew bool //Still no frame read from it? + fixed int32 //Fixed atoms (not supported) + ioread *os.File //The crd file + crd *bufio.Reader + remaining []float64 + box bool +} + +//New creates a new Old Amber trajectory object from a file. +func New(filename string, ats int, box bool) (*CrdObj, error) { + var err error + traj := new(CrdObj) + traj.ioread, err = os.Open(filename) + if err != nil { + return nil, Error{UnableToOpen, filename, []string{""New""}, true} + + } + traj.filename = filename + traj.crd = bufio.NewReader(traj.ioread) + _, err = traj.crd.ReadString('\n') //The first line is just a comment + // println(TEST) /////////// + // TEST,err=traj.crd.ReadString('\n') //The first line is just a comment + // println(TEST) //////////// + if err != nil { + return nil, err //CHANGE + } + traj.natoms = ats + traj.remaining = make([]float64, 0, 9) + if box { + traj.box = true + } + traj.readable = true + return traj, nil +} + +//Readable returns true if the object is ready to be read from +//false otherwise. It doesnt guarantee that there is something +//to read. +func (C *CrdObj) Readable() bool { + return C.readable +} + +func (C *CrdObj) Close() { + if !C.readable { + return + } + C.ioread.Close() + C.readable = false +} + +//Next Reads the next frame in a DcDObj that has been initialized for read +//With initread. If keep is true, returns a pointer to matrix.DenseMatrix +//With the coordinates read, otherwiser, it discards the coordinates and +//returns nil. The box argument is never used. +func (C *CrdObj) Next(keep *v3.Matrix, box ...[]float64) error { + const ncoords = 3 + if !C.readable { + return Error{TrajUnIni, C.filename, []string{""Next""}, true} + } + //What do we do with remaining? + cont := -1 + line := 0 + //The following allows discarding a frame while still keeping track of it. + //Everything is the same if you read or discard, except the function that + //would set the values to the matrix simply does nothing in the discard case. + var setter func(file, col int, val float64) + if keep != nil { + setter = func(file, col int, val float64) { + // println(keep.NVecs()) /////////////////////////////////////////// + keep.Set(file, col, val) + + } + } else { + setter = func(file, col int, val float64) {} + } + //Here we read the coords that were left remaining in the last read. + for _, coord := range C.remaining { + if cont < ncoords-1 { + cont++ + setter(line, cont, coord) + continue + } + if cont >= ncoords-1 && line < C.natoms-1 { + line++ + cont = 0 + setter(line, cont, coord) + continue + } + } + cont = -1 + C.remaining = C.remaining[0:0] //This might not work as expected. I need it to set C.remaining to zero length. + for line < C.natoms-1 || cont < 2 { + i, err := C.crd.ReadString('\n') + //here we assume the error is an EOF. I need to change this to actually check. + if err != nil { + C.Close() + // println(err.Error()) ////// + return newlastFrameError(C.filename, ""Next"") + } + l := strings.Fields(i) + for _, j := range l { + coord, err := strconv.ParseFloat(j, 64) + if err != nil { + return Error{fmt.Sprint(""Unable to read coordinates from Amber trajectory"", err.Error()), C.filename, []string{""strconv.ParseFloat"", ""Next""}, true} + } + if cont < ncoords-1 { + cont++ + setter(line, cont, coord) + continue + } + if cont >= ncoords-1 && line < C.natoms-1 { + line++ + cont = 0 + setter(line, cont, coord) + continue + } + if cont >= cont-1 && line >= C.natoms-1 { + + // println(""ql"")//// + C.remaining = append(C.remaining, coord) + } + } + // println(""wei"") //////////// + } + if C.box { + C.nextBox() + } + return nil + +} + +func (C *CrdObj) nextVelBox() error { + var keep *v3.Matrix //nil + const ncoords = 3 + if !C.readable { + return Error{TrajUnIni, C.filename, []string{""Next""}, true} + } + var natoms int = C.natoms + 1 + //What do we do with remaining? + cont := 0 + line := 0 + //The following allows discarding a frame while still keeping track of it. + //Everything is the same if you read or discard, except the function that + //would set the values to the matrix simply does nothing in the discard case. + var setter func(file, col int, val float64) + if keep != nil { + setter = func(file, col int, val float64) { keep.Set(file, col, val) } + } else { + setter = func(file, col int, val float64) {} + } + //Here we read the coords that were left remaining in the last read. + for _, coord := range C.remaining { + if cont < ncoords { + setter(line, cont, coord) + coord++ + continue + } + if cont >= ncoords && line < natoms-1 { + line++ + cont = 0 + setter(line, cont, coord) + cont++ + continue + } + } + C.remaining = C.remaining[0:0] //This might not work as expected. I need it to set C.remaining to zero length. + // println(""remaining:"", len(C.remaining)) + for line < natoms-1 { + i, err := C.crd.ReadString('\n') + //here we assume the error is an EOF. I need to change this to actually check. + if err != nil { + C.Close() + // println(err.Error()) ////// + return newlastFrameError(C.filename, ""Next"") + } + l := strings.Fields(i) + // fmt.Println(l) //////////////////////////////////////////////////////////// + // println(""no"") /////////////////////// + const ncoords = 3 + for _, j := range l { + coord, err := strconv.ParseFloat(j, 64) + if err != nil { + return Error{fmt.Sprint(""Unable to read coordinates from Amber trajectory"", err.Error()), C.filename, []string{""strconv.ParseFloat"", ""Next""}, true} + } + if cont < ncoords { + // println(""no"")//// + setter(line, cont, coord) + cont++ + continue + } + if cont >= ncoords && line < natoms-1 { + // println(""wei"")//// + line++ + cont = 0 + setter(line, cont, coord) + cont++ + continue + } + if cont >= cont && line >= natoms-1 { + + // println(""ql"")//// + C.remaining = append(C.remaining, coord) + } + } + // println(""wei"") //////////// + } + return nil + +} + +func (C *CrdObj) nextBox() error { + var keep *v3.Matrix //nil + const ncoords = 3 + if !C.readable { + return Error{TrajUnIni, C.filename, []string{""Next""}, true} + } + var natoms int = 1 + //What do we do with remaining? + cont := 0 + line := 0 + //The following allows discarding a frame while still keeping track of it. + //Everything is the same if you read or discard, except the function that + //would set the values to the matrix simply does nothing in the discard case. + var setter func(file, col int, val float64) + if keep != nil { + setter = func(file, col int, val float64) { keep.Set(file, col, val) } + } else { + setter = func(file, col int, val float64) {} + } + //Here we read the coords that were left remaining in the last read. + for _, coord := range C.remaining { + if cont < ncoords { + setter(line, cont, coord) + coord++ + continue + } + if cont >= ncoords && line < natoms-1 { + line++ + cont = 0 + setter(line, cont, coord) + cont++ + continue + } + } + C.remaining = C.remaining[0:0] //This might not work as expected. I need it to set C.remaining to zero length. + // println(""remaining:"", len(C.remaining)) + for line < natoms-1 { + i, err := C.crd.ReadString('\n') + //here we assume the error is an EOF. I need to change this to actually check. + if err != nil { + C.Close() + // println(err.Error()) ////// + return newlastFrameError(C.filename, ""Next"") + } + l := strings.Fields(i) + // fmt.Println(l) //////////////////////////////////////////////////////////// + // println(""no"") /////////////////////// + const ncoords = 3 + for _, j := range l { + coord, err := strconv.ParseFloat(j, 64) + if err != nil { + return Error{fmt.Sprint(""Unable to read coordinates from Amber trajectory"", err.Error()), C.filename, []string{""strconv.ParseFloat"", ""Next""}, true} + } + if cont < ncoords { + // println(""no"")//// + setter(line, cont, coord) + cont++ + continue + } + if cont >= ncoords && line < natoms-1 { + // println(""wei"")//// + line++ + cont = 0 + setter(line, cont, coord) + cont++ + continue + } + if cont >= cont && line >= natoms-1 { + + // println(""ql"")//// + C.remaining = append(C.remaining, coord) + } + } + // println(""wei"") //////////// + } + return nil + +} + +//Natoms returns the number of atoms per frame in the XtcObj. +//XtcObj must be initialized. 0 means an uninitialized object. +func (C *CrdObj) Len() int { + return int(C.natoms) +} + +//Errors + +//errDecorate is a helper function that asserts that the error is +//implements chem.Error and decorates the error with the caller's name before returning it. +//if used with a non-chem.Error error, it will cause a panic. +func errDecorate(err error, caller string) error { + err2 := err.(chem.Error) //I know that is the type returned byt initRead + err2.Decorate(caller) + return err2 +} + +//Error is the general structure for Crd trajectory errors. It fullfills chem.Error and chem.TrajError +type Error struct { + message string + filename string //the input file that has problems, or empty string if none. + deco []string + critical bool +} + +func (err Error) Error() string { + return fmt.Sprintf(""Old Amber trajectory file %s error: %s"", err.filename, err.message) +} + +func (E Error) Decorate(deco string) []string { + //Even thought this method does not use a pointer as a receiver, and tries to alter the received, + //it should work, since E.deco is a slice, and hence a pointer itself. + + if deco != """" { + E.deco = append(E.deco, deco) + } + return E.deco +} + +func (err Error) FileName() string { return err.filename } + +func (err Error) Format() string { return ""Old Amber"" } + +func (err Error) Critical() bool { return err.critical } + +const ( + TrajUnIni = ""Traj object uninitialized to read"" + ReadError = ""Error reading frame"" + UnableToOpen = ""Unable to open file"" + SecurityCheckFailed = ""FailedSecurityCheck"" + WrongFormat = ""Wrong format in the trajectory file or frame"" + NotEnoughSpace = ""Not enough space in passed blocks"" + EOF = ""EOF"" +) + +//lastFrameError implements chem.LastFrameError +type lastFrameError struct { + deco []string + fileName string +} + +//lastFrameError does nothing +func (E lastFrameError) NormalLastFrameTermination() {} + +func (E lastFrameError) FileName() string { return E.fileName } + +func (E lastFrameError) Error() string { return ""EOF"" } + +func (E lastFrameError) Critical() bool { return false } + +func (E lastFrameError) Format() string { return ""Old Amber"" } + +func (E lastFrameError) Decorate(deco string) []string { + //Even thought this method does not use a pointer as a receiver, and tries to alter the received, + //it should work, since E.deco is a slice, and hence a pointer itself. + if deco != """" { + E.deco = append(E.deco, deco) + } + return E.deco +} + +func newlastFrameError(filename string, caller string) *lastFrameError { + e := new(lastFrameError) + e.fileName = filename + e.deco = []string{caller} + return e +} +","Go" +"Computational Biochemistry","rmera/gochem","traj/dcd/dcd.go",".go","20368","633","/* + * dcd.go, part of gochem + * + * Copyright 2012 Raul Mera Adasme + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 2.1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +/* + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + * + */ +/***Dedicated to the long life of the Ven. Khenpo Phuntzok Tenzin Rinpoche***/ + +package dcd + +import ( + ""bytes"" + ""encoding/binary"" + ""fmt"" + ""io"" + ""log"" + ""math"" + ""os"" + ""runtime"" + + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" + ""gonum.org/v1/gonum/floats"" +) + +const mAXTITLE int32 = 80 +const rSCAL32BITS int32 = 1 + +//Container for an Charmm/NAMD binary trajectory file. +type DCDObj struct { + natoms int32 + buffSize int + readLast bool //Have we read the last frame? + readable bool //Is it ready to be read? + filename string + charmm bool //Charmm traj? + extrablock bool //simulation box! + fourdim bool + new bool //Still no frame read from it? + fixed int32 //Fixed atoms (not supported) + box [6]float32 + fhandle *os.File + dcd io.ReadCloser //The DCD file + dcdFields [][]float32 + concBuffer [][][]float32 + endian binary.ByteOrder +} + +//Angles in radians, lens in A +func vectors2LenAngles(vecs []float64) ([]float64, []float64) { + lens := make([]float64, 3) + angs := make([]float64, 3) + lens[0] = floats.Norm(vecs[0:3], 2) + lens[2] = floats.Norm(vecs[3:6], 2) + lens[3] = floats.Norm(vecs[6:9], 2) + angs[0] = math.Acos(floats.Dot(vecs[3:6], vecs[6:9]) / (lens[1] * lens[2])) + angs[1] = math.Acos(floats.Dot(vecs[6:9], vecs[0:3]) / (lens[0] * lens[2])) + angs[1] = math.Acos(floats.Dot(vecs[0:3], vecs[3:6]) / (lens[0] * lens[1])) + + return lens, angs +} + +//Lens in A, angles in Radians +func lensAngs2Vecs(lens, angs, vecs []float64) []float64 { + if len(vecs) < 0 { + vecs = make([]float64, 9) + } + vecs[0] = lens[0] + vecs[1] = 0 + vecs[2] = 0 + vecs[3] = lens[1] * math.Cos(angs[2]) + vecs[4] = lens[1] * math.Sin(angs[2]) + vecs[5] = 0 + vecs[6] = lens[2] * math.Cos(angs[1]) + vecs[6] = lens[2] * (math.Cos(angs[0]) - math.Cos(angs[1])*math.Cos(angs[2])) / math.Sin(angs[2]) + //Deal with floating-point fun + cutoff := 1e-5 + for i, v := range vecs { + if v < cutoff { + vecs[i] = 0.0 + } + } + //If anything fails, I'm not crashing the calling program over a stupid box xD + defer func() { + if r := recover(); r != nil { + for i, _ := range vecs { + vecs[i] = 0.0 + } + } + }() + return vecs +} + +//New builds a new DCDObj object from a DCD trajectory file +func New(filename string) (*DCDObj, error) { + traj := new(DCDObj) + if err := traj.initRead(filename); err != nil { + return nil, errDecorate(err, ""New"") + } + traj.dcdFields = make([][]float32, 3, 3) + traj.dcdFields[0] = make([]float32, int(traj.natoms), int(traj.natoms)) + traj.dcdFields[1] = make([]float32, int(traj.natoms), int(traj.natoms)) + traj.dcdFields[2] = make([]float32, int(traj.natoms), int(traj.natoms)) + traj.concBuffer = append(traj.concBuffer, traj.dcdFields) + return traj, nil + +} + +//Readable returns true if the object is ready to be read from +//false otherwise. It doesnt guarantee that there is something +//to read. +func (D *DCDObj) Readable() bool { + return D.readable +} + +//Close Closes the trajectory, including the underlying file +func (D *DCDObj) Close() { + if !D.readable { + return + } + D.dcd.Close() + D.readable = false +} + +//initRead initializes a XtcObj for reading. +//It requires only the filename, which must be valid. +//It support big and little endianness, charmm or (namd>=2.1) and no +//fixed atoms. +func (D *DCDObj) initRead(name string) error { + wrapbinerr := func(err error) error { + return Error{err.Error(), D.filename, []string{""binary.Read"", ""initRead""}, true} + } + + rec_scale := rSCAL32BITS //At least for now we will not support anything else. + D.endian = binary.LittleEndian + _ = rec_scale + NB := bytes.NewBuffer //shortness sake + var err error + D.dcd, err = os.Open(name) + if err != nil { + return Error{err.Error(), D.filename, []string{""os.Open"", ""initRead""}, true} + } + var check int32 + if err := binary.Read(D.dcd, D.endian, &check); err != nil { + return wrapbinerr(err) + } + //For some reason the first thing we should read is an 84. + //If this fails it means that the file is big endian. + if check != 84 { + D.endian = binary.BigEndian // + } + //Then the magic number ""CORD"", also for some unknown reason. + magic := make([]byte, 4, 4) + if err := binary.Read(D.dcd, D.endian, magic); err != nil { + return wrapbinerr(err) + } + if string(magic) != ""CORD"" { + return Error{WrongFormat + "": Wrong magic number"", D.filename, []string{""initRead""}, true} + } + + //We first read a big chuck for random access. + buf := make([]byte, 80, 80) + if err := binary.Read(D.dcd, D.endian, buf); err != nil { + return wrapbinerr(err) + } + //X-plor sets this last int to zero, charmm sets it to its version number. + //if we have a charmm file we get some additional flags. + if err := binary.Read(NB(buf[76:]), D.endian, &check); err != nil { + return wrapbinerr(err) + } + if check != 0 { + // fmt.Println(""CHARMM!!!"") //////77 + D.charmm = true + if err := binary.Read(NB(buf[40:]), D.endian, &check); err != nil { + return wrapbinerr(err) + } + if check != 0 { + // fmt.Println(""block"", check) /////////// + D.extrablock = true + } + if err := binary.Read(NB(buf[40:]), D.endian, &check); err != nil { + return wrapbinerr(err) + } + if check == 1 { + // fmt.Println(""4-dim"", check) /////////// + D.fourdim = true + } + + } else { + return Error{WrongFormat + "": X-plor DCD not supported"", D.filename, []string{""initRead""}, true} + } + if err := binary.Read(NB(buf[32:]), D.endian, &D.fixed); err != nil { + return Error{err.Error(), D.filename, []string{""initRead""}, true} + + } + // fmt.Println(""fixed"", D.fixed) + var delta float32 //This should work only on Charmm and namd >=2.1 + if err := binary.Read(NB(buf[36:]), D.endian, &delta); err != nil { + return wrapbinerr(err) + } + // fmt.Println(""delta:"", delta)/////////////////////////////////////// + + if err := binary.Read(D.dcd, D.endian, &check); err != nil { + return Error{err.Error(), D.filename, []string{""initRead""}, true} + } + if check != 84 { + return Error{WrongFormat, D.filename, []string{""initRead""}, true} + } + var input_int int32 + if err := binary.Read(D.dcd, D.endian, &input_int); err != nil { + return wrapbinerr(err) + } + //how many units of mAXTITLE does the title have? + var ntitle int32 + if err := binary.Read(D.dcd, D.endian, &ntitle); err != nil { + return wrapbinerr(err) + } + title := make([]byte, mAXTITLE*ntitle, mAXTITLE*ntitle) + if err := binary.Read(D.dcd, D.endian, title); err != nil { + return wrapbinerr(err) + } + // fmt.Println(""Title:"", string(title))/////////////////////////////////////// + if err := binary.Read(D.dcd, D.endian, &input_int); err != nil { + return wrapbinerr(err) + + } + if err := binary.Read(D.dcd, D.endian, &check); err != nil { + return wrapbinerr(err) + + } + if check != 4 { //one must read a 4 before the natoms + return Error{WrongFormat, D.filename, []string{""initRead""}, true} + } + if err := binary.Read(D.dcd, D.endian, &D.natoms); err != nil { + return wrapbinerr(err) + } + // fmt.Println(""natoms"", D.natoms) + if err := binary.Read(D.dcd, D.endian, &check); err != nil { + return wrapbinerr(err) + } + if check != 4 { //and one more 4 + return Error{WrongFormat, D.filename, []string{""initRead""}, true} + } + if D.fixed == 0 { + runtime.SetFinalizer(D, func(D *DCDObj) { + D.dcd.Close() + }) + D.readable = true + return nil //nothing else to do + } + D.new = true //nothing read yet + return Error{""Fixed atoms not supported"", D.filename, []string{""initRead""}, true} + +} + +//Next Reads the next frame in a DcDObj that has been initialized for read +//With initread. If keep is true, returns a pointer to matrix.DenseMatrix +//With the coordinates read, otherwiser, it discards the coordinates and +//returns nil. +func (D *DCDObj) Next(keep *v3.Matrix, box ...[]float64) error { + if !D.readable { + return Error{TrajUnIni, D.filename, []string{""Next""}, true} + } + + if D.dcdFields == nil { + D.dcdFields = make([][]float32, 3, 3) + D.dcdFields[0] = make([]float32, int(D.natoms), int(D.natoms)) + D.dcdFields[1] = make([]float32, int(D.natoms), int(D.natoms)) + D.dcdFields[2] = make([]float32, int(D.natoms), int(D.natoms)) + } + if err := D.nextRaw(D.dcdFields); err != nil { + return errDecorate(err, ""Next"") + } + if keep == nil { + return nil + } + if r, _ := keep.Dims(); int32(r) < D.natoms { + panic(""Not enough space in matrix"") + } + //outBlock := make([]float64, int(D.natoms)*3, int(D.natoms)*3) + for i := 0; i < int(D.natoms); i++ { + k := i - i*(i/int(D.natoms)) + keep.Set(k, 0, float64(D.dcdFields[0][k])) + keep.Set(k, 1, float64(D.dcdFields[1][k])) + keep.Set(k, 2, float64(D.dcdFields[2][k])) + } + // final := NewVecs(outBlock, int(D.natoms), 3) + // fmt.Print(final)/////////7 + if len(box) > 0 && D.extrablock && !allZeros(D.box) { + lens := []float64{float64(D.box[0]), float64(D.box[2]), float64(D.box[5])} + angs := []float64{float64(D.box[1]), float64(D.box[3]), float64(D.box[4])} + box[0] = lensAngs2Vecs(lens, angs, box[0]) //No error here, if it doesn't work, + //you just get a bunch of zeros as a box. + + //Here we reset the ""box buffer"" to zeros, so, if the next call fails, you get zeros + //and not something weird. + for i, _ := range D.box { + D.box[i] = 0 + } + } + //If we couldn't get box info, you'll at least get a heads-up. + if len(box) > 0 { + if !D.extrablock { + log.Printf(""The trajectory %s does not contain box info\n"", D.filename) + } + if D.extrablock && allZeros(D.box) { + log.Printf(""The trajectory %s contains box info, but"", D.filename) + log.Printf(""It's either absent from this frame, or it could not be read\n"") + } + } + return nil +} + +func allZeros(test [6]float32) bool { + for _, v := range test { + if v != 0.0 { + return false + } + } + return true + +} + +//Next Reads the next frame in a XtcObj that has been initialized for read +//With initread. If keep is true, returns a pointer to matrix.DenseMatrix +//With the coordinates read, otherwiser, it discards the coordinates and +//returns nil. +func (D *DCDObj) nextRaw(blocks [][]float32) error { + if len(blocks[0]) != int(D.natoms) || len(blocks[1]) != int(D.natoms) || len(blocks[2]) != int(D.natoms) { + return Error{NotEnoughSpace, D.filename, []string{""nextRaw""}, true} + } + D.new = false + if D.readLast { + D.Close() + return newlastFrameError(D.filename, ""nextRaw"") + } + //if there is an extra block we just skip it. + //Sadly, even when there is an extra block, it is not present in all + //snapshots for some trajectories, so we must use the block size to see if + //there is an extra block or if the X block starts inmediately + var blocksize int32 + if D.extrablock { + if err := binary.Read(D.dcd, D.endian, &blocksize); err != nil { + D.Close() + return newlastFrameError(D.filename, ""nextRaw"") + } + //If the blocksize is 4*natoms it means that the block is not an + //extra block, but the X coordinates, and thus we must skip the following. + //We will use the weaker condition blocksize batchsize { + for i := batchsize; i < l; i++ { + for j, _ := range D.concBuffer[i] { + D.concBuffer[i][j] = nil + } + D.concBuffer[i] = nil //no idea if this actually works. Edit: According to tests it does work. + } + D.concBuffer = D.concBuffer[:batchsize-1] //not sure if this frees the remaining []float32 slices + D.buffSize = batchsize + return nil + } + for i := 0; i < batchsize-l; i++ { + x := make([]float32, D.Len()) + y := make([]float32, D.Len()) + z := make([]float32, D.Len()) + tmp := [][]float32{x, y, z} + D.concBuffer = append(D.concBuffer, tmp) + } + D.buffSize = batchsize + return nil +} + +//NextConc takes a slice of bools and reads as many frames as elements the list has +//form the trajectory. The frames are discarted if the corresponding elemetn of the slice +//is false. The function returns a slice of channels through each of each of which +// a *matrix.DenseMatrix will be transmited +func (D *DCDObj) NextConc(frames []*v3.Matrix) ([]chan *v3.Matrix, error) { + if !D.Readable() { + return nil, Error{TrajUnIni, D.filename, []string{""NextConc""}, true} + } + framechans := make([]chan *v3.Matrix, len(frames)) //the slice of chans that will be returned + if D.buffSize < len(frames) { + D.setConcBuffer(len(frames)) + } + for key, _ := range frames { + DFields := D.concBuffer[key] + if err := D.nextRaw(DFields); err != nil { + return nil, errDecorate(err, ""NextConc"") + } + //We have to test for used twice to allow allocating for goCoords + //When the buffer is not going to be used. + if frames[key] == nil { + framechans[key] = nil //ignored frame + continue + } + framechans[key] = make(chan *v3.Matrix) + //Now the parallel part + go func(natoms int, DFields [][]float32, keep *v3.Matrix, pipe chan *v3.Matrix) { + for i := 0; i < int(D.natoms); i++ { + k := i - i*(i/int(D.natoms)) + keep.Set(k, 0, float64(DFields[0][k])) + keep.Set(k, 1, float64(DFields[1][k])) + keep.Set(k, 2, float64(DFields[2][k])) + } + // fmt.Println(""in gorutine!"", temp.GetRowVector(2)) + pipe <- keep + }(int(D.natoms), DFields, frames[key], framechans[key]) + } + return framechans, nil +} + +//Errors + +//errDecorate is a helper function that asserts that the error is +//implements chem.Error and decorates the error with the caller's name before returning it. +//if used with a non-chem.Error error, it will cause a panic. +func errDecorate(err error, caller string) error { + err2 := err.(chem.Error) //I know that is the type returned byt initRead + err2.Decorate(caller) + return err2 +} + +//Error is the general structure for DCD trajectory errors. It fullfills chem.Error and chem.TrajError +type Error struct { + message string + filename string //the input file that has problems, or empty string if none. + deco []string + critical bool +} + +func (err Error) Error() string { + return fmt.Sprintf(""dcd file %s error: %s"", err.filename, err.message) +} + +//Decorate Adds new information to the error +func (E Error) Decorate(deco string) []string { + //Even thought this method does not use a pointer as a receiver, and tries to alter the received, + //it should work, since E.deco is a slice, and hence a pointer itself. + + if deco != """" { + E.deco = append(E.deco, deco) + } + return E.deco +} + +//Filename returns the file to which the failing trajectory was associated +func (err Error) FileName() string { return err.filename } + +//Format returns the format of the file (always ""dcd"") associated to the error +func (err Error) Format() string { return ""dcd"" } + +//Critical returns true if the error is critical, false otherwise +func (err Error) Critical() bool { return err.critical } + +const ( + TrajUnIni = ""Traj object uninitialized to read"" + ReadError = ""Error reading frame"" + UnableToOpen = ""Unable to open file"" + SecurityCheckFailed = ""FailedSecurityCheck"" + WrongFormat = ""Wrong format in the DCD file or frame"" + NotEnoughSpace = ""Not enough space in passed blocks"" + EOF = ""EOF"" +) + +//lastFrameError implements chem.LastFrameError +type lastFrameError struct { + deco []string + fileName string +} + +//lastFrameError does nothing +func (E lastFrameError) NormalLastFrameTermination() {} + +func (E lastFrameError) FileName() string { return E.fileName } + +func (E lastFrameError) Error() string { return ""EOF"" } + +func (E lastFrameError) Critical() bool { return false } + +func (E lastFrameError) Format() string { return ""dcd"" } + +func (E lastFrameError) Decorate(deco string) []string { + //Even thought this method does not use a pointer as a receiver, and tries to alter the received, + //it should work, since E.deco is a slice, and hence a pointer itself. + if deco != """" { + E.deco = append(E.deco, deco) + } + return E.deco +} + +func newlastFrameError(filename string, caller string) *lastFrameError { + e := new(lastFrameError) + e.fileName = filename + e.deco = []string{caller} + return e +} +","Go" +"Computational Biochemistry","rmera/gochem","traj/dcd/compressed.go",".go","4912","153","/* + * dcd.go, part of gochem + * + * Copyright 2012 Raul Mera Adasme + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 2.1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ + +package dcd + +import ( + ""bufio"" + ""compress/flate"" + ""compress/lzw"" + ""io"" + ""log"" + ""os"" + ""strconv"" + ""strings"" +) + +const ( + lzwOrder = lzw.MSB + lzwLitwidth int = 8 +) + +//prepSource takes a filename and format string, opens the file and returns an object that will +// read data from the file, either 'as is' or decompressing first, it depending on the format string. +//If the format string is empty, it will try to deduce it form the file extension. File extensions supported are +//.dcd (non-compressed dcd), .gz (deflate) and .lzw. If the format string is empty and the extension doesn't +//match any supported type, a message will be logged and the non-compressed dcd format will be assumed. +//thus, prepSource only returns an error if the file can't be opened. +func (D *DCDObj) prepSource(fname string, format string) (io.ReadCloser, error) { + var err error + var fk string + var ret io.ReadCloser + if format == """" { + temp := strings.Split(fname, ""."") + fk = strings.ToLower(temp[len(temp)-1]) + } else { + fk = format + } + D.filename = fname + D.fhandle, err = os.Open(fname) + if err != nil { + return nil, Error{err.Error(), D.filename, []string{""os.Open"", ""prepSource""}, true} + } + reader := bufio.NewReader(D.fhandle) + + switch fk { + + case ""dcd"": + ret = D.fhandle + + case ""lzw"": + ret = lzw.NewReader(reader, lzwOrder, lzwLitwidth) + case ""gz"": + ret = flate.NewReader(reader) + default: + //if it's not a plain DCD, you'll get an error later. + log.Printf(""Format string %s not supported. %s will be assumed to be a plain DCD file"", fk, D.filename) + D.dcd = D.fhandle + } + return ret, nil + +} + +//parselevel parses a string into a compression extension and +//a compression level. +//The string needs to be in the format: gz_level (ejemplo: gz_-2) +//if any part of the procedure fails, we will assume that there is no +//""level"" and we return the whole file name, and a default value for +//level (-2, corresponding to the poorest, but faster, compression. +//Note that the compression level obtained only makes sense in the +//context of deflate (zlib or gzip) compression. +func parseLevel(f string) (string, int) { + data := strings.Split(f, ""_"") + if len(data) != 2 || data[0] != strings.ToLower(""gz"") { + return f, -2 + } + level, err := strconv.Atoi(data[1]) + if err != nil { + return f, -2 + } + if level < -2 || level > 9 { + if data[0] == ""gz"" { + return data[0], -2 + } else { + return f, -2 + } + } + return data[0], level +} + +//As you can see I wrote the whole function just to be reminded that it can not work, because +//DCD for _some_ reason, requires the number of frames at the begining, and so you need to +//move back and forth through the file every time you write a new frame. ^_^ We really +//need less crazy formats for MD. + +//prepTarget takes fname, the name of a DCD trajectory file and format, a string +//that is either empty or indicates a compression format. +//It creates the file and returns a io.WriteCloser that will write data, crude or +//compressed, with deflate (gzip/zlib) or with lzw, depending on the file extension. +//(.gz for deflate, .lzw for lzw, any other extension for a non compressed dcd) +//The file extension may contain information about the compression level, +//which applies only to deflate. If so, the requested compression level will be used. +/* +prepTarget(D *DCDWObj, fname string) (io.WriteCloser, error) { + var err error + var fk string + var tmpfk string + var ret io.WriteCloser + temp := strings.Split(fname, ""."") + tmpfk = strings.ToLower(temp[len(temp)-1]) + fk, level := parseLevel(tmpfk) + D.filename = fname + D.fhandle, err = os.Create(fname) + if err != nil { + return nil, Error{err.Error(), D.filename, []string{""os.Open"", ""prepTarget""}, true} + } + writer := bufio.NewWriter(D.fhandle) + + switch fk { + + case ""dcd"": + ret = D.fhandle + + case ""lzw"": + ret = lzw.NewWriter(writer, lzwOrder, lzwLitwidth) + case ""gz"": + ret, err = flate.NewWriter(writer, level) + default: + log.Printf(""Format string %s not supported. %s will be written to be a plain DCD file"", fk, D.filename) + D.dcd = D.fhandle + } + return ret, nil + +} +**/ +","Go" +"Computational Biochemistry","rmera/gochem","traj/dcd/dcd_write.go",".go","10438","337","// +build !goyira +/* + * dcd_write.go, part of gochem + * + * Copyright 2021 Raul Mera Adasme + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 2.1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + */ + +package dcd + +import ( + ""encoding/binary"" + ""fmt"" + ""io"" + ""os"" + ""runtime"" + + v3 ""github.com/rmera/gochem/v3"" +) + +//const mAXTITLE int32 = 80 +//const rSCAL32BITS int32 = 1 + +//A writing buffer for DCD format +type WB []byte + +//Writes w to the buffer +func (B WB) Write(w []byte) (int, error) { + if len(B) < len(w) { + return 0, fmt.Errorf(""mismatched buffers"") + } + for i := range w { + B[i] = w[i] + } + return len(w), nil +} + +//Container for an Charmm/NAMD binary trajectory file. +//opened for writing +type DCDWObj struct { + natoms int32 + buffSize int + readLast bool //Have we read the last frame? + writable bool //Is it ready to be written on + filename string + charmm bool //Charmm traj? + extrablock bool + fourdim bool + frames int32 + new bool //Still no frame written to it it? + fixed int32 //Fixed atoms (not supported) + dcd *os.File //The DCD file + dcdFields [][]float32 + concBuffer [][][]float32 + endian binary.ByteOrder +} + +//New writer initializes a DCD trajectory for writing. +func NewWriter(filename string, natoms int) (*DCDWObj, error) { + traj := new(DCDWObj) + traj.natoms = int32(natoms) + if err := traj.initWrite(filename); err != nil { + return nil, errDecorate(err, ""New"") + } + // traj.dcdFields = make([][]float32, 3, 3) + // traj.dcdFields[0] = make([]float32, natoms, natoms) + // traj.dcdFields[1] = make([]float32, natoms, natoms) + // traj.dcdFields[2] = make([]float32, natoms, natoms) + + return traj, nil + +} + +func (D *DCDWObj) Close() { + if !D.writable { + return + } + D.dcd.Close() + D.writable = false + +} + +//InitRead initializes a XtcObj for reading. +//It requires only the filename, which must be valid. +//It support big and little endianness, charmm or (namd>=2.1) and no +//fixed atoms. +func (D *DCDWObj) initWrite(name string) error { + wrapbinerr := func(err error) error { + return Error{err.Error(), D.filename, []string{""binary.Write"", ""initWrite""}, true} + } + + D.endian = binary.LittleEndian + var err error + D.dcd, err = os.Create(name) + if err != nil { + return Error{err.Error(), D.filename, []string{""os.Open"", ""initWrite""}, true} + } + if err := binary.Write(D.dcd, D.endian, int32(84)); err != nil { + return wrapbinerr(err) + } + //For some reason, we have to write this magic number. + magic := []byte(""CORD"") + if err := binary.Write(D.dcd, D.endian, magic); err != nil { + return wrapbinerr(err) + } + //The frames in the file go here. No frames written yet, but will update this part after every write. + if err := binary.Write(D.dcd, D.endian, int32(0)); err != nil { + return wrapbinerr(err) + } + //Initial time + if err := binary.Write(D.dcd, D.endian, int32(0)); err != nil { + return wrapbinerr(err) + } + //step interval (nsavc) + if err := binary.Write(D.dcd, D.endian, int32(1)); err != nil { + return wrapbinerr(err) + } + //5 zeros plus natom-rfreat + for i := 0; i < 6; i++ { + if err := binary.Write(D.dcd, D.endian, int32(0)); err != nil { + return wrapbinerr(err) + } + + } + //delta time + if err := binary.Write(D.dcd, D.endian, float32(1)); err != nil { + return wrapbinerr(err) + } + //No unit cell + if err := binary.Write(D.dcd, D.endian, int32(0)); err != nil { + return wrapbinerr(err) + } + //8 zeros for charmm + for i := 0; i < 8; i++ { + if err := binary.Write(D.dcd, D.endian, int32(0)); err != nil { + return wrapbinerr(err) + } + } + //charmm version, let's say, 24 + if err := binary.Write(D.dcd, D.endian, int32(24)); err != nil { + return wrapbinerr(err) + } + + //don't ask me why + if err := binary.Write(D.dcd, D.endian, int32(84)); err != nil { + return wrapbinerr(err) + } + //same as above + if err := binary.Write(D.dcd, D.endian, int32(244)); err != nil { + return wrapbinerr(err) + } + + //how many units of mAXTITLE does the title have? + var ntitle int32 = 2 //just a dummy title. + if err := binary.Write(D.dcd, D.endian, ntitle); err != nil { + return wrapbinerr(err) + } + title := make([]byte, 2*mAXTITLE, 2*mAXTITLE) + //Not a very good title, I suppose + for j := range title { + title[j] = byte('l') + } + title[len(title)-1] = byte('\000') //null-ended + if err := binary.Write(D.dcd, D.endian, title); err != nil { + return wrapbinerr(err) + } + //no idea + if err := binary.Write(D.dcd, D.endian, int32(244)); err != nil { + return wrapbinerr(err) + } + //no idea + if err := binary.Write(D.dcd, D.endian, int32(4)); err != nil { + return wrapbinerr(err) + } + //ok, this is important, the number of atoms in each snapshot + //We should have got the number of atoms when we created the object. Will check just in case. + //if it's zero it means it hasn't been set. + if D.natoms == 0 { + return Error{""Trajectory not initialized correctly, the number of atoms is set to zero!"", D.filename, []string{""initWrite""}, true} + } + if err := binary.Write(D.dcd, D.endian, D.natoms); err != nil { + return wrapbinerr(err) + } + //same as above + if err := binary.Write(D.dcd, D.endian, int32(4)); err != nil { + return wrapbinerr(err) + } + runtime.SetFinalizer(D, func(D *DCDWObj) { + D.dcd.Close() + }) + D.writable = true + D.new = true //nothing read yet + return nil //nothing else to do +} + +//WNext rites the next frame to the trajectory. +//the box isn't actually used, so far. It's only there for compatibility. +func (D *DCDWObj) WNext(towrite *v3.Matrix, box ...[]float64) error { + if !D.writable { + return Error{TrajUnIni, D.filename, []string{""WNext""}, true} + } + if towrite == nil { + return Error{""got nil coordinates"", D.filename, []string{""WNext""}, true} + + } + if int32(towrite.NVecs()) != D.natoms { + return Error{""Coordinates don't match the trajectory size"", D.filename, []string{""WNext""}, true} + } + if D.dcdFields == nil { + D.dcdFields = make([][]float32, 3, 3) + D.dcdFields[0] = make([]float32, int(D.natoms), int(D.natoms)) + D.dcdFields[1] = make([]float32, int(D.natoms), int(D.natoms)) + D.dcdFields[2] = make([]float32, int(D.natoms), int(D.natoms)) + } + //This is easier to write to the dcd + for i := 0; i < int(D.natoms); i++ { + k := i - i*(i/int(D.natoms)) //magic xD + D.dcdFields[0][k] = float32(towrite.At(k, 0)) + D.dcdFields[1][k] = float32(towrite.At(k, 1)) + D.dcdFields[2][k] = float32(towrite.At(k, 2)) + } + D.wnextRaw(D.dcdFields) + D.frames++ + D.updateFrames() + return nil +} + +//Next Reads the next frame in a XtcObj that has been initialized for read +//With initread. If keep is true, returns a pointer to matrix.DenseMatrix +//With the coordinates read, otherwiser, it discards the coordinates and +//returns nil. +func (D *DCDWObj) wnextRaw(blocks [][]float32) error { + if len(blocks[0]) != int(D.natoms) || len(blocks[1]) != int(D.natoms) || len(blocks[2]) != int(D.natoms) { + return Error{NotEnoughSpace, D.filename, []string{""nextRaw""}, true} + } + D.new = false + var blocksize int32 = int32(len(blocks[0])) * 4 //the ""4"" is because the size is required in bytes, apparently. + //now get the coords, each as a slice of float32 + //X + if err := binary.Write(D.dcd, D.endian, blocksize); err != nil { + return err + } + + err := D.writeFloat32Block(blocks[0]) + if err != nil { + return errDecorate(err, ""nextRaw"") + } + //Y + //Collect the size first, then the rest + if err := binary.Write(D.dcd, D.endian, blocksize); err != nil { + return err + } + err = D.writeFloat32Block(blocks[1]) + if err != nil { + return errDecorate(err, ""nextRaw"") + } + //Z + if err := binary.Write(D.dcd, D.endian, blocksize); err != nil { + return Error{err.Error(), D.filename, []string{""binary.Write"", ""wnextRaw""}, true} + } + err = D.writeFloat32Block(blocks[2]) + if err != nil { + return errDecorate(err, ""nextRaw"") + } + // fmt.Println(""Z"", blocks[2]) + //we skip the 4-D values if they exist. Apparently this is not present in the + //last snapshot, so we use an EOF here to signal that we have read the last snapshot. + return nil + +} + +//Writes a block of float32s to the file, adding its size +func (D *DCDWObj) writeFloat32Block(block []float32) error { + var blocksize int32 = int32(len(block)) * 4 + if err := binary.Write(D.dcd, D.endian, block); err != nil { + return Error{err.Error(), D.filename, []string{""binary.Write"", ""writeFloat32Block""}, true} + + } + if err := binary.Write(D.dcd, D.endian, blocksize); err != nil { + return Error{err.Error(), D.filename, []string{""binary.Write"", ""writeFloat32Block""}, true} + } + return nil +} + +//DCD is silly enough to require the number of frames at the begining. +func (D *DCDWObj) updateFrames() error { + currentoffset, err := D.dcd.Seek(0, io.SeekCurrent) //we'll need it to go back + if err != nil { + return Error{err.Error(), D.filename, []string{""dcd.Seek"", ""updateFrame""}, true} + } + //now we go to the begining of the file + _, err = D.dcd.Seek(0, io.SeekStart) + if err != nil { + return Error{err.Error(), D.filename, []string{""dcd.Seek"", ""updateFrame""}, true} + } + + wrapbinerr := func(err error) error { + return Error{err.Error(), D.filename, []string{""binary.Write"", ""updateFrame""}, true} + } + //I could try to get directly to the part we need to write, but it's so close to the begining that I think it's best to just write a couple + //of unnecesary numbers. + if err := binary.Write(D.dcd, D.endian, int32(84)); err != nil { + return wrapbinerr(err) + } + //For some reason, we have to write this magic number. + magic := []byte(""CORD"") + if err := binary.Write(D.dcd, D.endian, magic); err != nil { + return wrapbinerr(err) + } + if err := binary.Write(D.dcd, D.endian, int32(D.frames)); err != nil { + return wrapbinerr(err) + } + //we go back to the part of the file we were reading + _, err = D.dcd.Seek(currentoffset, io.SeekStart) + if err != nil { + return Error{err.Error(), D.filename, []string{""dcd.Seek"", ""updateFrame""}, true} + } + + return nil + +} +","Go" +"Computational Biochemistry","rmera/gochem","traj/dcd/dcd_test.go",".go","5980","252","/* + * dcd_test.go + * + * Copyright 2012 Raul Mera Adasme + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + */ +/* + * + * + */ + +package dcd + +import ( + ""fmt"" + ""testing"" + + chem ""github.com/rmera/gochem"" + + v3 ""github.com/rmera/gochem/v3"" +) + +func TestDCDWrite2(Te *testing.T) { + mol, traj, err := chem.XYZFileAsTraj(""../../test/traj.xyz"") + if err != nil { + fmt.Println(""There was an error!"", err.Error()) + Te.Error(err) + } + trajW, err := NewWriter(""../../test/testW2.dcd"", mol.Len()) + if err != nil { + Te.Error(err) + } + + for i := 0; ; i++ { + fmt.Println(""frame"", i, ""!!"") + err := traj.Next(mol.Coords[0]) + if err != nil { + if _, ok := err.(chem.LastFrameError); ok { + break + } + Te.Error(err) + break + } + trajW.WNext(mol.Coords[0]) + } + + fmt.Println(""XYZ read!"") +} + +//Tests the writing capabilities. +func TestDCDWrite(Te *testing.T) { + fmt.Println(""First test!"") + mol, err := chem.XYZFileRead(""../../test/traj.xyz"") + if err != nil { + Te.Error(err) + } + traj, err := NewWriter(""../../test/testW2.dcd"", mol.Len()) + if err != nil { + Te.Error(err) + } + i := 0 + mat := v3.Zeros(mol.Len()) + for ; ; i++ { + err := mol.Next(mat) + if err != nil { + if _, ok := err.(chem.LastFrameError); ok { + break + } + Te.Error(err) + break + } + traj.WNext(mat) + } + fmt.Println(""Over! frames read and written:"", i) +} + +/*TestDCD reads the frames of the test xtc file using the + * ""interactive"" or ""low level"" functions, i.e. one frame at a time + * It prints the firs 2 coordinates of each frame and the number of + * read frames at the end.*/ +func TestDCD(Te *testing.T) { + fmt.Println(""Fist test!"") + traj, err := New(""../../test/test_align.dcd"") + if err != nil { + Te.Error(err) + } + i := 0 + box := make([]float64, 9) + mat := v3.Zeros(traj.Len()) + for ; ; i++ { + err := traj.Next(mat, box) + if err != nil { + if _, ok := err.(chem.LastFrameError); ok { + break + } + Te.Error(err) + break + } + fmt.Println(mat.VecView(2), box) + mat.Zero() + } + fmt.Println(""Over! frames read:"", i) +} + +func TestFrameDCDConc(Te *testing.T) { + traj, err := New(""../../test/test_align.dcd"") + if err != nil { + Te.Error(err) + } + frames := make([]*v3.Matrix, 3, 3) + for i, _ := range frames { + frames[i] = v3.Zeros(traj.Len()) + } + results := make([][]chan *v3.Matrix, 0, 0) + for i := 0; ; i++ { + results = append(results, make([]chan *v3.Matrix, 0, len(frames))) + coordchans, err := traj.NextConc(frames) + if err != nil { + if _, ok := err.(chem.LastFrameError); ok { + fmt.Printf(""Frames read: %d\n"", i*len(frames)) + break + } + Te.Error(err) + break + } + for key, channel := range coordchans { + results[len(results)-1] = append(results[len(results)-1], make(chan *v3.Matrix)) + go SecondRow(channel, results[len(results)-1][key], len(results)-1, key) + } + res := len(results) - 1 + for frame, k := range results[res] { + if k == nil { + fmt.Println(frame) + continue + } + fmt.Println(res, frame, <-k) + } + } +} + +/* for framebunch, j := range results { + if j == nil { + break + } + for frame, k := range j { + if k == nil { + fmt.Println(framebunch, frame) + continue + } + fmt.Println(framebunch, frame, <-k) + } + } +} +*/ +func SecondRow(channelin, channelout chan *v3.Matrix, current, other int) { + if channelin != nil { + temp := <-channelin + viej := v3.Zeros(1) + vector := temp.VecView(2) + viej.Copy(vector) + fmt.Println(""sending througt"", channelin, channelout, viej, current, other) + channelout <- vector + } else { + channelout <- nil + } + return +} + +/* +//TestFrameXtc reads the frames of the test xtc file from the first to +// the forth frame skipping one frame for each read one. It uses the +// ""high level"" function. It prints the frames read twince, and the +// coordinates of the forth atom of the last read frame +func TestFrameDCD(Te *testing.T) { + fmt.Println(""Second test!"") + traj,err:=NewDCD(""test/test.dcd"") + if err != nil { + Te.Error(err) + } + Coords, read, err := ManyFrames(traj,0, 5, 1) + if err != nil { + Te.Error(err) + } + fmt.Println(len(Coords), read, VecView(Coords[read-1],4)) + fmt.Println(""DCD second test over!"") +} + +func TestFrameDCDConc(Te *testing.T) { + fmt.Println(""Third test!"") + traj,err:=NewDCD(""test/test.dcd"") + if err != nil { + Te.Error(err) + } + frames := []bool{true, true, true} + results := make([][]chan *VecMatrix, 0, 0) + _ = matrix.ZeroVecs(3, 3) ////////////// + for i := 0; ; i++ { + results = append(results, make([]chan *VecMatrix, 0, len(frames))) + coordchans, err := traj.NextConc(frames) + if err != nil && err.Error() != ""No more frames"" { + Te.Error(err) + } else if err != nil { + if coordchans == nil { + break + } + } + for key, channel := range coordchans { + results[len(results)-1] = append(results[len(results)-1], make(chan *VecMatrix)) + go SecondRow(channel, results[len(results)-1][key], len(results)-1, key) + } + } + for framebunch, j := range results { + if j == nil { + break + } + for frame, k := range j { + if k == nil { + fmt.Println(framebunch, frame) + continue + } + fmt.Println(framebunch, frame, <-k) + } + } +} +*/ +/* +func SecondRow(channelin, channelout chan *VecMatrix, current, other int) { + if channelin != nil { + temp := <-channelin + vector := VecView(temp, 2) + fmt.Println(""sending througt"", channelin, channelout, vector, current, other) + channelout <- vector + } else { + channelout <- nil + } + return +} +*/ +","Go" +"Computational Biochemistry","rmera/gochem","traj/xtc/libgoxtc.c",".c","2674","105","/* + * xtc.c + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + + +#include +#include +#include ""xdrfile.h"" +#include ""xdrfile_xtc.h"" + +int get_coords(XDRFILE *fp, float *coordbuffer, float *box, int natoms); +XDRFILE *openfile(char *name); +int read_natoms(char *name); +void xtc_close(XDRFILE *fp); + + +/* +int main(int argc, char **argv){ + int first=1; + int skip=2; + int end=6; + int i=0; //iterator + char name[20]=""test.xtc""; + XDRFILE *fp; + int natoms=0; + float *coords; + read_xtc_natoms(name,&natoms); + if (natoms==0){ + return 1; + } + printf(""read!, %d\n"",natoms); + fp=xdrfile_open(name,""r""); + if (fp==NULL){ + return 1; + } + for(i=first;i<=end;i++){ + coords=get_coords(fp,natoms); + } + + } +*/ + + +XDRFILE *openfile(char *name){ + XDRFILE *fp; + fp=xdrfile_open(name,""r""); + return fp; /*NULL if something goes wrong.*/ + } + +int read_natoms(char *name){ + int natoms=0; + read_xtc_natoms(name,&natoms); + return natoms; /*should return 0 if something goes wrong.*/ + } + +void xtc_close(XDRFILE *fp){ + xdrfile_close(fp); + } + +/*get_coords is meant to be called from Go functions. +It takes an XDRFILE pointer (fp), which can be treated just as an opaque +* object in Go, the number of atoms to be read (natoms) +* and a *float pointer to a buffer with enough space to +* save all the coordinates in a frame. This buffer should be allocated +* from Go, so it is garbage collected. +* The function returns 0 on success and other number depending on the +* error encountered*/ +int get_coords(XDRFILE *fp, float *coordbuffer,float *box, int natoms){ + int step=0; + int success=0; + rvec *coords; + rvec *grobox; + //float box[3][3]; + float prec=0; + float time=0; + coords=(rvec *)coordbuffer; /*This is the type the GROMACS function wants*/ + grobox=(rvec *)box; + if (coords==NULL){ + return 1; + } + success=read_xtc(fp,natoms,&step,&time,grobox, + coords,&prec); + return success; + } + +","C" +"Computational Biochemistry","rmera/gochem","traj/xtc/xtc.h",".h","274","9","#include +#include +#include ""xdrfile.h"" +#include ""xdrfile_xtc.h"" +int get_coords(XDRFILE *fp, float *coordbuffer, float *box, int natoms); //Delcare like a good guy. +XDRFILE *openfile(char *name); +int read_natoms(char *name); +void xtc_close(XDRFILE *fp); +","Unknown" +"Computational Biochemistry","rmera/gochem","traj/xtc/xtc_test.go",".go","3727","153","/* + * untitled.go + * + * Copyright 2012 Raul Mera Adasme + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + */ +/* + * + * + * + */ + +package xtc + +import ( + ""fmt"" + ""testing"" + + chem ""github.com/rmera/gochem"" + + v3 ""github.com/rmera/gochem/v3"" +) + +/*TestXTC reads the frames of the test xtc file using the + * ""interactive"" or ""low level"" functions, i.e. one frame at a time + * It prints the firs 2 coordinates of each frame and the number of + * read frames at the end.*/ +func TestXTC(Te *testing.T) { + fmt.Println(""First test"") + traj, err := New(""../../test/test.xtc"") + if err != nil { + Te.Error(err) + } + i := 0 + coords := v3.Zeros(traj.Len()) + box := make([]float64, 9) +reading: + for ; ; i++ { + err := traj.Next(coords, box) + if err != nil { + switch err := err.(type) { + default: + Te.Error(err) + fmt.Println(err.Error(), ""Para tu weveo longi"") + break reading + case chem.LastFrameError: + fmt.Println(""No More!"") + break reading + } + } + fmt.Println(coords.VecView(2), box) + + } + fmt.Println(""Over! frames read:"", i) +} + +/* +//TestFrameXTC reads the frames of the test xtc file from the first to +// the forth frame skipping one frame for each read one. It uses the +// ""high level"" function. It prints the frames read twince, and the +// coordinates of the forth atom of the last read frame +func TestFrameXTC(Te *testing.T) { + fmt.Println(""Second test!"") + traj,err:=NewXTC(""test/test.xtc"") + if err != nil { + Te.Error(err) + } + Coords, read, err := ManyFrames(traj, 0, 5, 1) + if err != nil { + Te.Error(err) + } + fmt.Println(len(Coords), read, VecView(Coords[read-1],4)) +} +*/ +func TestFrameXTCConc(Te *testing.T) { + traj, err := New(""../../test/test.xtc"") + if err != nil { + Te.Error(err) + } + frames := make([]*v3.Matrix, 3, 3) + for i, _ := range frames { + frames[i] = v3.Zeros(traj.Len()) + } + results := make([][]chan *v3.Matrix, 0, 0) + for i := 0; ; i++ { + results = append(results, make([]chan *v3.Matrix, 0, len(frames))) + coordchans, err := traj.NextConc(frames) + if err != nil { + if err, ok := err.(chem.LastFrameError); ok { + if coordchans == nil { + break + } + } else { + Te.Error(err) + } + } + for key, channel := range coordchans { + results[len(results)-1] = append(results[len(results)-1], make(chan *v3.Matrix)) + go SecondRow(channel, results[len(results)-1][key], len(results)-1, key) + } + res := len(results) - 1 + for frame, k := range results[res] { + if k == nil { + fmt.Println(frame) + continue + } + fmt.Println(res, frame, <-k) + } + } + traj.Close() +} + +/* for framebunch, j := range results { + if j == nil { + break + } + for frame, k := range j { + if k == nil { + fmt.Println(framebunch, frame) + continue + } + fmt.Println(framebunch, frame, <-k) + } + } +} +*/ +func SecondRow(channelin, channelout chan *v3.Matrix, current, other int) { + if channelin != nil { + temp := <-channelin + viej := v3.Zeros(1) + vector := temp.VecView(2) + viej.Copy(vector) + fmt.Println(""sending througt"", channelin, channelout, viej, current, other) + channelout <- vector + } else { + channelout <- nil + } + return +} +","Go" +"Computational Biochemistry","rmera/gochem","traj/xtc/xtc.go",".go","9421","314","/* + * xtc.go, part of gochem + * + * Copyright 2012 Raul Mera Adasme + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 2.1 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +/* + * + * + * Dedicated to the long life of the Ven. Khenpo Phuntzok Tenzin Rinpoche + * + * ***/ + +package xtc + +// #cgo CFLAGS: -I. +// #cgo LDFLAGS: -L. -lnsl -lm -lxdrfile +//#include +//#include +//#include +//#include +//#include +//#include +import ""C"" +import ( + ""fmt"" + + v3 ""github.com/rmera/gochem/v3"" +) + +//XTCObj is a container for an GROMACS XTC binary trajectory file. +type XTCObj struct { + readable bool + natoms int + filename string + fp *C.XDRFILE //pointer to the XDRFILE + goCoords []float64 + goBox []float64 + concBuffer [][]C.float + concBoxBuffer [][]C.float + cCoords []C.float + cBox []C.float + buffSize int +} + +//New returns an xtb object from a xtb-formated trajectory file +func New(filename string) (*XTCObj, error) { + traj := new(XTCObj) + if err := traj.initRead(filename); err != nil { + err := err.(Error) //I know that is the type returned byt initRead + err.Decorate(""New"") + return nil, err + } + return traj, nil + +} + +//Readable returns true if the object is ready to be read from +//false otherwise. IT doesnt guarantee that there is something +//to read. +func (X *XTCObj) Readable() bool { + if X.readable { + return true + } + return false +} + +//InitRead initializes a XTCObj for reading. +//It requires only the filename, which must be valid +func (X *XTCObj) initRead(name string) error { + Cfilename := C.CString(name) + Cnatoms := C.read_natoms(Cfilename) + X.natoms = int(Cnatoms) + totalcoords := X.natoms * 3 + X.fp = C.openfile(Cfilename) + if X.fp == nil { + return Error{UnableToOpen, X.filename, []string{""initRead""}, true} + } + //The idea is to reserve less memory, using the same buffer many times. + //X.goCoords = make([]float64, totalcoords, totalcoords) + X.cCoords = make([]C.float, totalcoords, totalcoords) + X.cBox = make([]C.float, 9) + X.concBuffer = append(X.concBuffer, X.cCoords) + X.concBoxBuffer = append(X.concBoxBuffer, X.cBox) + X.buffSize = 1 + X.readable = true + return nil +} + +//Next Reads the next frame in a XTCObj that has been initialized for read +//With initread. If keep is true, returns a pointer to matrix.DenseMatrix +//With the coordinates read, otherwiser, it discards the coordinates and +//returns nil. +func (X *XTCObj) Next(output *v3.Matrix, box ...[]float64) error { + if !X.Readable() { + return Error{TrajUnIni, X.filename, []string{""Next""}, true} + } + cnatoms := C.int(X.natoms) + worked := C.get_coords(X.fp, &X.cCoords[0], &X.cBox[0], cnatoms) + if worked == 11 { + X.Close() + return newlastFrameError(X.filename, ""Next"") //This is not really an error and should be catched in the calling function + } + if worked != 0 { + X.Close() + return Error{ReadError, X.filename, []string{""Next""}, true} + } + if output == nil { + return nil //just drop the frame and box + } + r, c := output.Dims() + if r < (X.natoms) { + panic(""Buffer v3.Matrix too small to hold trajectory frame"") + } + for j := 0; j < r; j++ { + for k := 0; k < c; k++ { + l := k + (3 * j) + output.Set(j, k, (10 * float64(X.cCoords[l]))) //nm to Angstroms + } + } + //We won't return an error here, as you most commonly don't want the vectors. + //If you give aything that won't fit the box vectors you just won't get the vectors back. + if len(box) > 0 && len(box[0]) >= 9 { + for k := 0; k < 9; k++ { + box[0][k] = 10 * float64(X.cBox[k]) + } + } + + return nil //Just drop the frame +} + +//SetConcBuffer +func (X *XTCObj) setConcBuffer(batchsize int) error { + l := X.buffSize + if l == batchsize { + return nil + //I won't do anything about the boxes if we have too many. It's little memory anyway. + } else if l > batchsize { + //I don't think it's worth it to free that memory. If the user wan't to read more frames again + //we'll have to re-aquire memory. Better just leave it until we free the object. + //I suspect the user rarely starts reading less frames concurrently half way the traj, anyway. + // for i := batchsize; i < l; i++ { + // X.concBuffer[i] = nil //no idea if this actually works + // X.concBoxBuffer[i]=nil + // } + X.concBuffer = X.concBuffer[:batchsize-1] //not sure if this frees the remaining []float32 slices + X.buffSize = batchsize + return nil + } + for i := 0; i < batchsize-l; i++ { + tmp := make([]C.float, X.Len()*3) + X.concBuffer = append(X.concBuffer, tmp) + } + X.buffSize = batchsize + return nil +} + +//Close closes the underlying file and sets all fields in the object to their zero-value +func (X *XTCObj) Close() { + if X.fp != nil { + C.xtc_close(X.fp) //we avoid closing it if it was closed already + } + X.readable = false + X.cCoords = nil + X.cBox = nil + X.concBuffer = nil + X.concBoxBuffer = nil + X.fp = nil +} + +//NextConc takes a slice of bools and reads as many frames as elements the list has +//form the trajectory. The frames are discarted if the corresponding elemetn of the slice +//is false. The function returns a slice of channels through each of each of which +// a *matrix.DenseMatrix will be transmited +func (X *XTCObj) NextConc(frames []*v3.Matrix) ([]chan *v3.Matrix, error) { + if X.buffSize < len(frames) { + X.setConcBuffer(len(frames)) + } + if X.natoms == 0 { + return nil, Error{TrajUnIni, X.filename, []string{""NextConc""}, true} + } + framechans := make([]chan *v3.Matrix, len(frames)) //the slice of chans that will be returned + cnatoms := C.int(X.natoms) + used := false + for key, val := range frames { + //cCoords:=X.concBuffer[key] + // fmt.Println(len(X.concBuffer), len(X.cBox), key, val.NVecs()) /////////////////////////////// + worked := C.get_coords(X.fp, &X.concBuffer[key][0], &X.cBox[0], cnatoms) + //Error handling + if worked == 11 { + if used == false { + //X.readable = false + X.Close() + return nil, newlastFrameError(X.filename, ""NextConc"") //This is not really an error and + } else { //should be catched in the calling function + X.readable = false + return framechans, newlastFrameError(X.filename, ""NextConc"") //same + } + } + if worked != 0 { + X.Close() + return nil, Error{ReadError, X.filename, []string{""NextConc""}, true} + } + if val == nil { + framechans[key] = nil //ignored frame + continue + } + used = true + framechans[key] = make(chan *v3.Matrix) + //Now the parallel part + go func(natoms int, cCoords []C.float, goCoords *v3.Matrix, pipe chan *v3.Matrix) { + r, c := goCoords.Dims() + for j := 0; j < r; j++ { + for k := 0; k < c; k++ { + l := k + (3 * j) + goCoords.Set(j, k, (10 * float64(cCoords[l]))) //nm to Angstroms + } + } + pipe <- goCoords + }(X.natoms, X.concBuffer[key], val, framechans[key]) + } + + return framechans, nil +} + +//Len returns the number of atoms per frame in the XTCObj. +//XTCObj must be initialized. 0 means an uninitialized object. +func (X *XTCObj) Len() int { + return X.natoms +} + +//Errors + +//Error is an error with xtb trajectories, compatible with goChem +type Error struct { + message string + filename string //the input file that has problems, or empty string if none. + deco []string + critical bool +} + +func (err Error) Error() string { + return fmt.Sprintf(""xtc file %s error: %s"", err.filename, err.message) +} + +func (E Error) Decorate(deco string) []string { + //Even thought this method does not use a pointer as a receiver, and tries to alter the received, + //it should work, since E.deco is a slice, and hence a pointer itself. + + if deco != """" { + E.deco = append(E.deco, deco) + } + return E.deco +} + +func (err Error) FileName() string { return err.filename } + +func (err Error) Format() string { return ""xtc"" } + +func (err Error) Critical() bool { return err.critical } + +const ( + TrajUnIni = ""Traj object uninitialized to read"" + ReadError = ""Error reading frame"" + UnableToOpen = ""Unable to open file"" + EOF = ""EOF"" +) + +type lastFrameError struct { + deco []string + fileName string +} + +//lastFrameError does nothing +func (E lastFrameError) NormalLastFrameTermination() {} + +func (E lastFrameError) FileName() string { return E.fileName } + +func (E lastFrameError) Error() string { return ""EOF"" } + +func (E lastFrameError) Critical() bool { return false } + +func (E lastFrameError) Format() string { return ""xtc"" } + +func (E lastFrameError) Decorate(deco string) []string { + //Even thought this method does not use a pointer as a receiver, and tries to alter the received, + //it should work, since E.deco is a slice, and hence a pointer itself. + if deco != """" { + E.deco = append(E.deco, deco) + } + return E.deco +} + +func newlastFrameError(filename string, caller string) *lastFrameError { + e := new(lastFrameError) + e.fileName = filename + e.deco = []string{caller} + return e +} +","Go" +"Computational Biochemistry","rmera/gochem","qm/doc.go",".go","975","29","/* + * doc.go, part of gochem. + * + * Copyright 2021 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + * */ + +//Package qm implements communication with several QM programs +//In such a way that the calculation settings are as separated +//as possible from the choice of QM program to perform that +//calculation. + +package qm +","Go" +"Computational Biochemistry","rmera/gochem","qm/nbo.go",".go","7134","315","package qm + +import ( + ""bufio"" + ""errors"" + ""fmt"" + ""io"" + ""strconv"" + ""strings"" + + chem ""github.com/rmera/gochem"" +) + +// just for brevity +var con func(string, string) bool = strings.Contains +var Err func(string, ...any) error = fmt.Errorf +var trim func(string) string = strings.TrimSpace + +type NBOData struct { + Charges []*Charge + EConfs []*EConf + Steric []*Steric + Delocs []*Deloc +} + +// Obtains NBO properties from the output file. Properties to obtain are: +// Natural Charges, delocalizations and steric energies. +func NBOProps(inpf io.Reader) (*NBOData, error) { + inp := bufio.NewReader(inpf) + ret := new(NBOData) + var nbo bool + var err error + var l string + for l, err = inp.ReadString('\n'); err == nil; l, err = inp.ReadString('\n') { + if con(l, ""N A T U R A L B O N D O R B I T A L A N A L Y S I S"") { + nbo = true + continue + } + if !nbo { + continue + } + if con(l, ""Total disjoint NLMO steric exchange energy from pairwise sum"") { + break + } + if con(l, ""Summary of Natural Population Analysis:"") { + ret, inp, err = SectionReader(inp, npa, ret) + if err != nil { + return nil, Err(""NPA Error %w"", err) + } + } + if con(l, ""Atom No Natural Electron Configuration"") { + ret, inp, err = SectionReader(inp, econf, ret) + if err != nil { + return nil, Err(""Natural Configuration Error %w"", err) + } + } + if con(l, ""SECOND ORDER PERTURBATION THEORY ANALYSIS OF FOCK MATRIX IN NBO BASIS"") { + ret, inp, err = SectionReader(inp, delocs, ret) + if err != nil { + return nil, Err(""Delocalizations error %w"", err) + } + + } + if con(l, ""NBO/NLMO STERIC ANALYSIS:"") { + ret, inp, err = SectionReader(inp, steric, ret) + if err != nil { + return nil, Err(""Steric error %w"", err) + } + + } + } + if errors.Is(err, io.EOF) { + err = nil + } + return ret, nil +} + +type section struct { + ini func(string) bool + end func(string) bool + reader func(string, *NBOData) error +} + +func print1or2(s []int) string { + r := make([]string, 0, len(s)) + for _, v := range s { + r = append(r, fmt.Sprintf(""%d"", v)) + } + return strings.Join(r, ""-"") +} + +type Deloc struct { + Donors []int //could be 1 or 2 + Acceptors []int //same + DonorType string + AccType string + Fock float64 + E2 float64 + DeltaE float64 +} + +func (D *Deloc) String() string { + return fmt.Sprintf(""D: %s %s | A: %s %s | E2: %4.1f F: %4.1f DE %4.1f"", D.DonorType, print1or2(D.Donors), D.AccType, print1or2(D.Acceptors), D.E2, D.Fock, D.DeltaE) +} + +func orbids(bondtype, line string, i, j, k, l int) ([]int, error) { + don, err := strconv.Atoi(trim(line[i:j])) + if err != nil { + return nil, err + } + r := []int{don} + if con(bondtype, ""BD"") { + don, err := strconv.Atoi(trim(line[k:l])) + if err != nil { + return nil, err + } + r = append(r, don) + } + return r, nil + +} + +var firstorbsindexes [4]int = [4]int{16, 19, 22, 25} +var secorbsindexes [4]int = [4]int{44, 47, 51, 54} + +func delocsreader(l string, nbo *NBOData) error { + if l == """" || l == ""\n"" || con(l, ""unit"") { + return nil + } + d := new(Deloc) + d.DonorType = l[7:10] + if d.DonorType[2] == ' ' { + d.DonorType = d.DonorType[:2] + } + d.AccType = l[35:38] + if d.AccType[2] == ' ' { + d.AccType = d.AccType[:2] + } + var err error + fi := firstorbsindexes[:] + d.Donors, err = orbids(d.DonorType, l, fi[0], fi[1], fi[2], fi[3]) //the numbers are the positions of the data we want in the line. + if err != nil { + return err + } + s := secorbsindexes[:] + d.Acceptors, err = orbids(d.AccType, l, s[0], s[1], s[2], s[3]) + if err != nil { + return err + } + d.E2, err = strconv.ParseFloat(trim(l[59:63]), 64) + if err != nil { + return err + } + d.DeltaE, err = strconv.ParseFloat(trim(l[67:71]), 64) + if err != nil { + return err + } + d.DeltaE *= chem.H2Kcal + d.Fock, err = strconv.ParseFloat(trim(l[74:]), 64) + if err != nil { + return err + } + d.Fock *= chem.H2Kcal + nbo.Delocs = append(nbo.Delocs, d) + + return nil +} + +var delocs section = section{ini: func(l string) bool { + return con(l, ""==============================================================================="") +}, + end: func(l string) bool { + return con(l, ""NATURAL BOND ORBITALS (Summary):"") + }, + reader: delocsreader, +} + +type Steric struct { + Type string + OrbIDs []int + E float64 +} + +func (S *Steric) String() string { + return fmt.Sprintf(""Orb: %s %s E: %4.1f"", S.Type, print1or2(S.OrbIDs), S.E) +} + +var steric section = section{ini: func(l string) bool { + return con(l, ""Occupied NLMO contributions dE(i) (kcal/mol) to total steric exchange energy"") +}, + end: func(l string) bool { return con(l, ""-------------------------------------------------"") }, + reader: func(l string, n *NBOData) error { + if l == """" || con(l, ""unit"") || l == ""\n"" { + return nil + } + var err error + s := new(Steric) + s.Type = trim(l[7:9]) + fi := firstorbsindexes[:] + s.OrbIDs, err = orbids(s.Type, l, fi[0], fi[1], fi[2], fi[3]) + if err != nil { + return err + } + s.E, err = strconv.ParseFloat(trim(l[35:41]), 64) + if err != nil { + return err + } + n.Steric = append(n.Steric, s) + return nil + }, +} + +type Charge struct { + Symbol string + ID int + Charge float64 +} + +func (C *Charge) String() string { + return fmt.Sprintf(""%s %d Charge: %3.1f"", C.Symbol, C.ID, C.Charge) +} + +var npa section = section{ini: func(l string) bool { + return con(l, ""--------------------------------------------------------------------"") +}, + end: func(l string) bool { + return con(l, ""===================================================================="") + }, + reader: func(l string, n *NBOData) error { + var err error + if n == nil { + return fmt.Errorf(""Given nil NBOData!"") + } + if n.Charges == nil { + n.Charges = make([]*Charge, 0, 10) + } + f := strings.Fields(l) + ch := new(Charge) + ch.Symbol = f[0] + ch.ID, err = strconv.Atoi(f[1]) + if err != nil { + return err + } + ch.Charge, err = strconv.ParseFloat(f[2], 64) + if err != nil { + return err + } + n.Charges = append(n.Charges, ch) + return err + }, +} + +type EConf struct { + Symbol string + ID int + Conf string +} + +func (C *EConf) String() string { + return fmt.Sprintf(""%s %d %s"", C.Symbol, C.ID, C.Conf) +} + +var econf section = section{ini: func(l string) bool { + return con(l, ""----------------------------------------------------------------------------"") +}, + end: func(l string) bool { + if l == """" || l == ""\n"" { + return true + } + return false + }, + reader: func(l string, n *NBOData) error { + var err error + if n == nil { + return fmt.Errorf(""Given nil NBOData!"") + } + if n.EConfs == nil { + n.EConfs = make([]*EConf, 0, 10) + } + f := strings.Fields(l) + c := new(EConf) + c.Symbol = f[0] + c.ID, err = strconv.Atoi(f[1]) + if err != nil { + return err + } + c.Conf = trim(strings.Join(f[2:], """")) + n.EConfs = append(n.EConfs, c) + return err + }, +} + +func SectionReader(inp *bufio.Reader, sec section, nbo *NBOData) (*NBOData, *bufio.Reader, error) { + var reading bool + var err error + for l, err := inp.ReadString('\n'); err == nil; l, err = inp.ReadString('\n') { + if sec.ini(l) { + reading = true + continue + } + if !reading { + continue + } + if sec.end(l) { + break + } + err := sec.reader(l, nbo) + if err != nil { + return nbo, nil, err + } + } + return nbo, inp, err + +} +","Go" +"Computational Biochemistry","rmera/gochem","qm/xtb.go",".go","21140","650","/* + * xtb.go, part of gochem. + * + * + * Copyright 2016 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + * + */ +//In order to use this part of the library you need the xtb program, which must be obtained from Prof. Stefan Grimme's group. +//Please cite the the xtb references if you used the program. + +package qm + +import ( + // ""bufio"" + ""bufio"" + ""fmt"" + ""math"" + ""os"" + ""os/exec"" + ""runtime"" + ""strconv"" + ""strings"" + + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" +) + +// XTBHandle represents an xtb calculation +type XTBHandle struct { + //Note that the default methods and basis vary with each program, and even + //for a given program they are NOT considered part of the API, so they can always change. + //This is unavoidable, as methods change with time + command string + inputname string + nCPU int + options []string + gfnff bool + metad string + relconstraints bool + force float64 + wrkdir string + inputfile string +} + +// NewXTBHandle initializes and returns an xtb handle +// with values set to their defaults. Defaults might change +// as new methods appear, so they are not part of the API. +func NewXTBHandle() *XTBHandle { + run := new(XTBHandle) + run.SetDefaults() + return run +} + +//XTBHandle methods + +// SetnCPU sets the number of CPU to be used +func (O *XTBHandle) SetnCPU(cpu int) { + O.nCPU = cpu +} + +// Command returns the path and name for the xtb excecutable +func (O *XTBHandle) Command() string { + return O.command +} + +// SetName sets the name for the calculations +// which is defines the input and output file names +func (O *XTBHandle) SetName(name string) { + O.inputname = name +} + +// SetCommand sets the path and name for the xtb excecutable +func (O *XTBHandle) SetCommand(name string) { + O.command = name +} + +// SetWorkDir sets the name of the working directory for the calculations +func (O *XTBHandle) SetWorkDir(d string) { + O.wrkdir = d +} + +func (O *XTBHandle) SetMetaD(set ...string) { + if len(set) == 0 || !strings.Contains(set[0], ""$"") { + O.metad = ""\n$metadyn\n save=10\n kpush=1.0\n alp=0.2\n$end\n"" + } else { + O.metad = set[0] + } +} + +func (O *XTBHandle) UnSetMetaD(set ...string) { + O.metad = """" +} + +// RelConstraints sets the use of relative contraints +// instead of absolute position restraints +// with the force force constant. If force is +// less than 0, the default value is employed. +func (O *XTBHandle) RelConstraints(force float64) { + if force > 0 { + //goChem units (Kcal/A^2) to xtb units (Eh/Bohr^2) + O.force = force * (chem.Kcal2H / (chem.A2Bohr * chem.A2Bohr)) + } + O.relconstraints = true + +} + +// SetDefaults sets calculations parameters to their defaults. +// Defaults might change +// as new methods appear, so they are not part of the API. +func (O *XTBHandle) SetDefaults() { + O.command = os.ExpandEnv(""xtb"") + // if O.command == ""/xtb"" { //if XTBHOME was not defined + // O.command = ""./xtb"" + // } + cpu := runtime.NumCPU() / 2 + O.nCPU = cpu + +} + +func (O *XTBHandle) seticonstraints(Q *Calc, xcontrol []string) []string { + //Here xtb expects distances in A and angles in deg, so no conversion needed. + var g2x = map[byte]string{ + 'B': ""distance: "", + 'A': ""angle: "", + 'D': ""dihedral: "", + } + + for _, v := range Q.IConstraints { + constra := g2x[v.Class] + + for _, w := range v.CAtoms { + constra += strconv.Itoa(w+1) + "", "" //1-based indexes for xtb + } + strings.TrimRight(constra, "","") + if v.UseVal { + constra += fmt.Sprintf("" %4.2f\n"", v.Val) + } else { + constra += "" auto\n"" + } + xcontrol = append(xcontrol, constra) + + } + return xcontrol +} + +// BuildInput builds an input for XTB. Right now it's very limited, only singlets are allowed and +// only unconstrained optimizations and single-points. +func (O *XTBHandle) BuildInput(coords *v3.Matrix, atoms chem.AtomMultiCharger, Q *Calc) error { + //Now lets write the thing + if O.wrkdir != """" && !strings.HasSuffix(O.wrkdir, ""/"") { + O.wrkdir += ""/"" + } + w := O.wrkdir + if O.inputname == """" { + O.inputname = ""gochem"" + } + //Only error so far + if atoms == nil || coords == nil { + return Error{ErrMissingCharges, ""XTB"", O.inputname, """", []string{""BuildInput""}, true} + } + err := chem.XYZFileWrite(w+O.inputname+"".xyz"", coords, atoms) + if err != nil { + return Error{ErrCantInput, ""XTB"", O.inputname, """", []string{""BuildInput""}, true} + } + // mem := """" + if Q.Memory != 0 { + //Here we can adjust memory if needed + } + + xcontroltxt := make([]string, 0, 10) + O.options = make([]string, 0, 6) + O.options = append(O.options, O.command) + if Q.Method == ""gfnff"" { + O.gfnff = true + } + O.options = append(O.options, O.inputname+"".xyz"") + O.options = append(O.options, fmt.Sprintf(""-c %d"", atoms.Charge())) + O.options = append(O.options, fmt.Sprintf(""-u %d"", (atoms.Multi()-1))) + if O.nCPU > 1 { + O.options = append(O.options, fmt.Sprintf(""-P %d"", O.nCPU)) + } + //Added new things to select a method in xtb + if !isInString([]string{""gfn1"", ""gfn2"", ""gfn0"", ""gfnff""}, Q.Method) { + O.options = append(O.options, ""--gfn 2"") //default method + } else if Q.Method != ""gfnff"" { + m := strings.ReplaceAll(Q.Method, ""gfn"", """") //so m should be ""0"", ""1"" or ""2"" + O.options = append(O.options, ""--gfn ""+m) //default method + } + + if Q.Dielectric > 0 && Q.Method != ""gfn0"" { //as of the current version, gfn0 doesn't support implicit solvation + solvent, ok := dielectric2Solvent[int(Q.Dielectric)] + if ok { + O.options = append(O.options, ""--alpb ""+solvent) + } + } + //O.options = append(O.options, ""-gfn"") + fixed := """" + fixtoken := ""$fix\n"" + if O.relconstraints { + force := """" + if O.force > 0 { + force = fmt.Sprintf(""force constant = %4.2f\n"", O.force) + } + fixtoken = ""$constrain\n"" + force + } + if Q.CConstraints != nil || Q.IConstraints != nil { + xcontroltxt = append(xcontroltxt, fixtoken) + if Q.CConstraints != nil { + fixed = ""atoms: "" + for _, v := range Q.CConstraints { + fixed = fixed + strconv.Itoa(v+1) + "", "" //1-based indexes + } + fixed = strings.TrimRight(fixed, "", "") + fixed = fixed + ""\n"" + xcontroltxt = append(xcontroltxt, fixed) + } + if Q.IConstraints != nil { + if !O.relconstraints { + xcontroltxt = append(xcontroltxt, (""$end\n$constrain\n"")) + } + xcontroltxt = O.seticonstraints(Q, xcontroltxt) + + } + xcontroltxt = append(xcontroltxt, ""$end\n"") + + } + jc := jobChoose{} + jc.opti = func() { + add := ""-o normal"" + if Q.OptTightness == 2 { + add = ""-o tight"" + } else if Q.OptTightness > 2 { + add = ""-o verytight"" + } + O.options = append(O.options, add) + } + jc.forces = func() { + O.options = append(O.options, ""--ohess"") + } + + jc.md = func() { + O.options = append(O.options, ""--md"") + //There are specific settings needed with gfnff, mainly, a shorter timestep + //The restart=false option doesn't have any effect, but it's added so it's easier later to use sed or whatever to change it to true, and restart + //a calculation. + if Q.Method == ""gfnff"" { + xcontroltxt = append(xcontroltxt, fmt.Sprintf(""$md\n temp=%5.3f\n time=%d\n velo=false\n nvt=true\n step=2.0\n hmass=4.0\n shake=0\n restart=false\n$end"", Q.MDTemp, Q.MDTime)) + } else { + xcontroltxt = append(xcontroltxt, fmt.Sprintf(""$md\n temp=%5.3f\n time=%d\n velo=false\n nvt=true\n restart=false\n$end"", Q.MDTemp, Q.MDTime)) + } + xcontroltxt = append(xcontroltxt, O.metad) //this should be either an empty string, or everything you need for metad. + + } + // O.options = append(O.options, ""--input xcontrol"") + O.options = append(O.options, Q.Others) + Q.Job.Do(jc) + if len(xcontroltxt) == 0 { + return nil //no need to write a control file + } + O.inputfile = O.inputname + "".inp"" //if not input file was written + //this will just be an empty string. + xcontrol, err := os.Create(w + O.inputfile) + if err != nil { + return err + } + for _, v := range xcontroltxt { + xcontrol.WriteString(v) + + } + xcontrol.Close() + return nil +} + +// Run runs the command given by the string O.command +// it waits or not for the result depending on wait. +// Not waiting for results works +// only for unix-compatible systems, as it uses bash and nohup. +func (O *XTBHandle) Run(wait bool) (err error) { + var com string + extraoptions := """" + if len(O.options) >= 3 { + extraoptions = strings.Join(O.options[2:], "" "") + } + inputfile := """" + if O.inputfile != """" { + inputfile = fmt.Sprintf(""--input %s"", O.inputfile) + } + + if O.gfnff { + com = fmt.Sprintf("" --gfnff %s.xyz %s %s -v > %s.out 2>&1"", O.inputname, inputfile, extraoptions, O.inputname) + } else { + + com = fmt.Sprintf("" %s.xyz %s %s -v > %s.out 2>&1"", O.inputname, inputfile, extraoptions, O.inputname) + } + if wait { + //It would be nice to have this logging as an option. + //log.Printf(O.command + com) //this is stderr, I suppose + command := exec.Command(""sh"", ""-c"", O.command+com) + command.Dir = O.wrkdir + err = command.Run() + + } else { + command := exec.Command(""sh"", ""-c"", ""nohup ""+O.command+com) + command.Dir = O.wrkdir + err = command.Start() + } + if err != nil { + err = Error{ErrNotRunning, XTB, O.inputname, err.Error(), []string{""exec.Start"", ""Run""}, true} + } + if err != nil { + return err + } + os.Remove(""xtbrestart"") + return nil +} + +// OptimizedGeometry returns the latest geometry from an XTB optimization. It doesn't actually need the chem.Atomer +// but requires it so XTBHandle fits with the QM interface. +func (O *XTBHandle) OptimizedGeometry(atoms chem.Atomer) (*v3.Matrix, error) { + inp := O.wrkdir + O.inputname + if !O.normalTermination() { + return nil, Error{ErrNoGeometry, XTB, inp, ""Calculation didn't end normally"", []string{""OptimizedGeometry""}, true} + } + mol, err := chem.XYZFileRead(O.wrkdir + ""xtbopt.xyz"") //Trying to run several calculations in parallel in the same directory will fail as the output has always the same name. + if err != nil { + return nil, Error{ErrNoGeometry, XTB, inp, """", []string{""OptimizedGeometry""}, true} + } + return mol.Coords[0], nil +} + +// This checks that an xtb calculation has terminated normally +// I know this duplicates code, I wrote this one first and then the other one. +func (O *XTBHandle) normalTermination() bool { + inp := O.wrkdir + O.inputname + if searchBackwards(""normal termination of x"", fmt.Sprintf(""%s.out"", inp)) != """" || searchBackwards(""abnormal termination of x"", fmt.Sprintf(""%s.out"", inp)) == """" { + return true + } + return false +} + +// search a file backwards, i.e., starting from the end, for a string. Returns the line that contains the string, or an empty string. +// I really really should have commented this one. +func searchBackwards(str, filename string) string { + var ini int64 = 0 + var end int64 = 0 + var first bool + first = true + buf := make([]byte, 1) + f, err := os.Open(filename) + if err != nil { + return """" + } + defer f.Close() + var i int64 = 1 + for ; ; i++ { + if _, err := f.Seek(-1*i, 2); err != nil { + return """" + } + if _, err := f.Read(buf); err != nil { + return """" + } + if buf[0] == byte('\n') && first == false { + first = true + } else if buf[0] == byte('\n') && end == 0 { + end = i + } else if buf[0] == byte('\n') && ini == 0 { + i-- + ini = i + f.Seek(-1*(ini), 2) + bufF := make([]byte, ini-end) + f.Read(bufF) + if strings.Contains(string(bufF), str) { + return string(bufF) + } + // first=false + end = 0 + ini = 0 + } + + } +} + +// Energy returns the energy of a previous XTB calculations, in kcal/mol. +// Returns error if problem, and also if the energy returned that is product of an +// abnormally-terminated ORCA calculation. (in this case error is ""Probable problem +// in calculation"") +func (O *XTBHandle) Energy() (float64, error) { + inp := O.wrkdir + O.inputname + var err error + var energy float64 + energyline := searchBackwards(""TOTAL ENERGY"", fmt.Sprintf(""%s.out"", inp)) + if energyline == """" { + return 0, Error{ErrNoEnergy, XTB, inp, fmt.Sprintf(""%s.out"", inp), []string{""searchBackwards"", ""Energy""}, true} + } + split := strings.Fields(energyline) + if len(split) < 5 { + return 0, Error{ErrNoEnergy, XTB, inp, err.Error(), []string{""Energy""}, true} + + } + energy, err = strconv.ParseFloat(split[3], 64) + if err != nil { + return 0, Error{ErrNoEnergy, XTB, inp, err.Error(), []string{""strconv.ParseFloat"", ""Energy""}, true} + } + + return energy * chem.H2Kcal, err //dummy thin +} + +// LargestImaginary returns the absolute value of the wave number (in 1/cm) for the largest imaginary mode in the vibspectrum file +// produced by a forces calculation with xtb. Returns an error and -1 if unable to check. +func (O *XTBHandle) LargestImaginary() (float64, error) { + largestimag := 0.0 + vibf, err := os.Open(O.wrkdir + ""vibspectrum"") + if err != nil { + //fmt.Println(""Unable to open file!!"") + return -1, Error{ErrCantValue, XTB, ""vibspectrum"", err.Error(), []string{""os.Open"", ""LargestImaginary""}, true} + } + vib := bufio.NewReader(vibf) + for i := 0; i < 3; i++ { + _, err := vib.ReadString('\n') //The text in ""data"" could be anything, including just ""\n"" + if err != nil { + return -1, Error{ErrCantValue, XTB, ""vibspectrum"", err.Error(), []string{""ReadString"", ""LargestImaginary""}, true} + + } + } + for { + line, err := vib.ReadString('\n') + if err != nil { //inefficient, (errs[1] can be checked once before), but clearer. + if strings.Contains(err.Error(), ""EOF"") { + err = nil //it's not an actual error + break + } else { + return -1, Error{ErrCantValue, XTB, ""vibspectrum"", err.Error(), []string{""ReadString"", ""LargestImaginary""}, true} + + } + } + + fields := strings.Fields(line) + if len(fields) < 5 { + return -1, Error{ErrCantValue, XTB, ""vibspectrum"", ""Can't parse vibspectrum"", []string{""ReadString"", ""LargestImaginary""}, true} + } + wave, err := strconv.ParseFloat(fields[len(fields)-4], 64) + if err != nil { + return -1, Error{ErrCantValue, XTB, ""vibspectrum"", ""Can't parse vibspectrum"", []string{""strconv.ParseFloat"", ""LargestImaginary""}, true} + } + if wave > 0.0 { + return largestimag, nil //no more imaginary frequencies so we just return the largest so far. + } else if math.Abs(wave) > largestimag { + largestimag = math.Abs(wave) + } + } + return largestimag, nil +} + +// FixImaginary prepares and runs a calculation on a geometry, produced by xtb on a previous Hessian calculation, which +// is distorted along the main imaginary mode found, if any. It such mode was not found, and thus the geometry was not +// produced by xtb, FixImaginary returns an error. +func (O *XTBHandle) FixImaginary(wait bool) error { + var com string + var err error + if _, err := os.Stat(""xtbhess.coord""); os.IsNotExist(err) { + return fmt.Errorf(""xtbhess.coord doesn't exist. There is likely no significant imaginary mode"") + } + if O.gfnff { + com = fmt.Sprintf("" --gfnff xtbhess.coord --input %s.inp %s > %s.out 2>&1"", O.inputname, strings.Join(O.options[2:], "" ""), O.inputname) + } else { + + com = fmt.Sprintf("" xtbhess.coord --input %s.inp %s > %s.out 2>&1"", O.inputname, strings.Join(O.options[2:], "" ""), O.inputname) + } + if wait == true { + //log.Printf(com) //this is stderr, I suppose + command := exec.Command(""sh"", ""-c"", O.command+com) + command.Dir = O.wrkdir + err = command.Run() + + } else { + command := exec.Command(""sh"", ""-c"", ""nohup ""+O.command+com) + command.Dir = O.wrkdir + err = command.Start() + } + if err != nil { + err = Error{ErrNotRunning, XTB, O.inputname, err.Error(), []string{""exec.Start"", ""Run""}, true} + } + if err != nil { + return err + } + os.Remove(""xtbrestart"") + return nil + +} + +// FreeEnergy returns the Gibbs free energy of a previous XTB calculations. +// A frequencies/solvation calculation is needed for this to work. FreeEnergy does _not_ check that the structure was at a minimum. You can check that with +// the LargestIm +func (O *XTBHandle) FreeEnergy() (float64, error) { + var err error + var energy float64 + inp := O.wrkdir + O.inputname + energyline := searchBackwards(""total free energy"", fmt.Sprintf(""%s.out"", inp)) + if energyline == """" { + return 0, Error{ErrNoFreeEnergy, XTB, inp, fmt.Sprintf(""%s.out"", inp), []string{""searchBackwards"", ""FreeEnergy""}, true} + } + split := strings.Fields(energyline) + if len(split) < 4 { + return 0, Error{ErrNoFreeEnergy, XTB, inp, err.Error(), []string{""Energy""}, true} + + } + energy, err = strconv.ParseFloat(split[4], 64) + if err != nil { + return 0, Error{ErrNoFreeEnergy, XTB, inp, err.Error(), []string{""strconv.ParseFloat"", ""Energy""}, true} + } + + return energy * chem.H2Kcal, err //err should be nil at this point. +} + +// XTB trajectories are multi-xyz files with the energy, gradient norm and program version in the +// 'comment' line of each frame (i.e. the second line, after the number of atoms). This function +// parses that line and returns the energy and gradient norm, the first is in kcal/mol, the second in +// atomic units. +func (O *XTBHandle) ParseFrameMetaData(data string) (energy, gnorm float64, err error) { + fi := strings.Fields(data) + e := fi[1] + energy, err = strconv.ParseFloat(e, 64) + if err != nil { + return energy, gnorm, err + } + gnorm, err = strconv.ParseFloat(e, 64) + if err != nil { + return energy, gnorm, err + } + return energy, gnorm, nil //I'll just leave the gradient in its original units + + //I expect the line to be: + //energy: -11.394330344820 gnorm: 0.001049679542 xtb: 6.7.1 (edcfbbe) +} + +// MDAverageEnergy gets the average potential and kinetic energy along a trajectory. +func (O *XTBHandle) MDAverageEnergy(start, skip int) (float64, float64, error) { + inp := O.wrkdir + O.inputname + var potential, kinetic float64 + if !O.normalTermination() { + return 0, 0, Error{ErrNoEnergy, XTB, inp, ""Calculation didn't end normally"", []string{""MDAverageEnergy""}, true} + } + outname := fmt.Sprintf(""%s.out"", inp) + outfile, err := os.Open(outname) + if err != nil { + return 0, 0, Error{ErrNoEnergy, XTB, inp, ""Couldn't open output file"", []string{""MDAverageEnergy""}, true} + } + out := bufio.NewReader(outfile) + reading := false + cont := 0 + read := 0 + for { + line, err := out.ReadString('\n') + // fmt.Println(""LINE"", line) ///////// + if err != nil && strings.Contains(err.Error(), ""EOF"") { + break + } else if err != nil { + return 0, 0, Error{ErrNoEnergy, XTB, inp, ""Error while iterating through output file"", []string{""MDAverageEnergy""}, true} + } + if strings.Contains(line, ""time (ps) Ekin T Etot"") { + reading = true + continue + } + if !reading { + continue + } + fields := strings.Fields(line) + if len(fields) != 7 { + continue + } + cont++ + if (cont-1)%skip != 0 || (cont-1) < start { + continue + } + K, err := strconv.ParseFloat(fields[3], 64) + if err != nil { + return 0, 0, Error{ErrNoEnergy, XTB, inp, fmt.Sprintf(""Error while retrieving %d th kinetic energy"", cont), []string{""MDAverageEnergy""}, true} + + } + V, err := strconv.ParseFloat(fields[3], 64) + if err != nil { + return 0, 0, Error{ErrNoEnergy, XTB, inp, fmt.Sprintf(""Error while retrieving %d th potential energy"", cont), []string{""MDAverageEnergy""}, true} + + } + fmt.Println(""potential"", V) ////////// + kinetic += K + potential += V + read++ + } + N := float64(read) + if math.IsNaN(potential/N) || math.IsNaN(kinetic/N) { //note that we still return whatever we got here, in addition to the error. The user can decide. + return potential / N, kinetic / N, Error{ErrProbableProblem, XTB, inp, ""At least one of the energies is NaN"", []string{""MDAverageEnergy""}, true} + } + return potential / N, kinetic / N, nil +} + +var dielectric2Solvent = map[int]string{ + 80: ""h2o"", + 5: ""chcl3"", + 9: ""ch2cl2"", + 10: ""octanol"", + 21: ""acetone"", + 37: ""acetonitrile"", + 33: ""methanol"", + 2: ""toluene"", + 1: ""hexadecane"", //not quite 1 + 7: ""thf"", + 47: ""dmso"", + 38: ""dmf"", + 1000: ""woctanol"", //This is a hackish way to have both dry and wet octanol. I gave wet octanol an fake epsilon that won't be used by anything else. + //really, what I should do is to add to the API a way to specify either epsilon or solvent name. FIX +} + +//old code + +// out, err := os.Create(fmt.Sprintf(""%s.out"", O.inputname)) +// if err != nil { +// return Error{ErrNotRunning, XTB, O.inputname, """", []string{""Run""}, true} +// } +// ferr, err := os.Create(fmt.Sprintf(""%s.err"", O.inputname)) +// +// if err != nil { +// return Error{ErrNotRunning, XTB, O.inputname, """", []string{""Run""}, true} +// } +// defer out.Close() +// defer ferr.Close() +// fullCommand:=strings.Join(O.options,"" "") +// fmt.Println(fullCommand) //(""Command"", O.command, O.options) //////////////////////// +// command := exec.Command(fullCommand) //, O.options...) +// command.Stdout = out +// command.Stderr = ferr +// err = command.Run() +// fmt.Println(O.command+fmt.Sprintf("" %s.xyz %s > %s.out &"", O.inputname, strings.Join(O.options[2:],"" ""), O.inputname)) //////////////////////// +","Go" +"Computational Biochemistry","rmera/gochem","qm/turbomole.go",".go","23637","797","/* + * turbomole.go, part of gochem. + * + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + * + */ + +//The TM handler implementation differs from the rest in that it uses several TM programs +// (define, x2t, t2x, cosmoprep) in order to prepare the input and retrieve results. +//Because of this, the programs using this handler will not work if TM is not installed. +//The handler has been made to work with TM7. + +package qm + +import ( + ""bufio"" + ""bytes"" + ""errors"" + ""fmt"" + ""io"" + ""log"" + ""os"" + ""os/exec"" + ""strconv"" + ""strings"" + + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" +) + +// TMHandle is the representation of a Turbomole (TM) calculation +// This imlpementation supports only singlets and doublets. +type TMHandle struct { + defmethod string + defbasis string + defauxbasis string + defgrid int + previousMO string + command string + precommand string // Sometimes, a TM optimization fails, but works if you start with a SP before the optimization. + //so we always start with a SP. precommand contains the SP command to be run. + cosmoprepcom string + inputname string + gimic bool + marij bool + dryrun bool + basicInput bool + symmetry string + jchoose jobChoose +} + +// Creates and initializes a new instance of TMRuner, with values set +// to its defaults. +func NewTMHandle() *TMHandle { + run := new(TMHandle) + run.SetDefaults() + return run +} + +const noCosmoPrep = ""goChem/QM: Unable to run cosmoprep"" + +//TMHandle methods + +// SetName sets the name of the subdirectory, in the current directory +// where the calculation will be ran +func (O *TMHandle) Name(name ...string) string { + ret := O.inputname + if len(name) > 0 && name[0] != """" { + O.inputname = name[0] + ret = name[0] + } + return ret + +} + +// SetMARIJ sets the multipole acceleration +func (O *TMHandle) SetMARIJ(state bool) { + O.marij = state +} + +// SetDryRun sets the flag to see this is a dry run or +// if define will actually be run. +func (O *TMHandle) SetDryRun(dry bool) { + O.dryrun = dry +} + +// SetCommand doesn't do anything, and it is here only for compatibility. +// In TM the command is set according to the method. goChem assumes a normal TM installation. +func (O *TMHandle) SetCommand(name string) { + //Does nothing again +} + +// SetCommand doesn't do anything, and it is here only for compatibility. +// In TM the command is set according to the method. goChem assumes a normal TM installation. +func (O *TMHandle) SetCosmoPrepCommand(name string) { + O.cosmoprepcom = name +} + +// SetDefaults sets default values for TMHandle. default is an optimization at +// +// TPSS-D3 / def2-SVP +// +// Defaults are not part of the API, they might change as new methods appear. +func (O *TMHandle) SetDefaults() { + O.defmethod = ""B97-3c"" + O.defbasis = ""def2-mTZVP"" + O.defgrid = 4 + O.defauxbasis = ""def2-mTZVP"" + O.command = ""ridft"" + O.marij = false //Apparently marij can cause convergence problems + O.dryrun = false //define IS run by default. + O.inputname = ""gochemturbo"" + O.cosmoprepcom = ""cosmoprep"" +} + +// addMARIJ adds the multipole acceleration if certain conditions are fullfilled: +// O.marij must be true +// The RI approximation must be in use +// The system must have more than 20 atoms +// The basis set cannot be very large (i.e. it can NOT be quadruple-zeta, tzvpp, or basis with diffuse functions) +func (O *TMHandle) addMARIJ(defstring string, atoms chem.AtomMultiCharger, Q *Calc) string { + if !O.marij { + return defstring + } + if strings.Contains(strings.ToLower(Q.Basis), ""def2"") && strings.HasSuffix(Q.Basis, ""d"") { //Rappoport basis + return defstring + } + if strings.Contains(Q.Basis, ""cc"") && strings.Contains(Q.Basis, ""aug"") { //correlation consistent with diffuse funcs. + return defstring + } + if strings.Contains(strings.ToLower(Q.Basis), ""qz"") { //both cc-pVQZ and def2-QZVP and QZVPP + return defstring + } + + if strings.Contains(strings.ToLower(Q.Basis), ""def2-tzvpp"") { //This is less clear but just in case I won't add MARIJ for tzvpp + return defstring + } + //I Have no idea what the MARIJ string was supposed to be. For now the method doesn't work. Remove this if you fix the code + //below, and uncoment it. + // if Q.RI && atoms.Len() >= 20 { + // defstring = fmt.Sprintf(""%s%s\n\n"") + // } + return defstring +} + +func ReasonableSetting(k string, Q *Calc) string { + if strings.Contains(k, ""$scfiterlimit"") { + k = ""$scfiterlimit 100\n"" + } + if strings.Contains(k, ""$scfdump"") { + k = """" + } + if strings.Contains(k, ""$maxcor 500 MiB per_core"") { + k = fmt.Sprintf(""$maxcor %d MiB per_core\n"", Q.Memory) + } + if strings.Contains(k, ""$ricore 500"") { + k = ""$ricore 1000\n"" + } + if Q.SCFConvHelp > 1 && strings.Contains(k, ""$scfdamp"") { + k = ""$scfdamp start=10 step=0.005 min=0.5\n"" + + } + if Q.SCFTightness > 1 && strings.Contains(k, ""$scfconv"") { + k = ""$scfconv 8\n"" + } + + return k +} + +/* +//Replaces the regular expression regex in the TM control file by replacement +func (O *TMHandle) ReplaceInControl(regex, replacement string) error { + //NOTE: This has repeated code. Refactor + re, err := regexp.Compile(regex) + if err != nil { + return fmt.Errorf(""ReplaceInControl: Replacement failed: %s"", err.Error()) + } + + path, err := os.Getwd() + if err != nil { + return err + } + dir := strings.Split(path, ""/"") + if dir[len(dir)-1] != O.inputname { + defer os.Chdir(""../"") + os.Chdir(O.inputname) + } + + f, err := os.Open(""control"") + if err != nil { + return Error{ErrCantInput, Turbomole, O.inputname, """", []string{""os.Open"", ""addtoControl""}, true} + } + lines := make([]string, 0, 200) //200 is just a guess for the number of lines in the control file + c := bufio.NewReader(f) + for err == nil { + var line string + line, err = c.ReadString('\n') + lines = append(lines, line) + } + f.Close() //I cant defer it because I need it closed now. + out, err := os.Create(""control"") + if err != nil { + return Error{ErrCantInput, Turbomole, O.inputname, """", []string{""os.Create"", ""addtoControl""}, true} + } + defer out.Close() + for _, i := range lines { + k := i + if re.MatchString(i) { + k = replacement + } + + if _, err := fmt.Fprintf(out, k); err != nil { + return Error{ErrCantInput, Turbomole, O.inputname, """", []string{""fmt.Fprintf"", ""ReplaceInControl""}, true} + } + } + return nil +} +*/ + +// Adds the text strings given before or after the first line containing the where[0] string. By default the ""target"" is ""$symmetry"" +func (O *TMHandle) AddToControl(toappend []string, before bool, where ...string) error { + c, err := os.Getwd() + if err != nil { + return err + } + dir := strings.Split(c, ""/"") + if dir[len(dir)-1] != O.inputname { + defer os.Chdir(""../"") + os.Chdir(O.inputname) + } + return O.addToControl(toappend, nil, before, where...) +} + +// Adds all the strings in toapend to the control file, just before the $symmetry keyword +// or just before the keyword specified in where. +func (O *TMHandle) addToControl(toappend []string, Q *Calc, before bool, where ...string) error { + f, err := os.Open(""control"") + if err != nil { + return Error{ErrCantInput, Turbomole, O.inputname, """", []string{""os.Open"", ""addtoControl""}, true} + } + lines := make([]string, 0, 200) //200 is just a guess for the number of lines in the control file + c := bufio.NewReader(f) + for err == nil { + var line string + line, err = c.ReadString('\n') + lines = append(lines, line) + } + f.Close() //I cant defer it because I need it closed now. + out, err := os.Create(""control"") + if err != nil { + return Error{ErrCantInput, Turbomole, O.inputname, """", []string{""os.Create"", ""addtoControl""}, true} + } + defer out.Close() + var k string + target := ""$symmetry"" + if len(where) > 0 { + target = where[0] + } + for _, i := range lines { + k = i //May not be too efficient + if Q != nil { + k = ReasonableSetting(k, Q) + } + if strings.Contains(i, target) { + if !before { + if _, err := fmt.Fprintf(out, k); err != nil { + return Error{ErrCantInput, Turbomole, O.inputname, """", []string{""fmt.Fprintf"", ""addtoControl""}, true} + + } + } + for _, j := range toappend { + if _, err := fmt.Fprintf(out, j+""\n""); err != nil { + return Error{ErrCantInput, Turbomole, O.inputname, """", []string{""fmt.Fprintf"", ""addtoControl""}, true} + } + } + } + if !strings.Contains(i, target) || before { + if _, err := fmt.Fprintf(out, k); err != nil { + return Error{ErrCantInput, Turbomole, O.inputname, """", []string{""fmt.Fprintf"", ""addtoControl""}, true} + + } + } + } + return nil +} + +func (O *TMHandle) addCosmo(epsilon float64) error { + //The ammount of newlines is wrong, must fix + cosmostring := """" //a few newlines before the epsilon + if epsilon == 0 { + return nil + } + cosmostring = fmt.Sprintf(""%s%3.1f\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nr all b\n*\n\n\n\n\n\n"", cosmostring, epsilon) + def := exec.Command(O.cosmoprepcom) + pipe, err := def.StdinPipe() + if err != nil { + return Error{noCosmoPrep, Turbomole, O.inputname, err.Error(), []string{""exec.StdinPipe"", ""addCosmo""}, true} + } + defer pipe.Close() + pipe.Write([]byte(cosmostring)) + if err := def.Run(); err != nil { + return Error{noCosmoPrep, Turbomole, O.inputname, err.Error(), []string{""exec.Run"", ""addCosmo""}, true} + + } + return nil + +} + +func (O *TMHandle) addBasis(basisOrEcp string, basiselems []string, basis, defstring string) string { + if basiselems == nil { //no atoms to add basis to, do nothing + return defstring + } + for _, elem := range basiselems { + defstring = fmt.Sprintf(""%s%s \""%s\"" %s\n"", defstring, basisOrEcp, strings.ToLower(elem), basis) + } + return defstring +} + +// modifies the coord file such as to freeze the atoms in the slice frozen. +func (O *TMHandle) addFrozen(frozen []int) error { + f, err := os.Open(""coord"") + if err != nil { + return Error{noCosmoPrep, Turbomole, O.inputname, err.Error(), []string{""os.Open"", ""addFrozen""}, true} + + } + lines := make([]string, 0, 200) //200 is just a guess for the number of lines in the coord file + c := bufio.NewReader(f) + for err == nil { + var line string + line, err = c.ReadString('\n') + lines = append(lines, line) + } + f.Close() //I cant defer it because I need it closed now. + out, err := os.Create(""coord"") + defer out.Close() + for key, i := range lines { + if isInInt(frozen, key-1) { + j := strings.Replace(i, ""\n"", "" f\n"", -1) + if _, err := fmt.Fprintf(out, j); err != nil { + return Error{noCosmoPrep, Turbomole, O.inputname, err.Error(), []string{""fmt.Fprintf"", ""addFrozen""}, true} + + } + } else { + if _, err := fmt.Fprintf(out, i); err != nil { + return Error{noCosmoPrep, Turbomole, O.inputname, err.Error(), []string{""fmt.Fprintf"", ""addFrozen""}, true} + + } + } + } + return nil +} + +func copy2pipe(pipe io.ReadCloser, file *os.File, end chan bool) { + io.Copy(file, pipe) + end <- true +} + +// BuildInput builds an input for TM based int the data in atoms, coords and C. +// returns only error. +// Note that at this point the interface does not support multiplicities different from 1 and 2. +// The number in atoms is simply ignored. +func (O *TMHandle) BuildInput(coords *v3.Matrix, atoms chem.AtomMultiCharger, Q *Calc) error { + const noDefine = ""goChem/QM: Unable to run define"" + const nox2t = ""goChem/QM: Unable to run x2t"" + err := os.Mkdir(O.inputname, os.FileMode(0755)) + for i := 0; err != nil; i++ { + if strings.Contains(err.Error(), ""file exists"") { + O.inputname = fmt.Sprintf(""%s%d"", O.inputname, i) + err = os.Mkdir(O.inputname, os.FileMode(0755)) + } else { + return Error{""goChem/QM: Unable to build input"", Turbomole, O.inputname, err.Error(), []string{""os.Mkdir"", ""BuildInput""}, true} + } + } + O.symmetry = Q.Symmetry + _ = os.Chdir(O.inputname) + defer os.Chdir("".."") + //Set the coordinates in a slightly stupid way. + chem.XYZFileWrite(""file.xyz"", coords, atoms) + x2t := exec.Command(""x2t"", ""file.xyz"") + stdout, err := x2t.StdoutPipe() + if err != nil { + return Error{nox2t, Turbomole, O.inputname, err.Error(), []string{""exec.StdoutPipe"", ""BuildInput""}, true} + } + coord, err := os.Create(""coord"") + if err != nil { + return Error{nox2t, Turbomole, O.inputname, err.Error(), []string{""os.Create"", ""BuildInput""}, true} + + } + if err := x2t.Start(); err != nil { + return Error{nox2t, Turbomole, O.inputname, err.Error(), []string{""exec.Start"", ""BuildInput""}, true} + + } + // var end chan bool + // go copy2pipe(stdout, coord, end) + // <-end + io.Copy(coord, stdout) + coord.Close() + //not defearable + defstring := ""\n\n\na coord\ndesy\nired\n*\n"" //reduntant internals + if Q.CartesianOpt { + defstring = ""\n\n\na coord\ndesy\n*\nno\n"" + } + if atoms == nil || coords == nil { + return Error{ErrMissingCharges, Turbomole, O.inputname, """", []string{""BuildInput""}, true} + } + if Q.Basis == """" { + log.Printf(""no basis set assigned for TM calculation, will used the default %s, \n"", O.defbasis) + Q.Basis = O.defbasis + } + //there is another check for these methods below. I should try to make it that it only checks for this + //once. + if Q.Method == ""r2scan-3c"" { + Q.Basis = ""def2-mTZVPP"" + Q.RI = true + } else if Q.Method == ""b97-3c"" { + Q.Basis = ""def2-mTZVP"" + Q.RI = true + } else if Q.Method == ""hf-3c"" { + Q.Basis = ""minix"" + Q.RI = false + } + defstring = defstring + ""b all "" + Q.Basis + ""\n"" + if Q.LowBasis != """" && len(Q.LBElements) > 0 { + defstring = O.addBasis(""b"", Q.LBElements, Q.LowBasis, defstring) + } + if Q.HighBasis != """" && len(Q.HBElements) > 0 { + defstring = O.addBasis(""b"", Q.HBElements, Q.HighBasis, defstring) + } + //Manually adding ECPs seem to be problematic, so I don't advise to do so. + if Q.ECP != """" && len(Q.ECPElements) > 0 { + defstring = O.addBasis(""ecp"", Q.ECPElements, Q.ECP, defstring) + } + defstring = defstring + ""\n*\n"" + //The following needs to be added because some atoms (I haven't tried so many, but + //so far only copper) causes define to ask an additional question. If one doesn't add ""y\n"" + //for each of those questions, the whole input for define will be wrong. + stupid := """" + stupidatoms := ""Zn Cu"" //if you want to add more stupid atoms just add then to the string: ""Cu Zn"" + for i := 0; i < atoms.Len(); i++ { + if stupidatoms == """" { + break + } + if strings.Contains(stupidatoms, atoms.Atom(i).Symbol) { + stupidatoms = strings.Replace(stupidatoms, atoms.Atom(i).Symbol, """", -1) + stupid = stupid + ""y\n"" + } + } + //Here we only produce singlet and doublet states (sorry). I will most certainly *not* deal with the ""joys"" + //of setting other multiplicities in define. + defstring = fmt.Sprintf(""%seht\n%sy\ny\n%d\n\n\n\n\n"", defstring, stupid, atoms.Charge()) //I add one additional ""y\n"" + method, ok := tMMethods[strings.ToLower(Q.Method)] + if !ok { + fmt.Fprintf(os.Stderr, ""no method assigned for TM calculation, will used the default %s, \n"", O.defmethod) + Q.Method = O.defmethod + Q.RI = true + } else { + Q.Method = method + } + //We only support HF and DFT + O.command = ""dscf"" + if Q.Method != ""hf"" && Q.Method != ""hf-3c"" { + grid := """" + if Q.Grid != 0 && Q.Grid <= 7 { + grid = fmt.Sprintf(""grid\n m%d\n"", Q.Grid) + } else { + + grid = fmt.Sprintf(""grid\n m%d\n"", O.defgrid) + } + defstring = defstring + ""dft\non\nfunc "" + Q.Method + ""\n"" + grid + ""*\n"" + if Q.RI { + mem := 500 + if Q.Memory != 0 { + mem = Q.Memory + } + defstring = fmt.Sprintf(""%sri\non\nm %d\n*\n"", defstring, mem) + O.command = ""ridft"" + } + } + defstring = O.addMARIJ(defstring, atoms, Q) + defstring = defstring + ""*\n"" + log.Println(defstring) + + //set the frozen atoms (only cartesian constraints are supported) + if err := O.addFrozen(Q.CConstraints); err != nil { + return errDecorate(err, ""BuildInput"") + } + if O.dryrun { + return nil + } + def := exec.Command(""define"") + pipe, err := def.StdinPipe() + if err != nil { + return Error{noDefine, Turbomole, O.inputname, err.Error(), []string{""exec.StdinPipe"", ""BuildInput""}, true} + } + defer pipe.Close() + pipe.Write([]byte(defstring)) + if err := def.Run(); err != nil { + return Error{noDefine, Turbomole, O.inputname, err.Error(), []string{""exec.Run"", ""BuildInput""}, true} + } + + O.setJob(Q) + + //Now modify control + args := make([]string, 1, 2) + args[0], ok = tMDisp[Q.Dispersion] + if !ok { + fmt.Fprintf(os.Stderr, ""Dispersion correction requested %s not supported, will used the default: D3, \n"", Q.Dispersion) + args[0] = ""$disp3"" + } + + if Q.Method == ""hf-3c"" { + args[0] = ""$disp3 -bj -func hf-3c"" + } + if Q.Method == ""b97-3c"" { + args[0] = ""$disp3 -bj -abc"" + } + + if strings.Contains(Q.Method, ""r2scan"") { // both r2scan and r2scan-3c get the extra grid + if err := O.addToControl([]string{"" radsize 8""}, nil, false, ""gridsize""); err != nil { + return errDecorate(err, ""BuildInput"") + } + if Q.Method == ""r2scan-3c"" { + args[0] = ""$disp4"" + } + + } + if Q.Gimic { + O.command = ""mpshift"" + args = append(args, ""$gimic"") + } + if err := O.addToControl(args, Q, true); err != nil { + return errDecorate(err, ""BuildInput"") + } + + //Finally the cosmo business. + err = O.addCosmo(Q.Dielectric) + if err != nil { + return errDecorate(err, ""BuildInput"") + } + return nil + +} + +func (O *TMHandle) setJob(Q *Calc) { + O.jchoose = jobChoose{} + O.jchoose.opti = func() { + O.precommand = O.command + O.command = ""jobex -c 200"" + if Q.RI { + O.command = O.command + "" -ri"" + if Q.OptTightness >= 2 { + O.command = O.command + ""-gcart 4"" + + } + } + } + O.jchoose.forces = func() { + O.command = ""NumForce -central"" + if Q.RI { + O.command = O.command + "" -ri"" + } + O.addToControl([]string{"" weight derivatives""}, nil, false, ""$dft"") + } + + Q.Job.Do(O.jchoose) +} + +func (O *TMHandle) NewJob(Q *Calc) error { + O.setJob(Q) + Q.Job.Do(O.jchoose) + return nil +} + +var tMMethods = map[string]string{ + ""hf"": ""hf"", + ""hf-3c"": ""hf-3c"", + ""b3lyp"": ""b3-lyp"", + ""b3-lyp"": ""b3-lyp"", + ""pbe"": ""pbe"", + ""tpss"": ""tpss"", + ""tpssh"": ""tpssh"", + ""bp86"": ""b-p"", + ""b-p"": ""b-p"", + ""blyp"": ""b-lyp"", + ""b-lyp"": ""b-lyp"", + ""b97-3c"": ""b97-3c"", + ""r2scan-3c"": ""r2scan-3c"", + ""r2scan"": ""r2scan"", + ""pw6b95"": ""pw6b95"", +} + +var tMDisp = map[string]string{ + """": """", + ""nodisp"": """", + ""D"": ""$olddisp"", + ""D2"": ""$disp2"", + ""D3"": ""$disp3"", + ""D3BJ"": ""$disp3 -bj"", + ""D4"": ""$disp4"", + ""D3abc"": ""$disp3 -bj -abc"", +} + +func (O *TMHandle) PreOpt(wait bool) error { + command := exec.Command(""sh"", ""-c"", ""jobex -level xtb -c 1000 > jobexpreopt.out"") + var err error + os.Chdir(O.inputname) + defer os.Chdir("".."") + if wait == true { + err = command.Run() + } else { + err = command.Start() + } + if err != nil { + err = Error{ErrNotRunning, Turbomole, O.inputname, err.Error(), []string{""exec.Run/Start"", ""Run""}, true} + return err + + } + return nil +} + +// Run runs the command given by the string O.command +// it waits or not for the result depending on wait. +// This is a Unix-only function. +func (O *TMHandle) Run(wait bool) error { + os.Chdir(O.inputname) + defer os.Chdir("".."") + var err error + filename := strings.Fields(O.command) + if O.precommand != """" { + precomm := exec.Command(""sh"", ""-c"", ""nohup ""+O.precommand+"" >""+filename[0]+"".out"") + _ = precomm.Run() //we try to run the pre command but don't care too much if it doesn't work + } + //fmt.Println(""nohup "" + O.command + "" > "" + filename[0] + "".out"") + command := exec.Command(""sh"", ""-c"", ""nohup ""+O.command+"" >""+filename[0]+"".out"") + if wait == true { + err = command.Run() + } else { + err = command.Start() + } + if err != nil { + err = Error{ErrNotRunning, Turbomole, O.inputname, err.Error(), []string{""exec.Run/Start"", ""Run""}, true} + + } + return err +} + +// Energy returns the energy from the corresponding calculation, in kcal/mol. +func (O *TMHandle) Energy() (float64, error) { + os.Chdir(O.inputname) + defer os.Chdir("".."") + f, err := os.Open(""energy"") + if err != nil { + return 0, Error{ErrNoEnergy, Turbomole, O.inputname, err.Error(), []string{""os.Open"", ""Energy""}, true} + } + defer f.Close() + fio := bufio.NewReader(f) + line, err := getSecondToLastLine(fio) + if err != nil { + return 0, errDecorate(err, ""Energy ""+O.inputname) + } + en := strings.Fields(line)[1] + energy, err := strconv.ParseFloat(en, 64) + if err != nil { + err = Error{ErrNoEnergy, Turbomole, O.inputname, err.Error(), []string{""strconv.ParseFloat"", ""Energy""}, true} + } + return energy * chem.H2Kcal, err +} + +func (O *TMHandle) FreeEnergy(T float64) (float64, float64, error) { + os.Chdir(O.inputname) + defer os.Chdir("".."") + //The ammount of newlines is wrong, must fix + str := fmt.Sprintf(""\n1\ntstart=%6.2f tend=%6.2f\nq\n"", T, T) + if O.symmetry != """" { + sym := string(O.symmetry[1]) + str = sym + str + } + def := exec.Command(""freeh"") + pipe, err := def.StdinPipe() + if err != nil { + return 0, 0, fmt.Errorf(""TM/FreeEnergy: Unable to open input pipe for freeh"") + } + + defer pipe.Close() + pipe.Write([]byte(str)) + var output []byte + if output, err = def.Output(); err != nil { + return 0, 0, fmt.Errorf(""Unable to run freeh"") + } + /* + f, err := os.Open(""freeh.out"") + if err != nil { + return 0, 0, fmt.Errorf(""Couldn't open output file freeh.out"") + } + defer f.Close() + */ + f := bytes.NewReader(output) + fio := bufio.NewReader(f) + var line string + cont := 0 + startcont := false + readFromTag := 2 + G := 0.0 + S := 0.0 + for line, err = fio.ReadString('\n'); err == nil; line, err = fio.ReadString('\n') { + if strings.Contains(line, ""(K) (MPa) (kJ/mol) (kJ/mol) (kJ/mol/K)"") { + startcont = true + continue + } + if startcont { + cont++ + } + if cont == readFromTag { + fi := strings.Fields(line) + G, err = strconv.ParseFloat(fi[5], 64) + if err != nil { + return 0, 0, err + } + S, err = strconv.ParseFloat(fi[7], 64) + if err != nil { + return 0, 0, err + } + S *= chem.KJ2Kcal + G *= chem.KJ2Kcal + break + } + + } + if err == nil || errors.Is(err, io.EOF) { + return G, S, nil + } + return G, S, err + +} + +// OptimizedGeometry returns the coordinates for the optimized structure. +func (O *TMHandle) OptimizedGeometry(atoms chem.Atomer) (*v3.Matrix, error) { + const not2x = ""unable to run t2x "" + os.Chdir(O.inputname) + defer os.Chdir("".."") + x2t := exec.Command(""t2x"") + stdout, err := x2t.StdoutPipe() + if err != nil { + return nil, Error{ErrNoGeometry, Turbomole, O.inputname, not2x + err.Error(), []string{""exec.StdoutPipe"", ""OptimizedGeometry""}, true} + } + if err := x2t.Start(); err != nil { + return nil, Error{ErrNoGeometry, Turbomole, O.inputname, not2x + err.Error(), []string{""exec.Start"", ""OptimizedGeometry""}, true} + + } + mol, err := chem.XYZRead(stdout) + if err != nil { + return nil, errDecorate(err, ""qm.OptimizedGeometry ""+Turbomole+"" ""+O.inputname) + } + return mol.Coords[len(mol.Coords)-1], nil + +} + +// Gets the second to last line in a turbomole energy file given as a bufio.Reader. +// expensive on the CPU but rather easy on the memory, as the file is read line by line. +func getSecondToLastLine(f *bufio.Reader) (string, error) { + prevline := """" + line := """" + var err error + for { + line, err = f.ReadString('\n') + if err != nil { + break + } + if !strings.Contains(line, ""$end"") { + prevline = line + } else { + break + } + } + return prevline, Error{err.Error(), Turbomole, """", ""Unknown"", []string{""getSecondToLastLine""}, true} +} +","Go" +"Computational Biochemistry","rmera/gochem","qm/crest.go",".go","11429","371","/* + * crest.go, part of gochem. + * + * + * Copyright 2024 Raul Mera . + * + * + * + */ +//In order to use this part of the library you need the xtb program, which must be obtained from Prof. Stefan Grimme's group. +//Please cite the the xtb references if you used the program. + +package qm + +import ( + // ""bufio"" + + ""bufio"" + ""errors"" + ""fmt"" + ""io"" + ""log"" + ""os"" + ""os/exec"" + ""runtime"" + ""strconv"" + ""strings"" + + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" +) + +// CrestHandle represents an xtb calculation +type CrestHandle struct { + //Note that the default methods and basis vary with each program, and even + //for a given program they are NOT considered part of the API, so they can always change. + //This is unavoidable, as methods change with time + command string + inputname string + nCPU int + options []string + relconstraints bool + wrkdir string + inputfile string + RunType string //entropy, protonate, deprotonate, search (default) + Temperatures [3]float64 //initial, final, step + EThres float64 + RMSDThres float64 +} + +// NewCrestHandle initializes and returns an xtb handle +// with values set to their defaults. Defaults might change +// as new methods appear, so they are not part of the API. +func NewCrestHandle() *CrestHandle { + run := new(CrestHandle) + run.SetDefaults() + return run +} + +//CrestHandle methods + +// SetnCPU sets the number of CPU to be used +func (O *CrestHandle) SetnCPU(cpu int) { + O.nCPU = cpu +} + +// Command returns the path and name for the xtb excecutable +func (O *CrestHandle) Command() string { + return O.command +} + +// SetName sets the name for the calculations +// which is defines the input and output file names +func (O *CrestHandle) SetName(name string) { + O.inputname = name +} + +// SetCommand sets the path and name for the xtb excecutable +func (O *CrestHandle) SetCommand(name string) { + O.command = name +} + +// SetWorkDir sets the name of the working directory for the calculations +func (O *CrestHandle) SetWorkDir(d string) { + O.wrkdir = d +} + +// SetDefaults sets calculations parameters to their defaults. +// Defaults might change +// as new methods appear, so they are not part of the API. +func (O *CrestHandle) SetDefaults() { + O.command = os.ExpandEnv(""crest"") + // if O.command == ""/xtb"" { //if CrestHOME was not defined + // O.command = ""./xtb"" + // } + cpu := runtime.NumCPU() / 2 + O.nCPU = cpu + +} + +// BuildInput builds an input for Crest. Right now it's very limited, only singlets are allowed and +// only unconstrained optimizations and single-points. +func (O *CrestHandle) BuildInput(coords *v3.Matrix, atoms chem.AtomMultiCharger, Q *Calc) error { + errid := ""CrestHandle/BuildInput"" + //Now lets write the thing + if O.wrkdir != """" && !strings.HasSuffix(O.wrkdir, ""/"") { + O.wrkdir += ""/"" + } + w := O.wrkdir + if O.inputname == """" { + O.inputname = ""gochem"" + } + //Only error so far + if atoms == nil || coords == nil { + return fmt.Errorf(""%s: no molecule or coordinates given"", errid) + } + err := chem.XYZFileWrite(w+O.inputname+"".xyz"", coords, atoms) + if err != nil { + return fmt.Errorf(""%s: Couldn't write xyz file: %w "", errid, err) + } + // mem := """" + + O.options = make([]string, 0, 6) + // O.options = append(O.options, O.command) + O.options = append(O.options, fmt.Sprintf(""--chrg %d"", atoms.Charge())) + O.options = append(O.options, fmt.Sprintf(""--uhf %d"", (atoms.Multi()-1))) + if O.nCPU > 1 { + O.options = append(O.options, fmt.Sprintf(""-P %d"", O.nCPU)) + } + //Added new things to select a method in xtb + if !isInString([]string{""gfn1"", ""gfn2"", ""gfn0"", ""gfnff""}, Q.Method) { + O.options = append(O.options, ""--gfn2"") //default method + } else { + O.options = append(O.options, ""--""+Q.Method) //default method + } + if Q.Dielectric > 0 && Q.Method != ""gfn0"" { //as of the current version, gfn0 doesn't support implicit solvation + solvent, ok := dielectric2Solvent[int(Q.Dielectric)] + if ok { + O.options = append(O.options, ""--alpb ""+solvent) + } + } + + o := ""--optlev vtight"" + if Q.OptTightness > 0 { + if Q.OptTightness < 2 { + o = ""--optlev normal"" + } + if Q.OptTightness == 2 { + o = ""--optlev tight"" + } + } + O.options = append(O.options, o) + + //run type. It's your responsibility to set only one of them to true. + + switch strings.ToLower(O.RunType) { + case ""entropy"": + O.options = append(O.options, ""--entropy"") + case ""protonate"": + O.options = append(O.options, ""--protonate"") + case ""deprotonate"": + O.options = append(O.options, ""--deprotonate"") + case ""v2"": + O.options = append(O.options, ""--v2"") + case ""v1"": + O.options = append(O.options, ""--v1"") + case ""v3"": + O.options = append(O.options, ""--v3"") + case ""v4"": + O.options = append(O.options, ""--v4"") + case ""tautomerize"": + O.options = append(O.options, ""--tautomerize"") + case """": + O.options = append(O.options, """") //I could have just left this empty + default: + log.Printf(""%s: Runtype %s not available, will do the CREST default (currently, v3)"", errid, O.RunType) + } + + ts := O.Temperatures + if ts == [3]float64{0, 0, 0} { + ts = [3]float64{298.15, 299.15, 1} + } + O.options = append(O.options, fmt.Sprintf(""--trange %5.2f %5.2f %5.2f"", ts[0], ts[1], ts[2])) + + if O.EThres > 0 { //crest expect this options in kcal, so no conversion needed + O.options = append(O.options, fmt.Sprintf(""--ewin %4.1f"", O.EThres)) + } + if O.RMSDThres > 0 { //crest expect this options in kcal, so no conversion needed + O.options = append(O.options, fmt.Sprintf(""--rthr %4.1f"", O.RMSDThres)) + } + + O.options = append(O.options, fmt.Sprintf(""--temp %5.2f"", ts[0])) + + if Q.CConstraints != nil || Q.IConstraints != nil { + xtbh := NewXTBHandle() + constraintsfile := ""constraints"" + xtbh.SetName(constraintsfile) + xtbh.SetWorkDir(O.wrkdir) + err = xtbh.BuildInput(coords, atoms, Q) + if err != nil { + return fmt.Errorf(""%s: Couldn't produce the constraints file: %w"", errid, err) + } + O.options = append(O.options, ""--cinp ""+constraintsfile+"".inp"") + } + O.options = append(O.options, O.inputname+"".xyz"") + + return nil +} + +// Run runs the command given by the string O.command +// it waits or not for the result depending on wait. +// Not waiting for results works +// only for unix-compatible systems, as it uses bash and nohup. +func (O *CrestHandle) Run(wait bool) (err error) { + errid := ""CrestHandle/Run"" + var com string + options := """" + if len(O.options) >= 3 { + options = strings.Join(O.options, "" "") + } + + com = fmt.Sprintf("" %s > %s.out 2>&1"", options, O.inputname) + + if wait { + //It would be nice to have this logging as an option. + //log.Printf(O.command + com) //this is stderr, I suppose + command := exec.Command(""sh"", ""-c"", O.command+com) + command.Dir = O.wrkdir + err = command.Run() + + } else { + command := exec.Command(""sh"", ""-c"", ""nohup ""+O.command+com) + command.Dir = O.wrkdir + err = command.Start() + } + if err != nil { + err = fmt.Errorf(""%s: %w"", errid, err) + } + os.Remove(""xtbrestart"") + return nil +} + +// Checks that an CREST calculation has terminated normally +func (O *CrestHandle) normalTermination() bool { + inp := O.wrkdir + O.inputname + if searchBackwards(""CREST terminated normally"", fmt.Sprintf(""%s.out"", inp)) != """" { + return true + } + return false +} + +func (O *CrestHandle) ConformerEnergies() ([]float64, error) { + ei := ""CrestHanle/ConformerEnergies"" + if !O.normalTermination() { + return nil, fmt.Errorf(""%s: CREST run didn't finish normally"", ei) + } + + finp, err := os.Open(O.wrkdir + ""crest_conformers.xyz"") + if err != nil { + return nil, fmt.Errorf(""%s: %w"", ei, err) + } + defer finp.Close() + energies := make([]float64, 0, 10) + fr := bufio.NewReader(finp) + var line string + trim := strings.TrimSpace + var reade bool + nenergy := 0 + for line, err = fr.ReadString('\n'); err == nil; line, err = fr.ReadString('\n') { + if _, err2 := strconv.Atoi(trim(line)); err2 == nil { + //I'm only trying to detect the lines after which comes the energy. Those lines + //should have only an integer, and they should be the only lines to be like that + reade = true + continue + } + if reade { + e, err := strconv.ParseFloat(trim(line), 64) + if err != nil { + return nil, fmt.Errorf(""%s: Couldn't parse energy %d: %w"", ei, nenergy, err) + } + energies = append(energies, e*chem.H2Kcal) + nenergy++ + reade = false + continue + } + } + if errors.Is(err, io.EOF) { + err = nil + } + return energies, err +} + +// Returns conformers from CREST as a trajectory, returning also the first one as a molecule. +// if asmolecule is given and true, then it returns the whole trajectory in the molecule, and nil +// for the trajectory. +func (O *CrestHandle) Conformers(asmolecule ...bool) (*chem.Molecule, *chem.XYZTraj, error) { + ei := ""CrestHandle/Conformers"" + if !O.normalTermination() { + return nil, nil, fmt.Errorf(""%s: CREST run didn't finish normally"", ei) + } + if len(asmolecule) > 0 && asmolecule[0] { + mol, err := chem.XYZFileRead(O.wrkdir + ""crest_conformers.xyz"") + if err != nil { + err = fmt.Errorf(""%s: Failed to retrieve conformers: %w"", ei, err) + } + return mol, nil, err + } + mol, traj, err := chem.XYZFileAsTraj(O.wrkdir + ""crest_conformers.xyz"") + if err != nil { + err = fmt.Errorf(""%s: Failed to retrieve conformers: %w"", ei, err) + } + return mol, traj, err +} + +// Returns the conformational and vibrational entropies at the first temperature given in the +// options (298.15 by default). +func (O *CrestHandle) Entropy() (float64, float64, error) { + ei := ""CrestHanle/Entropy"" + if !O.normalTermination() { + return 0, 0, fmt.Errorf(""%s: CREST run didn't finish normally"", ei) + } + inp := O.wrkdir + O.inputname + var err error + var sconf float64 + var svib float64 + energyline := searchBackwards(""Sconf ="", fmt.Sprintf(""%s.out"", inp)) + if energyline == """" { + return 0, 0, fmt.Errorf(""%s: Couldn't find conformational entropy in output"", ei) + } + split := strings.Fields(energyline) + if len(split) < 3 { + return 0, 0, fmt.Errorf(""%s: Bad format in found conformational entropy line: %s"", ei, energyline) + + } + sconf, err = strconv.ParseFloat(split[2], 64) + if err != nil { + return 0, 0, fmt.Errorf(""%s: Couldn't parse conformational entropy to a number: %s %s %w"", ei, energyline, split[2], err) + + } + sline := searchBackwards(""+ δSrrho ="", fmt.Sprintf(""%s.out"", inp)) + if sline == """" { + return 0, 0, fmt.Errorf(""%s: Couldn't find vibrational entropy in output"", ei) + } + split = strings.Fields(sline) + if len(split) < 4 { + return 0, 0, fmt.Errorf(""%s: Bad format in found vibrational entropy: %s"", ei, sline) + + } + svib, err = strconv.ParseFloat(split[3], 64) + if err != nil { + return 0, 0, fmt.Errorf(""%s: Couldn't parse vibrational entropy to a number: %s %s %w"", ei, energyline, split[3], err) + } + + return sconf / 1000.0, svib / 1000.0, err //It appears that the entropies are given in cal/mol*K, we give then + //in gochem units, kcal/mol*K +} +","Go" +"Computational Biochemistry","rmera/gochem","qm/qm_test.go",".go","11322","469","/* + * qm_test.go, part of gochem. + * + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + * + */ + +package qm + +import ( + ""fmt"" + ""os"" + ""strings"" + ""testing"" + + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" +) + +// TestQM tests the QM functionality. It prepares input for ORCA and MOPAC +// In the case of MOPAC it reads a previously prepared output and gets the energy. +func TestOrca(Te *testing.T) { + mol, err := chem.XYZFileRead(""../test/water.xyz"") + if err != nil { + Te.Error(err) + + } + if err := mol.Corrupted(); err != nil { + Te.Error(err) + } + fmt.Println(mol.Coords[0], len(mol.Coords), ""LOS JUIMOS CTM"", err) + // mol.Del(mol.Len() - 1) + mol.SetCharge(0) + mol.SetMulti(1) + calc := new(Calc) + calc.SetDefaults() + calc.SCFTightness = 2 //very demanding + calc.Job = &Job{Opti: true} + //calc.Job.Opti=true + calc.Method = ""r2scan-3c"" + calc.Dielectric = 4 + // calc.Basis = ""def2-SVP"" + // calc.HighBasis = ""def2-TZVP"" + calc.Grid = 4 + calc.Memory = 1000 + // calc.HBAtoms = []int{3, 10, 12} + // calc.HBElements = []string{""Cu"", ""Zn""} + calc.CConstraints = []int{0, 2} + calc.OldMO = true + orca := NewOrcaHandle() + orca.SetnCPU(12) ///////////////////// + orca.SetWorkDir(""orca"") + atoms := mol.Coords[0] //v3.Zeros(mol.Len()) + // mol.Next(atoms) + original_dir, _ := os.Getwd() //will check in a few lines + if err = os.Chdir(""../test""); err != nil { + Te.Error(err) + } + _ = orca.BuildInput(atoms, mol, calc) + orca.SetName(""gochemForces"") + calc.Job = &Job{Forces: true} + _ = orca.BuildInput(atoms, mol, calc) + //Now anothertest with HF-3c + calc.HBAtoms = nil + calc.HBElements = nil + calc.RI = false + calc.Grid = -1 + calc.Dielectric = 0 + calc.Method = ""HF-3c"" + orca.SetName(""HF3c"") + orca.SetnCPU(8) + // fmt.Println(mol.Coords[0], ""vieja"") + _ = orca.BuildInput(atoms, mol, calc) + path, _ := os.Getwd() + // if err:=orca.Run(false); err!=nil{ + // Te.Error(err.Error()) + // } + fmt.Println(path) + //Now a MOPAC optimization with the same configuration. + mopac := NewMopacHandle() + mopac.SetWorkDir(""mopac"") + mopac.BuildInput(atoms, mol, calc) + mopaccommand := os.Getenv(""MOPAC_LICENSE"") + ""/MOPAC2016.exe"" + mopac.SetCommand(mopaccommand) + fmt.Println(""command"", mopaccommand) + /* + if err := mopac.Run(true); err != nil { + if strings.Contains(err.Error(), ""no such file"") { + fmt.Println(""Error"", err.Error(), ("" Will continue."")) + } else { + Te.Error(err.Error()) + } + } + energy, err := mopac.Energy() + if err != nil { + if err.Error() == ""Probable problem in calculation"" { + fmt.Println(err.Error()) + } else { + Te.Error(err) + } + } + geometry, err := mopac.OptimizedGeometry(mol) + if err != nil { + if err.Error() == ""Probable problem in calculation"" { + fmt.Println(err.Error()) + } else { + Te.Error(err) + } + } + mol.Coords[0] = geometry + fmt.Println(energy) + if err := chem.XYZFileWrite(""mopac.xyz"", mol.Coords[0], mol); err != nil { + Te.Error(err) + } + //Took away this because it takes too long to run :-) + /* if err=orca.Run(true); err!=nil{ + Te.Error(err) + } + */ + if err = os.Chdir(original_dir); err != nil { + Te.Error(err) + } + fmt.Println(""end mopac and orca test!"") +} + +// TestTurbo tests the QM functionality. It prepares input for Turbomole +// Notice that 2 TM inputs cannot be in the same directory. Notice that TMHandle +// supports ECPs +func TestTurbo(Te *testing.T) { + fmt.Println(""Turbomole TEST y wea!"") + mol, err := chem.XYZFileRead(""../test/ethanol.xyz"") + original_dir, _ := os.Getwd() //will check in a few lines + os.Chdir(""../test"") + defer os.Chdir(original_dir) + if err != nil { + Te.Error(err) + } + if err := mol.Corrupted(); err != nil { + Te.Error(err) + } + mol.SetCharge(0) + mol.SetMulti(1) + calc := new(Calc) + calc.CartesianOpt = true + calc.SCFConvHelp = 1 //very demanding + calc.Memory = 1000 + //Not advised + // calc.ECP = ""ecp-10-mdf"" + // calc.ECPElements = []string{""O""} + calc.Grid = 4 + calc.Job = &Job{Opti: true} + calc.Method = ""BP86"" + calc.Dielectric = 4 + calc.Basis = ""def2-SVP"" + calc.HighBasis = ""def2-TZVP"" + calc.HBElements = []string{""C""} + calc.RI = true + calc.Dispersion = ""D3"" + calc.CConstraints = []int{0, 3} + tm := NewTMHandle() + atoms := mol.Coords[0] + //if err = os.Chdir(""./test""); err != nil { + // Te.Error(err) + //} + // tm.SetDryRun(true) //I don't have TM installed. + if err := tm.BuildInput(atoms, mol, calc); err != nil { + Te.Error(err) + } + /* + + if err := tm.Run(true); err != nil { + Te.Error(err) + } + energy, err := tm.Energy() + if err != nil { + Te.Error(err) + } + fmt.Println(""energy"", energy) + geo, err := tm.OptimizedGeometry(mol) + if err != nil { + Te.Error(err) + } + fmt.Println(""GEO"", geo) + chem.XYZFileWrite(""optiethanol.xyz"", geo, mol) + fmt.Println(""end TurboTest!"") + */ + // os.Chdir(original_dir) +} + +func TestFermions(Te *testing.T) { + mol, err := chem.XYZFileRead(""../test/ethanol.xyz"") + if err != nil { + Te.Error(err) + } + if err := mol.Corrupted(); err != nil { + Te.Error(err) + } + mol.SetCharge(0) + mol.SetMulti(1) + calc := new(Calc) + calc.Job = &Job{Opti: true} + calc.Method = ""BLYP"" + calc.Dielectric = 4 + calc.Basis = ""def2-SVP"" + calc.Grid = 4 + calc.Dispersion = ""D3"" + calc.CConstraints = []int{0, 10, 20} + cs := NewFermionsHandle() + cs.SetWorkDir(""fermions"") + cs.SetName(""gochemF"") + atoms := mol.Coords[0] + original_dir, _ := os.Getwd() //will check in a few lines + if err = os.Chdir(""../test""); err != nil { + Te.Error(err) + } + err = cs.BuildInput(atoms, mol, calc) + defer os.Chdir(original_dir) + // E, err := cs.Energy() + // if err != nil { + // Te.Error(err) + // } + // fmt.Println(""Final energy:"", E, ""kcal/mol"") + // ngeo,err:=cs.OptimizedGeometry(mol) + // if err!=nil{ + // fmt.Println(""Error with the geometry?: "", err.Error()) + // } + // chem.XYZFileWrite(""LastGeoFermions.xyz"",ngeo,mol) + fmt.Println(""Passed FermiONs++ test!"") +} + +func qderror_handler(err error, Te *testing.T) { + if err != nil { + if strings.Contains(""NonFatal"", err.Error()) { + fmt.Println(""Non fatal error: "", err.Error()) + } else { + Te.Error(err) + } + } +} + +func TestNWChem(Te *testing.T) { + mol, err := chem.XYZFileRead(""../test/water.xyz"") + if err != nil { + Te.Error(err) + } + if err := mol.Corrupted(); err != nil { + Te.Error(err) + } + fmt.Println(mol.Coords[0], len(mol.Coords), ""Quiere quedar leyenda, compadre?"", err) + mol.SetCharge(0) + mol.SetMulti(1) + calc := new(Calc) + calc.SCFTightness = 1 //quite tight + calc.SCFConvHelp = 1 + calc.Job = &Job{Opti: true} + calc.Method = ""TPSS"" + calc.Dielectric = 4 + calc.Basis = ""def2-SVP"" + calc.HighBasis = ""def2-TZVP"" + calc.Grid = 4 + calc.Memory = 1000 + calc.HBAtoms = []int{2} + calc.HBElements = []string{""O""} + calc.CConstraints = []int{1} + calc.SetDefaults() + nw := NewNWChemHandle() + orca := NewOrcaHandle() + nw.SetName(""gochem"") + nw.SetnCPU(1) + nw.SetCommand(""/usr/lib64/openmpi/bin/nwchem_openmpi"") + orca.SetName(""gochemII"") + nw.SetWorkDir(""../test/nwchem"") + orca.SetWorkDir(""../test/nwchem"") + atoms := mol.Coords[0] //v3.Zeros(mol.Len()) + // mol.Next(atoms) + // if err = os.Chdir(""../test""); err != nil { + // Te.Error(err) + // } + err = nw.BuildInput(atoms, mol, calc) + if err != nil { + Te.Error(err) + } + /* + //nw.Run(true) + _ = orca.BuildInput(atoms, mol, calc) + //The files are already in ./test. + os.Chdir(""../test"") + defer os.Chdir(""../qm"") + energy, err := nw.Energy() + if err != nil { + Te.Error(err) + } + fmt.Println(""NWChem Energy: "", energy) + newg, err := nw.OptimizedGeometry(mol) + if err != nil { + Te.Error(err) + } + chem.XYZFileWrite(""optiNW.xyz"", newg, mol) + */ +} + +func TestXtb(Te *testing.T) { + mol, err := chem.XYZFileRead(""../test/ethanol.xyz"") + if err != nil { + Te.Error(err) + } + if err := mol.Corrupted(); err != nil { + Te.Error(err) + } + fmt.Println(mol.Coords[0], len(mol.Coords), ""Quiere quedar XTB leyenda, compadre?"", err) + mol.SetCharge(0) + mol.SetMulti(1) + calc := new(Calc) + calc.Job = &Job{Opti: true} + calc.CConstraints = []int{2, 4} + //no support for constraints yet + calc.Method = ""gfn2"" + calc.Dielectric = 4 + xtb := NewXTBHandle() + xtb.SetName(""XTBgochem"") + xtb.SetWorkDir(""xtb"") + atoms := v3.Zeros(mol.Len()) + mol.Next(atoms) + if err = os.Chdir(""../test""); err != nil { + Te.Error(err) + } + err = xtb.BuildInput(atoms, mol, calc) + if err != nil { + Te.Error(err) + } + if err := xtb.Run(true); err != nil { + Te.Error(err) + } + os.Chdir(""../test"") + defer os.Chdir(""../qm"") + energy, err := xtb.Energy() + if err != nil { + Te.Error(err) + } + fmt.Println(""XTB Energy: "", energy) + newg, err := xtb.OptimizedGeometry(mol) + if err != nil { + Te.Error(err) + } + chem.XYZFileWrite(""optiXTB.xyz"", newg, mol) + +} + +func TestNBO(Te *testing.T) { + f, err := os.Open(""../test/nbo/etmetoh.out"") + if err != nil { + Te.Error(err) + } + defer f.Close() + + props, err := NBOProps(f) + + if err != nil { + Te.Error(err) + } + fmt.Println(""Electronic Configuration"") + for _, v := range props.EConfs { + fmt.Println(v) + } + + fmt.Println(""Charges"") + for _, v := range props.Charges { + fmt.Println(v) + } + + fmt.Println(""Delocalizations"") + for _, v := range props.Delocs { + fmt.Println(v) + } + + fmt.Println(""Steric Energies"") + for _, v := range props.Steric { + fmt.Println(v) + } +} + +func TestCrest(Te *testing.T) { + mol, err := chem.XYZFileRead(""../test/crest/etoh.xyz"") + if err != nil { + Te.Error(err) + } + if err := mol.Corrupted(); err != nil { + Te.Error(err) + } + q := new(Calc) + q.Method = ""gfn0"" + q.Dielectric = 80 + o := NewCrestHandle() + o.EThres = 10 + o.RMSDThres = 0.25 + o.SetWorkDir(""../test/crest"") + o.BuildInput(mol.Coords[0], mol, q) + err = o.Run(true) + if err != nil { + Te.Error(err) + } + m, _, err := o.Conformers(true) + if err != nil { + Te.Error(err) + } + for i, v := range m.Coords { + fmt.Println(""First line in coordinates"", i, v.VecView(0)) + } + o.RunType = ""entropy"" + o.BuildInput(mol.Coords[0], mol, q) + err = o.Run(true) + if err != nil { + Te.Error(err) + } + sconf, svib, err := o.Entropy() + if err != nil { + Te.Error(err) + } + fmt.Println(""T=298. TS(conf)="", sconf*298.0, ""TSvib="", svib*298, ""All in kcal/mol"") +} + +func TestCrestConstraint(Te *testing.T) { + mol, err := chem.XYZFileRead(""../test/crest/etoh.xyz"") + if err != nil { + Te.Error(err) + } + if err := mol.Corrupted(); err != nil { + Te.Error(err) + } + q := new(Calc) + q.Method = ""gfnff"" + q.Dielectric = 80 + q.CConstraints = []int{1, 2} + o := NewCrestHandle() + o.SetWorkDir(""../test/crest"") + o.RunType = ""entropy"" + o.BuildInput(mol.Coords[0], mol, q) + err = o.Run(true) + if err != nil { + Te.Error(err) + } + sconf, svib, err := o.Entropy() + if err != nil { + Te.Error(err) + } + fmt.Println(""T=298. TS(conf)="", sconf*298.0, ""TSvib="", svib*298, ""All in kcal/mol"") + +} +","Go" +"Computational Biochemistry","rmera/gochem","qm/qm.go",".go","9747","311","/* + * qm.go, part of gochem. + * + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * Dedicated to the long life of the Ven. Khenpo Phuntzok Tenzin Rinpoche + * + */ + +package qm + +import ( + ""fmt"" + + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" +) + +// builds an input for a QM calculation +type InputBuilder interface { + //Sets the name for the job, used for input + //and output files. The extentions will depend on the program. + SetName(name string) + + //BuildInput builds an input for the QM program based int the data in + //atoms, coords and C. returns only error. + BuildInput(coords *v3.Matrix, atoms chem.AtomMultiCharger, Q *Calc) error +} + +// Runs a QM calculation +type Runner interface { + //Run runs the QM program for a calculation previously set. + //it waits or not for the result depending of the value of + //wait. + Run(wait bool) (err error) +} + +// Builds inputs and runs a QM calculations +type BuilderRunner interface { + InputBuilder + Runner +} + +// Allows to recover energy and optimized geometries from a QM calculation +type EnergyGeo interface { + + //Energy gets the last energy for a calculation by parsing the + //QM program's output file. Return error if fail. Also returns + //Error (""Probable problem in calculation"") + //if there is a energy but the calculation didnt end properly. + Energy() (float64, error) + + //OptimizedGeometry reads the optimized geometry from a calculation + //output. Returns error if fail. Returns Error (""Probable problem + //in calculation"") if there is a geometry but the calculation didnt + //end properly* + OptimizedGeometry(atoms chem.Atomer) (*v3.Matrix, error) +} + +// Handle is an interface for a mostly-full functionality QM program +// where ""functionality"" reflects it's degree of support in goChem +type Handle interface { + BuilderRunner + EnergyGeo +} + +const ( + ErrProbableProblem = ""goChem/QM: Probable problem with calculations"" //this is never to be used for fatal errors + ErrMissingCharges = ""goChem/QM: Missing charges or coordinates"" + ErrCantValue = ""goChem/QM: Can't obtain requested value"" //for whatever doesn't match anything else + ErrNoEnergy = ""goChem/QM: No energy in output"" + ErrNoFreeEnergy = ""goChem/QM: No free energy in output. Forces calculation might have not been performed"" + ErrNoCharges = ""goChem/QM: Unable to read charges from output"" + ErrNoGeometry = ""gochem/QM: Unable to read geometry from output"" + ErrNotRunning = ""gochem/QM: Couldn't run calculation"" + ErrCantInput = ""goChem/QM: Can't build input file"" +) + +const ( + Orca = ""Orca"" + Mopac = ""Mopac"" + Turbomole = ""Turbomole"" + NWChem = ""NWChem"" + Fermions = ""Fermions++"" + XTB = ""XTB"" //this may go away if Orca starts supporting XTB. +) + +//errors + +// Error represents a decorable QM error. +type Error struct { + message string + code string //the name of the QM program giving the problem, or empty string if none + inputname string //the input file that has problems, or empty string if none. + additional string + deco []string + critical bool +} + +// Error returns a string with an error message. +func (err Error) Error() string { + return fmt.Sprintf(""%s (%s/%s) Message: %s"", err.message, err.inputname, err.code, err.additional) +} + +// Decorate will add the dec string to the decoration slice of strings of the error, +// and return the resulting slice. +func (err Error) Decorate(dec string) []string { + err.deco = append(err.deco, dec) + return err.deco +} + +// Code returns the name of the program that ran/was meant to run the +// calculation that caused the error. +func (err Error) Code() string { return err.code } //May not be needed + +// InputName returns the name of the input file which processing caused the error +func (err Error) InputName() string { return err.inputname } + +// Critical return whether the error is critical or it can be ifnored +func (err Error) Critical() bool { return err.critical } + +// errDecorate is a helper function that asserts that the error is +// implements chem.Error and decorates the error with the caller's name before returning it. +// if used with a non-chem.Error error, it will cause a panic. +func errDecorate(err error, caller string) error { + err2 := err.(chem.Error) //I know that is the type returned byt initRead + err2.Decorate(caller) + return err2 +} + +//end errors + +// jobChoose is a structure where each QM handler has to provide a closure that makes the proper arrangements for each supported case. +type jobChoose struct { + opti func() + forces func() + sp func() + md func() + charges func() +} + +// Job is a structure that define a type of calculations. +// The user should set one of these to true, +// and goChem will see that the proper actions are taken. If the user sets more than one of the +// fields to true, the priority will be Opti>Forces>SP (i.e. if Forces and SP are true, +// only the function handling forces will be called). +type Job struct { + Opti bool + Forces bool + SP bool + MD bool + Charges bool +} + +// Do sets the job set to true in J, according to the corresponding function in plan. A ""nil"" plan +// means that the corresponding job is not supported by the QM handle and we will default to single point. +func (J *Job) Do(plan jobChoose) { + if J == nil { + return + } + //now the actual options + if J.Opti { + plan.opti() + return + } + if J.Forces && plan.forces != nil { + plan.forces() + return + } + if J.MD && plan.md != nil { + plan.md() + return + } + if J.Charges && plan.charges != nil { //the default option is a single-point + plan.charges() + return + } + + if plan.sp != nil { //the default option is a single-point + plan.sp() + return + } + +} + +//Container for constraints to internal coordinates +//type IntConstraint struct { +// Kind byte +// Atoms []int +//} + +// PointCharge is a container for a point charge, such as those used in QM/MM +// calculations +type PointCharge struct { + Charge float64 + Coords *v3.Matrix +} + +// IConstraint is a container for a constraint to internal coordinates +type IConstraint struct { + CAtoms []int + Val float64 + Class byte // B: distance, A: angle, D: Dihedral + UseVal bool //if false, don't add any value to the constraint (which should leave it at the value in the starting structure. This migth not work on every program, but it works in ORCA. +} + +// Calc is a structure for the general representation of a calculation +// mostly independent of the QM program (although, of course, some methods will not work in some programs) +type Calc struct { + Symmetry string + Method string + Basis string + RI bool + RIJ bool + CartesianOpt bool //Do the optimization in cartesian coordinates. + BSSE string //Correction for BSSE + auxBasis string //for RI calculations + auxColBasis string //for RICOSX or similar calculations + HighBasis string //a bigger basis for certain atoms + LowBasis string //lower basis for certain atoms + HBAtoms []int + LBAtoms []int + HBElements []string + LBElements []string + CConstraints []int //cartesian contraints + IConstraints []*IConstraint + ECPElements []string //list of elements with ECP. + // IConstraints []IntConstraint //internal constraints + Dielectric float64 + // Solventmethod string + Dispersion string //D2, D3, etc. + Others string //analysis methods, etc + // PCharges []PointCharge + Guess string //initial guess + Grid int + OldMO bool //Try to look for a file with MO. + Job *Job //NOTE: This should probably be a pointer: FIX! NOTE2: Fixed it, but must check and fix whatever is now broken. + //The following 3 are only for MD simulations, will be ignored in every other case. + MDTime int //simulation time (whatever unit the program uses!) + MDTemp float64 //simulation temperature (K) + MDPressure int //simulation pressure (whatever unit the program uses!) + SCFTightness int //1,2 and 3. 0 means the default + OptTightness int + SCFConvHelp int + ECP string //The ECP to be used. It is the programmers responsibility to use a supported ECP (for instance, trying to use 10-electron core ECP for Carbon will fail) + Gimic bool + NBO bool + Memory int //Max memory to be used in MB (the effect depends on the QM program) +} + +// Utilities here +func (Q *Calc) SetDefaults() { + Q.RI = true + // Q.BSSE = ""gcp"" + Q.Dispersion = ""D3"" + Q.Memory = 3000 +} + +// Utilities here +func (Q *Calc) ConstrainNoHs(mol chem.Atomer) { + c := make([]int, 0, 20) + for i := 0; i < mol.Len(); i++ { + if mol.Atom(i).Symbol != ""H"" { + c = append(c, i) + } + } + Q.CConstraints = append(Q.CConstraints, c...) +} + +// isIn is a helper for the RamaList function, +// returns true if test is in container, false otherwise. +func isInInt(container []int, test int) bool { + if container == nil { + return false + } + for _, i := range container { + if test == i { + return true + } + } + return false +} + +// Same as the previous, but with strings. +func isInString(container []string, test string) bool { + if container == nil { + return false + } + for _, i := range container { + if test == i { + return true + } + } + return false +} +","Go" +"Computational Biochemistry","rmera/gochem","qm/orca.go",".go","23773","768","/* + * qm.go, part of gochem. + * + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + */ + +package qm + +import ( + ""fmt"" + ""log"" + ""os"" + ""os/exec"" + ""runtime"" + ""strconv"" + ""strings"" + + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" +) + +// OrcaHandle represents an Orca calculation. +// Note that the default methods and basis vary with each program, and even +// for a given program they are NOT considered part of the API, so they can always change. +type OrcaHandle struct { + defmethod string + defbasis string + defauxbasis string + defguess string + previousMO string + bsse string + command string + inputname string + wrkdir string + nCPU int + orca4 bool + cosmorsready bool +} + +// NewOrcaHandle initializes and returns a new OrcaHandle. +func NewOrcaHandle() *OrcaHandle { + run := new(OrcaHandle) + run.SetDefaults() + return run +} + +//OrcaHandle methods + +// SetnCPU sets the number of CPU to be used. +func (O *OrcaHandle) SetnCPU(cpu int) { + O.nCPU = cpu +} + +// SetName sets the name of the job, which will reflect in the +// name fo the input and output files. +func (O *OrcaHandle) SetName(name string) { + O.inputname = name +} + +// SetCommand sets the name and path of the Orca excecutable +func (O *OrcaHandle) SetCommand(name string) { + O.command = name +} + +// SetMOName sets the name of the file containing molecular +// orbitales (in the corresponding Orca format) to be +// used as initial guess. +func (O *OrcaHandle) SetMOName(name string) { + O.previousMO = name +} + +// SetWorkDir sets the name of the working directory for the calculation +func (O *OrcaHandle) SetWorkDir(d string) { + O.wrkdir = d +} + +// SetOrca3 sets the use of Orca3 to true or false. The default state +// is false, meaning that Orca4 is used. +func (O *OrcaHandle) SetOrca4(b bool) { + O.orca4 = b +} + +// SetDefaults Sets defaults for ORCA calculation. The default is +// currently a single-point at +// revPBE/def2-SVP with RI, and all the available CPU with a max of +// 8. The ORCA command is set to $ORCA_PATH/orca, at least in +// unix. +// The default is _not_ part of the API, it can change as new methods appear. +func (O *OrcaHandle) SetDefaults() { + O.defmethod = ""r2scan-3c"" //This is an API break, the default was BLYP/def2-SVP + O.defguess = ""HUECKEL"" + // O.defbasis = ""def2-SVP"" + // O.defauxbasis = ""def2/J"" + // if O.orca3 { + // O.defauxbasis = ""def2-SVP/J"" + // } + O.command = os.ExpandEnv(""${ORCA_PATH}/orca"") + if O.command == ""/orca"" { //if ORCA_PATH was not defined + O.command = ""./orca"" + } + cpu := runtime.NumCPU() / 2 + O.nCPU = cpu + O.inputname = ""gochem"" +} + +// BuildInput builds an input for ORCA based int the data in atoms, coords and C. +// returns only error. +func (O *OrcaHandle) BuildInput(coords *v3.Matrix, atoms chem.AtomMultiCharger, Q *Calc) error { + if O.wrkdir != """" { + O.wrkdir = O.wrkdir + ""/"" + } + //Only error so far + if atoms == nil || coords == nil { + return Error{ErrMissingCharges, Orca, O.inputname, """", []string{""BuildInput""}, true} + } + if Q.Basis == """" && !strings.HasSuffix(Q.Method, ""-3c"") { + log.Printf(""no basis set assigned for ORCA calculation, will used the default %s, \n"", O.defbasis) //NOTE: This could be changed for a non-critical error + Q.Basis = O.defbasis + } + if Q.Method == """" { + log.Printf(""no method assigned for ORCA calculation, will used the default %s, \n"", O.defmethod) + Q.Method = O.defmethod + // Q.auxColBasis = """" //makes no sense for pure functional + // Q.auxBasis = fmt.Sprintf(""%s/J"", Q.Basis) + } + + //Set RI or RIJCOSX if needed + if Q.Guess == """" { + Q.Guess = O.defguess + } + ri := """" + // if Q.RI && Q.RIJ { + // return Error{""goChem/QM: RI and RIJ cannot be activated at the same time"", Orca, O.inputname, """", []string{""BuildInput""}, true} + // } + //Not needed in orca5, but doesn't harm either + if Q.RI || Q.RIJ { + Q.auxBasis = ""def2/J"" //Of course, this will only work with Karlsruhe basis. + // if !strings.Contains(Q.Others,"" RI ""){ + ri = ""RI"" + } + if Q.RIJ { + ri = ""RIJCOSX"" + } + + disp := ""D3"" + if Q.Dispersion != """" { + disp = orcaDisp[Q.Dispersion] + } + if strings.HasSuffix(Q.Method, ""-3c"") || strings.HasSuffix(Q.Method, ""MP2"") { + disp = """" //Orca assigns dispersion automatically to the -3c methods. MP2 doesn't need dispersion. + } + opt := """" + optfreq := """" //stores all optimizations and frequencies flags + jc := jobChoose{} + jc.opti = func() { + opt = ""Opt"" + if Q.OptTightness == 1 { + opt = ""TightOpt"" + } else if Q.OptTightness >= 2 { + opt = ""VeryTightOpt"" + } + //We change to variable trust radius, and also to XTB2 Hessian. + if O.orca4 { + optfreq += ""%geom trust 0.3\nend\n\n"" + } else { + optfreq += ""%geom trust 0.3\n inhess XTB2\nend\n\n"" + } + } + //TODO: NOTE"" Add a flag for analytical Hessian. + jc.forces = func() { + optfreq += ""%freq\n NumFreq true\n CentralDiff true\n QuasiRRho true\nend\n\n"" + if O.orca4 { + strings.Replace(optfreq, "" QuasiRRho true\n"", """", -1) //AFAIK this is not supported in Orca 4 + } + } + Q.Job.Do(jc) + hfuhf := ""RHF"" + if atoms.Multi() != 1 { + hfuhf = ""UHF"" + } + moinp := """" + //If this flag is set we'll look for a suitable MO file. + //If not found, we'll use our default guess (Hueckel), which is NOT Orca's default. + //This is not needed in Orca5, but it doesn't harm, and _I think_ it is needed in Orca 4, so we'll leave it for now. + if Q.OldMO == true { + dir, _ := os.Open(""./"") //This should always work, hence ignoring the error + files, _ := dir.Readdir(-1) //Get all the files. + for _, val := range files { + if O.previousMO != """" { + break + } + if val.IsDir() == true { + continue + } + name := val.Name() + if strings.Contains(name, "".gbw"") { + O.previousMO = name + Q.Guess = """" //Remove the default + break + } + } + if O.previousMO != """" { + // Q.Guess = ""MORead"" + moinp = fmt.Sprintf(""%%scf\n Guess MORead\n MOInp \""%s\""\nend\n\n"", O.previousMO) + } else { + moinp = """" + // Q.Guess = """" //The default guess + } + } + tight := ""TightSCF"" + if Q.SCFTightness != 0 { + tight = orcaSCFTight[Q.SCFTightness] + } + conv := """" + if Q.SCFConvHelp == 0 { + //The default for this is nothing for RHF and SlowConv for UHF + if atoms.Multi() > 1 { + conv = ""SlowConv"" + } + } else { + conv = orcaSCFConv[Q.SCFConvHelp] + } + pal := """" + if O.nCPU > 1 { + pal = fmt.Sprintf(""%%pal nprocs %d\n end\n\n"", O.nCPU) //fmt.Fprintf(os.Stderr, ""CPU number of %d for ORCA calculations currently not supported, maximun 8"", O.nCPU) + } + grid := """" + if Q.Grid >= 3 { + grid = fmt.Sprintf(""DefGrid3"") + } + if O.orca4 { + grid = """" + if Q.Grid > 2 && Q.Grid <= 9 { + grid = fmt.Sprintf(""Grid%d"", Q.Grid) + } + if Q.Grid > 4 { + grid += "" NoFinalGrid"" + } + } + var err error + var bsse string + if bsse, err = O.buildgCP(Q); err != nil { + fmt.Fprintln(os.Stderr, err.Error()) + } + HF3cAdditional := """" // additional settings for HF-3c. + if Q.Method == ""HF-3c"" { //This method includes its own basis sets and corrections, so previous choices are overwritten. NOTE: there are some defaults that should be changed to get HF-3c to work better. + Q.Basis = """" + Q.auxBasis = """" + Q.auxColBasis = """" + //Q.Guess = """" + bsse = """" + disp = """" + HF3cAdditional = ""%scf\n MaxIter 200\n MaxIntMem 2000\nend\n\n"" + + } + NBO := """" + nbostr := """" + if Q.NBO { + NBO = ""NBO"" + nbostr = ""%nbo\nNBOKEYLIST=\""$NBO STERIC $END\""\nend"" + } + MainOptions := []string{""!"", hfuhf, Q.Method, Q.Basis, Q.auxBasis, Q.auxColBasis, tight, disp, conv, Q.Guess, opt, Q.Others, grid, ri, bsse, NBO, ""\n\n""} + mainline := strings.Join(MainOptions, "" "") + constraints := O.buildCConstraints(Q.CConstraints) + iconstraints, err := O.buildIConstraints(Q.IConstraints) + if err != nil { + return errDecorate(err, ""BuildInput"") + } + cosmo := """" + if Q.Dielectric > 0 { + method := ""cpcm"" + cosmo = fmt.Sprintf(""%%%s epsilon %1.0f\n refrac 1.30\n end\n\n"", method, Q.Dielectric) + } + mem := """" + if Q.Memory != 0 { + mem = fmt.Sprintf(""%%MaxCore %d\n\n"", Q.Memory) + } + + ElementBasis := """" + /**************** Removed High Basis Elements. This is an API break. + if Q.HBElements != nil || Q.LBElements != nil { + elementbasis := make([]string, 0, len(Q.HBElements)+len(Q.LBElements)+2) + elementbasis = append(elementbasis, ""%basis \n"") + for _, val := range Q.HBElements { + elementbasis = append(elementbasis, fmt.Sprintf("" newgto %s \""%s\"" end\n"", val, Q.HighBasis)) + } + for _, val := range Q.LBElements { + elementbasis = append(elementbasis, fmt.Sprintf("" newgto %s \""%s\"" end\n"", val, Q.LowBasis)) + } + elementbasis = append(elementbasis, "" end\n\n"") + ElementBasis = strings.Join(elementbasis, """") + } + *******************************/ + //Now lets write the thing + if O.inputname == """" { + O.inputname = ""gochem"" + } + file, err := os.Create(fmt.Sprintf(""%s.inp"", O.wrkdir+O.inputname)) + if err != nil { + return Error{ErrCantInput, Orca, O.inputname, err.Error(), []string{""os,Open"", ""BuildInput""}, true} + + } + defer file.Close() + _, err = fmt.Fprint(file, mainline) + //With this check its assumed that the file is ok + if err != nil { + return Error{ErrCantInput, Orca, O.inputname, err.Error(), []string{""fmt.Printf"", ""BuildInput""}, true} + + } + fmt.Fprint(file, HF3cAdditional) + fmt.Fprint(file, pal) + fmt.Fprint(file, moinp) + fmt.Fprint(file, mem) + fmt.Fprint(file, constraints) + fmt.Fprint(file, iconstraints) + fmt.Fprint(file, optfreq) + fmt.Fprint(file, ElementBasis) + fmt.Fprint(file, cosmo) + fmt.Fprint(file, nbostr) + fmt.Fprint(file, ""\n"") + //Now the type of coords, charge and multiplicity + fmt.Fprintf(file, ""* xyz %d %d\n"", atoms.Charge(), atoms.Multi()) + //now the coordinates + // fmt.Println(atoms.Len(), coords.Rows()) /////////////// + + for i := 0; i < atoms.Len(); i++ { + //api break, removed support for ""high"" and ""low"" basis in a calculation. + newbasis := """" + /********* + if isInInt(Q.HBAtoms, i) == true { + newbasis = fmt.Sprintf(""newgto \""%s\"" end"", Q.HighBasis) + } else if isInInt(Q.LBAtoms, i) == true { + newbasis = fmt.Sprintf(""newgto \""%s\"" end"", Q.LowBasis) + } + **********/ + // fmt.Println(atoms.Atom(i).Symbol) + fmt.Fprintf(file, ""%-2s %8.3f%8.3f%8.3f %s\n"", atoms.Atom(i).Symbol, coords.At(i, 0), coords.At(i, 1), coords.At(i, 2), newbasis) + } + fmt.Fprintf(file, ""*\n"") + return nil +} + +// Run runs the command given by the string O.command +// it waits or not for the result depending on wait. +// Not waiting for results works +// only for unix-compatible systems, as it uses bash and nohup. +func (O *OrcaHandle) Run(wait bool) (err error) { + if wait == true { + out, err := os.Create(fmt.Sprintf(""%s.out"", O.inputname)) + if err != nil { + return Error{ErrNotRunning, Orca, O.inputname, """", []string{""Run""}, true} + } + defer out.Close() + command := exec.Command(O.command, fmt.Sprintf(""%s.inp"", O.inputname)) + command.Stdout = out + command.Dir = O.wrkdir + err = command.Run() + + } else { + command := exec.Command(""sh"", ""-c"", ""nohup ""+O.command+fmt.Sprintf("" %s.inp > %s.out &"", O.inputname, O.inputname)) + command.Dir = O.wrkdir + err = command.Start() + } + if err != nil { + err = Error{ErrNotRunning, Orca, O.inputname, err.Error(), []string{""exec.Start"", ""Run""}, true} + } + return err +} + +// buildIConstraints transforms the list of cartesian constrains in the QMCalc structre +// into a string with ORCA-formatted internal constraints. +func (O *OrcaHandle) buildIConstraints(C []*IConstraint) (string, error) { + if C == nil { + return ""\n"", nil //no constraints + } + constraints := make([]string, len(C)+3) + constraints[0] = ""%geom Constraints\n"" + for key, val := range C { + + if iConstraintOrder[val.Class] != len(val.CAtoms) { + return """", Error{""Internal constraint ill-formated"", Orca, O.inputname, """", []string{""buildConstraints""}, true} + } + + var temp string + var value string + //if UseVal is false, we don't add any value to the contraint. Orca will constraint the coordinate to its value in the starting structure. + if val.UseVal { + value = fmt.Sprintf(""%2.3f"", val.Val) + } else { + value = """" + } + if val.Class == 'B' { + temp = fmt.Sprintf("" {B %d %d %s C}\n"", val.CAtoms[0], val.CAtoms[1], value) + } else if val.Class == 'A' { + temp = fmt.Sprintf("" {A %d %d %d %s C}\n"", val.CAtoms[0], val.CAtoms[1], val.CAtoms[2], value) + } else if val.Class == 'D' { + temp = fmt.Sprintf("" {D %d %d %d %d %s C}\n"", val.CAtoms[0], val.CAtoms[1], val.CAtoms[2], val.CAtoms[3], value) + } + constraints[key+1] = temp + } + last := len(constraints) - 1 + constraints[last-1] = "" end\n"" + constraints[last] = "" end\n"" + final := strings.Join(constraints, """") + return final, nil +} + +var iConstraintOrder = map[byte]int{ + 'B': 2, + 'A': 3, + 'D': 4, +} + +// buildCConstraints transforms the list of cartesian constrains in the QMCalc structre +// into a string with ORCA-formatted cartesian constraints +func (O *OrcaHandle) buildCConstraints(C []int) string { + if C == nil { + return ""\n"" //no constraints + } + constraints := make([]string, len(C)+3) + constraints[0] = ""%geom Constraints\n"" + for key, val := range C { + constraints[key+1] = fmt.Sprintf("" {C %d C}\n"", val) + } + last := len(constraints) - 1 + constraints[last-1] = "" end\n"" + constraints[last] = "" end\n"" + final := strings.Join(constraints, """") + return final +} + +// Only DFT is supported. Also, only Karlsruhe's basis sets. If you are using Pople's, +// let us know so we can send a mission to rescue you from the sixties :-) +func (O *OrcaHandle) buildgCP(Q *Calc) (string, error) { + ret := """" + var err error + if strings.ToLower(Q.BSSE) == ""gcp"" { + switch strings.ToLower(Q.Basis) { + case ""def2-svp"": + ret = ""GCP(DFT/SVP)"" + case ""def2-tzvp"": + ret = ""GCP(DFT/TZ)"" + case ""def2-sv(p)"": + ret = ""GCP(DFT/SV(P))"" + default: + err = Error{Orca, O.inputname, ""Method/basis combination for gCP unavailable, will skip the correction"", """", []string{""buildCP""}, false} + } + } + return ret, err +} + +var orcaSCFTight = map[int]string{ + 0: """", + 1: ""TightSCF"", + 2: ""VeryTightSCF"", +} + +var orcaSCFConv = map[int]string{ + 0: """", + 1: ""SlowConv"", + 2: ""VerySlowConv"", +} + +var orcaDisp = map[string]string{ + ""nodisp"": """", + ""D3OLD"": ""VDW10"", //compatibility with ORCA 2.9 + ""D2"": ""D2"", + ""D3BJ"": ""D3BJ"", + ""D3bj"": ""D3BJ"", + ""D3"": ""D3ZERO"", + ""D3ZERO"": ""D3ZERO"", + ""D3Zero"": ""D3ZERO"", + ""D3zero"": ""D3ZERO"", + ""D4"": ""D4"", + ""VV10"": ""NL"", //for these methods only the default integration grid is supported. + ""SCVV10"": ""SCNL"", + ""NL"": ""NL"", + ""SCNL"": ""SCNL"", +} + +// OptimizedGeometry reads the latest geometry from an ORCA optimization. Returns the +// +// geometry or error. Returns the geometry AND error if the geometry read +// is not the product of a correctly ended ORCA calculation. In this case +// the error is ""probable problem in calculation"" +func (O *OrcaHandle) OptimizedGeometry(atoms chem.Atomer) (*v3.Matrix, error) { + var err error + geofile := fmt.Sprintf(""%s.xyz"", O.wrkdir+O.inputname) + //Here any error of orcaNormal... or false means the same, so the error can be ignored. + if trust := O.orcaNormalTermination(); !trust { + err = Error{ErrProbableProblem, Orca, O.inputname, """", []string{""OptimizedGeometry""}, false} + } + //This might not be super efficient but oh well. + mol, err1 := chem.XYZFileRead(geofile) + if err1 != nil { + return nil, errDecorate(err1, ""qm.OptimizedGeometry ""+Orca+"" ""+O.inputname+"" ""+ErrNoGeometry) // Error{ErrNoEnergy, Orca, O.inputname, err1.Error(),[]string{""OptimizedGeometry""}, true} + } + return mol.Coords[0], err //returns the coords, the error indicates whether the structure is trusty (normal calculation) or not +} + +// Energy returns the free energy resulting from a frequencies calculation +// Returns error if problem, and also if the energy returned that is product of an +// abnormally-terminated ORCA calculation. (in this case error is ""Probable problem +// in calculation"") +func (O *OrcaHandle) FreeEnergy() (float64, error) { + templateline := ""Final Gibbs free energy .."" + indexinline := 5 + return O.energies(templateline, indexinline) +} + +// Energy returns the energy of a previous Orca calculations. +// Returns error if problem, and also if the energy returned that is product of an +// abnormally-terminated ORCA calculation. (in this case error is ""Probable problem +// in calculation"") +func (O *OrcaHandle) Energy() (float64, error) { + templateline := ""FINAL SINGLE POINT ENERGY"" + position := 4 + return O.energies(templateline, position) +} + +func (O *OrcaHandle) energies(templateline string, indexinline int) (float64, error) { + var err error + err = Error{ErrProbableProblem, Orca, O.inputname, """", []string{""Energy""}, false} + f, err1 := os.Open(fmt.Sprintf(""%s.out"", O.wrkdir+O.inputname)) + if err1 != nil { + return 0, Error{ErrNoEnergy, Orca, O.inputname, err.Error(), []string{""os.Open"", ""qm.Energy""}, true} + } + defer f.Close() + f.Seek(-1, 2) //We start at the end of the file + energy := 0.0 + var found bool + for i := 0; ; i++ { + line, err1 := getTailLine(f) + if err1 != nil { + return 0.0, errDecorate(err, ""Energy ""+O.inputname) + } + if strings.Contains(line, ""**ORCA TERMINATED NORMALLY**"") { + err = nil + } + if strings.Contains(line, templateline) { + splitted := strings.Fields(line) + energy, err1 = strconv.ParseFloat(splitted[indexinline], 64) + if err1 != nil { + return 0.0, Error{ErrNoEnergy, Orca, O.inputname, err1.Error(), []string{""strconv.Parsefloat"", ""Energy""}, true} + + } + found = true + break + } + } + if !found { + return 0.0, Error{ErrNoEnergy, Orca, O.inputname, """", []string{""Energy""}, false} + } + return energy * chem.H2Kcal, err +} + +// Gets previous line of the file f +func getTailLine(f *os.File) (line string, err error) { + var i int64 = 1 + buf := make([]byte, 1) + var ini int64 = -1 + for ; ; i++ { + //move the pointer back one byte per cycle + if _, err := f.Seek(-2, 1); err != nil { + return """", Error{err.Error(), Orca, ""Unknown"", """", []string{""os.File.Seek"", ""getTailLine""}, true} + } + if _, err := f.Read(buf); err != nil { + return """", Error{err.Error(), Orca, ""Unknown"", """", []string{""os.File.Read"", ""getTailLine""}, true} + } + if buf[0] == byte('\n') && ini == -1 { + ini = i + break + } + } + bufF := make([]byte, ini) + f.Read(bufF) + + if _, err := f.Seek(int64(-1*(len(bufF))), 1); err != nil { //making up for the read + return """", Error{err.Error(), Orca, ""Unknown"", """", []string{""os.File.Seek"", ""getTailLine""}, true} + + } + return string(bufF), nil +} + +// This checks that an ORCA calculation has terminated normally +// I know this duplicates code, I wrote this one first and then the other one. +func (O *OrcaHandle) orcaNormalTermination() bool { + var ini int64 = 0 + var end int64 = 0 + var first bool + buf := make([]byte, 1) + f, err := os.Open(fmt.Sprintf(""%s.out"", O.wrkdir+O.inputname)) + if err != nil { + return false + } + defer f.Close() + var i int64 = 1 + for ; ; i++ { + if _, err := f.Seek(-1*i, 2); err != nil { + return false + } + if _, err := f.Read(buf); err != nil { + return false + } + if buf[0] == byte('\n') && first == false { + first = true + } else if buf[0] == byte('\n') && end == 0 { + end = i + } else if buf[0] == byte('\n') && ini == 0 { + ini = i + break + } + + } + f.Seek(-1*ini, 2) + bufF := make([]byte, ini-end) + f.Read(bufF) + if strings.Contains(string(bufF), ""**ORCA TERMINATED NORMALLY**"") { + return true + } + return false +} + +// Options for COSMO-RS. The Option NullHBonds should set the contribution of H-Bonds to the free energy to 0, +// but I'm not at all sure it works. Use with care. +type COSMORSOptions struct { + T float64 + SolvMol *chem.Molecule + SolvName string + NullHBonds bool //This +} + +func DefaultCOSMORSOptions() *COSMORSOptions { + o := new(COSMORSOptions) + o.T = 298.15 + o.SolvName = ""water"" + o.NullHBonds = false + return o +} + +func (O *OrcaHandle) SetCOSMORS(coords *v3.Matrix, atoms chem.AtomMultiCharger, Options ...*COSMORSOptions) error { + var Op *COSMORSOptions + if len(Options) > 0 { + Op = Options[0] + } else { + Op = DefaultCOSMORSOptions() + } + + str := []string{""%cosmors\n""} + oldinput := O.inputname + O.inputname += ""_cosmors"" + if Op.SolvMol != nil { + solvstruc := ""solv.cosmorsxyz"" + fout, err := os.Create(solvstruc) + if err != nil { + return fmt.Errorf(""Couldn't create .cosmorsxyz file: %w"", err) + } + fout.WriteString(fmt.Sprintf(""%d\n%d %d\n"", Op.SolvMol.Len(), Op.SolvMol.Charge(), Op.SolvMol.Multi())) + for i := 0; i < Op.SolvMol.Len(); i++ { + at := Op.SolvMol.Atom(i) + coord := Op.SolvMol.Coords[0].VecView(i) + fout.WriteString(fmt.Sprintf(""%s %5.3f %5.3f %5.3f\n"", at.Symbol, coord.At(0, 0), coord.At(0, 1), coord.At(0, 2))) + } + fout.Close() + str = append(str, ""solventfilename \""solv\""\n"") + } else { + if Op.SolvName == """" { + return fmt.Errorf(""qm/Orca/SetCOSMORS: Neither solvent molecule nor name given!"") + } + str = append(str, fmt.Sprintf(""solvent \""%s\""\n"", Op.SolvName)) + } + if Op.T > 0 { + str = append(str, fmt.Sprintf(""temp %5.2f\n"", Op.T)) + } + if Op.NullHBonds { + str = append(str, ""sigmahb 10000\n"") //NOTE: The plan is to set the hbond threshold to a crazy high value so no hbond is detected. + } + str = append(str, ""end\n\n"") + + str = append(str, fmt.Sprintf(""* xyz %d %d\n"", atoms.Charge(), atoms.Multi())) + //now the coordinates + // fmt.Println(atoms.Len(), coords.Rows()) /////////////// + + for i := 0; i < atoms.Len(); i++ { + str = append(str, fmt.Sprintf(""%-2s %8.3f%8.3f%8.3f\n"", atoms.Atom(i).Symbol, coords.At(i, 0), coords.At(i, 1), coords.At(i, 2))) + } + str = append(str, ""*\n"") + cosmo, err := os.Create(O.wrkdir + O.inputname + "".inp"") + if err != nil { + return fmt.Errorf(""qm/Orca/SetCOSMORS: Couldn't create COSMO-RS input file: %w"", err) + } + defer cosmo.Close() + for _, v := range str { + cosmo.WriteString(v) + } + + O.inputname = oldinput + O.cosmorsready = true + return nil +} + +// Runs a previously set COSMO-RS calculation in ORCA, +func (O *OrcaHandle) DoCOSMORS() (float64, error) { + //NOTE: Some code from Energy() is repeated here, hopefully I'll abstract that part when I have some time. + oldinput := O.inputname + O.inputname += ""_cosmors"" + if !O.cosmorsready { + return -1, fmt.Errorf(""Orca/DoCOSMORS: COSMO-RS calculation has not been set"") + } + err := O.Run(true) + if err != nil { + return -1, fmt.Errorf(""Orca/DoCOSMORS:Failed to run COSMO-RS calculation: %w"", err) + } + + f, err1 := os.Open(fmt.Sprintf(""%s.out"", O.wrkdir+O.inputname)) + if err1 != nil { + return -1, fmt.Errorf(""Orca/DoCOSMORS: Can't open COSMO-RS output: %w"", err1) + } + defer f.Close() + f.Seek(-1, 2) //We start at the end of the file + energy := 0.0 + var found bool + templateline := ""Free energy of solvation (dGsolv) :"" + for i := 0; ; i++ { + line, err1 := getTailLine(f) + if err1 != nil { + return 0, fmt.Errorf(""Orca/DoCOSMORS: Error COSMO-RS output: %w"", err1) + + } + if strings.Contains(line, ""**ORCA TERMINATED NORMALLY**"") { + err = nil + } + if strings.Contains(line, templateline) { + splitted := strings.Fields(line) + energy, err1 = strconv.ParseFloat(splitted[8], 64) + if err1 != nil { + return 0.0, fmt.Errorf(""Orca/DoCOSMORS: Couldn't read deltaGSolv from output: %w"", err1) + } + found = true + break + } + } + if !found { + return 0.0, fmt.Errorf(""Orca/DoCOSMORS: Couldn't find deltaGSolv in output:"") + + } + + O.inputname = oldinput + return energy, err +} +","Go" +"Computational Biochemistry","rmera/gochem","qm/fermions.go",".go","11498","360","/* + * fermions.go, part of gochem. + * + * + * Copyright 2014 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + */ +//This functionality hasn't been tested for a while, so +//I can not ensure that it will work with current FermiONs++ +//versions. + +package qm + +import ( + ""fmt"" + ""log"" + ""os"" + ""os/exec"" + ""strconv"" + ""strings"" + + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" +) + +//A structure for handing FermiONs calculations +//Note that the default methods and basis vary with each program, and even +//for a given program they are NOT considered part of the API, so they can always change. +type FermionsHandle struct { + defmethod string + defbasis string + defauxbasis string + // previousMO string + // restart bool + // smartCosmo bool + command string + inputname string + nCPU int + gpu string + wrkdir string +} + +//NewFermionsHandle initializes and returns a FermionsHandle +func NewFermionsHandle() *FermionsHandle { + run := new(FermionsHandle) + run.SetDefaults() + return run +} + +//FermionsHandle methods + +//SetGPU sets GPU usage. Alternatives are ""cuda"" or ""opencl"" (alias ""ocl""). Anything else is ignored. GPU is off by default. +func (O *FermionsHandle) SetGPU(rawname string) { + name := strings.ToLower(rawname) + if name == ""cuda"" { + O.gpu = ""USE_CUDA YES\nCUDA_LINALG_MIN 500"" + } else if name == ""opencl"" || name == ""ocl"" { + O.gpu = ""USE_OCL YES\nOCL_LINALG_MIN 500"" //OpenCL is only for SCF energies!!!!! + } +} + +//SetName sets the name of the job, that will translate into the input and output files. +func (O *FermionsHandle) SetName(name string) { + O.inputname = name +} + +//SetCommand sets the name and/or path of the FermiONs++ excecutable +func (O *FermionsHandle) SetCommand(name string) { + O.command = name +} + +//SetWorkDir sets the name of the working directory for the Fermions calculations +func (O *FermionsHandle) SetWorkDir(d string) { + O.wrkdir = d +} + +//Sets defaults for Fermions++ calculation. Default is a single-point at +//revPBE/def2-SVP +func (O *FermionsHandle) SetDefaults() { + O.defmethod = ""revpbe"" + O.defbasis = ""def2-svp"" + O.command = ""qccalc"" + O.inputname = ""gochem"" + O.gpu = """" + +} + +//BuildInput builds an input for Fermions++ based int the data in atoms, coords and C. +//returns only error. +func (O *FermionsHandle) BuildInput(coords *v3.Matrix, atoms chem.AtomMultiCharger, Q *Calc) error { + //Only error so far + if O.wrkdir != """" { + O.wrkdir = O.wrkdir + ""/"" + } + if atoms == nil || coords == nil { + return Error{ErrMissingCharges, Fermions, O.inputname, """", []string{""BuildInput""}, true} + } + if Q.Basis == """" { + log.Printf(""no basis set assigned for Fermions++ calculation, will used the default %s, \n"", O.defbasis) + Q.Basis = O.defbasis + } + if Q.Method == """" { + log.Printf(""no method assigned for Fermions++ calculation, will used the default %s, \n"", O.defmethod) + Q.Method = O.defmethod + } + + disp, ok := fermionsDisp[strings.ToLower(Q.Dispersion)] + if !ok { + disp = ""disp_corr D3"" + } + + grid, ok := fermionsGrid[Q.Grid] + if !ok { + grid = ""M3"" + } + grid = fmt.Sprintf(""GRID_RAD_TYPE %s"", grid) + var err error + + m := strings.ToLower(Q.Method) + method, ok := fermionsMethods[m] + if !ok { + method = ""EXC XC_GGA_X_PBE_R\n ECORR XC_GGA_C_PBE"" + } + task := ""SinglePoint"" + dloptions := """" + jc := jobChoose{} + jc.opti = func() { + task = ""DLF_OPTIMIZE"" + dloptions = fmt.Sprintf(""*start::dlfind\n JOB std\n method l-bfgs\n trust_radius energy\n dcd %s.dcd\n maxcycle 300\n maxene 200\n coord_type cartesian\n*end\n"", O.inputname) + //Only cartesian constraints supported by now. + if len(Q.CConstraints) > 0 { + dloptions = fmt.Sprintf(""%s\n*start::dlf_constraints\n"", dloptions) + for _, v := range Q.CConstraints { + dloptions = fmt.Sprintf(""%s cart %d\n"", dloptions, v+1) //fortran numbering, starts with 1. + } + dloptions = fmt.Sprintf(""%s*end\n"", dloptions) + } + } + Q.Job.Do(jc) + cosmo := """" + if Q.Dielectric > 0 { + cosmo = fmt.Sprintf(""*start::solvate\n pcm_model cpcm\n epsilon %f\n cavity_model bondi\n*end\n"", Q.Dielectric) + } + + ////////////////////////////////////////////////////////////// + //Now lets write the thing. + ////////////////////////////////////////////////////////////// + file, err := os.Create(fmt.Sprintf(""%s%s.in"", O.wrkdir, O.inputname)) + if err != nil { + return Error{ErrCantInput, Fermions, O.inputname, err.Error(), []string{""os.Create"", ""BuildInput""}, true} + } + defer file.Close() + //Start with the geometry part (coords, charge and multiplicity) + fmt.Fprintf(file, ""*start::geo\n"") + fmt.Fprintf(file, ""%d %d\n"", atoms.Charge(), atoms.Multi()) + for i := 0; i < atoms.Len(); i++ { + fmt.Fprintf(file, ""%-2s %8.3f%8.3f%8.3f\n"", atoms.Atom(i).Symbol, coords.At(i, 0), coords.At(i, 1), coords.At(i, 2)) + } + fmt.Fprintf(file, ""*end\n\n"") + fmt.Fprintf(file, ""*start::sys\n"") + fmt.Fprintf(file, "" TODO %s\n"", task) + fmt.Fprintf(file, "" BASIS %s\n PC pure\n"", strings.ToLower(Q.Basis)) + fmt.Fprintf(file, "" %s\n"", method) + fmt.Fprintf(file, "" %s\n"", grid) + fmt.Fprintf(file, "" %s\n"", disp) + fmt.Fprintf(file, "" %s\n"", O.gpu) + if !Q.Job.Opti { + fmt.Fprintf(file, "" INFO 2\n"") + } + fmt.Fprintf(file, ""*end\n\n"") + fmt.Fprintf(file, ""%s\n"", cosmo) + fmt.Fprintf(file, ""%s\n"", dloptions) + return nil +} + +//Run runs the command given by the string O.command +//it waits or not for the result depending on wait. +//Not waiting for results works +//only for unix-compatible systems, as it uses bash and nohup. +func (O *FermionsHandle) Run(wait bool) (err error) { + if wait == true { + command := exec.Command(O.command, fmt.Sprintf(""%s.in"", O.inputname), fmt.Sprintf(""%s.out"", O.inputname)) + command.Dir = O.wrkdir + err = command.Run() + + } else { + //This will not work in windows. + command := exec.Command(""sh"", ""-c"", ""nohup ""+O.command+fmt.Sprintf("" %s.in > %s.out &"", O.inputname, O.inputname)) + command.Dir = O.wrkdir + err = command.Start() + } + if err != nil { + err = Error{ErrNotRunning, Fermions, O.inputname, err.Error(), []string{""exec.Start/Run"", ""Run""}, true} + + } + return err +} + +var fermionsDisp = map[string]string{ + """": """", + ""nodisp"": """", + ""d2"": ""disp_corr D2"", + ""d3bj"": ""disp_corr BJ"", + ""bj"": ""disp_corr BJ"", + ""d3"": ""disp_corr D3"", +} + +//M5 etc are not supported +var fermionsGrid = map[int]string{ + 1: ""M3"", + 2: ""M3"", + 3: ""M3"", + 4: ""M4"", + 5: ""M4"", +} + +//All meta-gga functionals here are buggy in the libxc library, and thus not reliable. I leave them hoping this will get fixed eventually. +var fermionsMethods = map[string]string{ + ""b3lyp"": ""EXC XC_HYB_GGA_XC_B3LYP\n ECORR XC_HYB_GGA_XC_B3LYP"", + ""b3-lyp"": ""EXC XC_HYB_GGA_XC_B3LYP\n ECORR XC_HYB_GGA_XC_B3LYP"", + ""pbe"": ""EXC XC_GGA_X_PBE\n ECORR XC_GGA_C_PBE"", + ""revpbe"": ""EXC XC_GGA_X_PBE_R\n ECORR XC_GGA_C_PBE"", + ""pbe0"": ""EXC XC_HYB_GGA_XC_PBEH\n ECORR XC_HYB_GGA_XC_PBEH"", + ""mpw1b95"": ""EXC XC_HYB_MGGA_XC_MPW1B95\n ECORR XC_HYB_MGGA_XC_MPW1B95"", //probably also buggy + ""tpss"": ""EXC XC_MGGA_X_TPSS\n ECORR XC_MGGA_C_TPSS"", //Buggy in current libxc, avoid. + ""bp86"": ""EXC XC_GGA_X_B88\n ECORR XC_GGA_C_P86"", + ""b-p"": ""EXC XC_GGA_X_B88\n ECORR XC_GGA_C_P86"", + ""blyp"": ""EXC XC_GGA_X_B88\n ECORR XC_GGA_C_LYP"", + ""b-lyp"": ""EXC XC_GGA_X_B88\n ECORR XC_GGA_C_LYP"", +} + +/* +//Reads the latest geometry from an Fermions++ optimization. Returns the +//geometry or error. +func (O *FermionsHandle) OptimizedGeometry(atoms chem.Ref) (*v3.Matrix, error) { + var err2 error + if !O.fermionsNormalTermination() { + return nil, fmt.Errorf(""Probable problem in calculation"") + } + //The following is kinda clumsy and should be replaced for a better thing which looks for + //the convergency signal instead of the not-convergency one. Right now I dont know + //what is that signal for FermiONs++. + if searchFromEnd(""NOT CONVERGED"",fmt.Sprintf(""%s.out"",O.inputname)){ + err2=fmt.Errorf(""Probable problem in calculation"") + } + trj,err:=dcd.New(fmt.Sprintf(""%s.dcd"",O.inputname)) + if err!=nil{ + return nil, fmt.Errorf(""Probable problem in calculation %"", err) + } + ret := chem.v3.Zeros(trj.Len()) + for { + err := trj.Next(ret) + if err != nil && err.Error() != ""No more frames"" { + return nil, fmt.Errorf(""Probable problem in calculation %"", err) + } else { + break + } + + } + return ret, err2 + + +} + +*/ + +//Energy the energy of a previously completed Fermions++ calculation. +//Returns error if problem, and also if the energy returned that is product of an +//abnormally-terminated Fermions++ calculation. (in this case error is ""Probable problem +//in calculation"") +func (O *FermionsHandle) Energy() (float64, error) { + var err error + inp := O.wrkdir + O.inputname + err = Error{ErrProbableProblem, Fermions, inp, """", []string{""Energy""}, false} + f, err1 := os.Open(fmt.Sprintf(""%s.out"", inp)) + if err1 != nil { + return 0, Error{ErrNoEnergy, Fermions, inp, err1.Error(), []string{""os.Open"", ""Energy""}, true} + } + defer f.Close() + f.Seek(-1, 2) //We start at the end of the file + energy := 0.0 + var found bool + for i := 0; ; i++ { + line, err1 := getTailLine(f) + if err1 != nil { + return 0.0, Error{ErrNoEnergy, Fermions, inp, err1.Error(), []string{""os.File.Seek"", ""Energy""}, true} + } + if strings.Contains(line, ""Timing report"") { + err = nil + } + if strings.Contains(line, "" * Free energy: "") { + splitted := strings.Fields(line) + energy, err1 = strconv.ParseFloat(splitted[len(splitted)-3], 64) + if err1 != nil { + return 0.0, Error{ErrNoEnergy, Fermions, inp, err1.Error(), []string{""strconv.ParseFloat"", ""Energy""}, true} + } + found = true + break + } + } + if !found { + return 0.0, Error{ErrNoEnergy, Fermions, inp, """", []string{""Energy""}, true} + } + return energy * chem.H2Kcal, err +} + +//This checks that an Fermions++ calculation has terminated normally +//Notice that this function will succeed whenever FermiONs++ exists +//correctly. In the case of a geometry optimization, this DOES NOT +//mean that the optimization converged (as opposed to, the NWChem +//interface, whose the equivalent function will return true ONLY +//if the optimization converged) +func (O *FermionsHandle) fermionsNormalTermination() bool { + return searchFromEnd(""Timing report"", fmt.Sprintf(""%s.out"", O.wrkdir+O.inputname)) +} + +//This will return true if the templa string is present in the file filename +//which is seached from the end. +func searchFromEnd(templa, filename string) bool { + ret := false + f, err1 := os.Open(filename) + if err1 != nil { + return false + } + defer f.Close() + f.Seek(-1, 2) //We start at the end of the file + for i := 0; ; i++ { + line, err1 := getTailLine(f) + if err1 != nil { + return false + } + if strings.Contains(line, templa) { + ret = true + break + } + } + return ret +} + +//OptimizedGeometry does nothing and returns nil for both values. +// It is there for compatibility but it represents unimplemented functionality. +func (O *FermionsHandle) OptimizedGeometry(atoms chem.Atomer) (*v3.Matrix, error) { + return nil, nil +} +","Go" +"Computational Biochemistry","rmera/gochem","qm/nwchem.go",".go","22049","640","/* + * nwchem.go, part of gochem. + * + * + * Copyright 2013 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + */ + +package qm + +import ( + ""bufio"" + ""fmt"" + ""log"" + ""os"" + ""os/exec"" + ""runtime"" + ""strconv"" + ""strings"" + + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" +) + +// NWChemHandle represents an NWChem calculation. +// Note that the default methods and basis vary with each program, and even +// for a given program they are NOT considered part of the API, so they can always change. +type NWChemHandle struct { + defmethod string + defbasis string + defauxbasis string + previousMO string + restart bool + smartCosmo bool + command string + inputname string + nCPU int + wrkdir string +} + +// Initializes and returns a NWChem handle +func NewNWChemHandle() *NWChemHandle { + run := new(NWChemHandle) + run.SetDefaults() + return run +} + +//NWChemHandle methods + +// SetnCPU sets the number of CPU to be used +func (O *NWChemHandle) SetnCPU(cpu int) { + O.nCPU = cpu +} + +// SetRestart sets whether the calculation is a restart +// of a previous one. +func (O *NWChemHandle) SetRestart(r bool) { + O.restart = r +} + +// SetName sets the name for the job, reflected in the input and +// output files. +func (O *NWChemHandle) SetName(name string) { + O.inputname = name +} + +// SetCommand sets the name/path of the MOPAC excecutable +func (O *NWChemHandle) SetCommand(name string) { + O.command = name +} + +// SetWorkDir sets the working directory for the calculation +func (O *NWChemHandle) SetWorkDir(d string) { + O.wrkdir = d +} + +// SetMOName sets the name of a file containing orbitals which will be used as a guess for this calculations +func (O *NWChemHandle) SetMOName(name string) { + O.previousMO = name +} + +// SetsSmartCosmo sets the behaviour of NWChem regarding COSMO. +// For an optimization, a true value causes NBWChem to first calculate an SCF with do_gasphase True and use THAT density guess +// for the first optimization step. The optimization is done with do_gasphase False. +// for a SP, smartCosmo simply means do_gasphase False. +// Notice that SmartCosmo is not reallty too smart, for optimizations. In my tests, it doesn't really +// make things better. I keep it mostly just in case. +func (O *NWChemHandle) SetSmartCosmo(set bool) { + O.smartCosmo = set +} + +// SetDefaults sets the NWChem calculation to goChem's default values (_not_ considered part of the API!) +// As of now, default is a single-point at +// TPSS/def2-SVP with RI, and half the logical CPUs available (to account for the multithreading common on Intel CPUs) +func (O *NWChemHandle) SetDefaults() { + O.defmethod = ""tpss"" + O.defbasis = ""def2-svp"" + O.command = ""nwchem"" + O.smartCosmo = false + cpu := runtime.NumCPU() / 2 //we divide by 2 because of the hyperthreading that is so frequent nowadays. + O.nCPU = cpu + +} + +// BuildInput builds an input for NWChem based int the data in atoms, coords and C. +// returns only error. +func (O *NWChemHandle) BuildInput(coords *v3.Matrix, atoms chem.AtomMultiCharger, Q *Calc) error { + //Only error so far + if atoms == nil || coords == nil { + return Error{ErrMissingCharges, NWChem, O.inputname, """", []string{""BuildInput""}, true} + } + if Q.Basis == """" { + log.Printf(""no basis set assigned for NWChem calculation, will use the default %s, \n"", O.defbasis) + Q.Basis = O.defbasis + } + if Q.Method == """" { + log.Printf(""no method assigned for NWChem calculation, will use the default %s, \n"", O.defmethod) + Q.Method = O.defmethod + Q.RI = true + } + if O.inputname == """" { + O.inputname = ""gochem"" + } + if O.wrkdir != """" { + O.wrkdir = O.wrkdir + ""/"" + } + //The initial guess + vectors := fmt.Sprintf(""output %s.movecs"", O.inputname) //The initial guess + switch Q.Guess { + case """": + case ""hcore"": //This option is not a great idea, apparently. + vectors = fmt.Sprintf(""input hcore %s"", vectors) + default: + if !Q.OldMO { + //If the user gives something in Q.Guess but DOES NOT want an old MO to be used, I assume he/she wants to put whatever + //is in Q.Guess directly in the vector keyword. If you want the default put an empty string in Q.Guess. + vectors = fmt.Sprintf(""%s %s"", Q.Guess, vectors) + break + } + //I assume the user gave a basis set name in Q.Guess which I can use to project vectors from a previous run. + moname := getOldMO(O.previousMO) + if moname == """" { + break + } + if strings.ToLower(Q.Guess) == strings.ToLower(Q.Basis) { + //Useful if you only change functionals. + vectors = fmt.Sprintf(""input %s %s"", moname, vectors) + } else { + //This will NOT work if one assigns different basis sets to different atoms. + vectors = fmt.Sprintf(""input project %s %s %s"", strings.ToLower(Q.Guess), moname, vectors) + } + } + vectors = ""vectors "" + vectors + + disp, ok := nwchemDisp[Q.Dispersion] + if !ok { + disp = ""vdw 3"" + } + tightness := """" + switch Q.SCFTightness { + case 1: + tightness = ""convergence energy 5.000000E-08\n convergence density 5.000000E-09\n convergence gradient 1E-05"" + case 2: + //NO idea if this will work, or the criteria will be stronger than the criteria for the intergral evaluation + //and thus the SCF will never converge. Delete when properly tested. + tightness = ""convergence energy 1.000000E-10\n convergence density 5.000000E-11\n convergence gradient 1E-07"" + } + + //For now, the only convergence help I trust is to run a little HF calculation before and use the orbitals as a guess. + //It works quite nicely. When the NWChem people get their shit together and fix the bugs with cgmin and RI and cgmin and + //COSMO, cgmin will be a great option also. + scfiters := ""iterations 60"" + prevscf := """" + if Q.SCFConvHelp > 0 { + scfiters = ""iterations 200"" + if Q.Guess == """" { + prevscf = fmt.Sprintf(""\nbasis \""3-21g\""\n * library 3-21g\nend\nset \""ao basis\"" 3-21g\nscf\n maxiter 200\n vectors output hf.movecs\n %s\nend\ntask scf energy\n\n"", strings.ToLower(mopacMultiplicity[atoms.Multi()])) + vectors = fmt.Sprintf(""vectors input project \""3-21g\"" hf.movecs output %s.movecs"", O.inputname) + } + } + grid, ok := nwchemGrid[Q.Grid] + if !ok { + grid = ""medium"" + } + if Q.SCFTightness > 0 { //We need this if we want the SCF to converge. + grid = ""xfine"" + } + grid = fmt.Sprintf(""grid %s"", grid) + var err error + + //Only cartesian constraints supported by now. + constraints := """" + if len(Q.CConstraints) > 0 { + constraints = ""constraints\n fix atom"" + for _, v := range Q.CConstraints { + constraints = fmt.Sprintf(""%s %d"", constraints, v+1) //goChem numbering starts from 0, apparently NWChem starts from 1, hence the v+1 + } + constraints = constraints + ""\nend"" + } + + cosmo := """" + if Q.Dielectric > 0 { + //SmartCosmo in a single-point means that do_gasphase False is used, nothing fancy. + if Q.Job.Opti || O.smartCosmo { + cosmo = fmt.Sprintf(""cosmo\n dielec %4.1f\n do_gasphase False\nend"", Q.Dielectric) + } else { + cosmo = fmt.Sprintf(""cosmo\n dielec %4.1f\n do_gasphase True\nend"", Q.Dielectric) + } + } + memory := """" + if Q.Memory != 0 { + memory = fmt.Sprintf(""memory total %d mb"", Q.Memory) + } + m := strings.ToLower(Q.Method) + method, ok := nwchemMethods[m] + if !ok { + method = ""xtpss03 ctpss03"" + } + method = fmt.Sprintf(""xc %s"", method) + + task := ""dft energy"" + driver := """" + preopt := """" + esp := """" + jc := jobChoose{} + jc.charges = func() { + esp = ""esp\n restrain\nend\n"" + task = task + ""\ntask esp"" + } + jc.opti = func() { + eprec := """" //The available presition is set to default except if tighter SCF convergene criteria are being used. + if Q.SCFTightness > 0 { + eprec = "" eprec 1E-7\n"" + } + if Q.Dielectric > 0 && O.smartCosmo { + //If COSMO is used, and O.SmartCosmo is enabled, we start the optimization with a rather loose SCF (the default). + //and use that denisty as a starting point for the next calculation. The idea is to + //avoid the gas phase calculation in COSMO. + //This procedure doesn't seem to help at all, and just using do_gasphase False appears to be good enough in my tests. + preopt = fmt.Sprintf(""cosmo\n dielec %4.1f\n do_gasphase True\nend\n"", Q.Dielectric) + preopt = fmt.Sprintf(""%sdft\n iterations 100\n %s\n %s\n print low\nend\ntask dft energy\n"", preopt, vectors, method) + vectors = fmt.Sprintf(""vectors input %s.movecs output %s.movecs"", O.inputname, O.inputname) //We must modify the initial guess so we use the vectors we have just generated + } + //We use this 3-step optimization scheme where we try to compensate for the lack of + //variable trust radius in nwchem (at least, back when I wrote this!) + task = ""dft optimize"" + //First an optimization with very loose convergency and a small trust radius. + driver = fmt.Sprintf(""driver\n maxiter 200\n%s trust 0.05\n gmax 0.0500\n grms 0.0300\n xmax 0.1800\n xrms 0.1200\n xyz %s_prev\nend\ntask dft optimize"", eprec, O.inputname) + //Then a second optimization with a less loose convergency and a 0.1 trust radius + driver = fmt.Sprintf(""%s\ndriver\n maxiter 200\n%s trust 0.1\n gmax 0.009\n grms 0.001\n xmax 0.04 \n xrms 0.02\n xyz %s_prev2\nend\ntask dft optimize"", driver, eprec, O.inputname) + //Then the final optimization with the default trust radius and convergence criteria. + driver = fmt.Sprintf(""%s\ndriver\n maxiter 200\n%s trust 0.3\n xyz %s\nend\n"", driver, eprec, O.inputname) + //Old criteria (ORCA): gmax 0.003\n grms 0.0001\n xmax 0.004 \n xrms 0.002\n + } + Q.Job.Do(jc) + ////////////////////////////////////////////////////////////// + //Now lets write the thing. Ill process/write the basis later + ////////////////////////////////////////////////////////////// + file, err := os.Create(fmt.Sprintf(""%s.nw"", O.wrkdir+O.inputname)) + if err != nil { + return Error{err.Error(), NWChem, O.wrkdir + O.inputname, """", []string{""os.Create"", ""BuildInput""}, true} + + } + defer file.Close() + start := ""start"" + if O.restart { + start = ""restart"" + } + + _, err = fmt.Fprintf(file, ""%s %s\n"", start, O.inputname) + //after this check its assumed that the file is ok. + if err != nil { + return Error{err.Error(), NWChem, O.inputname, """", []string{""fmt.Fprintf"", ""BuildInput""}, true} + } + fmt.Fprint(file, ""echo\n"") //echo input in the output. + fmt.Fprintf(file, ""charge %d\n"", atoms.Charge()) + if memory != """" { + fmt.Fprintf(file, ""%s\n"", memory) //the memory + } + //Now the geometry: + //If we have cartesian constraints we give the directive noautoz to optimize in cartesian coordinates. + autoz := """" + if len(Q.CConstraints) > 0 { + autoz = ""noautoz"" + } + fmt.Fprintf(file, ""geometry units angstroms noautosym %s\n"", autoz) + elements := make([]string, 0, 5) //I will collect the different elements that are in the molecule using the same loop as the geometry. + for i := 0; i < atoms.Len(); i++ { + symbol := atoms.Atom(i).Symbol + //In the following if/else I try to set up basis for specific atoms. Not SO sure it works. + if isInInt(Q.HBAtoms, i) { + symbol = symbol + ""1"" + } else if isInInt(Q.LBAtoms, i) { + symbol = symbol + ""2"" + } + fmt.Fprintf(file, "" %-2s %8.3f%8.3f%8.3f \n"", symbol, coords.At(i, 0), coords.At(i, 1), coords.At(i, 2)) + + if !isInString(elements, symbol) { + elements = append(elements, symbol) + } + } + fmt.Fprintf(file, ""end\n"") + fmt.Fprintf(file, prevscf) //The preeliminar SCF if exists. + //The basis. First the ao basis (required) + decap := strings.ToLower //hoping to make the next for loop less ugly + basis := make([]string, 1, 2) + basis[0] = ""\""ao basis\"""" + fmt.Fprintf(file, ""basis \""large\"" spherical\n"") //According to the manual this fails with COSMO. The calculations dont crash. Need to compare energies and geometries with Turbomole in order to be sure. + for _, el := range elements { + if isInString(Q.HBElements, el) || strings.HasSuffix(el, ""1"") { + fmt.Fprintf(file, "" %-2s library %s\n"", el, decap(Q.HighBasis)) + } else if isInString(Q.LBElements, el) || strings.HasSuffix(el, ""2"") { + fmt.Fprintf(file, "" %-2s library %s\n"", el, decap(Q.LowBasis)) + } else { + fmt.Fprintf(file, "" %-2s library %s\n"", el, decap(Q.Basis)) + } + } + fmt.Fprintf(file, ""end\n"") + fmt.Fprintf(file, ""set \""ao basis\"" large\n"") + //Only Ahlrichs basis are supported for RI. USE AHLRICHS BASIS, PERKELE! :-) + //The only Ahlrichs J basis in NWchem appear to be equivalent to def2-TZVPP/J (orca nomenclature). I suppose that they are still faster + //than not using RI if the main basis is SVP. One can also hope that they are good enough if the main basis is QZVPP or something. + //(about the last point, it appears that in Turbomole, the aux basis also go up to TZVPP). + //This comment is based on the H, Be and C basis. + if Q.RI { + fmt.Fprint(file, ""basis \""cd basis\""\n * library \""Ahlrichs Coulomb Fitting\""\nend\n"") + } + //Now the geometry constraints. I kind of assume they are + if constraints != """" { + fmt.Fprintf(file, ""%s\n"", constraints) + } + fmt.Fprintf(file, preopt) + if cosmo != """" { + fmt.Fprintf(file, ""%s\n"", cosmo) + } + //The DFT block + fmt.Fprint(file, ""dft\n"") + fmt.Fprintf(file, "" %s\n"", vectors) + fmt.Fprintf(file, "" %s\n"", scfiters) + if tightness != """" { + fmt.Fprintf(file, "" %s\n"", tightness) + } + fmt.Fprintf(file, "" %s\n"", grid) + fmt.Fprintf(file, "" %s\n"", method) + if disp != """" { + fmt.Fprintf(file, "" disp %s\n"", disp) + } + if Q.Job.Opti { + fmt.Fprintf(file, "" print convergence\n"") + } + //task part + fmt.Fprintf(file, "" mult %d\n"", atoms.Multi()) + fmt.Fprint(file, ""end\n"") + if Q.Job.Charges { + fmt.Fprintf(file, esp) + } + fmt.Fprintf(file, ""%s"", driver) + fmt.Fprintf(file, ""task %s\n"", task) + + return nil +} + +// Run runs the command given by the string O.command +// it waits or not for the result depending on wait. +// Not waiting for results works +// only for unix-compatible systems, as it uses bash and nohup. +func (O *NWChemHandle) Run(wait bool) (err error) { + if wait == true { + out, err := os.Create(fmt.Sprintf(""%s.out"", O.wrkdir+O.inputname)) + if err != nil { + return Error{ErrNotRunning, NWChem, O.wrkdir + O.inputname, err.Error(), []string{""os.Create"", ""Run""}, true} + + } + defer out.Close() + command := exec.Command(O.command, fmt.Sprintf(""%s.nw"", O.inputname)) + // if O.nCPU > 1 { + // fmt.Println(""mpirun"", ""-np"", fmt.Sprintf(""%d"", O.nCPU), O.command, fmt.Sprintf(""%s.nw"", O.inputname)) //////////////////////////// + // command = exec.Command(""mpirun"", ""-np"", fmt.Sprintf(""%d"", O.nCPU), O.command, fmt.Sprintf(""%s.nw"", O.inputname)) + // } + command.Dir = O.wrkdir + command.Stdout = out + command.Stderr = out + err = command.Run() + + } else { + //This will not work in windows. + command := exec.Command(""sh"", ""-c"", ""nohup ""+O.command+fmt.Sprintf("" %s.nw > %s.out &"", O.inputname, O.inputname)) + command.Dir = O.wrkdir + err = command.Start() + } + if err != nil { + err = Error{ErrNotRunning, Mopac, O.inputname, err.Error(), []string{""exec.command.Start/Run"", ""Run""}, true} + } + return err +} + +func getOldMO(prevMO string) string { + dir, _ := os.Open(""./"") //This should always work, hence ignoring the error + files, _ := dir.Readdir(-1) //Get all the files. + for _, val := range files { + if prevMO != """" { + break + } + if val.IsDir() == true { + continue + } + name := val.Name() + if strings.Contains("".movecs"", name) { + prevMO = name + break + } + } + if prevMO != """" { + return prevMO + } else { + return """" + + } +} + +var nwchemDisp = map[string]string{ + ""nodisp"": """", + ""D2"": ""vdw 2"", + ""D3"": ""vdw 3"", + ""D3ZERO"": ""vdw 3"", + ""D3Zero"": ""vdw 3"", + ""D3zero"": ""vdw 3"", +} + +var nwchemGrid = map[int]string{ + 1: ""xcoarse"", + 2: ""coarse"", + 3: ""medium"", + 4: ""fine"", + 5: ""xfine"", +} + +var nwchemMethods = map[string]string{ + ""b3lyp"": ""b3lyp"", + ""b3-lyp"": ""b3lyp"", + ""pbe0"": ""pbe0"", + ""mpw1b95"": ""mpw1b95"", + ""revpbe"": ""revpbe cpbe96"", + ""TPSS"": ""xtpss03 ctpss03"", + ""tpss"": ""xtpss03 ctpss03"", + ""TPSSh"": ""xctpssh"", + ""tpssh"": ""xctpssh"", + ""bp86"": ""becke88 perdew86"", + ""b-p"": ""becke88 perdew86"", + ""blyp"": ""becke88 lyp"", +} + +// OptimizedGeometry returns the latest geometry from an NWChem optimization. Returns the +// geometry or error. Returns the geometry AND error if the geometry read +// is not the product of a correctly ended NWChem calculation. In this case +// the error is ""probable problem in calculation"". +func (O *NWChemHandle) OptimizedGeometry(atoms chem.Atomer) (*v3.Matrix, error) { + var err2 error + lastnumber := 0 + lastname := """" + if !O.nwchemNormalTermination() { + err2 = Error{ErrProbableProblem, NWChem, O.inputname, """", []string{""OptimizedGeometry""}, false} + } + dir, err := os.Open(O.wrkdir) + if err != nil { + return nil, Error{ErrNoGeometry, NWChem, O.inputname, err.Error(), []string{""os.Open"", ""OptimizedGeometry""}, true} + } + files, err := dir.Readdirnames(-1) + if err != nil { + return nil, Error{ErrNoGeometry, NWChem, O.inputname, err.Error(), []string{""os.Readdirnames"", ""OptimizedGeometry""}, true} + } + //This is a crappy sort/filter, but really, it will never be the bottleneck. + //We go over the dir content and look for xyz files with the name of the input and without + // the susbstring _prev. Among these, we choose the file with the largest number in the filename + //(which will be the latest geometry written) and return that geometry. + for _, v := range files { + //quite ugly, feel free to fix. + if !(strings.Contains(v, O.inputname) && strings.Contains(v, "".xyz"") && !strings.Contains(v, ""_prev"")) { + continue + } + numbers := strings.Split(strings.Replace(v, "".xyz"", """", 1), ""-"") + ndx, err := strconv.Atoi(numbers[len(numbers)-1]) + if err != nil { + continue + } + if ndx >= lastnumber { + lastnumber = ndx + lastname = v + } + } + if lastname == """" { + return nil, Error{ErrNoGeometry, NWChem, O.inputname, """", []string{""OptimizedGeometry""}, true} + } + mol, err := chem.XYZFileRead(O.wrkdir + lastname) + if err != nil { + return nil, errDecorate(err, ""qm.OptimizedGeometry ""+"" ""+NWChem+"" ""+O.inputname+"" ""+ErrNoGeometry) + } + return mol.Coords[0], err2 +} + +// Energy returns the energy of a previous NWChem calculation. +// Returns error if problem, and also if the energy returned that is product of an +// abnormally-terminated NWChem calculation. (in this case error is ""Probable problem +// in calculation"") +func (O *NWChemHandle) Energy() (float64, error) { + var err error + err = Error{ErrProbableProblem, NWChem, O.inputname, """", []string{""Energy""}, false} + f, err1 := os.Open(fmt.Sprintf(""%s.out"", O.wrkdir+O.inputname)) + if err1 != nil { + return 0, Error{ErrNoEnergy, NWChem, O.inputname, err1.Error(), []string{""os.Open"", ""Energy""}, true} + } + defer f.Close() + f.Seek(-1, 2) //We start at the end of the file + energy := 0.0 + var found bool + for i := 0; ; i++ { + line, err1 := getTailLine(f) + if err1 != nil { + return 0.0, errDecorate(err1, ""qm.Energy ""+NWChem) + } + if strings.Contains(line, ""CITATION"") { + err = nil + } + if strings.Contains(line, ""Total DFT energy"") { + splitted := strings.Fields(line) + energy, err1 = strconv.ParseFloat(splitted[len(splitted)-1], 64) + if err1 != nil { + return 0.0, Error{ErrNoEnergy, NWChem, O.inputname, err1.Error(), []string{""strconv.ParseFloat"", ""Energy""}, true} + + } + found = true + break + } + } + if !found { + return 0.0, Error{ErrNoEnergy, NWChem, O.inputname, """", []string{""Energy""}, true} + + } + return energy * chem.H2Kcal, err +} + +func (O *NWChemHandle) move2lines(fin *bufio.Reader) error { + _, err := fin.ReadString('\n') + if err != nil { + return Error{ErrNoEnergy, NWChem, O.inputname, err.Error(), []string{""os.Open"", ""Charges""}, true} + } + _, err = fin.ReadString('\n') + if err != nil { + return Error{ErrNoEnergy, NWChem, O.inputname, err.Error(), []string{""os.Open"", ""Charges""}, true} + } + return nil +} + +// Charges returns the RESP charges from a previous NWChem calculation. +func (O *NWChemHandle) Charges() ([]float64, error) { + f, err1 := os.Open(fmt.Sprintf(""%s.out"", O.wrkdir+O.inputname)) + if err1 != nil { + return nil, Error{ErrNoCharges, NWChem, O.inputname, err1.Error(), []string{""os.Open"", ""Charges""}, true} + } + charges := make([]float64, 0, 30) + var reading bool = false + defer f.Close() + fin := bufio.NewReader(f) + for { + + line, err := fin.ReadString('\n') + if err != nil { + if strings.Contains(err.Error(), ""EOF"") { //This allows that an XYZ ends without a newline + break + } else { + return nil, Error{ErrNoCharges, NWChem, O.inputname, err.Error(), []string{""os.Open"", ""Charges""}, true} + } + } + if strings.Contains(line, ""ESP RESP RESP2"") { + reading = true + err := O.move2lines(fin) + if err != nil { + return nil, err + } + continue + } + if !reading { + continue + } + if reading && strings.Contains(line, ""------------------------------------"") { + break + } + fields := strings.Fields(line) + if len(fields) < 7 { + return nil, Error{ErrNoCharges, NWChem, O.inputname, """", []string{""os.Open"", ""Charges""}, true} + } + charge, err := strconv.ParseFloat(fields[len(fields)-2], 64) + if err != nil { + return nil, Error{ErrNoCharges, NWChem, O.inputname, err.Error(), []string{""os.Open"", ""Charges""}, true} + } + charges = append(charges, charge) + + } + + return charges, nil +} + +// This checks that an NWChem calculation has terminated normally +// I know this duplicates code, I wrote this one first and then the other one. +func (O *NWChemHandle) nwchemNormalTermination() bool { + ret := false + f, err1 := os.Open(fmt.Sprintf(""%s.out"", O.wrkdir+O.inputname)) + if err1 != nil { + return false + } + defer f.Close() + f.Seek(-1, 2) //We start at the end of the file + for i := 0; ; i++ { + line, err1 := getTailLine(f) + if err1 != nil { + return false + } + if strings.Contains(line, ""CITATION"") { + ret = true + break + } + } + return ret +} +","Go" +"Computational Biochemistry","rmera/gochem","qm/mopac.go",".go","9752","317","/* + * mopac.go, part of gochem. + * + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + */ + +package qm + +import ( + ""bufio"" + ""fmt"" + ""log"" + ""os"" + ""os/exec"" + ""strconv"" + ""strings"" + + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" +) + +//MopacHandle represents a MOPAC calculations +type MopacHandle struct { + defmethod string + command string + inputname string + wrkdir string +} + +//NewMopacHandle creates and initializes a new MopacHandle, with values set +//to its defaults. +func NewMopacHandle() *MopacHandle { + run := new(MopacHandle) + run.SetDefaults() + return run +} + +//MopacHandle methods + +//SetName sets the name for the job, used for input +//and output files (ex. input will be name.inp). +func (O *MopacHandle) SetName(name string) { + O.inputname = name +} + +//SetCommand sets the command to run the MOPAC program. +func (O *MopacHandle) SetCommand(name string) { + O.command = name +} + +/*Sets some defaults for MopacHandle. default is an optimization at + PM6-DH2X It tries to locate MOPAC2012 according to the + $MOPAC_LICENSE environment variable, which might only work in UNIX. + If other system or using MOPAC2009 the command Must be set with the + SetCommand function. */ +func (O *MopacHandle) SetDefaults() { + O.defmethod = ""PM6-D3H4 NOMM"" + O.command = os.ExpandEnv(""${MOPAC_LICENSE}/MOPAC2016.exe"") +} + +func (O *MopacHandle) SetWorkDir(d string) { + O.wrkdir = d +} + +//BuildInput builds an input for ORCA based int the data in atoms, coords and C. +//returns only error. +func (O *MopacHandle) BuildInput(coords *v3.Matrix, atoms chem.AtomMultiCharger, Q *Calc) error { + if O.wrkdir != """" { + O.wrkdir = O.wrkdir + ""/"" + } + if strings.Contains(Q.Others, ""RI"") { + Q.Others = """" + } + //Only error so far + if atoms == nil || coords == nil { + return Error{ErrMissingCharges, Mopac, O.inputname, """", []string{""BuildInput""}, true} + } + ValidMethods := []string{""PM3"", ""PM6"", ""PM7"", ""AM1""} + if Q.Method == """" || !isInString(ValidMethods, Q.Method[0:3]) { //not found + log.Printf(""no method assigned for MOPAC calculation, will used the default %s, \n"", O.defmethod) + Q.Method = O.defmethod + } + opt := """" //Empty string means optimize + jc := jobChoose{} + jc.sp = func() { + opt = ""1SCF"" + } + jc.opti = func() {} + Q.Job.Do(jc) + //If this flag is set we'll look for a suitable MO file. + //If not found, we'll just use the default ORCA guess + hfuhf := ""RHF"" + if atoms.Multi() != 1 { + hfuhf = ""UHF"" + } + cosmo := """" + if Q.Dielectric > 0 { + cosmo = fmt.Sprintf(""EPS=%2.1f RSOLV=1.3 LET DDMIN=0.0"", Q.Dielectric) //The DDMIN ensures that the optimization continues when cosmo is used. From the manual I understand that it is OK + } + strict := """" + if Q.SCFTightness > 0 { + strict = ""GNORM=0.01 RELSCF=0.00001"" + } + multi := mopacMultiplicity[atoms.Multi()] + charge := fmt.Sprintf(""CHARGE=%d"", atoms.Charge()) + MainOptions := []string{hfuhf, Q.Method, strict, opt, cosmo, charge, multi, Q.Others, ""BONDS AUX\n""} + mainline := strings.Join(MainOptions, "" "") + //Now lets write the thing + if O.inputname == """" { + O.inputname = ""input"" + } + file, err := os.Create(fmt.Sprintf(""%s.mop"", O.wrkdir+O.inputname)) + if err != nil { + return Error{ErrCantInput, Mopac, O.inputname, """", []string{""os.Create"", ""BuildInput""}, true} + + } + defer file.Close() + if _, err = fmt.Fprint(file, ""* ===============================\n* Input file for Mopac\n* ===============================\n""); err != nil { + return Error{ErrCantInput, Mopac, O.inputname, """", []string{""BuildInput""}, true} + //After this check I just assume the file is ok and dont check again. + } + fmt.Fprint(file, mainline) + fmt.Fprint(file, ""\n"") + fmt.Fprint(file, ""Mopac file generated by gochem :-)\n"") + //now the coordinates + for i := 0; i < atoms.Len(); i++ { + tag := 1 + if isInInt(Q.CConstraints, i) { + tag = 0 + } + // fmt.Println(atoms.Atom(i).Symbol) + fmt.Fprintf(file, ""%-2s %8.5f %d %8.5f %d %8.5f %d\n"", atoms.Atom(i).Symbol, coords.At(i, 0), tag, coords.At(i, 1), tag, coords.At(i, 2), tag) + } + fmt.Fprintf(file, ""\n"") + return nil +} + +var mopacMultiplicity = map[int]string{ + 1: ""Singlet"", + 2: ""Doublet"", + 3: ""Triplet"", + 4: ""Quartet"", + 5: ""Quintet"", //I don't think we reaaally need these ones :-) + 6: ""Sextet"", + 7: ""Heptet"", + 8: ""Octet"", + 9: ""Nonet"", +} + +//Run runs the command given by the string O.command +//it waits or not for the result depending on wait. Not waiting for results works +//only for unix-compatible systems, as it uses bash and nohup. +func (O *MopacHandle) Run(wait bool) (err error) { + if wait == true { + command := exec.Command(O.command, fmt.Sprintf(""%s.mop"", O.inputname)) + command.Dir = O.wrkdir + err = command.Run() + } else { + command := exec.Command(""sh"", ""-c"", ""nohup ""+O.command+fmt.Sprintf("" %s.mop &"", O.inputname)) + command.Dir = O.wrkdir + err = command.Start() + } + if err != nil { + err = Error{ErrNotRunning, Mopac, O.inputname, err.Error(), []string{""exec.Start/Run"", ""Run""}, true} + } + return +} + +//Energy gets the last energy for a MOPAC2009/2012 calculation by +//parsing the mopac output file. Return error if fail. Also returns +//Error (""Probable problem in calculation"") +//if there is a energy but the calculation didnt end properly +func (O *MopacHandle) Energy() (float64, error) { + var err error + inp := O.wrkdir + O.inputname + var energy float64 + file, err := os.Open(fmt.Sprintf(""%s.out"", inp)) + if err != nil { + return 0, Error{ErrNoEnergy, Mopac, inp, err.Error(), []string{""os.Open"", ""Energy""}, true} + } + defer file.Close() + out := bufio.NewReader(file) + err = Error{ErrNoEnergy, Mopac, inp, """", []string{""Energy""}, true} + trust_radius_warning := false + for { + var line string + line, err = out.ReadString('\n') + if err != nil { + break + } + if strings.Contains(line, ""TRUST RADIUS NOW LESS THAN 0.00010 OPTIMIZATION TERMINATING"") { + trust_radius_warning = true + continue + } + if strings.Contains(line, ""TOTAL ENERGY"") { + splitted := strings.Fields(line) + if len(splitted) < 4 { + err = Error{ErrNoEnergy, Mopac, inp, """", []string{""Energy""}, true} + break + } + energy, err = strconv.ParseFloat(splitted[3], 64) + if err != nil { + break + } + energy = energy * chem.EV2Kcal + err = nil + break + } + } + if err != nil { + return 0, err + } + if trust_radius_warning { + err = Error{ErrProbableProblem, Mopac, inp, """", []string{""Energy""}, false} + } + return energy, err +} + +//OptimizeGeometry reads the optimized geometry from a MOPAC2009/2012 output. +//Return error if fail. Returns Error (""Probable problem in calculation"") +//if there is a geometry but the calculation didnt end properly +func (O *MopacHandle) OptimizedGeometry(atoms chem.Atomer) (*v3.Matrix, error) { + var err error + inp := O.wrkdir + O.inputname + natoms := atoms.Len() + coords := make([]float64, natoms*3, natoms*3) //will be used for return + file, err := os.Open(fmt.Sprintf(""%s.out"", inp)) + if err != nil { + return nil, Error{ErrNoGeometry, Mopac, inp, """", []string{""os.Open"", ""OptimizedGeometry""}, true} + } + defer file.Close() + out := bufio.NewReader(file) + err = Error{ErrNoGeometry, Mopac, inp, """", []string{""OptimizedGeometry""}, true} + //some variables that will be changed/increased during the next for loop + final_point := false //to see if we got to the right part of the file + reading := false //start reading + i := 0 + errsl := make([]error, 3, 3) + trust_radius_warning := false + for { + var line string + line, err = out.ReadString('\n') + if err != nil { + break + } + + if (!reading) && strings.Contains(line, ""TRUST RADIUS NOW LESS THAN 0.00010 OPTIMIZATION TERMINATING"") { + trust_radius_warning = true + continue + } + + if !reading && (strings.Contains(line, ""FINAL POINT AND DERIVATIVES"") || strings.Contains(line, ""GEOMETRY OPTIMISED"")) || strings.Contains(line, ""GRADIENTS WERE INITIALLY ACCEPTABLY SMALL"") || strings.Contains(line, ""HERBERTS TEST WAS SATISFIED IN BFGS"") { + final_point = true + continue + } + if strings.Contains(line, ""(ANGSTROMS) (ANGSTROMS) (ANGSTROMS)"") && final_point { + _, err = out.ReadString('\n') + if err != nil { + break + } + reading = true + continue + } + if reading { + //So far we dont check that there are not too many atoms in the mopac output. + if i >= natoms { + err = nil + break + } + coords[i*3], errsl[0] = strconv.ParseFloat(strings.TrimSpace(line[22:35]), 64) + coords[i*3+1], errsl[1] = strconv.ParseFloat(strings.TrimSpace(line[38:51]), 64) + coords[i*3+2], errsl[2] = strconv.ParseFloat(strings.TrimSpace(line[54:67]), 64) + i++ + err = parseErrorSlice(errsl) + if err != nil { + break + } + } + } + if err != nil { + return nil, Error{ErrNoGeometry, Mopac, inp, err.Error(), []string{""OptimizedGeometry""}, true} + } + mcoords, err := v3.NewMatrix(coords) + if trust_radius_warning { + return mcoords, Error{ErrProbableProblem, Mopac, inp, """", []string{""OptimizedGeometry""}, false} + } + return mcoords, err +} + +//Support function, gets a slice of errors and returns the first +//non-nil error found, or nil if all errors are nil. +func parseErrorSlice(errorsl []error) error { + for _, val := range errorsl { + if val != nil { + return val + } + } + return nil +} +","Go" +"Computational Biochemistry","rmera/gochem","v3/gonum.go",".go","17792","533","/* + * gonum.go, part of gochem. + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + */ + +//Package chem provides atom and molecule structures, facilities for reading and writing some +//files used in computational chemistry and some functions for geometric manipulations and shape +//indicators. + +//gonum.go contains most of what is needed for handling the gonum/mat64 types and facilities. +//At this point the name is mostly historical: It used to be the only file importing gonum, +//Now that gomatrix support is discontinued, there is a tighter integration with gonum and +//other files import mat64. + +//All the *Vec functions will operate/produce column or row vectors depending on whether the matrix underlying Dense +//is row or column major. + +package v3 + +import ( + ""fmt"" + ""math"" + + ""gonum.org/v1/gonum/blas/blas64"" + ""gonum.org/v1/gonum/mat"" + + // ""math/cmplx"" + ""sort"" +) + +// Matrix is a set of vectors in 3D space. The underlying implementation varies. +// Within the package it is understood that a ""vector"" is a row vector, i.e. the +// cartesian coordinates of a point in 3D space. The name of some functions in +// the library reflect this. +type Matrix struct { + //The main container, must be able to implement most + //gonum interfaces + *mat.Dense +} + +// Matrix2Dense returns the A Gonum Dense matrix +// associated with A. Changes in one will +// be reflected in t he other +func Matrix2Dense(A *Matrix) *mat.Dense { + return A.Dense +} + +// Dense2Matrix returns a *v3.Matrix +// from a Gonum dense matrix, which has to be +// Nx3 +func Dense2Matrix(A *mat.Dense) *Matrix { + r, c := A.Dims() + if c != 3 { + panic(fmt.Sprintf(""malformed *mat.Dense matrix to make *v3.Matrix, must be Nx3, is %d x %d"", r, c)) + } + return &Matrix{A} +} + +// NewMatrix creates and returns a Matrix with 3 columns from data. +func NewMatrix(data []float64) (*Matrix, error) { + const cols int = 3 + l := len(data) + rows := l / cols + if l%cols != 0 { + return nil, Error(fmt.Errorf(""NewMatrix: Input slice lenght %d not divisible by %d: %d"", rows, cols, rows%cols)) + } + r := mat.NewDense(rows, cols, data) + return &Matrix{r}, nil +} + +// RawSlice returns the underlying []float64 slice for the receiver. +// Changes on either the []float64 or the receiver are expected to +// reflect on the other. +func (F *Matrix) RawSlice() []float64 { + return F.RawMatrix().Data +} + +// Row fills the dst slice of float64 with the ith row of matrix F and returns it. +// The slice must have the correct size or be nil, in which case a new slice will be created. +// This method is merely a frontend for the mat64.Row function of gonum. +func (F *Matrix) Row(dst []float64, i int) []float64 { + return mat.Row(dst, i, F.Dense) +} + +// Col fills the dst slice of float64 with the ith col of matrix F and returns it. +// The slice must have the correct size or be nil, in which case a new slice will be created. +// This method is merely a frontend for the mat64.Col function of gonum. +func (F *Matrix) Col(dst []float64, i int) []float64 { + return mat.Col(dst, i, F.Dense) +} + +// ColSlice puts a view of the given col of the matrix on the receiver +func (F *Matrix) ColSlice(i int) *Matrix { + // r := new(mat64.Dense) + Fr, _ := F.Dims() + r := F.Dense.Slice(0, Fr, i, i+1).(*mat.Dense) + return &Matrix{r} +} + +// ColView a view of the given col of the matrix on the receiver. +// This function is for compatibility with the gonum v1 API +// The older one might be deleted in the future, but, if at all, +// it will take time. +func (F *Matrix) ColView(i int) *Matrix { + // r := new(mat64.Dense) + Fr, _ := F.Dims() + r := F.Dense.Slice(0, Fr, i, i+1).(*mat.Dense) + return &Matrix{r} +} + +// VecView eturns view of the ith vector of the matrix in the receiver +func (F *Matrix) VecView(i int) *Matrix { + //r := new(mat64.Dense) + /* mr,mc:=F.Caps() ///////////////////////// + j:=0 + k:=1+i + l:=3 + println(""ESTAMOS EN LA BEEE"") + if i < 0{ + println(1) + }else if mr <= i{ + println(2) + } else if j < 0{ + println(3) + } else if mc <= j{ + println(4) + } else if k <= i{ + println(5,k,i) + } else if mr < k { + println(6) + } else if l <= j { + println(7) + }else if mc < l { + println(8) + } + println(""nooo"",i,mr,mc)//////////// + */ + r := F.Dense.Slice(i, i+1, 0, 3).(*mat.Dense) + return &Matrix{r} +} + +// VecSlice slice of the given vector of the matrix in the receiver +// This function is to keep compatibility with the new gonum v1 API +func (F *Matrix) VecSlice(i int) *Matrix { + //r := new(mat64.Dense) + r := F.Dense.Slice(i, i+1, 0, 3).(*mat.Dense) + return &Matrix{r} +} + +// View returns a view of F starting from i,j and spanning r rows and +// c columns. Changes in the view are reflected in F and vice-versa +// This view has the wrong signature for the interface mat64.Viewer, +// But the right signatur was not possible to implement. Notice that very little +// memory allocation happens, only a couple of ints and pointers. +func (F *Matrix) View(i, j, r, c int) *Matrix { + ret := F.Dense.Slice(i, i+r, j, j+c).(*mat.Dense) + return &Matrix{ret} +} + +// Slice returns a view of F starting from i,j and spanning r rows and +// c columns. Changes in the view are reflected in F and vice-versa +// This function is to keep compatibility with the gonum v1 API. +func (F *Matrix) Slice(i, r, j, c int) *Matrix { + ret := F.Dense.Slice(i, r, j, c).(*mat.Dense) + return &Matrix{ret} +} + +// Sub puts the element-wise subtraction +// of matrices A and B into the receiver +func (F *Matrix) Sub(A, B *Matrix) { + F.Dense.Sub(A.Dense, B.Dense) +} + +// Add puts the element-wise addition +// of matrices A and B into the receiver +func (F *Matrix) Add(A, B *Matrix) { + F.Dense.Add(A.Dense, B.Dense) +} + +// SetMatrix the matrix A in the received starting from the ith row and jth col +// of the receiver. +func (F *Matrix) SetMatrix(i, j int, A *Matrix) { + b := F.RawMatrix() + ar, ac := A.Dims() + fc := 3 + if ar+i > F.NVecs() || ac+j > fc { + panic(ErrShape) + } + r := make([]float64, ac, ac) + for k := 0; k < ar; k++ { + A.Row(r, k) + startpoint := fc*(k+i) + j + copy(b.Data[startpoint:startpoint+fc], r) + } +} + +// Mul Wraps mat.Mul to take care of the case when one of the +// arguments is also the received. Since the received is a Matrix, +// the mat64 function could check A (mat64.Dense) vs F (Matrix) and +// it would not know that internally F.Dense==A, hence the need for this function. +func (F *Matrix) Mul(A, B mat.Matrix) { + if F == A { + A := A.(*Matrix) + F.Dense.Mul(A.Dense, B) + } else if F == B { + B := B.(*Matrix) + F.Dense.Mul(A, B.Dense) + } else { + F.Dense.Mul(A, B) + } + + /* + if C, ok := A.(*Matrix); ok { + if D, ok2 := B.(*Matrix); ok2 { + F.Dense.Mul(C.Dense, D.Dense) + }else{ + F.Dense.Mul(C.Dense,D) + } + + }else{ + if D, ok2 := B.(*Matrix); ok2 { + F.Dense.Mul(A,D.Dense) + }else{ + F.Dense.Mul(A,B) + } + } + */ +} + +func stupidDot(A, B *Matrix) float64 { + return A.At(0, 0)*B.At(0, 0) + A.At(0, 1)*B.At(0, 1) + A.At(0, 2)*B.At(0, 2) +} + +// Dot gets the dot product between the first row of F and the first row of A. It's a vector dot product, +// to be used with 1-row matrices. +func (F *Matrix) Dot(A *Matrix) float64 { + //The reason for making Dot ask for a v3.Matrix is that then we can call mat64.Dot with A.Dense, which should make things faster. + id := mat.NewDense(3, 3, []float64{1, 0, 0, 0, 1, 0, 0, 0, 1}) //Identity matrix + return mat.Inner(F.Dense.RowView(0), id, A.Dense.RowView(0)) +} + +// Scale multiplies each element in the matrix A by +// v +func (F *Matrix) Scale(v float64, A *Matrix) { + F.Dense.Scale(v, A.Dense) +} + +// Norm acts as a front-end for the mat64 function. +func (F *Matrix) Norm(i float64) float64 { + //This used to always return Frobenius norm, no matter what you give as an argument. + //The argument is there for compatibility (Gonum used to have ""0"" as the Froebius norm + //and that was, until recently, still used in goChem. I think I have fixes all these + //use cases but be mindful of possible bugs. + + return mat.Norm(F.Dense, i) +} + +/* +For now I'm not sure we need this wrapper and I do try to keep the to the minimum. + +//Sum acts as a wrapper for the mat64 function, for compatibility. It returns the sum of the elements of F. +func (F *Matrix) Sum() float64{ + return mat64.Sum(F.Dense) +} +*/ + +// Stack puts A stacked over B in the receiver +func (F *Matrix) Stack(A, B *Matrix) { + f := F.RawMatrix() + ar, _ := A.Dims() + br, _ := B.Dims() + if F.NVecs() < ar+br { + panic(ErrShape) + } + for i := 0; i < ar; i++ { + A.Row(f.Data[i*3:i*3+3], i) + } + + for i := ar; i < ar+br; i++ { + B.Row(f.Data[i*3:i*3+3], i-ar) + } + +} + +//func EmptyVecs() *Matrix { +// dens := EmptyDense() +// return &Matrix{dens} +// +//} + +//Some of the following function have an err return type in the signature, but they always return a nil error. This is +//Because of a change in gonum/matrix. The NewDense function used to return error and now panics. +//I do not think it is worth to fix these functions. + +//func Eye(span int) *chemDense { +// return gnEye(span) +//} + +//Some temporary support function. +//func Eigen(in *Dense, epsilon float64) (*Dense, []float64, error) { +// i, j, k := gnEigen(in, epsilon) +// return i, j, k +//} + +//This is a facility to sort Eigenvectors/Eigenvalues pairs +//It satisfies the sort.Interface interface. + +// This is a temporal function. It returns the determinant of a 3x3 matrix. Panics if the matrix is not 3x3. +// It is also defined in the chem package which is not-so-clean. +func det(A mat.Matrix) float64 { + r, c := A.Dims() + if r != 3 || c != 3 { + panic(ErrDeterminant) + } + return (A.At(0, 0)*(A.At(1, 1)*A.At(2, 2)-A.At(2, 1)*A.At(1, 2)) - A.At(1, 0)*(A.At(0, 1)*A.At(2, 2)-A.At(2, 1)*A.At(0, 2)) + A.At(2, 0)*(A.At(0, 1)*A.At(1, 2)-A.At(1, 1)*A.At(0, 2))) +} + +type eigenpair struct { + //evecs must have as many rows as evals has elements. + evecs *Matrix + evals sort.Float64Slice +} + +func (E eigenpair) Less(i, j int) bool { + return E.evals[i] < E.evals[j] +} +func (E eigenpair) Swap(i, j int) { + E.evals.Swap(i, j) + // E.evecs[i],E.evecs[j]=E.evecs[j],E.evecs[i] + E.evecs.SwapVecs(i, j) + +} +func (E eigenpair) Len() int { + return len(E.evals) +} + +// EigenWrap wraps the mat.Eigen structure in order to guarantee +// That the eigenvectors and eigenvalues are sorted according to the eigenvalues +// It also guarantees orthonormality and handness. I don't know how many of +// these are already guaranteed by Eig(). Will delete the unneeded parts +// And even this whole function when sure. The main reason for this function +// Is the compatibiliy with go.matrix. This function should dissapear when we +// have a pure Go blas. +func EigenWrap(in *Matrix, epsilon float64) (*Matrix, []float64, error) { + if epsilon < 0 { + epsilon = appzero + } + eigen := new(mat.Eigen) + ok := eigen.Factorize(mat.DenseCopyOf(in.Dense), mat.EigenRight) //Not sure if that DenseCopy is still needed. + if !ok { + return nil, nil, Error(fmt.Errorf(""error in EigenWrap: mat.Eigen.Factorize"")) + } + evals_cmp := make([]complex128, 3) //We only deal with 3-column matrixes in this package + TempVec := mat.NewCDense(3, 3, nil) /// An allocation. We have to see whether I should try to minimize these. Also, see comment above. + evals_cmp = eigen.Values(evals_cmp) + eigen.VectorsTo(TempVec) + evecsprev := Zeros(3) + //This is horrible, but, apparently, Gonum just doesn't provide anything to go from CDense to Dense. At least these are guaranteed to be 3x3 matrices + for i := 0; i < 3; i++ { + for j := 0; j < 3; j++ { + scalar := TempVec.At(i, j) + if imag(scalar) != 0 { + return nil, nil, Error(fmt.Errorf(""mat.EigenFactorize: Found a complex Eigenvector"")) + } + evecsprev.Set(i, j, real(scalar)) + } + } + evals := make([]float64, 3, 3) + + for k, _ := range evals { + evals[k] = real(evals_cmp[k]) //no check of the thing being real for now. + } + evecs := Zeros(3) + fn := func() { evecs.Copy(evecsprev.T()) } + err := mat.Maybe(fn) + if err != nil { + return nil, nil, Error(fmt.Errorf(""EigenWrap: mat.Copy/math.T"")) + + } + //evecs.TCopy(evecs.Dense) + eig := eigenpair{evecs, evals[:]} + sort.Sort(eig) + //Here I should orthonormalize vectors if needed instead of just complaining. + //I think orthonormality is guaranteed by DenseMatrix.Eig() If it is, Ill delete all this + //If not I'll add ortonormalization routines. + eigrows, _ := eig.evecs.Dims() + for i := 0; i < eigrows; i++ { + //vectori := eig.evecs.VecView(i) + for j := i + 1; j < eigrows; j++ { + // vectorj := eig.evecs.VecView(j) + if math.Abs(eig.evecs.RowView(i).Dot(eig.evecs.RowView(j))) > epsilon && i != j { + fmt.Println(""Dot should be"", stupidDot(eig.evecs.RowView(i), eig.evecs.RowView(j))) + reterr := fmt.Errorf(""EigenWrap: Eigenvectors %d and %d nor orthogonal: %v %v. Dot: %5.3f. EigMatrix: %v"", i, j, eig.evecs.Dense.RowView(i), eig.evecs.Dense.RowView(j), math.Abs(eig.evecs.RowView(i).Dot(eig.evecs.RowView(j))), eig.evecs) + return eig.evecs, evals[:], reterr + } + } + if math.Abs(eig.evecs.VecView(1).Norm(2)-1) > epsilon { + //Of course I could just normalize the vectors instead of complaining. + //err= fmt.Errorf(""Vectors not normalized %s"",err.Error()) + + } + } + //Checking and fixing the handness of the matrix.This if-else is Jannes idea, + //I don't really know whether it works. + // eig.evecs.TCopy(eig.evecs) + if det(eig.evecs) < 0 { //Right now, this will fail if the matrix is not 3x3 (30/10/2013) + eig.evecs.Scale(-1, eig.evecs) //SSC + } else { + /* + eig.evecs.TransposeInPlace() + eig.evecs.ScaleRow(0,-1) + eig.evecs.ScaleRow(2,-1) + eig.evecs.TransposeInPlace() + */ + } + // eig.evecs.TCopy(eig.evecs) + return eig.evecs, eig.evals, nil //Returns a slice of evals +} + +/* +//Returns the singular value decomposition of matrix A +func gnSVD(A *mat64.Dense) ( *mat64.Dense,*mat64.Dense,*mat64.Dense) { + facts := mat64.SVD(A.Dense, appzero, math.SmallestNonzeroFloat64, true, true) //I am not sure that the second appzero is appropiate + //make sigma a matrix + // lens:=len(s) + // Sigma, _ := mat64.NewDense(lens, lens, make([]float64, lens*lens)) //the slice is hardcoded, no error + // for i := 0; i < lens; i++ { + // Sigma.Set(i, i, s[i]) + // } + return &chemDense{facts.U}, &chemDense{facts.S()}, &chemDense{facts.V} + +} +*/ + +/* +//A wrapper for mat64.Dense.T which returns a Matrix. +func (F *Matrix) Tr () *Matrix{ + Tra:=F.Dense.T() + if Tra,ok:= Tra.(*mat64.Dense);ok{ + return &Matrix{Tra} + }else{ + panic(""goChem/v3: gonum/matrix/mat64.Dense.T() returned a non mat64.Dense"") + } +} +*/ + +// I know, premature optimization and so on. It's an internal thing, sue me. +var transposetmp float64 + +// Tr performs an explicit, in-place tranpose of the receiver. +// it relies in the fact that v3 matrix are all 3D. If the receiver has more than +// 3 rows, the square submatrix of the first 3 rows will be transposed (i.e. no panic or returned error). +// it panics if the receiver has less than 3 rows. +func (F *Matrix) Tr() { + //This function exists because I can't use the implicit tranpose provided by mat64.Dense.T() + //which returns a matrix that is not possible to cast into a mat64.Dense + if F.NVecs() < 3 { + panic(""goChem/v3/Tr: Only 3x3 matrices are allowed for both the argument of Tr(), while the receiver must have 3 rows or more"") + } + R := F.RawMatrix() + dataSwitch(R, 0, 1) + dataSwitch(R, 0, 2) + dataSwitch(R, 1, 2) +} + +// Returns the transpose of F. Does not modify F. +func (F *Matrix) TrRet(toret ...*Matrix) *Matrix { + if F.NVecs() < 3 { + panic(""goChem/v3/TrRet: The receiver must have 3 rows or more"") + } + var r *Matrix + if len(toret) > 0 && toret[0] != nil && toret[0].NVecs() == 3 { + r = toret[0] + } else { + r = Zeros(3) + } + for i := 0; i < 3; i++ { + for j := 0; j < 3; j++ { + r.Set(i, j, F.At(j, i)) + } + } + return r +} + +// I can only hope this gets inlined +func dataSwitch(R blas64.General, r, c int) { + transposetmp = R.Data[3*r+c] + R.Data[3*r+c] = R.Data[3*c+r] + R.Data[3*c+r] = transposetmp +} + +type Error error + +// PanicMsg is a message used for panics, even though it does satisfy the error interface. +// for errors use Error. +type PanicMsg string + +func (v PanicMsg) Error() string { return string(v) } + +//Here I use a few of the gonum/mat64 messages for compatibility (Copyright (c) The gonum authors). I assumed here that this is small enough not to require +//messing about with licenses, but of course I don't intend any copyright impringement and I will set somethign up if contacted. + +const ( + ErrNotXx3Matrix = PanicMsg(""goChem/v3: A VecMatrix should have 3 columns"") + ErrNoCrossProduct = PanicMsg(""goChem/v3: Invalid matrix for cross product"") + ErrNotOrthogonal = PanicMsg(""goChem/v3: Vectors nor orthogonal"") + ErrNotEnoughElements = PanicMsg(""goChem/v3: not enough elements in Matrix"") + ErrGonum = PanicMsg(""goChem/v3: Error in gonum function"") + ErrEigen = PanicMsg(""goChem/v3: Can't obtain eigenvectors/eigenvalues of given matrix"") + ErrDeterminant = PanicMsg(""goChem/v3: Determinants are only available for 3x3 matrices"") + ErrShape = PanicMsg(""goChem/v3: Dimension mismatch"") + ErrIndexOutOfRange = PanicMsg(""mat64: index out of range"") +) +","Go" +"Computational Biochemistry","rmera/gochem","v3/doc.go",".go","1196","30","/* + * doc.go, part of gochem. + * + * Copyright 2015 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + * */ + +// Package v3 implements a Matrix type representing a row-major 3D matrix (i.e. a Nx3 matrix). +// The v3.Matrix is used to represent the cartesian coordinates of sets of atoms in goChem. +// It is based int gonum's (github.com/gonum) Dense type, with some additional restrictions +// because of the fixed number of columns and with some additional functions that were found +// useful for the purposes of goChem. + +package v3 +","Go" +"Computational Biochemistry","rmera/gochem","v3/gonum_purego.go",".go","18262","727","// +build ignored + +/* + * gonum_go.go, part of gochem. + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + */ + +//Package chem provides atom and molecule structures, facilities for reading and writing some +//files used in computational chemistry and some functions for geometric manipulations and shape +//indicators. + +//All the *Vec functions will operate/produce column or row vectors depending on whether the matrix underlying Dense +//is row or column major. + +package chem + +import ( + ""fmt"" + ""math"" + ""sort"" + + matrix ""github.com/skelterjohn/go.matrix"" +) + +/*Here I make a -very incomplete- implementation of the gonum api backed by go.matrix, which will enable me to port gochem to gonum. + * Since the agreement in the gonum community was NOT to build a temporary implementation, I just build the functions that + * gochem uses, on my own type (which should implement all the relevant gonum interfaces). + * all the gonum-owned names will start with gn (i.e. RandomFunc becomes gnRandomFunc) so its latter easy to use search and replace to set the + * correct import path when gonum is implemented (such as gonum.RandomFunc) + */ + +//INTERFACES This part is from GONUM, copyright, the gonum authors. + +//This part of the package is deprecated. Gonum is the only implemantation used in goChem now. + +type Normer interface { + Norm(o float64) float64 +} + +type NormerMatrix interface { + Normer + Matrix +} + +// BlasMatrix represents a cblas native representation of a matrix. +type BlasMatrix struct { + Rows, Cols int + Stride int + Data []float64 +} + +//VecMatrix is a set of vectors in 3D space. The underlying implementation varies. +type VecMatrix struct { + *Dense +} + +//For the pure-go implementation I must implement Dense on top of go.matrix +type chemDense struct { + *Dense +} + +//For the pure-go implementation I must implement Dense on top of go.matrix +type Dense struct { + *matrix.DenseMatrix +} + +//Generate and returns a CoorMatrix with arbitrary shape from data. +func newDense(data []float64, rows, cols int) *Dense { + if len(data) < cols*rows { + panic(notEnoughElements) + } + return &Dense{matrix.MakeDenseMatrix(data, rows, cols)} + +} + +func det(A *VecMatrix) float64 { + return A.Det() + +} + +//Generate and returns a CoorMatrix with arbitrary shape from data. +func newchemDense(data []float64, rows, cols int) (*chemDense, error) { + if len(data) < cols*rows { + return nil, fmt.Errorf(string(notEnoughElements)) + } + return &chemDense{newDense(data, rows, cols)}, nil + +} + +//NewVecs enerates and returns a VecMatrix with 3 columns from data. +func NewVecs(data []float64) (*VecMatrix, error) { + ///fmt.Println(""JAJAJA BIENVENIDO AL INFIERNO!!!!"") //Surely a debugging msg I had forgotten about. It would have rather surprised any Spanish-speaking user :-) + const cols int = 3 + l := len(data) + rows := l / cols + if l%cols != 0 { + return nil, fmt.Errorf(""Input slice lenght %d not divisible by %d: %d"", rows, cols, rows%cols) + } + r := newDense(data, rows, cols) + return &VecMatrix{r}, nil +} + +//Returns and empty, but not nil, Dense. It barely allocates memory +func EmptyDense() *Dense { + var a *matrix.DenseMatrix + return &Dense{a} + +} + +//Returns an zero-filled Dense with the given dimensions +//It is to be substituted by the Gonum function. +func gnZeros(rows, cols int) *chemDense { + return &chemDense{&Dense{matrix.Zeros(rows, cols)}} +} + +//Returns an identity matrix spanning span cols and rows +func gnEye(span int) *chemDense { + A := gnZeros(span, span) + for i := 0; i < span; i++ { + A.Set(i, i, 1.0) + } + return A +} + +func Eye(span int) *chemDense { + return gnEye(span) +} + +//Some temporary support function. +//func Eigen(in *Dense, epsilon float64) (*Dense, []float64, error) { +// i, j, k := gnEigen(in, epsilon) +// return i, j, k +//} + +//This is a facility to sort Eigenvectors/Eigenvalues pairs +//It satisfies the sort.Interface interface. +type eigenpair struct { + //evecs must have as many rows as evals has elements. + evecs *VecMatrix + evals sort.Float64Slice +} + +func (E eigenpair) Less(i, j int) bool { + return E.evals[i] < E.evals[j] +} +func (E eigenpair) Swap(i, j int) { + E.evals.Swap(i, j) + // E.evecs[i],E.evecs[j]=E.evecs[j],E.evecs[i] + E.evecs.SwapRows(i, j) +} +func (E eigenpair) Len() int { + return len(E.evals) +} + +//EigenWrap wraps the matrix.DenseMatrix.Eigen() function in order to guarantee +//That the eigenvectors and eigenvalues are sorted according to the eigenvalues +//It also guarantees orthonormality and handness. I don't know how many of +//these are already guaranteed by Eig(). Will delete the unneeded parts +//And even this whole function when sure. +func EigenWrap(in *VecMatrix, epsilon float64) (*VecMatrix, []float64, error) { + var err error + if epsilon < 0 { + epsilon = appzero + } + evecsDM, vals, _ := in.Eigen() + evecs := &VecMatrix{&Dense{evecsDM}} + // fmt.Println(""evecs fresh"", evecs) /////// + evals := [3]float64{vals.Get(0, 0), vals.Get(1, 1), vals.Get(2, 2)} //go.matrix specific code here. + f := func() { evecs.TCopy(evecs) } + if err = gnMaybe(gnPanicker(f)); err != nil { + return nil, nil, err + } + eig := eigenpair{evecs, evals[:]} + + // fmt.Println(""evecs presort"", eig.evecs) ///////// + sort.Sort(eig) + + //Here I should orthonormalize vectors if needed instead of just complaining. + //I think orthonormality is guaranteed by DenseMatrix.Eig() If it is, Ill delete all this + //If not I'll add ortonormalization routines. + eigrows, _ := eig.evecs.Dims() + // fmt.Println(""evecs"", eig.evecs) //////////////// + for i := 0; i < eigrows; i++ { + vectori := eig.evecs.RowView(i) + for j := i + 1; j < eigrows; j++ { + vectorj := eig.evecs.RowView(j) + if math.Abs(vectori.Dot(vectorj)) > epsilon && i != j { + return eig.evecs, evals[:], notOrthogonal + } + } + // fmt.Println(""VECTORS"", eig.evecs) ////////////////////////// + if math.Abs(vectori.Norm(2)-1) > epsilon { + //Of course I could just normalize the vectors instead of complaining. + //err= fmt.Errorf(""Vectors not normalized %s"",err.Error()) + + } + } + //Checking and fixing the handness of the matrix.This if-else is Jannes idea, + //I don't really know whether it works. + eig.evecs.TCopy(eig.evecs) + if eig.evecs.Det() < 0 { + eig.evecs.Scale(-1, eig.evecs) //SSC + } else { + /* + eig.evecs.TransposeInPlace() + eig.evecs.ScaleRow(0,-1) + eig.evecs.ScaleRow(2,-1) + eig.evecs.TransposeInPlace() + */ + // fmt.Println(""all good, I guess"") + } + eig.evecs.TCopy(eig.evecs) + return eig.evecs, eig.evals, err //Returns a slice of evals +} + +//Returns the singular value decomposition of matrix A +func gnSVD(A *chemDense) (*chemDense, *chemDense, *chemDense) { + U, s, V, err := A.SVD() + if err != nil { + panic(err.Error()) + } + theU := chemDense{&Dense{U}} + sigma := chemDense{&Dense{s}} + theV := chemDense{&Dense{V}} + return &theU, &sigma, &theV + +} + +//returns a rows,cols matrix filled with gnOnes. +func gnOnes(rows, cols int) *chemDense { + gnOnes := gnZeros(rows, cols) + for i := 0; i < rows; i++ { + for j := 0; j < cols; j++ { + gnOnes.Set(i, j, 1) + } + } + return gnOnes +} + +func gnMul(A, B Matrix) *chemDense { + ar, _ := A.Dims() + _, bc := B.Dims() + C := gnZeros(ar, bc) + C.Mul(A, B) + return C +} + +func gnCopy(A Matrix) *chemDense { + r, c := A.Dims() + B := gnZeros(r, c) + B.Copy(A) + return B +} + +func gnT(A Matrix) *chemDense { + r, c := A.Dims() + B := gnZeros(c, r) + B.TCopy(A) + return B +} + +//Methods +/* When gonum is ready, all this functions will take a num.Matrix interface as an argument, instead of a + * Dense*/ + +func (F *Dense) Add(A, B Matrix) { + ar, ac := A.Dims() + br, bc := B.Dims() + fr, fc := F.Dims() + if ac != bc || br != ar || ac != fc || ar != fr { + panic(gnErrShape) + } + for i := 0; i < fr; i++ { + for j := 0; j < fc; j++ { + F.Set(i, j, A.At(i, j)+B.At(i, j)) + } + } + +} + +func (F *Dense) BlasMatrix() BlasMatrix { + b := new(BlasMatrix) + r, c := F.Dims() + b.Rows = r + b.Cols = c + b.Stride = 0 //not really + b.Data = F.Array() + return *b +} + +func (F *Dense) At(A, B int) float64 { + return F.Get(A, B) +} + +func (F *Dense) Copy(A Matrix) { + ar, ac := A.Dims() + fr, fc := F.Dims() + if ac > fc || ar > fr { + // fmt.Println(ar, ac, fr, fc) + panic(gnErrShape) + } + + for i := 0; i < ar; i++ { + for j := 0; j < ac; j++ { + F.Set(i, j, A.At(i, j)) + } + + } + +} + +//Returns an array with the data in the ith row of F +func (F *Dense) Col(a []float64, i int) []float64 { + r, c := F.Dims() + if i >= c { + panic(""Matrix: Requested column out of bounds"") + } + if a == nil { + a = make([]float64, r, r) + } + for j := 0; j < r; j++ { + if j >= len(a) { + break + } + a[j] = F.At(j, i) + } + return a +} + +func (F *Dense) Dims() (int, int) { + return F.Rows(), F.Cols() +} + +//Dot returns the dot product between 2 vectors or matrices +func (F *Dense) Dot(B Matrix) float64 { + frows, fcols := F.Dims() + brows, bcols := B.Dims() + if fcols != bcols || frows != brows { + panic(gnErrShape) + } + a, b := F.Dims() + A := gnZeros(a, b) + A.MulElem(F, B) + return A.Sum() +} + +//puts the inverse of B in F or panics if F is non-singular. +//its just a dirty minor adaptation from the code in go.matrix from John Asmuth +//it will be replaced by the gonum implementation when the library is ready. +//Notice that this doesn't actually check for errors, the error value returned is always nil. +//I just did that crappy fix because this gomatrix-interface should be taken out or deprecated soon. +func gnInverse(B Matrix) (*VecMatrix, error) { + //fr,fc:=F.Dims() + ar, ac := B.Dims() + if ac != ar { + panic(gnErrSquare) + } + F := ZeroVecs(ar) + var ok bool + var A *VecMatrix + A, ok = B.(*VecMatrix) + if !ok { + C, ok := B.(*Dense) + if !ok { + panic(""Few types are allowed so far"") + } + A = &VecMatrix{C} + + } + augt, _ := A.Augment(matrix.Eye(ar)) + aug := &Dense{augt} + augr, _ := aug.Dims() + for i := 0; i < augr; i++ { + j := i + for k := i; k < augr; k++ { + if math.Abs(aug.Get(k, i)) > math.Abs(aug.Get(j, i)) { + j = k + } + } + if j != i { + aug.SwapRows(i, j) + } + if aug.Get(i, i) == 0 { + panic(gnErrSingular) + } + aug.ScaleRow(i, 1.0/aug.Get(i, i)) + for k := 0; k < augr; k++ { + if k == i { + continue + } + aug.ScaleAddRow(k, i, -aug.Get(k, i)) + } + } + F.SubMatrix(aug, 0, ac, ar, ac) + return F, nil +} + +//A slightly modified version of John Asmuth's ParalellProduct function. +func (F *Dense) Mul(A, B Matrix) { + Arows, Acols := A.Dims() + Brows, Bcols := B.Dims() + if Acols != Brows { + panic(gnErrShape) + } + if F == nil { + F = gnZeros(Arows, Bcols).Dense //I don't know if the final API will allow this. + } + + in := make(chan int) + quit := make(chan bool) + + dotRowCol := func() { + for { + select { + case i := <-in: + sums := make([]float64, Bcols) + for k := 0; k < Acols; k++ { + for j := 0; j < Bcols; j++ { + sums[j] += A.At(i, k) * B.At(k, j) + } + } + for j := 0; j < Bcols; j++ { + F.Set(i, j, sums[j]) + } + case <-quit: + return + } + } + } + + threads := 2 + + for i := 0; i < threads; i++ { + go dotRowCol() + } + + for i := 0; i < Arows; i++ { + in <- i + } + + for i := 0; i < threads; i++ { + quit <- true + } + + return +} + +func (F *Dense) MulElem(A, B Matrix) { + arows, acols := A.Dims() + brows, bcols := B.Dims() + frows, fcols := F.Dims() + if arows != brows || acols != bcols || arows != frows || acols != fcols { + panic(gnErrShape) + } + for i := 0; i < arows; i++ { + for j := 0; j < acols; j++ { + F.Set(i, j, A.At(i, j)*B.At(i, j)) + } + + } +} + +func (F *Dense) Norm(i float64) float64 { + //The parameters is for compatibility + return F.TwoNorm() +} + +//Returns an array with the data in the ith row of F +func (F *Dense) Row(a []float64, i int) []float64 { + r, c := F.Dims() + if i >= r { + panic(""Matrix: Requested row out of bounds"") + } + if a == nil { + a = make([]float64, c, c) + } + for j := 0; j < c; j++ { + if j >= len(a) { + break + } + a[j] = F.At(i, j) + } + return a +} + +//Scale the matrix A by a number i, putting the result in the received. +func (F *Dense) Scale(i float64, A Matrix) { + if A == F { //if A and F points to the same object. + F.scaleAux(i) + } else { + F.Copy(A) + F.scaleAux(i) + } +} + +//Puts a view of the given col of the matrix on the receiver +func (F *VecMatrix) ColView(i int) *VecMatrix { + r := new(Dense) + *r = *F.Dense + Fr, _ := F.Dims() + r.View(0, i, Fr, 1) + return &VecMatrix{r} +} + +//Returns view of the given vector of the matrix in the receiver +func (F *VecMatrix) VecView(i int) *VecMatrix { + r := new(Dense) + *r = *F.Dense + r.View(i, 0, 1, 3) + return &VecMatrix{r} +} + +//View returns a view of F starting from i,j and spanning r rows and +//c columns. Changes in the view are reflected in F and vice-versa +//This view has the wrong signature for the interface mat64.Viewer, +//But the right signatur was not possible to implement. Notice that very little +//memory allocation happens, only a couple of ints and pointers. +func (F *VecMatrix) View(i, j, r, c int) *VecMatrix { + ret := new(Dense) + *ret = *F.Dense + ret.View(i, j, r, c) + return &VecMatrix{ret} +} + +func (F *Dense) scaleAux(factor float64) { + fr, fc := F.Dims() + for i := 0; i < fr; i++ { + for j := 0; j < fc; j++ { + F.Set(i, j, F.At(i, j)*factor) + } + + } +} + +//When go.matrix is abandoned it is necesary to implement SetMatrix +//SetMatrix() +//Copies A into F aligning A(0,0) with F(i,j) +func (F *Dense) SetMatrix(i, j int, A Matrix) { + fr, fc := F.Dims() + ar, ac := A.Dims() + if ar+i > fr || ac+j > fc { + panic(gnErrShape) + } + for l := 0; l < ar; l++ { + for m := 0; m < ac; m++ { + F.Set(l+i, m+j, A.At(l, m)) + } + } +} + +//puts in F a matrix consisting in A over B +func (F *Dense) Stack(A, B Matrix) { + Arows, Acols := A.Dims() + Brows, Bcols := B.Dims() + Frows, Fcols := F.Dims() + + if Acols != Bcols || Acols != Fcols || Arows+Brows != Frows { + panic(gnErrShape) + } + + for i := 0; i < Arows+Brows; i++ { + for j := 0; j < Acols; j++ { + if i < Arows { + F.Set(i, j, A.At(i, j)) + } else { + F.Set(i, j, B.At(i-Arows, j)) + } + } + } + + return +} + +//Subtracts the matrix B from A putting the result in F +func (F *Dense) Sub(A, B Matrix) { + ar, ac := A.Dims() + br, bc := B.Dims() + fr, fc := F.Dims() + if ac != bc || br != ar || ac != fc || ar != fr { + panic(gnErrShape) + } + for i := 0; i < fr; i++ { + for j := 0; j < fc; j++ { + F.Set(i, j, A.At(i, j)-B.At(i, j)) + } + } + +} + +//not tested +//returns a copy of the submatrix of A starting by the point i,j and +//spanning rows rows and cols columns. +func (F *Dense) SubMatrix(A *Dense, i, j, rows, cols int) { + temp := Dense{A.GetMatrix(i, j, rows, cols)} + F.Copy(&temp) +} + +//Sum returns the sum of all elements in matrix A. +func (F *Dense) Sum() float64 { + Rows, Cols := F.Dims() + var sum float64 + for i := 0; i < Cols; i++ { + for j := 0; j < Rows; j++ { + sum += F.Get(j, i) + } + } + return sum +} + +//Transpose +func (F *Dense) TCopy(A Matrix) { + ar, ac := A.Dims() + fr, fc := F.Dims() + if ar != fc || ac != fr { + panic(gnErrShape) + } + var B *Dense + var ok bool + if B, ok = A.(*Dense); !ok { + if C, ok := A.(*VecMatrix); ok { + B = C.Dense + } else if D, ok := A.(*chemDense); ok { + B = D.Dense + } else { + panic(""Only Dense, chemDense and VecMatrix are currently accepted"") + } + } + //we do it in a different way if you pass the received as the argument + //(transpose in place) We could use continue for i==j + if F == B { + /* for i := 0; i < ar; i++ { + for j := 0; j < i; j++ { + tmp := A.At(i, j) + F.Set(i, j, A.At(j, i)) + F.Set(j, i, tmp) + } + */F.TransposeInPlace() + } else { + F.DenseMatrix = B.Transpose() + /* + for i := 0; i < ar; i++ { + for j := 0; j < ac; j++ { + F.Set(j, i, A.At(i, j)) + } + } + */ + } +} + +//Unit takes a vector and divides it by its norm +//thus obtaining an unitary vector pointing in the same direction as +//vector. +func (F *Dense) Unit(A NormerMatrix) { + norm := 1.0 / A.Norm(2) + F.Scale(norm, A) +} + +func (F *Dense) View(i, j, rows, cols int) { + F.DenseMatrix = F.GetMatrix(i, j, rows, cols) +} + +/**These are from the current proposal for gonum, by Dan Kortschak. It will be taken out + * from here when gonum is implemented. The gn prefix is appended to the names to make them + * unimported and to allow easy use of search/replace to add the ""num"" prefix when I change to + * gonum.**/ + +// A Panicker is a function that may panic. +type gnPanicker func() + +// Maybe will recover a panic with a type matrix.Error from fn, and return this error. +// Any other error is re-panicked. +func gnMaybe(fn gnPanicker) (err error) { + defer func() { + if r := recover(); r != nil { + var ok bool + if err, ok = r.(gnError); ok { + return + } + panic(r) + } + }() + fn() + return +} + +// Type Error represents matrix package errors. These errors can be recovered by Maybe wrappers. +type gnError string + +func (err gnError) Error() string { return string(err) } + +const ( + //RM + not3xXMatrix = gnError(""matrix: The other dimmension should be 3"") + notOrthogonal = gnError(""matrix: Vectors nor orthogonal"") + notEnoughElements = gnError(""matrix: not enough elements"") + //end RM + gnErrIndexOutOfRange = gnError(""matrix: index out of range"") + gnErrZeroLength = gnError(""matrix: zero length in matrix definition"") + gnErrRowLength = gnError(""matrix: row length mismatch"") + gnErrColLength = gnError(""matrix: col length mismatch"") + gnErrSquare = gnError(""matrix: expect square matrix"") + gnErrNormOrder = gnError(""matrix: invalid norm order for matrix"") + gnErrSingular = gnError(""matrix: matrix is singular"") + gnErrShape = gnError(""matrix: dimension mismatch"") + gnErrIllegalStride = gnError(""matrix: illegal stride"") + gnErrPivot = gnError(""matrix: malformed pivot list"") +) +","Go" +"Computational Biochemistry","rmera/gochem","v3/v3_test.go",".go","3920","166","/* + * coord_test.go + * + * Copyright 2013 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + * + * + */ + +package v3 + +import ( + ""fmt"" + ""testing"" + + ""gonum.org/v1/gonum/mat"" +) + +// Returns an zero-filled Dense with the given dimensions +// It is to be substituted by the Gonum function. +func gnZeros(r, c int) *mat.Dense { + f := make([]float64, r*c, r*c) + return mat.NewDense(r, c, f) + +} + +// Returns an identity matrix spanning span cols and rows +func gnEye(span int) *mat.Dense { + A := gnZeros(span, span) + for i := 0; i < span; i++ { + A.Set(i, i, 1.0) + } + return A +} + +func TestGeo(Te *testing.T) { + a := []float64{1.0, 2.0, 3, 4, 5, 6, 7, 8, 9} + A, err := NewMatrix(a) + if err != nil { + Te.Error(err) + } + ar, ac := A.Dims() + T := Zeros(ar) + T.Copy(A) + T.T() + B := gnEye(ar) + //B.Copy(A) + T.Mul(A, B) + E := Zeros(ar) + E.MulElem(A, B) + fmt.Println(T, ""\n"", T, ""\n"", A, ""\n"", B, ""\n"", ar, ac) + View := A.VecView(1) + View.Set(0, 0, 100) + fmt.Println(""View\n"", A, ""\n"", View) + +} + +func TestSomeVecs(Te *testing.T) { + a := []float64{1.0, 2.0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18} + A, err := NewMatrix(a) + if err != nil { + Te.Error(err) + } + B := Zeros(3) //We should cause an error by modifying this. + cind := []int{1, 3, 5} + err = B.SomeVecsSafe(A, cind) + if err != nil { + Te.Error(err) + } + fmt.Println(A, ""\n"", B) + B.Set(1, 1, 55) + B.Set(2, 2, 66) + fmt.Println(""Changed B"") + fmt.Println(A, ""\n"", B) + A.SetVecs(B, cind) + fmt.Println(""Now A should see changes in B"") + fmt.Println(A, ""\n"", B) +} + +func TestScale(Te *testing.T) { + a := []float64{1.0, 2.0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18} + A, err := NewMatrix(a) + if err != nil { + Te.Error(err) + } + B := Zeros(6) + A.Scale(3, A) + B.Scale(2, A) + fmt.Println(A, ""\n"", B) + Row, err := NewMatrix([]float64{10, 20, 30}) + if err != nil { + Te.Error(err) + } + A.AddVec(A, Row) + fmt.Println(""Additions"") + fmt.Println(A) + A.SubVec(A, Row) + fmt.Println(A, A.NVecs(), B.NVecs()) + // B.Pow(A, 2) + // fmt.Println(""Squared"", A, ""\n"", B) + b := []float64{1.0, 2.0, 3, 4, 5, 6, 7, 8, 9} + S, err := NewMatrix(b) + if err != nil { + Te.Error(err) + } + row, err := NewMatrix([]float64{2, 2, 3}) + if err != nil { + Te.Error(err) + } + fmt.Println(""Before scale"", S, ""\n"", row) + S.ScaleByVec(S, row) + fmt.Println(""Scaled by row"", S) + col := row.T() + fmt.Println(""Transpose"", col) + S.ScaleByCol(S, col) + fmt.Println(""Scaled by col"", S) + rows2, _ := NewMatrix([]float64{2, 2, 2, 3, 3, 3}) + fmt.Println(""Before adding 4"", rows2) + rows2.AddFloat(rows2, 4) + fmt.Println(""After adding 4"", rows2) +} + +func TestRowMod(Te *testing.T) { + a := []float64{1.0, 2.0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18} + A, err := NewMatrix(a) + if err != nil { + Te.Error(err) + } + B := Zeros(5) + B.DelVec(A, 3) + fmt.Println(""with and wihout row 3\n"", A, ""\n"", B) + fmt.Println(""test for Unit"") + row, err := NewMatrix([]float64{2, 2, 3}) + if err != nil { + Te.Error(err) + } + fmt.Println(""Original vector"", row) + row.Unit(row) + fmt.Println(""Unitarized"", row) + +} + +func TestEigen(Te *testing.T) { + a := []float64{1, 2, 0, 2, 1, 0, 0, 0, 1} + A, err := NewMatrix(a) + if err != nil { + Te.Error(err) + } + evecs, evals, err := EigenWrap(A, -1) + fmt.Println(evecs, ""\n"", evals, ""\n"", err) +} +","Go" +"Computational Biochemistry","rmera/gochem","v3/init_cblas.go",".go","1419","43","// +build cblas + +/* + * init_cblas.go, part of gochem. + * + * Copyright 2014 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + */ + +//The point of this is that the user can use compile tags to get their programs compiled with goblas or cblas. +//goblas is the default, the cblas tag being required to use, well, cblas. + +package v3 + +import ( + ""gonum.org/v1/gonum/blas/cblas64"" + ""gonum.org/v1/gonum/mat"" +) + +//For now this is here as we do not have other blas engine options. +//When we do, there will be several files with different inits, +//That will be chosen with compiler flags. +func init() { + mat.Register(cblas64.Blas{}) +} +","Go" +"Computational Biochemistry","rmera/gochem","v3/gocoords.go",".go","9476","334","/* + * gocoords.go, part of gochem. + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + */ + +//Package chem provides atom and molecule structures, facilities for reading and writing some +//files used in computational chemistry and some functions for geometric manipulations and shape +//indicators. + +package v3 + +import ( + ""fmt"" + ""math"" + ""strings"" + + ""gonum.org/v1/gonum/mat"" +) + +const appzero float64 = 0.000000000001 //used to correct floating point +//errors. Everything equal or less than this is considered zero. This probably sucks. + +// Zeros returns a zero-filled Matrix with vecs vectors and 3 in the other dimension. +func Zeros(vecs int) *Matrix { + const cols int = 3 + f := make([]float64, cols*vecs, cols*vecs) + return &Matrix{mat.NewDense(vecs, cols, f)} +} + +//METHODS + +// SwapVecs swaps the vectors i and j in the receiver +func (F *Matrix) SwapVecs(i, j int) { + if i >= F.NVecs() || j >= F.NVecs() { + panic(ErrIndexOutOfRange) + } + rowi := F.Row(nil, i) + rowj := F.Row(nil, j) + for k := 0; k < 3; k++ { + F.Set(i, k, rowj[k]) + F.Set(j, k, rowi[k]) + } +} + +// AddVec adds a vector to the coordmatrix A putting the result on the received. +// depending on whether the underlying matrix to coordmatrix +// is col or row major, it could add a col or a row vector. +func (F *Matrix) AddVec(A, vec *Matrix) { + ar, ac := A.Dims() + rr, rc := vec.Dims() + fr, fc := F.Dims() + if ac != rc || rr != 1 || ac != fc || ar != fr { + panic(ErrShape) + } + var B *Matrix + if A.Dense == F.Dense { //Using identical matrices for this should be A-OK, but something changed in gonum. I am not sure of why is it forbidden now. + B = Zeros(A.NVecs()) + B.Copy(A) + } else { + B = A + } + for i := 0; i < ar; i++ { + j := B.VecView(i) + f := F.VecView(i) + f.Dense.Add(j.Dense, vec.Dense) + } +} + +// DelRow deletes a row in matrix A, placing the results +// in the receiver. Equivalent to DelVec for compatibility. +func (F *Matrix) DelRow(A *Matrix, i int) { + F.DelVec(A, i) +} + +// DelVec deletes a (row) vector in matrix A, placing the results +// in the receiver. +func (F *Matrix) DelVec(A *Matrix, i int) { + ar, ac := A.Dims() + fr, fc := F.Dims() + if i >= ar || fc != ac || fr != (ar-1) { + panic(ErrShape) + } + tempA1 := A.View(0, 0, i, ac) + tempF1 := F.View(0, 0, i, ac) + tempF1.Copy(tempA1) + //now the other part + // if i != ar-1 { + //fmt.Println(""options"", ar, i, ar-i-1) + if i < ar-1 { + tempA2 := A.View(i+1, 0, ar-i-1, ac) //The magic happens here + tempF2 := F.View(i, 0, ar-i-1, fc) + tempF2.Copy(tempA2) + } +} + +// NVecs return the number of (row) vectors in F. +func (F *Matrix) NVecs() int { + r, c := F.Dims() + if c != 3 { + panic(ErrNotXx3Matrix) + } + return r + +} + +// Len return the number of (row) vectors in F. +// Equivalent to NVecs, but more in line with Go APIS. +func (F *Matrix) Len() int { + return F.NVecs() +} + +// ScaleByRow scales each coordinates in the A by the coordinate in the row-vector coord. +// The result is put in F. This is the old name fo the function, now called ScaleByVec. It is kept for compatibility +func (F *Matrix) ScaleByRow(A, coord *Matrix) { + F.ScaleByVec(A, coord) +} + +// SetVecs sets the vector F[clist[i]] to the vector A[i], for all indexes i in clist. +// nth vector of A. Indexes i must be positive or 0 +func (F *Matrix) SetVecs(A *Matrix, clist []int) { + ar, ac := A.Dims() + fr, fc := F.Dims() + if ac != fc || fr < len(clist) || ar < len(clist) { + panic(ErrShape) + } + for key, val := range clist { + for j := 0; j < ac; j++ { + F.Set(val, j, A.At(key, j)) //This will panic if an index is less than zero, which is fine. + } + } +} + +// SomeVecs puts in the receiver copy of the ith rows of matrix A, +// where i-s are the numbers in clist. The rows are in the same order +// than the clist. The numbers in clist must be positive or zero. +func (F *Matrix) SomeVecs(A *Matrix, clist []int) { + _, ac := A.Dims() + // fr, fc := F.Dims() + // if ac != fc || fr != len(clist) || ar < len(clist) { + // panic(ErrShape) + // } + for key, val := range clist { + for j := 0; j < ac; j++ { + F.Set(key, j, A.At(val, j)) + } + } +} + +// SomeVecsSafe puts in the receiver a copy of the ith vectors of matrix A, +// where i-s are the numbers in clist. The vectors are in the same order +// than the clist. It will return on error in case of most problems, but it +// could panic in corner cases. +func (F *Matrix) SomeVecsSafe(A *Matrix, clist []int) error { + var err error + defer func() { + if r := recover(); r != nil { + switch e := r.(type) { + case PanicMsg: + err = fmt.Errorf(""SomeVecSafe: %s: %s"", ErrGonum, e) + case mat.Error: + err = fmt.Errorf(""SomeVecsSafe: %s"", e) + default: + panic(r) + } + } + }() + F.SomeVecs(A, clist) + return err +} + +// StackVec puts in F a matrix consistent of A over B or A to the left of B. +func (F *Matrix) StackVec(A, B *Matrix) { + F.Stack(A, B) +} + +// String returns a neat string representation of a Matrix +func (F *Matrix) String() string { + r, c := F.Dims() + v := make([]string, r+2, r+2) + v[0] = ""\n["" + v[len(v)-1] = "" ]"" + row := make([]float64, c, c) + for i := 0; i < r; i++ { + F.Row(row, i) //now row has a slice witht he row i + if i == 0 { + v[i+1] = fmt.Sprintf(""%6.2f %6.2f %6.2f\n"", row[0], row[1], row[2]) + continue + } else if i == r-1 { + v[i+1] = fmt.Sprintf("" %6.2f %6.2f %6.2f"", row[0], row[1], row[2]) + continue + } else { + v[i+1] = fmt.Sprintf("" %6.2f %6.2f %6.2f\n"", row[0], row[1], row[2]) + } + } + v[len(v)-2] = strings.Replace(v[len(v)-2], ""\n"", """", 1) + return strings.Join(v, """") +} + +// SubVec subtracts the vector to each vector of the matrix A, putting +// the result on the receiver. Panics if matrices are mismatched. It will not +// work if A and row reference to the same Matrix. +func (F *Matrix) SubVec(A, vec *Matrix) { + vec.Scale(-1, vec) + F.AddVec(A, vec) + vec.Scale(-1, vec) +} + +// Cross puts the cross product of the first vecs of a and b in the first vec of F. Panics if error. +func (F *Matrix) Cross(a, b *Matrix) { + if a.NVecs() < 1 || b.NVecs() < 1 || F.NVecs() < 1 { + panic(ErrNoCrossProduct) + } + //I ask for Matrix instead of Matrix, even though I only need the At method. + //This is so I dont need to ensure that the rows are taken, and thus I dont need to break the + //API if the matrices become col-major. + F.Set(0, 0, a.At(0, 1)*b.At(0, 2)-a.At(0, 2)*b.At(0, 1)) + F.Set(0, 1, a.At(0, 2)*b.At(0, 0)-a.At(0, 0)*b.At(0, 2)) + F.Set(0, 2, a.At(0, 0)*b.At(0, 1)-a.At(0, 1)*b.At(0, 0)) +} + +//METHODS Not Vec specific. + +// AddFloat puts in the receiver a matrix which elements are +// those of matrix A plus the float B. +func (F *Matrix) AddFloat(A *Matrix, B float64) { + ar, ac := A.Dims() + if F != A { + F.Copy(A) + } + for i := 0; i < ar; i++ { + for j := 0; j < ac; j++ { + F.Set(i, j, A.At(i, j)+B) + } + } +} + +// AddRow adds the row vector row to each row of the matrix A, putting +// the result on the receiver. Panics if matrices are mismatched. It will not work if A and row +// reference to the same Matrix. +func (F *Matrix) AddRow(A, row *Matrix) { + F.AddVec(A, row) +} + +// ScaleByCol scales each column of matrix A by Col, putting the result +// in the received. +func (F *Matrix) ScaleByCol(A, Col mat.Matrix) { + ar, ac := A.Dims() + cr, cc := Col.Dims() + fr, fc := F.Dims() + if ar != cr || cc > 1 || ar != fr || ac != fc { + panic(ErrShape) + } + if F != A { + F.Copy(A) + } + for i := 0; i < ac; i++ { + temp := F.ColView(i) + + temp.Dense.MulElem(temp.Dense, Col) + } + +} + +// ScaleByVec scales each column of matrix A by Vec, putting the result +// in the received. +func (F *Matrix) ScaleByVec(A, Vec *Matrix) { + ar, ac := A.Dims() + rr, rc := Vec.Dims() + fr, fc := F.Dims() + if ac != rc || rr != 1 || ar != fr || ac != fc { + panic(ErrShape) + } + // if F != A { + // F.Copy(A) + // } + for i := 0; i < ac; i++ { + temp := F.RowView(i) + temp.Dense.MulElem(temp.Dense, Vec.Dense) + } +} + +// RowView puts a view of the given row of the matrix in the receiver +// Equivalent to VecView +func (F *Matrix) RowView(i int) *Matrix { + return F.VecView(i) +} + +// SubRow subtracts the row vector row to each row of the matrix A, putting +// the result on the receiver. Panics if matrices are mismatched. It will not +// work if A and row reference to the same Matrix. +func (F *Matrix) SubRow(A, row *Matrix) { + F.SubVec(A, row) +} + +// Unit puts in the receiver the unit vector pointing in the same +// direction as the vector A (A divided by its norm). +func (F *Matrix) Unit(A *Matrix) { + if A.Dense != F.Dense { + F.Copy(A) + } + norm := 1.0 / F.Norm(2) + F.Scale(norm, F) +} + +// KronekerDelta is a naive implementation of the kroneker delta function. +func KronekerDelta(a, b, epsilon float64) float64 { + if epsilon < 0 { + epsilon = appzero + } + if math.Abs(a-b) <= epsilon { + return 1 + } + return 0 +} +","Go" +"Computational Biochemistry","rmera/gochem","v3/init_goblas.go",".go","1244","40","// +build ignore + +/* + * init_goblas.go, part of gochem. + * + * Copyright 2014 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + */ + +//The point of this is that the user can use compile tags to get their programs compiled with goblas or cblas. +//goblas is the default, the cblas tag being required to use, well, cblas. + +package v3 + +import ( + ""gonum.org/v1/gonum/blas/native"" + ""gonum.org/v1/gonum/mat"" +) + +func init() { + mat.Register(native.Blas{}) +} +","Go" +"Computational Biochemistry","rmera/gochem","chemplot/plot_test.go",".go","1906","65","/* + * plot_test.go + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + */ + +/*This provides some tests for the library functions requiring plotinum, in the form of little functions + * that have practical applications*/ + +package chemplot + +import ( + ""fmt"" + ""testing"" + + chem ""github.com/rmera/gochem"" +) + +//TestRama tests the Ramachandran plot functionality. +//it generates a Ramachandran plot for the chain A of the PDB 2c9v. +func TestRama(Te *testing.T) { + mol, err := chem.PDBFileRead(""../test/2c9v.pdb"", true) + if err != nil { + Te.Error(err) + } + ramalist, err := chem.RamaList(mol, ""A"", []int{0, -1}) //// + if err != nil { + Te.Error(err) + } + ramalist2, index := chem.RamaResidueFilter(ramalist, []string{}, false) // []string{""HIS"", ""GLY"", ""ALA"", ""VAL"", ""LYS"", ""CYS""}, true) + rama, err := chem.RamaCalc(mol.Coords[0], ramalist2) + if err != nil { + Te.Error(err) + } + var i int + for i = 0; i < len(ramalist); i++ { + if index[i] != -1 { + break + } + } + fmt.Println(""Rama"", rama, len(rama), len(ramalist), mol.Len()) + err = RamaPlot(rama, []int{index[i]}, ""Test Ramachandran"", ""../test/Rama"") + if err != nil { + Te.Error(err) + } + //PDBWrite(mol,""test/Used4Rama.pdb"") + //for the 3 residue I should get -131.99, 152.49. +} +","Go" +"Computational Biochemistry","rmera/gochem","chemplot/ramachandran.go",".go","7887","274","/* + * ramachandran.go, part of gochem + * + * Copyright 2012 Raul Mera + * + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 2.1 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + * +*/ +/***Dedicated to the long life of the Ven. Khenpo Phuntzok Tenzin Rinpoche***/ + +package chemplot + +import ( + ""fmt"" + ""image/color"" + ""math"" + + // ""strings"" + ""gonum.org/v1/plot"" + ""gonum.org/v1/plot/plotter"" + ""gonum.org/v1/plot/vg"" + ""gonum.org/v1/plot/vg/draw"" + // ""github.com/rmera/gochem"" + // ""github.com/rmera/gochem/v3"" +) + +const ( + ErrNilData = ""goChem/ChemPlot: Nil data given "" + ErrInconsistentData = ""goChem/ChemPlot: Inconsistent data length "" + ErrTooManyTags = ""goChem/ChemPlot: Maximun number of tagable residues is 4"" + ErrOutOfRange = ""goChem/ChemPlot: Index requested out of range"" +) + +type Error struct { + message string //The error message itself. + code string //the name of the QM program giving the problem, or empty string if none + function string //the function returning the error. + additional string //anything else! + critical bool +} + +const ( + glyphSize = 2.3 * vg.Millimeter + plotSide = 6 * vg.Inch +) + +func (err Error) Error() string { return fmt.Sprintf(""%s Message: %s"", err.function, err.message) } + +func (err Error) Code() string { return err.code } //May not be needed + +func (err Error) FunctionName() string { return err.function } + +func (err Error) Critical() bool { return err.critical } + +func basicRamaPlot(title string) (*plot.Plot, error) { + p, err := plot.New() + if err != nil { + return nil, err + } + p.Title.Padding = vg.Millimeter * 3 + p.Title.Text = title //""Ramachandran plot"" + p.X.Label.Text = ""Phi"" + p.Y.Label.Text = ""Psi"" + //Constant axes + p.X.Min = -180 + p.X.Max = 180 + p.Y.Min = -180 + p.Y.Max = 180 + p.Add(plotter.NewGrid()) + return p, nil + +} + +// RamaPlotParts produces plots, in png format for the ramachandran data (phi and psi dihedrals) +// contained in data. Data points in tag (maximun 4) are highlighted in the plot. +// the extension must be included in plotname. Returns an error or nil. In RamaPlotParts +// The data is divided in several slices, where each is represented differently in the plot +func RamaPlotParts(data [][][]float64, tag [][]int, title, plotname string) error { + var err error + if data == nil { + return Error{ErrNilData, """", ""RamaPlot"", """", true} + } + // Create a new plot, set its title and + // axis labels. + p, err2 := basicRamaPlot(title) + if err2 != nil { + return Error{err2.Error(), """", ""RamaPlotParts"", """", true} + } + var tagged int + temp := make(plotter.XYs, 1) //len(val)) + for key, val := range data { + // fmt.Println(key, len(val)) + for k, v := range val { + temp[0].X = v[0] + temp[0].Y = v[1] + // Make a scatter plotter and set its style. + s, err := plotter.NewScatter(temp) //(pts) + if err != nil { + return Error{err.Error(), """", ""RamaPlotParts"", """", true} + + } + s.GlyphStyle.Radius = glyphSize + if tag != nil { + if len(tag) < len(data) { + return Error{ErrInconsistentData, """", ""RamaPlotParts"", ""If a non-nil tag slice is provided it must contain an element (which can be nil) for each element in the dihedral slice"", true} + } + if tag[key] != nil && isInInt(tag[key], k) { + s.GlyphStyle.Shape, err = getShape(tagged) + tagged++ + } + } + //set the colors + r, g, b := colors(key, len(data)-1) + // fmt.Println(""DATA POINT"", key, ""color"", r, g, b) + s.GlyphStyle.Color = color.RGBA{R: r, B: b, G: g, A: 255} + //The tagging procedure is a bit complex. + p.Add(s) + } + + } + filename := fmt.Sprintf(""%s.png"", plotname) + //here I intentionally shadow err. + if err := p.Save(6*vg.Inch, 6*vg.Inch, filename); err != nil { + return Error{err2.Error(), """", ""RamaPlotParts"", """", true} + } + + return err +} + +//takes hue (0-360), v and s (0-1), returns r,g,b (0-255) +func iHVS2RGB(h, v, s float64) (uint8, uint8, uint8) { + var i, f, p, q, t float64 + var r, g, b float64 + maxcolor := 255.0 + conversion := maxcolor * v + if s == 0.0 { + return uint8(conversion), uint8(conversion), uint8(conversion) + } + //conversion:=math.Sqrt(3*math.Pow(maxcolor,2))*v + h = h / 60 + i = math.Floor(h) + f = h - i + p = v * (1 - s) + q = v * (1 - s*f) + t = v * (1 - s*(1-f)) + switch int(i) { + case 0: + r = v + g = t + b = p + case 1: + r = q + g = v + b = p + case 2: + r = p + g = v + b = t + case 3: + r = p + g = q + b = v + case 4: + r = t + g = p + b = v + default: //case 5 + r = v + g = p + b = q + } + + r = r * conversion + g = g * conversion + b = b * conversion + return uint8(r), uint8(g), uint8(b) //just a test +} + +//colors assigns an color to the number key depending +//on its place in a linear interpolation from 0 to steps +//the colors go by decreasing hue with step, from 0 to 240 +//we stop at a hue of 240 to avoid violet colors that can be +//confusing +//meaning that keys closer to 0 will be blue, while keys close +//to steps will be red. +func colors(key, steps int) (r, g, b uint8) { + const MAXHUE float64 = 240.0 + norm := MAXHUE / float64(steps) + hp := float64((float64(key) * norm)) + var h float64 + h = MAXHUE - hp //we invert the order + s := 1.0 + v := 1.0 + r, g, b = iHVS2RGB(h, v, s) + return r, g, b +} + +// RamaPlot Produces plots, in png format for the ramachandran data (psi and phi dihedrals) +// contained in data. Data points in tag (maximun 4) are highlighted in the plot. +// the extension must be included in plotname. Returns an error or nil*/ +func RamaPlot(data [][]float64, tag []int, title, plotname string) error { + var err error + if data == nil { + return Error{ErrNilData, """", ""RamaPlot"", """", true} + } + // Create a new plot, set its title and + // axis labels. + p, err := basicRamaPlot(title) + if err != nil { + return Error{err.Error(), """", ""RamaPlot"", """", true} + + } + temp := make(plotter.XYs, 1) + var tagged int //How many residues have been tagged? + for key, val := range data { + temp[0].X = val[0] + temp[0].Y = val[1] + // Make a scatter plotter and set its style. + s, err := plotter.NewScatter(temp) //(pts) + if err != nil { + return Error{err.Error(), """", ""RamaPlot"", """", true} + } + r, g, b := colors(key, len(data)-1) + s.GlyphStyle.Radius = glyphSize + if tag != nil && isInInt(tag, key) { + //We don't check the error here. We will just get a default glyph. + s.GlyphStyle.Shape, err = getShape(tagged) + tagged++ + } + // fmt.Println(""colors rgb"", r,g,b) + s.GlyphStyle.Color = color.RGBA{R: r, B: b, G: g, A: 255} + // fmt.Println(r,b,g, key, norm, len(data)) ////////////////////////// + // Add the plotter + p.Add(s) + } + // Save the plot to a PNG file. + filename := fmt.Sprintf(""%s.png"", plotname) + //here I intentionally shadow err. + if err := p.Save(6*vg.Inch, 6*vg.Inch, filename); err != nil { + return Error{err.Error(), """", ""RamaPlot"", """", true} + } + return err +} + +func getShape(tagged int) (draw.GlyphDrawer, error) { + switch tagged { + case 0: + return draw.PyramidGlyph{}, nil + case 1: + return draw.CircleGlyph{}, nil + case 2: + return draw.SquareGlyph{}, nil + case 3: + return draw.CrossGlyph{}, nil + default: + return draw.RingGlyph{}, Error{ErrTooManyTags, """", ""getShape"", """", false} // you can still ignore the error and will get just the regular glyph (your residue will not be tagegd) + } +} +","Go" +"Computational Biochemistry","rmera/gochem","chemplot/plotutils.go",".go","561","31","package chemplot + +//Some internal convenience functions. + +//isIn is a helper for the RamaList function, +//returns true if test is in container, false otherwise. +func isInInt(container []int, test int) bool { + if container == nil { + return false + } + for _, i := range container { + if test == i { + return true + } + } + return false +} + +//Same as the previous, but with strings. +func isInString(container []string, test string) bool { + if container == nil { + return false + } + for _, i := range container { + if test == i { + return true + } + } + return false +} +","Go" +"Computational Biochemistry","rmera/gochem","chemgraph/graph.go",".go","5203","249","package chemgraph + +import ( + ""fmt"" + ""math"" + + chem ""github.com/rmera/gochem"" + ""gonum.org/v1/gonum/graph"" +) + +type Atom struct { + *chem.Atom + Bonds []*Bond + IDFunc func(*Atom) int64 +} + +func (A *Atom) ID() int64 { + if A.IDFunc == nil { + return int64(A.Index()) + } + return A.IDFunc(A) +} + +func (A *Atom) AtID() int { + return A.Atom.ID +} + +type Bond struct { + *chem.Bond + At1, At2 *Atom + Weightfunc func(*Bond) float64 +} + +func (B *Bond) Weight() float64 { + if B.Weightfunc == nil { + return B.Energy + } + return B.Weightfunc(B) +} + +func (B *Bond) From() graph.Node { + return B.At1 +} + +func (B *Bond) To() graph.Node { + return B.At2 +} + +// I'll try to just switch them in place, as bonds are not directional +// look here if you have issues +func (B *Bond) ReversedEdge() graph.Edge { + B.At1, B.At2 = B.At2, B.At1 + return B +} + +type Bonds []*Bond + +func (B Bonds) Len() int { + return len(B) +} +func (B Bonds) Contains(index int) bool { + for _, b := range B { + if b.Index == index { + return true + } + } + return false +} + +// Implements gonum.graph.Nodes +type Atoms struct { + Atoms []*Atom + curr int +} + +func (A *Atoms) Len() int { + return len(A.Atoms) +} +func (A *Atoms) Reset() { + A.curr = 0 +} +func (A *Atoms) Next() bool { + if A.curr >= len(A.Atoms)-1 { + return false + } + A.curr++ + return true +} +func (A *Atoms) Node() graph.Node { + return A.Atoms[A.curr] +} + +// implements Gonum graph.Graph and graph.Weighted interfaces +type Topology struct { + *chem.Topology + Bonds + *Atoms +} + +func (T *Topology) Nodes() *Atoms { + if T.Atoms.Len() == 0 { + panic(""Topology has no atoms"") + } + return T.Atoms +} + +func (T *Topology) From(id int64) graph.Nodes { + ret := make([]*Atom, 0) + for _, b := range T.Bonds { + ///undirected graph + if b.From().ID() == id || b.To().ID() == id { + ret = append(ret, b.To().(*Atom)) + } + } + return &Atoms{curr: 0, Atoms: ret} +} + +func (T *Topology) HasEdgeBetween(id1, id2 int64) bool { + for _, b := range T.Bonds { + if (b.From().ID() == id1 && b.To().ID() == id2) || (b.From().ID() == id2 && b.To().ID() == id1) { + return true + } + } + return false +} + +func (T *Topology) WeightedEdgeBetween(id1, id2 int64) *Bond { + for _, b := range T.Bonds { + if (b.From().ID() == id1 && b.To().ID() == id2) || (b.From().ID() == id2 && b.To().ID() == id1) { + return b + } + } + return nil +} + +func (T *Topology) Edge(id1, id2 int64) graph.Edge { + for _, b := range T.Bonds { + //I'm making the graph always undirected + if (b.From().ID() == id1 && b.To().ID() == id2) || (b.From().ID() == id2 && b.To().ID() == id1) { + return b + } + } + return nil +} + +func (T *Topology) WeightedEdge(id1, id2 int64) graph.Edge { + return T.Edge(id1, id2) +} + +func (T *Topology) Weight(id1, id2 int64) (w float64, ok bool) { + if id1 == id2 { + return 0.0, true + } + b := T.Edge(id1, id2) + if b == nil { + return -1, false + } + return b.(*Bond).Weight(), true +} + +// For each edge from A1->A2 adds a corresponding, equal edge from A2->A1 +func (T *Topology) SymmetrizePath() { + bonds := make([]*Bond, 0, len(T.Bonds)) + for _, v := range T.Bonds { + b := new(Bond) + b.Bond = v.Bond + b.At1 = v.At2 + b.At2 = v.At1 + b.Weightfunc = v.Weightfunc + bonds = append(bonds, b) + T.Atoms.Atoms[b.At1.Index()].Bonds = append(T.Atoms.Atoms[b.At1.Index()].Bonds, b) + T.Atoms.Atoms[b.At2.Index()].Bonds = append(T.Atoms.Atoms[b.At2.Index()].Bonds, b) + } + T.Bonds = append(T.Bonds, bonds...) +} + +// Will panic if a non-atom node is given +func (T *Topology) AddNode(n graph.Node) { + a := n.(*Atom) + a.SetIndex(len(T.Atoms.Atoms)) + T.Atoms.Atoms = append(T.Atoms.Atoms, a) + +} + +// Will panic if a non-bond edge is given +func (T *Topology) SetWeightedEdge(e graph.WeightedEdge) { + b := e.(*Bond) + T.Bonds = append(T.Bonds, b) +} + +func (T *Topology) NewNode() graph.Node { + a := new(Atom) + a.SetIndex(len(T.Atoms.Atoms)) + a.IDFunc = T.Atoms.Atoms[0].IDFunc + return a +} + +func atomID(Ats []*Atom, id int64) *Atom { + for _, v := range Ats { + if v.ID() == id { + return v + } + } + return nil +} + +func bondContains(B Bonds, index int) bool { + for _, b := range B { + if b.Index == index { + return true + } + } + return false +} + +// I might add an interafece to avoid using chem.Molecule +func TopologyFromChem(mol *chem.Molecule, IDFunc func(*Atom) int64, weightfunc func(*Bond) float64) *Topology { + mol.FillIndexes() + b := make([]*Bond, 0) + a := make([]*Atom, 0) + if IDFunc == nil { + IDFunc = func(A *Atom) int64 { return int64(A.Index()) } + } + if weightfunc == nil { + weightfunc = func(B *Bond) float64 { return 1 / math.Abs(B.Energy) } + } + for i := 0; i < mol.Len(); i++ { + at := mol.Atom(i) + a = append(a, &Atom{Atom: at, IDFunc: IDFunc}) + for _, v := range at.Bonds { + if !bondContains(b, v.Index) { + nb := &Bond{Bond: v, At1: &Atom{Atom: v.At1, IDFunc: IDFunc}, At2: &Atom{Atom: v.At2, IDFunc: IDFunc}, Weightfunc: weightfunc} + b = append(b, nb) + } + } + } + + for i, v := range b { + At1 := atomID(a, v.At1.ID()) + At2 := atomID(a, v.At2.ID()) + if At1 == nil || At2 == nil { + panic(fmt.Sprintf(""TopologyFromChem: Bond %d has at least one non-existent atom"", i)) + } + At1.Bonds = append(At1.Bonds, v) + At2.Bonds = append(At2.Bonds, v) + } + return &Topology{Topology: mol.Topology, Bonds: Bonds(b), Atoms: &Atoms{Atoms: a, curr: 0}} +} +","Go" +"Computational Biochemistry","rmera/gochem","protcap/doc.go",".go","235","4","package protcap + +/*pcap contains functions to cap peptides/aminoacidic residues cut from proteins, both the at the backbone (N- and C- capping) and (NOTE: The following is not yet implemented) the side chaing (CB- and -CA- capping)*/ +","Go" +"Computational Biochemistry","rmera/gochem","protcap/cap_test.go",".go","2101","57","package protcap + +import ( + ""fmt"" + ""testing"" + + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" +) + +const dir string = ""../test"" + +func errql(t *testing.T, err error) { + if err != nil { + t.Error(err) + } +} + +func TestCComplexCap(Te *testing.T) { + mol, err := chem.PDBFileRead(dir + ""/2c9vIOH.pdb"") + errql(Te, err) + sq := [][]int{{13, 14, 15}, {36, 37, 38}} + ch := []string{""A""} + cp := NewComplexBBCap() + for i, v := range sq { + pep := chem.Molecules2Atoms(mol, v, ch) + m1 := chem.NewTopology(0, 1) + m1.SomeAtoms(mol, pep) + c := v3.Zeros(len(pep)) + c.SomeVecs(mol.Coords[0], pep) + ccoord, cmol := cp.Cap(c, m1, v[0], v[len(v)-1], true) + chem.PDBFileWrite(fmt.Sprintf(""%s/results/cap%dPutLast.pdb"", dir, i), ccoord, cmol, nil) + cccoord, ccmol := cp.Cap(c, m1, v[0], v[len(v)-1], false) + chem.PDBFileWrite(fmt.Sprintf(""%s/results/cap%dPutMed.pdb"", dir, i), cccoord, ccmol, nil) + ccccoord, cccmol := BBHCap(c, m1, v[0], v[len(v)-1], true) + chem.PDBFileWrite(fmt.Sprintf(""%s/results/cap%dHPutLast.pdb"", dir, i), ccccoord, cccmol, nil) + cccccoord, ccccmol := BBHCap(c, m1, v[0], v[len(v)-1], false) + chem.PDBFileWrite(fmt.Sprintf(""%s/results/cap%dHPutMed.pdb"", dir, i), cccccoord, ccccmol, nil) + + wcord, wmol := cp.Cap(c, m1, -1, v[len(v)-1], true) + chem.PDBFileWrite(fmt.Sprintf(""%s/results/cap%dOnlyC.pdb"", dir, i), wcord, wmol, nil) + wwcord, wwmol := cp.Cap(c, m1, v[0], -1, false) + chem.PDBFileWrite(fmt.Sprintf(""%s/results/cap%dOnlyNPutMed.pdb"", dir, i), wwcord, wwmol, nil) + wwwcord, wwwmol := cp.Cap(c, m1, v[0], -1, true) + chem.PDBFileWrite(fmt.Sprintf(""%s/results/cap%dOnlyNPutLast.pdb"", dir, i), wwwcord, wwwmol, nil) + + xcord, xmol := BBHCap(c, m1, -1, v[len(v)-1], true) + chem.PDBFileWrite(fmt.Sprintf(""%s/results/cap%dHOnlyC.pdb"", dir, i), xcord, xmol, nil) + xxcord, xxmol := BBHCap(c, m1, v[0], -1, false) + chem.PDBFileWrite(fmt.Sprintf(""%s/results/cap%dHOnlyNPutMed.pdb"", dir, i), xxcord, xxmol, nil) + xxxcord, xxxmol := BBHCap(c, m1, v[0], -1, true) + chem.PDBFileWrite(fmt.Sprintf(""%s/results/cap%dHOnlyNPutLast.pdb"", dir, i), xxxcord, xxxmol, nil) + + } + +} +","Go" +"Computational Biochemistry","rmera/gochem","protcap/cap.go",".go","5940","210","package protcap + +import ( + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" +) + +type ComplexBBCap struct { + cp *capper +} + +func NewComplexBBCap() *ComplexBBCap { + r := new(ComplexBBCap) + r.cp = newCapper() + return r +} + +func (CC *ComplexBBCap) Cap(c *v3.Matrix, mol *chem.Topology, tocapN, tocapC int, putLast bool) (*v3.Matrix, *chem.Topology) { + return BBHCap(c, mol, tocapN, tocapC, putLast, CC.cp) + +} + +// CapBackBoneNoRef takes a sub-peptide, represented by c and mol, of a larger peptide and caps the N- side of the first residue +// with MolID tocapN and the C- side of the residue with MolID tocapC (they can both be the same residue). If you only want to cap +// one of both sides, you can give -1 for tocapN or tocapC to avoid adding an N-cap or C-cap, respectively. +// By default, the capping atom will be added to the end of the corresponding residue, but you can put it at the end of the +// c and mol by giving a true in putLast. +func BBHCap(c *v3.Matrix, mol *chem.Topology, tocapN, tocapC int, putLast bool, cp ...*capper) (*v3.Matrix, *chem.Topology) { + // new method to cap C=O & C-N. For C=O, take the vectors C-O & C-CA, make a copy of the C-CA one. Take the cross product between C-O and C-CA, and rotate the copy around the cross product until it is in the right position. (so ~60 degrees, I'd think). + var iN, iC, iCAN, iCAO, iO, iH int + Zero := v3.Zeros(1) + V1 := v3.Zeros(1) + V2 := v3.Zeros(1) + Cross := v3.Zeros(1) + Ncap := v3.Zeros(1) + Ccap := v3.Zeros(1) + + for i := 0; i < mol.Len(); i++ { + a := mol.Atom(i) + if tocapN == a.MolID { //slices.Contains(tocapN, a.MolID) { + switch a.Name { + case ""N"": + iN = i + case ""H"": + iH = i + case ""CA"": + iCAN = i + case ""CD"": + if a.MolName == ""PRO"" { + iH = i //proline doesn't have NH since the CD carbon form the lateral chain is + //bonded to the N. + } + } + } + if tocapC == a.MolID { //slices.Contains(tocapC, a.MolID) { + switch a.Name { + case ""C"": + // println(""C!"", i) + iC = i + case ""O"": + iO = i + case ""CA"": + iCAO = i + + } + } + } + rotangle := 120 * chem.Deg2Rad + //The N-Capping + placekeep := -1 + if tocapN > 0 { + nref := mol.Atom(iCAN) + place := nref.MolID + added := 0 + if putLast { + place = -1 * place + } else { + placekeep = place + } + + if len(cp) == 0 { + + Ncap = capGeo(c, Ncap, Zero, V1, V2, Cross, iN, iH, iCAN, -1*rotangle) + nc := new(chem.Atom) + nc.Name = ""HNA"" + nc.Symbol = ""H"" + nc.ID = mol.Len() + nc.SetIndex(nc.ID - 1) + nc.MolName = nref.MolName + nc.MolID = nref.MolID + nc.Chain = nref.Chain + c, mol = insertInMol(Ncap, c, []*chem.Atom{nc}, mol, place) + added = 1 + } else { + ats, tc := cp[0].NCap(c, iN, iH, iCAN, nref) + + c, mol = insertInMol(tc, c, ats.Atoms, mol, place) + added = 3 + } + //must update the C-cap indexes to consider the atoms we added in the middle + //as N-cap. placekeep will only be >0 if we add N-cap and we add it to the middle. + if placekeep > 0 { + if mol.Atom(iC).MolID > placekeep { //this check shouldn't be needed, ncap should always + //come before cap so the condition should always be true. + iC += added + iCAO += added + iO += added + } + } + + } + + //The C-Capping + if tocapC > 0 { + cref := mol.Atom(iCAO) + place := cref.MolID + if putLast { + place = -1 * place + } + + if len(cp) == 0 { + Ccap = capGeo(c, Ccap, Zero, V1, V2, Cross, iC, iO, iCAO, -1*rotangle) + //we now create the capping atoms to add to the topology + cc := new(chem.Atom) + cc.Name = ""HCP"" + cc.Symbol = ""H"" + cc.ID = mol.Len() + 1 + cc.SetIndex(cc.ID - 1) + cc.MolID = cref.MolID + cc.MolName = cref.MolName + cc.Chain = cref.Chain + c, mol = insertInMol(Ccap, c, []*chem.Atom{cc}, mol, place) + } else { + + ats, tc := cp[0].CCap(c, iC, iO, iCAO, cref) + c, mol = insertInMol(tc, c, ats.Atoms, mol, place) + } + + } + + return c, mol +} + +// inserts in in c and ina in mol as the last element of the +// residue with ID molID. If molID is not given or absent from mol, it will insert the atom at the end +func insertInMol(in, c *v3.Matrix, inat []*chem.Atom, mol *chem.Topology, molID int) (*v3.Matrix, *chem.Topology) { + posbefore := mol.Len() - 1 + // first := mol.Atom(0).MolID //this is to ensure that if the given molID is the first residue + //we don't pick the first atom in that residue, but the last + for i := 0; i < mol.Len(); i++ { + a := mol.Atom(i) + if a.MolID == molID+1 { // && a.MolID != first { + posbefore = i - 1 //here we are already in the residue we want. + //posbefore is the position before that, so we subtract one + break + } + } + + pre := c.View(0, 0, posbefore+1, 3) //posbefore is the index (0-based) of the last element, so posbefore+1 is the + //number of elements to take. + ret := v3.Zeros(c.Len() + in.Len()) + ret.Stack(pre, in) + start := posbefore + in.Len() + 1 + if posbefore < c.Len()-1 { + post := c.View(posbefore+1, 0, c.Len()-posbefore-1, 3) + for i := start; i < ret.Len(); i++ { + x := post.At(i-start, 0) + y := post.At(i-start, 1) + z := post.At(i-start, 2) + ret.Set(i, 0, x) + ret.Set(i, 1, y) + ret.Set(i, 2, z) + } + } + //now the atoms + ats := make([]*chem.Atom, 0, mol.Len()+len(inat)) + ats = append(ats, mol.Atoms[0:posbefore+1]...) + // inat2 := make([]*chem.Atom, 0, len(inat)) + for i, v := range inat { + w := new(chem.Atom) + w.Copy(v) + w.ID = posbefore + 1 + i + w.SetIndex(posbefore + i) + w.MolID = molID + if molID < 0 { + w.MolID = -1 * molID + } + ats = append(ats, w) + } + // ats = append(ats, inat2...) + if posbefore < c.Len()-1 { + ats = append(ats, mol.Atoms[posbefore+1:]...) + } + tret := chem.NewTopology(0, 1, ats) + return ret, tret +} + +func capGeo(c, Cap, Zero, V1, V2, Cross *v3.Matrix, izero, iv1, iv2 int, angle float64) *v3.Matrix { + Zero.Copy(c.VecView(izero)) + c.SubVec(c, Zero) + Cap.Copy(c.VecView(iv1)) + V1.Copy(Cap) + V2.Copy(c.VecView(iv2)) + Cross.Cross(V1, V2) + Cap = chem.Rotate(V1, Cap, Cross, angle) + Cap.AddVec(Cap, Zero) + c.AddVec(c, Zero) + return Cap +} +","Go" +"Computational Biochemistry","rmera/gochem","protcap/amide.go",".go","5064","133","package protcap + +import ( + ""strings"" + + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" +) + +// I think this is small enough and general enough to be worth hardcoding. It's a formamide molecule, optimized at the +// GFN2 level. +const capstr string = ""6\n\nC -4.92794702449458 1.89045342665579 -0.07921100123582\nO -4.70801763850576 3.04272114512478 -0.33847635299908\nN -4.42554476863113 1.23149344587307 0.98228022653061\nH -4.63126053618251 0.26640246053375 1.16518717959352\nH -3.81743860256653 1.72542300625019 1.61607772779290\nH -5.57786142961950 1.24519651556242 -0.69948777968212\n"" + +const CN float64 = 1.35 //C-N distance in amide (aprox) in A + +type capper struct { + mol *chem.Molecule + coord *v3.Matrix + coord2 *v3.Matrix + tmp *v3.Matrix + tmp2 *v3.Matrix + tmpNCap *v3.Matrix + tmpCCap *v3.Matrix + HNReplace int + HCReplace int + N int + C int + O int + HN int //the no-replaced one. +} + +func newCapper() *capper { + r := new(capper) + mol, err := chem.XYZRead(strings.NewReader(capstr)) //as this is hardcoded, thre really shouldn't be errors. + //I can just panic if that happens as it is surely a bug. + if err != nil { + panic(err) + } + r.tmp = v3.Zeros(1) + r.tmp2 = v3.Zeros(1) + r.tmpCCap = v3.Zeros(3) + r.tmpNCap = v3.Zeros(3) + r.mol = mol + r.coord = mol.Coords[0] + r.coord2 = v3.Zeros(r.coord.Len()) + r.HNReplace = 4 + r.HCReplace = 5 + r.C = 0 + r.N = 2 + r.O = 1 + r.HN = 3 + return r +} + +// Returns a matrix and topology containing the atoms and proper positions to C-cap the residue with coordinates +// in co, with indexes for the atoms C,O and CA given. firstID is the ID wanted for the first +// atom in the capping. sample is an atom from the residue to be capped, from which to get things like +// MolID, MolName and Chain. +func (c *capper) CCap(co *v3.Matrix, C, O, CA int, sample *chem.Atom) (*chem.Topology, *v3.Matrix) { + c.coord2.Copy(c.coord) + + //c.cap will superimpose atoms in such a way that we need to scale our C-H bond to be as long as an C-N bond + //so the superposition worke better. The displaced H atom will not be part of the returned molecule anyway. + + c.StretchToDist(c.HCReplace, c.C, CN, []int{c.HCReplace}, c.tmp2) + return c.cap(co, c.tmpCCap, []int{c.N, c.HN, c.HNReplace}, []int{c.HCReplace, c.C, c.O}, []int{CA, C, O}, sample) +} + +// Returns a matrix and topology containing the atoms and proper positions to N-cap the residue with coordinates +// in co, and with indexes for the atoms N,HN and CA given. firstID is the ID wanted for the first +// atom in the capping. sample is an atom from the residue to be capped, from which to get things like +// MolID, MolName and Chain. + +func (c *capper) NCap(co *v3.Matrix, N, HN, CA int, sample *chem.Atom) (*chem.Topology, *v3.Matrix) { + c.coord2.Copy(c.coord) + //c.cap will superimpose atoms in such a way that we need to scale our N-H bond to be as long as an C-N bond + //so the superposition worke better. The displaced H atom will not be part of the returned molecule anyway. + c.StretchToDist(c.HNReplace, c.N, CN, []int{c.HNReplace}, c.tmp2) + return c.cap(co, c.tmpNCap, []int{c.C, c.O, c.HCReplace}, []int{c.N, c.HN, c.HNReplace}, []int{N, HN, CA}, sample) + +} + +// This is the more general function used by CCap and NCap. +func (c *capper) cap(co *v3.Matrix, tmp *v3.Matrix, capindexes, supindexes, resindexes []int, sample *chem.Atom) (*chem.Topology, *v3.Matrix) { + c.coord2.Copy(c.coord) + // c.StretchToDist(c.HNReplace, c.N, CN, []int{c.HNReplace}, c.tmp2) + var err error + c.coord2, err = chem.Super(c.coord2, co, supindexes, resindexes) + if err != nil { + panic(""Superposition failed for capping:"" + err.Error()) //NOTE: Consider changing to return an error + } + ats := []*chem.Atom{c.mol.Atom(capindexes[0]), c.mol.Atom(capindexes[1]), c.mol.Atom(capindexes[2])} + // t := v3.Zeros(len(capindexes)) + tmp.SomeVecs(c.coord2, capindexes) + for _, v := range ats { + // v.ID = firstID + i + v.SetIndex(v.ID - 1) + v.MolID = sample.MolID + v.MolName = sample.MolName + v.Name = v.Name + ""C"" + v.Chain = sample.Chain + if len(v.Name) > 3 { + v.Name = v.Name[:3] //not to keep adding 'C's very time this is called. + } + + } + return chem.NewTopology(0, 1, ats), tmp +} + +// Moves all atoms in coord2 with indexes present in topull along the axis between the atoms +// i and j in coord2, until the distance between i and j (if one of them is include in topull) is +// dist. tmp is given for temp storage. +func (c *capper) StretchToDist(i, j int, dist float64, topull []int, tmp *v3.Matrix) float64 { + c.tmp.Sub(c.coord2.VecView(j), c.coord2.VecView(i)) + tdist := c.tmp.Norm(2) + c.tmp.Unit(c.tmp) + newmag := dist - tdist + c.tmp.Scale(newmag, c.tmp) + tmp.SomeVecs(c.coord2, topull) + tmp.AddVec(tmp, c.tmp) + c.coord2.SetVecs(tmp, topull) + return tdist +} + +// Returns a copy of c. +func (c *capper) Copy() *capper { + r := newCapper() + r.coord.Copy(r.coord) + r.coord2.Copy(r.coord2) + return r + +} +","Go" +"Computational Biochemistry","rmera/gochem","align/lovo_options.go",".go","4010","143","package align + +import ""runtime"" + +//Options contains various options for the LOVOnMostRigid and RMSDTraj functions +type Options struct { + begin int + skip int + cpus int + //The following are ignored by the RMSDTraj function + atomNames []string + chains []string + // nMostRigid int + writeTraj string //the name of a file to where the aligned trajectory will be written. Nothing will be written if empty. + lessThanRMSD float64 //instead of using a N for the most rigid, selects all residues with RMSD (the square root of the RMSD) < LessThanRMSD, in A. If >0, this overrrides NMostRigid + minimumN int //The smallest N we are willing to have. Only valid if LessThanRMSD is in use. +} + +//DefaultOptions return reasonable options for atomistic trajectories. +//It prepares a superposition of alpha carbons (CA) with all logical CPUs, +//trying to use for the superposition all CAs with RMSD lower than 1.0 A. +func DefaultOptions() *Options { + r := new(Options) + r.cpus = runtime.NumCPU() + //all available CPUs + r.atomNames = []string{""CA""} + r.chains = nil + // r.nMostRigid = -1 + r.lessThanRMSD = 1.0 + r.minimumN = 10 //just a reasonable value. + return r +} + +//DefaultCGOptions returns reasonable options for Martini trajectories. +func DefaultCGOptions() *Options { + r := DefaultOptions() + r.atomNames = []string{""BB""} + // r.Skip = 1000 //seems reasonable for CG, those trajectories are _long_. + return r + +} + +//Sets O.N to represent the perc percent of the residues +//in the sequence. It also requires seqlen, the total number of +//residues in the system +//func (O *Options) SetRigidPercent(perc int, seqlen int) { +// frac := float64(perc) / 100 +// O.nMostRigid = int(frac * float64(seqlen)) +// +//} + +//Returns the value of the +//func (O *Options) NMostRigid(N ...int) int { +// if len(N) < 0 || N[0] <= 0 { +// return O.nMostRigid +// } +// O.nMostRigid = N[0] +// return N[0] +// +//} + +//Returns the value of the first frame of the sequence to use, +//and sets it to a new value, if given. +func (O *Options) Begin(n ...int) int { + if len(n) > 0 || n[0] >= 0 { + O.begin = n[0] + } + return O.begin +} + +//Returns the value of the skipped frames between reads, +//and sets it to a new value, if given. +func (O *Options) Skip(n ...int) int { + if len(n) > 0 || n[0] >= 0 { + O.skip = n[0] + } + return O.skip +} + +//Returns the number of gorutines to be used, +//and sets it to a new value, if given. +func (O *Options) Cpus(n ...int) int { + if len(n) > 0 || n[0] > 0 { + O.cpus = n[0] + } + return O.cpus +} + +// +// The following options are ignored by the RMSDTraj function +// + +//Returns the minimum RMSD for an atom to be consiered +//as part of the alignment, and sets it to a new value, +//if given. +//if this flag is set to 0 or less, the regular LOVO +//convergency criterion is used. +func (O *Options) LessThanRMSD(rmsd ...float64) float64 { + if len(rmsd) > 0 { + O.lessThanRMSD = rmsd[0] + } + return O.lessThanRMSD + +} + +//Returns the smallest acceptable number of atoms +//to be returned by the alinment procedure. Only used +//if the LessThanRMSD is active. +//and sets it to a new value, if given. +func (O *Options) MinimumN(n ...int) int { + if len(n) > 0 && n[0] > 0 { + O.minimumN = n[0] + } + return O.minimumN +} + +//Returns the atom names consiered or the alignment +//and sets them to new values, if those are given. +func (O *Options) AtomNames(names ...[]string) []string { + if len(names) > 0 && len(names[0]) > 0 { + O.atomNames = names[0] + } + return O.atomNames +} + +//Returns the atom names consiered or the alignment +//and sets them to new values, if those are given. +func (O *Options) Chains(chains ...[]string) []string { + if len(chains) > 0 { + O.chains = chains[0] + } + return O.chains +} + +//Returns the name of the files where the aligned trajectory will be written, and sets it to a +//new value, if given. No trajectory file will be given if this value is set to an empty string. +func (O *Options) TrajName(name ...string) string { + if len(name) > 0 && name[0] != """" { + O.writeTraj = name[0] + } + return O.writeTraj +} +","Go" +"Computational Biochemistry","rmera/gochem","align/lovo.go",".go","14944","552","/* + * lovo.go, part of gochem. + * + * + * Copyright 2021 Raul Mera rauldotmeraatusachdotcl + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + * + */ + +package align + +import ( + // ""bufio"" + + ""fmt"" + ""log"" + ""math"" + ""sort"" + ""strings"" + + chem ""github.com/rmera/gochem"" + ""github.com/rmera/gochem/traj/dcd"" + ""github.com/rmera/gochem/traj/stf"" + ""github.com/rmera/gochem/traj/xtc"" + v3 ""github.com/rmera/gochem/v3"" +) + +//ConcTraje is an interface for a trajectory that can be read concurrently. +type ConcTrajCloser interface { + chem.ConcTraj + //closes the trajectory + Close() +} + +type MolIDandChain struct { + molid int + chain string +} + +func (M *MolIDandChain) String() string { + return fmt.Sprintf(""molid:%04d-chain:%s"", M.molid, M.chain) +} + +func (M *MolIDandChain) MolID() int { + return M.molid +} + +func (M *MolIDandChain) Chain() string { + return M.chain +} + +//LOVOReturn contains the information returned by LOVOnMostRigid +type LOVOReturn struct { + N int + FramesRead int //how many frames where actually read from the trajectory + Natoms []int //IDs of the N most rigid atoms + Nmols []*MolIDandChain //IDs for the N most rigid residues/molecules + RMSD []float64 //the RMSD for all residues, not only the N most rigid. + Iterations int //The iterations that were needed for convergency. + +} + +//String returns a string representation of the LOVOReturn object. +func (L *LOVOReturn) String() string { + retsl := make([]string, 0, len(L.Nmols)+2) + retsl = append(retsl, fmt.Sprintf(""N: %d, Frames read: %d, Iterations needed: %d, RMSD: %v, Natoms: %v, Nmols:"", L.N, L.FramesRead, L.Iterations, L.RMSD, L.Natoms)) + for _, v := range L.Nmols { + retsl = append(retsl, v.String()) + } + return strings.Join(retsl, "" "") +} + +//Implements Sort to sort by residue +func (L *LOVOReturn) Less(i, j int) bool { + return L.Nmols[i].molid < L.Nmols[j].molid +} + +func (L *LOVOReturn) Swap(i, j int) { + L.Nmols[i], L.Nmols[j] = L.Nmols[j], L.Nmols[i] +} +func (L *LOVOReturn) Len() int { + return len(L.Nmols) +} + +//PyMOLSel returns a string of text to create a PyMOL +//selection with the L.N most rigid residues from a LOVO +//calculation. +func (L *LOVOReturn) PyMOLSel() string { + pymolsele := ""select rigid,"" + for i, v := range L.Nmols { + if v.chain == """" { + pymolsele += fmt.Sprintf("" (resi %d) "", v.molid) + + } else { + pymolsele += fmt.Sprintf("" (resi %d and chain %s) "", v.molid, v.chain) + } + if i < len(L.Nmols)-1 { + pymolsele += ""or"" + } + } + return pymolsele + +} + +//Return the LOVO-selected residues in a format that +//can be pasted into the Gromacs gmx make_ndx tool +//to build a selection. The selection will incluede +//the residues from the chain given, and the chain ID, +//if given, or all residues matching, if not. +//The atomname (normally CA in atomistic simulations or +//BB in Martini ones is not added, mostly out of laziness +//and because it's easy to +//simply append "" & a CA"" or "" & a BB"" at the end of the string. +func (L *LOVOReturn) GMX(chain ...string) string { + data := L.Nmols + first := true + ret := """" + for _, v := range data { + if len(chain) > 0 && chain[0] != """" && chain[0] != v.Chain() { + continue + } + mid := v.MolID() + if first { + ret = fmt.Sprintf(""r %d "", mid) + first = false + continue + } + ret = fmt.Sprintf(""%s | r %d "", ret, mid) + } + + if len(chain) > 0 && chain[0] != """" { + ret = fmt.Sprintf(""%s & chain %s"", ret, chain[0]) + } + return ret +} + +func opentraj(name string) (ConcTrajCloser, error) { + t := strings.Split(name, ""."") + format := t[len(t)-1] + var err error + var ret ConcTrajCloser + switch strings.ToLower(format) { + case ""xtc"": + ret, err = xtc.New(name) + case ""dcd"": + ret, err = dcd.New(name) + case ""stf"": + ret, _, err = stf.New(name) + case ""pdb"": + ret, err = chem.PDBFileRead(name) + default: + ret = nil + err = fmt.Errorf(""Trajectory fromat not supported. Must have concurrent read support in goChem"") + } + return ret, err + +} + +//tolerance is the minimum amount of residues we are willing to use in the superposition. +func mobileLimit(limit float64, tolerance int, RMSD *rMSD) (int, float64) { + var n = 0 + for n < tolerance { + n = 0 + for ; n < RMSD.Len(); n++ { + if RMSD.RMSD(n) >= limit { + n-- + break + } + } + limit *= 1.1 + } + return n, limit +} + +//LOVO returns slices with the indexes of the n atoms and residues +//most rigid from mol, along the traj trajectory, considering only atoms with names in atomnames (normally, PDB names are used) +//and belonging to one of the chains in chains (only the first slice given in chains will be considered, if nothing is given, +//atoms from any chain will be considred. +//If you use this function in your research, please cite the references for the LOVO alignment method: +//10.1371/journal.pone.0119264. +//10.1186/1471-2105-8-306 +//If you use this function in a to-consumer program, please print a message asking to cite the references when the function is used. +func LOVO(mol chem.Atomer, ref *v3.Matrix, trajname string, opt ...*Options) (*LOVOReturn, error) { + var o *Options + if len(opt) == 0 { + o = DefaultOptions() + } else { + o = opt[0] + } + //we first do one iteration aligning the whole thing. + //these are atom, not residue indexes! + const defaultTopRigid int = 10 //by default we obtain the 1/topdefaultTopRigid top rigid + var fullindexes []int = res2atoms(mol, o.atomNames, o.chains, nil) + var printtraj string + printtraj = o.writeTraj + o.writeTraj = """" + indexesold := make([]int, len(fullindexes)) + copy(indexesold, fullindexes) + var RMSD *rMSD + var n int = len(fullindexes) + var totalframes int + var itercount int + var disagreement int + var prevlim float64 + var rmsd []float64 + for { + traj, err := opentraj(trajname) + if err != nil { + return nil, err + } + if disagreement == 1 && printtraj != """" { + o.writeTraj = printtraj + } + rmsd, totalframes, err = RMSDTraj(mol, ref, traj, indexesold[0:n], o) + if err != nil { + return nil, err + } + traj.Close() + itercount++ + RMSD = newRMSD(fullindexes, rmsdFilter(rmsd, fullindexes)) + RMSD.SortBy(""rmsd"") + var newlim float64 + if o.lessThanRMSD > 0 { + n, newlim = mobileLimit(o.lessThanRMSD, o.minimumN, RMSD) + } + indexes := RMSD.MolIDsCopy() + //There is a difference between the original paper and this implementation. + //In the original paper, the criterion for convergency is the sum of MSD of the phi*N most rigid atoms + //Here I simply check that the identity of those phi*N atoms has converged. + //I think it is completely equivalent. + if sameElementsInt(indexes[0:n], indexesold[0:n]) && (newlim == o.lessThanRMSD || approxEq(newlim, prevlim, 0.01)) { + break //converged + } + prevlim = newlim + disagreement = disagreementInt(indexes[0:n], indexesold[0:n]) + indexesold = indexes + } + //Now indexes old should countain what we want + RMSD.SortBy(""molid"") + r := &LOVOReturn{N: n, Natoms: indexesold[0:n], Nmols: iDs2MolIDandChains(mol, indexesold[0:n]), RMSD: RMSD.rMSDs, FramesRead: totalframes, Iterations: itercount} + return r, nil + +} + +type rmsdandcoords struct { + rmsd []float64 + coords *v3.Matrix +} + +func concproc(v chan *v3.Matrix, ref, t *v3.Matrix, r chan *rmsdandcoords, indexes []int) { + //the errors that Super and MemRMSD can return all + //would be programming erros in this case, so I'll just turn them into panics. + var err2 error + c := <-v + cr, err2 := chem.Super(c, ref, indexes, indexes) + if err2 != nil { + panic(err2.Error()) + } + rmsd, err2 := chem.MemPerAtomRMSD(cr, ref, nil, nil, t) + if err2 != nil { + panic(err2.Error() + fmt.Sprintf(""Lengths: %d"", t.NVecs())) + } + ret := &rmsdandcoords{rmsd: rmsd, coords: cr} + r <- ret + +} + +//RMSDTraj returns the RMSD for all atoms in a structure, averaged over the trajectory traj. +//Frames are read in sets of cpus at the time: The read starts at the set begin/cpus and we skip a set every skip/cpu +//(the numbers are, of course, rounded). The RMSDs and the total number of frames read are returned, together with an error or nil. +func RMSDTraj(mol chem.Atomer, ref *v3.Matrix, traj chem.ConcTraj, indexes []int, o *Options) ([]float64, int, error) { + RMSD := make([]float64, mol.Len()) + var err error + chunksize := o.cpus + chunk := make([]*v3.Matrix, chunksize) + tmps := make([]*v3.Matrix, chunksize) + for i, _ := range chunk { + chunk[i] = v3.Zeros(mol.Len()) + tmps[i] = v3.Zeros(mol.Len()) + } + var wtraj *dcd.DCDWObj + if o.writeTraj != """" { + wtraj, err = dcd.NewWriter(o.writeTraj, mol.Len()) + if err != nil { + log.Printf(""Couldn't open %s for writing. Will not write aligned trajectory"", o.writeTraj) //no error handling here. If we can't open the file, we just don't write anything. + } else { + defer wtraj.Close() + + } + + } + begin := o.begin / chunksize //how many chunks to skip before begining. + skip := o.skip / chunksize //how many chunks to skip + results := make([]chan *rmsdandcoords, chunksize) + for i, _ := range results { + results[i] = make(chan *rmsdandcoords) + } + var chans []chan *v3.Matrix + var chunksread int = 0 + for read := 0; ; read++ { + if (read) < begin || (read)%(skip+1) != 0 { + c := make([]*v3.Matrix, chunksize) //all nil + _, err = traj.NextConc(c) + if err != nil { + break + } + } + chans, err = traj.NextConc(chunk) + if err != nil { + break + } + chunksread++ + for i, v := range chans { + go concproc(v, ref, tmps[i], results[i], indexes) + + } + for _, res := range results { + trmsd := <-res + for i, _ := range RMSD { + RMSD[i] += trmsd.rmsd[i] + } + if wtraj != nil { + wtraj.WNext(trmsd.coords) + } + } + + } + if err == nil { + log.Println(""Finished reading trajectory without a EOF signal. This shouldn't happen."") + } else if _, ok := err.(chem.LastFrameError); !ok { + return nil, -1, fmt.Errorf(""Error while reading trajectory, read %d sets of frames. Error: %s"", chunksread, err.Error()) + } + totalframes := float64(chunksread * chunksize) + for i, v := range RMSD { + RMSD[i] = v / totalframes + } + return RMSD, int(totalframes), nil +} + +type rMSD struct { + //Note that the default methods and basis vary with each program, and even + //for a given program they are NOT considered part of the API, so they can always change. + //This is unavoidable, as methods change with time + molIDs []int + rMSDs []float64 + residues int + lessbyMolIDs func(i, j int) bool + lessbyRMSDs func(i, j int) bool + sorting string +} + +func newRMSD(residues []int, iniRMSD ...[]float64) *rMSD { + ret := new(rMSD) + ret.residues = len(residues) + ret.molIDs = make([]int, len(residues)) + copy(ret.molIDs, residues) + if len(iniRMSD) > 0 { + M := iniRMSD[0] + if len(M) != ret.residues { + panic(""Inconsistent data, if given, the number of initial RMSD values must match the number of residues"") + } + ret.rMSDs = make([]float64, len(M)) + copy(ret.rMSDs, M) + + } + ret.lessbyMolIDs = func(i, j int) bool { return ret.molIDs[i] < ret.molIDs[j] } + ret.lessbyRMSDs = func(i, j int) bool { return ret.rMSDs[i] < ret.rMSDs[j] } + return ret +} + +//MolID returns the molecule identifier of the nth residue of the structure. +func (m *rMSD) MolIDsCopy(rets ...[]int) []int { + var ret []int + if len(rets) != 0 { + ret = rets[0] + } else { + + ret = make([]int, len(m.molIDs)) + } + copy(ret, m.molIDs) + // //By hand + // for i, v := range m.molIDs { + // ret[i] = v + // + // } + return ret //I'll just let it panic if the number given is too large. +} + +func (m *rMSD) Swap(i, j int) { + m.molIDs[i], m.molIDs[j] = m.molIDs[j], m.molIDs[i] + m.rMSDs[i], m.rMSDs[j] = m.rMSDs[j], m.rMSDs[i] +} + +//returns the ith RMSD in the current order +func (m *rMSD) RMSD(i int) float64 { + return m.rMSDs[i] +} + +func (m *rMSD) Len() int { + return m.residues +} + +func (m *rMSD) Less(i, j int) bool { + switch m.sorting { + case ""rmsd"": + return m.lessbyRMSDs(i, j) + default: + return m.lessbyMolIDs(i, j) + + } + +} + +func (m *rMSD) SortBy(sorting string) { + m.sorting = strings.ToLower(sorting) + sort.Stable(m) +} + +//helper functions + +func approxEq(i, j, epsilon float64) bool { + if math.Abs(i)-math.Abs(j) <= epsilon { + return true + } + return false + +} + +//returns true if t1 and t2 have the same elements +//(whether or not in the same order) and false otherwise. +func sameElementsInt(t1, t2 []int) bool { + if len(t1) != len(t2) { + return false + } + for _, v := range t1 { + if !isInInt(v, t2) { + return false + } + } + return true + +} + +func disagreementInt(t1, t2 []int) int { + if len(t1) != len(t2) { + log.Printf(""inCommonInt: Slices differ in size! %d %d"", len(t1), len(t2)) + return -1 + } + dis := make([]int, 0, len(t1)) + for _, v := range t1 { + if !isInInt(v, t2) { + dis = append(dis, v) + } + } + return len(dis) +} + +//isInInt is a helper for the RamaList function, +//returns true if test is in container, false otherwise. +func isInInt(test int, container []int) bool { + if container == nil { + return false + } + for _, i := range container { + if test == i { + return true + } + } + return false +} + +//Same as the previous, but with strings. +func isInString(test string, container []string) bool { + if container == nil { + return false + } + for _, i := range container { + if test == i { + return true + } + } + return false +} + +//Some internal convenience functions. + +//retuns the indexes in mol of the atoms with name in names and residue id (MolID) in res. +//if res is empty returns all atoms with name in names. +func res2atoms(mol chem.Atomer, names, chains []string, res []int) []int { + ret := make([]int, 0, len(res)) + for i := 0; i < mol.Len(); i++ { + a := mol.Atom(i) + if (res == nil || isInInt(a.MolID, res)) && isInString(a.Name, names) { + if len(chains) == 0 || isInString(a.Chain, chains) { + ret = append(ret, i) + } + } + } + return ret + +} + +//returns a slice of RMSDs where the values with an index not in indexes have been removed. +func rmsdFilter(rmsd []float64, indexes []int) []float64 { + ret := make([]float64, 0, len(indexes)) + for i, v := range rmsd { + if isInInt(i, indexes) { + ret = append(ret, v) + } + } + return ret + +} + +func isInMIDaC(s *MolIDandChain, c []*MolIDandChain) bool { + for _, v := range c { + if v.molid == s.molid && v.chain == s.chain { + return true + } + } + return false + +} + +func iDs2MolIDandChains(mol chem.Atomer, indexes []int) []*MolIDandChain { + ret := make([]*MolIDandChain, 0, len(indexes)) + for _, v := range indexes { + at := mol.Atom(v) + s := &MolIDandChain{molid: at.MolID, chain: at.Chain} + if !isInMIDaC(s, ret) { + ret = append(ret, s) + } + } + return ret + +} +","Go" +"Computational Biochemistry","rmera/gochem","align/lovo_test.go",".go","1592","60","/* + * lovo_test.go + * + * Copyright 2021 Raul Mera Adasme + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + */ +/* + * + * + */ + +package align + +import ( + ""fmt"" + ""testing"" + + chem ""github.com/rmera/gochem"" +) + +func TestLovo(Te *testing.T) { + path := ""../test"" //not a portable test, but I wanted a more ""realistic"" case. I'll change it for a more self contained test before + molname := ""/test_align.pdb"" + trajfilename := ""/test_align.xtc"" + + mol, err := chem.PDBFileRead(path+molname, false) + if err != nil { + fmt.Println(""There was an error!"", err.Error()) + Te.Error(err) + } + trajname := path + trajfilename + o := DefaultOptions() + // o.NMostRigid(10) + o.LessThanRMSD(1.0) + o.Skip(0) + o.Cpus(2) + o.TrajName(path + ""/aligned.dcd"") + ret, err := LOVO(mol, mol.Coords[0], trajname, o) + if err != nil { + Te.Error(err) + } + // fmt.Println(""Most rigid residues:"", ret.Nmols) + fmt.Println(ret.PyMOLSel()) + fmt.Println(ret.String()) + fmt.Println(ret.GMX(""A"")) +} +","Go" +"Computational Biochemistry","rmera/gochem","histo/histo_test.go",".go","524","24","package histo + +import ( + ""encoding/json"" + ""fmt"" + ""testing"" +) + +func TestHistoIO(Te *testing.T) { + fmt.Println(""Histogram JSON output test!"") + M := NewMatrix(3, 3, []float64{0, 1, 2, 3, 4, 8}) + M.Fill() + rawdata := []float64{1, 6, 3, 2, 4, 5, 7, 6, 3.5, 3, 5, 1, 1, 0, 0, 5, 8, 1, 2, 3, 44, 3, 7, 3, 1, 3, 5, 32, 1} + M.NewHisto(0, 1, nil, rawdata) + v := M.View(0, 1) + fmt.Println(v.String()) + j, err := json.Marshal(M) + fmt.Println(""JSON:"", string(j), err) + M2 := new(Matrix) + json.Unmarshal(j, M2) + fmt.Printf(""%v\n"", M2) + +} +","Go" +"Computational Biochemistry","rmera/gochem","histo/histo.go",".go","14555","561","package histo + +import ( + ""encoding/json"" + ""fmt"" + ""log"" + ""math"" + ""sort"" + ""strings"" + ""sync"" + + ""gonum.org/v1/gonum/floats"" + ""gonum.org/v1/gonum/stat"" +) + +//Combines 2 matrices element-wise using the function f, which should take 2 histograms to be +//combined and one more where the result of the operation is stored. +func MatrixCombine(f func(a, b, dest *Data), a, b, dest *Matrix) { + if a.rows != b.rows || a.cols != b.cols || a.rows != dest.rows || a.cols != dest.cols { + panic(""goChem/histo.MatrixMerge: Ill-formed matrices for merging"") + } + //This should work if they are both nil + if !(a.dividers == nil && b.dividers == nil) && !floats.Equal(a.dividers, b.dividers) { + panic(""goChem/histo.MatrixMerge: Matrices don't have the same dividers"") + } + for i, v := range dest.d { + f(a.d[i], b.d[i], v) + } +} + +//A matrix of histograms +type Matrix struct { + mu sync.Mutex + rows, cols int //total + d []*Data //row-major + dividers []float64 //if not nil, all histograms have the same dividers +} + +//NewMatrix returns a new matrix of *Data with r and c rows and column +//and dividers dividers. Dividers can be nil, in which case, elements +//of the matrix will not be forced to have the same dividers +func NewMatrix(r, c int, dividers []float64) *Matrix { + ret := new(Matrix) + ret.rows = r + ret.cols = c + ret.d = make([]*Data, r*c) + ret.dividers = dividers + return ret +} + +func (M *Matrix) Dims() (int, int) { + return M.rows, M.cols +} + +//Copies the dividers of the histogram +func (M *Matrix) CopyDividers(dest ...[]float64) []float64 { + if M.dividers == nil { + return nil + } + d := getCopySlice(len(M.dividers), dest...) + return floats.ScaleTo(d, 1, M.dividers) +} + +func (M *Matrix) String() string { + ret := fmt.Sprintf(""rows:%d cols:%d | Data:\n"", M.rows, M.cols) + t := make([]string, 0, len(M.d)) + for _, v := range M.d { + t = append(t, v.String()) + } + return ret + strings.Join(t, ""\n\n"") +} + +func (M *Matrix) MarshalJSON() ([]byte, error) { + j, err := json.Marshal(struct { + Rows int `json:""rows""` + Cols int `json:""cols""` + D []*Data `json:""data""` + Dividers []float64 `json:""dividers""` + }{ + Rows: M.rows, + Cols: M.cols, + D: M.d, + Dividers: M.dividers, + }) + if err != nil { + return nil, err + } + return j, nil +} + +func (M *Matrix) UnmarshalJSON(b []byte) error { + var a struct { + Rows int `json:""rows""` + Cols int `json:""cols""` + D []*Data `json:""data""` + Dividers []float64 `json:""dividers""` + } + + err := json.Unmarshal(b, &a) + if err != nil { + return err + } + M.rows = a.Rows + M.cols = a.Cols + M.d = a.D + M.dividers = a.Dividers + return nil +} + +//returns the index in the []*Data slice of a matrix given +//the row and column indexes. +//just to avoid fixing it in many places if I screw up +func (M *Matrix) rc2i(r, c int) int { + M.Check(r, c, true) + return M.cols*r + c +} + +//Fill fills the matrix with empty histograms +//If the matrix has a non-nil delimiters slice, +//that slice is used for all the histograms created +func (M *Matrix) Fill() { + for i := 0; i < M.rows; i++ { + for j := 0; j < M.cols; j++ { + M.NewHisto(i, j, M.dividers, nil) + } + + } +} + +//Check checks if the given row and column indexes are within range. +//if pan is given and true, it panics if either is out of range, +//otherwise, it returns an error. +func (M *Matrix) Check(r, c int, pan ...bool) error { + p := false + var err error + if len(pan) > 0 && pan[0] { + p = true + } + if r >= M.rows { + err = fmt.Errorf(""goChem/Histo: Row out of range"") + } + if c >= M.cols { + err = fmt.Errorf(""goChem/Histo: Column out of range"") + } + if err != nil && p { + panic(err.Error()) + } + return err +} + +//NewHisto Puts a new histogram in the r,c position in the matrix. Dividers can be nil, in which case, the matrix +//should have its dividers. If there are no dividers, or they don't match, the function will panic. +//rawdata can also be nil, in which case, an empty histogram will be put in the position. +func (M *Matrix) NewHisto(r, c int, dividers []float64, rawdata []float64, ID ...int) { + if dividers == nil { + if M.dividers != nil { + dividers = M.dividers + } else { + panic(""goChem/histo.Matrix.NewHisto: dividers not given, and can't be taken from current first element"") + } + } else if M.dividers != nil && !floats.Equal(M.dividers, dividers) { + //Maybe this should be returned as an error instead + log.Printf(""goChem/histo.Matrix.NewHisto: dividers given but don't match the dividers of the matrix. The matrix's dividers will be used."") + dividers = M.dividers + } + M.d[M.rc2i(r, c)] = NewData(dividers, rawdata, ID...) +} + +//View Returns a view of the histogram in the r,c position in the matrix +func (M *Matrix) View(r, c int) *Data { + return M.d[M.rc2i(r, c)] +} + +//Adds one or more data points to the histogram in the r,c position in the matrix +func (M *Matrix) AddData(r, c int, point ...float64) { + M.d[M.rc2i(r, c)].AddData(point...) +} + +//Adds one or more data points to the histogram in the r,c position in the matrix +//it is concurrent safe +func (M *Matrix) AddDataCS(r, c int, point ...float64) { + M.mu.Lock() + M.d[M.rc2i(r, c)].AddData(point...) + M.mu.Unlock() +} + +//Normalize all the histograms in the matrix +func (M *Matrix) NormalizeAll() { + for _, v := range M.d { + v.Normalize() + } +} + +//Un-normalize all the histograms in the matrix +func (M *Matrix) UnNormalizeAll() { + for _, v := range M.d { + v.UnNormalize() + } +} + +//Applies the f function to each element in the matrix, the results are returned as +//a [][]float64. Also returns error unpon failure, or nil. +func (M *Matrix) FromAll(f func(D *Data) (float64, error)) ([][]float64, error) { + r := make([][]float64, M.rows) + var err error + for i := 0; i < M.rows; i++ { + r[i] = make([]float64, M.cols) + for j := 0; j < M.cols; j++ { + r[i][j], err = f(M.d[M.rc2i(i, j)]) + if err != nil { + return nil, fmt.Errorf(""goChem/Histo.Matrix.FromAll: Error at %d, %d: %v"", i, j, err) + } + } + } + return r, nil +} + +//Applies the f function to each element in the matrix. Returns error unpon failure, or nil. +func (M *Matrix) ToAll(f func(D *Data) error) error { + var err error + for i := 0; i < M.rows; i++ { + for j := 0; j < M.cols; j++ { + err = f(M.d[M.rc2i(i, j)]) + if err != nil { + return fmt.Errorf(""goChem/Histo.Matrix.ToAll: Error at %d, %d: %v"", i, j, err) + } + + } + } + return nil +} + +type Data struct { + id int + normalized bool + total int + dividers []float64 + histo []float64 +} + +func (D *Data) MarshalJSON() ([]byte, error) { + j, err := json.Marshal(struct { + ID int `json:""id""` + Normalized bool `json:""normalized""` + Total int `json:""total""` + Dividers []float64 `json:""dividers""` + Histo []float64 `json:""histo""` + }{ + ID: D.id, + Normalized: D.normalized, + Total: D.total, + Dividers: D.dividers, + Histo: D.histo, + }) + if err != nil { + return nil, err + } + return j, nil +} + +func (D *Data) UnmarshalJSON(b []byte) error { + var a struct { + ID int `json:""id""` + Normalized bool `json:""normalized""` + Total int `json:""total""` + Dividers []float64 `json:""dividers""` + Histo []float64 `json:""histo""` + } + + err := json.Unmarshal(b, &a) + if err != nil { + return err + } + D.id = a.ID + D.normalized = a.Normalized + D.total = a.Total + D.dividers = a.Dividers + D.histo = a.Histo + return nil +} + +//ID returns the ID of the histogram +func (D *Data) ID() int { + return D.id +} + +//String prints a -hopefully- pretty string representation of +//the histogram. The representation uses 3 lines of thext +func (D *Data) String() string { + ret := fmt.Sprintf(""ID: %d, Normalized: %v, TotalData: %d\n"", D.id, D.normalized, D.total) + d := make([]string, 0, len(D.dividers)-1) + h := make([]string, 0, len(D.dividers)-1) + for i, v := range D.histo { + d = append(d, fmt.Sprintf(""%4.2f-%4.2f"", D.dividers[i], D.dividers[i+1])) + h = append(h, fmt.Sprintf(""%9.3f"", v)) + } + //fmt.Println(h, D.histo) ///////// + return ret + fmt.Sprintf(""%s\n%s"", strings.Join(d, "" ""), strings.Join(h, "" "")) + +} + +//Returns a new histogram from the dividers and rawdata given +//rawdata can be nil. In that case, an empty histogram is created. +//if an ID for the histogram is given, it will be set. If not, the ID will +//be set to -1. +func NewData(dividers []float64, rawdata []float64, ID ...int) *Data { + d := new(Data) + //I prefer to copy the slice to avoid somebody changing it from outside + d.dividers = make([]float64, len(dividers)) + for i, v := range dividers { + d.dividers[i] = v + } + d.histo = make([]float64, len(dividers)-1) + if rawdata != nil { + //d.total = len(rawdata) + d.ReHisto(d.dividers, rawdata) + //println(""not nil!"") /////// + } + d.id = -1 + if len(ID) > 0 { + d.id = ID[0] + } + return d + +} + +//Adds the given data point(s) to the histogram +func (M *Data) AddData(point ...float64) { + var norma bool + if M.normalized { + norma = true + M.UnNormalize() + } + for _, v := range point { + for j, w := range M.dividers { + //Values that are larger than the last divider are just omitted. + if j == len(M.dividers)-1 { + break + } + if w <= v && v < M.dividers[j+1] { + M.histo[j]++ + break + } + } + } + M.total += len(point) + //if it was normalized, we should return it to that state + if norma { + M.Normalize() + } +} + +//Normalized Returns true if the histogram is normalized +func (D *Data) Normalized() bool { + return D.normalized +} + +//Normalize normalizes the histogram +func (D *Data) Normalize() { + D.normaunnorma(true) +} + +//UnNormalize un-normalizes the histogram +func (D *Data) UnNormalize() { + D.normaunnorma(false) +} + +//normalizes or un-normalizes the histogram depending +//on whether normalize is true +func (D *Data) normaunnorma(normalize bool) { + if D.total <= 0 { + return + } + n := float64(D.total) + D.normalized = false + if normalize { + n = 1 / float64(D.total) + D.normalized = true + } + + floats.Scale(n, D.histo) + +} + +//Copies the dividers of the histogram +func (D *Data) CopyDividers(dest ...[]float64) []float64 { + d := getCopySlice(len(D.dividers), dest...) + return floats.ScaleTo(d, 1, D.dividers) +} + +func (D *Data) Copy(dest ...[]float64) []float64 { + d := getCopySlice(len(D.histo), dest...) + return floats.ScaleTo(d, 1, D.histo) +} + +func (D *Data) View() []float64 { + return D.histo +} + +//Add adds the histograms a and b putting the result in the receiver. +func (D *Data) Add(a, b *Data) { + D.dividers = a.CopyDividers(D.dividers) + if len(a.dividers) != len(b.dividers) { + panic(""goChem/Histo.Data.Add: Ill-formed histograms for addition"") + } + + for i, v := range a.dividers { + if v != b.dividers[i] { + panic(""goChem/Histo.Data.Add: Dividers must match in added histograms"") + } + if i == len(a.dividers)-1 { + break //a.histo has 1 less element than a.dividers, so we skip the next operation for the last one. + } + D.histo[i] = a.histo[i] + b.histo[i] + } +} + +//Sub substract the histograms a and b puting the results in the receiver +//if abs is given and true (only the first element is considered) +func (D *Data) Sub(a, b *Data, abs ...bool) { + f := func(a float64) float64 { return a } + if len(abs) > 0 && abs[0] { + f = func(a float64) float64 { return math.Abs(a) } + } + D.dividers = a.CopyDividers(D.dividers) + if len(a.dividers) != len(b.dividers) { + panic(""goChem/Histo.Data.Add: Ill-formed histograms for addition"") + } + + for i, v := range a.dividers { + if v != b.dividers[i] { + panic(""goChem/Histo.Data.Add: Dividers must match in added histograms"") + } + if i == len(a.dividers)-1 { + break //a.histo has 1 less element than a.dividers, so we skip the next operation for the last one. + } + + D.histo[i] = f(a.histo[i] - b.histo[i]) + } +} + +func (D *Data) Sum() float64 { + return floats.Sum(D.histo) +} + +func (D *Data) ReHisto(dividers, rawdata []float64) { + if rawdata != nil { + sort.Float64s(rawdata) + //stat.Histograms just panics instead of omitting the values that are off limits + //so we remove them here before the call. + maxi := sort.SearchFloat64s(rawdata, dividers[len(dividers)-1]) + mini := sort.SearchFloat64s(rawdata, dividers[0]) + if maxi < len(rawdata) { + rawdata = rawdata[:maxi] + } + if mini != 0 { + rawdata = rawdata[mini:] + } + + } + D.total = len(rawdata) //as this could have been modified + D.histo = stat.Histogram(nil, dividers, rawdata, nil) + //println(D.histo[0]) //////////// +} + +func getCopySlice(N int, dest ...[]float64) []float64 { + var d []float64 + if len(dest) > 0 && len(dest[0]) >= N { + d = dest[0] + if len(dest[0]) > N { + d = dest[0][:N] //floats.ScaleTo wants both slices to _match_ + } + } else { + d = make([]float64, N) + } + return d + +} + +//Some convenience functions + +func Integrate(lower, upper float64, dividers ...[]float64) func(*Data) (float64, error) { + var divs []float64 + if len(dividers) > 0 { + divs = dividers[0] + } + r := func(D *Data) (float64, error) { + if len(divs) == 0 { + divs = D.CopyDividers() + } + d := D.View() + if d == nil { + return 0, nil + } + var ret float64 + + for i, v := range d { + if divs[i+1] < lower { + continue + } + if divs[i+1] >= upper { + break + } + ret += v + } + return ret, nil + } + return r +} + +//returns the nquant quartile of the histogram. nquant is a float between 0 and 1 +func Quantile(nquant float64, dividers ...[]float64) func(*Data) (float64, error) { + f := func(p, w []float64) float64 { return stat.Quantile(nquant, stat.CumulantKind(4), p, w) } + + return StatFunc(f, dividers...) +} + +func Mean(dividers ...[]float64) func(*Data) (float64, error) { + return StatFunc(stat.Mean, dividers...) +} + +func StdDev(dividers ...[]float64) func(*Data) (float64, error) { + f := func(p, w []float64) float64 { + _, s := stat.MeanStdDev(p, w) + if math.IsNaN(s) || math.IsInf(s, 0) { + s = 0.0 + } + return s + } + return StatFunc(f, dividers...) +} + +//returns the results of the function f which takes a set of values and their weights (in this case, the values +// are the mean of the 2 limits of each histogram bin, and the weights are the value for that bin. +func StatFunc(f func(x, w []float64) float64, dividers ...[]float64) func(*Data) (float64, error) { + var divs []float64 + if len(dividers) > 0 { + divs = dividers[0] + } + r := func(D *Data) (float64, error) { + if len(divs) == 0 { + divs = D.CopyDividers() + } + // fmt.Println(divs) //////////////////////////////// + d := D.View() + if d == nil { + return 0, nil + } + var q float64 + points := make([]float64, 0, len(d)) + for i, _ := range d { + points = append(points, (divs[i+1]+divs[i])/2) + } + // fmt.Println(""points"", points, ""d"", d, ""\n"") //////////////// + q = f(points, d) + return q, nil + } + + return r +} +","Go" +"Computational Biochemistry","rmera/gochem","solv/solvation.go",".go","21705","731","/* + * solvation.go, part of gochem + * + * Copyright 2020 Raul Mera A. (raulpuntomeraatusachpuntocl) + * + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 2.1 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . + * + * +*/ + +package solv + +import ( + ""fmt"" + ""log"" + ""math"" + ""runtime"" + ""sort"" + ""slices"" + ""strings"" + + // ""sort"" + // ""strconv"" + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" + ""gonum.org/v1/gonum/mat"" +) + +const epsilon = 0.0001 + +func EllipsoidAxes(coords *v3.Matrix, epsilon float64, mol ...chem.Masser) ([]float64, error) { + var masses []float64 + var err2 error + var err error + if len(mol) < 0 { + masses = nil + } else { + masses, err = mol[0].Masses() + if err != nil { + masses = nil + err2 = err + } + } + moment, err := chem.MomentTensor(coords, masses) + if err != nil { + return nil, err + } + rhos, err := chem.Rhos(moment, epsilon) + if err != nil { + return nil, err + } + + return rhos, err2 +} + +// Options contains options for the RDF/MDDF calculation +type Options struct { + com bool + cpus int + step float64 + end float64 + skip int +} + +// Returns a Options with the default options. +func DefaultOptions() *Options { + ret := new(Options) + ret.com = false + ret.cpus = runtime.NumCPU() + ret.step = 0.1 + ret.end = 10 + ret.skip = 1 + return ret +} + +// Returns whether to use center of mass for solvent in the calculations +// and sets the value to the one given, if any +func (r *Options) COM(com ...bool) bool { + ret := r.com + if len(com) > 0 { + r.com = com[0] + } + return ret +} + +// Returns the current value of the Cpus options (the number of gorutines to +// use on the concurrent calculation) and sets it, if +// a valid value is given +func (r *Options) Cpus(cpus ...int) int { + ret := r.cpus + if len(cpus) > 0 && cpus[0] > 0 { + r.cpus = cpus[0] + } + return ret +} + +// Returns the skipped frames (for functions where it's applicable) and sets it, if +// a valid value is given +func (r *Options) Skip(skip ...int) int { + ret := r.skip + if len(skip) > 0 && skip[0] > 0 { + r.skip = skip[0] + } + return ret +} + +// Returns the distance step to be used in the RDF/MDDF calculation +// and sets if to a value, if a valid value is given +func (r *Options) Step(step ...float64) float64 { + ret := r.step + if len(step) > 0 && step[0] > 0 { + r.step = step[0] + } + return ret +} + +// Returns the maximum distance from the solute to be considered +// in the RDF/MDDF calculation and sets if to a value, if given +func (r *Options) End(end ...float64) float64 { + ret := r.end + if len(end) > 0 && end[0] > 0 { + r.end = end[0] + } + return ret +} + +// ConcMolRDF calculates the RDF for a trajectory given the indexes of the solute atoms, the solvent molecule name, the step for the ""layers"" and the cutoff. +// It processes several frames of the trajectory concurrently, depending on the logical CPUs available. +// The code includes some extra comments, so it can be used as a template for concurrent trajectory processing. +func ConcMolRDF(traj chem.ConcTraj, mol *chem.Molecule, refindexes []int, residues []string, options ...*Options) ([]float64, []float64, error) { + var o *Options + if len(options) > 0 { + o = options[0] + } else { + o = DefaultOptions() + } + A := 1.0 + B := 1.0 + if mol.Len() > 1 { + scoords := v3.Zeros(len(refindexes)) + scoords.SomeVecs(mol.Coords[0], refindexes) + smol := chem.NewTopology(0, 1) + smol.SomeAtoms(mol, refindexes) + elip, err := EllipsoidAxes(scoords, epsilon, smol) + if err != nil { + return nil, nil, err + } + //fmt.Println(elip, elip[0]*elip[1]*elip[2]) ///////////////////////////////// + A = elip[0] / elip[2] + B = elip[1] / elip[2] + + } + + var ret []float64 + frames := make([]*v3.Matrix, o.cpus, o.cpus) + framesread := 0 + for i, _ := range frames { + frames[i] = v3.Zeros(traj.Len()) + } + results := make([]chan []float64, len(frames)) + for i, _ := range results { + results[i] = make(chan []float64) + } + var err error + for i := 0; ; i++ { + if err != nil { //if we got a LastFrameError in the previous + break + } + coordchans, err := traj.NextConc(frames) //we get a slice of channels, each of which will receive a frame. They are sorted by the frame they receive. + if err != nil { + if err, ok := err.(chem.LastFrameError); ok { + if coordchans == nil { + break + } + } else { + if err, ok := err.(chem.Error); ok { + err.Decorate(fmt.Sprintf(""ConcMolRDF, failed when reading the %d th frame"", i)) + return nil, nil, err + } + return nil, nil, err // somehow it wasn't a chem.Error. This should never happen. + } + } + for key, channel := range coordchans { + go unitRDF(channel, results[key], mol, refindexes, residues, o) //we give each of the channels we got from NextConc to a gorutine ""worker"" that performs the analysis. We pass them a chan to transmit the results back. + } + //Here we go through the ""results"" channels, which are sorted by frame, so if we just iterate with a for, we'll get the results for the frames in the right order (not that it matters here). + for _, k := range results { + if k == nil { + break //shouldn't happen + } + rettemp := <-k + if len(rettemp) == 0 { //we ran out of frames + break + } + if ret == nil { + ret = make([]float64, len(rettemp)) + } + for i, v := range ret { + ret[i] = v + rettemp[i] + } + + framesread++ + } + } + //fmt.Println(A, B) ///////////// + ret, ret2, err := MDFFromCDF(ret, framesread, A, B, o.step) + return ret, ret2, err +} + +// The worker function for the RDF +func unitRDF(channelin chan *v3.Matrix, channelout chan []float64, mol chem.Atomer, refindexes []int, residues []string, o *Options) { + if channelin != nil { + temp := <-channelin + rdf := FrameUMolCRDF(temp, mol, refindexes, residues, o) + channelout <- rdf + } else { + channelout <- nil + } + return +} + +// MolRDF calculates the RDF for a trajectory given the indexes of the solute atoms, the solvent molecule name, the step for the ""layers"" and the cutoff. +// API BREAK: mol used to be chem.Atomer. +func MolRDF(traj chem.Traj, mol *chem.Molecule, refindexes []int, residues []string, options ...*Options) ([]float64, []float64, error) { + var o *Options + if len(options) > 0 { + o = options[0] + } else { + o = DefaultOptions() + } + var ret []float64 + coords := v3.Zeros(mol.Len()) + framesread := 0 + var err error + A := 1.0 + B := 1.0 + +reading: + for i := 0; ; i++ { + if i > 0 && i%o.skip != 0 && err == nil { + err = traj.Next(nil) //if this err is not nil, the next traj.Next() will not be excecuted, whether it's a skip or a read. Instead, we'll go directly to error processing. + continue + } else if err == nil { //in case the frame we skipped before gave an error + err = traj.Next(coords) + } + if err != nil { + switch err := err.(type) { + case chem.LastFrameError: + break reading + case chem.Error: + err.Decorate(fmt.Sprintf(""MolRDF: Failed while reading the %d th frame"", i)) + return nil, nil, err + default: + return nil, nil, err + + } + } + rdf := FrameUMolCRDF(coords, mol, refindexes, residues, o) ///only difference + if ret == nil { + ret = make([]float64, len(rdf)) + } + for j, _ := range ret { + ret[j] = ret[j] + rdf[j] + } + if mol.Len() > 1 && framesread == 1 { + elip, err := EllipsoidAxes(coords, epsilon, mol) + if err != nil { + return nil, nil, err + } + A = elip[0] / elip[2] + B = elip[1] / elip[2] + + } + + framesread++ + + } + ret, ret2, err := MDFFromCDF(ret, framesread, A, B, o.step) + + return ret, ret2, err +} + +// Obtains the radial standard-deviation distribution function from the unnormalized cummulative RDF and square RDF +func SQRDF2RSDF(avs, sqavs []float64, framesread int, step float64) []float64 { + ret := make([]float64, len(avs)) + for i, v := range avs { + ret[i] = sqavs[i]/float64(framesread) - math.Pow(v/float64(framesread), 2) + + } + last := math.Sqrt(ret[len(ret)-1]) + for i, _ := range ret { + ret[i] = math.Sqrt(ret[i]) / last + } + + return ret + +} + +// MDDFFromCDF takes the sume of a cummulative distribution function over framesread frames. +// It obtaines the RDF/MDDF from there by dividing each ""shell"" by an approximation to the +// volume (the ellipsoid of inerta of the solute scaled to the corresponding radius) and divided +// by the frames read. It returns a slice with the average density per shell (divided by volume) +// and another with the average number of molecules per shell, in both cases, divided by the value +// of the last shell. The function also requires the ratio of the largest semiaxes of the ellipsoid of inertia +// to its smallest semiaxis, A and B. It returns an error and nil slices if A and B are smaller than 1. +// it overwrites the original slice CDF slice! +// API BREAK: The original function did not take A and B, and simply approximated the volume as a sphere. +// This departs from the behavior described in the publication, in a way that could create wrong results. +// The current implementation also departs from the publication, which approximated the volume by a parallelepiped. +// I think this behavior is better, as it allows the MDDF to reduce to the RDF for spherically symmetric systems. +func MDFFromCDF(ret []float64, framesread int, A, B, step float64) ([]float64, []float64, error) { + if A < 1.0 || B < 1.0 { + return nil, nil, fmt.Errorf(""goChem/solvation.MDFFromCDF: A and B are the ratio between the lartest axis of an elipsoid to the smallest, they can't be smaller than 1.0"") + } + ret2 := make([]float64, len(ret)) + vp := (4.0 / 3.0) * math.Pi * A * B + //vp := 4 * math.Pi + // avtotalsolv := ret[len(ret)-1] //I think this is not needed, as we are already dealing with densities + var vol float64 + acc := 0.0 + for i, _ := range ret { + if i >= 1 { + acc = acc + ret[i-1] + ret2[i] = ret[i] + ret[i] = ret[i] - acc + } + } + for i, _ := range ret { + if i >= 1 { + fi := float64(i) + vol = vp * (math.Pow((fi+1)*step, 3) - math.Pow((fi)*step, 3)) + + } else if i == 0 { + vol = vp * math.Pow(step, 3) + + } else { + vol = 1 + } + ret[i] = ret[i] / float64(framesread) + ret2[i] = ret2[i] / float64(framesread) + ret[i] = ret[i] / vol + + } + last := ret[len(ret)-1] + for i, _ := range ret { + ret[i] = ret[i] / last + } + + return ret, ret2, nil +} + +// FrameUMolCRDF Obtains the the number of solvent molecules in each solvent shell, and the sqare of that number for each shell +// in a given frame. +func FrameUMolSQRDF(coord *v3.Matrix, mol chem.Atomer, refindexes []int, residues []string, options ...*Options) ([]float64, []float64) { + //NOTE: It could be good to have this function take a slice of floats and put the results there, so as to avoid + //allocating more than needed. + var o *Options + if len(options) > 0 { + o = options[0] + } else { + o = DefaultOptions() + } + + totalsteps := int(o.end / o.step) + av := make([]float64, 0, totalsteps) + sqav := make([]float64, 0, totalsteps) + // Here we get the RDF by counting the molecules at X distance or less from the solute, and subtracting the result from the previous callculation. + //This means that we do more calculation than needed, as every time keep including the solvent that was in previous layers. + // acclen := 0.0 + + res := DistRank(coord, mol, refindexes, residues, o) + sort.Sort(res) + dists := res.Distances() + var nprev float64 = 0 + for i := 1; i <= totalsteps; i++ { + limit := float64(i) * o.step + n := sort.SearchFloat64s(dists, limit) + // the limit is not found, SearchFloat64 will return the index of the first element larger or equal than limit. + // we want the one before that. + if n > 0 { + n-- + } + av = append(av, float64(n)-nprev) + sqav = append(av, math.Pow(float64(n)-nprev, 2)) + nprev = float64(n) + + } + return av, sqav +} + +// FrameUMolCRDF Obtains the Unnormalized Cummulative Molecular RDF for one solvated structure. The RDF would be these values averaged over several structures. +func FrameUMolCRDF(coord *v3.Matrix, mol chem.Atomer, refindexes []int, residues []string, options ...*Options) []float64 { + //NOTE: It could be good to have this function take a slice of floats and put the results there, so as to avoid + //allocating more than needed. + var o *Options + if len(options) > 0 { + o = options[0] + } else { + o = DefaultOptions() + } + + totalsteps := int(o.end / o.step) + ret := make([]float64, 0, totalsteps) + // Here we get the RDF by counting the molecules at X distance or less from the solute, and subtracting the result from the previous callculation. + //This means that we do more calculation than needed, as every time keep including the solvent that was in previous layers. + // acclen := 0.0 + + res := DistRank(coord, mol, refindexes, residues, o) + sort.Sort(res) + dists := res.Distances() + for i := 1; i <= totalsteps; i++ { + limit := float64(i) * o.step + n := sort.SearchFloat64s(dists, limit) + // the limit is not found, SearchFloat64 will return the index of the first element larger or equal than limit. + // we want the one before that. + if n > 0 { + n-- + } + ret = append(ret, float64(n)) + } + return ret +} + +type resAndChain struct { + ResID int + Chain string +} + +// returns all the residue numbers in mol covered by indexes +func allResIDandChains(mol chem.Atomer, indexes []int) []*resAndChain { + ret := make([]*resAndChain, 0, 2) + for _, i := range indexes { + at := mol.Atom(i) + if !repeated(at.MolID, at.Chain, ret) { + ret = append(ret, &resAndChain{ResID: at.MolID, Chain: at.Chain}) + } + } + return ret +} + +func repeated(id int, chain string, rac []*resAndChain) bool { + for _, v := range rac { + if v.Chain == chain && id == v.ResID { + return true + } + } + return false +} + +// DistRank determines, for a reference set of coordinates and a set of residue names, the minimum distance between any atom from the reference +// and any atom from each residue with one of the names given (or the centroid of each residue, if a variadic ""com"" bool is given) +// returns a list with ID and distances, which satisfies the sort interface and has several other useful methods. +func DistRank(coord *v3.Matrix, mol chem.Atomer, refindexes []int, residues []string, options ...*Options) MolDistList { + var o *Options + if len(options) > 0 { + o = options[0] + } else { + o = DefaultOptions() + } + + ranks := make([]*molDist, 0, 30) + // resIDs := make([]*resAndChain, 0, 30) + var molname string + var id, molid_skip int //The ""skip"" variables keep the residue just being read or discarded to avoid reading a residue twice. + molid_skip = -1 + var chain, chain_skip string + var distance float64 + water := v3.Zeros(3) + var ref *v3.Matrix + ownresIDs := allResIDandChains(mol, refindexes) //We could call this upstream and just get this numbers, but I suspect + ref = v3.Zeros(len(refindexes)) + ref.SomeVecs(coord, refindexes) + cutoff := o.end + cutoffplus := cutoff + 3 + // chunk := NewTopology(0, 1) + tmp := v3.Zeros(1) + // fmt.Println(""Start looking!"") /////////////////// + for i := 0; i < mol.Len(); i++ { + at := mol.Atom(i) + molname = at.MolName + id = at.MolID + chain = at.Chain + var test *v3.Matrix + //a little pre-screening for waters + if isInString([]string{""SOL"", ""WAT"", ""HOH""}, molname) && dist(ref.VecView(0), coord.VecView(i), tmp) > cutoffplus { + continue + + } + if isInString(residues, molname) && !repeated(id, chain, ownresIDs) && (id != molid_skip || chain != chain_skip) { + expectedreslen := 6 + indexes := make([]int, 1, expectedreslen) + indexes[0] = i + // fmt.Println(""New mol!"", molname, id, chain) ////////// + for j := i + 1; j < mol.Len(); j++ { + at2 := mol.Atom(j) + if at2.MolID != id { + break + } + indexes = append(indexes, j) + } + if len(indexes) == 3 { + test = water + } else { + test = v3.Zeros(len(indexes)) + } + test.SomeVecs(coord, indexes) + //This is a bit ugly + if o.com == true { + var mass *mat.Dense + topol := chem.NewTopology(0, 1) + topol.SomeAtoms(mol, indexes) + massp, err := topol.Masses() + if err != nil { + mass = mat.NewDense(len(massp), 1, massp) + } + c, err := chem.CenterOfMass(test, mass) + if err != nil { //this really is very unlikely to fail. The ref matrix would have to be wrong. It could even deserve a panic. + o.com = false //if it fails, we don't try again, for consistency. Any previous successful COM use will not comparable with numbers used from now on. + log.Printf(""gochem/solv/DistRank Couldn't obtain the COM/centroid: %s. Will work with all solvent atoms\n"", err.Error()) + distance = MolShortestDist(test, ref) //we don't panic, we just keep going with all atoms + } + distance = MolShortestDist(c, ref) + } else { + distance = MolShortestDist(test, ref) + } + if distance <= cutoff { + ranks = append(ranks, &molDist{Distance: distance, MolID: id, Chain:chain}) + } + molid_skip = id + chain_skip = chain + + } + } + return MolDistList(ranks) + +} + +// A structure for the distance from a residue to a particular point +type molDist struct { + Distance float64 + Chain string + MolID int +} + +func (M *molDist) str() string { + return fmt.Sprintf(""D: %4.3f ID: %d"", M.Distance, M.MolID) +} + +// A set of distances for different molecules to the same point +type MolDistList []*molDist + +func (M MolDistList) Swap(i, j int) { + M[i], M[j] = M[j], M[i] +} + +// Less returns true if the distance of the element i +// to the pre-defined point is smallert than that of the element j, +// or false otherwise +func (M MolDistList) Less(i, j int) bool { + return M[i].Distance < M[j].Distance +} +func (M MolDistList) Len() int { + return len(M) +} + +// Distance returns the distance from the element i of +// the slice to the pre-defined point +func (M MolDistList) Distance(i int) float64 { + return M[i].Distance +} + +// MolID resturns the MolID (the residue number, for a protein) +// of the i element of the slice +func (M MolDistList) MolID(i int) int { + return M[i].MolID +} + +// String produces a string representation of a set of distances +func (M MolDistList) String() string { + retslice := make([]string, len(M)) + for i := range M { + retslice[i] = M[i].str() + } + return strings.Join(retslice, ""\n"") +} + +// Distances returns a slice with all the distances in the set +func (M MolDistList) Distances() []float64 { + ret := make([]float64, len(M)) + for i := range M { + ret[i] = M[i].Distance //This absolutely should never fail! + } + return ret +} + +// MolIDs returns a slice with the molIDs in al the lists +func (M MolDistList) MolIDs() []int { + ret := make([]int, len(M)) + for i := range M { + ret[i] = M[i].MolID //This absolutely should never fail! + } + return ret +} + +// MolIDs returns a slice with all the chains present, and, for a given chain, all the residue IDs. +func (M MolDistList) MolIDsByChain() ([][]int,[]string){ + ids:=make([][]int,0,1) + chains := make([]string, 0,1) + for i,v := range M { + if !slices.Contains(chains,v.Chain){ + ch:=v.Chain + chains=append(chains,ch) + id:=make([]int,0,10) + for _,w:=range M[i+1:]{ + if w.Chain==ch{ + id=append(id,w.MolID) + } + } + ids=append(ids,id) + } + } + return ids,chains +} + + + + + + +// Data returns a list with all the MolIDs and a list with all the distances +// in the set +func (M MolDistList) Data() ([]int, []float64) { + ret := make([]int, len(M)) + ret2 := make([]float64, len(M)) + for i := range M { + ret[i] = M[i].MolID //This absolutely should never fail! + ret2[i] = M[i].Distance + } + return ret, ret2 +} + +// AtomIDs returns a list of all the atom IDs for all the residues in the list. +// Only a convenience function. +func (M MolDistList) AtomIDs(mol chem.Atomer) []int { + molids := M.MolIDs() + return chem.Molecules2Atoms(mol, molids, []string{}) +} + +// Merge aggregates the receiver and the arguments in the receiver +// it removes entries with repeated MolIDs +func (M MolDistList) Merge(list ...MolDistList) { + for _, v := range list { + ref := M.MolIDs() + for _, w := range v { + if !isInInt(ref, w.MolID) { + M = append(M, w) + } + } + } + +} + +// MolShortestDistGiven two sets of coordinates, it obtains the distance between the two closest atoms +// in the 2 sets. +// This is probably not a very efficient way to do it. +// Note:This should probably be moved to the main gochem package, in geometric.go +func MolShortestDist(test, ref *v3.Matrix) float64 { + temp := v3.Zeros(1) + var d1, dclosest float64 + var vt1, vr1 *v3.Matrix // vtclosest,vr1, vrclosest *v3.Matrix + dclosest = 100000 //we initialize this to some crazy large value so it's immediately replaced with the first calculated distance. + // dist(ref.VecView(0), test.VecView(0), temp) + for i := 0; i < test.NVecs(); i++ { + vt1 = test.VecView(i) + for j := 0; j < ref.NVecs(); j++ { + vr1 = ref.VecView(j) + temp.Sub(vr1, vt1) + d1 = temp.Norm(2) + if d1 < dclosest { + dclosest = d1 + } + } + } + return dclosest +} + +func dist(r, t, temp *v3.Matrix) float64 { + temp.Sub(r, t) + return temp.Norm(2) +} + +//NOTE: These will be replaced when the generic funcions +//make it to Go's stdlib. + +// isInInt returns true if test is in container, false otherwise. +func isInInt(container []int, test int) bool { + if container == nil { + return false + } + for _, i := range container { + if test == i { + return true + } + } + return false +} + +// Same as the previous, but with strings. +func isInString(container []string, test string) bool { + if container == nil { + return false + } + for _, i := range container { + if test == i { + return true + } + } + return false +} +","Go" +"Computational Biochemistry","rmera/gochem","chemjson/doc.go",".go","604","12","package chemjson + +//Package chemjson implements serializacion and unserialization of +//goChem data types. It's planned use is the communication of goChem +//programs with other, independent programs which can be written in +//languages other than Go, as long as those languages implement a +//way of serializing and unserializing JSON data and some library +//to deal with the goChem types is implemented. +//chemjson also implements the transmision of options, so an external +//program can transmit data an options for a job to a goChem program +//and later collect the results, for instance, via UNIX pipes. +","Go" +"Computational Biochemistry","rmera/gochem","chemjson/json.go",".go","8696","301","/* + * json.go, part of gochem. + * + * + * Copyright 2012 Raul Mera + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + * + * Gochem is developed at the laboratory for instruction in Swedish, Department of Chemistry, + * University of Helsinki, Finland. + * + * + */ +/***Dedicated to the long life of the Ven. Khenpo Phuntzok Tenzin Rinpoche***/ + +package chemjson + +import ( + ""bufio"" + ""encoding/json"" + ""fmt"" + ""io"" + ""strings"" + + chem ""github.com/rmera/gochem"" + v3 ""github.com/rmera/gochem/v3"" +) + +//A ready-to-serialize container for an atom. +type Atom struct { + A *chem.Atom + Coords []float64 + Bfac float64 +} + +//A ready-to-serialize container for coordinates +type Coords struct { + Coords []float64 +} + +//An easily JSON-serializable error type, +type Error struct { + deco []string + IsError bool //If this is false (no error) all the other fields will be at their zero-values. + InOptions bool //If error, was it in parsing the options? + InSelections bool //Was it in parsing selections? + InProcess bool + InPostProcess bool //was it in preparing the output? + Selection string //Which selection? + State int //Which state of it? + Atom int + Function string //which go function gave the error + Message string //the error itself +} + +//Error implements the error interface +func (J *Error) Error() string { + return J.Message +} + +//Decorate will add the dec string to the decoration slice of strings of the error, +//and return the resulting slice. +func (err Error) Decorate(dec string) []string { + if dec == """" { + return err.deco + } + err.deco = append(err.deco, dec) + return err.deco +} + +//Serializes the error. Panics on failure. +func (J *Error) Marshal() []byte { + ret, err2 := json.Marshal(J) + if err2 != nil { + panic(strings.Join([]string{J.Error(), err2.Error()}, "" - "")) // Yo, dawg, I heard you like errors, so I got an error while serializing your error so you can... you know the drill. + } + return ret +} + +//Information to be passed back to the calling program. +type Info struct { + Molecules int + Bfactors bool + SS bool + FramesPerMolecule []int + AtomsPerMolecule []int + FloatInfo [][]float64 + StringInfo [][]string + IntInfo [][]int + BoolInfo [][]bool + Energies []float64 +} + +//Send Marshals the info and writes to out, returns an error or nil +func (J *Info) Send(out io.Writer) *Error { + enc := json.NewEncoder(out) + if err := enc.Encode(J); err != nil { + return NewError(""postprocess"", ""JSONInfo.Marshal"", err) + } + return nil +} + +//Options passed from the calling external program +type Options struct { + SelNames []string + AtomsPerSel []int //Knowing in advance makes memory allocation more efficient + StatesPerSel []int //How many snapshots a traj has? + StringOptions [][]string + IntOptions [][]int + BoolOptions [][]bool + FloatOptions [][]float64 +} + +//Takes an error and some additional info to create a json-marshal-ble error +func NewError(where, function string, err error) *Error { + jerr := new(Error) + jerr.IsError = true + switch where { + case ""options"": + jerr.InOptions = true + case ""selection"": + jerr.InSelections = true + case ""postprocess"": + jerr.InPostProcess = true + default: + jerr.InProcess = true + } + jerr.Function = function + jerr.Message = err.Error() + return jerr +} + +//DecodeOptions Decodes or unmarshals json options into an Options structure +func DecodeOptions(stdin *bufio.Reader) (*Options, *Error) { + line, err := stdin.ReadBytes('\n') + if err != nil { + return nil, NewError(""options"", ""DecodeOptions"", err) + } + ret := new(Options) + err = json.Unmarshal(line, ret) + if err != nil { + return nil, NewError(""options"", ""DecodeOptions"", err) + } + return ret, nil +} + +//DecodeMolecule Decodes a JSON molecule into a gochem molecule. Can handle several frames (all of which need to have the same amount of atoms). It does +//not collect the b-factors. +func DecodeMolecule(stream *bufio.Reader, atomnumber, frames int) (*chem.Topology, []*v3.Matrix, *Error) { + const funcname = ""DecodeMolecule"" //for the error + atoms := make([]*chem.Atom, 0, atomnumber) + coordset := make([]*v3.Matrix, 0, frames) + rawcoords := make([]float64, 0, 3*atomnumber) + for i := 0; i < atomnumber; i++ { + line, err := stream.ReadBytes('\n') //Using this function allocates a lot without need. There is no function that takes a []bytes AND a limit. I might write one at some point. + if err != nil { + break + } + at := new(chem.Atom) + err = json.Unmarshal(line, at) + if err != nil { + return nil, nil, NewError(""selection"", funcname, err) + } + atoms = append(atoms, at) + line, err = stream.ReadBytes('\n') //See previous comment. + if err != nil { + break + } + ctemp := new(Coords) + if err = json.Unmarshal(line, ctemp); err != nil { + return nil, nil, NewError(""selection"", funcname, err) + } + rawcoords = append(rawcoords, ctemp.Coords...) + } + mol := chem.NewTopology(-1, 99999, atoms) //no idea of the charge or multiplicity + coords, err := v3.NewMatrix(rawcoords) + if err != nil { + return nil, nil, NewError(""selection"", funcname, err) + } + coordset = append(coordset, coords) + if frames == 1 { + return mol, coordset, nil + } + for i := 0; i < (frames - 1); i++ { + coords, err := DecodeCoords(stream, atomnumber) + if err != nil { + return mol, coordset, NewError(""selection"", funcname, fmt.Errorf(""Error reading the %d th frame: %s"", i+2, err.Error())) + } + coordset = append(coordset, coords) + } + return mol, coordset, nil + +} + +//Decodecoords decodes streams from a bufio.Reader containing 3*atomnumber JSON floats into a v3.Matrix with atomnumber rows. +func DecodeCoords(stream *bufio.Reader, atomnumber int) (*v3.Matrix, *Error) { + const funcname = ""DecodeCoords"" + rawcoords := make([]float64, 0, 3*atomnumber) + for i := 0; i < atomnumber; i++ { + line, err := stream.ReadBytes('\n') //Using this function allocates a lot without need. There is no function that takes a []bytes AND a limit. I might write one at some point. + if err != nil { + break + } + ctemp := new(Coords) + if err = json.Unmarshal(line, ctemp); err != nil { + return nil, NewError(""selection"", funcname, err) + } + rawcoords = append(rawcoords, ctemp.Coords...) + } + coords, err := v3.NewMatrix(rawcoords) + if err != nil { + return nil, NewError(""selection"", funcname, err) + } + return coords, nil +} + +//Takes a chem.Atomer, coordinates, bfactos and secondary strucuctures, encodes them and writes them to the given io.writer +func SendMolecule(mol chem.Atomer, coordset, bfactors []*v3.Matrix, ss [][]string, out io.Writer) *Error { + const funcname = ""SendMolecule"" + enc := json.NewEncoder(out) + if err := EncodeAtoms(mol, enc); err != nil { + return err + } + for _, coords := range coordset { + if err := EncodeCoords(coords, enc); err != nil { + return err + } + } + if bfactors != nil { + jb := new(jSONbfac) + for _, b := range bfactors { + jb.Bfactors = b.Col(nil, 0) + if err := enc.Encode(jb); err != nil { + return NewError(""postprocess"", funcname+""(bfactors)"", err) + } + } + } + if ss != nil { + jss := new(jSONss) + for _, s := range ss { + jss.SS = s + if err := enc.Encode(jss); err != nil { + return NewError(""postprocess"", funcname+""(ss)"", err) + } + } + } + return nil +} + +type jSONbfac struct { + Bfactors []float64 +} + +type jSONss struct { + SS []string +} + +type jSONCoords struct { + Coords []float64 +} + +//Encodes a goChem Atomer into a JSON +func EncodeAtoms(mol chem.Atomer, enc *json.Encoder) *Error { + const funcname = ""EncodeAtoms"" + if mol == nil { + return nil //Its assumed to be intentional. + } + for i := 0; i < mol.Len(); i++ { + if err := enc.Encode(mol.Atom(i)); err != nil { + return NewError(""postprocess"", funcname, err) + } + } + return nil +} + +//Encodes a set of coordinates into JSON +func EncodeCoords(coords *v3.Matrix, enc *json.Encoder) *Error { + c := new(Coords) + t := make([]float64, 3, 3) + for i := 0; i < coords.NVecs(); i++ { + c.Coords = coords.Row(t, i) + if err := enc.Encode(c); err != nil { + return NewError(""postprocess"", ""chemjson.EncodeCoords"", err) + } + } + return nil +} +","Go" +"Computational Biochemistry","rmera/gochem","ff/doc.go",".go","1061","29","/* + * doc.go, part of goChem + * + * Copyright 2025 Raul Mera A. (rmeraaatacademicosdotutadotcl) + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this program. If not, see + * . + * + */ + +/* +Top is a package for reading/editing/writing force-field topologies (not to be +confused with the gochem Topology structure). It's under development. +Only Gromacs topologies can be read/written with the program's current version +Charmm special terms are also not supported. +*/ +package ff +","Go" +"Computational Biochemistry","rmera/gochem","ff/old.go",".go","18298","622","package ff + +import ( + ""bufio"" + ""errors"" + ""fmt"" + ""io"" + ""os"" + ""slices"" + ""strconv"" + ""strings"" +) + +type TermSelect struct { + m map[string]func(string) (string, error) +} + +func NewTermSelect() TermSelect { + m := make(map[string]func(string) (string, error)) + m[""atoms""] = nil + m[""bonds""] = nil + m[""angles""] = nil + m[""constraints""] = nil + m[""dihedrals""] = nil + m[""exclusions""] = nil + m[""vsitesn""] = nil + m[""nonskiplines""] = nil + m[""default""] = nil + return TermSelect{m: m} +} + +func (T TermSelect) NTerms() int { + return len(T.m) +} + +func (T TermSelect) GetErr(header string) (func(string) (string, error), error) { + val, ok := T.m[header] + if !ok { + return nil, fmt.Errorf(""TermSelect.Get: Attempted to get unsuported value: %s"", header) + } + if val == nil { + return val, fmt.Errorf(""Warning: Function set to nil"") + } + + return val, nil +} + +// gets the function set to a header. Panics if the heeader is not present +func (T TermSelect) Get(header string) func(string) (string, error) { + val, ok := T.m[header] + if !ok { + panic(fmt.Sprintf(""grotop/TermSelect/MustGet: Attempted to get unsuported header: %s"", header)) + } + return val +} + +func (T TermSelect) GetOrDefault(header string) func(string) (string, error) { + val, ok := T.m[header] + if !ok { + panic(fmt.Sprintf(""grotop/TermSelect/MustGet: Attempted to get unsuported header: %s"", header)) + } + if val == nil { + return func(s string) (string, error) { return s, nil } + } + return val +} + +// Set each of the given headers to the corresponding string slice in s (headers and s must +// be of the same lenght. Note that you can set +// headers to 'nil', thus marking them as 'unselected'. Panics if header doesn't exist. +func (T TermSelect) Set(header string, s func(string) (string, error)) { + _, ok := T.m[header] + if !ok { + panic(fmt.Sprintf(""term %s not supported"", s)) + } + T.m[header] = s +} + +// Same as Set but returns an error if header doesn't exist. +func (T TermSelect) SetErr(header string, s func(string) (string, error)) (err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf(""%s"", r) + } + }() + T.Set(header, s) + return +} + +// Set each of the given headers to the corresponding string slice in s (headers and s must +// be of the same lenght. Note that you can set +// headers to 'nil', thus marking them as 'unselected'. +func (T TermSelect) SetMany(headers []string, s []func(string) (string, error)) error { + if headers == nil { + return fmt.Errorf(""TermSelect.Set: No term given"") + } + if len(headers) > len(s) { + return fmt.Errorf(""TermSelect.Set: Not enough strings for the headers to be set"") + } + var err error + for i, v := range headers { + _, ok := T.m[v] + if !ok { + if err == nil { + err = fmt.Errorf(""term %s not supported"", v) + } else { + err = fmt.Errorf(""term %s not supported - %s"", v, err.Error()) + } + } + T.m[v] = s[i] + + } + return err +} + +// Set all headers to a do-nothing function. Only the first given functionw +// will be used to set all headers. If nothing is given, a 'do nothing' function +// which returns the same string given, will be used. +func (t TermSelect) SetAll(f ...func(string) (string, error)) { + fu := func(s string) (string, error) { return s, nil } + if len(f) > 0 && f[0] != nil { + fu = f[0] + } + for k, _ := range t.m { + t.m[k] = fu + } + +} + +// Returns all the headers sorted. If onlySelected is given and true, +// only the headers that have associated a non-nil function are returned. +func (T TermSelect) Headers(onlySelected ...bool) []string { + var sel bool + if len(onlySelected) > 0 { + sel = onlySelected[0] + } + ret := make([]string, 0, 2) + for k, v := range T.m { + if !sel || (v != nil) { + ret = append(ret, k) + } + } + slices.Sort(ret) + return ret +} + +// Represents a topology stored in memory, as opposed to in a file. +type TopInMem struct { + t []string + i int +} + +// Returns a new TopInMem, with the topology +// represented by the given slice of strings (each +// string must correspond to one line of the file, including +// the respective '\n'. +func NewTopInMem(t []string) *TopInMem { + return &TopInMem{t: t, i: 0} +} + +func TopInMemFromFile(fname string) (*TopInMem, error) { + T := new(TopInMem) + T.t = make([]string, 0, 10) + f, err := os.Open(fname) + if err != nil { + return nil, err + } + defer f.Close() + re := bufio.NewReader(f) + var l string + for l, err = re.ReadString('\n'); err == nil; l, err = re.ReadString('\n') { + ll := strings.TrimSuffix(l, ""\n"") + T.t = append(T.t, ll) + } + if err != nil && errors.Is(err, io.EOF) { + err = nil + } + // fmt.Println(T.t) //////////////////////////////////// + return T, err +} + +// Returns a deep copy of the topology +func (t *TopInMem) Copy() *TopInMem { + s := make([]string, len(t.t)) + copy(s, t.t) + return NewTopInMem(s) +} + +// Resets the reader to start from the first line +func (t *TopInMem) Reset() { + t.i = 0 +} + +// Resets the reader to start from the first line +func (t *TopInMem) Len() int { + return len(t.t) +} + +// Adds a string to the topology +func (t *TopInMem) WriteString(s string) (int, error) { + t.t = append(t.t, s) + return len(s), nil + +} + +// Replaces the last-read string in the topology for s +func (t *TopInMem) ReplaceString(s string) { + t.t[t.i-1] = s +} + +// Returns the next line in the topology. Note that the byte argument is +// not used, you can't choose how much you want to read, it's always the +// full next line (unlike in the bufio.Reader ReadString method). +func (t *TopInMem) ReadString(byte) (string, error) { + if t.i >= len(t.t) { + t.i = 0 //you can re-start reading it. + return """", io.EOF + } + t.i++ + return t.t[t.i-1], nil +} + +func (t *TopInMem) WriteToFile(name string) error { + f, err := os.Create(name) + if err != nil { + return fmt.Errorf(""grotop/TopInMem.WriteToFile: %w"", err) + } + for i, v := range t.t { + _, err = f.WriteString(v + ""\n"") + if err != nil { + return fmt.Errorf(""grotop/TopInMem.WriteToFile: Couldn't write %d-th line to file: %w"", i+1, err) + } + } + return nil +} + +// Removes unneeded whitelines (including lines containing only a ';') from t. +// it allocates a new []string of the same size as the original to do the change +// so not very memory efficient. +func (t *TopInMem) Clean() { + newt := make([]string, 0, len(t.t)) + header := NewTopHeader() //will probably move thise to the structure + //so it's not re-created every time you call this function. + for i, v := range t.t { + if strings.Trim(v, ""\t; \n"") == """" { //if the string is nothing but white spaces and linejumps + if i < len(t.t)-1 && !header.Is(t.t[i+1]) { + continue + } + } + newt = append(newt, v) + } + t.t = newt +} + +// Transforms each supported section of an Gromacs itp/top file with corresponding function in the +// given TermSelect. Writes the modified trajectory to a StringWriter, and returns an error or nil. +// if a function in the TermSelect map is nil, FuncApplier will apply a 'do nothing' function, that +// returns the same string given, instead. +func FuncApplier(top StringReaderReplacer, T TermSelect) error { + header := NewTopHeader() + currentfunc := T.GetOrDefault(""default"") + currentheader := """" + var fl string + var err error + for fl, err = top.ReadString('\n'); err == nil; fl, err = top.ReadString('\n') { + if strings.HasPrefix(fl, "";"") { + top.ReplaceString(fl) + continue + } + ls := strings.Split(fl, "";"") //remove comments + l := ls[0] + co := """" + if len(ls) > 1 { + co = ""; "" + strings.Join(ls[1:], "" "") + // co = strings.Replace(co, ""\n"", """", 1) + } + if len(strings.Fields(l)) == 0 { + li, err := T.GetOrDefault(""nonskiplines"")(l) + if err != nil { + return err + } + top.ReplaceString(li + co) + continue + } + if strings.Contains(l, ""#"") { + top.ReplaceString(l + co) + if err != nil { + return err + } + + continue + } + if header.Is(l) { + fun, e := T.GetErr(header.Which(l)) + if e == nil { + currentfunc = fun + currentheader = header.Which(l) + //return """", fmt.Errorf(""couldn't find function %s in map"", l) + } + + top.ReplaceString(l + co) + continue + } + li, err := currentfunc(l) + if err != nil { + return fmt.Errorf(""Problem with header %s: %w"", currentheader, err) + } + top.ReplaceString(li + co) + + } + if errors.Is(err, io.EOF) { + err = nil + } + return nil +} + +// Returns the same function that will delete lines that have been already +// seen in the file. This will use a fair bit of memory as all lines have to be +// kept in memory for comparison with the next ones. +func DelRepeatedFunctions(T TermSelect) { + lines := make([]string, 0, 200) + f := func(s string) (string, error) { + if slices.Contains(lines, s) { + return """", nil + } + lines = append(lines, s) + return s, nil + } + fns := make([]func(string) (string, error), T.NTerms()) + for i, _ := range fns { + fns[i] = f + } + h := T.Headers() + T.SetMany(h, fns) +} + +// Returns the same function that will delete lines that are identical to the previous non-repeated +// line in the file. So, if 2 lines are repeated, but there are lines in between them, the repeated +// ones will _not_ be deleted. For that, see DelRepeatedFunctions. The reason for adding this function +// is that it requires less memory. +func DelDuplicatedFunctions(T TermSelect) { + prevline := ""2@@$)(/^*9HhL.Goは最高のプログラミング言語です"" //just a line that is unlikely to be found in a topology file + f := func(s string) (string, error) { + if s == prevline { + return """", nil + } + prevline = s + return s, nil + } + fns := make([]func(string) (string, error), T.NTerms()) + for i, _ := range fns { + fns[i] = f + } + h := T.Headers() + T.SetMany(h, fns) +} + +// The terms string must be already formatted in Gromacs format for each term. +// The slice of slices must contain one slice per header (which can be empty). +// in the alphabetical order of the headers. +// if you want to set the non-selected terms to 'do nothing' you can do so before +// calling this, with the method 'SetAll' +// and each slice contains a term to be added for that type. +func AddTermFunctions(T TermSelect, terms2add [][]string) { + sel := T.Headers(true) + slices.Sort(sel) + for i, k := range sel { + call := 0 + T.m[k] = func(string) (string, error) { + if call == 0 { + call++ //I _think_ each 'version' of the variable call will be 'closured' in each function + //so each function will only work once. + //I admit it's not very efficient, but I find it way clearer than dealing with it at + //the function applier level. + return strings.Join(terms2add[i], """"), nil + } + return """", nil + } + } +} + +// Returns a TermSelect with funcions in atoms and vsites that delete all atoms and vsites +// with indexes present in todel. todel must be 1-based indexes. The functions do _not_ +// adjust the indexes of the atoms not removed (see the ShiftAtomNumberFunctions) +// it also do _not_ remove bonded terms involving the atoms. +func DeleteAtomsFunction(todel []int) TermSelect { + f := func(s string) (string, error) { + at, err := strconv.Atoi(fi(s)[0]) + if err != nil { + return """", fmt.Errorf(""Can't parse numbers in line %s %w"", s, err) + } + if slices.Contains(todel, at) { + return """", nil + } + return s, nil + } + T := NewTermSelect() + T.SetAll() //set everything to a 'do nothing' function + //so everything we don't set explicily will just use that. + T.Set(""atoms"", f) + T.Set(""vsitesn"", f) + + return T +} + +// Returns a TermSelect with functions that replace the term belonging to one of the headers in +// headers2edit and with atoms atoms (which must match in order, too, or in reverse order in +// 'reverse' is true), with the string newterm, unless the newterm string is ""DONOTREPLACE"" in which case +// the functions in the returned TermSelect do nothing. In addition EditTermFunction returns a function that, after +// the TermSelect is applied to a topology, will return a slice of strings with the matching terms. +func EditTermFunction(newterm string, atoms []int, headers2edit []string, reverse bool) (TermSelect, func() []string) { + retterm := []string{} + replace := func(s string) string { + if newterm == ""DONOTREPLACE"" { + return s + } + return newterm + } + adder := func() func(s string) (string, error) { + return func(s string) (string, error) { + st := fi(s) + if len(atoms) <= 0 || len(atoms) > len(st) { + return """", fmt.Errorf(""0 or too many elements in atom list: %d"", len(atoms)) + } + /// fmt.Println(len(st), atoms, st, s) //////////////////////////////// + ats, err := parseints(st[:len(atoms)]) + if err != nil { + return """", fmt.Errorf(""Can't parse numbers in line %s %w"", s, err) + } + fmt.Println(""ats, atoms"", ats, atoms) //////////////////////////////////////////// + if slices.Equal(ats, atoms) { + retterm = append(retterm, s) + return replace(s), nil + } + if reverse { + slices.Reverse(ats) + if slices.Equal(ats, atoms) { + retterm = append(retterm, s) + return replace(s), nil + } + + } + return s, nil + } + } + T := NewTermSelect() + h := T.Headers() + T.SetAll() + fmt.Println(""header2edit"", headers2edit) ///////////////////// + for _, v := range h { + if slices.Contains(headers2edit, v) { + T.Set(v, adder()) + } + } + return T, func() []string { return retterm } + +} + +// Returns a set of functions that will switch every atom index in tosub for the atom in the same position +// in replacement, in lines belonging to supported records of an itp file (as of now: atoms, bonds, constraints, angles, dihedrals, +// exclusions, virtual_sitesn. +// Some exceptional behavior: +// If len(tosub)==0 then replacement is expected to have 1 value, which will be added to all atoms. +// if len(tosub)==1 and that element is negative, then replacement is also expected to have one value, which will be +// added to all atoms with index larger than the absolute value of tosub[0] +// I admit this 'exceptionsl behavior' is pretty hack-y, but I didn't want to repeat code so much. +// if you need to add/subtract something to all atoms greater than something, it's easier to use ShiftAtomNumberFunctions +func SwitchAtomNumbersFunctions(tosub, replacement []int) TermSelect { + // rep := strings.Replace + change := func(i int) int { + if len(tosub) == 0 { + return i + replacement[0] + } + index := slices.Index(tosub, i) + if index == -1 { + return i + } + return replacement[index] + } + after := 0 + if len(tosub) == 1 && tosub[0] < 0 { + after = -1 * tosub[0] + tosub = []int{} + } + + if len(tosub) != 0 && len(tosub) != len(replacement) { + panic(sf(""tosub and replacement should have equal lenght unless len(tosub)==0, but len(tosub): %d len(replacement): %d"", len(tosub), len(replacement))) + } + T := NewTermSelect() + + adder := func(atoms int) func(s string) (string, error) { + return func(s string) (string, error) { + st := fi(s) + if atoms <= 0 || atoms > len(st) { + atoms = len(st) //all fields are atoms + } + /// fmt.Println(len(st), atoms, st, s) //////////////////////////////// + ats, err := parseints(st[:atoms]) + if err != nil { + return """", fmt.Errorf(""Can't parse numbers in line %s %w"", s, err) + } + for i, v := range ats { + if v < after { + continue + } + at2 := change(v) + st[i] = sf(""%3d"", at2) + } + return strings.Join(st, "" ""), nil + } + } + + vsitesn := func(s string) (string, error) { + st := fi(s) + ats, err := parseints(st) + if err != nil { + return """", fmt.Errorf(""Can't parse numbers in line %s %w"", s, err) + } + if ats[0] > after { + at2 := change(ats[0]) + st[0] = sf(""%3d"", at2) + + } + for i, v := range ats[2:] { + if v <= after { + continue + } + at2 := change(v) + st[i+2] = sf(""%3d"", at2) + } + return strings.Join(st, "" ""), nil + } + T.SetAll() //set everything to a 'do nothing' function + //so everything we don't set explicily will just use that. + T.Set(""atoms"", adder(1)) + T.Set(""bonds"", adder(2)) + T.Set(""angles"", adder(3)) + T.Set(""constraints"", T.Get(""bonds"")) + T.Set(""dihedrals"", adder(4)) + T.Set(""exclusions"", adder(-1)) + T.Set(""vsitesn"", vsitesn) + + return T +} + +// Returns a set of functions that will add or subtract toadd (depending on its sign) to every atom index greater +// than after, in lines belonging to supported records of an itp file (as of now: atoms, bonds, constraints, angles, dihedrals, +// exclusions, virtual_sitesn +func ShiftAtomNumbersFunctions(after, toadd int) TermSelect { + return SwitchAtomNumbersFunctions([]int{-1 * after}, []int{toadd}) +} + +//The next one is not a utility function, as it is applied by itself, without the FuncApplier function, but I'll keep it in this file + +// Merges the '[]' sections of two topologies. The sections in both must be in the same order. +// It adds all +func MergeTopologies(top1, top2 StringReader, target io.StringWriter) error { + header := NewTopHeader() + var fl string + var err error + next_header2 := """" + for fl, err = top1.ReadString('\n'); err == nil; fl, err = top1.ReadString('\n') { + ls := strings.Split(fl, "";"") //remove comments + l := ls[0] + target.WriteString(fl) + // fmt.Println(""casha"", fl) ///////////// + //every time we reach a header in top1, we start looking for the header in top2 + //if we reach a header, or we have previously reached a header (next_header2), + //and it's the same we read in top2, then we start inserting + //whatever is in top2 after that header, until we encounter the next header. + if header.Is(l) { + writing2 := false + h1 := header.Which(l) + // fmt.Println(""headerq1"", l, h1) /////////////////// + if h1 == ""moleculetype"" { + continue + } + var err2 error + var fl2 string + for fl2, err2 = top2.ReadString('\n'); err2 == nil; fl2, err2 = top2.ReadString('\n') { + + ls2 := strings.Split(fl2, "";"") //remove comments + l2 := ls2[0] + if header.Is(l2) && header.Which(l2) == h1 { + writing2 = true + + // fmt.Println(""headerq2"", l2) /////////////////// + continue + } + if strings.HasPrefix(l2, ""#"") { + target.WriteString(fl2) + continue + } + if next_header2 == h1 || writing2 { + // fmt.Println(""next_header1ql"", next_header2) /////////////////// + + if header.Is(l2) { + next_header2 = header.Which(l2) + writing2 = false + break + } + + // fmt.Println(""cashi"", fl2) ////////// + target.WriteString(fl2) + } + } + // v, ok := top2.(*TopInMem) + // if ok { + // v.Reset() + // } + if err2 != nil && !errors.Is(err2, io.EOF) { + // fmt.Println(""this error shouldn't be here"", err2) /////////// + return err2 + } + } + } + if !errors.Is(err, io.EOF) { + return err + } + return nil +} +","Go" +"Computational Biochemistry","rmera/gochem","ff/functions.go",".go","10235","430","package ff + +import ( + ""fmt"" + ""slices"" + + chem ""github.com/rmera/gochem"" +) + +func applyToTerms(f func(int) int, T []*Term) { + for i, v := range T { + for j, w := range v.Indexes { + T[i].Indexes[j] = f(w) + } + for j, w := range v.Indexes { + T[i].Indexes[j] = f(w) + } + } +} + +// Modifies the Indexes and IDs of all atoms in the atoms, terms +// and vsite definitions according to f. +func (F *Top) ModIndexes(f func(int) int) { + for i := 0; i < F.Mol.Len(); i++ { + at := F.Mol.Atom(i) + at.SetIndex(f(at.Index())) + // at.ID = f(at.ID) + } + applyToTerms(f, F.Bonds) + applyToTerms(f, F.Impropers) + applyToTerms(f, F.Constraints) + applyToTerms(f, F.Angles) + + applyToTerms(f, F.Dihedrals) + + for _, v := range F.Exclusions { + for j, w := range v { + v[j] = f(w) + } + } + for _, v := range F.VSites { + v.Index = f(v.Index) + for j, w := range v.Atoms { + v.Atoms[j] = f(w) + } + } + +} + +func mergeTerms[T ~[]E, E any](T1, T2 T) T { + ret := make(T, 0, len(T2)+len(T1)) + for _, v := range T1 { + ret = append(ret, v) + } + for _, v := range T2 { + ret = append(ret, v) + } + return ret + +} + +// Merges F2 into F, and _after_ F. F2 is modified, as all atom indexes are set to start +// from the last atom of F, unless moveindexes is given and false. AType and LJ are +// merged by preserving all elements in the receiver plus the non-repeated elements of +// F2, if keepours is true or preserving all elements in F2 plus the non-repeated +// elements in the receiver, otherwise. Note that 2 LJ elements could be repeated +// (i.e. refer to the same atoms) but have different values, so the choice between +// keepours true or false is important. +func (F *Top) Merge(F2 *Top, keepours bool, moveindexes ...bool) { + disp := F.Mol.Len() + sum := func(i int) int { + return i + disp + } + if len(moveindexes) > 0 || !moveindexes[0] { + sum = func(i int) int { + return i + } + + } + if keepours { + F2.ATypes = deleteRepeated(F.ATypes, F2.ATypes) + F2.LJ = deleteRepeated(F.LJ, F2.LJ) + } else { + F.ATypes = deleteRepeated(F2.ATypes, F.ATypes) + F.LJ = deleteRepeated(F2.LJ, F.LJ) + + } + F2.ModIndexes(sum) + for i := 0; i < F2.Mol.Len(); i++ { + F.Mol.AppendAtom(F2.Mol.Atom(i)) + } + F.Bonds = mergeTerms(F.Bonds, F2.Bonds) + F.Constraints = mergeTerms(F.Constraints, F2.Constraints) + F.Angles = mergeTerms(F.Angles, F2.Angles) + F.Impropers = mergeTerms(F.Impropers, F2.Impropers) + F.Dihedrals = mergeTerms(F.Dihedrals, F2.Dihedrals) + F.VSites = mergeTerms(F.VSites, F2.VSites) + F.Exclusions = mergeTerms(F.Exclusions, F2.Exclusions) +} + +type eq interface { + equal(any) bool +} + +func containsEqual(w []eq, e eq) bool { + for _, v := range w { + if e.equal(v) { + return true + } + } + return false + +} + +// Returns a copy of D whitout the elements that are present in N +func deleteRepeated[E eq, T []E](N, D T) T { + ret := make([]E, 0, len(N)) + todelete := make([]int, 0, 100) + for i, r := range D { + for _, k := range N { + if r.equal(k) { + todelete = append(todelete, i) + break + } + } + } + for i, v := range D { + if !slices.Contains(todelete, i) { + ret = append(ret, v) + } + } + return ret +} + +func containsSame[T ~[]E, E comparable](C1, C2 T) bool { + if len(C1) != len(C2) { + return false + } + for i, v := range C1 { + if v == C2[i] { + continue + } + r := false + for _, w := range C2 { + if v == w { + r = true + } + } + if !r { + return r + } + + } + return true + +} + +// Find the Terms with Indexes that match the atom indexes given in Indexes. The match comparison +// depends on the value of 'order'. Acceptable values are: +// 's' (strict, only a term with the values in the same order as +// given is considered). +// 'r' (reverse, both the given order and its reverse are accepted) +// 'a' (any, any order is accepted) +// it only returns error if an invalid order is given, so, if that is +// hardcoded, you may safely omit the error check. +func FindTerm(T []*Term, Indexes []int, order byte) (int, error) { + j := -1 + rev := make([]int, 0, len(Indexes)) + copy(rev, Indexes) + slices.Reverse(rev) + for i, v := range T { + switch order { + case 's': + if slices.Equal(v.Indexes, Indexes) { + j = i + break + } + case 'r': + if slices.Equal(v.Indexes, Indexes) || slices.Equal(v.Indexes, rev) { + j = i + break + } + case 'a': + if containsSame(v.Indexes, Indexes) { + j = i + } + default: + return -1, fmt.Errorf(""Invalid value for order: %v"", order) + + } + } + return j, nil +} + +// Deletes all atoms (and, if applicable, their virtual site definitions) +// with IDs present in todel. It modifies F in place, and also returns it. +// It does _not_ delete terms associated with the atoms. +func DeleteAtomsAndVSites(F *Top, todel []int) *Top { + //First we generate a new list of atoms without the ones to delete + nat := make([]*chem.Atom, 0, F.Len()-len(todel)) + for i := 0; i < F.Len(); i++ { + if !slices.Contains(todel, i+1) { + nat = append(nat, F.Mol.Atom(i)) + } + } + //Now the same for the VSites + vsites := make([]*VSite, 0, len(F.VSites)) //we don't know how many vsites we'll delete + for _, v := range F.VSites { + if !slices.Contains(todel, v.Index) { + vsites = append(vsites, v) + } + } + F.Mol.Atoms = nat + F.VSites = vsites + return F +} + +// Returns FF like F but removing all atoms, bonded terms and exclusions that _only_ +// contain terms in todel or, if removecontaining[0] is given and true, all +// bonded terms and exclusions that contains at least one of the terms in todel. +// todel refers to indexes, so it's zero-based +func DeleteTermsForAtomsAndVSites(F *Top, todel []int, removeallcontaining ...bool) *Top { + var dodel func([]int) bool + //here we decide what to delete + dodel = func(indexes []int) bool { + //this one only deletes if ids ONLY contains atoms that + //are in todel + if len(indexes) > len(todel) { + return false + } + for _, v := range indexes { + if !slices.Contains(todel, v) { + return false + } + } + return true + } + if len(removeallcontaining) > 0 && removeallcontaining[0] { + dodel = func(indexes []int) bool { + //this one only deletes if ids has _any_ atom in todel + for _, v := range indexes { + if slices.Contains(todel, v) { + return true + } + } + return false + } + + } + //now a function to delete terms, since we'll do that a few times + var DelTerms func([]*Term) []*Term = func(ts []*Term) []*Term { + ret := make([]*Term, 0, len(ts)) + for _, v := range ts { + if dodel(v.Indexes) { + continue + } + t2 := new(Term) + t2.Copy(v) + ret = append(ret, t2) + + } + return ret + } + + //Well, that was a lot, but now just sit back + //and enjoy. + + //Copy the basic data. It's all deep copy as we dont' want + //to alter the original. + mol := chem.NewTopology(0, 1) + mol.CopyAtoms(F.Mol) + F2 := NewTop(mol, F.SigmaEpsilon) + F2.currentHeader = F.currentHeader + F2.VSites = F.VSites + F2 = DeleteAtomsAndVSites(F2, todel) + + //Now we just apply the functions we worked hard for + //above. + F2.Bonds = DelTerms(F.Bonds) + F2.Angles = DelTerms(F.Angles) + F2.Constraints = DelTerms(F.Constraints) + F2.Impropers = DelTerms(F.Impropers) + F2.Dihedrals = DelTerms(F.Dihedrals) + + //And the exclusions. We still get to recycle the dodel function. + F2.Exclusions = make([][]int, 0, len(F.Exclusions)) + for _, v := range F.Exclusions { + if dodel(v) { + continue + } + ex := make([]int, len(v)) + copy(ex, v) + F2.Exclusions = append(F2.Exclusions, ex) + } + + return F2 +} + +// Creates a 'hole' in indexes and ids of size size after the +// term with index after (so, for indexes 3,4,5,1,7, if we +// request a hole of size 3 afrter 4, we get 3,4,8,1,10) +func termHole(T []*Term, after, size int) []*Term { + for i, v := range T { + for j, w := range v.Indexes { + if w > after { + T[i].Indexes[j] += size + } + } + } + return T +} + +// Shifts all atoms by shift +func Shift(F *Top, shift int, shiftAtoms bool) { + //here we decide what to delete + //now a function to delete terms, since we'll do that a few times + var ShiftTerms func([]*Term) = func(ts []*Term) { + for _, v := range ts { + for j, _ := range v.Indexes { + v.Indexes[j] += shift + } + + } + } + ShiftTerms(F.Bonds) + ShiftTerms(F.Angles) + ShiftTerms(F.Constraints) + ShiftTerms(F.Impropers) + ShiftTerms(F.Dihedrals) + for i, v := range F.Exclusions { + for j, _ := range v { + F.Exclusions[i][j] += shift + } + } + + if shiftAtoms { + for i := 0; i < F.Len(); i++ { + at := F.Mol.Atom(i) + at.SetIndex(at.Index() + shift) + } + } + //Vsites get shifted even if atoms don't. + for i, v := range F.VSites { + F.VSites[i].Index += shift + for j, _ := range v.Atoms { + F.VSites[i].Atoms[j] += shift + } + } +} + +// Changes all indexes in the given terms according to the given map +// modifies the terms and returns them. +func switchterms(m map[int]int, te []*Term) []*Term { + for i, v := range te { + for j, w := range v.Indexes { + te[i].Indexes[j] = m[w] + } + } + return te +} + +// Switches atoms from originalposition to newposition +// Atoms DO NOT get switched. +func Switch(switchmap map[int]int, F *Top) *Top { + fmt.Println(""map!"", switchmap) ////////// + switchterms(switchmap, F.Bonds) + switchterms(switchmap, F.Angles) + switchterms(switchmap, F.Constraints) + switchterms(switchmap, F.Impropers) + switchterms(switchmap, F.Dihedrals) + F.Mol = chem.SwitchAtoms(switchmap, F.Mol) + for i, v := range F.Exclusions { + for j, w := range v { + F.Exclusions[i][j] = switchmap[w] + } + } + for i, v := range F.VSites { + F.VSites[i].Index = switchmap[F.VSites[i].Index] + for j, w := range v.Atoms { + F.VSites[i].Atoms[j] = switchmap[w] + } + } + return F +} + +// not ready +/* +func MakeHole(after int, size int, F *FF) { + F.Bonds = termHole(F.Bonds, after, size) + F.Angles = termHole(F.Angles, after, size) + + for i, v := range F.Exclusions { + for j, w := range v { + if w > after { + F.Exclusions[i][j] += size + } + } + } + + for i, v := range F.VSites { + if v.ID > after { + F.VSites[i].ID += size + } + for j, w := range v.Atoms { + if w > after { + F.Bonds[i].IDs[j] += size + } + } + } + +} +*/ + +/* +type FF struct { + SigmaEpsilon bool //are LJ terms using sigma/epsilon, or C6/C12? + currentHeader string + Mol *chem.Topology + Bonds []*Term + Constraints []*Term + Angles []*Term + Impropers []*Term + Dihedrals []*Term + VSites []*VSite + ATypes []*AtomType + LJ []*LJPair + Exclusions [][]int +} +*/ +","Go" +"Computational Biochemistry","rmera/gochem","ff/innertop.go",".go","7826","331","package ff + +import ( + ""fmt"" + ""math"" + ""strings"" + + chem ""github.com/rmera/gochem"" +) + +// just to make things a bit shorter. +var fi func(string) []string = strings.Fields +var sf func(string, ...any) string = fmt.Sprintf + +func sigmaepsilonToc6c12(sigma, e float64) (c6 float64, c12 float64) { + return 4 * e * math.Pow(sigma, 6), e * 4 * (math.Pow(sigma, 12)) +} + +func c6c12ToSigmaepsilon(c6, c12 float64) (sigma float64, epsilon float64) { + return math.Pow(c6/c12, (1 / 6)), math.Pow(c6, 2) / (4 * c12) +} + +type Top struct { + SigmaEpsilon bool //are LJ terms using sigma/epsilon, or C6/C12? + currentHeader string + Mol *chem.Topology + Bonds []*Term + Constraints []*Term + Angles []*Term + Impropers []*Term + Dihedrals []*Term + VSites []*VSite + ATypes []*AtomType + LJ []*LJPair + Exclusions [][]int +} + +// Returns a string with the terms and the virtual sites +func (F *Top) SmallString() string { + r := make([]string, 0, 30) + r = append(r, ""Bonds"") + for _, v := range F.Bonds { + r = append(r, v.String()) + } + r = append(r, ""Angles"") + for _, v := range F.Angles { + r = append(r, v.String()) + } + r = append(r, ""Impropers"") + for _, v := range F.Impropers { + r = append(r, v.String()) + } + r = append(r, ""Dihedrals"") + for _, v := range F.Dihedrals { + r = append(r, v.String()) + } + r = append(r, ""Virtual Sites"") + for _, v := range F.VSites { + r = append(r, v.String()) + } + return strings.Join(r, ""\n"") +} + +// Returns the ith set of exclusions in 1-based notation +// NOTE: Right now it doesn't work as exclusions _are_ 1 based. +func (F *Top) Exclusions1(i int) []int { + s := F.Exclusions[i] + r := make([]int, len(s)) + for i, v := range s { + r[i] = v + 1 + } + return r +} + +// AssignBonds assigns bonds to a molecule based on a simple distance +// criterium, similar to that described in DOI:10.1186/1758-2946-3-33 +func (F *Top) MolecularBonds(constraints ...bool) error { + F.Mol.RemoveBonds() + fakedistance := 0.0 + list := F.Bonds + if len(constraints) > 0 && constraints[0] { + list = append(list, F.Constraints...) + } + for i, v := range list { + at1 := F.Mol.Atom(v.Indexes[0]) + at2 := F.Mol.Atom(v.Indexes[1]) + b := &chem.Bond{Index: i, Dist: fakedistance, At1: at1, At2: at2} + at1.Bonds = append(at1.Bonds, b) + at2.Bonds = append(at2.Bonds, b) + } + return nil + +} + +// returns a new and empty (but with some values set to defaults) +// FF object. SigmaEpsilon is true if LJ terms are expressed as sigma/epsilon, +// false for C6/C12 +func NewTop(mol *chem.Topology, SigmaEpsilon ...bool) *Top { + se := true //sigma-epsilon true is the form used by Martini3. + if len(SigmaEpsilon) > 0 { + se = SigmaEpsilon[0] + } + ret := new(Top) + ret.Mol = mol + ret.SigmaEpsilon = se + ret.currentHeader = ""NOHEADER"" + return ret +} + +// Returns the nummber of atoms in the topology. +func (F *Top) Len() int { + return F.Mol.Len() +} + +// Returns the epsilon value for the LJ potential of the given +// atom type, if available. Returns zero if the atomtype is defined +// but no LJ potential is assigned to it (normally, if the potentials are +// defined for pair, rather than separately for atoms) and -1 if the type +// is not found. +func (F *Top) VdWForType(t string) float64 { + for _, v := range F.ATypes { + if v.Name == t { + return v.Epsilon + } + } + return -1 +} + +// Returns the epsilon value for the LJ potential of the given +// atom type, if available. Returns zero if the pair is found +// but no LJ potential is assigned to it and -1 if the pair +// is not found. +func (F *Top) VdWForPair(t1, t2 string) float64 { + for _, v := range F.LJ { + w := v.Names + if (t1 == w[0] && t2 == w[1]) || (t1 == w[1] && t2 == w[0]) { + return v.Epsilon + } + } + return -1 +} + +// Returns a copy of the receiver +func (F *Top) Copy() *Top { + F2 := new(Top) + mol := chem.NewTopology(0, 1) + for i := 0; i < F.Mol.Len(); i++ { + a := new(chem.Atom) + a.Copy(F.Mol.Atom(i)) + mol.AppendAtom(a) + } + F2.Mol = mol + F2.SigmaEpsilon = F.SigmaEpsilon + F2.currentHeader = F.currentHeader + F2.Bonds = copyTerms(F.Bonds) + F2.Constraints = copyTerms(F.Constraints) + F2.Angles = copyTerms(F.Angles) + F2.Impropers = copyTerms(F.Impropers) + F2.Dihedrals = copyTerms(F.Dihedrals) + F2.ATypes = make([]*AtomType, 0, len(F.ATypes)) + for _, v := range F.ATypes { + a := new(AtomType) + a.Copy(v) + F2.ATypes = append(F2.ATypes, a) + } + F2.LJ = make([]*LJPair, 0, len(F.LJ)) + for _, v := range F.LJ { + a := new(LJPair) + a.Copy(v) + F2.LJ = append(F2.LJ, a) + } + F2.Exclusions = make([][]int, 0, len(F.Exclusions)) + for _, v := range F.Exclusions { + a := make([]int, len(v)) + copy(a, v) + F2.Exclusions = append(F2.Exclusions, a) + } + F2.VSites = make([]*VSite, 0, len(F.VSites)) + for _, v := range F.VSites { + a := new(VSite) + a.Copy(v) + F2.VSites = append(F2.VSites, a) + } + return F2 +} + +func copyTerms(T []*Term) []*Term { + ret := make([]*Term, 0, len(T)) + for _, v := range T { + t2 := new(Term) + t2.Copy(v) + ret = append(ret, t2) + } + return ret +} + +type AtomType struct { + sigmaEpsilon bool //NOTE: might unexport this. + Name string + Sigma float64 + Epsilon float64 + AtNum int + Mass float64 + Charge float64 + Ptype string +} + +// Copy puts a copy of B in the receiver +func (A *AtomType) Copy(B *AtomType) { + A.sigmaEpsilon = B.sigmaEpsilon + A.Name = B.Name + A.Sigma = B.Sigma + A.Epsilon = B.Epsilon + A.AtNum = B.AtNum + A.Mass = B.Mass + A.Charge = B.Charge + A.Ptype = B.Ptype +} + +func (A *AtomType) C6C12Gro() (float64, float64) { + return sigmaepsilonToc6c12(A.Sigma*chem.A2NM, A.Epsilon*chem.Kcal2KJ) +} + +func (A *AtomType) equal(B any) bool { + b := B.(*AtomType) + return A.Name == b.Name +} + +type LJPair struct { + Names []string + FuncType int + Sigma float64 + Epsilon float64 +} + +// Copies B into the receiver +func (A *LJPair) Copy(B *LJPair) { + if len(A.Names) != len(B.Names) { + A.Names = make([]string, len(B.Names)) + } + copy(A.Names, B.Names) + A.Sigma = B.Sigma + A.Epsilon = B.Epsilon + A.FuncType = B.FuncType +} + +func (A *LJPair) C6C12Gro() (float64, float64) { + return sigmaepsilonToc6c12(A.Sigma*chem.A2NM, A.Epsilon*chem.Kcal2KJ) +} +func (A *LJPair) FillSigmaEpsilonFromC6C12(c6, c12 float64) { + A.Sigma, A.Epsilon = c6c12ToSigmaepsilon(c6, c12) +} + +func (A *LJPair) equal(B any) bool { + b := B.(*LJPair) + sym := A.Names[0] == b.Names[0] && A.Names[1] == b.Names[1] + asym := A.Names[1] == b.Names[0] && A.Names[0] == b.Names[1] + return sym || asym +} + +type VSite struct { + Index int //0-based + N int //0 for virtual_sistesn + FuncType int + Atoms []int //zerobased + Factors []float64 +} + +func (V *VSite) String() string { + r := make([]string, 0, 6) + r = append(r, spf(""%d %1d "", V.Index, V.FuncType)) + for _, v := range V.Atoms { + r = append(r, spf(""%d"", v)) + } + return strings.Join(r, """") +} + +// Copies B into the receiver +func (A *VSite) Copy(B *VSite) { + A.Index = B.Index + A.N = B.N + A.FuncType = B.FuncType + if len(A.Atoms) != len(B.Atoms) { + A.Atoms = make([]int, len(B.Atoms)) + } + copy(A.Atoms, B.Atoms) + if len(A.Factors) != len(B.Factors) { + A.Factors = make([]float64, len(B.Factors)) + } + copy(A.Factors, B.Factors) + +} + +type Term struct { + FuncType uint + Indexes []int //0based + K float64 + Eq float64 + Constraint bool + Vsite bool + RB []float64 +} + +var spf func(string, ...any) string = fmt.Sprintf + +func (T *Term) String() string { + r := make([]string, 0, 5) + r = append(r, spf(""%1d "", T.FuncType)) + for _, v := range T.Indexes { + r = append(r, spf(""%d"", v)) + } + return strings.Join(r, """") +} + +func (A *Term) Copy(B *Term) { + if len(A.Indexes) != len(B.Indexes) { + A.Indexes = make([]int, len(B.Indexes)) + } + copy(A.Indexes, B.Indexes) + + A.FuncType = B.FuncType + A.K = B.K + A.Eq = B.Eq + A.Constraint = B.Constraint + A.Vsite = B.Vsite + if len(A.RB) != len(B.RB) { + A.RB = make([]float64, len(B.RB)) + } + copy(A.RB, B.RB) +} +","Go" +"Computational Biochemistry","rmera/gochem","ff/gromacsheaders.go",".go","4878","179","/* + * main.go, part of goChem + * + * + * Copyright 2024 Raul Mera + * + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + * + */ + +/* +Set of functions to automate some simple editing of top files +*/ + +package ff + +import ( + ""fmt"" + ""os/exec"" + ""regexp"" + ""strconv"" +) + +// Utility functions + +func qerr(err error) { + if err != nil { + panic(err.Error()) + } +} + +// yeah, yeah, it's ugly. If it makes you feel better, it's supposed to be temporary, +// while I'm still figuring out which commands do I need. +func runcq(command string, a ...interface{}) { + w := exec.Command(""sh"", ""-c"", fmt.Sprintf(command, a...)) + w.Run() +} + +// Parses s, which is supposed to contain only integers, to []int +// If the first zerobasedindex is given and true, it subtract 1 to each element of s to make the +// returned slice zero-based. +func parseints(s []string, zerobasedindex ...bool) ([]int, error) { + sub := 0 + if len(zerobasedindex) > 0 && zerobasedindex[0] { + sub = 1 + } + r := make([]int, 0, len(s)) + for _, v := range s { + i, err := strconv.Atoi(v) + if err != nil { + return nil, err + } + r = append(r, i-sub) //Gromacs indexes are 1-based so we subtract 1 to make it zero based, if we are told to. + } + return r, nil +} + +func parsefloats(s ...string) ([]float64, error) { + r := make([]float64, 0, len(s)) + for _, v := range s { + i, err := strconv.ParseFloat(v, 64) + if err != nil { + return nil, err + } + r = append(r, i) + } + return r, nil +} + +type Atom struct { + Index int + MolID int + Name string + PDBName string + MolName string + Charge float64 +} + +//The following is to be removed and placed in a separate ""utils"" module + +type topHeader struct { + wany *regexp.Regexp + vsitesany *regexp.Regexp + spec map[string]*regexp.Regexp + set bool + line string +} + +func NewTopHeader() *topHeader { + R := new(topHeader) + R.Set() + return R + +} + +func (T *topHeader) Set() { + T.wany = regexp.MustCompile(`\[\p{Zs}*.*\p{Zs}*\]`) + T.vsitesany = regexp.MustCompile(`\[\p{Zs}*virtual_sites[01234n]?\p{Zs}*\]`) + T.spec = map[string]*regexp.Regexp{ + ""atoms"": regexp.MustCompile(`\[\p{Zs}*atoms\p{Zs}*\]`), + ""constraints"": regexp.MustCompile(`\[\p{Zs}*constraints\p{Zs}*\]`), + ""bonds"": regexp.MustCompile(`\[\p{Zs}*bonds\p{Zs}*\]`), + ""angles"": regexp.MustCompile(`\[\p{Zs}*angles\p{Zs}*\]`), + ""vsites1"": regexp.MustCompile(`\[\p{Zs}*virtual_sites1\p{Zs}*\]`), + ""vsites2"": regexp.MustCompile(`\[\p{Zs}*virtual_sites2\p{Zs}*\]`), + ""vsites3"": regexp.MustCompile(`\[\p{Zs}*virtual_sites3\p{Zs}*\]`), + ""vsitesn"": regexp.MustCompile(`\[\p{Zs}*virtual_sitesn\p{Zs}*\]`), + ""exclusions"": regexp.MustCompile(`\[\p{Zs}*exclusions\p{Zs}*\]`), + ""molecules"": regexp.MustCompile(`\[\p{Zs}*molecules\p{Zs}*\]`), + ""dihedrals"": regexp.MustCompile(`\[\p{Zs}*dihedrals\p{Zs}*\]`), + ""moleculetype"": regexp.MustCompile(`\[\p{Zs}moleculetype\p{Zs}*\]`), + ""atomtypes"": regexp.MustCompile(`\[\p{Zs}atomtypes\p{Zs}*\]`), + ""nonbond"": regexp.MustCompile(`\[\p{Zs}nonbond_params\p{Zs}*\]`), + ""defaults"": regexp.MustCompile(`\[\p{Zs}*defaults\p{Zs}*\]`), + } + T.set = true + +} + +func (T *topHeader) delcomments(line string) string { + return cleanString(line) +} + +// Returns true if the line is a Gromacs header. It discards comments. +func (T *topHeader) Is(line string) bool { + line = T.delcomments(line) + return T.wany.MatchString(line) +} + +func (T *topHeader) IsVirtualSites(line string) bool { + line = T.delcomments(line) + return T.vsitesany.MatchString(line) +} + +func (T *topHeader) IsDihedrals(line string) bool { + line = T.delcomments(line) + return T.spec[""dihedrals""].MatchString(line) +} + +// Returns a string indicating which Gromacs top file header +// the line is, or an empty string if the line is not a header. +func (T *topHeader) Which(line string) string { + line = T.delcomments(line) + if !T.wany.MatchString(line) { + return """" + } + for k, v := range T.spec { + if v.MatchString(line) { + return k + } + } + return """" +} + +type StringReader interface { + ReadString(byte) (string, error) +} +type StringReplacer interface { + ReplaceString(string) +} +type StringReaderReplacer interface { + StringReader + StringReplacer +} +","Go" +"Computational Biochemistry","rmera/gochem","ff/groio.go",".go","18387","696","package ff + +import ( + ""bufio"" + ""errors"" + ""fmt"" + ""io"" + ""os"" + ""slices"" + ""strconv"" + ""strings"" + + chem ""github.com/rmera/gochem"" +) + +const ( + //Conversions from Gromacs to goChem and back + //From Gromacs to goChem + KbFgro = (chem.KJ2Kcal) / (chem.NM2A * chem.NM2A) //bonds + KangFgro = chem.KJ2Kcal //Gromacs uses radians in force constants. Note this also works for impropers + KRBFgro = chem.KJ2Kcal + BondFgro = chem.NM2A + AngFgro = chem.Deg2Rad + + //From goChem to Gromacs + Kb2gro = 1 / KbFgro + Kang2gro = chem.Kcal2KJ + KRB2gro = chem.Kcal2KJ + Bond2gro = chem.A2NM + Ang2gro = chem.Rad2Deg +) + +// Ryckaert-Bellemans from Gromas to goChem . This modifies the given slice +func rbFromGro(rb []float64) []float64 { + for i, v := range rb { + rb[i] = v * KRBFgro + } + return rb +} + +// This allocates a new slice so the original is not modified +func rbToGro(rb []float64) []float64 { + ret := make([]float64, len(rb)) + copy(ret, rb) + for i, v := range ret { + ret[i] = v * KRB2gro + } + return ret +} + +type cond struct { + reading bool +} + +func newCond() *cond { + c := new(cond) + c.reading = true + return c +} + +// a function to read conditional parts of gromacs topologies +// depending on the defined flags that should be in 'defines' +func (c *cond) read(line string, defines []string) bool { + if strings.HasPrefix(line, ""#ifdef"") { + if slices.Contains(defines, fi(line)[0]) { + c.reading = true + return false + } else { + c.reading = false + return false + } + } + if strings.HasPrefix(line, ""#ifndef"") { + if !slices.Contains(defines, fi(line)[0]) { + c.reading = true + return false + } else { + c.reading = false + return false + } + } + + if strings.HasPrefix(line, ""#else"") { + c.reading = !c.reading + return false + } + if strings.HasPrefix(line, ""#endif"") { + c.reading = true + return false + } + return c.reading +} + +//The high-level functions + +// FillFF will fill the receiver with data from the given StringReader which must be +// in Gromacs itp/top format. If non bonded (Lennard-Jones) terms are present it +// will interpret them as sigma/epsilon if sigmaep is true, as C6/C12 otherwise +// if followIncludes values are given, the first one will determine whether #include +// statements will trigger opening and reading the included file(s). +// NOTE: Many Gromacs headers are supported, but not all. Notably, virtual_sitesX +// headers, where X is between 1-4 are currently _not_ supported. +// Only the generic virtual_sitesn are. +func (F *Top) Fill(r StringReader, followIncludes bool, defines ...string) error { + follow := followIncludes + var err error + var s string + read := newCond() + h := NewTopHeader() + var atindex []int + if F.Mol.Len() == 0 { + atindex = append(atindex, -1) //mark that atoms need to be added. + } + if F.Mol == nil { + return fmt.Errorf(""Can't read topology if no molecule is loaded on the FF object"") + } + for s, err = r.ReadString('\n'); err == nil; s, err = r.ReadString('\n') { + s = cleanString(s) + if s == """" { + continue + } + if !read.read(s, defines) { + continue + } + //This should allow us to 'follow' include files. Probably a risky thing to use. + if strings.Contains(s, ""#include"") && follow { + f := fi(s) + fname := strings.Trim(f[len(f)-1], ""\""'"") + file, err := os.Open(fname) + if err != nil { + return fmt.Errorf(""Failed to include file: %s. Error: %w"", file, err) + } + defer file.Close() + reader := bufio.NewReader(file) + err = F.Fill(reader, follow) + if err != nil { + return fmt.Errorf(""Failed to include file: %s. Error: %w"", file, err) + } + continue + } + if h.Is(s) { + F.currentHeader = h.Which(s) + continue + } + var T *Term + var vs *VSite + var att *AtomType + var LJ *LJPair + + switch F.currentHeader { + + case ""atoms"": + err = F.AtomDataFromGro(s, atindex...) + case ""bonds"": + T, err = TermFromGro(s, F.currentHeader) + F.Bonds = append(F.Bonds, T) + case ""constraints"": + T, err = TermFromGro(s, F.currentHeader) + F.Constraints = append(F.Constraints, T) + case ""angles"": + T, err = TermFromGro(s, F.currentHeader) + F.Angles = append(F.Angles, T) + // case ""impropers"": + // T, err = TermFromGro(s, F.currentHeader) + // F.Impropers = append(F.Impropers, T) + case ""dihedrals"": + T, err = TermFromGro(s, F.currentHeader) + if T.FuncType == 2 { + F.Impropers = append(F.Impropers, T) + } else { + F.Dihedrals = append(F.Dihedrals, T) + } + + //note that I don't support other vsites right now. + case ""vsitesn"": + vs, err = VSitesNFromGro(s) + F.VSites = append(F.VSites, vs) + case ""exclusions"": + err = F.ExclusionsFromGro(s) + case ""atomtypes"": + att, err = AtomTypeFromGro(s, F.SigmaEpsilon) + F.ATypes = append(F.ATypes, att) + case ""nonbond"": + LJ, err = LJPairFromGro(s, F.SigmaEpsilon) + F.LJ = append(F.LJ, LJ) + case ""defaults"": + f := fi(s) + if f[0] == ""1"" && f[1] == ""2"" { + F.SigmaEpsilon = true + } else { + F.SigmaEpsilon = false + } + default: + continue + + } + + if err != nil { + return fmt.Errorf(""Couldn't read header %s. Line: %s. Error: %w"", F.currentHeader, s, err) + } + } + if errors.Is(err, io.EOF) { + err = nil + } + return err +} + +func (F *Top) AllToGro(r io.StringWriter) (err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf(""%s"", r) + } + }() + if len(F.ATypes) > 0 { + _, err = r.WriteString(""[ atomtypes ]\n"") + qerr(err) + printGro(r, F.ATypes, 1, 1) + } + if len(F.LJ) > 0 { + _, err = r.WriteString(""\n[ nonbond_params ]\n"") + qerr(err) + printGro(r, F.LJ, 1, 1) + } + _, err = r.WriteString(""\n[ atoms ]\n"") + qerr(err) + for i := 0; i < F.Mol.Len(); i++ { + _, err = r.WriteString(F.Atom2Gro(i)) + qerr(err) + } + _, err = r.WriteString(""\n[ bonds ]\n"") + printGro(r, F.Bonds, Bond2gro, Kb2gro) + _, err = r.WriteString(""\n[ constraints ]\n"") + printGro(r, F.Constraints, Bond2gro, Kb2gro) + _, err = r.WriteString(""\n[ exclusions ]\n"") + printExcluGro(r, F.Exclusions) + _, err = r.WriteString(""\n[ angles ]\n"") + printGro(r, F.Angles, Ang2gro, Kang2gro) + _, err = r.WriteString(""\n[ dihedrals ]\n"") + printGro(r, F.Dihedrals, Ang2gro, Kang2gro) + _, err = r.WriteString(""; Impropers\n"") + printGro(r, F.Impropers, Ang2gro, Kang2gro) + _, err = r.WriteString(""\n[ virtual_sitesn ]\n"") + //while the ToGro() signature for the interface + //printGo takes requires returning an error, the only + //implementation that actually has an error to return + //is that of VSites. + err = printGro(r, F.VSites, 1, 1) + qerr(err) + + return nil +} + +/* +type FF struct { + SigmaEpsilon bool //are LJ terms using sigma/epsilon, or C6/C12? + currentHeader string + Mol *chem.Topology + Bonds []*Term + Constraints []*Term + Angles []*Term + Impropers []*Term + Dihedrals []*Term + VSites []*VSite + ATypes []*AtomType + LJ []*LJPair + Exclusions [][]int +} +*/ + +type groer interface { + ToGro(float64, float64) (string, error) +} + +func printGro[G ~[]E, E groer](r io.StringWriter, g G, equnit, kunit float64) error { + for _, v := range g { + m, e := v.ToGro(equnit, kunit) + if e != nil { + return e + } + _, e = r.WriteString(m) + if e != nil { + return e + } + } + return nil +} + +func printExcluGro(r io.StringWriter, g [][]int) error { + for _, v := range g { + v1 := exclusion(v) + m, e := v1.ToGro() + if e != nil { + return e + } + _, e = r.WriteString(m) + if e != nil { + return e + } + } + return nil +} + +// Returns a string without gromacs comments (sequences starting with ';'), +// trailing and leading spaces, tabs and newlines +func cleanString(s string) string { + f := strings.Split(s, "";"")[0] + return strings.Trim(f, ""\n\t "") + +} + +func (F *Top) ExclusionsFromGro(s string) error { + ex, err := parseints(fi(s), true) + if err != nil { + return err + } + F.Exclusions = append(F.Exclusions, ex) + return nil + +} + +type exclusion []int + +func (e exclusion) ToGro() (string, error) { + ret := make([]string, 0, len(e)+1) + for _, v := range e { + ret = append(ret, sf(""%4d"", v+1)) //Gromacs indexes from 1 + } + ret = append(ret, ""\n"") + return strings.Join(ret, "" ""), nil + +} + +//NOTE: It's a pain in the neck, but I should return errors in these cases instead of panicking. +// Go, I love you, but I do wish I wouldn't have to write a gazillion 'if err!=nil {return err}'12 + +// Adds the data in the gromacs-topology atom-section string to the atom with index index[0] in the +// molecule in ff. IF index is not given, the function will search the molecule to add the data to the +// atom that matches the ID on the topology string. If a negative index is given, AtomDataFromGro will +// create a new atom and append it to FF.Mol +func (F *Top) AtomDataFromGro(s string, index ...int) (err error) { + s = cleanString(s) + var at *chem.Atom + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf(""%s"", r) + } + }() + ix := -1 + if len(index) > 0 { + ix = index[0] + if index[0] < 0 { + F.Mol.AppendAtom(&chem.Atom{}) + ix = F.Mol.Len() - 1 + } + } + l := fi(s) + ID, err := strconv.Atoi(l[0]) + if ix >= 0 { + at = F.Mol.Atom(ix) + at.ID = ID + } else { + for i := 0; i < F.Mol.Len(); i++ { + a := F.Mol.Atom(i) + if a.ID == ID { + at = a + } + } + } + if at == nil { + // println(""index:"", ix) ////////////////////////////////// + err = fmt.Errorf(""Couldn't find atom with ID %d"", ID) + return + } + qerr(err) + at.Symbol = l[1] + at.MolID, err = strconv.Atoi(l[2]) + qerr(err) + at.MolName = l[3] + at.Name = l[4] + at.Charge, err = strconv.ParseFloat(l[6], 64) + qerr(err) + return nil +} + +// Writes the ith (0-based) atom in the FF molecule to a Gromacs sopology line +func (F *Top) Atom2Gro(i int) string { + A := F.Mol.Atom(i) + return fmt.Sprintf("" %5d %4s %5d %4s %4s %5d %6.4f \n"", A.ID, A.Symbol, A.MolID, A.MolName, A.Name, A.ID, A.Charge) +} + +// Returns a term containing the information in the GromacsTop-formatted string s, +// given that the string is part of the header header. +func TermFromGro(s, header string) (T *Term, err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf(""%s"", r) + } + }() + T = new(Term) + l := strings.Fields(cleanString(s)) + + //first the 'special' cases. + + //r-b terms. don't have equilibrium values or force constants. + if header == ""dihedrals"" && len(l) == 11 { + // Ryckaert-Bellemans entonces + qerr(err) + T.Indexes, err = parseints(l[:4], true) + qerr(err) + T.FuncType = 3 + T.RB, err = parsefloats(l[5:]...) + T.RB = rbFromGro(T.RB) + qerr(err) + if len(T.RB) != 6 { + err = fmt.Errorf(""R-B term detected but read %d parameters instead of the 6 expected"", len(T.RB)) + T = nil + return + } + return + } + //constraints are especial because they lack force constants. + if header == ""constraints"" { + qerr(err) + T.Indexes, err = parseints(l[:2], true) + qerr(err) + T.Constraint = true + var ft int + ft, err = strconv.Atoi(l[2]) + qerr(err) + T.FuncType = uint(ft) + // println(T.FuncType, ""CONSTRAINTTYPE"") /////////////////////////////////// + T.Eq, err = strconv.ParseFloat(l[3], 64) //could be 3 if there is a function type but I don't think there is. Check + qerr(err) + T.Eq *= BondFgro //unit + return + } + //everything else is: atom1 ... atom(ats) functype eqval fconst + var ats int = -1 + var equnits float64 + var kunits float64 + switch header { + case ""bonds"": + ats = 2 + equnits = BondFgro + kunits = KbFgro + case ""angles"": + ats = 3 + equnits = AngFgro + kunits = KangFgro + case ""impropers"": + ats = 4 + equnits = AngFgro + kunits = KangFgro + case ""dihedrals"": + ats = 4 + equnits = AngFgro + kunits = KangFgro + } + + qerr(err) + T.Indexes, err = parseints(l[:ats], true) + qerr(err) + T.Constraint = false + var ft int + ft, err = strconv.Atoi(l[ats]) + qerr(err) + T.FuncType = uint(ft) + T.Eq, err = strconv.ParseFloat(l[ats+1], 64) //could be 3 if there is a function type but I don't think there is. Check + qerr(err) + T.Eq *= equnits + T.K, err = strconv.ParseFloat(l[ats+2], 64) //could be 3 if there is a function type but I don't think there is. Check + qerr(err) + T.K *= kunits + return + +} + +func (T *Term) writeAtoms(zerobased ...bool) string { + add := 1 + if len(zerobased) > 0 && zerobased[0] { + add = 0 + } + r := make([]string, 0, len(T.Indexes)) + for _, v := range T.Indexes { + r = append(r, fmt.Sprintf(""%4d"", v+add)) + } + return strings.Join(r, "" "") +} + +// Writes the term to a string in Gromacs top format. +// Requires the unit conversion factors, which depends on what is in the term. +func (T *Term) ToGro(equnit, kunit float64) (string, error) { + if equnit <= 0 { + equnit = 1.0 + } + if kunit <= 0 { + kunit = 1.0 + } + ret := make([]string, 0, 15) + ret = append(ret, T.writeAtoms()) + if T.Vsite { + return """", nil //placeholder + } + flf := ""%6.2f"" //float format + ret = append(ret, fmt.Sprintf(""%1d"", T.FuncType)) + + if len(T.RB) == 0 { + ret = append(ret, fmt.Sprintf(flf, T.Eq*equnit)) + } + if !T.Constraint && len(T.RB) == 0 { + ret = append(ret, fmt.Sprintf(flf, T.K*kunit)) + } + if len(T.RB) > 0 && len(T.RB) != 6 { + panic(fmt.Sprintf(""grotop/Term.String: R-B potential must have 6 parameters, got %d"", len(T.RB))) + } + + RB := rbToGro(T.RB) + + for _, v := range RB { + // ret = append(ret, ""nowe"", fmt.Sprintf(""****%6.4f****"", v)) /////////////////////// + ret = append(ret, fmt.Sprintf(flf, v)) + } + ret = append(ret, ""\n"") + + return strings.Join(ret, "" ""), nil +} + +// Returns a *VSite witht he information in +// the string s containing a virtual_sitesn line +func VSitesNFromGro(s string) (vsit *VSite, err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf(""%s"", r) + } + }() + vsit = new(VSite) + f := strings.Fields(cleanString(s)) + id, err := strconv.Atoi(f[0]) + qerr(err) + typ, err := strconv.Atoi(f[1]) + qerr(err) + if id < 0 || typ < 0 { + return nil, fmt.Errorf(""ill-formatted vsiten string: %s"", s) + } + vsit.Index = id - 1 + vsit.FuncType = typ + vsit.N = 0 //marks a vsitesn + var indexes []int + + if typ != 3 { + indexes = make([]int, 0, len(f[2:])) + for _, v := range f[2:] { + num, err := strconv.Atoi(v) + if err != nil && num < 0 { + return nil, fmt.Errorf(""ill-formatted vsiten string: %s Error: %w"", s, err) + } + indexes = append(indexes, num-1) + } + } else { + terms := len(f[2:]) + if terms%2 != 0 { + return nil, fmt.Errorf(""ill-formatted vsiten string for site with weights: %s Error: %w"", s, err) + } + ws := make([]float64, 0, len(f[2:])/2) + for i := 0; i < (terms - 1); i++ { + num, err := strconv.Atoi(f[2+i]) + if err != nil && num < 0 { + return nil, fmt.Errorf(""ill-formatted vsiten string: %s Error: %w"", s, err) + } + weight, err := strconv.ParseFloat(f[3+i], 64) + if err != nil && num < 0 { + return nil, fmt.Errorf(""ill-formatted vsiten string: %s Error: %w"", s, err) + } + indexes = append(indexes, num) + ws = append(ws, weight) + } + vsit.Factors = ws + } + vsit.Atoms = indexes + return vsit, err +} + +// Returns a Gromacstop-formatted virtual_siteX string with the information in the receiver +// 'X' depends on the information in the receiver (the field 'N'). +// The arguments are only to fullfill an interface and theyare not used. +func (V *VSite) ToGro(nousedunit1, nousedunit2 float64) (string, error) { + ret := make([]string, 0, 8) + ret = append(ret, sf(""%5d"", V.Index+1)) //Gromacs uses 1-based indexes, goChem uses zero-based. + ret = append(ret, sf(""%2d"", V.FuncType)) + if V.N == 0 { //vsites_n + if V.FuncType == 3 && len(V.Factors) != len(V.Atoms) { + return """", fmt.Errorf(""virtual_site n with weights detected, but weights don't mach atoms"") + } + for i, v := range V.Atoms { + if V.FuncType == 3 { + ret = append(ret, sf(""%5d %5.3f"", v+1, V.Factors[i])) //each couple is an atom and a weight + } else { + ret = append(ret, sf(""%5d"", v+1)) //each couple is an atom and a weight + } + } + } else { + for _, v := range V.Atoms { + ret = append(ret, sf(""%5d"", v+1)) //each couple is an atom and a weight + } + //NOTE:Right now I'm assuming factors are just in Gromacs units, which + //is not consistent with 'regular' goChem units. + //Support for vsites other than 'n' is not quite there yet. + for _, v := range V.Factors { + ret = append(ret, sf(""%5.3f"", v)) //each couple is an atom and a weight + } + + } + ret = append(ret, ""\n"") + return strings.Join(ret, "" ""), nil //I'm not sure about the separator. Just """" could be enough. + +} + +// Reads a string with the appropriate gromacs topology format +// to return a pointer to AtomType. If sigmaep is true, it transforms +// the data in the string from sigma/epsilon to c6/c12 +func AtomTypeFromGro(s string, sigmaep bool) (ret *AtomType, err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf(""Couldn't read atom type from string. Error: %s String:%s"", r, s) + } + }() + s = cleanString(s) + f := fi(s) + ret = new(AtomType) + ret.Name = f[0] + ret.Mass, err = strconv.ParseFloat(f[1], 64) + qerr(err) + ret.Charge, err = strconv.ParseFloat(f[2], 64) + qerr(err) + ret.Ptype = f[3] + //sigmaep is checked twice because there used to be just one pair of values to keep both + //c6/c12 and sigma epsilon. I tried to add a separate sigma epsilong without changing the + //code much. + ret.Sigma, ret.Epsilon, err = c6c12OrSigmaEpsilon(f[4], f[5], sigmaep) + ret.Sigma *= chem.NM2A + ret.Epsilon *= chem.KJ2Kcal + return ret, err +} + +func (A *AtomType) ToGro(unused1, unused2 float64) (string, error) { + var c6, c12 float64 + //s, e := A.Sigma*chem.Kcal2KJ, A.Epsilon*chem.A2NM + + c6, c12 = A.C6C12Gro() + + return sf(""%5s %5.3f %5.3f %1s %6.4e %6.4ef"", A.Name, A.Mass, A.Charge, A.Ptype, c6, c12), nil +} + +func LJPairFromGro(s string, sigmaep bool) (ret *LJPair, err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf(""Couldn't read atom type from string. Error: %s String:%s"", r, s) + } + }() + s = cleanString(s) + f := fi(s) + ret = new(LJPair) + ret.Names = []string{f[0], f[1]} + ret.FuncType, err = strconv.Atoi(f[2]) + qerr(err) + ret.Sigma, ret.Epsilon, err = c6c12OrSigmaEpsilon(f[3], f[4], sigmaep) + ret.Sigma *= chem.NM2A + ret.Epsilon *= chem.KJ2Kcal + return ret, err + +} + +func (L *LJPair) ToGro(unused1, unused2 float64) (string, error) { + c6, c12 := L.C6C12Gro() + return sf(""%5s %5s %1d %6.4e %6.4e\n"", L.Names[0], L.Names[1], L.FuncType, c6, c12), nil +} + +func c6c12OrSigmaEpsilon(num1, num2 string, sigmaepsilon bool) (float64, float64, error) { + var sig, ep float64 + var err error + sig, err = strconv.ParseFloat(num1, 64) + if err != nil { + return -1, -1, err + } + ep, err = strconv.ParseFloat(num2, 64) + if err != nil { + return -1, -1, err + } + if !sigmaepsilon { + + sig, ep = c6c12ToSigmaepsilon(sig, ep) + } + return sig, ep, nil + +} +","Go" +"Computational Biochemistry","rmera/gochem","ff/edit_test.go",".go","218","16","package ff + +import ( + ""fmt"" + ""testing"" +) + +func TestEdit(Te *testing.T) { + m := AddOrDelAtomFunctions(true, 6, 1) + res, err := FuncApplier(""tops/Protein_Mb.itp"", m) + if err != nil { + Te.Error(err) + } + fmt.Print(res) +} +","Go" +"Computational Biochemistry","alanwilter/acpype","acpype_docker.sh",".sh","139","4","#!/usr/bin/env bash + +docker run --rm -i -t -v ""${PWD}"":/wdir -w /wdir -u ""$(id -u ""${USER}""):$(id -g ""${USER}"")"" acpype/acpype acpype ""$@"" +","Shell" +"Computational Biochemistry","alanwilter/acpype","release.sh",".sh","1777","81","#!/usr/bin/env bash + +# Create releases for pip or docker or both + +set -euo pipefail + +version=""$(pcregrep -wor ""\d{4}\.[12]?[0-9]\.[123]?[0-9]"" acpype/__init__.py)"" + +function usage() { + echo ""syntax: $0 < [-p, -d] | -a > to create a release for pip or docker or both"" + echo "" -p : for pip, create wheel and upload to https://pypi.org/project/acpype/ (if you have permission)"" + echo "" -d : for docker, create images and upload to https://hub.docker.com/u/acpype (if you have permission)"" + echo "" -a : do both above"" + echo "" -v : verbose mode, print all commands"" + echo "" -h : prints this message"" + exit 1 +} + +function run_pip() { + echo "">>> Creating pip package"" + poetry build + poetry publish + # python3 -m twine upload --repository testpypi dist/*""$version""* # TestPyPI + # python3 -m twine upload --repository pypi dist/*""$version""* # official release + rm -vfr dist/*""$version""* +} + +function run_docker() { + echo "">>> Creating docker images"" + docker buildx build --platform linux/amd64 -t acpype/acpype:latest -t acpype/acpype:""$version"" . + echo "">>> Pushing docker images"" + docker push acpype/acpype --all-tags + docker image rm acpype/acpype:""$version"" +} + +function run_both() { + run_docker + run_pip +} + +do_pip=false +do_doc=false +do_all=false +verb=false +no_args=true + +while getopts ""adpvh"" optionName; do + case ""$optionName"" in + a) do_all=true ;; + d) do_doc=true ;; + p) do_pip=true ;; + v) verb=true ;; + h) usage ;; + ?) usage ;; + *) usage ;; + esac + no_args=false +done + +if ""${no_args}""; then + usage +elif $do_all && ($do_doc || $do_pip); then + usage +fi + +if ${verb}; then + set -x +fi + +if $do_pip; then + run_pip +fi + +if $do_doc; then + run_docker +fi + +if $do_all; then + run_both +fi +","Shell" +"Computational Biochemistry","alanwilter/acpype","Acpype_API_Jupyter.ipynb",".ipynb","6269","269","{ + ""cells"": [ + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""## For calculating topologies via antechamber"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 9, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""import acpype\n"", + ""from acpype.topol import ACTopol, MolTopol\n"", + ""from glob import glob"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""Directory where the Ligand.acpype folder will be saved"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 10, + ""metadata"": {}, + ""outputs"": [ + { + ""name"": ""stdout"", + ""output_type"": ""stream"", + ""text"": [ + ""2021.12.24\n"" + ] + }, + { + ""data"": { + ""text/plain"": [ + ""['tests/DDD.pdb',\n"", + "" 'tests/dmp.pdb',\n"", + "" 'tests/FFF.pdb',\n"", + "" 'tests/AAA.pdb',\n"", + "" 'tests/benzene.pdb',\n"", + "" 'tests/KKK.pdb']"" + ] + }, + ""execution_count"": 10, + ""metadata"": {}, + ""output_type"": ""execute_result"" + } + ], + ""source"": [ + ""print(acpype.__version__)\n"", + ""glob(\""tests/*.pdb\"")"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 11, + ""metadata"": {}, + ""outputs"": [ + { + ""name"": ""stdout"", + ""output_type"": ""stream"", + ""text"": [ + ""WARNING: no charge value given, trying to guess one...\n"", + ""==> ... charge set to 0\n"" + ] + } + ], + ""source"": [ + ""molecule = ACTopol(\""tests/dmp.pdb\"", chargeType=\""gas\"")"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 12, + ""metadata"": {}, + ""outputs"": [ + { + ""name"": ""stdout"", + ""output_type"": ""stream"", + ""text"": [ + ""==> ... converting pdb input file to mol2 input file\n"", + ""==> * Babel OK *\n"", + ""==> Executing Antechamber...\n"", + ""==> * Antechamber OK *\n"", + ""==> * Parmchk OK *\n"", + ""==> Executing Tleap...\n"", + ""==> * Tleap OK *\n"", + ""==> Removing temporary files...\n"" + ] + } + ], + ""source"": [ + ""molecule.createACTopol()"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 13, + ""metadata"": {}, + ""outputs"": [ + { + ""name"": ""stdout"", + ""output_type"": ""stream"", + ""text"": [ + ""==> Using OpenBabel v.3.1.0\n"", + ""\n"", + ""==> Writing NEW PDB file\n"", + ""\n"", + ""==> Writing CNS/XPLOR files\n"", + ""\n"", + ""==> Writing GROMACS files\n"", + ""\n"", + ""==> Disambiguating lower and uppercase atomtypes in GMX top file, even if identical.\n"", + ""\n"", + ""==> Writing GMX dihedrals for GMX 4.5 and higher.\n"", + ""\n"", + ""==> Writing CHARMM files\n"", + ""\n"", + ""==> Writing pickle file dmp.pkl\n"", + ""==> Removing temporary files...\n"" + ] + } + ], + ""source"": [ + ""molecule.createMolTopol()"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""## For an example of ACPYPE amb2gmx feature:"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 14, + ""metadata"": {}, + ""outputs"": [ + { + ""name"": ""stdout"", + ""output_type"": ""stream"", + ""text"": [ + ""DEBUG: prmtop and inpcrd files loaded\n"", + ""DEBUG: basename defined = 'glycam_exe'\n"", + ""DEBUG: getCoords done\n"", + ""DEBUG: getABCOEFs done\n"", + ""DEBUG: charge to be balanced: total -0.0000000000\n"", + ""DEBUG: balanceCharges done\n"", + ""DEBUG: Balanced TotalCharge -0.0000000000\n"", + ""DEBUG: PBC = None\n"", + ""DEBUG: getAtoms done\n"", + ""DEBUG: getBonds done\n"", + ""DEBUG: getAngles done\n"", + ""DEBUG: getDihedrals done\n"" + ] + } + ], + ""source"": [ + ""mol = MolTopol(acFileXyz=\""tests/glycam_exe.inpcrd\"", acFileTop=\""tests/glycam_exe.prmtop\"", debug=True, amb2gmx=True)"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 15, + ""metadata"": {}, + ""outputs"": [ + { + ""name"": ""stdout"", + ""output_type"": ""stream"", + ""text"": [ + ""==> Writing GROMACS files\n"", + ""\n"", + ""==> Disambiguating lower and uppercase atomtypes in GMX top file, even if identical.\n"", + ""\n"", + ""DEBUG: writing GRO file\n"", + ""DEBUG: Box size estimated\n"", + ""DEBUG: writing POSRE file\n"", + ""DEBUG: atomTypes 11\n"", + ""DEBUG: GMX atomtypes done\n"", + ""DEBUG: atoms 30\n"", + ""DEBUG: GMX atoms done\n"", + ""DEBUG: bonds 30\n"", + ""DEBUG: GMX bonds done\n"", + ""DEBUG: atomPairs 76\n"", + ""DEBUG: GMX pairs done\n"", + ""DEBUG: angles 53\n"", + ""DEBUG: GMX angles done\n"", + ""DEBUG: setProperDihedralsCoef done\n"", + ""DEBUG: properDihedralsCoefRB 79\n"", + ""DEBUG: properDihedralsAlphaGamma 0\n"", + ""DEBUG: properDihedralsGmx45 87\n"", + ""==> Writing GMX dihedrals for GMX 4.5 and higher.\n"", + ""\n"", + ""DEBUG: GMX special proper dihedrals done\n"", + ""DEBUG: improperDihedrals 2\n"", + ""DEBUG: GMX improper dihedrals done\n"", + ""==> Non-default 1-4 scale parameters detected. Converting individually. Please cite:\n"", + ""\n"", + "" BERNARDI, A., FALLER, R., REITH, D., and KIRSCHNER, K. N. ACPYPE update for\n"", + "" nonuniform 1-4 scale factors: Conversion of the GLYCAM06 force field from AMBER\n"", + "" to GROMACS. SoftwareX 10 (2019), 100241. doi: 10.1016/j.softx.2019.100241\""\n"", + ""\n"" + ] + } + ], + ""source"": [ + ""mol.writeGromacsTopolFiles()"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""### Easter egg!\n"", + ""Yep, it's possible to convert to CNS system from Amber *prmtop* and *inpcrd* files."" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 16, + ""metadata"": {}, + ""outputs"": [ + { + ""name"": ""stdout"", + ""output_type"": ""stream"", + ""text"": [ + ""==> Writing NEW PDB file\n"", + ""\n"", + ""==> Writing CNS/XPLOR files\n"", + ""\n"" + ] + } + ], + ""source"": [ + ""mol.writeCnsTopolFiles()"" + ] + } + ], + ""metadata"": { + ""kernelspec"": { + ""display_name"": ""Python 3"", + ""language"": ""python"", + ""name"": ""python3"" + }, + ""language_info"": { + ""codemirror_mode"": { + ""name"": ""ipython"", + ""version"": 3 + }, + ""file_extension"": "".py"", + ""mimetype"": ""text/x-python"", + ""name"": ""python"", + ""nbconvert_exporter"": ""python"", + ""pygments_lexer"": ""ipython3"", + ""version"": ""3.9.7"" + } + }, + ""nbformat"": 4, + ""nbformat_minor"": 4 +} +","Unknown" +"Computational Biochemistry","alanwilter/acpype","update_linux_bins.sh",".sh","2261","104","#!/usr/bin/env bash + +env_name=""ambertools"" +source=""$HOME/mambaforge/envs/${env_name}"" +destination=""acpype/amber_linux"" + +if mamba env list | grep -q "" $env_name ""; then + if [[ ""$1"" == ""-f"" ]]; then + mamba env remove --name ""$env_name"" --yes + mamba create -n ""$env_name"" ambertools --yes + else + echo ""The '$env_name' environment already exists. Use '-f' to force re-run."" + exit 1 + fi +fi + +files=( + bin/bondtype + bin/tleap + bin/atomtype + bin/wrapped_progs/bondtype + bin/wrapped_progs/atomtype + bin/wrapped_progs/antechamber + bin/wrapped_progs/parmchk2 + bin/wrapped_progs/am1bcc + bin/antechamber + bin/parmchk2 + bin/sqm + bin/am1bcc + bin/teLeap + LICENSE + GNU_LGPL_v3 + amber.sh + dat/antechamber + dat/chamber + dat/leap + lib/libcifparse.so + lib/libsff_fortran.so + lib/libnetcdf.so.19 + lib/libmfhdf.so.0 + lib/libmfhdf.so.0.0.0 + lib/libdf.so.0 + lib/libdf.so.0.0.0 + lib/libhdf5_hl.so.310 + lib/libhdf5_hl.so.310.0.2 + lib/libhdf5.so.310 + lib/libhdf5.so.310.2.0 + lib/libcrypto.so.3 + lib/libzip.so.5 + lib/libzip.so.5.5 + lib/libsz.so.2 + lib/libsz.so.2.0.1 +) + +exclude=( + --exclude=__pycache__ + --exclude=*.pyc + --exclude=*.pyo + --exclude=*.log + --exclude=pixmaps/ +) + +rm -fr $destination + +for item in ""${files[@]}""; do + source_path=""${source}/${item}"" + destination_path=""${destination}/${item}"" + pdir=$(dirname ""$destination_path"") + + mkdir -p ""$pdir"" + if [ -d ""$source_path"" ]; then + rsync -av ""${exclude[@]}"" ""$source_path"" ""$pdir"" + else + rsync -av ""${exclude[@]}"" ""$source_path"" ""$destination_path"" + fi +done + +tar xvfz charmmgen.tgz + +pre-commit run -a + +tree -d $destination + +find $destination | wc -l # 569 files, 15 dirs +# acpype/amber_linux +# ├── bin +# │ └── wrapped_progs +# ├── dat +# │ ├── antechamber +# │ ├── chamber +# │ └── leap +# │ ├── cmd +# │ │ └── oldff +# │ ├── lib +# │ │ └── oldff +# │ ├── parm +# │ └── prep +# │ ├── oldff +# │ └── protonated_nucleic +# └── lib +# amber.sh +# GNU_LGPL_v3 +# LICENSE +","Shell" +"Computational Biochemistry","alanwilter/acpype","CONTRIBUTING.md",".md","2510","79","# Instructions for setting up a development environment + +## For Coding + +If using `Linux` with Intel processors, you can skip the `conda` step and directly to [Setting ACPYPE](#setting-acpype). Otherwise: + +### Setting `conda` + +For `Linux` (Ubuntu 20 recommended) and `macOS`. Anyway, `CONDA` is strongly recommended. +Also recommended is GPG key, so do accordingly in [GitHub](https://docs.github.com/articles/generating-a-gpg-key/). + +```bash +curl -sSL https://install.python-poetry.org | python3 - + +conda create -n acpype python=3.9 ambertools openbabel ocl-icd-system ipython gromacs=2019.1 -y +# ocl-icd-system: case you have GPU + +conda activate acpype +``` + +### Setting ACPYPE + +```bash +git clone https://github.com/alanwilter/acpype.git + +cd acpype + +poetry install + +pre-commit install + +pre-commit run -a + +sys=$(perl -e '`uname` eq ""Darwin\n"" ? print ""macos"" : print ""linux""') +cp ./acpype/amber_${sys}/bin/charmmgen $(dirname $(which antechamber)) + +git config user.email _email_ # as seen in 'gpg --list-secret-keys --keyid-format=long' + +git config user.signingkey _singing_key_ # as seen in 'gpg --list-secret-keys --keyid-format=long' + +git config commit.gpgsign true + +pytest --cov=tests --cov=acpype --cov-report=term-missing:skip-covered --cov-report=xml +``` + +If using `VSCode`: + +- Enable `enableCommitSigning` in `settings.json` (**_Workspace_** recommended): + + ```yml + ""git.enableCommitSigning"": true, + ``` + +- Another `VSCode` nuisance, if using its graphic buttons for commit etc.: its environment won't necessarily recognise the dependencies installed via `poetry` under `conda` environment named `acpype` (unless you have started `VSCode` from folder repository with command `code .`). To avoid troubles do: + + ```bash + conda deactivate + poetry install # it will create its own virtualenv + ``` + + You could use this `poetry virtualenv` as the `Python Interpreter` for `VSCode`, however `ambertools`, `gromacs` and `openbabel` won't be available (unless you've had installed them system wide by other means rather than `conda`). + To avoid further troubles, go back to `conda activate acpype` and remember to do the instructions above if you add new dependencies to the project via `poetry`. + +## For Documenting + +Using [Sphinx](https://www.sphinx-doc.org) with theme from `pip install sphinx-rtd-theme`. + +Online documentation provided by [Read the Docs](http://acpype.readthedocs.io). + +To test it locally: + +```bash +cd docs/ +make clean +make html +``` + +Then open `_build/html/index.html` in a browser. +","Markdown" +"Computational Biochemistry","alanwilter/acpype","run_acpype.py",".py","203","11","#!/usr/bin/env python3 + +import re +import sys + +from acpype.cli import init_main + +if __name__ == ""__main__"": + sys.argv[0] = re.sub(r""(-script\.pyw?|\.exe)?$"", """", sys.argv[0]) + sys.exit(init_main()) +","Python" +"Computational Biochemistry","alanwilter/acpype","update_macos_bins.sh",".sh","2819","124","#!/usr/bin/env bash + +env_name=""ambertools"" +source=""$HOME/mambaforge/envs/${env_name}"" +destination=""acpype/amber_macos"" + +if mamba env list | grep -q "" $env_name ""; then + if [[ ""$1"" == ""-f"" ]]; then + mamba env remove --name ""$env_name"" --yes + mamba create -n ""$env_name"" ambertools --yes + else + echo ""The '$env_name' environment already exists. Use '-f' to force re-run."" + exit 1 + fi +fi + +files=( + bin/bondtype + bin/tleap + bin/atomtype + bin/wrapped_progs/bondtype + bin/wrapped_progs/atomtype + bin/wrapped_progs/antechamber + bin/wrapped_progs/parmchk2 + bin/wrapped_progs/am1bcc + bin/antechamber + bin/parmchk2 + bin/sqm + bin/am1bcc + bin/teLeap + LICENSE + GNU_LGPL_v3 + amber.sh + dat/antechamber + dat/chamber + dat/leap + lib/libcifparse.dylib + lib/libsff_fortran.dylib + lib/libnetcdf.19.dylib + lib/libmfhdf.0.dylib + lib/libmfhdf.dylib + lib/libdf.dylib + lib/libdf.0.dylib + lib/libhdf5_hl.310.dylib + lib/libhdf5_hl.dylib + lib/libhdf5.310.dylib + lib/libhdf5.dylib + lib/libcrypto.3.dylib + lib/libzip.5.5.dylib + lib/libzip.5.dylib + lib/libsz.2.dylib + lib/libsz.2.0.1.dylib + lib/libblosc.1.dylib + lib/libblosc.1.21.5.dylib + lib/libzstd.1.dylib + lib/libzstd.1.5.5.dylib + lib/liblz4.1.dylib + lib/liblz4.1.9.4.dylib + lib/libsnappy.1.dylib + lib/libsnappy.1.1.10.dylib + lib/libjpeg.8.dylib + lib/libjpeg.8.3.2.dylib + lib/libgfortran.5.dylib + lib/libquadmath.0.dylib + lib/libgcc_s.1.1.dylib + lib/libarpack.2.dylib + lib/libarpack.2.1.0.dylib + lib/libopenblas.0.dylib + lib/libblas.3.dylib + lib/liblapack.3.dylib + lib/libopenblas.0.dylib + lib/libomp.dylib +) + +exclude=( + --exclude=__pycache__ + --exclude=*.pyc + --exclude=*.pyo + --exclude=*.log + --exclude=pixmaps/ +) + +rm -fr $destination + +for item in ""${files[@]}""; do + source_path=""${source}/${item}"" + destination_path=""${destination}/${item}"" + pdir=$(dirname ""$destination_path"") + + mkdir -p ""$pdir"" + if [ -d ""$source_path"" ]; then + rsync -av ""${exclude[@]}"" ""$source_path"" ""$pdir"" + else + rsync -av ""${exclude[@]}"" ""$source_path"" ""$destination_path"" + fi +done + +tar xvfz charmmgen_macos.tgz + +pre-commit run -a + +tree -d $destination + +find $destination | wc -l # 584 files, 16 dirs +# acpype/amber_linux +# ├── bin +# │ └── wrapped_progs +# ├── dat +# │ ├── antechamber +# │ ├── chamber +# │ └── leap +# │ ├── cmd +# │ │ └── oldff +# │ ├── lib +# │ │ └── oldff +# │ ├── parm +# │ └── prep +# │ ├── oldff +# │ └── protonated_nucleic +# └── lib +# amber.sh +# GNU_LGPL_v3 +# LICENSE +","Shell" +"Computational Biochemistry","alanwilter/acpype","recipe/setup_conda.py",".py","1005","34",""""""" +AnteChamber PYthon Parser interfacE + +A tool based in Python to use Antechamber to generate topologies for chemical compounds +and to interface with others python applications like CCPN or ARIA. +"""""" + +from setuptools import setup + +dver: dict = {} +with open(""./acpype/__init__.py"") as fp: + exec(fp.read(), dver) + +setup( + name=""acpype"", + version=dver[""__version__""], + description=""ACPYPE - AnteChamber PYthon Parser interfacE"", + classifiers=[ + ""Intended Audience :: Science/Research"", + ""Natural Language :: English"", + ""Programming Language :: Python :: 3.9"", + ""Topic :: Scientific/Engineering :: Bio-Informatics"", + ], + url=""https://alanwilter.github.io/acpype/"", + author=""Alan Silva"", + author_email=""alanwilter@gmail.com"", + license=""GPL-3.0-or-later"", + packages=[""acpype""], + keywords=[""acpype"", ""amber"", ""gromacs""], + include_package_data=True, + entry_points={""console_scripts"": [""acpype = acpype.cli:init_main""]}, + zip_safe=False, +) +","Python" +"Computational Biochemistry","alanwilter/acpype","recipe/build.sh",".sh","119","3","#!/usr/bin/env sh +$PYTHON ""$RECIPE_DIR""/setup_conda.py install --single-version-externally-managed --record=record.txt +","Shell" +"Computational Biochemistry","alanwilter/acpype","legacy/CcpnToAcpype.py",".py","12343","376","import os +import random +import string +import sys +import time +import traceback +from shutil import rmtree + +from ccpnmr.format.converters import ( + Mol2Format, # type: ignore + PdbFormat, # type: ignore +) + +from acpype.cli import ACTopol, elapsedTime, header + +letters = string.ascii_letters + + +def dirWalk(adir): + ""walk all files for a dir"" + for f in os.listdir(adir): + fullpath = os.path.abspath(os.path.join(adir, f)) + if os.path.isdir(fullpath) and not os.path.islink(fullpath): + yield from dirWalk(fullpath) + else: + yield fullpath + + +def addMolPep(cnsPepPath, molName): + """""" + Add info about MOL in CNS topol*.pep file + input: cns pep file path to be modified and MOL name + """""" + txt = f""first IONS tail + {molName} end\nlast IONS head - {molName} end\n\n"" + pepFile = open(cnsPepPath).read() + if txt in pepFile: + print(f""{molName} already added to {cnsPepPath}"") + return False + pepFile = pepFile.splitlines(1) + pepFile.reverse() + for line in pepFile: + if line != ""\n"": + if ""SET ECHO"" in line.upper(): + an_id = pepFile.index(line) + pepFile.insert(an_id + 1, txt) + break + pepFile.reverse() + nPepFile = open(cnsPepPath, ""w"") + nPepFile.writelines(pepFile) + nPepFile.close() + print(f""{molName} added to {cnsPepPath}"") + return True + + +def addMolPar(cnsParPath, molParPath): + """""" + Add parameters of MOL.par in CNS paralldhg*.pro file + input: cns par file path to be modified and MOL.par file + """""" + + def formatLine(line, n): + items = line.split() + mult = eval(items[6]) + if len(items) < len(items) + (mult - 1) * 3: + for i in range(1, mult): + line += molFile[n + i] + n += mult - 1 + return line, n + + pars = [""BOND"", ""ANGLe"", ""DIHEdral"", ""IMPRoper"", ""NONBonded""] + molName = os.path.basename(molParPath).split(""_"")[0] + txt = ""! Parameters for Heterocompound %s\n"" % molName + end = ""! end %s\n\n"" % molName + + parFile = open(cnsParPath).read() + if txt in parFile: + print(f""{molName} already added to {cnsParPath}"") + return False + + molFile = open(molParPath).readlines() + molList = [] + n = 0 + for n in range(len(molFile)): + line = molFile[n] + if line.strip()[0:4] in [x[0:4] for x in pars]: + if ""DIHE"" in line and ""MULT"" in line: + line, n = formatLine(line, n) + elif ""IMPR"" in line and ""MULT"" in line: + line, n = formatLine(line, n) + molList.append(line) + n += 1 + + parList = parFile.splitlines(1) + parList.reverse() + for line in parList: + if line != ""\n"": + if ""SET ECHO"" in line.upper(): + an_id = parList.index(line) + break + parList.insert(an_id + 1, txt) + for line in molList: # NOTE: Check if pars are there, but using string size, need to be smarter + if pars[0][:4] in line: # BOND + parTxt = line[:16] + revParTxt = reverseParLine(parTxt) + if parTxt not in parFile and revParTxt not in parFile: + parList.insert(an_id + 1, line) + if pars[4][:4] in line: # NONB + if line[:16] not in parFile: + parList.insert(an_id + 1, line) + if pars[1][:4] in line: # ANGLe + parTxt = line[:23] + revParTxt = reverseParLine(parTxt) + if parTxt not in parFile and revParTxt not in parFile: + parList.insert(an_id + 1, line) + if pars[2][:4] in line or pars[3][:4] in line: # DIHE and IMPR + if line[:32] not in parFile: + parList.insert(an_id + 1, line) + parList.insert(an_id + 1, end) + + parList.reverse() + nParFile = open(cnsParPath, ""w"") + nParFile.writelines(parList) + nParFile.close() + print(f""{molName} added to {cnsParPath}"") + return True + + +def reverseParLine(txt): + lvec = txt.split() + head = lvec[0] + pars = lvec[1:] + pars.reverse() + for item in [""%6s"" % x for x in pars]: + head += item + return head + + +def addMolTop(cnsTopPath, molTopPath): + """""" + Add topol of MOL.top in CNS topalldhg*.pro file + input: cns top file path to be modified and MOL.top file + """""" + keys = [""RESIdue"", ""GROUP"", ""ATOM"", ""BOND"", ""ANGLe"", ""DIHEdral"", ""IMPRoper""] + molName = os.path.basename(molTopPath).split(""_"")[0] + ions = ""\nPRESidue IONS\nEND\n\n"" + + txt = ""! Topol for Heterocompound %s\n"" % molName + end = ""\n"" + + topFile = open(cnsTopPath).read() + if txt in topFile: + print(f""{molName} already added to {cnsTopPath}"") + return False + + molFile = open(molTopPath).readlines() + molMass = [] + molTop = [] + + for line in molFile: + if line.strip()[0:4] == ""MASS"": + molMass.append(line) + if line.strip()[0:4] in [x[0:4] for x in keys]: + molTop.append(line) + if line.strip()[0:3] == ""END"": + molTop.append(line) + + topList = topFile.splitlines(1) + topList.reverse() + for line in topList: + if line != ""\n"": + if ""SET ECHO"" in line.upper(): + an_id = topList.index(line) + break + + if ions not in topFile: + topList.insert(an_id + 1, ions) + + topList.insert(an_id + 1, txt) + for line in molMass: + if line not in topFile: # NOTE: comparing strings! + topList.insert(an_id + 1, line) + for line in molTop: + topList.insert(an_id + 1, line) + topList.insert(an_id + 1, end) + + topList.reverse() + nTopFile = open(cnsTopPath, ""w"") + nTopFile.writelines(topList) + nTopFile.close() + print(f""{molName} added to {cnsTopPath}"") + return True + + +class AcpypeForCcpnProject: + """""" + Class to take a Ccpn project, check if it has an + unusual chem comp and call ACPYPE API to generate + a folder with acpype results + usage: + acpypeProject = AcpypeForCcpnProject(ccpnProject) + acpypeProject.run(kw**) + acpypeDictFilesList = acpypeProject.acpypeDictFiles + returns a dict with list of the files inside chem chomp acpype folder + or None + """""" + + def __init__(self, project): + self.project = project + self.heteroMols = None + self.acpypeDictFiles = None + + def getHeteroMols(self): + """"""Return a list [] of chains obj"""""" + ccpnProject = self.project + maxNumberAtoms = 300 # MAXATOM in AC is 256, then it uses memory reallocation + other = [] + molSys = ccpnProject.findFirstMolSystem() + for chain in molSys.chains: + if chain.molecule.molType == ""other"": + numRes = len(chain.residues) + if numRes == 1: + numberAtoms = next(len(x.atoms) for x in chain.residues) + if numberAtoms > maxNumberAtoms: + print(""molecule with %i (> %i) atoms; skipped by acpype"" % (numberAtoms, maxNumberAtoms)) + else: + other.append(chain) + else: + print(""molType 'other', chain %s with %i residues; skipped by acpype"" % (chain, numRes)) + self.heteroMols = other + return other + + def run( + self, + chain=None, + chargeType=""bcc"", + chargeVal=None, + guessCharge=False, + multiplicity=""1"", + atomType=""gaff2"", + force=False, + basename=None, + debug=False, + outTopol=""all"", + engine=""tleap"", + allhdg=False, + timeTol=36000, + qprog=""sqm"", + ekFlag=None, + outType=""mol2"", + ): + ccpnProject = self.project + + if chain: + other = [chain] + else: + other = self.getHeteroMols() + + if not other: + print(""WARN: no molecules entitled for ACPYPE"") + return None + + acpypeDict = {} + + for chain in other: + if chargeVal is None and not guessCharge: + chargeVal = chain.molecule.formalCharge + # pdbCode = ccpnProject.name + res = chain.findFirstResidue() + resName = res.ccpCode.upper() + if chargeVal is None: + print(f""Running ACPYPE for '{resName} : {chain.molecule.name}' and trying to guess net charge"") + else: + print(f""Running ACPYPE for '{resName} : {chain.molecule.name}' with charge '{chargeVal}'"") + random.seed() + d = [random.choice(letters) for x in range(10)] + randString = """".join(d) + randString = ""test"" + dirTemp = ""/tmp/ccpn2acpype_%s"" % randString + if not os.path.exists(dirTemp): + os.mkdir(dirTemp) + + if outType == ""mol2"": + resTempFile = os.path.join(dirTemp, ""%s.mol2"" % resName) + else: + resTempFile = os.path.join(dirTemp, ""%s.pdb"" % resName) + + entry = ccpnProject.currentNmrEntryStore.findFirstEntry() + strucGen = entry.findFirstStructureGeneration() + refStructure = strucGen.structureEnsemble.sortedModels()[0] + + if outType == ""mol2"": + mol2Format = Mol2Format.Mol2Format(ccpnProject) + mol2Format.writeChemComp( + resTempFile, + chemCompVar=chain.findFirstResidue().chemCompVar, + coordSystem=""pdb"", + minimalPrompts=True, + forceNamingSystemName=""XPLOR"", + ) + else: + pdbFormat = PdbFormat.PdbFormat(ccpnProject) + pdbFormat.writeCoordinates( + resTempFile, + exportChains=[chain], + structures=[refStructure], + minimalPrompts=True, + forceNamingSystemName=""XPLOR"", + ) + + origCwd = os.getcwd() + os.chdir(dirTemp) + + t0 = time.time() + print(header) + + try: + molecule = ACTopol( + resTempFile, + chargeType=chargeType, + chargeVal=chargeVal, + debug=debug, + multiplicity=multiplicity, + atomType=atomType, + force=force, + outTopol=outTopol, + engine=engine, + allhdg=allhdg, + basename=basename, + timeTol=timeTol, + qprog=qprog, + ekFlag='''""%s""''' % ekFlag, + ) + + if not molecule.acExe: + molecule.printError(""no 'antechamber' executable... aborting!"") + hint1 = ""HINT1: is 'AMBERHOME' environment variable set?"" + hint2 = ( + ""HINT2: is 'antechamber' in your $PATH?"" + + "" What 'which antechamber' in your terminal says?"" + + "" 'alias' doesn't work for ACPYPE."" + ) + molecule.printMess(hint1) + molecule.printMess(hint2) + sys.exit(1) + + molecule.createACTopol() + molecule.createMolTopol() + acpypeFailed = False + except Exception: + raise + _exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() + print(""ACPYPE FAILED: %s"" % exceptionValue) + if debug: + traceback.print_tb(exceptionTraceback, file=sys.stdout) + acpypeFailed = True + + execTime = int(round(time.time() - t0)) + + if execTime == 0: + msg = ""less than a second"" + else: + msg = elapsedTime(execTime) + try: + rmtree(molecule.tmpDir) + except Exception: + raise + print(""Total time of execution: %s"" % msg) + if not acpypeFailed: + acpypeDict[resName] = [x for x in dirWalk(os.path.join(dirTemp, ""%s.acpype"" % resName))] + else: + acpypeDict[resName] = [] + # sys.exit(1) + + os.chdir(origCwd) + self.acpypeDictFiles = acpypeDict +","Python" +"Computational Biochemistry","alanwilter/acpype","acpype/mol.py",".py","4075","153",""""""" + Constructors to define and store the system's topology + + It will create instances for Atoms, AtomTypes, Bonds, Angles and Dihedrals + where the topology (the relationships between atoms) is defined and + paramenters are stored. + + Example: + + >>> atom = acpype.mol.Atom(...) # to be improved + + Attributes: + acpype.mol.Atom : define Atom + acpype.mol.AtomType : define AtomType +"""""" + + +from typing import List + +from acpype.params import Pi + + +class AtomType: + + """""" + AtomType per atom in gaff or amber. + """""" + + def __init__(self, atomTypeName, mass, ACOEF, BCOEF): + self.atomTypeName = atomTypeName + self.mass = mass + self.ACOEF = ACOEF + self.BCOEF = BCOEF + + def __str__(self): + return """" % self.atomTypeName + + def __repr__(self): + return """" % self.atomTypeName + + +class Atom: + r"""""" + Atom Object Definition + + Charges in *prmtop* file are divided by ``18.2223`` to be converted + in units of the electron charge. + + To convert ``ACOEF`` and ``BCOEF`` to ``r0`` (Å) and ``epsilon`` (ε: kcal/mol), as seen + in ``gaff.dat`` for example, for a same atom type (``i = j``): + + .. math:: + r_0 &= 1/2 * (2 * A_{coef}/B_{coef})^{1/6} \\ + \epsilon &= 1/(4 * A_{coef}) * B_{coef}^2 + + To convert ``r0`` and ``epsilon`` to ``ACOEF`` and ``BCOEF``: + + .. math:: + A_{coef} &= \sqrt{\epsilon_i * \epsilon_j} * (r_{0i} + r_{0j})^{12} \\ + B_{coef} &= 2 * \sqrt{\epsilon_i * \epsilon_j} * (r_{0i} + r_{0j})^6 \\ + &= 2 * A_{coef}/(r_{0i} + r_{0j})^6 + + where index ``i`` and ``j`` for atom types. + Coordinates are given in Å and masses in Atomic Mass Unit. + + Returns: + acpype.mol.Atom: atom object + """""" + + def __init__( + self, atomName: str, atomType: AtomType, id_: int, resid: int, mass: float, charge: float, coord: List[float] + ): + """""" + Args: + atomName (str): atom name + atomType (AtomType): atomType object + id_ (int): atom number index + resid (int): residues number index + mass (float): atom mass + charge (float): atom charge + coord (List[float]): atom (x,y,z) coordinates + """""" + self.atomName = atomName + self.atomType = atomType + self.id = id_ + self.cgnr = id_ + self.resid = resid + self.mass = mass + self.charge = charge # / qConv + self.coords = coord + + def __str__(self): + return f"""" + + def __repr__(self): + return f"""" + + +class Bond: + + """""" + attributes: pair of Atoms, spring constant (kcal/mol), dist. eq. (Ang) + """""" + + def __init__(self, atoms, kBond, rEq): + self.atoms = atoms + self.kBond = kBond + self.rEq = rEq + + def __str__(self): + return f""<{self.atoms}, r={self.rEq}>"" + + def __repr__(self): + return f""<{self.atoms}, r={self.rEq}>"" + + +class Angle: + + """""" + attributes: 3 Atoms, spring constant (kcal/mol/rad^2), angle eq. (rad) + """""" + + def __init__(self, atoms, kTheta, thetaEq): + self.atoms = atoms + self.kTheta = kTheta + self.thetaEq = thetaEq # rad, to convert to degree: thetaEq * 180/Pi + + def __str__(self): + return f""<{self.atoms}, ang={self.thetaEq * 180 / Pi:.2f}>"" + + def __repr__(self): + return f""<{self.atoms}, ang={self.thetaEq * 180 / Pi:.2f}>"" + + +class Dihedral: + + """""" + attributes: 4 Atoms, spring constant (kcal/mol), periodicity, + phase (rad) + """""" + + def __init__(self, atoms, kPhi, period, phase): + self.atoms = atoms + self.kPhi = kPhi + self.period = period + self.phase = phase # rad, to convert to degree: kPhi * 180/Pi + + def __str__(self): + return f""<{self.atoms}, ang={self.phase * 180 / Pi:.2f}>"" + + def __repr__(self): + return f""<{self.atoms}, ang={self.phase * 180 / Pi:.2f}>"" +","Python" +"Computational Biochemistry","alanwilter/acpype","acpype/__init__.py",".py","2506","59",""""""" + The Package + + Requirements: + - ``Python 3.9`` or higher + - ``Antechamber`` (from ``AmberTools`` preferably) + - ``OpenBabel`` (optional, but strongly recommended) + + This code is released under **GNU General Public License V3**. + + **<<< NO WARRANTY AT ALL!!! >>>** + + It was inspired by: + + - ``amb2gmx.pl`` (Eric Sorin, David Mobley and John Chodera) and depends on Antechamber and Openbabel + - `YASARA Autosmiles `_ (Elmar Krieger) + - ``topolbuild`` (Bruce Ray) + - ``xplo2d`` (G.J. Kleywegt) + + For Non-uniform 1-4 scale factor conversion (e.g. if using ``GLYCAM06``), please cite: + + BERNARDI, A., FALLER, R., REITH, D., and KIRSCHNER, K. N. ACPYPE update for + nonuniform 1-4 scale factors: Conversion of the GLYCAM06 force field from AMBER + to GROMACS. SoftwareX 10 (2019), 100241. + doi: `10.1016/j.softx.2019.100241 `_ + + For Antechamber, please cite: + + 1. WANG, J., WANG, W., KOLLMAN, P. A., and CASE, D. A. Automatic atom type and + bond type perception in molecular mechanical calculations. Journal of Molecular + Graphics and Modelling 25, 2 (2006), 247-260. + doi: `10.1016/j.jmgm.2005.12.005 `_ + 2. WANG, J., WOLF, R. M., CALDWELL, J. W., KOLLMAN, P. A., and CASE, D. A. + Development and testing of a General Amber Force Field. Journal of Computational + Chemistry 25, 9 (2004), 1157-1174. + doi: `10.1002/jcc.20035 `_ + + If you use this code, I am glad if you cite: + + SOUSA DA SILVA, A. W. & VRANKEN, W. F. + ACPYPE - AnteChamber PYthon Parser interfacE. + BMC Research Notes 5 (2012), 367 + doi: `10.1186/1756-0500-5-367 `_ + + and (optionally) + + BATISTA, P. R.; WILTER, A.; DURHAM, E. H. A. B. & PASCUTTI, P. G. Molecular + Dynamics Simulations Applied to the Study of Subtypes of HIV-1 Protease. + Cell Biochemistry and Biophysics 44 (2006), 395-404. + doi: `10.1385/CBB:44:3:395 `_ + + Alan Silva, D.Sc. +"""""" + +# from https://packaging.python.org/guides/single-sourcing-package-version/ +# using option 2 +# updated automatically via pre-commit git-hook +__version__ = ""2023.11.14"" +","Python" +"Computational Biochemistry","alanwilter/acpype","acpype/topol.py",".py","125358","3446","import abc +import array +import math +import os +import pickle +import re +import signal +import subprocess as sub +from datetime import datetime +from shutil import copy2, rmtree, which + +from acpype import __version__ as version +from acpype.logger import set_logging_conf as logger +from acpype.mol import Angle, Atom, AtomType, Bond, Dihedral +from acpype.params import ( + MAXTIME, + TLEAP_TEMPLATE, + binaries, + cal, + dictAtomTypeAmb2OplsGmxCode, + dictAtomTypeGaff2OplsGmxCode, + diffTol, + ionOrSolResNameList, + leapAmberFile, + maxDist, + maxDist2, + minDist, + minDist2, + oplsCode2AtomTypeDict, + outTopols, + qConv, + qDict, + radPi, + specialGaffAtoms, +) +from acpype.utils import ( + _getoutput, + checkOpenBabelVersion, + distanceAA, + elapsedTime, + find_bin, + imprDihAngle, + job_pids_family, + parmMerge, + set_for_pip, + while_replace, +) + +year = datetime.today().year +tag = version + +lineHeader = f"""""" +| ACPYPE: AnteChamber PYthon Parser interfacE v. {tag} (c) {year} AWSdS | +"""""" +frameLine = (len(lineHeader) - 2) * ""="" +header = f""{frameLine}{lineHeader}{frameLine}"" + +# TODO: +# Howto Charmm and Amber with NAMD +# Howto build topology for a modified amino acid +# CYANA topology files + +head = ""%s created by acpype (v: "" + tag + "") on %s\n"" + +date = datetime.now().ctime() + +pid: int + + +class Topology_14: + """""" + Amber topology abstraction for non-uniform 1-4 scale factors. + """""" + + def __init__(self) -> None: + self.pointers = array.array(""d"") + self.charge = array.array(""d"") + self.atom_type_index = array.array(""d"") + self.nonbonded_parm_index = array.array(""d"") + self.scee_scale_factor = array.array(""d"") + self.scnb_scale_factor = array.array(""d"") + self.dihedral_force_constants = array.array(""d"") + self.dihedral_periodicity = array.array(""d"") + self.dihedral_phase = array.array(""d"") + self.dihedral_yes_H = array.array(""d"") + self.dihedral_no_H = array.array(""d"") + self.lennard_jones_acoef = array.array(""d"") + self.lennard_jones_bcoef = array.array(""d"") + + def read_amber_topology(self, buff): + """"""Read AMBER topology file."""""" + flag_strings = [ + ""%FLAG POINTERS"", + ""%FLAG CHARGE"", + ""%FLAG ATOM_TYPE_INDEX"", + ""%FLAG NONBONDED_PARM_INDEX"", + ""%FLAG SCEE_SCALE_FACTOR"", + ""%FLAG SCNB_SCALE_FACTOR"", + ""%FLAG DIHEDRAL_FORCE_CONSTANT"", + ""%FLAG DIHEDRAL_PERIODICITY"", + ""%FLAG DIHEDRAL_PHASE"", + ""%FLAG DIHEDRALS_INC_HYDROGEN"", + ""%FLAG DIHEDRALS_WITHOUT_HYDROGEN"", + ""%FLAG LENNARD_JONES_ACOEF"", + ""%FLAG LENNARD_JONES_BCOEF"", + ] + attributes = [ + ""pointers"", + ""charge"", + ""atom_type_index"", + ""nonbonded_parm_index"", + ""scee_scale_factor"", + ""scnb_scale_factor"", + ""dihedral_force_constants"", + ""dihedral_periodicity"", + ""dihedral_phase"", + ""dihedral_yes_H"", + ""dihedral_no_H"", + ""lennard_jones_acoef"", + ""lennard_jones_bcoef"", + ] + for i, _item in enumerate(attributes): + try: + setattr(self, attributes[i], self.p7_array_read(buff, flag_strings[i])) + except Exception: + logger().exception(f""Skipping non-existent attributes {attributes[i]} {flag_strings[i]}"") + + @staticmethod + def skipline(buff, index): + """"""skip line."""""" + while buff[index] != ""\n"": + index += 1 + index += 1 + return index + + def p7_array_read(self, buff, flag_string): + """"""Convert AMBER topology data to python array."""""" + myarray = array.array(""d"") + i = buff.index(flag_string) + i = self.skipline(buff, i) + i = self.skipline(buff, i) + while 1: + while buff[i] == "" "" or buff[i] == ""\t"" or buff[i] == ""\n"": + i += 1 + j = i + if buff[i] == ""%"": + break + while buff[i] != "" "" and buff[i] != ""\t"" and buff[i] != ""\n"": + i += 1 + myarray.append(float(buff[j:i])) + return myarray + + def print_gmx_pairs(self): + """"""Generate non-bonded pairs list."""""" + pair_list = [] + pair_buff = ""[ pairs_nb ]\n; ai aj funct qi qj sigma epsilon\n"" + pair_list.append(pair_buff) + dihedrals = self.dihedral_yes_H + self.dihedral_no_H + dih_number = len(dihedrals) + j = 0 + while j < dih_number: + if dihedrals[j + 2] > 0: + parm_idx = int(dihedrals[j + 4]) - 1 + scee_scale_factor = self.scee_scale_factor[parm_idx] + if scee_scale_factor == 0: + scee_scale_factor = 1.2 + ai = int(abs(dihedrals[j]) / 3) + al = int(abs(dihedrals[j + 3]) / 3) + qi = self.charge[ai] / qConv + ql = self.charge[al] / qConv / scee_scale_factor + ntypes = int(self.pointers[1]) + ai_index = int(self.atom_type_index[ai]) + al_index = int(self.atom_type_index[al]) + nb_parm_index = int(self.nonbonded_parm_index[ntypes * (ai_index - 1) + al_index - 1]) - 1 + scnb_scale_factor = self.scnb_scale_factor[parm_idx] + if scnb_scale_factor == 0: + scnb_scale_factor = 2 + lj_acoeff = self.lennard_jones_acoef[nb_parm_index] / scnb_scale_factor + lj_bcoeff = self.lennard_jones_bcoef[nb_parm_index] / scnb_scale_factor + if lj_bcoeff != 0: + sigma6 = lj_acoeff / lj_bcoeff + else: + sigma6 = 1 # arbitrary and doesn't matter + epsilon = lj_bcoeff / 4 / sigma6 * 4.184 + sigma = sigma6 ** (1 / 6) / 10 + pair_buff = ( + f""{ai + 1:>10.0f} {al + 1:>10.0f} {1:>6.0f} "" + + f""{qi:>10.6f} {ql:>10.6f} "" + + f""{sigma:>15.5e} {epsilon:>15.5e}\n"" + ) + pair_list.append(pair_buff) + j += 5 + return """".join(pair_list) + + def hasNondefault14(self): + """"""Check non-uniform 1-4 scale factor."""""" + for val in self.scee_scale_factor: + if val not in (0, 1.2): + return True + for val in self.scnb_scale_factor: + if val not in (0, 2): + return True + return False + + def patch_gmx_topol14(self, gmx_init_top): + """"""Patch GMX topology file for non-uniform 1-4 scale factor."""""" + pair_buff = self.print_gmx_pairs() + jdefault = gmx_init_top.index(""\n[ atomtypes ]"") + ipair = gmx_init_top.index(""[ pairs ]"") + jpair = gmx_init_top.index(""\n[ angles ]"") + init_buff = ( + ""\n\n[ defaults ]\n"" + + ""; nbfunc comb-rule gen-pairs \n"" + + ""1 2 no \n"" + ) + return ( + gmx_init_top.splitlines()[0] + + init_buff + + gmx_init_top[jdefault:ipair] + + pair_buff + + gmx_init_top[jpair : len(gmx_init_top)] + ) + + +class AbstractTopol(abc.ABC): + + """""" + Abstract super class to build topologies + """""" + + @abc.abstractmethod + def __init__(self): + self.debug = None + self.verbose = None + self.chargeVal = None + self.tmpDir = None + self.absInputFile = None + self.chargeType = None + self.obabelExe = None + self.baseName = None + self.acExe = None + self.force = None + self.acBaseName = None + self.atomType = None + self.acMol2FileName = None + self.multiplicity = None + self.qFlag = None + self.ekFlag = None + self.timeTol = None + self.acXyzFileName = None + self.acTopFileName = None + self.acParDict = None + self.tleapExe = None + self.parmchkExe = None + self.acFrcmodFileName = None + self.gaffDatfile = None + self.homeDir = None + self.rootDir = None + self.extOld = None + self.direct = None + self.merge = None + self.gmx4 = None + self.sorted = None + self.chiral = None + self.outTopols = None + self.ext = None + self.xyzFileData = None + self.charmmBase = None + self.allhdg = None + self.topo14Data = None + self.atomPairs = None + self.properDihedralsGmx45 = None + self.properDihedralsAlphaGamma = None + self.properDihedralsCoefRB = None + self.resName = None + self.acLog = None + self.tleapLog = None + self.parmchkLog = None + self.inputFile = None + self.obabelLog = None + self.absHomeDir = None + self.molTopol = None + self.topFileData = None + self.residueLabel = None + self._atomTypeNameList = None + self.atomTypeSystem = None + self.totalCharge = None + self.atoms = None + self.atomTypes = None + self.pbc = None + self.bonds = None + self.angles = None + self.properDihedrals = None + self.improperDihedrals = None + self.condensedProperDihedrals = None + self.chiralGroups = None + self.excludedAtoms = None + self.atomsGromacs = None + self.atomTypesGromacs = None + self.CnsTopFileName = None + self.CnsInpFileName = None + self.CnsParFileName = None + self.CnsPdbFileName = None + self.is_smiles = None + self.smiles = None + self.amb2gmx = None + + set_for_pip(binaries) # check and call environments + + def printDebug(self, text=""""): + """"""Debug log level."""""" + logger(self.level).debug(f""{while_replace(text)}"") + + def printWarn(self, text=""""): + """"""Warn log level."""""" + logger(self.level).warning(f""{while_replace(text)}"") + + def printError(self, text=""""): + """"""Error log level."""""" + logger(self.level).error(f""{while_replace(text)}"") + + def printMess(self, text=""""): + """"""Info log level."""""" + logger(self.level).info(f""==> {while_replace(text)}"") + + def printDebugQuoted(self, text=""""): + """"""Print quoted messages."""""" + logger(self.level).debug(10 * ""+"" + ""start_quote"" + 59 * ""+"") + logger(self.level).debug(while_replace(text)) + logger(self.level).debug(10 * ""+"" + ""end_quote"" + 61 * ""+"") + + def printErrorQuoted(self, text=""""): + """"""Print quoted messages."""""" + logger(self.level).error(10 * ""+"" + ""start_quote"" + 59 * ""+"") + logger(self.level).error(while_replace(text)) + logger(self.level).error(10 * ""+"" + ""end_quote"" + 61 * ""+"") + + def search(self, name=None, alist=False): + """""" + Returns a list with all atomName matching 'name' or just the first case. + """""" + ll = [x for x in self.atoms if x.atomName == name.upper()] + if ll and not alist: + ll = ll[0] + return ll + + def checkSmiles(self): + """""" + Check if input arg is a SMILES string. + + Returns: + bool: True/False + """""" + if find_bin(self.binaries[""obabel_bin""]): + if checkOpenBabelVersion() >= 300: + from openbabel import openbabel as ob + from openbabel import pybel + + ob.cvar.obErrorLog.StopLogging() + + elif checkOpenBabelVersion() >= 200 and checkOpenBabelVersion() < 300: + import openbabel as ob + import pybel # type: ignore + + ob.cvar.obErrorLog.StopLogging() + else: + logger(self.level).warning(""WARNING: your input may be a SMILES but"") + logger(self.level).warning("" without OpenBabel, this functionality won't work"") + return False + + # Check if input is a smiles string + try: + ob.obErrorLog.SetOutputLevel(0) + pybel.readstring(""smi"", self.smiles) + return True + except Exception: + ob.obErrorLog.SetOutputLevel(0) + + return False + + def guessCharge(self): + """""" + Guess the charge of a system based on antechamber. + + Returns None in case of error. + """""" + done = False + error = False + charge = self.chargeVal + localDir = os.path.abspath(""."") + if not os.path.exists(self.tmpDir): + os.mkdir(self.tmpDir) + if not os.path.exists(os.path.join(self.tmpDir, self.inputFile)): + copy2(self.absInputFile, self.tmpDir) + os.chdir(self.tmpDir) + + if self.chargeType == ""user"": + if self.ext == "".mol2"": + self.printMess(""Reading user's charges from mol2 file..."") + charge = self.readMol2TotalCharge(self.inputFile) + done = True + else: + self.chargeType = ""bcc"" + self.printWarn(""cannot read charges from a PDB file"") + self.printWarn(""using now 'bcc' method for charge"") + if self.chargeVal is None and not done: + self.printWarn(""no charge value given, trying to guess one..."") + mol2FileForGuessCharge = self.inputFile + if self.ext == "".pdb"": + cmd = f""'{self.obabelExe}' -ipdb '{self.inputFile}' -omol2 -O '{self.baseName}.mol2'"" + self.printDebug(f""guessCharge: {cmd}"") + out = _getoutput(cmd) + self.printDebug(out) + mol2FileForGuessCharge = os.path.abspath(f""{self.baseName}.mol2"") + in_mol = ""mol2"" + else: + in_mol = self.ext[1:] + if in_mol == ""mol"": + in_mol = ""mdl"" + + cmd = f""'{self.acExe}' -dr no -i '{mol2FileForGuessCharge}' -fi {in_mol} -o tmp -fo mol2 -c gas -pf n"" + + logger(self.level).debug(while_replace(cmd)) + + log = _getoutput(cmd).strip() + + if os.path.exists(""tmp""): + charge = self.readMol2TotalCharge(""tmp"") + else: + try: + charge = float( + log.strip() + .split(""equal to the total charge ("")[-1] + .split("") based on Gasteiger atom type, exit"")[0] + ) + except Exception: + error = True + + if not charge: + error = True + charge = 0 + if error: + self.printError(""guessCharge failed"") + os.chdir(localDir) + rmtree(self.tmpDir) + self.printErrorQuoted(log) + self.printMess(""Trying with net charge = 0 ..."") + charge = float(charge) + charge2 = int(round(charge)) + drift = abs(charge2 - charge) + self.printDebug(f""Net charge drift '{drift:3.6f}'"") + if drift > diffTol: + self.printWarn(f""Net charge drift '{drift:3.5f}' bigger than tolerance '{diffTol:3.5f}'"") + if not self.force and self.chargeType != ""user"": + msg = ""Error with calculated charge"" + logger(self.level).error(msg) + rmtree(self.tmpDir) + raise Exception(msg) + self.chargeVal = str(charge2) + self.printMess(f""... charge set to {charge2}"") + os.chdir(localDir) + + def setResNameCheckCoords(self): + """""" + Set a 3 letter residue name and check coords for issues + like duplication, atoms too close or too sparse. + """""" + exit_ = False + localDir = os.path.abspath(""."") + if not os.path.exists(self.tmpDir): + os.mkdir(self.tmpDir) + + copy2(self.absInputFile, self.tmpDir) + os.chdir(self.tmpDir) + + exten = self.ext[1:] + if self.ext == "".pdb"": + tmpFile = open(self.inputFile) + else: + if exten == ""mol"": + exten = ""mdl"" + cmd = f""'{self.acExe}' -dr no -i '{self.inputFile}' -fi {exten} -o tmp -fo ac -pf y"" + self.printDebug(cmd) + out = _getoutput(cmd) + if not out.isspace(): + self.printDebug(out) + try: + tmpFile = open(""tmp"") + except Exception: + rmtree(self.tmpDir) + raise + + tmpData = tmpFile.readlines() + residues = set() + coords = {} + for line in tmpData: + if ""ATOM "" in line or ""HETATM"" in line: + residues.add(line[17:20]) + at = line[0:17] + cs = line[30:54] + if cs in coords: + coords[cs].append(at) + else: + coords[cs] = [at] + + if len(residues) > 1: + self.printError(f""more than one residue detected '{residues!s}'"") + self.printError(f""verify your input file '{self.inputFile}'. Aborting ..."") + msg = ""Only ONE Residue is allowed for ACPYPE to work"" + logger(self.level).error(msg) + raise Exception(msg) + + dups = """" + shortd = """" + longd = """" + longSet = set() + id_ = 0 + items = list(coords.items()) + ll = len(items) + for item in items: + id_ += 1 + if len(item[1]) > 1: # if True means atoms with same coordinates + for i in item[1]: + dups += f""{i} {item[0]}\n"" + for id2 in range(id_, ll): + item2 = items[id2] + c1 = list(map(float, [item[0][i : i + 8] for i in range(0, 24, 8)])) + c2 = list(map(float, [item2[0][i : i + 8] for i in range(0, 24, 8)])) + dist2 = distanceAA(c1, c2) + if dist2 < minDist2: + dist = math.sqrt(dist2) + shortd += f""{dist:8.5f} {item[1]} {item2[1]}\n"" + if dist2 < maxDist2: # and not longOK: + longSet.add(str(item[1])) + longSet.add(str(item2[1])) + if str(item[1]) not in longSet and ll > 1: + longd += f""{item[1]}\n"" + + if dups: + self.printError(f""Atoms with same coordinates in '{self.inputFile}'!"") + self.printErrorQuoted(dups[:-1]) + exit_ = True + + if shortd: + self.printError(f""Atoms TOO close (< {minDist} Ang.)"") + self.printErrorQuoted(f""Dist (Ang.) Atoms\n{shortd[:-1]}"") + exit_ = True + + if longd: + self.printError(f""Atoms TOO scattered (> {maxDist} Ang.)"") + self.printErrorQuoted(longd[:-1]) + exit_ = True + + if exit_: + if self.force: + self.printWarn(""You chose to proceed anyway with '-f' option. GOOD LUCK!"") + else: + self.printError(""Use '-f' option if you want to proceed anyway. Aborting ..."") + if not self.debug: + rmtree(self.tmpDir) + msg = ""Coordinates issues with your system"" + logger(self.level).error(msg) + rmtree(self.tmpDir) + raise Exception(msg) + + # escape resname list index out of range: no RES name in pdb for example + resname = next(iter(residues)).strip() + if not resname: + resname = ""LIG"" + self.printWarn(""No residue name identified, using default resname: 'LIG'"") + newresname = resname + + # To avoid resname likes: 001 (all numbers), 1e2 (sci number), ADD : reserved terms for leap + leapWords = [ + ""_cmd_options_"", + ""_types_"", + ""add"", + ""addAtomTypes"", + ""addIons"", + ""addIons2"", + ""addPath"", + ""addPdbAtomMap"", + ""addPdbResMap"", + ""alias"", + ""alignAxes"", + ""bond"", + ""bondByDistance"", + ""center"", + ""charge"", + ""check"", + ""clearPdbAtomMap"", + ""clearPdbResMap"", + ""clearVariables"", + ""combine"", + ""copy"", + ""createAtom"", + ""createParmset"", + ""createResidue"", + ""createUnit"", + ""crossLink"", + ""debugOff"", + ""debugOn"", + ""debugStatus"", + ""deleteBond"", + ""deleteOffLibEntry"", + ""deleteRestraint"", + ""desc"", + ""deSelect"", + ""displayPdbAtomMap"", + ""displayPdbResMap"", + ""edit"", + ""flip"", + ""groupSelectedAtoms"", + ""help"", + ""impose"", + ""list"", + ""listOff"", + ""loadAmberParams"", + ""loadAmberPrep"", + ""loadMol2"", + ""loadOff"", + ""loadPdb"", + ""loadPdbUsingSeq"", + ""logFile"", + ""matchVariables"", + ""measureGeom"", + ""quit"", + ""relax"", + ""remove"", + ""restrainAngle"", + ""restrainBond"", + ""restrainTorsion"", + ""saveAmberParm"", + ""saveAmberParmPert"", + ""saveAmberParmPol"", + ""saveAmberParmPolPert"", + ""saveAmberPrep"", + ""saveMol2"", + ""saveOff"", + ""saveOffParm"", + ""savePdb"", + ""scaleCharges"", + ""select"", + ""sequence"", + ""set"", + ""setBox"", + ""solvateBox"", + ""solvateCap"", + ""solvateDontClip"", + ""solvateOct"", + ""solvateShell"", + ""source"", + ""transform"", + ""translate"", + ""verbosity"", + ""zMatrix"", + ] + isLeapWord = False + for word in leapWords: + if resname.upper().startswith(word.upper()): + self.printDebug(f""Residue name is a reserved word: '{word.upper()}'"") + isLeapWord = True + try: + float(resname) + self.printDebug(f""Residue name is a 'number': '{resname}'"") + isNumber = True + except ValueError: + isNumber = False + + if resname[0].isdigit() or isNumber or isLeapWord: + newresname = ""R"" + resname + if not resname.isalnum(): + newresname = ""MOL"" + if newresname != resname: + self.printWarn( + f""In {self.acBaseName}.lib, residue name will be '{newresname}' instead of '{resname}' elsewhere"" + ) + + self.resName = newresname + + os.chdir(localDir) + self.printDebug(""setResNameCheckCoords done"") + + def readMol2TotalCharge(self, mol2File): + """"""Reads the charges in given mol2 file and returns the total."""""" + charge = 0.0 + ll = [] + cmd = f""'{self.acExe}' -dr no -i '{mol2File}' -fi mol2 -o tmp -fo mol2 -c wc -cf tmp.crg -pf n"" + + self.printDebug(cmd) + + log = _getoutput(cmd) + + if os.path.exists(""tmp.crg""): + tmpFile = open(""tmp.crg"") + tmpData = tmpFile.readlines() + for line in tmpData: + ll += line.split() + charge = sum(map(float, ll)) + if not log.isspace(): + self.printDebugQuoted(log) + + self.printDebug(""readMol2TotalCharge: "" + str(charge)) + + return charge + + def execAntechamber(self, chargeType=None, atomType=None) -> bool: + r"""""" + To call Antechamber and execute it. + + Args: + chargeType ([str], optional): bcc, gas or user. Defaults to None/bcc. + atomType ([str], optional): gaff, amber, gaff2, amber2. Defaults to None/gaff2. + + Returns: + bool: True if failed. + + :: + + Welcome to antechamber 21.0: molecular input file processor. + + Usage: antechamber \ + -i input file name + -fi input file format + -o output file name + -fo output file format + -c charge method + -cf charge file name + -nc net molecular charge (int) + -a additional file name + -fa additional file format + -ao additional file operation + crd : only read in coordinate + crg : only read in charge + radius: only read in radius + name : only read in atom name + type : only read in atom type + bond : only read in bond type + -m multiplicity (2S+1), default is 1 + -rn residue name, overrides input file, default is MOL + -rf residue topology file name in prep input file, + default is molecule.res + -ch check file name for gaussian, default is 'molecule' + -ek mopac or sqm keyword, inside quotes; overwrites previous ones + -gk gaussian job keyword, inside quotes, is ignored when both -gopt and -gsp are used + -gopt gaussian job keyword for optimization, inside quotes + -gsp gaussian job keyword for single point calculation, inside quotes + -gm gaussian memory keyword, inside quotes, such as ""%mem=1000MB"" + -gn gaussian number of processors keyword, inside quotes, such as ""%nproc=8"" + -gdsk gaussian maximum disk usage keyword, inside quotes, such as ""%maxdisk=50GB"" + -gv add keyword to generate gesp file (for Gaussian 09 only) + 1 : yes + 0 : no, the default + -ge gaussian esp file generated by iop(6/50=1), default is g09.gesp + -tor torsional angle list, inside a pair of quotes, such as ""1-2-3-4:0,5-6-7-8"" + ':1' or ':0' indicates the torsional angle is frozen or not + -df am1-bcc precharge flag, 2 - use sqm(default); 0 - use mopac + -at atom type + gaff : the default + gaff2: for gaff2 (beta-version) + amber: for PARM94/99/99SB + bcc : bcc + sybyl: sybyl + -du fix duplicate atom names: yes(y)[default] or no(n) + -bk component/block Id, for ccif + -an adjust atom names: yes(y) or no(n) + the default is 'y' for 'mol2' and 'ac' and 'n' for the other formats + -j atom type and bond type prediction index, default is 4 + 0 : no assignment + 1 : atom type + 2 : full bond types + 3 : part bond types + 4 : atom and full bond type + 5 : atom and part bond type + -s status information: 0(brief), 1(default) or 2(verbose) + -eq equalizing atomic charge, default is 1 for '-c resp' and '-c bcc' and 0 + for the other charge methods + 0 : no use + 1 : by atomic paths + 2 : by atomic paths and structural information, i.e. E/Z configurations + -pf remove intermediate files: yes(y) or no(n)[default] + -pl maximum path length to determin equivalence of atomic charges for resp and bcc, + the smaller the value, the faster the algorithm, default is -1 (use full length), + set this parameter to 10 to 30 if your molecule is big (# atoms >= 100) + -seq atomic sequence order changable: yes(y)[default] or no(n) + -dr acdoctor mode: yes(y)[default] or no(n) + -i -o -fi and -fo must appear; others are optional + Use 'antechamber -L' to list the supported file formats and charge methods + + List of the File Formats + + file format type abbre. index | file format type abbre. index + -------------------------------------------------------------- + Antechamber ac 1 | Sybyl Mol2 mol2 2 + PDB pdb 3 | Modified PDB mpdb 4 + AMBER PREP (int) prepi 5 | AMBER PREP (car) prepc 6 + Gaussian Z-Matrix gzmat 7 | Gaussian Cartesian gcrt 8 + Mopac Internal mopint 9 | Mopac Cartesian mopcrt 10 + Gaussian Output gout 11 | Mopac Output mopout 12 + Alchemy alc 13 | CSD csd 14 + MDL mdl 15 | Hyper hin 16 + AMBER Restart rst 17 | Jaguar Cartesian jcrt 18 + Jaguar Z-Matrix jzmat 19 | Jaguar Output jout 20 + Divcon Input divcrt 21 | Divcon Output divout 22 + SQM Input sqmcrt 23 | SQM Output sqmout 24 + Charmm charmm 25 | Gaussian ESP gesp 26 + Component cif ccif 27 | GAMESS dat gamess 28 + Orca input orcinp 29 | Orca output orcout 30 + -------------------------------------------------------------- + AMBER restart file can only be read in as additional file. + + List of the Charge Methods + + charge method abbre. index | charge method abbre. index + -------------------------------------------------------------- + RESP resp 1 | AM1-BCC bcc 2 + CM1 cm1 3 | CM2 cm2 4 + ESP (Kollman) esp 5 | Mulliken mul 6 + Gasteiger gas 7 | Read in charge rc 8 + Write out charge wc 9 | Delete Charge dc 10 + -------------------------------------------------------------- + """""" + global pid + + self.printMess(""Executing Antechamber..."") + + self.makeDir() + + ct = chargeType or self.chargeType + at = atomType or self.atomType + if ""amber2"" in at: + at = ""amber"" + + if ct == ""user"": + ct = """" + else: + ct = f""-c {ct}"" + + exten = self.ext[1:] + if exten == ""mol"": + exten = ""mdl"" + + cmd = ""'{}' -dr no -i '{}' -fi {} -o '{}' -fo mol2 {} -nc {} -m {} -s 2 -df {} -at {} -pf n {}"".format( + self.acExe, + self.inputFile, + exten, + self.acMol2FileName, + ct, + self.chargeVal, + self.multiplicity, + self.qFlag, + at, + self.ekFlag, + ) + + self.printDebug(cmd) + + if os.path.exists(self.acMol2FileName) and not self.force: + self.printMess(""AC output file present... doing nothing"") + else: + try: + os.remove(self.acMol2FileName) + except Exception: + self.printDebug(""No file left to be removed"") + signal.signal(signal.SIGALRM, self.signal_handler) + signal.alarm(self.timeTol) + p = sub.Popen(cmd, shell=True, stderr=sub.STDOUT, stdout=sub.PIPE) + pid = p.pid + + out = str(p.communicate()[0].decode()) # p.stdout.read() + self.acLog = out + + if os.path.exists(self.acMol2FileName): + self.printMess(""* Antechamber OK *"") + else: + self.printErrorQuoted(self.acLog) + return True + return False + + def signal_handler(self, _signum, _frame): # , pid = 0): + """"""Signal handler."""""" + global pid + pids = job_pids_family(pid) + self.printDebug(f""PID: {pid}, PIDS: {pids}"") + self.printMess(f""Timed out! Process {pids} killed, max exec time ({self.timeTol}s) exceeded"") + # os.system('kill -15 %s' % pids) + for i in pids.split(): + os.kill(int(i), 15) + msg = ""Semi-QM taking too long to finish... aborting!"" + logger(self.level).error(msg) + raise Exception(msg) + + def delOutputFiles(self): + """"""Delete temporary output files."""""" + delFiles = [ + ""mopac.in"", + ""tleap.in"", + ""fixbo.log"", + ""addhs.log"", + ""ac_tmp_ot.mol2"", + ""frcmod.ac_tmp"", + ""fragment.mol2"", + self.tmpDir, + ] # , 'divcon.pdb', 'mopac.pdb', 'mopac.out'] #'leap.log' + self.printMess(""Removing temporary files..."") + for file_ in delFiles: + file_ = os.path.join(self.absHomeDir, file_) + if os.path.exists(file_): + if os.path.isdir(file_): + rmtree(file_) + else: + os.remove(file_) + + def checkXyzAndTopFiles(self): + """"""Check XYZ and TOP files."""""" + fileXyz = self.acXyzFileName + fileTop = self.acTopFileName + if os.path.exists(fileXyz) and os.path.exists(fileTop): + return True + return False + + def execTleap(self): + """"""Execute tleap."""""" + fail = False + + self.makeDir() + + if self.ext == "".pdb"": + self.printMess(""... converting pdb input file to mol2 input file"") + if self.convertPdbToMol2(): + self.printError(""convertPdbToMol2 failed"") + + if self.execAntechamber(): + self.printError(""Antechamber failed"") + fail = True + + if self.execParmchk(): + self.printError(""Parmchk failed"") + fail = True + + if fail: + return True + + tleapScpt = TLEAP_TEMPLATE % self.acParDict + + fp = open(""tleap.in"", ""w"") + fp.write(tleapScpt) + fp.close() + + cmd = f""'{self.tleapExe}' -f tleap.in"" + + if self.checkXyzAndTopFiles() and not self.force: + self.printMess(""Topologies files already present... doing nothing"") + else: + try: + os.remove(self.acTopFileName) + os.remove(self.acXyzFileName) + except Exception: + self.printDebug(""No crd or prm files left to be removed"") + self.printMess(""Executing Tleap..."") + self.printDebug(cmd) + self.tleapLog = _getoutput(cmd) + self.checkLeapLog(self.tleapLog) + + if self.checkXyzAndTopFiles(): + self.printMess(""* Tleap OK *"") + else: + self.printErrorQuoted(self.tleapLog) + return True + return False + + def checkLeapLog(self, log): + """"""Check Leap log."""""" + log = log.splitlines(True) + check = """" + block = False + for line in log: + # print ""*""+line+""*"" + if ""Checking '"" in line: + # check += line + block = True + if ""Checking Unit."" in line: + block = False + if block: + check += line + self.printDebugQuoted(check[:-1]) + + def locateDat(self, aFile): + """"""Locate a file pertinent to $AMBERHOME/dat/leap/parm/."""""" + amberhome = os.environ.get(""AMBERHOME"") + if amberhome: + aFileF = os.path.join(amberhome, ""dat/leap/parm"", aFile) + if os.path.exists(aFileF): + return aFileF + aFileF = os.path.join(os.path.dirname(self.acExe), ""../dat/leap/parm"", aFile) + if os.path.exists(aFileF): + return aFileF + return None + + def execParmchk(self): + """"""Execute parmchk."""""" + self.makeDir() + cmd = f""'{self.parmchkExe}' -i '{self.acMol2FileName}' -f mol2 -o '{self.acFrcmodFileName}'"" + + if ""amber"" in self.atomType: + gaffFile = self.locateDat(self.gaffDatfile) + parmfile = self.locateDat(""parm10.dat"") + frcmodffxxSB = self.locateDat(""frcmod.ff14SB"") + # frcmodparmbsc0 = self.locateDat('frcmod.parmbsc0') + parmGaffFile = parmMerge(parmfile, gaffFile) + parmGaffffxxSBFile = parmMerge(parmGaffFile, frcmodffxxSB, frcmod=True) + # parm99gaffff99SBparmbsc0File = parmMerge(parm99gaffff99SBFile, frcmodparmbsc0, frcmod = True) + # parm10file = self.locateDat('parm10.dat') # PARM99 + frcmod.ff99SB + frcmod.parmbsc0 in AmberTools 1.4 + + cmd += f"" -p '{parmGaffffxxSBFile}'"" # Ignoring BSC0 + elif ""gaff2"" in self.atomType: + cmd += "" -s 2"" + + self.printDebug(cmd) + self.parmchkLog = _getoutput(cmd) + + if os.path.exists(self.acFrcmodFileName): + check = self.checkFrcmod() + if check: + self.printWarn(""Couldn't determine all parameters:"") + self.printMess(f""From file '{self.acFrcmodFileName + check}'\n"") + else: + self.printMess(""* Parmchk OK *"") + else: + self.printErrorQuoted(self.parmchkLog) + return True + return False + + def checkFrcmod(self): + """"""Check FRCMOD file."""""" + check = """" + frcmodContent = open(self.acFrcmodFileName).readlines() + for line in frcmodContent: + if ""ATTN, need revision"" in line: + check += line + return check + + def convertPdbToMol2(self): + """"""Convert PDB to MOL2 by using obabel."""""" + if self.ext == "".pdb"": + if self.execObabel(): + self.printError(f""convert pdb to mol2 via {binaries['obabel_bin']} failed"") + return True + return False + + def convertSmilesToMol2(self): + """"""Convert Smiles to MOL2 by using obabel."""""" + + # if not self.obabelExe: + # msg = ""SMILES needs OpenBabel python module"" + # logger(self.level).error(msg) + # raise Exception(msg) + + if checkOpenBabelVersion() >= 300: + from openbabel import pybel + + elif checkOpenBabelVersion() >= 200 and checkOpenBabelVersion() < 300: + import pybel # type: ignore + + try: + mymol = pybel.readstring(""smi"", str(self.smiles)) + mymol.addh() + mymol.make3D() + mymol.write(self.ext.replace(""."", """"), self.absInputFile, overwrite=True) + return True + except Exception: + return False + + def execObabel(self): + """"""Execute obabel."""""" + self.makeDir() + + cmd = f""'{self.obabelExe}' -ipdb '{self.inputFile}' -omol2 -O '{self.baseName}.mol2'"" + self.printDebug(cmd) + self.obabelLog = _getoutput(cmd) + self.ext = "".mol2"" + self.inputFile = self.baseName + self.ext + self.acParDict[""ext""] = ""mol2"" + if os.path.exists(self.inputFile): + self.printMess(""* Babel OK *"") + else: + self.printErrorQuoted(self.obabelLog) + return True + return False + + def makeDir(self): + """"""Make Dir."""""" + os.chdir(self.rootDir) + self.absHomeDir = os.path.abspath(self.homeDir) + if not os.path.exists(self.homeDir): + os.mkdir(self.homeDir) + os.chdir(self.homeDir) + if self.absInputFile: + copy2(self.absInputFile, ""."") + return True + + def createACTopol(self): + """""" + If successful, Amber Top and Xyz files will be generated. + """""" + if self.execTleap(): + self.printError(""Tleap failed"") + if not self.debug: + self.delOutputFiles() + + def createMolTopol(self): + """""" + Create MolTopol obj. + """""" + self.topFileData = open(self.acTopFileName).readlines() + self.molTopol = MolTopol( + self, # acTopolObj + verbose=self.verbose, + debug=self.debug, + gmx4=self.gmx4, + merge=self.merge, + direct=self.direct, + is_sorted=self.sorted, + chiral=self.chiral, + ) + if self.outTopols: + if ""cns"" in self.outTopols: + self.molTopol.writeCnsTopolFiles() + if ""gmx"" in self.outTopols: + self.molTopol.writeGromacsTopolFiles() + if ""charmm"" in self.outTopols: + self.writeCharmmTopolFiles() + try: # scape the pickle save error + self.pickleSave() + except Exception: + self.printError(""pickleSave failed"") + + if not self.debug: + self.delOutputFiles() # required to use on Jupyter Notebook + os.chdir(self.rootDir) + + def pickleSave(self): + """""" + Create portable serialized representations of System's Python objects. + + Example: + + to restore: + + .. code-block:: python + + from acpype import * + # import cPickle as pickle + import pickle + mol = pickle.load(open('DDD.pkl','rb')) + """""" + pklFile = self.baseName + "".pkl"" + dumpFlag = False + if not os.path.exists(pklFile): + mess = ""Writing pickle file %s"" % pklFile + dumpFlag = True + elif self.force: + mess = ""Overwriting pickle file %s"" % pklFile + dumpFlag = True + else: + mess = ""Pickle file %s already present... doing nothing"" % pklFile + self.printMess(mess) + if dumpFlag: + with open(pklFile, ""wb"") as f: # for python 3.3 or higher + pickle.dump(self, f) + + def getFlagData(self, flag): + """""" + For a given acFileTop flag, return a list of the data related. + """""" + + def proc_line(line): + # data need format + data = line.rstrip() + sdata = [data[i : i + f].strip() for i in range(0, len(data), f)] + if ""+"" and ""."" in data and flag != ""RESIDUE_LABEL"": # it's a float + ndata = list(map(float, sdata)) + elif flag != ""RESIDUE_LABEL"": + try: # try if it's integer + ndata = list(map(int, sdata)) + except Exception: + ndata = sdata + else: + ndata = sdata + + return ndata + + block = False + tFlag = ""%FLAG "" + flag + ndata = [] + + if not self.topFileData: + msg = ""PRMTOP file empty?"" + logger(self.level).error(msg) + raise Exception(msg) + + for rawLine in self.topFileData: + line = rawLine.replace(""\r"", """").replace(""\n"", """") + if tFlag in line: + block = True + continue + if block and ""%FLAG "" in line: + break + if block: + if ""%FORMAT"" in line: + line = line.strip().strip(""%FORMAT()"").split(""."")[0] + for c in line: + if c.isalpha(): + f = int(line.split(c)[1]) + break + continue + ndata += proc_line(line) + + if flag == ""AMBER_ATOM_TYPE"": + nn = [] + ll = set() + prefixed = False + for ii in ndata: + prefixed = True + if ii[0].isdigit(): + ll.add(ii) + ii = ""A"" + ii + nn.append(ii) + if prefixed and ll: + self.printDebug(""GMX does not like atomtype starting with Digit"") + self.printDebug(""prefixing AtomType %s with 'A'."" % list(ll)) + ndata = nn + return ndata # a list + + def getResidueLabel(self): + """""" + Get a 3 capital letters code from acFileTop. + + Returns a list. + """""" + residueLabel = self.getFlagData(""RESIDUE_LABEL"") + residueLabel = list(map(str, residueLabel)) + if residueLabel[0] != residueLabel[0].upper(): + self.printWarn(f""residue label '{residueLabel[0]}' in '{self.inputFile}' is not all UPPERCASE"") + self.printWarn(""this may raise problem with some applications like CNS"") + self.residueLabel = residueLabel + + def getCoords(self): + """""" + For a given acFileXyz file, return a list of coords as:: + + [[x1,y1,z1],[x2,y2,z2], etc.] + """""" + if not self.xyzFileData: + msg = ""INPCRD file empty?"" + logger(self.level).error(msg) + raise Exception(msg) + data = """" + for rawLine in self.xyzFileData[2:]: + line = rawLine.replace(""\r"", """").replace(""\n"", """") + data += line + ll = len(data) + ndata = list(map(float, [data[i : i + 12] for i in range(0, ll, 12)])) + + gdata = [] + for i in range(0, len(ndata), 3): + gdata.append([ndata[i], ndata[i + 1], ndata[i + 2]]) + + self.printDebug(""getCoords done"") + + return gdata + + def getAtoms(self): + """""" + Set a list with all atoms objects built from dat in acFileTop. + + Set also atomType system is gaff or amber, list of atomTypes, resid + and system's total charge. + """""" + atomNameList = self.getFlagData(""ATOM_NAME"") + atomTypeNameList = self.getFlagData(""AMBER_ATOM_TYPE"") + self._atomTypeNameList = atomTypeNameList + massList = self.getFlagData(""MASS"") + chargeList = self.getFlagData(""CHARGE"") + resIds = [*self.getFlagData(""RESIDUE_POINTER""), 0] + coords = self.getCoords() + ACOEFs, BCOEFs = self.getABCOEFs() + + atoms = [] + atomTypes = [] + tmpList = [] # a list with unique atom types + totalCharge = 0.0 + countRes = 0 + id_ = 0 + FirstNonSoluteId = None + for atomName in atomNameList: + if atomName != atomName.upper(): + self.printDebug(""atom name '%s' HAS to be all UPPERCASE... Applying this here."" % atomName) + atomName = atomName.upper() + atomTypeName = atomTypeNameList[id_] + if id_ + 1 == resIds[countRes]: + resid = countRes + countRes += 1 + resName = self.residueLabel[resid] + if resName in ionOrSolResNameList and not FirstNonSoluteId: + FirstNonSoluteId = id_ + mass = massList[id_] + charge = chargeList[id_] + chargeConverted = charge / qConv + totalCharge += charge + coord = coords[id_] + ACOEF = ACOEFs[id_] + BCOEF = BCOEFs[id_] + atomType = AtomType(atomTypeName, mass, ACOEF, BCOEF) + if atomTypeName not in tmpList: + tmpList.append(atomTypeName) + atomTypes.append(atomType) + atom = Atom(atomName, atomType, id_ + 1, resid, mass, chargeConverted, coord) + atoms.append(atom) + id_ += 1 + + balanceChargeList, balanceValue, balanceIds = self.balanceCharges(chargeList, FirstNonSoluteId) + + for id_ in balanceIds: + atoms[id_].charge = balanceValue / qConv + + if atomTypeName[0].islower(): + self.atomTypeSystem = ""gaff"" + else: + self.atomTypeSystem = ""amber"" + self.printDebug(""Balanced TotalCharge %13.10f"" % float(sum(balanceChargeList) / qConv)) + + self.totalCharge = int(round(totalCharge / qConv)) + + self.atoms = atoms + self.atomTypes = atomTypes + + self.pbc = None + if len(coords) == len(atoms) + 2 or len(coords) == len(atoms) * 2 + 2: + self.pbc = [coords[-2], coords[-1]] + self.printDebug(""PBC = %s"" % self.pbc) + self.printDebug(""getAtoms done"") + + def getBonds(self): + """"""Get Bonds."""""" + uniqKbList = self.getFlagData(""BOND_FORCE_CONSTANT"") + uniqReqList = self.getFlagData(""BOND_EQUIL_VALUE"") + bondCodeHList = self.getFlagData(""BONDS_INC_HYDROGEN"") + bondCodeNonHList = self.getFlagData(""BONDS_WITHOUT_HYDROGEN"") + bondCodeList = bondCodeHList + bondCodeNonHList + bonds = [] + for i in range(0, len(bondCodeList), 3): + idAtom1 = bondCodeList[i] // 3 # remember python starts with id 0 + idAtom2 = bondCodeList[i + 1] // 3 + bondTypeId = bondCodeList[i + 2] - 1 + atom1 = self.atoms[idAtom1] + atom2 = self.atoms[idAtom2] + kb = uniqKbList[bondTypeId] + req = uniqReqList[bondTypeId] + atoms = [atom1, atom2] + bond = Bond(atoms, kb, req) + bonds.append(bond) + self.bonds = bonds + self.printDebug(""getBonds done"") + + def getAngles(self): + """"""Get Angles."""""" + uniqKtList = self.getFlagData(""ANGLE_FORCE_CONSTANT"") + uniqTeqList = self.getFlagData(""ANGLE_EQUIL_VALUE"") + # for list below, true atom number = index/3 + 1 + angleCodeHList = self.getFlagData(""ANGLES_INC_HYDROGEN"") + angleCodeNonHList = self.getFlagData(""ANGLES_WITHOUT_HYDROGEN"") + angleCodeList = angleCodeHList + angleCodeNonHList + angles = [] + for i in range(0, len(angleCodeList), 4): + idAtom1 = angleCodeList[i] // 3 # remember python starts with id 0 + idAtom2 = angleCodeList[i + 1] // 3 + idAtom3 = angleCodeList[i + 2] // 3 + angleTypeId = angleCodeList[i + 3] - 1 + atom1 = self.atoms[idAtom1] + atom2 = self.atoms[idAtom2] + atom3 = self.atoms[idAtom3] + kt = uniqKtList[angleTypeId] + teq = uniqTeqList[angleTypeId] # angle given in rad in prmtop + atoms = [atom1, atom2, atom3] + angle = Angle(atoms, kt, teq) + angles.append(angle) + self.angles = angles + self.printDebug(""getAngles done"") + + def getDihedrals(self): + """""" + Get dihedrals (proper and imp), condensed list of prop dih and + atomPairs. + """""" + uniqKpList = self.getFlagData(""DIHEDRAL_FORCE_CONSTANT"") + uniqPeriodList = self.getFlagData(""DIHEDRAL_PERIODICITY"") + uniqPhaseList = self.getFlagData(""DIHEDRAL_PHASE"") + # for list below, true atom number = abs(index)/3 + 1 + dihCodeHList = self.getFlagData(""DIHEDRALS_INC_HYDROGEN"") + dihCodeNonHList = self.getFlagData(""DIHEDRALS_WITHOUT_HYDROGEN"") + dihCodeList = dihCodeHList + dihCodeNonHList + properDih = [] + improperDih = [] + condProperDih = [] # list of dihedrals condensed by the same quartet + # atomPairs = [] + atomPairs = set() + for i in range(0, len(dihCodeList), 5): + idAtom1 = dihCodeList[i] // 3 # remember python starts with id 0 + idAtom2 = dihCodeList[i + 1] // 3 + # 3 and 4 indexes can be negative: if id3 < 0, end group interations + # in amber are to be ignored; if id4 < 0, dihedral is improper + idAtom3raw = dihCodeList[i + 2] // 3 # can be negative -> exclude from 1-4vdw + idAtom4raw = dihCodeList[i + 3] // 3 # can be negative -> Improper + idAtom3 = abs(idAtom3raw) + idAtom4 = abs(idAtom4raw) + dihTypeId = dihCodeList[i + 4] - 1 + atom1 = self.atoms[idAtom1] + atom2 = self.atoms[idAtom2] + atom3 = self.atoms[idAtom3] + atom4 = self.atoms[idAtom4] + kPhi = uniqKpList[dihTypeId] # already divided by IDIVF + period = int(uniqPeriodList[dihTypeId]) # integer + phase = uniqPhaseList[dihTypeId] # angle given in rad in prmtop + if phase == kPhi == 0: + period = 0 # period is set to 0 + atoms = [atom1, atom2, atom3, atom4] + dihedral = Dihedral(atoms, kPhi, period, phase) + if idAtom4raw > 0: + try: + atomsPrev = properDih[-1].atoms + except Exception: + atomsPrev = [] + properDih.append(dihedral) + if idAtom3raw < 0 and atomsPrev == atoms: + condProperDih[-1].append(dihedral) + else: + condProperDih.append([dihedral]) + pair = (atom1, atom4) + # if atomPairs.count(pair) == 0 and idAtom3raw > 0: + if idAtom3raw > 0: + atomPairs.add(pair) + else: + improperDih.append(dihedral) + if self.sorted: + atomPairs = sorted(atomPairs, key=lambda x: (x[0].id, x[1].id)) + self.properDihedrals = properDih + self.improperDihedrals = improperDih + self.condensedProperDihedrals = condProperDih # [[],[],...] + self.atomPairs = atomPairs # set((atom1, atom2), ...) + self.printDebug(""getDihedrals done"") + + def getChirals(self): + """""" + Get chiral atoms (for CNS only!). + + Plus its 4 neighbours and improper dihedral angles + to store non-planar improper dihedrals. + """""" + if not self._parent.obabelExe: + self.printWarn(""No Openbabel python module, no chiral groups"") + self.chiralGroups = [] + return + + if checkOpenBabelVersion() >= 300: + from openbabel import openbabel as ob + from openbabel import pybel + + elif checkOpenBabelVersion() >= 200 and checkOpenBabelVersion() < 300: + import openbabel as ob + import pybel # type: ignore + + self.printMess(""Using OpenBabel v."" + ob.OBReleaseVersion() + ""\n"") + + "" obchiral script - replace the obchiral executable"" + out = [] + _filename, file_extension = os.path.splitext(self.inputFile) + mol = pybel.readfile(file_extension.replace(""."", """"), self.inputFile) + for ml in mol: + for at in ml: + if ob.OBStereoFacade(ml.OBMol).HasTetrahedralStereo(at.idx): + out.append(at.idx) + "" end of obchiral script "" + + chiralGroups = [] + for id_ in out: + atChi = self.atoms[id_] + quad = [] + for bb in self.bonds: + bAts = bb.atoms[:] + if atChi in bAts: + bAts.remove(atChi) + quad.append(bAts[0]) + if len(quad) != 4: + if self.chiral: + self.printWarn(f""Atom {atChi} has less than 4 connections to 4 different atoms. It's NOT Chiral!"") + continue + v1, v2, v3, v4 = (x.coords for x in quad) + chiralGroups.append((atChi, quad, imprDihAngle(v1, v2, v3, v4))) + self.chiralGroups = chiralGroups + + def sortAtomsForGromacs(self): + """""" + Re-sort atoms for gromacs, which expects all hydrogens to immediately + follow the heavy atom they are bonded to and belong to the same charge + group. + + Currently, atom mass < 1.2 is taken to denote a proton. This behaviour + may be changed by modifying the 'is_hydrogen' function within. + + JDC 2011-02-03 + """""" + + # Build dictionary of bonded atoms. + bonded_atoms = dict() + for atom in self.atoms: + bonded_atoms[atom] = list() + for bond in self.bonds: + [atom1, atom2] = bond.atoms + bonded_atoms[atom1].append(atom2) + bonded_atoms[atom2].append(atom1) + + # Define hydrogen and heavy atom classes. + def is_hydrogen(atom): + """"""Check for H."""""" + return atom.mass < 1.2 + + def is_heavy(atom): + """"""Check for non H."""""" + return not is_hydrogen(atom) + + # Build list of sorted atoms, assigning charge groups by heavy atom. + sorted_atoms = list() + cgnr = 1 # charge group number: each heavy atoms is assigned its own charge group + # First pass: add heavy atoms, followed by the hydrogens bonded to them. + for atom in self.atoms: + if is_heavy(atom): + # Append heavy atom. + atom.cgnr = cgnr + sorted_atoms.append(atom) + # Append all hydrogens. + for bonded_atom in bonded_atoms[atom]: + if is_hydrogen(bonded_atom) and bonded_atom not in sorted_atoms: + # Append bonded hydrogen. + bonded_atom.cgnr = cgnr + sorted_atoms.append(bonded_atom) + cgnr += 1 + + # Second pass: Add any remaining atoms. + if len(sorted_atoms) < len(self.atoms): + for atom in self.atoms: + if atom not in sorted_atoms: + atom.cgnr = cgnr + sorted_atoms.append(atom) + cgnr += 1 + + # Replace current list of atoms with sorted list. + self.atoms = sorted_atoms + + # Renumber atoms in sorted list, starting from 1. + for index, atom in enumerate(self.atoms): + atom.id = index + 1 + + def balanceCharges(self, chargeList, FirstNonSoluteId=None): + """""" + Spread charges fractions among atoms to balance system's total charge. + + Note that python is very annoying about floating points. + Even after balance, there will always be some residue of order :math:`e^{-12}` + to :math:`e^{-16}`, which is believed to vanished once one writes a topology + file, say, for CNS or GMX, where floats are represented with 4 or 5 + maximum decimals. + """""" + limIds = [] + total = sum(chargeList) + totalConverted = total / qConv + self.printDebug(""charge to be balanced: total %13.10f"" % (totalConverted)) + maxVal = max(chargeList[:FirstNonSoluteId]) + minVal = min(chargeList[:FirstNonSoluteId]) + if abs(maxVal) >= abs(minVal): + lim = maxVal + else: + lim = minVal + nLims = chargeList.count(lim) + diff = totalConverted - round(totalConverted) + fix = lim - diff * qConv / nLims + id_ = 0 + for c in chargeList: + if c == lim: + limIds.append(id_) + chargeList[id_] = fix + id_ += 1 + self.printDebug(""balanceCharges done"") + return chargeList, fix, limIds + + def getABCOEFs(self): + """"""Get non-bonded coefficients."""""" + uniqAtomTypeIdList = self.getFlagData(""ATOM_TYPE_INDEX"") + nonBonIdList = self.getFlagData(""NONBONDED_PARM_INDEX"") + rawACOEFs = self.getFlagData(""LENNARD_JONES_ACOEF"") + rawBCOEFs = self.getFlagData(""LENNARD_JONES_BCOEF"") + ACOEFs = [] + BCOEFs = [] + ntypes = max(uniqAtomTypeIdList) + for id_ in range(len(self._atomTypeNameList)): + atomTypeId = uniqAtomTypeIdList[id_] + index = ntypes * (atomTypeId - 1) + atomTypeId + nonBondId = nonBonIdList[index - 1] + ACOEFs.append(rawACOEFs[nonBondId - 1]) + BCOEFs.append(rawBCOEFs[nonBondId - 1]) + self.printDebug(""getABCOEFs done"") + return ACOEFs, BCOEFs + + def setProperDihedralsCoef(self): + """""" + Create proper dihedrals list with Ryckaert-Bellemans coefficients. + + It takes self.condensedProperDihedrals and returns + self.properDihedralsCoefRB, a reduced list of quartet atoms + RB. + Coefficients ready for GMX (multiplied by 4.184):: + + self.properDihedralsCoefRB = [ [atom1,..., atom4], C[0:5] ] + + For proper dihedrals: a quartet of atoms may appear with more than + one set of parameters and to convert to GMX they are treated as RBs. + + The resulting coefficients calculated here may look slighted different + from the ones calculated by amb2gmx.pl because python is taken full float + number from prmtop and not rounded numbers from rdparm.out as amb2gmx.pl does. + """""" + properDihedralsCoefRB = [] + properDihedralsAlphaGamma = [] + properDihedralsGmx45 = [] + for item in self.condensedProperDihedrals: + V = 6 * [0.0] + C = 6 * [0.0] + for dih in item: + period = dih.period # Pn + kPhi = dih.kPhi # in rad + phaseRaw = dih.phase * radPi # in degree + phase = int(phaseRaw) # in degree + if period > 4 and self.gmx4: + rmtree(self.absHomeDir) + msg = ""Likely trying to convert ILDN to RB, DO NOT use option '-z'"" + logger(self.level).error(msg) + raise Exception(msg) + if phase in [0, 180]: + properDihedralsGmx45.append([item[0].atoms, phaseRaw, kPhi, period]) + if self.gmx4: + if kPhi != 0: + V[period] = 2 * kPhi * cal + if period == 1: + C[0] += 0.5 * V[period] + if phase == 0: + C[1] -= 0.5 * V[period] + else: + C[1] += 0.5 * V[period] + elif period == 2: + if phase == 180: + C[0] += V[period] + C[2] -= V[period] + else: + C[2] += V[period] + elif period == 3: + C[0] += 0.5 * V[period] + if phase == 0: + C[1] += 1.5 * V[period] + C[3] -= 2 * V[period] + else: + C[1] -= 1.5 * V[period] + C[3] += 2 * V[period] + elif period == 4: + if phase == 180: + C[2] += 4 * V[period] + C[4] -= 4 * V[period] + else: + C[0] += V[period] + C[2] -= 4 * V[period] + C[4] += 4 * V[period] + else: + properDihedralsAlphaGamma.append([item[0].atoms, phaseRaw, kPhi, period]) + # print phaseRaw, kPhi, period + if phase in [0, 180]: + properDihedralsCoefRB.append([item[0].atoms, C]) + + self.printDebug(""setProperDihedralsCoef done"") + + self.properDihedralsCoefRB = properDihedralsCoefRB + self.properDihedralsAlphaGamma = properDihedralsAlphaGamma + self.properDihedralsGmx45 = properDihedralsGmx45 + + def writeCharmmTopolFiles(self): + """"""Write CHARMM topology files."""""" + + self.printMess(""Writing CHARMM files\n"") + + at = self.atomType + self.getResidueLabel() + res = self.resName + + cmd = f""'{self.acExe}' -dr no -i '{self.acMol2FileName}' -fi mol2 -o '{self.charmmBase}' \ + -fo charmm -s 2 -at {at} -pf n -rn {res}"" + + self.printDebug(cmd) + + log = _getoutput(cmd) + self.printDebugQuoted(log) + + def writePdb(self, afile): + """""" + Write a new PDB file with the atom names defined by Antechamber. + + The format generated here use is slightly different from: + + old: http://www.wwpdb.org/documentation/file-format-content/format23/sect9.html + latest: http://www.wwpdb.org/documentation/file-format-content/format33/sect9.html + + respected to atom name. Using GAFF2 atom types:: + + CU/Cu Copper, CL/cl Chlorine, BR/br Bromine + + Args: + afile ([str]): file path name + """""" + # TODO: assuming only one residue ('1') + pdbFile = open(afile, ""w"") + fbase = os.path.basename(afile) + pdbFile.write(""REMARK "" + head % (fbase, date)) + id_ = 1 + for atom in self.atoms: + # id_ = self.atoms.index(atom) + 1 + aName = atom.atomName + if atom.atomType.atomTypeName.upper() in specialGaffAtoms: + s = atom.atomType.atomTypeName.upper() + else: + s = atom.atomType.atomTypeName[0].upper() + + rName = self.residueLabel[0] + x = atom.coords[0] + y = atom.coords[1] + z = atom.coords[2] + line = ""%-6s%5d %4s %3s Z%4d%s%8.3f%8.3f%8.3f%6.2f%6.2f%s%2s\n"" % ( + ""ATOM"", + id_, + aName, + rName, + 1, + 4 * "" "", + x, + y, + z, + 1.0, + 0.0, + 10 * "" "", + s, + ) + pdbFile.write(line) + id_ += 1 + pdbFile.write(""END\n"") + + def writeGromacsTopolFiles(self): + """""" + Write GMX topology Files. + + :: + + # from ~/Programmes/amber10/dat/leap/parm/gaff.dat + #atom type atomic mass atomic polarizability comments + ca 12.01 0.360 Sp2 C in pure aromatic systems + ha 1.008 0.135 H bonded to aromatic carbon + + #bonded atoms harmonic force kcal/mol/A^2 eq. dist. Ang. comments + ca-ha 344.3* 1.087** SOURCE3 1496 0.0024 0.0045 + * for gmx: 344.3 * 4.184 * 100 * 2 = 288110 kJ/mol/nm^2 (why factor 2?) + ** convert Ang to nm ( div by 10) for gmx: 1.087 A = 0.1087 nm + # CA HA 1 0.10800 307105.6 ; ged from 340. bsd on C6H6 nmodes; PHE,TRP,TYR (from ffamber99bon.itp) + # CA-HA 367.0 1.080 changed from 340. bsd on C6H6 nmodes; PHE,TRP,TYR (from parm99.dat) + + # angle HF kcal/mol/rad^2 eq angle degrees comments + ca-ca-ha 48.5* 120.01 SOURCE3 2980 0.1509 0.2511 + * to convert to gmx: 48.5 * 4.184 * 2 = 405.848 kJ/mol/rad^2 (why factor 2?) + # CA CA HA 1 120.000 418.400 ; new99 (from ffamber99bon.itp) + # CA-CA-HA 50.0 120.00 (from parm99.dat) + + # dihedral idivf barrier hight/2 kcal/mol phase degrees periodicity comments + X -ca-ca-X 4 14.500* 180.000 2.000 intrpol.bsd.on C6H6 + *convert 2 gmx: 14.5/4 * 4.184 * 2 (?) (yes in amb2gmx, not in topolbuild, why?) = 30.334 or 15.167 kJ/mol + # X -CA-CA-X 4 14.50 180.0 2. intrpol.bsd.on C6H6 (from parm99.dat) + # X CA CA X 3 30.334 0.000 -30.33400 0.000 0.000 0.000 ; intrpol.bsd.on C6H6 + ;propers treated as RBs in GMX to use combine multiple AMBER torsions per quartet (from ffamber99bon.itp) + + # impr. dihedral barrier hight/2 phase degrees periodicity comments + X -X -ca-ha 1.1* 180. 2. bsd.on C6H6 nmodes + * to convert to gmx: 1.1 * 4.184 = 4.6024 kJ/mol/rad^2 + # X -X -CA-HA 1.1 180. 2. bsd.on C6H6 nmodes (from parm99.dat) + # X X CA HA 1 180.00 4.60240 2 ; bsd.on C6H6 nmodes + ;impropers treated as propers in GROMACS to use correct AMBER analytical function (from ffamber99bon.itp) + + # 6-12 parms sigma = 2 * r * 2^(-1/6) epsilon + # atomtype radius Ang. pot. well depth kcal/mol comments + ha 1.4590* 0.0150** Spellmeyer + ca 1.9080 0.0860 OPLS + * to convert to gmx: + sigma = 1.4590 * 2^(-1/6) * 2 = 2 * 1.29982 Ang. = 2 * 0.129982 nm = 1.4590 * 2^(5/6)/10 = 0.259964 nm + ** to convert to gmx: 0.0150 * 4.184 = 0.06276 kJ/mol + # amber99_3 CA 0.0000 0.0000 A 3.39967e-01 3.59824e-01 (from ffamber99nb.itp) + # amber99_22 HA 0.0000 0.0000 A 2.59964e-01 6.27600e-02 (from ffamber99nb.itp) + # C* 1.9080 0.0860 Spellmeyer + # HA 1.4590 0.0150 Spellmeyer (from parm99.dat) + # to convert r and epsilon to ACOEF and BCOEF + # ACOEF = sqrt(e1*e2) * (r1 + r2)^12 ; BCOEF = 2 * sqrt(e1*e2) * (r1 + r2)^6 = 2 * ACOEF/(r1+r2)^6 + # to convert ACOEF and BCOEF to r and epsilon + # r = 0.5 * (2*ACOEF/BCOEF)^(1/6); ep = BCOEF^2/(4*ACOEF) + # to convert ACOEF and BCOEF to sigma and epsilon (GMX) + # sigma = (ACOEF/BCOEF)^(1/6) * 0.1 ; epsilon = 4.184 * BCOEF^2/(4*ACOEF) + # ca ca 819971.66 531.10 + # ca ha 76245.15 104.66 + # ha ha 5716.30 18.52 + + For proper dihedrals: a quartet of atoms may appear with more than + one set of parameters and to convert to GMX they are treated as RBs; + use the algorithm: + + .. code-block:: c++ + + for(my $j=$i;$j<=$lines;$j++){ + my $period = $pn{$j}; + if($pk{$j}>0) { + $V[$period] = 2*$pk{$j}*$cal; + } + # assign V values to C values as predefined # + if($period==1){ + $C[0]+=0.5*$V[$period]; + if($phase{$j}==0){ + $C[1]-=0.5*$V[$period]; + }else{ + $C[1]+=0.5*$V[$period]; + } + }elsif($period==2){ + if(($phase{$j}==180)||($phase{$j}==3.14)){ + $C[0]+=$V[$period]; + $C[2]-=$V[$period]; + }else{ + $C[2]+=$V[$period]; + } + }elsif($period==3){ + $C[0]+=0.5*$V[$period]; + if($phase{$j}==0){ + $C[1]+=1.5*$V[$period]; + $C[3]-=2*$V[$period]; + }else{ + $C[1]-=1.5*$V[$period]; + $C[3]+=2*$V[$period]; + } + }elsif($period==4){ + if(($phase{$j}==180)||($phase{$j}==3.14)){ + $C[2]+=4*$V[$period]; + $C[4]-=4*$V[$period]; + }else{ + $C[0]+=$V[$period]; + $C[2]-=4*$V[$period]; + $C[4]+=4*$V[$period]; + } + } + } + """""" + if self.amb2gmx: + os.chdir(self.absHomeDir) + + self.printMess(""Writing GROMACS files\n"") + + self.setAtomType4Gromacs() + + self.writeGroFile() + + self.writePosreFile() + + self.writeGromacsTop() + + self.writeMdpFiles() + + if self.amb2gmx: + os.chdir(self.rootDir) + + def setAtomType4Gromacs(self): + """""" + Set atom types for Gromacs. + + Atom types names in Gromacs TOP file are not case sensitive; + this routine will append a '_' to lower case atom type. + + Example: + + >>> CA and ca -> CA and ca_ + """""" + + if self.merge: + self.printMess(""Merging identical lower and uppercase atomtypes in GMX top file.\n"") + atNames = [at.atomTypeName for at in self.atomTypes] + delAtomTypes = [] + modAtomTypes = [] + atomTypesGromacs = [] + dictAtomTypes = {} + for at in self.atomTypes: + atName = at.atomTypeName + dictAtomTypes[atName] = at + if atName.islower() and atName.upper() in atNames: + atUpper = self.atomTypes[atNames.index(atName.upper())] + if at.ACOEF == atUpper.ACOEF and at.BCOEF == atUpper.BCOEF and at.mass == atUpper.mass: + delAtomTypes.append(atName) + else: + newAtName = atName + ""_"" + modAtomTypes.append(atName) + atomType = AtomType(newAtName, at.mass, at.ACOEF, at.BCOEF) + atomTypesGromacs.append(atomType) + dictAtomTypes[newAtName] = atomType + else: + atomTypesGromacs.append(at) + + atomsGromacs = [] + for a in self.atoms: + atName = a.atomType.atomTypeName + if atName in delAtomTypes: + atom = Atom(a.atomName, dictAtomTypes[atName.upper()], a.id, a.resid, a.mass, a.charge, a.coords) + atom.cgnr = a.cgnr + atomsGromacs.append(atom) + elif atName in modAtomTypes: + atom = Atom(a.atomName, dictAtomTypes[atName + ""_""], a.id, a.resid, a.mass, a.charge, a.coords) + atom.cgnr = a.cgnr + atomsGromacs.append(atom) + else: + atomsGromacs.append(a) + + self.atomTypesGromacs = atomTypesGromacs + self.atomsGromacs = atomsGromacs + return + + self.printMess(""Disambiguating lower and uppercase atomtypes in GMX top file, even if identical.\n"") + self.atomTypesGromacs = self.atomTypes + self.atomsGromacs = self.atoms + + def writeGromacsTop(self): + """"""Write GMX topology file."""""" + if self.atomTypeSystem == ""amber"": + d2opls = dictAtomTypeAmb2OplsGmxCode + else: + d2opls = dictAtomTypeGaff2OplsGmxCode + + topText = [] + itpText = [] + oitpText = [] + otopText = [] + top = self.baseName + ""_GMX.top"" + itp = self.baseName + ""_GMX.itp"" + posre = ""posre_"" + self.baseName + "".itp"" + otop = self.baseName + ""_GMX_OPLS.top"" + oitp = self.baseName + ""_GMX_OPLS.itp"" + + headDefault = """""" +[ defaults ] +; nbfunc comb-rule gen-pairs fudgeLJ fudgeQQ +1 2 yes 0.5 0.8333333333 +"""""" + headItp = """""" +; Include %s topology +#include ""%s"" +"""""" + headLigPosre = """""" +; Ligand position restraints +#ifdef POSRES_LIG +#include ""%s"" +#endif +"""""" + headOpls = """""" +; Include forcefield parameters +#include ""ffoplsaa.itp"" +"""""" + headSystem = """""" +[ system ] + %s +"""""" + headMols = """""" +[ molecules ] +; Compound nmols +"""""" + headAtomtypes = """""" +[ atomtypes ] +;name bond_type mass charge ptype sigma epsilon Amb +"""""" + headAtomtypesOpls = """""" +; For OPLS atomtypes manual fine tuning +; AC_at:OPLS_at:OPLScode: Possible_Alternatives (see ffoplsaa.atp and ffoplsaanb.itp) +"""""" + headMoleculetype = """""" +[ moleculetype ] +;name nrexcl + %-16s 3 +"""""" + headAtoms = """""" +[ atoms ] +; nr type resi res atom cgnr charge mass ; qtot bond_type +"""""" + headBonds = """""" +[ bonds ] +; ai aj funct r k +"""""" + headPairs = """""" +[ pairs ] +; ai aj funct +"""""" + headAngles = """""" +[ angles ] +; ai aj ak funct theta cth +"""""" + headProDih = """""" +[ dihedrals ] ; propers +; treated as RBs in GROMACS to use combine multiple AMBER torsions per quartet +; i j k l func C0 C1 C2 C3 C4 C5 +"""""" + + headProDihAlphaGamma = """"""; treated as usual propers in GROMACS since Phase angle diff from 0 or 180 degrees +; i j k l func phase kd pn +"""""" + + headProDihGmx45 = """""" +[ dihedrals ] ; propers +; for gromacs 4.5 or higher, using funct 9 +; i j k l func phase kd pn +"""""" + + headImpDih = """""" +[ dihedrals ] ; impropers +; treated as propers in GROMACS to use correct AMBER analytical function +; i j k l func phase kd pn +"""""" + + # NOTE: headTopWaterTip3p and headTopWaterSpce actually do NOTHING + # ============================================================================================================== + # _headTopWaterTip3p = """""" + # [ bondtypes ] + # ; i j func b0 kb + # OW HW 1 0.09572 462750.4 ; TIP3P water + # HW HW 1 0.15139 462750.4 ; TIP3P water + # + # [ angletypes ] + # ; i j k func th0 cth + # HW OW HW 1 104.520 836.800 ; TIP3P water + # HW HW OW 1 127.740 0.000 ; (found in crystallographic water with 3 bonds) + # """""" + # + # _headTopWaterSpce = """""" + # [ bondtypes ] + # ; i j func b0 kb + # OW HW 1 0.1 462750.4 ; SPCE water + # HW HW 1 0.1633 462750.4 ; SPCE water + # + # [ angletypes ] + # ; i j k func th0 cth + # HW OW HW 1 109.47 836.800 ; SPCE water + # HW HW OW 1 125.265 0.000 ; SPCE water + # """""" + # ============================================================================================================== + + headNa = """""" +[ moleculetype ] + ; molname nrexcl + NA+ 1 + +[ atoms ] + ; id_ at type res nr residue name at name cg nr charge mass + 1 %s 1 NA+ NA+ 1 1 22.9898 +"""""" + headCl = """""" +[ moleculetype ] + ; molname nrexcl + CL- 1 + +[ atoms ] + ; id_ at type res nr residue name at name cg nr charge mass + 1 %s 1 CL- CL- 1 -1 35.45300 +"""""" + headK = """""" +[ moleculetype ] + ; molname nrexcl + K+ 1 + +[ atoms ] + ; id_ at type res nr residue name at name cg nr charge mass + 1 %s 1 K+ K+ 1 1 39.100 +"""""" + headWaterTip3p = """""" +[ moleculetype ] +; molname nrexcl ; TIP3P model + WAT 2 + +[ atoms ] +; nr type resnr residue atom cgnr charge mass + 1 OW 1 WAT O 1 -0.834 16.00000 + 2 HW 1 WAT H1 1 0.417 1.00800 + 3 HW 1 WAT H2 1 0.417 1.00800 + +#ifdef FLEXIBLE +[ bonds ] +; i j funct length force.c. +1 2 1 0.09572 462750.4 0.09572 462750.4 +1 3 1 0.09572 462750.4 0.09572 462750.4 + +[ angles ] +; i j k funct angle force.c. +2 1 3 1 104.520 836.800 104.520 836.800 +#else +[ settles ] +; i j funct length +1 1 0.09572 0.15139 + +[ exclusions ] +1 2 3 +2 1 3 +3 1 2 +#endif +"""""" + + headWaterSpce = """""" +[ moleculetype ] +; molname nrexcl ; SPCE model + WAT 2 + +[ atoms ] +; nr type resnr residue atom cgnr charge mass + 1 OW 1 WAT O 1 -0.8476 15.99940 + 2 HW 1 WAT H1 1 0.4238 1.00800 + 3 HW 1 WAT H2 1 0.4238 1.00800 + +#ifdef FLEXIBLE +[ bonds ] +; i j funct length force.c. +1 2 1 0.1 462750.4 0.1 462750.4 +1 3 1 0.1 462750.4 0.1 462750.4 + +[ angles ] +; i j k funct angle force.c. +2 1 3 1 109.47 836.800 109.47 836.800 +#else +[ settles ] +; OW funct doh dhh +1 1 0.1 0.16330 + +[ exclusions ] +1 2 3 +2 1 3 +3 1 2 +#endif +"""""" + if self.direct and self.amb2gmx: + self.printMess(""Converting directly from AMBER to GROMACS (EXPERIMENTAL).\n"") + + # Dict of ions dealt by acpype emulating amb2gmx + ionsDict = {""Na+"": headNa, ""Cl-"": headCl, ""K+"": headK} + ionsSorted = [] + # NOTE: headWaterTip3p and headWaterSpce actually do the real thing + # so, skipping headTopWaterTip3p and headWaterTip3p + # headTopWater = headTopWaterTip3p + headWater = headWaterTip3p + + nWat = 0 + topText.append(""; "" + head % (top, date)) + otopText.append(""; "" + head % (otop, date)) + topText.append(headDefault) + + nSolute = 0 + if not self.amb2gmx: + topText.append(headItp % (itp, itp)) + topText.append(headLigPosre % posre) + otopText.append(headOpls) + otopText.append(headItp % (itp, itp)) + otopText.append(headLigPosre % posre) + itpText.append(""; "" + head % (itp, date)) + oitpText.append(""; "" + head % (oitp, date)) + + self.printDebug(""atomTypes %i"" % len(self.atomTypesGromacs)) + temp = [] + otemp = [] + for aType in self.atomTypesGromacs: + aTypeName = aType.atomTypeName + oaCode = d2opls.get(aTypeName, [""x"", ""0""])[:-1] + aTypeNameOpls = oplsCode2AtomTypeDict.get(oaCode[0], ""x"") + A = aType.ACOEF + B = aType.BCOEF + # one cannot infer sigma or epsilon for B = 0, assuming 0 for them + if B == 0.0: + sigma, epsilon, r0, epAmber = 0, 0, 0, 0 + else: + r0 = 0.5 * math.pow((2 * A / B), (1.0 / 6)) + epAmber = 0.25 * B * B / A + sigma = 0.1 * math.pow((A / B), (1.0 / 6)) + epsilon = cal * epAmber + if aTypeName == ""OW"": + if A == 629362.166 and B == 625.267765: + # headTopWater = headTopWaterSpce + headWater = headWaterSpce + # OW 629362.166 625.267765 spce + # OW 581935.564 594.825035 tip3p + # print aTypeName, A, B + line = ( + "" %-8s %-11s %3.5f %3.5f A %13.5e %13.5e"" + % ( + aTypeName, + aTypeName, + 0.0, + 0.0, + sigma, + epsilon, + ) + + f"" ; {r0:4.2f} {epAmber:1.4f}\n"" + ) + oline = f""; {aTypeName}:{aTypeNameOpls}:opls_{oaCode[0]}: {oaCode[1:]!r}\n"" + # tmpFile.write(line) + temp.append(line) + otemp.append(oline) + if self.amb2gmx: + topText.append(headAtomtypes) + topText += temp + nWat = self.residueLabel.count(""WAT"") + for ion in ionsDict: + nIon = self.residueLabel.count(ion) + if nIon > 0: + idIon = self.residueLabel.index(ion) + ionType = self.search(name=ion).atomType.atomTypeName + ionsSorted.append((idIon, nIon, ion, ionType)) + ionsSorted.sort() + else: + itpText.append(headAtomtypes) + itpText += temp + oitpText.append(headAtomtypesOpls) + oitpText += otemp + self.printDebug(""GMX atomtypes done"") + + if len(self.atoms) > 3 * nWat + sum(x[1] for x in ionsSorted): + nSolute = 1 + + if nWat: + # topText.append(headTopWater) + self.printDebug(""type of water '%s'"" % headWater[43:48].strip()) + + if nSolute: + if self.amb2gmx: + topText.append(headMoleculetype % self.baseName) + else: + itpText.append(headMoleculetype % self.baseName) + oitpText.append(headMoleculetype % self.baseName) + + self.printDebug(""atoms %i"" % len(self.atoms)) + qtot = 0.0 + count = 1 + temp = [] + otemp = [] + id2oplsATDict = {} + for atom in self.atomsGromacs: + resid = atom.resid + resname = self.residueLabel[resid] + if not self.direct: + if resname in [*list(ionsDict), ""WAT""]: + break + aName = atom.atomName + aType = atom.atomType.atomTypeName + oItem = d2opls.get(aType, [""x"", 0]) + oplsAtName = oplsCode2AtomTypeDict.get(oItem[0], ""x"") + id_ = atom.id + id2oplsATDict[id_] = oplsAtName + oaCode = ""opls_"" + oItem[0] + cgnr = id_ + if self.sorted: + cgnr = atom.cgnr # JDC + charge = atom.charge + mass = atom.mass + omass = float(oItem[-1]) + qtot += charge + resnr = resid + 1 + line = ""%6d %4s %5d %5s %5s %4d %12.6f %12.5f ; qtot %1.3f\n"" % ( + id_, + aType, + resnr, + resname, + aName, + cgnr, + charge, + mass, + qtot, + ) # JDC + oline = ""%6d %4s %5d %5s %5s %4d %12.6f %12.5f ; qtot % 3.3f %-4s\n"" % ( + id_, + oaCode, + resnr, + resname, + aName, + cgnr, + charge, + omass, + qtot, + oplsAtName, + ) # JDC + count += 1 + temp.append(line) + otemp.append(oline) + if temp: + if self.amb2gmx: + topText.append(headAtoms) + topText += temp + else: + itpText.append(headAtoms) + itpText += temp + oitpText.append(headAtoms) + oitpText += otemp + self.printDebug(""GMX atoms done"") + + # remove bond of water + self.printDebug(""bonds %i"" % len(self.bonds)) + temp = [] + otemp = [] + for bond in self.bonds: + res1 = self.residueLabel[bond.atoms[0].resid] + res2 = self.residueLabel[bond.atoms[0].resid] + if ""WAT"" in [res1, res2]: + continue + a1Name = bond.atoms[0].atomName + a2Name = bond.atoms[1].atomName + id1 = bond.atoms[0].id + id2 = bond.atoms[1].id + oat1 = id2oplsATDict.get(id1) + oat2 = id2oplsATDict.get(id2) + line = ""%6i %6i %3i %13.4e %13.4e ; %6s - %-6s\n"" % ( + id1, + id2, + 1, + bond.rEq * 0.1, + bond.kBond * 200 * cal, + a1Name, + a2Name, + ) + oline = ""%6i %6i %3i ; %13.4e %13.4e ; %6s - %-6s %6s - %-6s\n"" % ( + id1, + id2, + 1, + bond.rEq * 0.1, + bond.kBond * 200 * cal, + a1Name, + a2Name, + oat1, + oat2, + ) + temp.append(line) + otemp.append(oline) + temp.sort() + otemp.sort() + if temp: + if self.amb2gmx: + topText.append(headBonds) + topText += temp + else: + itpText.append(headBonds) + itpText += temp + oitpText.append(headBonds) + oitpText += otemp + self.printDebug(""GMX bonds done"") + + self.printDebug(""atomPairs %i"" % len(self.atomPairs)) + temp = [] + for pair in self.atomPairs: + # if not printed: + # tmpFile.write(headPairs) + # printed = True + a1Name = pair[0].atomName + a2Name = pair[1].atomName + id1 = pair[0].id + id2 = pair[1].id + # id1 = self.atoms.index(pair[0]) + 1 + # id2 = self.atoms.index(pair[1]) + 1 + line = ""%6i %6i %6i ; %6s - %-6s\n"" % (id1, id2, 1, a1Name, a2Name) + temp.append(line) + temp.sort() + if temp: + if self.amb2gmx: + topText.append(headPairs) + topText += temp + else: + itpText.append(headPairs) + itpText += temp + oitpText.append(headPairs) + oitpText += temp + self.printDebug(""GMX pairs done"") + + self.printDebug(""angles %i"" % len(self.angles)) + temp = [] + otemp = [] + for angle in self.angles: + a1 = angle.atoms[0].atomName + a2 = angle.atoms[1].atomName + a3 = angle.atoms[2].atomName + id1 = angle.atoms[0].id + id2 = angle.atoms[1].id + id3 = angle.atoms[2].id + oat1 = id2oplsATDict.get(id1) + oat2 = id2oplsATDict.get(id2) + oat3 = id2oplsATDict.get(id3) + line = ""%6i %6i %6i %6i %13.4e %13.4e ; %6s - %-6s - %-6s\n"" % ( + id1, + id2, + id3, + 1, + angle.thetaEq * radPi, + 2 * cal * angle.kTheta, + a1, + a2, + a3, + ) + oline = ""%6i %6i %6i %6i ; %13.4e %13.4e ; %6s - %-4s - %-6s %4s - %+4s - %-4s\n"" % ( + id1, + id2, + id3, + 1, + angle.thetaEq * radPi, + 2 * cal * angle.kTheta, + a1, + a2, + a3, + oat1, + oat2, + oat3, + ) + temp.append(line) + otemp.append(oline) + temp.sort() + otemp.sort() + if temp: + if self.amb2gmx: + topText.append(headAngles) + topText += temp + else: + itpText.append(headAngles) + itpText += temp + oitpText.append(headAngles) + oitpText += otemp + self.printDebug(""GMX angles done"") + + self.setProperDihedralsCoef() + self.printDebug(""properDihedralsCoefRB %i"" % len(self.properDihedralsCoefRB)) + self.printDebug(""properDihedralsAlphaGamma %i"" % len(self.properDihedralsAlphaGamma)) + self.printDebug(""properDihedralsGmx45 %i"" % len(self.properDihedralsGmx45)) + temp = [] + otemp = [] + if self.gmx4: + self.printMess(""Writing RB dihedrals for old GMX 4.\n"") + for dih in self.properDihedralsCoefRB: + a1 = dih[0][0].atomName + a2 = dih[0][1].atomName + a3 = dih[0][2].atomName + a4 = dih[0][3].atomName + id1 = dih[0][0].id + id2 = dih[0][1].id + id3 = dih[0][2].id + id4 = dih[0][3].id + oat1 = id2oplsATDict.get(id1) + oat2 = id2oplsATDict.get(id2) + oat3 = id2oplsATDict.get(id3) + oat4 = id2oplsATDict.get(id4) + c0, c1, c2, c3, c4, c5 = dih[1] + line = ""%6i %6i %6i %6i %6i %10.5f %10.5f %10.5f %10.5f %10.5f %10.5f"" % ( + id1, + id2, + id3, + id4, + 3, + c0, + c1, + c2, + c3, + c4, + c5, + ) + "" ; %6s-%6s-%6s-%6s\n"" % (a1, a2, a3, a4) + oline = ""%6i %6i %6i %6i %6i ; %10.5f %10.5f %10.5f %10.5f %10.5f %10.5f"" % ( + id1, + id2, + id3, + id4, + 3, + c0, + c1, + c2, + c3, + c4, + c5, + ) + "" ; %6s-%6s-%6s-%6s %4s-%4s-%4s-%4s\n"" % (a1, a2, a3, a4, oat1, oat2, oat3, oat4) + temp.append(line) + otemp.append(oline) + temp.sort() + otemp.sort() + if temp: + if self.amb2gmx: + topText.append(headProDih) + topText += temp + else: + itpText.append(headProDih) + itpText += temp + oitpText.append(headProDih) + oitpText += otemp + self.printDebug(""GMX proper dihedrals done"") + else: + self.printMess(""Writing GMX dihedrals for GMX 4.5 and higher.\n"") + funct = 9 # 9 + for dih in self.properDihedralsGmx45: + a1 = dih[0][0].atomName + a2 = dih[0][1].atomName + a3 = dih[0][2].atomName + a4 = dih[0][3].atomName + id1 = dih[0][0].id + id2 = dih[0][1].id + id3 = dih[0][2].id + id4 = dih[0][3].id + ph = dih[1] # phase already in degree + kd = dih[2] * cal # kPhi PK + pn = dih[3] # .period + line = ""%6i %6i %6i %6i %6i %8.2f %9.5f %3i ; %6s-%6s-%6s-%6s\n"" % ( + id1, + id2, + id3, + id4, + funct, + ph, + kd, + pn, + a1, + a2, + a3, + a4, + ) + oline = ""%6i %6i %6i %6i %6i ; %8.2f %9.5f %3i ; %6s-%6s-%6s-%6s\n"" % ( + id1, + id2, + id3, + id4, + funct, + ph, + kd, + pn, + a1, + a2, + a3, + a4, + ) + temp.append(line) + otemp.append(oline) + temp.sort() + otemp.sort() + if temp: + if self.amb2gmx: + topText.append(headProDihGmx45) + topText += temp + else: + itpText.append(headProDihGmx45) + itpText += temp + oitpText.append(headProDihGmx45) + oitpText += otemp + + # for properDihedralsAlphaGamma + if not self.gmx4: + funct = 4 # 4 + else: + funct = 1 + temp = [] + otemp = [] + for dih in self.properDihedralsAlphaGamma: + a1 = dih[0][0].atomName + a2 = dih[0][1].atomName + a3 = dih[0][2].atomName + a4 = dih[0][3].atomName + id1 = dih[0][0].id + id2 = dih[0][1].id + id3 = dih[0][2].id + id4 = dih[0][3].id + ph = dih[1] # phase already in degree + kd = dih[2] * cal # kPhi PK + pn = dih[3] # .period + line = ""%6i %6i %6i %6i %6i %8.2f %9.5f %3i ; %6s-%6s-%6s-%6s\n"" % ( + id1, + id2, + id3, + id4, + funct, + ph, + kd, + pn, + a1, + a2, + a3, + a4, + ) + oline = ""%6i %6i %6i %6i %6i ; %8.2f %9.5f %3i ; %6s-%6s-%6s-%6s\n"" % ( + id1, + id2, + id3, + id4, + funct, + ph, + kd, + pn, + a1, + a2, + a3, + a4, + ) + temp.append(line) + otemp.append(oline) + temp.sort() + otemp.sort() + if temp: + if self.amb2gmx: + topText.append(headProDihAlphaGamma) + topText += temp + else: + itpText.append(headProDihAlphaGamma) + itpText += temp + oitpText.append(headProDihAlphaGamma) + oitpText += otemp + self.printDebug(""GMX special proper dihedrals done"") + + self.printDebug(""improperDihedrals %i"" % len(self.improperDihedrals)) + temp = [] + otemp = [] + for dih in self.improperDihedrals: + a1 = dih.atoms[0].atomName + a2 = dih.atoms[1].atomName + a3 = dih.atoms[2].atomName + a4 = dih.atoms[3].atomName + id1 = dih.atoms[0].id + id2 = dih.atoms[1].id + id3 = dih.atoms[2].id + id4 = dih.atoms[3].id + kd = dih.kPhi * cal + pn = dih.period + ph = dih.phase * radPi + line = ""%6i %6i %6i %6i %6i %8.2f %9.5f %3i ; %6s-%6s-%6s-%6s\n"" % ( + id1, + id2, + id3, + id4, + funct, + ph, + kd, + pn, + a1, + a2, + a3, + a4, + ) + oline = ""%6i %6i %6i %6i %6i ; %8.2f %9.5f %3i ; %6s-%6s-%6s-%6s\n"" % ( + id1, + id2, + id3, + id4, + funct, + ph, + kd, + pn, + a1, + a2, + a3, + a4, + ) + temp.append(line) + otemp.append(oline) + temp.sort() + otemp.sort() + if temp: + if self.amb2gmx: + topText.append(headImpDih) + topText += temp + else: + itpText.append(headImpDih) + itpText += temp + oitpText.append(headImpDih) + oitpText += otemp + self.printDebug(""GMX improper dihedrals done"") + + if not self.direct: + for ion in ionsSorted: + topText.append(ionsDict[ion[2]] % ion[3]) + + if nWat: + topText.append(headWater) + + topText.append(headSystem % (self.baseName)) + topText.append(headMols) + otopText.append(headSystem % (self.baseName)) + otopText.append(headMols) + + if nSolute > 0: + topText.append("" %-16s %-6i\n"" % (self.baseName, nSolute)) + otopText.append("" %-16s %-6i\n"" % (self.baseName, nSolute)) + + if not self.direct: + for ion in ionsSorted: + topText.append("" %-16s %-6i\n"" % (ion[2].upper(), ion[1])) + + if nWat: + topText.append("" %-16s %-6i\n"" % (""WAT"", nWat)) + + if self.topo14Data.hasNondefault14(): + citation = ( + "" BERNARDI, A., FALLER, R., REITH, D., and KIRSCHNER, K. N. ACPYPE update for\n"" + + "" nonuniform 1-4 scale factors: Conversion of the GLYCAM06 force field from AMBER\n"" + + ' to GROMACS. SoftwareX 10 (2019), 100241. doi: 10.1016/j.softx.2019.100241""\n' + ) + + msg = ""Non-default 1-4 scale parameters detected. Converting individually. Please cite:\n\n"" + citation + + self.printMess(msg) + topText = self.topo14Data.patch_gmx_topol14("""".join(topText)) + + gmxDir = os.path.abspath(""."") + topFileName = os.path.join(gmxDir, top) + topFile = open(topFileName, ""w"") + topFile.writelines(topText) + self.topText = topText + + if not self.amb2gmx: + itpFileName = os.path.join(gmxDir, itp) + itpFile = open(itpFileName, ""w"") + itpFile.writelines(itpText) + oitpFileName = os.path.join(gmxDir, oitp) + oitpFile = open(oitpFileName, ""w"") + oitpFile.writelines(oitpText) + otopFileName = os.path.join(gmxDir, otop) + otopFile = open(otopFileName, ""w"") + otopFile.writelines(otopText) + + def writeGroFile(self): + """"""Write GRO files."""""" + # print ""Writing GROMACS GRO file\n"" + self.printDebug(""writing GRO file"") + gro = self.baseName + ""_GMX.gro"" + gmxDir = os.path.abspath(""."") + groFileName = os.path.join(gmxDir, gro) + groFile = open(groFileName, ""w"") + groFile.write(head % (gro, date)) + groFile.write("" %i\n"" % len(self.atoms)) + count = 1 + for atom in self.atoms: + coords = [c * 0.1 for c in atom.coords] + resid = atom.resid + line = ""%5d%5s%5s%5d%8.3f%8.3f%8.3f\n"" % ( + resid + 1, + self.residueLabel[resid], + atom.atomName, + count, + coords[0], + coords[1], + coords[2], + ) + count += 1 + if count == 100000: + count = 0 + groFile.write(line) + if self.pbc: + boxX = self.pbc[0][0] * 0.1 + boxY = self.pbc[0][1] * 0.1 + boxZ = self.pbc[0][2] * 0.1 + vX = self.pbc[1][0] + # vY = self.pbc[1][1] + # vZ = self.pbc[1][2] + if vX == 90.0: + self.printDebug(""PBC triclinic"") + text = f""{boxX:11.5f} {boxY:11.5f} {boxZ:11.5f}\n"" + elif round(vX, 2) == 109.47: + self.printDebug(""PBC octahedron"") + f1 = 0.471405 # 1/3 * sqrt(2) + f2 = 0.333333 * boxX + v22 = boxY * 2 * f1 + v33 = boxZ * f1 * 1.73205 # f1 * sqrt(3) + v21 = v31 = v32 = 0.0 + v12 = f2 + v13 = -f2 + v23 = f1 * boxX + text = ""{:11.5f} {:11.5f} {:11.5f} {:11.5f} {:11.5f} {:11.5f} {:11.5f} {:11.5f} {:11.5f}\n"".format( + boxX, + v22, + v33, + v21, + v31, + v12, + v32, + v13, + v23, + ) + else: + self.printDebug(""Box size estimated"") + X = [a.coords[0] * 0.1 for a in self.atoms] + Y = [a.coords[1] * 0.1 for a in self.atoms] + Z = [a.coords[2] * 0.1 for a in self.atoms] + boxX = max(X) - min(X) # + 2.0 # 2.0 is double of rlist + boxY = max(Y) - min(Y) # + 2.0 + boxZ = max(Z) - min(Z) # + 2.0 + text = f""{boxX * 20.0:11.5f} {boxY * 20.0:11.5f} {boxZ * 20.0:11.5f}\n"" + groFile.write(text) + + def writePosreFile(self, fc=1000): + """""" + Write file with positional restraints for heavy atoms. + + http://www.mdtutorials.com/gmx/complex/06_equil.html + """""" + self.printDebug(""writing POSRE file"") + posre = ""posre_"" + self.baseName + "".itp"" + gmxDir = os.path.abspath(""."") + posreFileName = os.path.join(gmxDir, posre) + posreFile = open(posreFileName, ""w"") + posreFile.write(""; "" + head % (posre, date)) + posreFile.write(""\n[ position_restraints ]\n; atom type fx fy fz\n"") + for atom in self.atoms: + if not atom.atomType.atomTypeName.upper().startswith(""H""): + posreFile.write(f""{atom.id:>6d} 1 {fc:>5d} {fc:>5d} {fc:>5d}\n"") + + def writeMdpFiles(self): + """"""Write MDP for test with GROMACS."""""" + emMdp = f""""""; to test +; echo 0 | gmx editconf -f {self.baseName}_GMX.gro -bt octahedron -d 10 -c -princ +; gmx grompp -f em.mdp -c out.gro -p {self.baseName}_GMX.top -o em.tpr -v +; gmx mdrun -ntmpi 1 -v -deffnm em + +; Parameters describing what to do, when to stop and what to save +integrator = steep ; Algorithm (steep = steepest descent minimization) +nsteps = 500 ; Maximum number of (minimization) steps to perform +nstxout = 10 + +; Parameters describing how to find the neighbors of each atom and how to calculate the interactions +nstlist = 1 ; Frequency to update the neighbour list and long range forces +cutoff-scheme = Verlet +rlist = 1.2 ; Cut-off for making neighbour list (short range forces) +coulombtype = PME ; Treatment of long range electrostatic interactions +rcoulomb = 1.2 ; long range electrostatic cut-off +vdw-type = cutoff +vdw-modifier = force-switch +rvdw-switch = 1.0 +rvdw = 1.2 ; long range Van der Waals cut-off +pbc = xyz ; Periodic Boundary Conditions +DispCorr = no +; vmd em.gro em.trr +"""""" + mdMdp = f""""""; to test +; gmx grompp -f md.mdp -c em.gro -p {self.baseName}_GMX.top -o md.tpr +; gmx mdrun -ntmpi 1 -v -deffnm md +; define = -DPOSRES_LIG +integrator = md +nsteps = 10000 +nstxout = 10 +cutoff-scheme = verlet +coulombtype = PME +constraints = h-bonds +vdwtype = cutoff +vdw-modifier = force-switch +rlist = 1.0 +rvdw = 1.0 +rvdw-switch = 0.9 +rcoulomb = 1.1 +DispCorr = EnerPres +lincs-iter = 2 +fourierspacing = 0.25 +gen-vel = yes +; vmd md.gro md.trr +"""""" + rungmx = f"""""" +echo 0 | gmx editconf -f {self.baseName}_GMX.gro -bt octahedron -d 10 -c -princ +gmx grompp -f em.mdp -c out.gro -p {self.baseName}_GMX.top -o em.tpr -v +gmx mdrun -ntmpi 1 -v -deffnm em +gmx grompp -f md.mdp -c em.gro -p {self.baseName}_GMX.top -o md.tpr -r em.gro +gmx mdrun -ntmpi 1 -v -deffnm md +"""""" + emMdpFile = open(""em.mdp"", ""w"") + mdMdpFile = open(""md.mdp"", ""w"") + runGmxFile = open(""rungmx.sh"", ""w"") + emMdpFile.write(emMdp) + mdMdpFile.write(mdMdp) + runGmxFile.write(rungmx) + os.chmod(""rungmx.sh"", 0o744) + + def writeCnsTopolFiles(self): + """"""Write CNS topology files."""""" + + if self.amb2gmx: + os.chdir(self.absHomeDir) + + autoAngleFlag = True + autoDihFlag = True + cnsDir = os.path.abspath(""."") + + pdb = self.baseName + ""_NEW.pdb"" + par = self.baseName + ""_CNS.par"" + top = self.baseName + ""_CNS.top"" + inp = self.baseName + ""_CNS.inp"" + + pdbFileName = os.path.join(cnsDir, pdb) + parFileName = os.path.join(cnsDir, par) + topFileName = os.path.join(cnsDir, top) + inpFileName = os.path.join(cnsDir, inp) + + self.CnsTopFileName = topFileName + self.CnsInpFileName = inpFileName + self.CnsParFileName = parFileName + self.CnsPdbFileName = pdbFileName + + parFile = open(parFileName, ""w"") + topFile = open(topFileName, ""w"") + inpFile = open(inpFileName, ""w"") + + self.printMess(""Writing NEW PDB file\n"") + self.writePdb(pdbFileName) + + self.printMess(""Writing CNS/XPLOR files\n"") + + # print ""Writing CNS PAR file\n"" + parFile.write(""Remarks "" + head % (par, date)) + parFile.write(""\nset echo=false end\n"") + + parFile.write(""\n{ Bonds: atomType1 atomType2 kb r0 }\n"") + lineSet = [] + for bond in self.bonds: + a1Type = bond.atoms[0].atomType.atomTypeName + ""_"" + a2Type = bond.atoms[1].atomType.atomTypeName + ""_"" + kb = 1000.0 + if not self.allhdg: + kb = bond.kBond + r0 = bond.rEq + line = ""BOND %5s %5s %8.1f %8.4f\n"" % (a1Type, a2Type, kb, r0) + lineRev = ""BOND %5s %5s %8.1f %8.4f\n"" % (a2Type, a1Type, kb, r0) + if line not in lineSet: + if lineRev not in lineSet: + lineSet.append(line) + for item in lineSet: + parFile.write(item) + + parFile.write(""\n{ Angles: aType1 aType2 aType3 kt t0 }\n"") + lineSet = [] + for angle in self.angles: + a1 = angle.atoms[0].atomType.atomTypeName + ""_"" + a2 = angle.atoms[1].atomType.atomTypeName + ""_"" + a3 = angle.atoms[2].atomType.atomTypeName + ""_"" + kt = 500.0 + if not self.allhdg: + kt = angle.kTheta + t0 = angle.thetaEq * radPi + line = ""ANGLe %5s %5s %5s %8.1f %8.2f\n"" % (a1, a2, a3, kt, t0) + lineRev = ""ANGLe %5s %5s %5s %8.1f %8.2f\n"" % (a3, a2, a1, kt, t0) + if line not in lineSet: + if lineRev not in lineSet: + lineSet.append(line) + for item in lineSet: + parFile.write(item) + + parFile.write( + ""\n{ Proper Dihedrals: aType1 aType2 aType3 aType4 kt per\ +iod phase }\n"" + ) + lineSet = set() + for item in self.condensedProperDihedrals: + seq = """" + id_ = 0 + for dih in item: + # id_ = item.index(dih) + ll = len(item) + a1 = dih.atoms[0].atomType.atomTypeName + ""_"" + a2 = dih.atoms[1].atomType.atomTypeName + ""_"" + a3 = dih.atoms[2].atomType.atomTypeName + ""_"" + a4 = dih.atoms[3].atomType.atomTypeName + ""_"" + kp = 750.0 + if not self.allhdg: + kp = dih.kPhi + p = dih.period + ph = dih.phase * radPi + if ll > 1: + if id_ == 0: + line = ( + ""DIHEdral %5s %5s %5s %5s MULT %1i %7.3f %4i %8\ +.2f\n"" + % (a1, a2, a3, a4, ll, kp, p, ph) + ) + else: + line = ""%s %7.3f %4i %8.2f\n"" % (40 * "" "", kp, p, ph) + else: + line = ""DIHEdral %5s %5s %5s %5s %15.3f %4i %8.2f\n"" % (a1, a2, a3, a4, kp, p, ph) + seq += line + id_ += 1 + lineSet.add(seq) + for item in lineSet: + parFile.write(item) + + parFile.write( + ""\n{ Improper Dihedrals: aType1 aType2 aType3 aType4 kt p\ +eriod phase }\n"" + ) + lineSet = set() + for idh in self.improperDihedrals: + a1 = idh.atoms[0].atomType.atomTypeName + ""_"" + a2 = idh.atoms[1].atomType.atomTypeName + ""_"" + a3 = idh.atoms[2].atomType.atomTypeName + ""_"" + a4 = idh.atoms[3].atomType.atomTypeName + ""_"" + kp = 750.0 + if not self.allhdg: + kp = idh.kPhi + p = idh.period + ph = idh.phase * radPi + line = ""IMPRoper %5s %5s %5s %5s %13.1f %4i %8.2f\n"" % (a1, a2, a3, a4, kp, p, ph) + lineSet.add(line) + if self.chiral: + for idhc in self.chiralGroups: + _atc, neig, angle = idhc + a1 = neig[0].atomType.atomTypeName + ""_"" + a2 = neig[1].atomType.atomTypeName + ""_"" + a3 = neig[2].atomType.atomTypeName + ""_"" + a4 = neig[3].atomType.atomTypeName + ""_"" + kp = 11000.0 + p = 0 + ph = angle + line = ""IMPRoper %5s %5s %5s %5s %13.1f %4i %8.2f\n"" % (a1, a2, a3, a4, kp, p, ph) + lineSet.add(line) + + for item in lineSet: + parFile.write(item) + + parFile.write(""\n{ Nonbonded: Type Emin sigma; (1-4): Emin/2 sigma }\n"") + for at in self.atomTypes: + A = at.ACOEF + B = at.BCOEF + atName = at.atomTypeName + ""_"" + if B == 0.0: + sigma = epAmber = ep2 = sig2 = 0.0 + else: + epAmber = 0.25 * B * B / A + ep2 = epAmber / 2.0 + sigma = math.pow((A / B), (1.0 / 6)) + sig2 = sigma + line = ""NONBonded %5s %11.6f %11.6f %11.6f %11.6f\n"" % (atName, epAmber, sigma, ep2, sig2) + parFile.write(line) + parFile.write(""\nset echo=true end\n"") + + # print ""Writing CNS TOP file\n"" + topFile.write(""Remarks "" + head % (top, date)) + topFile.write(""\nset echo=false end\n"") + topFile.write(f""\nautogenerate angles={autoAngleFlag} dihedrals={autoDihFlag} end\n"") + topFile.write(""\n{ atomType mass }\n"") + + for at in self.atomTypes: + atType = at.atomTypeName + ""_"" + mass = at.mass + line = ""MASS %-5s %8.3f\n"" % (atType, mass) + topFile.write(line) + + topFile.write(""\nRESIdue %s\n"" % self.residueLabel[0]) + topFile.write(""\nGROUP\n"") + + topFile.write(""\n{ atomName atomType Charge }\n"") + + for at in self.atoms: + atName = at.atomName + atType = at.atomType.atomTypeName + ""_"" + charge = at.charge + line = ""ATOM %-5s TYPE= %-5s CHARGE= %8.4f END\n"" % (atName, atType, charge) + topFile.write(line) + + topFile.write(""\n{ Bonds: atomName1 atomName2 }\n"") + for bond in self.bonds: + a1Name = bond.atoms[0].atomName + a2Name = bond.atoms[1].atomName + line = ""BOND %-5s %-5s\n"" % (a1Name, a2Name) + topFile.write(line) + + if not autoAngleFlag or 1: # generating angles anyway + topFile.write(""\n{ Angles: atomName1 atomName2 atomName3}\n"") + for angle in self.angles: + a1Name = angle.atoms[0].atomName + a2Name = angle.atoms[1].atomName + a3Name = angle.atoms[2].atomName + line = ""ANGLe %-5s %-5s %-5s\n"" % (a1Name, a2Name, a3Name) + topFile.write(line) + + if not autoDihFlag or 1: # generating angles anyway + topFile.write(""\n{ Proper Dihedrals: name1 name2 name3 name4 }\n"") + for item in self.condensedProperDihedrals: + for dih in item: + a1Name = dih.atoms[0].atomName + a2Name = dih.atoms[1].atomName + a3Name = dih.atoms[2].atomName + a4Name = dih.atoms[3].atomName + line = ""DIHEdral %-5s %-5s %-5s %-5s\n"" % (a1Name, a2Name, a3Name, a4Name) + break + topFile.write(line) + + topFile.write(""\n{ Improper Dihedrals: aName1 aName2 aName3 aName4 }\n"") + for dih in self.improperDihedrals: + a1Name = dih.atoms[0].atomName + a2Name = dih.atoms[1].atomName + a3Name = dih.atoms[2].atomName + a4Name = dih.atoms[3].atomName + line = ""IMPRoper %-5s %-5s %-5s %-5s\n"" % (a1Name, a2Name, a3Name, a4Name) + topFile.write(line) + + if self.chiral: + for idhc in self.chiralGroups: + _atc, neig, angle = idhc + a1Name = neig[0].atomName + a2Name = neig[1].atomName + a3Name = neig[2].atomName + a4Name = neig[3].atomName + line = ""IMPRoper %-5s %-5s %-5s %-5s\n"" % (a1Name, a2Name, a3Name, a4Name) + topFile.write(line) + + topFile.write(""\nEND {RESIdue %s}\n"" % self.residueLabel[0]) + + topFile.write(""\nset echo=true end\n"") + + inpFile.write(""Remarks "" + head % (inp, date)) + inpData = """""" +topology + @%(CNS_top)s +end + +parameters + @%(CNS_par)s + nbonds + atom cdie shift eps=1.0 e14fac=0.4 tolerance=0.5 + cutnb=9.0 ctonnb=7.5 ctofnb=8.0 + nbxmod=5 vswitch wmin 1.0 + end + remark dielectric constant eps set to 1.0 +end + +flags exclude elec ? end + +segment name="" "" + chain + coordinates @%(NEW_pdb)s + end +end +coordinates @%(NEW_pdb)s +coord copy end + +! Remarks If you want to shake up the coordinates a bit ... + vector do (x=x+6*(rand()-0.5)) (all) + vector do (y=y+6*(rand()-0.5)) (all) + vector do (z=z+6*(rand()-0.5)) (all) + write coordinates output=%(CNS_ran)s end + +! Remarks RMS diff after randomisation and before minimisation +coord rms sele=(known and not hydrogen) end + +print threshold=0.02 bonds +print threshold=3.0 angles +print threshold=3.0 dihedrals +print threshold=3.0 impropers + +! Remarks Do Powell energy minimisation +minimise powell + nstep=250 drop=40.0 +end + +write coordinates output=%(CNS_min)s end +write structure output=%(CNS_psf)s end + +! constraints interaction (not hydro) (not hydro) end + +print threshold=0.02 bonds +print threshold=3.0 angles +print threshold=3.0 dihedrals +print threshold=3.0 impropers + +flags exclude * include vdw end energy end +distance from=(not hydro) to=(not hydro) cutoff=2.6 end + +! Remarks RMS fit after minimisation +coord fit sele=(known and not hydrogen) end + +stop +"""""" + dictInp = {} + dictInp[""CNS_top""] = top + dictInp[""CNS_par""] = par + dictInp[""NEW_pdb""] = pdb + dictInp[""CNS_min""] = self.baseName + ""_NEW_min.pdb"" + dictInp[""CNS_psf""] = self.baseName + ""_CNS.psf"" + dictInp[""CNS_ran""] = self.baseName + ""_rand.pdb"" + line = inpData % dictInp + inpFile.write(line) + if not self.amb2gmx: + self.printDebug(""chiralGroups %i"" % len(self.chiralGroups)) + else: + os.chdir(self.rootDir) + + +class ACTopol(AbstractTopol): + + """""" + Class to build the AC topologies (Antechamber AmberTools). + """""" + + def __init__( + self, + inputFile, + binaries=binaries, + chargeType=""bcc"", + chargeVal=None, + multiplicity=""1"", + atomType=""gaff2"", + force=False, + basename=None, + debug=False, + outTopol=""all"", + allhdg=False, + timeTol=MAXTIME, + qprog=""sqm"", + ekFlag=None, + verbose=True, + gmx4=False, + merge=False, + direct=False, + is_sorted=False, + chiral=False, + amb2gmx=False, + level=20, + ): + super().__init__() + self.binaries = binaries + self.amb2gmx = amb2gmx + self.debug = debug + self.verbose = verbose + self.gmx4 = gmx4 + self.merge = merge + self.direct = direct + self.sorted = is_sorted + self.chiral = chiral + + if not self.verbose: + level = 100 + if self.debug: + level = 10 + self.level = level or 20 + + self.acExe = find_bin(binaries[""ac_bin""]) + if not os.path.exists(self.acExe): + self.printError(f""no '{binaries['ac_bin']}' executable... aborting! "") + hint1 = ""HINT1: is 'AMBERHOME' environment variable set?"" + hint2 = ( + f""HINT2: is '{binaries['ac_bin']}' in your $PATH?"" + + f""\n What 'which {binaries['ac_bin']}' in your terminal says?"" + + ""\n 'alias' doesn't work for ACPYPE."" + ) + self.printMess(hint1) + self.printMess(hint2) + msg = ""Missing ANTECHAMBER"" + logger(self.level).error(msg) + raise Exception(msg) + self.inputFile = os.path.basename(inputFile) + self.rootDir = os.path.abspath(""."") + self.absInputFile = os.path.abspath(inputFile) + + if not os.path.exists(self.absInputFile) and not re.search(r""\.mol2$|\.mdl$|\.pdb$"", self.inputFile): + self.smiles = inputFile + if self.checkSmiles(): + self.is_smiles = True + if not basename: + self.inputFile = ""smiles_molecule.mol2"" + else: + self.inputFile = f""{basename}.mol2"" + self.absInputFile = os.path.abspath(self.inputFile) + else: + self.is_smiles = False + self.smiles = None + elif not os.path.exists(self.absInputFile): + msg = f""Input file {inputFile} DOES NOT EXIST"" + logger(self.level).error(msg) + raise Exception(msg) + baseOriginal, ext = os.path.splitext(self.inputFile) + base = basename or baseOriginal + self.baseOriginal = baseOriginal + self.ext = ext + self.baseName = base # name of the input file without ext. + self.obabelExe = find_bin(binaries[""obabel_bin""]) + if not os.path.exists(self.obabelExe): + if self.ext != "".mol2"" and self.ext != "".mdl"": + self.printError(f""no '{binaries['obabel_bin']}' executable; you need it if input is PDB or SMILES"") + self.printError(""otherwise use only MOL2 or MDL file as input ... aborting!"") + msg = ""Missing OBABEL"" + logger(self.level).error(msg) + raise Exception(msg) + else: + self.printWarn(f""no '{binaries['obabel_bin']}' executable, no PDB file can be used as input!"") + if self.is_smiles: + self.convertSmilesToMol2() + self.timeTol = timeTol + self.printDebug(""Max execution time tolerance is %s"" % elapsedTime(self.timeTol)) + # ekFlag e.g. (default used by sqm): + # acpype -i cccc -k ""qm_theory='AM1', grms_tol=0.0005, scfconv=1.d-10, ndiis_attempts=700, qmcharge=0"" + if ekFlag == '""None""' or ekFlag is None: + self.ekFlag = """" + else: + self.ekFlag = ""-ek %s"" % ekFlag + self.extOld = ext + self.homeDir = self.baseName + "".acpype"" + self.chargeType = chargeType + self.chargeVal = chargeVal + self.multiplicity = multiplicity + self.atomType = atomType + self.gaffDatfile = ""gaff.dat"" + leapGaffFile = ""leaprc.gaff"" + if ""2"" in self.atomType: + leapGaffFile = ""leaprc.gaff2"" + self.gaffDatfile = ""gaff2.dat"" + self.force = force + self.allhdg = allhdg + self.tleapExe = which(""tleap"") or """" + self.parmchkExe = which(""parmchk2"") or """" + acBase = base + ""_AC"" + self.acBaseName = acBase + self.acXyzFileName = acBase + "".inpcrd"" + self.acTopFileName = acBase + "".prmtop"" + self.acFrcmodFileName = acBase + "".frcmod"" + self.tmpDir = os.path.join(self.rootDir, "".acpype_tmp_%s"" % os.path.basename(base)) + self.setResNameCheckCoords() + self.guessCharge() + acMol2FileName = f""{base}_{chargeType}_{atomType}.mol2"" + self.acMol2FileName = acMol2FileName + self.charmmBase = ""%s_CHARMM"" % base + self.qFlag = qDict[qprog] + self.outTopols = [outTopol] + if outTopol == ""all"": + self.outTopols = outTopols + self.acParDict = { + ""base"": base, + ""ext"": ext[1:], + ""acBase"": acBase, + ""acMol2FileName"": acMol2FileName, + ""res"": self.resName, + ""leapAmberFile"": leapAmberFile, + ""baseOrg"": self.baseOriginal, + ""leapGaffFile"": leapGaffFile, + } + + +class MolTopol(AbstractTopol): + """""" + Class to write topologies and parameters files for several applications. + + https://ambermd.org/FileFormats.php + + Parser, take information in AC xyz and top files and convert to objects. + + Args: + acFileXyz + acFileTop + + Returns: + molTopol obj or None + """""" + + def __init__( + self, + acTopolObj=None, + acFileXyz=None, + acFileTop=None, + debug=False, + basename=None, + verbose=True, + gmx4=False, + merge=False, + direct=False, + is_sorted=False, + chiral=False, + amb2gmx=False, + level=20, + ): + super().__init__() + self.amb2gmx = amb2gmx + self.chiral = chiral + self.allhdg = False + self.debug = debug + self.level = level + self.gmx4 = gmx4 + self.merge = merge + self.direct = direct + self.sorted = is_sorted + self.verbose = verbose + self.inputFile = acFileTop + + if not self.verbose: + level = 100 + if self.debug: + level = 10 + self.level = level + + if acTopolObj: + if not acFileXyz: + acFileXyz = acTopolObj.acXyzFileName + if not acFileTop: + acFileTop = acTopolObj.acTopFileName + self._parent = acTopolObj + self.allhdg = self._parent.allhdg + self.debug = self._parent.debug + self.inputFile = self._parent.inputFile + elif not self.amb2gmx: + self.amb2gmx = True + if not os.path.exists(acFileXyz) or not os.path.exists(acFileTop): + self.printError(f""Files '{acFileXyz}' and/or '{acFileTop}' don't exist"") + self.printError(""molTopol object won't be created"") + + self.xyzFileData = open(acFileXyz).readlines() + self.topFileData = [x for x in open(acFileTop).readlines() if not x.startswith(""%COMMENT"")] + self.topo14Data = Topology_14() + self.topo14Data.read_amber_topology("""".join(self.topFileData)) + self.printDebug(""prmtop and inpcrd files loaded"") + + self.getResidueLabel() + if len(self.residueLabel) > 1: + self.baseName = basename or os.path.splitext(os.path.basename(acFileTop))[0] # 'solute' + else: + self.baseName = basename or self.residueLabel[0] # 3 caps letters + if acTopolObj: + self.baseName = basename or acTopolObj.baseName + self.printDebug(""basename defined = '%s'"" % self.baseName) + + self.getAtoms() + + self.getBonds() + + self.getAngles() + + self.getDihedrals() + + if self.amb2gmx: + self.rootDir = os.path.abspath(""."") + self.homeDir = f""{self.baseName}.amb2gmx"" + self.makeDir() + else: + self.getChirals() + + # Sort atoms for gromacs output. # JDC + if self.sorted: + self.printMess(""Sorting atoms for gromacs ordering.\n"") + self.sortAtomsForGromacs() +","Python" +"Computational Biochemistry","alanwilter/acpype","acpype/acs_api.py",".py","4815","176","import io +import json +import os +import shutil +import sys +import time +import traceback + +from acpype.params import MAXTIME +from acpype.topol import ACTopol, header +from acpype.utils import elapsedTime, while_replace + +em_mdp = io.StringIO() +AC_frcmod = io.StringIO() +AC_inpcrd = io.StringIO() +AC_lib = io.StringIO() +AC_prmtop = io.StringIO() +mol2 = io.StringIO() +CHARMM_inp = io.StringIO() +CHARMM_prm = io.StringIO() +CHARMM_rtf = io.StringIO() +CNS_inp = io.StringIO() +CNS_par = io.StringIO() +CNS_top = io.StringIO() +GMX_OPLS_itp = io.StringIO() +GMX_OPLS_top = io.StringIO() +GMX_gro = io.StringIO() +GMX_itp = io.StringIO() +GMX_top = io.StringIO() +NEW_pdb = io.StringIO() +md_mdp = io.StringIO() + +filesInMemory = [ + (em_mdp, ""em.mdp""), + (AC_frcmod, ""_AC.frcmod""), + (AC_inpcrd, ""_AC.inpcrd""), + (AC_lib, ""_AC.lib""), + (AC_prmtop, ""_AC.prmtop""), + (mol2, "".mol2""), + (CHARMM_inp, ""_CHARMM.inp""), + (CHARMM_prm, ""_CHARMM.prm""), + (CHARMM_rtf, ""_CHARMM.rtf""), + (CNS_inp, ""_CNS.inp""), + (CNS_par, ""_CNS.par""), + (CNS_top, ""_CNS.top""), + (GMX_OPLS_itp, ""_GMX_OPLS.itp""), + (GMX_OPLS_top, ""_GMX_OPLS.top""), + (GMX_gro, ""_GMX.gro""), + (GMX_itp, ""_GMX.itp""), + (GMX_top, ""_GMX.top""), + (NEW_pdb, ""_NEW.pdb""), + (md_mdp, ""md.mdp""), +] + + +def clearFileInMemory(): + for files in filesInMemory: + files[0].seek(0) + files[0].truncate(0) + + +def readFiles(basename, chargeType, atomType): + for files in filesInMemory: + if files[1] == ""em.mdp"" or files[1] == ""md.mdp"": + filename = files[1] + elif files[1] == "".mol2"": + filename = basename + ""_"" + chargeType + ""_"" + atomType + files[1] + else: + filename = basename + files[1] + readfile = tuple(open(filename)) + for line in readfile: + files[0].write(line) + + +def acpype_api( + inputFile, + chargeType=""bcc"", + chargeVal=None, + multiplicity=""1"", + atomType=""gaff2"", + force=False, + basename=None, + debug=False, + outTopol=""all"", + engine=""tleap"", + allhdg=False, + timeTol=MAXTIME, + qprog=""sqm"", + ekFlag=None, + verbose=True, + gmx4=False, + merge=False, + direct=False, + is_sorted=False, + chiral=False, + is_smiles=False, +): + output = {} + at0 = time.time() + print(header) + + if debug: + texta = ""Python Version %s"" % sys.version + print(""DEBUG: %s"" % while_replace(texta)) + try: + molecule = ACTopol( + inputFile=inputFile, + chargeType=chargeType, + chargeVal=chargeVal, + debug=debug, + multiplicity=multiplicity, + atomType=atomType, + force=force, + outTopol=outTopol, + allhdg=allhdg, + basename=basename, + timeTol=timeTol, + qprog=qprog, + ekFlag=ekFlag, + verbose=verbose, + gmx4=gmx4, + merge=merge, + direct=direct, + is_sorted=is_sorted, + chiral=chiral, + ) + + molecule.createACTopol() + molecule.createMolTopol() + + ""Output in JSON format"" + os.chdir(molecule.absHomeDir) + readFiles(molecule.baseName, chargeType, atomType) + output = { + ""file_name"": molecule.baseName, + ""em_mdp"": em_mdp.getvalue(), + ""AC_frcmod"": AC_frcmod.getvalue(), + ""AC_inpcrd"": AC_inpcrd.getvalue(), + ""AC_lib"": AC_lib.getvalue(), + ""AC_prmtop"": AC_prmtop.getvalue(), + ""mol2"": mol2.getvalue(), + ""CHARMM_inp"": CHARMM_inp.getvalue(), + ""CHARMM_prm"": CHARMM_prm.getvalue(), + ""CHARMM_rtf"": CHARMM_rtf.getvalue(), + ""CNS_inp"": CNS_inp.getvalue(), + ""CNS_par"": CNS_par.getvalue(), + ""CNS_top"": CNS_top.getvalue(), + ""GMX_OPLS_itp"": GMX_OPLS_itp.getvalue(), + ""GMX_OPLS_top"": GMX_OPLS_top.getvalue(), + ""GMX_gro"": GMX_gro.getvalue(), + ""GMX_itp"": GMX_itp.getvalue(), + ""GMX_top"": GMX_top.getvalue(), + ""NEW_pdb"": NEW_pdb.getvalue(), + ""md_mdp"": md_mdp.getvalue(), + } + + except Exception: + _exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() + print(""ACPYPE FAILED: %s"" % exceptionValue) + if debug: + traceback.print_tb(exceptionTraceback, file=sys.stdout) + output = {""file_name"": f""ERROR: {exceptionValue!s}""} + + execTime = int(round(time.time() - at0)) + if execTime == 0: + amsg = ""less than a second"" + else: + amsg = elapsedTime(execTime) + print(""Total time of execution: %s"" % amsg) + clearFileInMemory() + try: + shutil.rmtree(molecule.absHomeDir) + except Exception: + print(""DEBUG: No folder left to be removed"") + return json.dumps(output) +","Python" +"Computational Biochemistry","alanwilter/acpype","acpype/logger.py",".py","2253","73","import logging +import os +import sys +from shutil import move +from tempfile import NamedTemporaryFile + +tmpLogFile = NamedTemporaryFile().name + + +class LogFormatter(logging.Formatter): + + """""" + Define log formatter + """""" + + err_fmt = ""ERROR: %(msg)s"" + warn_fmt = ""WARNING: %(msg)s"" + dbg_fmt = ""DEBUG: %(msg)s"" + info_fmt = ""%(msg)s"" + + def __init__(self): + super().__init__(fmt=""%(levelno)d: %(msg)s"", datefmt=None, style=""%"") + + def format(self, record): + # Save the original format configured by the user + # when the logger formatter was instantiated + format_orig = self._style._fmt + + # Replace the original format with one customized by logging level + if record.levelno == logging.DEBUG: + self._style._fmt = LogFormatter.dbg_fmt + elif record.levelno == logging.INFO: + self._style._fmt = LogFormatter.info_fmt + elif record.levelno == logging.ERROR: + self._style._fmt = LogFormatter.err_fmt + elif record.levelno == logging.WARNING: + self._style._fmt = LogFormatter.warn_fmt + # Call the original formatter class to do the grunt work + result = logging.Formatter.format(self, record) + # Restore the original format configured by the user + self._style._fmt = format_orig + return result + + +def copy_log(molecule): + if not os.path.exists(molecule.absHomeDir): + raise UnboundLocalError + local_log = os.path.join(molecule.absHomeDir, ""acpype.log"") + if os.path.exists(local_log): + os.remove(local_log) + if os.path.exists(tmpLogFile): + move(tmpLogFile, local_log) + + +def set_logging_conf(level=20): + # Setting logging configurations + logging.root.setLevel(0) + logger = logging.getLogger(__name__) + if logger.handlers: + logger.handlers.pop() + + fmt = LogFormatter() + file_handler = logging.FileHandler(filename=tmpLogFile) + stdout_handler = logging.StreamHandler(sys.stdout) + file_handler.setLevel(logging.DEBUG) + stdout_handler.setLevel(level) + stdout_handler.setFormatter(fmt) + file_handler.setFormatter(fmt) + if not logger.handlers: + logger.addHandler(file_handler) + logger.addHandler(stdout_handler) + return logger +","Python" +"Computational Biochemistry","alanwilter/acpype","acpype/params.py",".py","22671","1034","binaries = {""ac_bin"": ""antechamber"", ""obabel_bin"": ""obabel""} + +MAXTIME = 3 * 3600 +cal = 4.184 +Pi = 3.141593 +qConv = 18.2223 +radPi = 57.295780 # 180/Pi +maxDist = 3.0 +minDist = 0.5 +maxDist2 = maxDist**2 # squared Ang. +minDist2 = minDist**2 # squared Ang. +diffTol = 0.01 + +# List of Topology Formats created by acpype so far: +outTopols = [""gmx"", ""cns"", ""charmm""] +qDict = {""mopac"": 0, ""divcon"": 1, ""sqm"": 2} + +# Residues that are not solute, to be avoided when balancing charges in +# amb2gmx mode +ionOrSolResNameList = [""Cl-"", ""Na+"", ""K+"", ""CIO"", ""Cs+"", ""IB"", ""Li+"", ""MG2"", ""Rb+"", ""WAT"", ""MOH"", ""NMA""] + +specialGaffAtoms = [""CU"", ""BR"", ""CL""] + +# leapAmberFile = 'leaprc.ff99SB' # 'leaprc.ff10' and 'leaprc.ff99bsc0' has extra Atom Types not in parm99.dat +leapAmberFile = ""leaprc.protein.ff14SB"" # 'leaprc.ff14SB' + +# ""qm_theory='AM1', grms_tol=0.0002, maxcyc=999, tight_p_conv=1, scfconv=1.d-10,"" +# ""AM1 ANALYT MMOK GEO-OK PRECISE"" + +usage = """""" + acpype -i _file_ | _SMILES_string_ [-c _string_] [-n _int_] [-m _int_] [-a _string_] [-f] etc. or + acpype -p _prmtop_ -x _inpcrd_ [-d | -w]"""""" + +epilog = """""" + + output: assuming 'root' is the basename of either the top input file, + the 3-letter residue name or user defined (-b option) + root_bcc_gaff.mol2: final mol2 file with 'bcc' charges and 'gaff' atom type + root_AC.inpcrd : coord file for AMBER + root_AC.prmtop : topology and parameter file for AMBER + root_AC.lib : residue library file for AMBER + root_AC.frcmod : modified force field parameters + root_GMX.gro : coord file for GROMACS + root_GMX.top : topology file for GROMACS + root_GMX.itp : molecule unit topology and parameter file for GROMACS + root_GMX_OPLS.itp : OPLS/AA mol unit topol & par file for GROMACS (experimental!) + em.mdp, md.mdp : run parameters file for GROMACS + root_NEW.pdb : final pdb file generated by ACPYPE + root_CNS.top : topology file for CNS/XPLOR + root_CNS.par : parameter file for CNS/XPLOR + root_CNS.inp : run parameters file for CNS/XPLOR + root_CHARMM.rtf : topology file for CHARMM + root_CHARMM.prm : parameter file for CHARMM + root_CHARMM.inp : run parameters file for CHARMM"""""" + +TLEAP_TEMPLATE = """""" +verbosity 1 +source %(leapAmberFile)s +source %(leapGaffFile)s +mods = loadamberparams %(acBase)s.frcmod +%(res)s = loadmol2 %(acMol2FileName)s +check %(res)s +saveamberparm %(res)s %(acBase)s.prmtop %(acBase)s.inpcrd +saveoff %(res)s %(acBase)s.lib +quit +"""""" + +dictAmbAtomType2AmbGmxCode = { + ""BR"": ""1"", + ""C"": ""2"", + ""CA"": ""3"", + ""CB"": ""4"", + ""CC"": ""5"", + ""CK"": ""6"", + ""CM"": ""7"", + ""CN"": ""8"", + ""CQ"": ""9"", + ""CR"": ""10"", + ""CT"": ""11"", + ""CV"": ""12"", + ""CW"": ""13"", + ""C*"": ""14"", + ""Ca"": ""15"", + ""F"": ""16"", + ""H"": ""17"", + ""HC"": ""18"", + ""H1"": ""19"", + ""H2"": ""20"", + ""H3"": ""21"", + ""HA"": ""22"", + ""H4"": ""23"", + ""H5"": ""24"", + ""HO"": ""25"", + ""HS"": ""26"", + ""HW"": ""27"", + ""HP"": ""28"", + ""I"": ""29"", + ""Cl"": ""30"", + ""Na"": ""31"", + ""IB"": ""32"", + ""Mg"": ""33"", + ""N"": ""34"", + ""NA"": ""35"", + ""NB"": ""36"", + ""NC"": ""37"", + ""N2"": ""38"", + ""N3"": ""39"", + ""N*"": ""40"", + ""O"": ""41"", + ""OW"": ""42"", + ""OH"": ""43"", + ""OS"": ""44"", + ""O2"": ""45"", + ""P"": ""46"", + ""S"": ""47"", + ""SH"": ""48"", + ""CU"": ""49"", + ""FE"": ""50"", + ""K"": ""51"", + ""Rb"": ""52"", + ""Cs"": ""53"", + ""Li"": ""56"", + ""Zn"": ""57"", + ""Sr"": ""58"", + ""Ba"": ""59"", + ""MCH3A"": ""MCH3A"", + ""MCH3B"": ""MCH3B"", + ""MNH2"": ""MNH2"", + ""MNH3"": ""MNH3"", + ""MW"": ""MW"", +} + +dictOplsAtomType2OplsGmxCode = { + ""Ac3+"": [""697""], + ""Am3+"": [""699""], + ""Ar"": [""Ar"", ""097""], + ""Ba2+"": [""414""], + ""Br"": [""722"", ""730""], + ""Br-"": [""402""], + ""CT"": [ + ""064"", + ""076"", + ""122"", + ""135"", + ""136"", + ""137"", + ""138"", + ""139"", + ""148"", + ""149"", + ""152"", + ""157"", + ""158"", + ""159"", + ""161"", + ""173"", + ""174"", + ""175"", + ""181"", + ""182"", + ""183"", + ""184"", + ""206"", + ""207"", + ""208"", + ""209"", + ""210"", + ""211"", + ""212"", + ""213"", + ""214"", + ""215"", + ""216"", + ""217"", + ""218"", + ""219"", + ""220"", + ""223"", + ""224"", + ""225"", + ""229"", + ""230"", + ""242"", + ""243"", + ""244"", + ""256"", + ""257"", + ""258"", + ""259"", + ""273"", + ""274"", + ""275"", + ""276"", + ""291"", + ""292"", + ""293"", + ""294"", + ""297"", + ""305"", + ""306"", + ""307"", + ""308"", + ""331"", + ""371"", + ""373"", + ""375"", + ""391"", + ""396"", + ""421"", + ""431"", + ""443"", + ""448"", + ""453"", + ""455"", + ""458"", + ""461"", + ""468"", + ""476"", + ""482"", + ""484"", + ""486"", + ""490"", + ""491"", + ""492"", + ""498"", + ""499"", + ""505"", + ""515"", + ""516"", + ""645"", + ""670"", + ""671"", + ""672"", + ""673"", + ""674"", + ""675"", + ""676"", + ""677"", + ""678"", + ""679"", + ""680"", + ""681"", + ""701"", + ""725"", + ""747"", + ""748"", + ""755"", + ""756"", + ""757"", + ""758"", + ""762"", + ""764"", + ""765"", + ""766"", + ""774"", + ""775"", + ""776"", + ""782"", + ""783"", + ""903"", + ""904"", + ""905"", + ""906"", + ""907"", + ""908"", + ""912"", + ""913"", + ""914"", + ""915"", + ""942"", + ""943"", + ""944"", + ""945"", + ""951"", + ""957"", + ""959"", + ""960"", + ""961"", + ""962"", + ""963"", + ""964"", + ], + ""CA"": [ + ""053"", + ""145"", + ""147"", + ""166"", + ""199"", + ""221"", + ""228"", + ""260"", + ""263"", + ""266"", + ""302"", + ""312"", + ""315"", + ""317"", + ""336"", + ""351"", + ""362"", + ""380"", + ""457"", + ""460"", + ""463"", + ""472"", + ""488"", + ""521"", + ""522"", + ""523"", + ""528"", + ""532"", + ""533"", + ""538"", + ""539"", + ""551"", + ""582"", + ""590"", + ""591"", + ""592"", + ""593"", + ""604"", + ""605"", + ""606"", + ""607"", + ""608"", + ""609"", + ""610"", + ""611"", + ""612"", + ""625"", + ""644"", + ""647"", + ""648"", + ""649"", + ""650"", + ""651"", + ""652"", + ""714"", + ""716"", + ""718"", + ""720"", + ""724"", + ""727"", + ""729"", + ""731"", + ""735"", + ""736"", + ""737"", + ""738"", + ""739"", + ""742"", + ""752"", + ""768"", + ""916"", + ""917"", + ""918"", + ], + ""C3"": [ + ""007"", + ""010"", + ""036"", + ""039"", + ""063"", + ""065"", + ""067"", + ""068"", + ""069"", + ""070"", + ""080"", + ""088"", + ""090"", + ""092"", + ""096"", + ""106"", + ""107"", + ""109"", + ""126"", + ""132"", + ""415"", + ""418"", + ""425"", + ""429"", + ], + ""C"": [ + ""001"", + ""017"", + ""026"", + ""058"", + ""095"", + ""131"", + ""231"", + ""234"", + ""235"", + ""247"", + ""252"", + ""267"", + ""320"", + ""322"", + ""334"", + ""366"", + ""378"", + ""470"", + ""471"", + ""772"", + ""952"", + ], + ""C2"": [ + ""005"", + ""009"", + ""015"", + ""016"", + ""019"", + ""022"", + ""027"", + ""028"", + ""031"", + ""034"", + ""037"", + ""056"", + ""057"", + ""061"", + ""071"", + ""081"", + ""089"", + ""091"", + ""093"", + ""110"", + ], + ""CT_2"": [""223B"", ""224B"", ""225B"", ""246"", ""283"", ""284"", ""285"", ""292B"", ""293B"", ""295"", ""298"", ""299"", ""906B"", ""912B""], + ""CM"": [""141"", ""142"", ""143"", ""227"", ""323"", ""324"", ""337"", ""338"", ""381"", ""382"", ""517"", ""518"", ""708""], + ""CW"": [""508"", ""514"", ""543"", ""552"", ""561"", ""567"", ""575"", ""583"", ""588"", ""637""], + ""CB"": [""050"", ""349"", ""350"", ""364"", ""365"", ""501"", ""595"", ""623"", ""624""], + ""CH"": [""006"", ""008"", ""014"", ""025"", ""029"", ""030"", ""060"", ""073""], + ""CZ"": [""261"", ""423"", ""754"", ""925"", ""927"", ""928"", ""929"", ""931""], + ""CO"": [""189"", ""191"", ""193"", ""195"", ""197"", ""198""], + ""C_2"": [""232"", ""233"", ""277"", ""280"", ""465""], + ""CR"": [""506"", ""509"", ""558"", ""572"", ""634""], + ""CQ"": [""347"", ""531"", ""621"", ""642""], + ""CV"": [""507"", ""560"", ""574"", ""636""], + ""CY"": [""711"", ""712"", ""713"", ""733""], + ""CS"": [""544"", ""568"", ""589""], + ""CK"": [""353"", ""627""], + ""CN"": [""502"", ""594""], + ""CP"": [""043"", ""048""], + ""CU"": [""550"", ""581""], + ""CT_3"": [""245"", ""296""], + ""C="": [""150"", ""178""], + ""CD"": [""011"", ""075""], + ""C4"": [""066""], + ""C7"": [""077""], + ""C8"": [""074""], + ""C9"": [""072""], + ""CX"": [""510""], + ""C!"": [""145B""], + ""C*"": [""500""], + ""C+"": [""700""], + ""C_3"": [""271""], + ""CC"": [""045""], + ""CF"": [""044""], + ""CG"": [""049""], + ""CT_4"": [""160""], + ""Ca2+"": [""412""], + ""Cl"": [""123"", ""151"", ""226"", ""264""], + ""Cl-"": [""401"", ""709""], + ""Cs+"": [""410""], + ""Cu2+"": [""Cu2+""], + ""Eu3+"": [""705""], + ""F"": [""164"", ""719"", ""721"", ""726"", ""728"", ""786"", ""956"", ""965""], + ""F-"": [""400""], + ""Fe2+"": [""Fe2+""], + ""Gd3+"": [""706""], + ""HA"": [ + ""146"", + ""316"", + ""318"", + ""389"", + ""524"", + ""525"", + ""526"", + ""529"", + ""534"", + ""535"", + ""536"", + ""540"", + ""541"", + ""546"", + ""547"", + ""554"", + ""555"", + ""556"", + ""563"", + ""564"", + ""565"", + ""569"", + ""570"", + ""576"", + ""577"", + ""578"", + ""584"", + ""585"", + ""586"", + ""597"", + ""598"", + ""599"", + ""600"", + ""601"", + ""602"", + ""613"", + ""614"", + ""615"", + ""616"", + ""617"", + ""618"", + ""619"", + ""629"", + ""630"", + ""631"", + ""638"", + ""639"", + ""640"", + ""643"", + ""653"", + ""654"", + ""655"", + ""656"", + ""715"", + ""717"", + ""740"", + ""741"", + ""746"", + ], + ""HC"": [ + ""140"", + ""144"", + ""153"", + ""156"", + ""165"", + ""176"", + ""185"", + ""190"", + ""192"", + ""194"", + ""196"", + ""255"", + ""279"", + ""282"", + ""329"", + ""330"", + ""332"", + ""344"", + ""372"", + ""374"", + ""376"", + ""392"", + ""416"", + ""419"", + ""422"", + ""426"", + ""430"", + ""432"", + ""444"", + ""449"", + ""454"", + ""456"", + ""459"", + ""462"", + ""469"", + ""477"", + ""483"", + ""485"", + ""487"", + ""702"", + ""710"", + ""759"", + ""763"", + ""777"", + ""778"", + ""779"", + ""784"", + ""911"", + ""926"", + ""930"", + ""950"", + ""958"", + ], + ""H"": [ + ""004"", + ""013"", + ""041"", + ""047"", + ""128"", + ""240"", + ""241"", + ""250"", + ""254"", + ""314"", + ""325"", + ""327"", + ""339"", + ""342"", + ""343"", + ""357"", + ""358"", + ""360"", + ""367"", + ""369"", + ""383"", + ""385"", + ""387"", + ""388"", + ""428"", + ""479"", + ""481"", + ""504"", + ""513"", + ""545"", + ""553"", + ""562"", + ""596"", + ""632"", + ""744"", + ""745"", + ""909"", + ""910"", + ], + ""H3"": [""021"", ""052"", ""055"", ""104"", ""105"", ""289"", ""290"", ""301"", ""304"", ""310"", ""941"", ""955""], + ""HO"": [""024"", ""079"", ""155"", ""163"", ""168"", ""170"", ""172"", ""188"", ""270"", ""435""], + ""HS"": [""033"", ""086"", ""087"", ""204"", ""205""], + ""HW"": [""112"", ""114"", ""117"", ""119"", ""796""], + ""H4"": [""345"", ""390""], + ""H5"": [""355"", ""359""], + ""He"": [""130""], + ""I"": [""732""], + ""I-"": [""403""], + ""K+"": [""408""], + ""Kr"": [""098""], + ""LP"": [""433"", ""797""], + ""La3+"": [""703""], + ""Li+"": [""404"", ""406""], + ""MCH3A"": [""MCH3A""], + ""MCH3B"": [""MCH3B""], + ""MNH2"": [""MNH2""], + ""MNH3"": [""MNH3""], + ""MW"": [""MW"", ""115""], + ""Mg2+"": [""411""], + ""NA"": [ + ""040"", + ""046"", + ""319"", + ""321"", + ""333"", + ""354"", + ""361"", + ""377"", + ""379"", + ""503"", + ""512"", + ""542"", + ""548"", + ""557"", + ""587"", + ""628"", + ], + ""NC"": [""311"", ""335"", ""346"", ""348"", ""363"", ""520"", ""527"", ""530"", ""537"", ""603"", ""620"", ""622"", ""641"", ""646""], + ""N"": [""003"", ""012"", ""094"", ""237"", ""238"", ""239"", ""249"", ""251"", ""265"", ""478"", ""480"", ""787""], + ""N3"": [""020"", ""101"", ""102"", ""103"", ""286"", ""287"", ""288"", ""309"", ""427"", ""940"", ""953""], + ""N2"": [""051"", ""054"", ""300"", ""303"", ""313"", ""341"", ""356"", ""368"", ""386"", ""743""], + ""NB"": [""042"", ""352"", ""511"", ""549"", ""559"", ""573"", ""580"", ""626"", ""635""], + ""N*"": [""319B"", ""333B"", ""354B"", ""377B""], + ""NT"": [""127"", ""900"", ""901"", ""902""], + ""NZ"": [""262"", ""424"", ""750"", ""753""], + ""NO"": [""760"", ""767""], + ""NY"": [""749"", ""751""], + ""Na+"": [""405"", ""407""], + ""Nd3+"": [""704""], + ""Ne"": [""129""], + ""OS"": [""062"", ""108"", ""179"", ""180"", ""186"", ""395"", ""442"", ""447"", ""452"", ""467"", ""473"", ""566"", ""571"", ""579"", ""773""], + ""O"": [""002"", ""059"", ""236"", ""248"", ""253"", ""326"", ""328"", ""340"", ""370"", ""384"", ""771"", ""788""], + ""OH"": [""023"", ""078"", ""154"", ""162"", ""167"", ""169"", ""171"", ""187"", ""268"", ""420"", ""434""], + ""O2"": [""018"", ""125"", ""272"", ""394"", ""441"", ""446"", ""451"", ""954""], + ""OW"": [""111"", ""113"", ""116"", ""118"", ""795""], + ""O_2"": [""278"", ""281"", ""466""], + ""OY"": [""475"", ""494"", ""497""], + ""OL"": [""120""], + ""ON"": [""761""], + ""OU"": [""437""], + ""O_3"": [""269""], + ""P"": [""393"", ""440"", ""445"", ""450"", ""785""], + ""P+"": [""781""], + ""Rb+"": [""409""], + ""S"": [""035"", ""038"", ""084"", ""085"", ""124"", ""202"", ""203"", ""222"", ""633""], + ""SH"": [""032"", ""082"", ""083"", ""200"", ""201"", ""417"", ""734""], + ""SI"": [""SI""], + ""SY"": [""474""], + ""SY2"": [""493""], + ""SZ"": [""496""], + ""Sr2+"": [""413""], + ""Th4+"": [""698""], + ""U"": [""436""], + ""Xe"": [""099""], + ""Yb3+"": [""707""], + ""Zn2+"": [""Zn2+""], +} + +# reverse dictOplsAtomType2OplsGmxCode +oplsCode2AtomTypeDict = {} +for k, vv in list(dictOplsAtomType2OplsGmxCode.items()): + for code in vv: + oplsCode2AtomTypeDict[code] = k + +# Cross dictAmbAtomType2AmbGmxCode with dictOplsAtomType2OplsGmxCode & add H1,HP,H2 +dictAtomTypeAmb2OplsGmxCode = {""H1"": [""140"", ""1.00800""], ""HP"": [""140"", ""1.00800""], ""H2"": [""140"", ""1.00800""]} +dictOplsMass = { + ""SY2"": [""32.06000""], + ""Zn2+"": [""65.37000""], + ""CQ"": [""12.01100""], + ""CP"": [""12.01100""], + ""Nd3+"": [""144.24000""], + ""Br-"": [""79.90400""], + ""Cu2+"": [""63.54600""], + ""Br"": [""79.90400""], + ""H"": [""1.00800""], + ""P"": [""30.97376""], + ""Sr2+"": [""87.62000""], + ""ON"": [""15.99940""], + ""OL"": [""0.00000""], + ""OH"": [""15.99940""], + ""OY"": [""15.99940""], + ""OW"": [""15.99940""], + ""OU"": [""15.99940""], + ""OS"": [""15.99940""], + ""Am3+"": [""243.06000""], + ""HS"": [""1.00800""], + ""HW"": [""1.00800""], + ""HO"": [""1.00800""], + ""HC"": [""1.00800""], + ""HA"": [""1.00800""], + ""O2"": [""15.99940""], + ""Ca2+"": [""40.08000""], + ""Th4+"": [""232.04000""], + ""He"": [""4.00260""], + ""C"": [""12.01100""], + ""Cs+"": [""132.90540""], + ""O"": [""15.99940""], + ""Gd3+"": [""157.25000""], + ""S"": [""32.06000""], + ""P+"": [""30.97376""], + ""La3+"": [""138.91000""], + ""H3"": [""1.00800""], + ""H4"": [""1.00800""], + ""MNH2"": [""0.00000""], + ""MW"": [""0.00000""], + ""NB"": [""14.00670""], + ""K+"": [""39.09830""], + ""Ne"": [""20.17970""], + ""Rb+"": [""85.46780""], + ""C+"": [""12.01100""], + ""C*"": [""12.01100""], + ""NO"": [""14.00670""], + ""CT_4"": [""12.01100""], + ""NA"": [""14.00670""], + ""C!"": [""12.01100""], + ""NC"": [""14.00670""], + ""NZ"": [""14.00670""], + ""CT_2"": [""12.01100""], + ""CT_3"": [""12.01100""], + ""NY"": [""14.00670""], + ""C9"": [""14.02700""], + ""C8"": [""13.01900""], + ""C="": [""12.01100""], + ""Yb3+"": [""173.04000""], + ""C3"": [""15.03500"", ""12.01100""], + ""C2"": [""14.02700""], + ""C7"": [""12.01100""], + ""C4"": [""16.04300""], + ""CK"": [""12.01100""], + ""Cl-"": [""35.45300""], + ""N*"": [""14.00670""], + ""CH"": [""13.01900""], + ""CO"": [""12.01100""], + ""CN"": [""12.01100""], + ""CM"": [""12.01100""], + ""F"": [""18.99840""], + ""CC"": [""12.01100""], + ""CB"": [""12.01100""], + ""CA"": [""12.01100""], + ""CG"": [""12.01100""], + ""CF"": [""12.01100""], + ""N"": [""14.00670""], + ""CZ"": [""12.01100""], + ""CY"": [""12.01100""], + ""CX"": [""12.01100""], + ""Ac3+"": [""227.03000""], + ""CS"": [""12.01100""], + ""CR"": [""12.01100""], + ""N2"": [""14.00670""], + ""N3"": [""14.00670""], + ""CW"": [""12.01100""], + ""CV"": [""12.01100""], + ""CU"": [""12.01100""], + ""CT"": [""12.01100""], + ""SZ"": [""32.06000""], + ""SY"": [""32.06000""], + ""Cl"": [""35.45300""], + ""NT"": [""14.00670""], + ""O_2"": [""15.99940""], + ""Xe"": [""131.29300""], + ""SI"": [""28.08000""], + ""SH"": [""32.06000""], + ""Eu3+"": [""151.96000""], + ""F-"": [""18.99840""], + ""MNH3"": [""0.00000""], + ""H5"": [""1.00800""], + ""C_3"": [""12.01100""], + ""C_2"": [""12.01100""], + ""I-"": [""126.90450""], + ""LP"": [""0.00000""], + ""I"": [""126.90450""], + ""Na+"": [""22.98977""], + ""Li+"": [""6.94100""], + ""U"": [""0.00000""], + ""MCH3A"": [""0.00000""], + ""MCH3B"": [""0.00000""], + ""CD"": [""13.01900"", ""12.01100""], + ""O_3"": [""15.99940""], + ""Kr"": [""83.79800""], + ""Fe2+"": [""55.84700""], + ""Ar"": [""39.94800""], + ""Mg2+"": [""24.30500""], + ""Ba2+"": [""137.33000""], +} +for ambKey in dictAmbAtomType2AmbGmxCode: + if ambKey in dictOplsAtomType2OplsGmxCode: + dictAtomTypeAmb2OplsGmxCode[ambKey] = dictOplsAtomType2OplsGmxCode[ambKey] + list(dictOplsMass[ambKey]) + +# learnt from 22 residues test. +dictAtomTypeAmb2OplsGmxCode = { + ""HS"": [""204"", ""1.008""], + ""HP"": [""140"", ""1.008""], + ""HO"": [""155"", ""168"", ""1.008""], + ""HC"": [""140"", ""1.008""], + ""HA"": [""146"", ""1.008""], + ""O2"": [""272"", ""15.9994""], + ""C*"": [""500"", ""12.011""], + ""NA"": [""503"", ""512"", ""14.0067""], + ""NB"": [""511"", ""14.0067""], + ""CB"": [""501"", ""12.011""], + ""C"": [""235"", ""271"", ""12.011""], + ""CN"": [""502"", ""12.011""], + ""CM"": [""302"", ""12.011""], + ""CC"": [""507"", ""508"", ""510"", ""12.011""], + ""H"": [""240"", ""241"", ""290"", ""301"", ""304"", ""310"", ""504"", ""513"", ""1.008""], + ""CA"": [""145"", ""166"", ""12.011""], + ""O"": [""236"", ""15.9994""], + ""N"": [""237"", ""238"", ""239"", ""14.0067""], + ""S"": [""202"", ""32.06""], + ""CR"": [""506"", ""509"", ""12.011""], + ""N2"": [""300"", ""303"", ""14.0067""], + ""N3"": [""287"", ""309"", ""14.0067""], + ""CW"": [""508"", ""510"", ""514"", ""12.011""], + ""CV"": [""507"", ""12.011""], + ""CT"": [ + ""135"", + ""136"", + ""137"", + ""149"", + ""157"", + ""158"", + ""206"", + ""209"", + ""210"", + ""223B"", + ""224B"", + ""245"", + ""246"", + ""274"", + ""283"", + ""284"", + ""285"", + ""292"", + ""292B"", + ""293B"", + ""296"", + ""307"", + ""308"", + ""505"", + ""12.011"", + ], + ""OH"": [""154"", ""167"", ""15.9994""], + ""H1"": [""140"", ""1.008""], + ""H4"": [""146"", ""1.008""], + ""H5"": [""146"", ""1.008""], + ""SH"": [""200"", ""32.06""], +} + +# learnt from 22 residues test. +dictAtomTypeGaff2OplsGmxCode = { + ""cc"": [""500"", ""506"", ""507"", ""508"", ""514"", ""12.011""], + ""ca"": [""145"", ""166"", ""501"", ""502"", ""12.011""], + ""h1"": [""140"", ""1.008""], + ""h4"": [""146"", ""1.008""], + ""h5"": [""146"", ""1.008""], + ""cz"": [""302"", ""12.011""], + ""c2"": [""509"", ""510"", ""12.011""], + ""nh"": [""300"", ""303"", ""14.0067""], + ""ha"": [""146"", ""1.008""], + ""na"": [""503"", ""512"", ""14.0067""], + ""nc"": [""511"", ""14.0067""], + ""nd"": [""511"", ""14.0067""], + ""hx"": [""140"", ""1.008""], + ""hs"": [""204"", ""1.008""], + ""hn"": [""240"", ""241"", ""290"", ""301"", ""304"", ""310"", ""504"", ""513"", ""1.008""], + ""ho"": [""155"", ""168"", ""1.008""], + ""c3"": [ + ""135"", + ""136"", + ""137"", + ""149"", + ""157"", + ""158"", + ""206"", + ""209"", + ""210"", + ""223B"", + ""224B"", + ""245"", + ""246"", + ""274"", + ""283"", + ""284"", + ""285"", + ""292"", + ""292B"", + ""293B"", + ""296"", + ""307"", + ""308"", + ""505"", + ""12.011"", + ], + ""hc"": [""140"", ""1.008""], + ""cd"": [""500"", ""506"", ""507"", ""508"", ""514"", ""12.011""], + ""c"": [""235"", ""271"", ""12.011""], + ""oh"": [""154"", ""167"", ""15.9994""], + ""ss"": [""202"", ""32.06""], + ""o"": [""236"", ""272"", ""15.9994""], + ""n"": [""237"", ""238"", ""239"", ""14.0067""], + ""sh"": [""200"", ""32.06""], + ""n4"": [""287"", ""309"", ""14.0067""], +} + +# draft +atomTypeAmber2oplsDict = { + ""HS"": [""HS""], + ""HP"": [""HC""], + ""HO"": [""HO""], + ""HC"": [""HC""], + ""HA"": [""HA""], + ""O2"": [""O2""], + ""C*"": [""C*""], + ""NA"": [""NA""], + ""NB"": [""NB""], + ""CB"": [""CB""], + ""CN"": [""CN""], + ""CV"": [""CV""], + ""CM"": [""CA""], + ""CA"": [""CA""], + ""CR"": [""CR""], + ""OH"": [""OH""], + ""H1"": [""HC""], + ""H4"": [""HA""], + ""N2"": [""N2""], + ""N3"": [""N3""], + ""H5"": [""HA""], + ""SH"": [""SH""], + ""N"": [""N""], + ""S"": [""S""], + ""O"": [""O""], + ""C"": [""C"", ""C_3""], + ""CW"": [""CW"", ""CX""], + ""H"": [""H"", ""H3""], + ""CC"": [""CX"", ""CW"", ""CV""], + ""CT"": [""CT"", ""CT_2"", ""CT_3""], +} + +# draft +a2oD = { + ""amber99_2"": [""opls_235"", ""opls_271""], + ""amber99_3"": [""opls_302"", ""opls_145""], + ""amber99_5"": [""opls_507"", ""opls_508"", ""opls_510""], + ""amber99_11"": [ + ""opls_209"", + ""opls_158"", + ""opls_283"", + ""opls_223B"", + ""opls_293B"", + ""opls_284"", + ""opls_292B"", + ""opls_274"", + ""opls_136"", + ""opls_135"", + ""opls_292"", + ""opls_157"", + ""opls_206"", + ""opls_137"", + ""opls_505"", + ""opls_224B"", + ""opls_307"", + ""opls_308"", + ""opls_210"", + ""opls_149"", + ], + ""amber99_13"": [""opls_514""], + ""amber99_14"": [""opls_500""], + ""amber99_17"": [""opls_504"", ""opls_241"", ""opls_240"", ""opls_290"", ""opls_301"", ""opls_310"", ""opls_304"", ""opls_513""], + ""amber99_18"": [""opls_140""], + ""amber99_19"": [""opls_140""], + ""amber99_22"": [""opls_146""], + ""amber99_23"": [""opls_146""], + ""amber99_25"": [""opls_155""], + ""amber99_26"": [""opls_204""], + ""amber99_28"": [""opls_140""], + ""amber99_34"": [""opls_238"", ""opls_239"", ""opls_237""], + ""amber99_35"": [""opls_512"", ""opls_503""], + ""amber99_36"": [""opls_511""], + ""amber99_38"": [""opls_300"", ""opls_303""], + ""amber99_39"": [""opls_309"", ""opls_287""], + ""amber99_41"": [""opls_236""], + ""amber99_43"": [""opls_154""], + ""amber99_45"": [""opls_272""], + ""amber99_47"": [""opls_202""], + ""amber99_48"": [""opls_200""], +} +","Python" +"Computational Biochemistry","alanwilter/acpype","acpype/utils.py",".py","8559","283","import math +import os +import subprocess as sub +import sys +from shutil import which + +from acpype.params import Pi + + +def find_bin(abin): + return which(abin) or """" + + +def checkOpenBabelVersion(): + ""check openbabel version"" + import warnings + + import openbabel as obl + + warnings.filterwarnings(""ignore"") + return int(obl.OBReleaseVersion().replace(""."", """")) + + +def dotproduct(aa, bb): + """"""scalar product"""""" + return sum((a * b) for a, b in zip(aa, bb)) + + +def cross_product(a, b): + """"""cross product"""""" + c = [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] + return c + + +def length(v): + """"""distance between 2 vectors"""""" + return math.sqrt(dotproduct(v, v)) + + +def vec_sub(aa, bb): + """"""vector A - B"""""" + return [a - b for a, b in zip(aa, bb)] + + +def imprDihAngle(a, b, c, d): + """"""calculate improper dihedral angle"""""" + ba = vec_sub(a, b) + bc = vec_sub(c, b) + cb = vec_sub(b, c) + cd = vec_sub(d, c) + n1 = cross_product(ba, bc) + n2 = cross_product(cb, cd) + angle = math.acos(dotproduct(n1, n2) / (length(n1) * length(n2))) * 180 / Pi + cp = cross_product(n1, n2) + if dotproduct(cp, bc) < 0: + angle = -1 * angle + return angle + + +def distanceAA(c1, c2): + """"""Distance between two atoms"""""" + # print c1, c2 + dist2 = (c1[0] - c2[0]) ** 2 + (c1[1] - c2[1]) ** 2 + (c1[2] - c2[2]) ** 2 + # dist2 = math.sqrt(dist2) + return dist2 + + +def elapsedTime(seconds, add_s=False, separator="" ""): + """""" + Takes an amount of seconds and turns it into a human-readable amount of time. + """""" + suffixes = [""y"", ""w"", ""d"", ""h"", ""m"", ""s""] + # the formatted time string to be returned + atime = [] + + # the pieces of time to iterate over (days, hours, minutes, etc) + # - the first piece in each tuple is the suffix (d, h, w) + # - the second piece is the length in seconds (a day is 60s * 60m * 24h) + parts = [ + (suffixes[0], 60 * 60 * 24 * 7 * 52), + (suffixes[1], 60 * 60 * 24 * 7), + (suffixes[2], 60 * 60 * 24), + (suffixes[3], 60 * 60), + (suffixes[4], 60), + (suffixes[5], 1), + ] + + # for each time piece, grab the value and remaining seconds, and add it to + # the time string + for suffix, alength in parts: + value = seconds // alength + if value > 0: + seconds = seconds % alength + atime.append(f'{value!s}{(suffix, (suffix, suffix + ""s"")[value > 1])[add_s]}') + if seconds < 1: + break + + return separator.join(atime) + + +def splitBlock(dat): + """"""split a amber parm dat file in blocks + 0 = mass, 1 = extra + bond, 2 = angle, 3 = dihedral, 4 = improp, 5 = hbond + 6 = equiv nbon, 7 = nbon, 8 = END, 9 = etc. + """""" + dict_ = {} + count = 0 + for line in dat: + line = line.rstrip() + if count in dict_: + dict_[count].append(line) + else: + dict_[count] = [line] + if not line: + count += 1 + return dict_ + + +def parseFrcmod(lista): + """"""Parse FRCMOD file"""""" + heads = [""MASS"", ""BOND"", ""ANGL"", ""DIHE"", ""IMPR"", ""HBON"", ""NONB""] + dict_ = {} + dd = {} + for line in lista[1:]: + line = line.strip() + if line[:4] in heads: + ahead = line[:4] + dict_[ahead] = [] + dd = {} + continue + if line: + key = line.replace("" -"", ""-"").replace(""- "", ""-"").split()[0] + if key in dd: + if not dd[key].count(line): + dd[key].append(line) + else: + dd[key] = [line] + dict_[ahead] = dd + for kk in dict_: + if not dict_[kk]: + dict_.pop(kk) + return dict_ + + +def parmMerge(fdat1, fdat2, frcmod=False): + """"""merge two amber parm dat/frcmod files and save in /tmp"""""" + name1 = os.path.basename(fdat1).split("".dat"")[0] + if frcmod: + name2 = os.path.basename(fdat2).split(""."")[1] + else: + name2 = os.path.basename(fdat2).split("".dat"")[0] + mname = ""/tmp/"" + name1 + name2 + "".dat"" + if os.path.exists(mname): + if os.path.getsize(mname): + return mname + mdatFile = open(mname, ""w"") + mdat = [f""merged {name1} {name2}""] + + dat1 = splitBlock(open(fdat1).readlines()) + + if frcmod: + dHeads = {""MASS"": 0, ""BOND"": 1, ""ANGL"": 2, ""DIHE"": 3, ""IMPR"": 4, ""HBON"": 5, ""NONB"": 7} + dat2 = parseFrcmod(open(fdat2).readlines()) # dict + for kk in dat2: + for parEntry in dat2[kk]: + idFirst = None + for line in dat1[dHeads[kk]][:]: + if line: + key = line.replace("" -"", ""-"").replace(""- "", ""-"").split()[0] + if key == parEntry: + if not idFirst: + idFirst = dat1[dHeads[kk]].index(line) + dat1[dHeads[kk]].remove(line) + rev = dat2[kk][parEntry][:] + rev.reverse() + if idFirst is None: + idFirst = 0 + for ll in rev: + if dHeads[kk] in [0, 1, 7]: # MASS has title in index 0 and so BOND, NONB + dat1[dHeads[kk]].insert(idFirst + 1, ll) + else: + dat1[dHeads[kk]].insert(idFirst, ll) + dat1[0][0] = mdat[0] + for kk in dat1: + for line in dat1[kk]: + mdatFile.write(line + ""\n"") + return mname + + dat2 = splitBlock(open(fdat2).readlines()) + id1 = 0 + id2 = 0 + for kk in list(dat1)[:8]: + if kk == 0: + lines = dat1[kk][1:-1] + dat2[kk][1:-1] + [""""] + for line in lines: + mdat.append(line) + if kk == 1: + for i in dat1[kk]: + if ""-"" in i: + id1 = dat1[kk].index(i) + break + for j in dat2[kk]: + if ""-"" in j: + id2 = dat2[kk].index(j) + break + l1 = dat1[kk][:id1] + l2 = dat2[kk][:id2] + line = """" + for item in l1 + l2: + line += item.strip() + "" "" + mdat.append(line) + lines = dat1[kk][id1:-1] + dat2[kk][id2:-1] + [""""] + for line in lines: + mdat.append(line) + if kk in [2, 3, 4, 5, 6]: # angles, p dih, imp dih + lines = dat1[kk][:-1] + dat2[kk][:-1] + [""""] + for line in lines: + mdat.append(line) + if kk == 7: + lines = dat1[kk][:-1] + dat2[kk][1:-1] + [""""] + for line in lines: + mdat.append(line) + for kk in list(dat1)[8:]: + for line in dat1[kk]: + mdat.append(line) + for kk in list(dat2)[9:]: + for line in dat2[kk]: + mdat.append(line) + for line in mdat: + mdatFile.write(line + ""\n"") + mdatFile.close() + + return mname + + +def job_pids_family(jpid): + """"""INTERNAL: Return all job processes (PIDs)"""""" + apid = repr(jpid) + dict_pids = {} + pids = [apid] + cmd = f""ps -A -o uid,pid,ppid|grep {os.getuid()}"" + out = _getoutput(cmd).split(""\n"") # getoutput(""ps -A -o uid,pid,ppid|grep %i"" % os.getuid()).split('\n') + for item in out: + vec = item.split() + dict_pids[vec[2]] = vec[1] + while True: + try: + apid = dict_pids[apid] + pids.append(apid) + except KeyError: + break + return "" "".join(pids) + + +def _getoutput(cmd): + """""" + To simulate commands.getoutput + shell=True is necessary despite security issues + """""" + out = sub.Popen(cmd, shell=True, stderr=sub.STDOUT, stdout=sub.PIPE).communicate()[0][:-1] + return out.decode() + + +def while_replace(string): + while "" "" in string: + string = string.replace("" "", "" "") + return string + + +def set_for_pip(binaries): + # For pip package + if which(binaries[""ac_bin""]) is None: + LOCAL_PATH = os.path.dirname(__file__) + if sys.platform == ""linux"": + os.environ[""PATH""] += os.pathsep + LOCAL_PATH + ""/amber_linux/bin"" + os.environ[""AMBERHOME""] = LOCAL_PATH + ""/amber_linux/"" + os.environ[""LD_LIBRARY_PATH""] = LOCAL_PATH + ""/amber_linux/lib/"" + elif sys.platform == ""darwin"": + os.environ[""PATH""] += os.pathsep + LOCAL_PATH + ""/amber_macos/bin"" + os.environ[""AMBERHOME""] = LOCAL_PATH + ""/amber_macos/"" + os.environ[""LD_LIBRARY_PATH""] = LOCAL_PATH + ""/amber_macos/lib/"" + os.environ[""DYLD_LIBRARY_PATH""] = LOCAL_PATH + ""/amber_macos/lib/"" +","Python" +"Computational Biochemistry","alanwilter/acpype","acpype/cli.py",".py","5672","188","#!/usr/bin/env python3 + +import os +import sys +import time +from shutil import rmtree +from typing import Dict, List, Optional + +from acpype.logger import copy_log, tmpLogFile +from acpype.logger import set_logging_conf as logger +from acpype.params import binaries +from acpype.parser_args import get_option_parser +from acpype.topol import AbstractTopol, ACTopol, MolTopol, header +from acpype.utils import elapsedTime, while_replace + + +def _chk_py_ver(): + if sys.version_info < (3, 8): + msg = ""Sorry, you need python 3.8 or higher"" + logger().error(msg) + raise Exception(msg) + + +def _handle_exception(level): + _exceptionType, exceptionValue, _exceptionTraceback = sys.exc_info() + logger(level).exception(f""ACPYPE FAILED: {exceptionValue}"") + return True + + +def init_main(binaries: Dict[str, str] = binaries, argv: Optional[List[str]] = None): + """""" + Orchestrate the command line usage for ACPYPE with its all input arguments. + + Args: + binaries (Dict[str, str], optional): Mostly used for debug and testing. Defaults to ``acpype.params.binaries``. + argv (Optional[List[str]], optional): Mostly used for debug and testing. Defaults to None. + + Returns: + SystemExit(status): 0 or 19 (failed) + """""" + _chk_py_ver() + if argv is None: + argv = sys.argv[1:] + + parser = get_option_parser() + args = parser.parse_args(argv) + + at0 = time.time() + + amb2gmxF = False + + if args.version: + print(header) + sys.exit(0) + + level = 20 + if not args.verboseless: + level = 100 + if args.debug: + level = 10 + + logger(level).info(header) + + if not args.input: + amb2gmxF = True + if not args.inpcrd or not args.prmtop: + parser.error(""missing input files"") + elif args.inpcrd or args.prmtop: + parser.error(""either '-i' or ('-p', '-x'), but not both"") + + logger(level).debug(f""CLI: {' '.join(argv)}"") + texta = f""Python Version {sys.version}"" + logger(level).debug(while_replace(texta)) + + if args.direct and not amb2gmxF: + parser.error(""option -u is only meaningful in 'amb2gmx' mode (args '-p' and '-x')"") + + acpypeFailed = False + if amb2gmxF: + logger(level).info(""Converting Amber input files to Gromacs ..."") + try: + molecule: AbstractTopol = MolTopol( + acFileXyz=args.inpcrd, + acFileTop=args.prmtop, + amb2gmx=True, + debug=args.debug, + basename=args.basename, + verbose=args.verboseless, + gmx4=args.gmx4, + merge=args.merge, + direct=args.direct, + is_sorted=args.sorted, + chiral=args.chiral, + ) + except Exception: + acpypeFailed = _handle_exception(level) + if not acpypeFailed: + try: + molecule.writeGromacsTopolFiles() + molecule.printDebug(""prmtop and inpcrd files parsed"") + except Exception: + acpypeFailed = _handle_exception(level) + + else: + try: + molecule = ACTopol( + args.input, + binaries=binaries, + chargeType=args.charge_method, + chargeVal=args.net_charge, + debug=args.debug, + multiplicity=args.multiplicity, + atomType=args.atom_type, + force=args.force, + outTopol=args.outtop, + allhdg=args.cnstop, + basename=args.basename, + timeTol=args.max_time, + qprog=args.qprog, + ekFlag=f'''""{args.keyword}""''', + verbose=args.verboseless, + gmx4=args.gmx4, + merge=args.merge, + direct=args.direct, + is_sorted=args.sorted, + chiral=args.chiral, + amb2gmx=False, + ) + except Exception: + acpypeFailed = _handle_exception(level) + if not acpypeFailed: + try: + molecule.createACTopol() + except Exception: + acpypeFailed = _handle_exception(level) + if not acpypeFailed: + try: + molecule.createMolTopol() + except Exception: + acpypeFailed = _handle_exception(level) + + execTime = int(round(time.time() - at0)) + if execTime == 0: + amsg = ""less than a second"" + else: + amsg = elapsedTime(execTime) + logger(level).info(f""Total time of execution: {amsg}"") + + if args.ipython: + try: + import IPython + + IPython.embed(colors=""neutral"") + except ModuleNotFoundError: + logger(level).exception(""No 'ipython' installed"") + + if not args.debug: + try: + rmtree(molecule.tmpDir) + except Exception: + logger(level).debug(""No tmp folder left to be removed"") + else: + try: + if molecule.tmpDir: + logger(level).debug(f""Keeping folder '{molecule.tmpDir}' for possible helping debugging"") + except Exception: + logger(level).debug(""No tmp folder left to be removed"") + + try: + copy_log(molecule) + except UnboundLocalError: + print(f""Log tmp location: {tmpLogFile}"") + + if acpypeFailed: + sys.exit(19) + + os.chdir(molecule.rootDir) + + if not amb2gmxF and molecule.obabelExe: + if molecule.checkSmiles(): + afile = ""smiles_molecule.mol2"" + if os.path.exists(afile): + os.remove(afile) + + +if __name__ == ""__main__"": + init_main() # necessary for to call in anaconda package; +","Python" +"Computational Biochemistry","alanwilter/acpype","acpype/parser_args.py",".py","5074","188","import argparse + +from acpype.params import MAXTIME, epilog, outTopols, usage + + +def get_option_parser(): + # not used yet: -e -l -r + parser = argparse.ArgumentParser(usage=usage + epilog) + group = parser.add_mutually_exclusive_group() + parser.add_argument( + ""-i"", + ""--input"", + action=""store"", + dest=""input"", + help=""input file type like '.pdb', '.mdl', '.mol2' or SMILES string (mandatory if -p and -x not set)"", + ) + parser.add_argument( + ""-b"", + ""--basename"", + action=""store"", + dest=""basename"", + help=""a basename for the project (folder and output files)"", + ) + parser.add_argument( + ""-x"", + ""--inpcrd"", + action=""store"", + dest=""inpcrd"", + help=""amber inpcrd file name (always used with -p)"", + ) + parser.add_argument( + ""-p"", + ""--prmtop"", + action=""store"", + dest=""prmtop"", + help=""amber prmtop file name (always used with -x)"", + ) + parser.add_argument( + ""-c"", + ""--charge_method"", + choices=[""gas"", ""bcc"", ""user""], + action=""store"", + default=""bcc"", + dest=""charge_method"", + help=""charge method: gas, bcc (default), user (user's charges in mol2 file)"", + ) + parser.add_argument( + ""-n"", + ""--net_charge"", + action=""store"", + type=int, + default=None, + dest=""net_charge"", + help=""net molecular charge (int), it tries to guess it if not not declared"", + ) + parser.add_argument( + ""-m"", + ""--multiplicity"", + action=""store"", + type=int, + default=1, + dest=""multiplicity"", + help=""multiplicity (2S+1), default is 1"", + ) + parser.add_argument( + ""-a"", + ""--atom_type"", + choices=[""gaff"", ""amber"", ""gaff2"", ""amber2""], + action=""store"", + default=""gaff2"", + dest=""atom_type"", + help=""atom type, can be gaff, gaff2 (default), amber (AMBER14SB) or amber2 (AMBER14SB + GAFF2)"", + ) + parser.add_argument( + ""-q"", + ""--qprog"", + choices=[""mopac"", ""sqm"", ""divcon""], + action=""store"", + default=""sqm"", + dest=""qprog"", + help=""am1-bcc flag, sqm (default), divcon, mopac"", + ) + parser.add_argument( + ""-k"", + ""--keyword"", + action=""store"", + dest=""keyword"", + help=""mopac or sqm keyword, inside quotes"", + ) + parser.add_argument( + ""-f"", + ""--force"", + action=""store_true"", + dest=""force"", + help=""force topologies recalculation anew"", + ) + group.add_argument( + ""-d"", + ""--debug"", + action=""store_true"", + dest=""debug"", + help=""for debugging purposes, keep any temporary file created (not allowed with arg -w)"", + ) + group.add_argument( + ""-w"", + ""--verboseless"", + action=""store_false"", + default=True, + dest=""verboseless"", + help=""print nothing (not allowed with arg -d)"", + ) + parser.add_argument( + ""-o"", + ""--outtop"", + choices=[""all"", *outTopols], + action=""store"", + default=""all"", + dest=""outtop"", + help=""output topologies: all (default), gmx, cns or charmm"", + ) + parser.add_argument( + ""-z"", + ""--gmx4"", + action=""store_true"", + dest=""gmx4"", + help=""write RB dihedrals old GMX 4.0"", + ) + parser.add_argument( + ""-t"", + ""--cnstop"", + action=""store_true"", + dest=""cnstop"", + help=""write CNS topology with allhdg-like parameters (experimental)"", + ) + parser.add_argument( + ""-s"", + ""--max_time"", + type=int, + action=""store"", + default=MAXTIME, + dest=""max_time"", + help=""max time (in sec) tolerance for sqm/mopac, default is %i hours"" % (MAXTIME // 3600), + ) + parser.add_argument( + ""-y"", + ""--ipython"", + action=""store_true"", + dest=""ipython"", + help=""start iPython interpreter"", + ) + parser.add_argument( + ""-g"", + ""--merge"", + action=""store_true"", + dest=""merge"", + help=""Merge lower and uppercase atomtypes in GMX top file if identical parameters"", + ) + parser.add_argument( + ""-u"", + ""--direct"", + action=""store_true"", + dest=""direct"", + help=""for 'amb2gmx' mode, does a direct conversion, for any solvent (EXPERIMENTAL)"", + # NOTE: when solvent is present, gmx mdrun is not working, lack solvent topology + ) + parser.add_argument( + ""-l"", + ""--sorted"", + action=""store_true"", + dest=""sorted"", + help=""sort atoms for GMX ordering"", + ) + parser.add_argument( + ""-j"", + ""--chiral"", + action=""store_true"", + dest=""chiral"", + help=""create improper dihedral parameters for chiral atoms in CNS"", + ) + parser.add_argument( + ""-v"", + ""--version"", + action=""store_true"", + dest=""version"", + help=""Show the Acpype version and exit"", + ) + return parser +","Python" +"Computational Biochemistry","alanwilter/acpype","acpype/amber_macos/amber.sh",".sh","1921","57","# Source this script to add the variables necessary to use Amber to your shell. +# This script must be located in the Amber root folder! + +# Amber was configured on 2023-10-08 at 18:58:13 + +# determine file path of this script (credit http://unix.stackexchange.com/questions/96203/find-location-of-sourced-shell-script) +if [ -n ""$BASH_SOURCE"" ]; then + this_script=""$BASH_SOURCE"" +elif [ -n ""$DASH_SOURCE"" ]; then + this_script=""$DASH_SOURCE"" +elif [ -n ""$ZSH_VERSION"" ]; then + setopt function_argzero + this_script=""$0"" +elif eval '[[ -n ${.sh.file} ]]' 2>/dev/null; then + eval 'this_script=${.sh.file}' +else + echo 1>&2 ""Unsupported shell. Please use bash, dash, ksh93 or zsh."" + exit 2 +fi + +export AMBERHOME=$(cd ""$(dirname ""$this_script"")""; pwd) +export PATH=""$AMBERHOME/bin:$PATH"" + +# Add Amber lib folder to LD_LIBRARY_PATH (if your platform supports it) +# Note that LD_LIBRARY_PATH is only necessary to help Amber's Python programs find their dynamic libraries, +# unless Amber has been moved from where it was installed. +if [ 1 = 1 ]; then + if [ -z ""$DYLD_FALLBACK_LIBRARY_PATH"" ]; then + export DYLD_FALLBACK_LIBRARY_PATH=""$AMBERHOME/lib"" + else + export DYLD_FALLBACK_LIBRARY_PATH=""$AMBERHOME/lib:$DYLD_FALLBACK_LIBRARY_PATH"" + fi +fi + +# Add location of Amber Perl modules to default Perl search path (if your platform supports it) +if [ 1 = 1 ]; then + if [ -z ""$PERL5LIB"" ]; then + export PERL5LIB=""$AMBERHOME/lib/perl"" + else + export PERL5LIB=""$AMBERHOME/lib/perl:$PERL5LIB"" + fi +fi + +# Add location of Amber Python modules to default Python search path (if your platform supports it) +if [ 1 = 1 ]; then + if [ -z ""$PYTHONPATH"" ]; then + export PYTHONPATH=""$AMBERHOME/lib/python3.11/site-packages"" + else + export PYTHONPATH=""$AMBERHOME/lib/python3.11/site-packages:$PYTHONPATH"" + fi +fi + +# Tell QUICK where to find its data files +if [ 1 = 1 ]; then + export QUICK_BASIS=""$AMBERHOME/AmberTools/src/quick/basis"" +fi +","Shell" +"Computational Biochemistry","alanwilter/acpype","acpype/amber_macos/dat/leap/parm/validate_torsions.py",".py","2065","60",""""""" +This script will validate the torsions specified in a particular database and +will highlight any specific torsions that need additional terms to explicitly +override generic torsions +"""""" +import os +import sys + +import parmed as pmd + +if len(sys.argv) < 2: + sys.exit(""%s [ [ ...]]"" % os.path.split(sys.argv[0])[1]) + +params = pmd.amber.AmberParameterSet(sys.argv[1:]) + +# First separate the generic terms and the specific terms. Store the generics as +# *just* the middle terms, and do both permutations +generics = dict() +generic_type_ids = set() +specifics = dict() +specific_type_ids = set() + +for key, dihtype in params.dihedral_types.items(): + if key[0] == ""X"" and key[3] == ""X"": + if id(dihtype) in generic_type_ids: + continue + generics[(key[1], key[2])] = generics[(key[2], key[1])] = dihtype + generic_type_ids.add(id(dihtype)) + else: + if id(dihtype) in specific_type_ids: + continue + specifics[key] = dihtype + specific_type_ids.add(id(dihtype)) + +# Now we have a separation of specifics and generics +print(""Found %d generic torsions and %d specific torsions"" % (len(generic_type_ids), len(specific_type_ids))) + +for specific_key, dihtype in specifics.items(): + # Look through all generic terms and see if there are any generics that + # match. If there is one (there will be ONLY one) see that the specific + # torsion overrides all periodicities on the generic torsion. + genkey = (specific_key[1], specific_key[2]) + if genkey not in generics: + continue + gdihtype = generics[genkey] + genper = {int(x.per) for x in gdihtype} + speper = {int(x.per) for x in dihtype} + diff = genper - speper + if len(diff) > 0: + print( + ""%-2s-%-2s-%-2s-%-2s is missing overriding periodicities %s"" + % ( + specific_key[0], + specific_key[1], + specific_key[2], + specific_key[3], + "", "".join(str(x) for x in sorted(diff)), + ) + ) +","Python" +"Computational Biochemistry","alanwilter/acpype","acpype/amber_linux/amber.sh",".sh","1877","57","# Source this script to add the variables necessary to use Amber to your shell. +# This script must be located in the Amber root folder! + +# Amber was configured on 2023-10-08 at 18:52:40 + +# determine file path of this script (credit http://unix.stackexchange.com/questions/96203/find-location-of-sourced-shell-script) +if [ -n ""$BASH_SOURCE"" ]; then + this_script=""$BASH_SOURCE"" +elif [ -n ""$DASH_SOURCE"" ]; then + this_script=""$DASH_SOURCE"" +elif [ -n ""$ZSH_VERSION"" ]; then + setopt function_argzero + this_script=""$0"" +elif eval '[[ -n ${.sh.file} ]]' 2>/dev/null; then + eval 'this_script=${.sh.file}' +else + echo 1>&2 ""Unsupported shell. Please use bash, dash, ksh93 or zsh."" + exit 2 +fi + +export AMBERHOME=$(cd ""$(dirname ""$this_script"")""; pwd) +export PATH=""$AMBERHOME/bin:$PATH"" + +# Add Amber lib folder to LD_LIBRARY_PATH (if your platform supports it) +# Note that LD_LIBRARY_PATH is only necessary to help Amber's Python programs find their dynamic libraries, +# unless Amber has been moved from where it was installed. +if [ 1 = 1 ]; then + if [ -z ""$LD_LIBRARY_PATH"" ]; then + export LD_LIBRARY_PATH=""$AMBERHOME/lib"" + else + export LD_LIBRARY_PATH=""$AMBERHOME/lib:$LD_LIBRARY_PATH"" + fi +fi + +# Add location of Amber Perl modules to default Perl search path (if your platform supports it) +if [ 1 = 1 ]; then + if [ -z ""$PERL5LIB"" ]; then + export PERL5LIB=""$AMBERHOME/lib/perl"" + else + export PERL5LIB=""$AMBERHOME/lib/perl:$PERL5LIB"" + fi +fi + +# Add location of Amber Python modules to default Python search path (if your platform supports it) +if [ 1 = 1 ]; then + if [ -z ""$PYTHONPATH"" ]; then + export PYTHONPATH=""$AMBERHOME/lib/python3.11/site-packages"" + else + export PYTHONPATH=""$AMBERHOME/lib/python3.11/site-packages:$PYTHONPATH"" + fi +fi + +# Tell QUICK where to find its data files +if [ 1 = 1 ]; then + export QUICK_BASIS=""$AMBERHOME/AmberTools/src/quick/basis"" +fi +","Shell" +"Computational Biochemistry","alanwilter/acpype","acpype/amber_linux/dat/leap/parm/validate_torsions.py",".py","2065","60",""""""" +This script will validate the torsions specified in a particular database and +will highlight any specific torsions that need additional terms to explicitly +override generic torsions +"""""" +import os +import sys + +import parmed as pmd + +if len(sys.argv) < 2: + sys.exit(""%s [ [ ...]]"" % os.path.split(sys.argv[0])[1]) + +params = pmd.amber.AmberParameterSet(sys.argv[1:]) + +# First separate the generic terms and the specific terms. Store the generics as +# *just* the middle terms, and do both permutations +generics = dict() +generic_type_ids = set() +specifics = dict() +specific_type_ids = set() + +for key, dihtype in params.dihedral_types.items(): + if key[0] == ""X"" and key[3] == ""X"": + if id(dihtype) in generic_type_ids: + continue + generics[(key[1], key[2])] = generics[(key[2], key[1])] = dihtype + generic_type_ids.add(id(dihtype)) + else: + if id(dihtype) in specific_type_ids: + continue + specifics[key] = dihtype + specific_type_ids.add(id(dihtype)) + +# Now we have a separation of specifics and generics +print(""Found %d generic torsions and %d specific torsions"" % (len(generic_type_ids), len(specific_type_ids))) + +for specific_key, dihtype in specifics.items(): + # Look through all generic terms and see if there are any generics that + # match. If there is one (there will be ONLY one) see that the specific + # torsion overrides all periodicities on the generic torsion. + genkey = (specific_key[1], specific_key[2]) + if genkey not in generics: + continue + gdihtype = generics[genkey] + genper = {int(x.per) for x in gdihtype} + speper = {int(x.per) for x in dihtype} + diff = genper - speper + if len(diff) > 0: + print( + ""%-2s-%-2s-%-2s-%-2s is missing overriding periodicities %s"" + % ( + specific_key[0], + specific_key[1], + specific_key[2], + specific_key[3], + "", "".join(str(x) for x in sorted(diff)), + ) + ) +","Python" +"Computational Biochemistry","alanwilter/acpype","docs/conf.py",".py","2260","66","# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import sys +from datetime import datetime + +sys.path.insert(0, os.path.abspath("".."")) + + +# -- Project information ----------------------------------------------------- +year = str(datetime.today().year) +project = ""ACPYPE"" +copyright = f""{year}, Alan Silva"" +author = ""Alan Silva"" + +release = year +# The full version, including alpha/beta/rc tags +try: + import acpype +except ImportError: + print(""WARNING: couldn't import acpype to read version."") +else: + release = acpype.__version__ + +version = release + +# -- General configuration --------------------------------------------------- + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [""sphinx.ext.napoleon"", ""sphinx.ext.autodoc"", ""sphinx.ext.autosummary""] + +autosummary_generate = True + +# Add any paths that contain templates here, relative to this directory. +templates_path = [""_templates""] + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = [""_build"", ""Thumbs.db"", "".DS_Store""] + + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = ""sphinx_rtd_theme"" # ""classic"" + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named ""default.css"" will overwrite the builtin ""default.css"". +# html_static_path = [""_static""] +","Python" +"Computational Biochemistry","alanwilter/acpype","scripts/run_test_acpype_db_ligands.py",".py","4942","154","#!/usr/bin/env python + +# usage: ./run_test_acpype_db_ligands.py (opt: n=10 or ""['001','Rca']"") + +import os +import sys +import time +from subprocess import Popen + +numCpu = 20 + + +def elapsedTime(seconds, suffixes=[""y"", ""w"", ""d"", ""h"", ""m"", ""s""], add_s=False, separator="" ""): + """""" + Takes an amount of seconds and turns it into a human-readable amount of time. + """""" + # the formatted time string to be returned + if seconds == 0: + return ""0s"" + time = [] + + # the pieces of time to iterate over (days, hours, minutes, etc) + # - the first piece in each tuple is the suffix (d, h, w) + # - the second piece is the length in seconds (a day is 60s * 60m * 24h) + parts = [ + (suffixes[0], 60 * 60 * 24 * 7 * 52), + (suffixes[1], 60 * 60 * 24 * 7), + (suffixes[2], 60 * 60 * 24), + (suffixes[3], 60 * 60), + (suffixes[4], 60), + (suffixes[5], 1), + ] + + # for each time piece, grab the value and remaining seconds, and add it to + # the time string + for suffix, length in parts: + value = seconds / length + if value > 0: + seconds = seconds % length + time.append(""{}{}"".format(str(value), (suffix, (suffix, suffix + ""s"")[value > 1])[add_s])) + if seconds < 1: + break + + return separator.join(time) + + +def runConversionJobs(chemCompVarFiles, scriptName): + # _timeStamp = time.strftime(""%Y_%m_%d_%H_%M_%S"") + + startCode = ""start"" + + currentChemCompVarFile = None + currentProcesses = {startCode: None} + currentJobOut = {} + currentIndex = -1 + endChemCompVarFile = chemCompVarFiles[-1] + + outputHandle = sys.__stdout__ + + while currentProcesses: + if startCode in currentProcesses.keys(): + del currentProcesses[startCode] + + if len(currentProcesses.keys()) < numCpu: + tempIndex = currentIndex + 1 + for _i in range(currentIndex, currentIndex + numCpu - len(currentProcesses.keys())): + # Don't start a job if it's at the end! + if currentChemCompVarFile != endChemCompVarFile: + chemCompVarFile = chemCompVarFiles[tempIndex] + + # + # TODO: ensure that stdout and stdin OK for this job!! Might want to reroute!! + # + + currentOutFile = chemCompVarFile.replace("".mol2"", "".out"") + jobOut = open(currentOutFile, ""w"") + + varDir, varFile = os.path.split(chemCompVarFile) + os.chdir(varDir) + process = Popen([""nice"", ""-19"", scriptName, ""-i"", varFile, ""-d""], stdout=jobOut, stderr=jobOut) + + currentJobOut[chemCompVarFile] = jobOut + currentProcesses[chemCompVarFile] = process + currentChemCompVarFile = chemCompVarFile + + outputHandle.write(""\n*** Job %s started ***\n\n"" % chemCompVarFile) + + tempIndex += 1 + + # Allow jobs to start one by one... nicer for output + time.sleep(1) + + currentIndex = tempIndex - 1 + + time.sleep(3) + + # + # Check if finished + # + + for chemCompVarFile in currentProcesses.keys(): + # Finished... + if currentProcesses[chemCompVarFile].poll() is not None: + del currentProcesses[chemCompVarFile] + currentJobOut[chemCompVarFile].close() + del currentJobOut[chemCompVarFile] + outputHandle.write(""\n *** Job %s finished ***\n"" % chemCompVarFile) + if not currentProcesses: + currentProcesses = {startCode: None} + + outputHandle.flush() + + +if __name__ == ""__main__"": + t0 = time.time() + + chemCompVarFiles = [] + curDir = os.getcwd() + ccpCodes = os.listdir(""other"") + ccpCodes.sort() + + # Only run this on 'other'! + if len(sys.argv) > 1: + args = sys.argv[1:] + if args[0].startswith(""n=""): + num = int(args[0][2:]) + ccpCodes = ccpCodes[:num] + else: + args = list(set(eval(args[0]))) + args.sort() + ccpCodes = args + + for ccpCode in ccpCodes: + # HACK to restart after powercut + # if ccpCode < 'NA': + # continue + + ccvNames = os.listdir(os.path.join(""other"", ccpCode)) + + for ccvName in ccvNames: + if ccvName[-5:] == "".mol2"" and not ccvName.count(""bcc_gaff""): + chemCompVarFiles.append(os.path.join(curDir, ""other"", ccpCode, ccvName)) + + runConversionJobs(chemCompVarFiles, ""acpype"") + execTime = int(round(time.time() - t0)) + msg = elapsedTime(execTime) + print(""Total time of execution: %s"" % msg) + print(""ALL DONE"") + +# nohup ./run_test_acpype_db_ligands.py & +# grep started nohup.out | wc -l ; grep finished nohup.out | wc -l # 17405 17405 +# grep -r ""FAILED: semi-QM taking"" other/* +# grep -r ""invalid"" other/* +","Python" +"Computational Biochemistry","alanwilter/acpype","scripts/ver_today.sh",".sh","587","19","#!/bin/bash + +today=""$(date +%Y.%-m.%-d)"" +last_tag=$(git describe --abbrev=0 --tags) + +while IFS= read -r afile; do + echo ""Updated version to $today in file $afile"" + perl -pi -e ""s/\b[0-9]{4}\.[12]?[0-9]\.[123]?[0-9]\b/$today/g"" ""$afile"" + git add ""$afile"" +done < <(pcregrep -lwr ""\d{4}\.[12]?[0-9]\.[123]?[0-9]"" ./*/*.py pyproject.toml) + +while IFS= read -r afile; do + echo ""Updated last_tag to $last_tag in file $afile"" + perl -pi -e ""s/\b[0-9]{4}\.[12]?[0-9]\.[123]?[0-9]\b/$last_tag/g"" ""$afile"" + git add ""$afile"" +done < <(pcregrep -lwr ""\d{4}\.[12]?[0-9]\.[123]?[0-9]"" README.md) + +exit 0 +","Shell" +"Computational Biochemistry","alanwilter/acpype","scripts/check_acpype.py",".py","26099","829","#!/usr/bin/env python3 +import os +import shutil +from glob import glob + +from acpype.topol import ACTopol +from acpype.utils import _getoutput + +usePymol = False +ffType = ""amber"" # gaff +cType = ""gas"" +debug = True + +water = "" -water none"" + +print(f""usePymol: {usePymol}, ffType: {ffType}, cType: {cType}"") + +tmpDir = ""/tmp/testAcpype"" + +delList = [""topol.top"", ""posre.itp""] + +# create Dummy PDB +tpdb = ""/tmp/tmp.pdb"" +dummyLine = ""ATOM 1 N ALA A 1 -1.188 -0.094 0.463 1.00 0.00 N\n"" +open(tpdb, ""w"").writelines(dummyLine) +tempObj = ACTopol(tpdb, chargeVal=0, verbose=False) + +# Binaries for ambertools +acExe = tempObj.acExe +tleapExe = tempObj.tleapExe +sanderExe = os.path.join(os.path.dirname(acExe), ""sander"") +ambpdbExe = os.path.join(os.path.dirname(acExe), ""ambpdb"") + +exePymol = ""/sw/bin/pymol"" + +# Binaries for gromacs +gpath = ""/home/awilter/miniconda3/envs/acpype/"" +gmxTopDir = gpath + ""share"" +pdb2gmx = gpath + ""bin/gmx pdb2gmx"" +grompp = gpath + ""bin/gmx grompp"" +mdrun = gpath + ""bin/gmx mdrun"" +g_energy = gpath + ""bin/gmx energy"" +gmxdump = gpath + ""bin/gmx dump"" + +amberff = ""oldff/leaprc.ff99SB"" + +genPdbTemplate = """""" +source %(amberff)s +mol = sequence {N%(res1)s %(res)s C%(res1)s} +savepdb mol %(aai3)s.pdb +saveamberparm mol prmtop inpcrd +quit +"""""" + +spe_mdp = """""" +# Create SPE.mdp file #single point energy +cat << EOF >| SPE.mdp +define = -DFLEXIBLE +cutoff-scheme = group +integrator = md +nsteps = 0 +dt = 0.001 +constraints = none +emtol = 10.0 +emstep = 0.01 +nstcomm = 1 +ns_type = simple +nstlist = 0 +rlist = 0 +rcoulomb = 0 +rvdw = 0 +Tcoupl = no +Pcoupl = no +gen_vel = no +nstxout = 1 +pbc = no +nstlog = 1 +nstenergy = 1 +nstvout = 1 +nstfout = 1 +nstxtcout = 1 +comm_mode = ANGULAR +continuation = yes +EOF +"""""" + +aa_dict = { + ""A"": ""ala"", + ""C"": ""cys"", + ""D"": ""asp"", + ""E"": ""glu"", + ""F"": ""phe"", + ""G"": ""gly"", + ""H"": ""hie"", + ""J"": ""hip"", + ""O"": ""hid"", + ""I"": ""ile"", + ""K"": ""lys"", + ""L"": ""leu"", + ""M"": ""met"", + ""N"": ""asn"", + ""P"": ""pro"", + ""Q"": ""gln"", + ""R"": ""arg"", + ""S"": ""ser"", + ""T"": ""thr"", + ""V"": ""val"", + ""W"": ""trp"", + ""Y"": ""tyr"", +} + +hisDictConv = {""HHH"": [""HIE"", ""HISE""], ""JJJ"": [""HIP"", ""HISH""], ""OOO"": [""HID"", ""HISD""]} + +pymolScript = ( + ""aa_dict = %s"" % str(aa_dict) + + """""" +def build3(object_name, sequence, first_residue = ""1""): + if len(sequence): + codeNT, code, codeCT = sequence + cmd.fragment('nt_'+aa_dict[codeNT],object_name) + cmd.alter(object_name,'resi=""%s""'%first_residue) + cmd.edit(object_name+"" and name C"") + for code in sequence[1:-1]: + editor.attach_amino_acid(""pk1"",aa_dict[code]) + editor.attach_amino_acid(""pk1"",'ct_'+aa_dict[codeCT]) + cmd.edit() + +seqi=aa_dict.keys() + +count=0 + +cmd.delete('all') + +for aai in seqi: + aai3=3*aai + build3(aai3,aai3) + cmd.alter(aai3,""chain='%s'""%aai3) + cmd.translate([15*count,0,0],aai3) + cmd.sculpt_activate(aai3) + for n in range(100): + cmd.sculpt_iterate(aai3) + count=count+1 + aafile = aai3+'.pdb' + cmd.set('pdb_conect_all') + cmd.save(aafile,'all') + cmd.delete('all') +"""""" +) + + +def pdebug(msg): + if debug: + print(""DEBUG: %s"" % msg) + + +def perror(msg): + if debug: + print(""ERROR: %s"" % msg) + + +def createAmberPdb(fpdb, opt): + """"""pdb -> apdb (amber) + opt = 0 : pymol pdb to apdb + opt = 1 : ogpdb to apdb + """""" + fLines = open(fpdb).readlines() + fName = ""a"" + fpdb + famb = open(fName, ""w"") + for line in fLines: + if ""ATOM "" in line: + if opt == 0: + if ""AAA"" not in fpdb: + line = line.replace("" HB3 "", "" HB1 "") + line = line.replace(""CD1 ILE"", ""CD ILE"") + line = line.replace("" HG3 "", "" HG1 "") + line = line.replace("" HA3 GLY"", "" HA1 GLY"") + line = line.replace(""HG13 ILE"", ""HG11 ILE"") + line = line.replace(""HG13 ILE"", ""HG11 ILE"") + if line[22:26] == "" 3"": + line = line.replace("" O "", "" OC1"").replace("" OXT"", "" OC2"") + elif opt == 1: + if line[22:26] == "" 3"": + line = line.replace("" O1 "", "" OC1"").replace("" O2 "", "" OC2"") + if line[22:26] == "" 1"": + res = line[17:20] + line = line.replace(""%s "" % res, ""N%s"" % res) + if line[22:26] == "" 3"": + res = line[17:20] + line = line.replace(""%s "" % res, ""C%s"" % res) + famb.write(line) # pay attention here! + famb.close() + return fName + + +def createAmberPdb3(fpdb): + """"""Add N and C XXX --> NXXX, CXXX"""""" + fLines = open(fpdb).readlines() + fName = fpdb.replace(""_"", ""a"") + famb = open(fName, ""w"") + for line in fLines: + if ""ATOM "" in line: + if line[22:26] == "" 1"": + res = line[17:20] + line = line.replace(""%s "" % res, ""N%s"" % res) + if line[22:26] == "" 3"": + res = line[17:20] + line = line.replace(""%s "" % res, ""C%s"" % res) + famb.write(line) # pay attention here! + famb.close() + return fName + + +def createAmberPdb2(fpdb, opt): + """""" + use formatConverter + Add N and C XXX --> NXXX, CXXX and OC1 & OC2 + """""" + projectName = ""testImport"" + if os.path.exists(projectName): + shutil.rmtree(projectName) + _fpdb = ""_%s"" % fpdb + + fLines = open(_fpdb).readlines() + fName = ""a"" + fpdb + famb = open(fName, ""w"") + for line in fLines: + if ""ATOM "" in line: + line = line.replace(""CYS"", ""CYN"") + line = line.replace(""LYS"", ""LYP"") + if opt == 0: + if line[22:26] == "" 3"": + line = line.replace("" O "", "" OC1 "").replace("" OXT "", "" OC2 "") + elif opt == 1: + if line[22:26] == "" 3"": + line = line.replace("" O1 "", "" OC1"").replace("" O2 "", "" OC2"") + if line[22:26] == "" 1"": + res = line[17:20] + line = line.replace(""%s "" % res, ""N%s"" % res) + if line[22:26] == "" 3"": + res = line[17:20] + line = line.replace(""%s "" % res, ""C%s"" % res) + famb.write(line) # pay attention here! + famb.close() + return fName + + +def createOldPdb2(fpdb): + """"""using my own dict for e.g. 2HB = HB2 -> HB1"""""" + defHB1 = ["" HB2"", ""2HB "", "" HB1""] + defHB2 = ["" HB3"", ""3HB "", "" HB2""] + defHG1 = ["" HG2"", ""2HG "", "" HG1""] + defHG2 = ["" HG3"", ""3HG "", "" HG2""] + defHD1 = ["" HD2"", ""2HD "", "" HD1""] + defHD2 = ["" HD3"", ""3HD "", "" HD2""] + def1HG2 = [""HG21"", ""1HG2""] + def2HG2 = [""HG22"", ""2HG2""] + def3HG2 = [""HG23"", ""3HG2""] + + dictPdb2GmxAtomNames = { + ""ALA"": (), + ""VAL"": (), + ""CYS"": (defHB1, defHB2), + ""ASP"": (defHB1, defHB2), + ""GLU"": (defHB1, defHB2, defHG1, defHG2), + ""PHE"": (defHB1, defHB2), + ""GLY"": (["" HA2 "", "" HA "", "" HA1 ""], ["" HA3"", ""3HA "", "" HA2""]), + ""HIE"": (defHB1, defHB2), + ""ILE"": ( + [""CD1"", ""CD ""], + [""HG12"", ""2HG1"", ""1HG1""], + [""HG13"", ""3HG1"", ""2HG1""], + def1HG2, + def2HG2, + def3HG2, + [""HD11"", ""1HD1"", "" HD1""], + [""HD12"", ""2HD1"", "" HD2""], + [""HD13"", ""3HD1"", "" HD3""], + ), + ""HIP"": (defHB1, defHB2), + ""HID"": (defHB1, defHB2), + ""LYS"": (defHB1, defHB2, defHG1, defHG2, defHD1, defHD2, ["" HE2"", ""2HE "", "" HE1""], ["" HE3"", ""3HE "", "" HE2""]), + ""LEU"": (defHB1, defHB2), + ""MET"": (defHB1, defHB2, defHG1, defHG2), + ""ASN"": (defHB1, defHB2), + ""PRO"": (defHB1, defHB2, defHG1, defHG2, defHD1, defHD2, ["" H3 "", ""3H "", "" H1 ""]), + ""GLN"": (defHB1, defHB2, defHG1, defHG2, [""HE21"", ""1HE2""], [""HE22"", ""2HE2""]), + ""ARG"": (defHB1, defHB2, defHG1, defHG2, defHD1, defHD2), + ""SER"": (defHB1, defHB2), + ""THR"": (def1HG2, def2HG2, def3HG2), + ""TRP"": (defHB1, defHB2), + ""TYR"": (defHB1, defHB2), + } + fName = ""_"" + fpdb + fLines = open(fpdb).readlines() + aLines = [] + for line in fLines: + if ""ATOM "" in line: + aLines.append(line) + nRes = int(aLines[-1][22:26]) + nLines = [] + for line in aLines: + res = line[17:20] + nResCur = int(line[22:26]) + for item in dictPdb2GmxAtomNames.get(res): + atAim = item[-1] + for at in item[:-1]: + # print(at, atAim) + # print(line) + line = line.replace(""%s"" % at, ""%s"" % atAim) + # print(line) + if nResCur == nRes: + line = line.replace(""O %s"" % res, ""OC1 %s"" % res) + line = line.replace(""OXT %s"" % res, ""OC2 %s"" % res) + nLines.append(line) + open(fName, ""w"").writelines(nLines) + return fName + + +def parseTopFile(lista): + """"""lista = top file in list format + return a (dict,dict) with fields"""""" + defDict = {} + parDict = {} + for line in lista: + line = line.split("";"")[0] + line = line.strip() + if line.startswith(""#def""): + vals = line.split() + defDict[vals[1]] = map(eval, vals[2:]) + elif line and not line.startswith(""#""): + if line.startswith(""[ ""): + flag = line.split()[1] + if flag not in parDict: + parDict[flag] = [] + else: + u = [] + t = line.split() + for i in t: + try: + v = eval(i) + except Exception: + v = i + u.append(v) + parDict[flag].append(u) + return parDict, defDict + + +def nbDict(lista): + tdict = {} + for line in lista: + line = line.split("";"")[0] + line = line.strip() + if line and not line.startswith(""#"") and not line.startswith(""[""): + name, type_ = line.split()[0:2] + tdict[name] = type_ + return tdict + + +def roundAllFloats(lista, ll): + """"""Round to 3 decimals"""""" + nlista = [] + for ii in lista: + tt = ii[: ll + 1] + for jj in ii[ll + 1 :]: + if jj > 100.0: + jj = round(jj, -1) + nn = round(jj, 3) + tt.append(nn) + nlista.append(tt) + return nlista + + +def checkTopAcpype(res): + """"""Compare acpype gmx itp against amber pdb2gmx results"""""" + os.chdir(tmpDir) + + def addParam(ll, item): + """"""ll : index for bonded types + item : set of atomtypes"""""" + dict_ = {2: ""bondtypes"", 3: ""angletypes"", 4: ""dihedraltypes""} + dType = {} # dict_ + for type_ in ffBon[0][dict_[ll]]: + i = type_[: ll + 1] + j = type_[ll + 1 :] + dType[str(i)] = j # dict_ {[atomtypes,funct] : parameters} + entries = [] + lNum = item[ll] # funct + ent = [ffDictAtom[x] for x in item[:ll]] # convert atomtypes ids to atomtypes names + rent = ent[:] + rent.reverse() + entries.append([*ent, lNum]) + entries.append([*rent, lNum]) + if ll == 4: + if len(item) == 6: + par = ffBon[1][item[5]] + return par + tent = ent[:] + rtent = rent[:] + if lNum in [3, 9]: # dih proper + tent[0] = ""X"" + entries.append([*tent, lNum]) + tent.reverse() + entries.append([*tent, lNum]) + tent[0] = ""X"" + entries.append([*tent, lNum]) + tent.reverse() + entries.append([*tent, lNum]) + rtent[0] = ""X"" + entries.append([*rtent, lNum]) + rtent.reverse() + entries.append([*rtent, lNum]) + if lNum in [1, 4]: # dih improp + tent[0] = ""X"" + entries.append([*tent, lNum]) + tent[1] = ""X"" + entries.append([*tent, lNum]) + rtent[0] = ""X"" + entries.append([*rtent, lNum]) + rtent[1] = ""X"" + entries.append([*rtent, lNum]) + found = False + for e in entries: + try: + par = dType[str(e)] + found = True + break + except Exception: + pass + if not found: + print(f""{dict_[ll]} {ent} {item} not found in {ffType} Bon"") + # print(item, e, par) + return par + + compareParameters = True + + agRes = parseTopFile(open(""ag%s.top"" % (res)).readlines()) + acRes = parseTopFile(open(f""ag{res}.acpype/ag{res}_GMX.itp"").readlines()) + ffBon = aBon + ffgRes = agRes + + atError = False + print("" ==> Comparing atomtypes AC x AMBER"") + + ffDictAtom = {} # dict link res atom numbers to amber atom types + for item in ffgRes[0][""atoms""]: + i, j = item[:2] # id, at + ambat = j + ffDictAtom[i] = ambat + # compare atom types AC x Amber + acat = acRes[0][""atoms""][i - 1][1] + if ambat != acat: + print("" %i %s AC: %s x AMB: %s"" % (i, item[4], acat, ambat)) + atError = True + + if not atError: + print("" atomtypes OK"") + + acDictAtom = {} + for item in acRes[0][""atoms""]: + i, j = item[:2] + acDictAtom[i] = j # dict for atom id -> atom type from acpype itp file + + flags = [ + (""pairs"", 2), + (""bonds"", 2), + (""angles"", 3), + (""dihedrals"", 4), + ] # , ['dihedraltypes', 'angletypes', 'bondtypes'] + + for flag, ll in flags: + print("" ==> Comparing %s"" % flag) + if flag != flags[0][0] and compareParameters: # not 'pairs' + agres = [] + tAgRes = ffgRes[0][flag] # e.g. dic 'bonds' from gmx top file + for item in tAgRes: + if flag == flags[1][0]: # 'bonds' + par = addParam(ll, item) + elif flag == flags[2][0]: # 'angles' + par = addParam(ll, item) + elif flag == flags[3][0]: # 'dihedrals', e.g. item = [2, 1, 5, 6, 9] + par = addParam(ll, item) + if len(item) == 6: + item.pop() + agres.append(item + par) + if compareParameters: + acres = acRes[0][flag] + else: + if flag == flags[3][0]: + agres = [x[: ll + 1] for x in ffgRes[0][flag]] + else: + agres = ffgRes[0][flag] + if compareParameters: + acres = acRes[0][flag] + else: + acres = [x[: ll + 1] for x in acRes[0][flag]] + + act = acres[:] + agt = agres[:] + + if compareParameters: + if flag != flags[0][0]: + # round parameters + act = roundAllFloats(act, ll) + agt = roundAllFloats(agt, ll) + act2 = act[:] + agt2 = agt[:] + + if not compareParameters or flag == flags[0][0]: + act2 = act[:] + agt2 = agt[:] + + for ac in act: + if str(ac) in str(agt): + act2.remove(ac) + agt2.remove(ac) + else: + t = ac[:-1] + t.reverse() + acr = [*t, ac[-1]] + if str(acr) in str(agt): + act2.remove(ac) + agt2.remove(acr) + + act3 = act2[:] + agt3 = agt2[:] + + if act2 and agt2: + # specially for dih since it may need to resort indexes + agl = {} + for ag in agt3: + t = ag[:-1] + t.sort() + ags = [*t, ag[-1]] + agl[str(ags)] = ag + for ac in act2: + t = ac[:-1] + t.sort() + acs = [*t, ac[-1]] + if str(acs) in str(agl.keys()): + act3.remove(ac) + agt3.remove(agl[str(acs)]) + + act4 = [] + agt4 = [] + + for ac in act3: + if ac[:5] not in tAgRes: + if flag == flags[3][0]: + if ac[6]: + act4.append(ac) + else: + act4.append(ac) + + tAcRes = [x[:5] for x in acres] + for ac in agt3: + if ag[:5] not in tAcRes: + act4.append(ac) + + if flag == flags[3][0]: + for ac in act4: + if not ac[6]: + act4.remove(ac) + for ag in agt4: + if not ag[6]: + agt4.remove(ac) + + if act4: + act4.sort() + print("" ac: "", act4) + if agt4: + agt4.sort() + print("" %sg: "" % ff, agt4) + + if not act4 and not agt4: + print("" %s OK"" % flag) + + +def parseOut(out): + lines = out.splitlines() + # for line in lines: + count = 0 + while count < len(lines): + line = lines[count] + if ""WARNING"" in line.upper(): + if ""will be determined based"" in line: + pass + elif ""Problems reading a PDB file"" in line: + pass + elif ""Open Babel Warning"" in line: + pass + elif ""no charge value given"" in line: + pass + elif ""audit log messages"" in line: + pass + elif ""all CONECT"" in line: + pass + elif ""with zero occupancy"" in line: + pass + elif ""check: Warnings:"" in line: + pass + else: + print(line) + elif ""Total charge"" in line: + print("" "", line) + elif ""ERROR"" in line.upper(): + if ""Fatal error"" in line: + print(line, lines[count + 1]) + else: + print(line) + count += 1 + + +def fixRes4Acpype(fpdb): + code = fpdb[2] + fLines = open(fpdb).readlines() + famb = open(fpdb, ""w"") + for line in fLines: + if ""ATOM "" in line: + line = line[:17] + aa_dict[code].upper() + line[20:] + famb.write(line) + famb.close() + + +def build_residues_tleap(): + """"""Build residues tripeptides with tleap and minimise with sander"""""" + mdin = """"""Minimization\n&cntrl\nimin=1, maxcyc=200, ntmin=2, ntb=0, igb=0,cut=999,/\n"""""" + open(""mdin"", ""w"").writelines(mdin) + seqi = aa_dict.keys() + for aai in seqi: + # if aai != 'H': continue + aai3 = 3 * aai + res = aa_dict.get(aai).upper() + res1 = res + leapDict = {""amberff"": amberff, ""res"": res, ""aai3"": aai3, ""res1"": res1} + tleapin = genPdbTemplate % leapDict + open(""tleap.in"", ""w"").writelines(tleapin) + cmd = ""%s -f tleap.in"" % (tleapExe) + _getoutput(cmd) + # cmd = ""%s -O; %s < restrt > %s.pdb; mv mdinfo %s.mdinfo"" % (sanderExe, ambpdbExe, aai3, aai3) + # -i mdin -o mdout -p prmtop -c inpcrd"" % (sanderExe) + cmd = f""{sanderExe} -O; {ambpdbExe} -c restrt > {aai3}.pdb"" + _getoutput(cmd) + _getoutput(""rm -f mdout mdinfo mdin restrt tleap.in prmtop inpcrd leap.log"") + + +def error(v1, v2): + """"""percentage relative error"""""" + if v1 == v2: + return 0 + return abs(v1 - v2) / max(abs(v1), abs(v2)) * 100 + + +def calcGmxPotEnerDiff(res): + def getEnergies(template): + cmd = template % cmdDict + pdebug(cmd) + out = _getoutput(cmd) + out = out.split(""\n"")[-nEner:] + dictEner = {} + for item in out: + k, v = ( + item.replace("" Dih."", ""_Dih."") + .replace("" (SR)"", ""_(SR)"") + .replace(""c En."", ""c_En."") + .replace("" (bar)"", ""_(bar)"") + .replace(""l E"", ""l_E"") + .split()[:2] + ) + v = eval(v) + dictEner[k] = v + if ""Dih."" in k or ""Bell."" in k: + if ""Dihedral P+I"" in list(dictEner.keys()): + dictEner[""Dihedral P+I""] = dictEner[""Dihedral P+I""] + v + else: + dictEner[""Dihedral P+I""] = v + if ""Coulomb"" in k or ""LJ"" in k: + if ""TotalNonBonded"" in list(dictEner.keys()): + dictEner[""TotalNonBonded""] = dictEner[""TotalNonBonded""] + v + else: + dictEner[""TotalNonBonded""] = v + dictEner[""Total_Bonded""] = dictEner.get(""Potential"") - dictEner.get(""TotalNonBonded"") + return dictEner + + os.chdir(tmpDir) + nEner = 9 # number of energy entries from g_energy + tEner = "" "".join([str(x) for x in range(1, nEner + 1)]) + open(""SPE.mdp"", ""w"").writelines(spe_mdp) + cmdDict = { + ""pdb2gmx"": pdb2gmx, + ""grompp"": grompp, + ""mdrun"": mdrun, + ""res"": res, + ""g_energy"": g_energy, + ""tEner"": tEner, + ""water"": water, + ""gmxdump"": gmxdump, + } + + # calc Pot Ener for aXXX.pdb (AMB_GMX) + template = """"""%(pdb2gmx)s -ff amber99sb -f a%(res)s.pdb -o a%(res)s_.pdb -p a%(res)s.top %(water)s + %(grompp)s -c a%(res)s_.pdb -p a%(res)s.top -f SPE.mdp -o a%(res)s.tpr -pp a%(res)sp.top + %(mdrun)s -v -deffnm a%(res)s + echo %(tEner)s | %(g_energy)s -f a%(res)s.edr + """""" + dictEnerAMB = getEnergies(template) + # print(dictEnerAMB) + + # calc Pot Ener for agXXX.acpype/agXXX.pdb (ACPYPE_GMX) + template = """""" + %(grompp)s -c ag%(res)s.acpype/ag%(res)s_NEW.pdb -p ag%(res)s.acpype/ag%(res)s_GMX.top -f SPE.mdp \ + -o ag%(res)s.tpr -pp ag%(res)sp.top + %(mdrun)s -v -deffnm ag%(res)s + echo %(tEner)s | %(g_energy)s -f ag%(res)s.edr + """""" + dictEnerACPYPE = getEnergies(template) + # print(dictEnerACPYPE) + + order = [ + ""LJ-14"", + ""LJ_(SR)"", + ""Coulomb-14"", + ""Coulomb_(SR)"", + ""TotalNonBonded"", + ""Potential"", + ""Angle"", + ""Bond"", + ""Proper_Dih."", + ""Improper_Dih."", + ""Dihedral P+I"", + ""Total_Bonded"", + ] # sorted(dictEnerAMB.items()) + for k in order: + v = dictEnerAMB.get(k) + v2 = dictEnerACPYPE.get(k) + rerror = error(v2, v) + if rerror > 0.1: + print(""%15s %.3f %5.6f x %5.6f"" % (k, rerror, v2, v)) + else: + print(""%15s %.3f"" % (k, rerror)) + + cmd = ""{gmxdump} -s a{res}.tpr"".format(**cmdDict) + amb = _getoutput(cmd) + cmd = ""{gmxdump} -s ag{res}.tpr"".format(**cmdDict) + acp = _getoutput(cmd) + + # dihAmb = [x.split(']=')[-1] for x in amb.splitlines() if ('PIDIHS' in x or 'PDIHS' in x) and 'functype' in x ] + # dihAcp = [x.split(']=')[-1] for x in acp.splitlines() if ('PIDIHS' in x or 'PDIHS' in x) and 'functype' in x ] + + dihAmb = [x.split(""PIDIHS"")[-1][2:] for x in amb.splitlines() if (""PIDIHS"" in x)] + dihAcp = [x.split(""PIDIHS"")[-1][2:] for x in acp.splitlines() if (""PIDIHS"" in x)] + + dAcp = set(dihAcp).difference(set(dihAmb)) + dAmb = set(dihAmb).difference(set(dihAcp)) + rAcp = ["" "".join(reversed(x.split())) for x in dAcp] + rAmb = ["" "".join(reversed(x.split())) for x in dAmb] + ddAmb = sorted(dAmb.difference(rAcp)) + ddAcp = sorted(dAcp.difference(rAmb)) + if ddAmb: + print(""IDIH: Amb diff Acp"", ddAmb) + if ddAcp: + print(""IDIH: Acp diff Amb"", ddAcp) + + return dihAmb, dihAcp + + +if __name__ == ""__main__"": + """"""order: (tleap/EM or pymol) AAA.pdb -f-> _AAA.pdb -f-> aAAA.pdb + --> (pdb2gmx) agAAA.pdb -f-> agAAA.pdb --> acpype"""""" + aNb = nbDict(open(gmxTopDir + ""/gromacs/top/amber99sb.ff/ffnonbonded.itp"").readlines()) + aBon = parseTopFile(open(gmxTopDir + ""/gromacs/top/amber99sb.ff/ffbonded.itp"").readlines()) + + tmpFile = ""tempScript.py"" + if not os.path.exists(tmpDir): + os.mkdir(tmpDir) + os.chdir(tmpDir) + os.system(r""rm -fr \#* *.acpype"") + # create res.pdb + if usePymol: + ff = open(tmpFile, ""w"") + ff.writelines(pymolScript) + ff.close() + cmd = f""{exePymol} -qc {tmpFile}"" + os.system(cmd) + else: + build_residues_tleap() + listRes = os.listdir(""."") # list all res.pdb + listRes = glob(""???.pdb"") + listRes.sort() + for resFile in listRes: + res, ext = os.path.splitext(resFile) # eg. res = 'AAA' + # if res != 'RRR': continue + if len(resFile) == 7 and ext == "".pdb"" and resFile[:3].isupper(): + print(f""\nFile {resFile} : residue {aa_dict[res[0]].upper()}"") + + _pdb = createOldPdb2(resFile) # using my own dict + apdb = createAmberPdb3(_pdb) # create file aAAA.pdb with NXXX, CXXX + + # from ogpdb to amber pdb and top + agpdb = ""ag%s.pdb"" % res # output name + agtop = ""ag%s.top"" % res + cmd = f"" {pdb2gmx} -f {apdb} -o {agpdb} -p {agtop} -ff amber99sb {water}"" + pdebug(cmd) + out = _getoutput(cmd) + # print(out) + # parseOut(out) + + # acpype on agpdb file + fixRes4Acpype(agpdb) + cv = None + # cmd = ""%s -dfi %s -c %s -a %s"" % (acpypeExe, agpdb, cType, ffType) + if res in [""JJJ"", ""RRR""] and cType == ""bcc"": + cv = 3 # cmd += ' -n 3' # acpype failed to get correct charge + mol = ACTopol(agpdb, chargeType=cType, atomType=ffType, chargeVal=cv, debug=False, verbose=debug) + mol.createACTopol() + mol.createMolTopol() + + # out = commands.getstatusoutput(cmd) + # parseOut(out[1]) + print(""Compare ACPYPE x GMX AMBER99SB topol & param"") + checkTopAcpype(res) + # calc Pot Energy + print(""Compare ACPYPE x GMX AMBER99SB Pot. Energy (|ERROR|%)"") + # calc gmx amber energies + dihAmb, dihAcp = calcGmxPotEnerDiff(res) + # calc gmx acpype energies + + os.system(r""rm -f %s/\#* posre.itp tempScript.py"" % tmpDir) + os.system(""find . -name 'ag*GMX*.itp' | xargs grep -v 'created by acpype on' > standard_ag_itp.txt"") +","Python" +"Computational Biochemistry","alanwilter/acpype","scripts/script_test.sh",".sh","5972","181","#!/usr/bin/env bash + +rm -fr temp_test + +mkdir -p temp_test + +cd temp_test || exit + +pdb2gmx=""/sw/bin/pdb2gmx"" +editconf=""/sw/bin/editconf"" +genbox=""/sw/bin/genbox"" +genion=""/sw/bin/genion"" +grompp=""/sw/bin/grompp"" +mdrun=""/sw/bin/mdrun"" +mrun="""" #""${mrun}"" + +echo -e ""\n#=#=# Test DMP from 1BVG for GROMACS #=#=#\n"" + +wget -c ""http://www.pdbe.org/download/1BVG"" -O 1BVG.pdb +grep 'ATOM ' 1BVG.pdb >|Protein.pdb +grep 'HETATM' 1BVG.pdb >|Ligand.pdb + +echo -e ""\n#=#=# CHECK 1BVG.pdb"" >|diff_out.log +diff 1BVG.pdb ../Data/1BVG.pdb >>diff_out.log + +# Edit Protein.pdb according to ffAMBER (http://ffamber.cnsm.csulb.edu/#usage) +sed s/PRO\ A\ \ \ 1/NPROA\ \ \ 1/g Protein.pdb | sed s/PRO\ B\ \ \ 1/NPROB\ \ \ 1/g | + sed s/PHE\ A\ \ 99/CPHEA\ \ 99/g | sed s/PHE\ B\ \ 99/CPHEB\ \ 99/g | + sed s/O\ \ \ CPHE/OC1\ CPHE/g | sed s/OXT\ CPHE/OC2\ CPHE/g | + sed s/HIS\ /HID\ /g | sed s/LYS\ /LYP\ /g | sed s/CYS\ /CYN\ /g >|ProteinAmber.pdb + +\cp Protein.pdb ProteinAmber.pdb + +# Process with pdb2gmx and define water +${pdb2gmx} -ff amber99sb -f ProteinAmber.pdb -o Protein2.pdb -p Protein.top -water spce -ignh + +# Generate Ligand topology file with acpype (GAFF) +acpype -i Ligand.pdb + +# Merge Protein2.pdb + updated Ligand_NEW.pdb -> Complex.pdb +grep -h ATOM Protein2.pdb Ligand.acpype/Ligand_NEW.pdb >|Complex.pdb + +# Edit Protein.top -> Complex.top +\cp Ligand.acpype/Ligand_GMX.itp Ligand.itp +\cp Protein.top Complex.top +# '#include ""Ligand.itp""' has to be inserted right after ffamber**.itp line and before Protein_*.itp line in Complex.top. +# shellcheck disable=SC1004 +sed '/forcefield\.itp\""/a\ +#include ""Ligand.itp"" +' Complex.top >|Complex2.top +echo ""Ligand 1"" >>Complex2.top +\mv Complex2.top Complex.top + +echo -e ""\n#=#=# CHECK parm99gaffff99SBparmbsc0File"" >>diff_out.log +# Generate Ligand topology file with acpype (AMBERbsc0) +acpype -i Ligand.pdb -a amber -b Ligand_Amber -c gas +# shellcheck disable=SC2129 +diff -w /tmp/parm99gaffff99SB.dat ../../ffamber_additions/parm99SBgaff.dat >>diff_out.log + +echo -e ""\n#=#=# CHECK Ligand.itp"" >>diff_out.log +diff Ligand.itp ../Data/Ligand.itp >>diff_out.log + +# Setup the box and add water +${editconf} -bt triclinic -f Complex.pdb -o Complex.pdb -d 1.0 +${genbox} -cp Complex.pdb -cs ffamber_tip3p.gro -o Complex_b4ion.pdb -p Complex.top + +# Create em.mdp file +cat <|EM.mdp +define = -DFLEXIBLE +integrator = cg ; steep +nsteps = 200 +constraints = none +emtol = 1000.0 +nstcgsteep = 10 ; do a steep every 10 steps of cg +emstep = 0.01 ; used with steep +nstcomm = 1 +coulombtype = PME +ns_type = grid +rlist = 1.0 +rcoulomb = 1.0 +rvdw = 1.4 +Tcoupl = no +Pcoupl = no +gen_vel = no +nstxout = 0 ; write coords every # step +optimize_fft = yes +EOF + +# Create md.mdp file +cat <|MD.mdp +integrator = md +nsteps = 1000 +dt = 0.002 +constraints = all-bonds +nstcomm = 1 +ns_type = grid +rlist = 1.2 +rcoulomb = 1.1 +rvdw = 1.0 +vdwtype = shift +rvdw-switch = 0.9 +coulombtype = PME-Switch +Tcoupl = v-rescale +tau_t = 0.1 0.1 +tc-grps = protein non-protein +ref_t = 300 300 +Pcoupl = parrinello-rahman +Pcoupltype = isotropic +tau_p = 0.5 +compressibility = 4.5e-5 +ref_p = 1.0 +gen_vel = yes +nstxout = 2 ; write coords every # step +lincs-iter = 2 +DispCorr = EnerPres +optimize_fft = yes +EOF + +# Setup ions +${grompp} -f EM.mdp -c Complex_b4ion.pdb -p Complex.top -o Complex_b4ion.tpr +\cp Complex.top Complex_ion.top +echo 15 | ${genion} -s Complex_b4ion.tpr -o Complex_b4em.pdb -neutral -conc 0.15 -p Complex_ion.top -norandom +\mv Complex_ion.top Complex.top + +# Run minimisaton +#${grompp} -f EM.mdp -c Complex_b4em.pdb -p Complex.top -o em.tpr +#${mdrun} -v -deffnm em + +# Run a short simulation +#${grompp} -f MD.mdp -c em.gro -p Complex.top -o md.tpr +#${mdrun} -v -deffnm md + +# or with openmpi, for a dual core +${grompp} -f EM.mdp -c Complex_b4em.pdb -p Complex.top -o em.tpr +${mrun} ${mdrun} -v -deffnm em +${grompp} -f MD.mdp -c em.gro -p Complex.top -o md.tpr +${mrun} ${mdrun} -v -deffnm md +# vmd md.gro md.trr + +echo -e ""\n#=#=# Test 'amb2gmx' Function on 1BVG #=#=#\n"" + +# Edit 1BVG.pdb and create ComplexAmber.pdb +sed s/HIS\ /HID\ /g 1BVG.pdb | sed s/H1\ \ PRO/H3\ \ PRO/g >|ComplexAmber.pdb + +# Create a input file with commands for tleap and run it +cat <|leap.in +verbosity 1 +source leaprc.ff99SB +source leaprc.gaff +loadoff Ligand.acpype/Ligand_AC.lib +loadamberparams Ligand.acpype/Ligand_AC.frcmod +complex = loadpdb ComplexAmber.pdb +solvatebox complex TIP3PBOX 10.0 +addions complex Na+ 23 +addions complex Cl- 27 +saveamberparm complex ComplexAmber.prmtop ComplexAmber.inpcrd +savepdb complex ComplexNAMD.pdb +quit +EOF +tleap -f leap.in >|leap.out + +# convert AMBER to GROMACS +acpype -p ComplexAmber.prmtop -x ComplexAmber.inpcrd + +# shellcheck disable=SC2129 +echo -e ""\n#=#=# CHECK ComplexAmber_GMX.top & ComplexAmber_GMX.gro"" >>diff_out.log +diff ComplexAmber_GMX.top ../Data/ComplexAmber_GMX.top >>diff_out.log +diff ComplexAmber_GMX.gro ../Data/ComplexAmber_GMX.gro >>diff_out.log + +# Run EM and MD +${grompp} -f EM.mdp -c ComplexAmber_GMX.gro -p ComplexAmber_GMX.top -o em.tpr +${mrun} ${mdrun} -v -deffnm em +${grompp} -f MD.mdp -c em.gro -p ComplexAmber_GMX.top -o md.tpr +${mrun} ${mdrun} -v -deffnm md +# vmd md.gro md.trr + +echo ""############################"" +echo ""####### DIFF SUMMARY #######"" +echo ""############################"" +cat diff_out.log +","Shell" +"Computational Biochemistry","alanwilter/acpype","scripts/compare_itps.py",".py","3220","110","#!/usr/bin/env python +import sys + + +def parseItpFile(lista): + parDict = {} + for line in lista: + line = line.split("";"")[0] + line = line.strip() + if line and not line.startswith(""#""): + if line.startswith(""[ ""): + flag = line.split()[1] + if flag not in parDict: + parDict[flag] = [] + else: + u = [] + t = line.split() + for i in t: + try: + v = eval(i) + except Exception: + v = i + u.append(v) + parDict[flag].append(u) + return parDict + + +def compareDicts(d1, d2): + flags = [(""pairs"", 2), (""bonds"", 2), (""angles"", 3), (""dihedrals"", 4)] + + for flag, ll in flags: + print("" ==> Comparing %s"" % flag) + flagD1 = [x[: ll + 1] for x in d1[flag]] + flagD2 = [x[: ll + 1] for x in d2[flag]] + + tempD1 = flagD1[:] + tempD2 = flagD2[:] + + _tempD1 = tempD1[:] + _tempD2 = tempD2[:] + + for item in tempD1: + if str(item) in str(tempD2): + try: + _tempD1.remove(item) + except Exception: + print(f""\tDuplicate item {item!r} in {flag} itp2"") + try: + _tempD2.remove(item) + except Exception: + print(f""\tDuplicate item {item!r} in {flag} itp1"") + else: + t = item[:-1] + t.reverse() + itemRev = [*t, item[-1]] + if str(itemRev) in str(tempD2): + try: + _tempD1.remove(item) + except Exception: + print(f""\tDuplicate item {item!r} in {flag} itp2"") + try: + _tempD2.remove(itemRev) + except Exception: + print(f""\tDuplicate item {item!r} in {flag} itp1"") + + tD1 = _tempD1[:] + tD2 = _tempD2[:] + + if _tempD1 and _tempD2: + # specially for dih since it may need to resort indexes + i2l = {} + for i2 in tD2: + t = i2[:-1] + t.sort() + i2s = [*t, i2[-1]] + i2l[str(i2s)] = i2 + for i1 in tD1: + t = i1[:-1] + t.sort() + i1s = [*t, i1[-1]] + if str(i1s) in str(list(i2l.keys())): + tD1.remove(i1) + tD2.remove(i2l[str(i1s)]) + + if tD1: + tD1.sort() + print("" itp1: "", tD1) + if tD2: + tD2.sort() + print("" itp2: "", tD2) + + if not tD1 and not tD2: + print("" %s OK"" % flag) + + +if __name__ == ""__main__"": + if len(sys.argv) != 3: + print(""ERROR: it needs 2 itp file as input"") + print("" compare_itps.py file1.itp file2.itp"") + sys.exit() + itp1, itp2 = sys.argv[1:3] + + listItp1 = open(itp1).readlines() + listItp2 = open(itp2).readlines() + + dictItp1 = parseItpFile(listItp1) + dictItp2 = parseItpFile(listItp2) + + compareDicts(dictItp1, dictItp2) +","Python" +"Computational Biochemistry","alanwilter/acpype","scripts/analyse_test_acpype_db_ligands.py",".py","30611","919","#!/usr/bin/env python +import fnmatch +import os +import sys + +from acpype.utils import _getoutput + +# Gmm with 200 atoms, biggest OK + +# usage: ./analyse_test_acpype_db_ligands.py (opt: n=10 or ""['001','Rca']"") + +# semi-QM = mopac (AT 1.2) or sqm (AT 1.3) + + +global id +id = 1 + +atomicDetailed = True + +checkChargeComparison = True + +results = {} + +ccpCodes = os.listdir(""other"") +ccpCodes.sort() + +groupResults = [ + [ + ""dirs totally empty or at least missing one *.mol2 input files for either PDB or IDEAL)"", + ""Dirs missing *.mol2 input files"", + [], + ], + [""still running presumably"", ""Mols still running presumably"", [""0 E, 0 W, ET , WT ""]], + [ + ""mols clean, no erros or warnings"", + ""Mols clean"", + [ + ""0 E, 1 W, ET , WT _0"", + ""0 E, 2 W, ET , WT _0_1"", + ""0 E, 2 W, ET , WT _0_2"", + ""0 E, 3 W, ET , WT _0_1_2"", + ""0 E, 2 W, ET , WT _0_3"", + ""0 E, 3 W, ET , WT _0_1_3"", + ""0 E, 3 W, ET , WT _0_2_3"", + ""0 E, 4 W, ET , WT _0_1_2_3"", + ""0 E, 2 W, ET , WT _0_8"", + ], + ], + [ + ""only guessCharge failed, but running semi-QM with charge = 0 finished fine"", + ""Mols only guessCharge failed"", + [ + ""1 E, 1 W, ET _0, WT _0"", + ""1 E, 2 W, ET _0, WT _0_1"", + ""1 E, 2 W, ET _0, WT _0_2"", + ""1 E, 3 W, ET _0, WT _0_1_2"", + ], + ], + [ + ""atoms in close contact"", + ""Mols have atoms in close contact"", + [ + ""0 E, 2 W, ET , WT _0_7"", + ""0 E, 3 W, ET , WT _0_1_7"", + ""0 E, 3 W, ET , WT _0_2_7"", + ""0 E, 3 W, ET , WT _0_3_7"", + ""0 E, 4 W, ET , WT _0_1_2_7"", + ""0 E, 4 W, ET , WT _0_1_3_7"", + ""0 E, 4 W, ET , WT _0_2_3_7"", + ""0 E, 5 W, ET , WT _0_1_2_3_7"", + ], + ], + [ + ""irregular bonds"", + ""Mols have irregular bonds"", + [ + ""0 E, 2 W, ET , WT _0_5"", + ""0 E, 3 W, ET , WT _0_1_5"", + ""0 E, 3 W, ET , WT _0_2_5"", + ""0 E, 4 W, ET , WT _0_1_2_5"", + ], + ], + [ + ""irregular bonds and atoms in close contact"", + ""Mols have irregular bonds and atoms in close contact"", + [ + ""0 E, 3 W, ET , WT _0_5_7"", + ""0 E, 4 W, ET , WT _0_1_5_7"", + ""0 E, 4 W, ET , WT _0_2_5_7"", + ""0 E, 5 W, ET , WT _0_1_2_5_7"", + ""0 E, 6 W, ET , WT _0_1_2_3_5_7"", + ""0 E, 4 W, ET , WT _0_3_5_7"", + ], + ], + [ + ""couldn't determine all parameters"", + ""Mols have missing parameters"", + [""0 E, 3 W, ET , WT _0_2_4"", ""0 E, 3 W, ET , WT _0_1_4"", ""0 E, 2 W, ET , WT _0_4""], + ], + [ + ""missing parameters and atoms in close contact"", + ""Mols have missing parameters and atoms in close contact"", + [""0 E, 4 W, ET , WT _0_1_4_7""], + ], + [ + ""missing parameters, irregular bonds and atoms in close contact"", + ""Mols have missing parameters, irregular bonds and atoms in close contact"", + [""0 E, 5 W, ET , WT _0_2_4_5_7""], + ], + [ + ""missing parameters, irregular bonds, maybe wrong atomtype and atoms in close contact"", + ""Mols have missing parameters, irregular bonds, maybe wrong atomtype and atoms in close contact"", + [""0 E, 5 W, ET , WT _0_4_5_6_7""], + ], + [""no 'tmp', acpype did nothing at all"", ""Mols have no 'tmp'"", [""1 E, 0 W, ET _7, WT ""]], + [""atoms with same coordinates"", ""Mols have duplicated coordinates"", [""1 E, 0 W, ET _1, WT ""]], + [ + ""maybe wrong atomtype"", + ""Mols with maybe wrong atomtype"", + [ + ""0 E, 2 W, ET , WT _0_6"", + ""0 E, 3 W, ET , WT _0_1_6"", + ""0 E, 4 W, ET , WT _0_1_3_6"", + ""0 E, 3 W, ET , WT _0_3_6"", + ], + ], + [ + ""maybe wrong atomtype and atoms in close contact"", + ""Mols with maybe wrong atomtype and atoms in close contact"", + [""0 E, 4 W, ET , WT _0_1_6_7"", ""0 E, 3 W, ET , WT _0_6_7"", ""0 E, 4 W, ET , WT _0_3_6_7""], + ], + [ + ""irregular bonds, maybe wrong atomtype and atoms in close contact"", + ""Mols with irregular bonds, maybe wrong atomtype and atoms in close contact"", + [""0 E, 5 W, ET , WT _0_1_5_6_7""], + ], + [ + ""guessCharge failed and atoms in close contact"", + ""Mols have guessCharge failed and atoms in close contact"", + [""1 E, 3 W, ET _0, WT _0_1_7"", ""1 E, 3 W, ET _0, WT _0_2_7"", ""1 E, 4 W, ET _0, WT _0_1_2_7""], + ], + [ + ""guessCharge failed and missing parameters"", + ""Mols have guessCharge failed and missing parameters"", + [ + ""1 E, 2 W, ET _0, WT _0_4"", + ""1 E, 3 W, ET _0, WT _0_1_4"", + ""1 E, 3 W, ET _0, WT _0_2_4"", + ""1 E, 4 W, ET _0, WT _0_1_2_4"", + ], + ], + [ + ""guessCharge failed and maybe wrong atomtype"", + ""Mols have guessCharge failed and maybe wrong atomtype"", + [ + ""1 E, 2 W, ET _0, WT _0_6"", + ""1 E, 3 W, ET _0, WT _0_1_6"", + ""1 E, 3 W, ET _0, WT _0_2_6"", + ""1 E, 4 W, ET _0, WT _0_1_2_6"", + ], + ], + [ + ""guessCharge failed and irregular bonds"", + ""Mols have guessCharge failed and irregular bonds"", + [""1 E, 3 W, ET _0, WT _0_2_5""], + ], + [ + ""guessCharge failed, missing parameters and maybe wrong atomtype"", + ""Mols have guessCharge failed, missing parameters and maybe wrong atomtype"", + [""1 E, 3 W, ET _0, WT _0_4_6"", ""1 E, 4 W, ET _0, WT _0_1_4_6"", ""1 E, 4 W, ET _0, WT _0_2_4_6""], + ], + [ + ""guessCharge failed, irregular bonds and maybe wrong atomtype"", + ""Mols have guessCharge failed, irregular bonds and maybe wrong atomtype"", + [""1 E, 4 W, ET _0, WT _0_2_5_6"", ""0 E, 3 W, ET , WT _0_5_6""], + ], + [ + ""guessCharge failed, missing parameters and atoms in close contact"", + ""Mols have guessCharge failed, missing parameters and atoms in close contact"", + [""1 E, 3 W, ET _0, WT _0_4_7"", ""1 E, 4 W, ET _0, WT _0_2_4_7""], + ], + [ + ""guessCharge failed, maybe wrong atomtype and atoms in close contact"", + ""Mols have guessCharge failed, maybe wrong atomtype and atoms in close contact"", + [ + ""1 E, 3 W, ET _0, WT _0_6_7"", + ""1 E, 4 W, ET _0, WT _0_1_6_7"", + ""1 E, 4 W, ET _0, WT _0_2_6_7"", + ""1 E, 5 W, ET _0, WT _0_1_2_6_7"", + ], + ], + [ + ""guessCharge failed, irregular bonds and atoms in close contact"", + ""Mols have guessCharge failed, irregular bonds and atoms in close contact"", + [""1 E, 4 W, ET _0, WT _0_2_5_7""], + ], + [ + ""guessCharge failed, irregular bonds, maybe wrong atomtype and atoms in close contact"", + ""Mols have guessCharge failed, irregular bonds, maybe wrong atomtype and atoms in close contact"", + [""1 E, 5 W, ET _0, WT _0_1_5_6_7"", ""1 E, 5 W, ET _0, WT _0_2_5_6_7""], + ], + [""atoms too close"", ""Mols have atoms too close"", [""1 E, 0 W, ET _2, WT ""]], + [""atoms too alone"", ""Mols have atoms too alone"", [""1 E, 0 W, ET _3, WT ""]], + [""tleap failed"", ""Mols have tleap failed"", [""3 E, 1 W, ET _4_5_6, WT _0"", ""3 E, 2 W, ET _4_5_6, WT _0_1""]], + [ + ""tleap failed, maybe wrong atomtype"", + ""Mols have tleap failed and maybe wrong atomtype"", + [""3 E, 3 W, ET _4_5_6, WT _0_1_6"", ""3 E, 2 W, ET _4_5_6, WT _0_6""], + ], + [""semi-QM timeout"", ""Mols have semi-QM timeout"", [""1 E, 2 W, ET _9, WT _0_1"", ""1 E, 1 W, ET _9, WT _0""]], + [ + ""semi-QM timeout and maybe wrong atomtype"", + ""Mols have semi-QM timeout and maybe wrong atomtype"", + [""1 E, 3 W, ET _9, WT _0_1_6"", ""1 E, 2 W, ET _9, WT _0_6""], + ], + [ + ""guessCharge and tleap failed"", + ""Mols have guessCharge and tleap failed"", + [""4 E, 1 W, ET _0_4_5_6, WT _0"", ""4 E, 2 W, ET _0_4_5_6, WT _0_1""], + ], + [ + ""guessCharge and tleap failed, maybe wrong atomtype"", + ""Mols have guessCharge and tleap failed, maybe wrong atomtype"", + [""4 E, 2 W, ET _0_4_5_6, WT _0_6"", ""4 E, 3 W, ET _0_4_5_6, WT _0_1_6""], + ], + [ + ""guessCharge failed and semi-QM timeout"", + ""Mols have guessCharge failed and semi-QM timeout"", + [""2 E, 1 W, ET _0_9, WT _0""], + ], + [ + ""atoms with same coordinates and maybe wrong atomtype"", + ""Mols have atoms with same coordinates and maybe wrong atomtype"", + [""1 E, 1 W, ET _1, WT _6""], + ], + [ + ""atoms too close and maybe wrong atomtype"", + ""Mols have atoms too close and maybe wrong atomtype"", + [""1 E, 1 W, ET _2, WT _6""], + ], + [ + ""atoms too alone and maybe wrong atomtype"", + ""Mols have atoms too alone and maybe wrong atomtype"", + [""1 E, 1 W, ET _3, WT _6""], + ], + [ + ""atoms with same coordinates and too close"", + ""Mols have atoms with same coordinates and too close"", + [""2 E, 0 W, ET _1_2, WT ""], + ], + [ + ""atoms with same coordinates and too alone"", + ""Mols have atoms with same coordinates and too alone"", + [""2 E, 0 W, ET _1_3, WT ""], + ], + [ + ""atoms with same coordinates, too alone and maybe wrong atomtype"", + ""Mols have atoms with same coordinates, too alone and maybe wrong atomtype"", + [""2 E, 1 W, ET _1_3, WT _6""], + ], + [ + ""atoms with same coordinates, too close and too alone"", + ""Mols have atoms with same coordinates, too close and too alone"", + [""3 E, 0 W, ET _1_2_3, WT ""], + ], +] + +error_warn_messages = """""" + warnType 0 = 'no charge value given, trying to guess one...' + warnType 1 = ""In ..., residue name will be 'R instead of ... elsewhere"" + warnType 2 = 'residue label ... is not all UPPERCASE' + + # mild warning (need to be sure the charge guessed is correct) + warnType 3 = ""The unperturbed charge of the unit ... is not zero"" + + # serious warnings (topology not reliable): + warnType 4 = ""Couldn't determine all parameters"" + warnType 5 = 'There is a bond of ... angstroms between' + warnType 6 = 'atom type may be wrong' + warnType 7 = 'Close contact of ... angstroms between ...' + + #warnType 8 = 'no 'babel' executable, no PDB file as input can be used!' + warnType 8 = ""residue name will be 'MOL' instead of"" + warnType 9 = 'UNKNOWN WARN' + + errorType 0 = 'guessCharge failed' # (not so serious if only err or because semi-QM worked with charge Zero) + errorType 1 = 'Atoms with same coordinates in' + errorType 2 = 'Atoms TOO close' + errorType 3 = 'Atoms TOO alone' + errorType 4 = 'Antechamber failed' + errorType 5 = 'Parmchk failed' + errorType 6 = 'Tleap failed' + errorType 7 = ""No such file or directory: 'tmp'"" # can be bondtyes wrong or wrong frozen atom type + errorType 8 = 'syntax error' + errorType 9 = 'Semi-QM taking too long to finish' + errorType 10 = 'UNKNOWN ERROR' +"""""" + +totalPdbOkCount = 0 +totalIdealOkCount = 0 +totalIdealMol2Count = 0 +totalPdbMol2Count = 0 + +emptyDir = [] +failedPdb = [] +failedIdeal = [] +failedBoth = [] +missPdbMol2 = [] +missIdealMol2 = [] +multIdealMol2 = [] +multPdbMol2 = [] + +ET0 = [] +ET1 = [] +ET2 = [] +ET3 = [] +ET4 = [] +ET5 = [] +ET6 = [] +ET7 = set() +ET8 = set() +ET9 = [] + +WT3 = set() +WT4 = [] +WT5 = set() +WT6 = set() +WT7 = set() + +mapResults = {} + +execTime = {} + +compareCharges = set() +compareChargesOK = set() +# ==> Trying with net charge = 0 ... +# ==> ... charge set to 0 +# Overall charge: 0 + +SCFfailedList = [] + + +def analyseFile(mol, structure, file): + """""" + mol = string molDir, e.g. 'Gnp' + structure = string 'pdb' or 'ideal' + file = string e.g. '10a/10a.none_neutral.pdb.out' + returns e.g. 'pdb: 0 E, 3 W, ET , WT _0_1_7' + """""" + # _flagChargeType = None # if charge was guesed correctly ('Y') or tried with 0 ('Z' for Zero) + guessChargeValue = None + warnTypes = """" + errorTypes = """" + tmpFile = open(file) + content = tmpFile.readlines() + for line in content: + if ""WARNING: "" in line: + if ""no charge value given"" in line: + warnTypes += ""_0"" + elif ""residue name will be 'R"" in line: + warnTypes += ""_1"" + elif ""not all UPPERCASE"" in line: + warnTypes += ""_2"" + elif ""applications like CNS"" in line: + pass + elif ""The unperturbed charge of the"" in line: + warnTypes += ""_3"" + charge = round(float(line[44:54])) + WT3.add(f""{mol}: {charge}"") + elif ""Couldn't determine all parameters"" in line: + warnTypes += ""_4"" + WT4.append(f""{mol}_{structure}"") + elif ""There is a bond of"" in line: + warnTypes += ""_5"" + # _dist = round(float(line[27:37])) + WT5.add(f""{mol}_{structure}"") + elif "" atom type of "" in line: + warnTypes += ""_6"" + WT6.add(f""{mol}_{structure}"") + # elif ""no 'babel' executable, no PDB"" in line: + elif ""residue name will be 'MOL' instead of"" in line: + warnTypes += ""_8"" + else: + print(""UNKNOWN WARN:"", file, line) + warnTypes += ""_9"" + if ""Warning: Close contact of "" in line: + warnTypes += ""_7"" + WT7.add(f""{mol}_{structure}"") + + if ""ERROR: "" in line: + if ""guessCharge failed"" in line: + errorTypes += ""_0"" + ET0.append(f""{mol}_{structure}"") + elif ""Atoms with same coordinates in"" in line: + errorTypes += ""_1"" + ET1.append(f""{mol}_{structure}"") + elif ""Atoms TOO close"" in line: + errorTypes += ""_2"" + ET2.append(f""{mol}_{structure}"") + elif ""Atoms TOO alone"" in line: + errorTypes += ""_3"" + ET3.append(f""{mol}_{structure}"") + elif ""Antechamber failed"" in line: + errorTypes += ""_4"" + ET4.append(f""{mol}_{structure}"") + elif ""Parmchk failed"" in line: + errorTypes += ""_5"" + ET5.append(f""{mol}_{structure}"") + elif ""Tleap failed"" in line: + errorTypes += ""_6"" + ET6.append(f""{mol}_{structure}"") + elif ""syntax error"" in line: + errorTypes += ""_8"" + ET8.add(f""{mol}_{structure}"") + elif ""Use '-f' option if you want to proceed anyway. Aborting"" in line: + pass + else: + print(""UNKNOWN ERROR:"", file, line) + errorTypes += ""_10"" + if ""No such file or directory: 'tmp'"" in line: + errorTypes += ""_7"" + ET7.add(f""{mol}_{structure}"") + if ""Semi-QM taking too long to finish"" in line: + errorTypes += ""_9"" + ET9.append(f""{mol}_{structure}"") + if ""Total time of execution:"" in line: + if mol in execTime: + # execTime[mol].append({structure:line[:-1].split(':')[1]}) + execTime[mol][structure] = line[:-1].split("":"")[1] + else: + # execTime[mol] = [{structure:line[:-1].split(':')[1]}] + execTime[mol] = {structure: line[:-1].split("":"")[1]} + # to compare charges from acpype out with input mol2 + if ""==> ... charge set to"" in line: + guessChargeValue = int(line.split(""to"")[1]) + # _flagChargeType = ""Y"" + # print ""*%s*"" % guessChargeValue + elif ""Trying with net charge ="" in line: + guessChargeValue = 0 + # _flagChargeType = ""Z"" + + if checkChargeComparison: + mol2FileName = file.replace("".out"", "".mol2"") + mol2File = open(mol2FileName).readlines() + for line in mol2File: + if ""# Overall charge:"" in line: + mol2Charge = int(line.split("":"")[1]) + if guessChargeValue: + if mol2Charge != guessChargeValue: + compareCharges.add(""%s_%i_%i"" % (mol, mol2Charge, guessChargeValue)) + else: + compareChargesOK.add(""%s_%i"" % (mol, mol2Charge)) + # this excpetion should happen only if acpype early aborted for both outs + # if mol not in `compareChargesOK.union(compareCharges)`: + if mol not in repr(compareChargesOK) and mol not in repr(compareCharges): + print(""!!!! Unable to compare. Failed to guess charge for"", mol, structure) + + out = parseSummurisedLine(warnTypes, errorTypes) + if out in mapResults: + if mol in mapResults[out]: + mapResults[out][mol].append(structure) + else: + mapResults[out][mol] = [structure] + else: + mapResults[out] = {mol: [structure]} + return out + + +def parseSummurisedLine(warnTypes, errorTypes): + wt = list(set(warnTypes.split(""_""))) + if wt != [""""]: + wt = wt[1:] + wt.sort(cmp=lambda x, y: int(x) - int(y)) + warnTypes = """" + for i in wt: + if i: + warnTypes += ""_"" + i + countWarn = warnTypes.count(""_"") + et = list(set(errorTypes.split(""_""))) + et.sort() + errorTypes = """" + for j in et: + if j: + errorTypes += ""_"" + j + countError = errorTypes.count(""_"") + return ""%i E, %i W, ET %s, WT %s"" % (countError, countWarn, errorTypes, warnTypes) + + +def parseChargeList(WT, dList): + listOk = [] + for wt in WT: + if wt.split("":"")[0] in dList: + listOk.append(wt) + listOk.sort() + return listOk + + +def myComp(vx, vy): + ix = int(vx.split()[0]) + iy = int(vy.split()[0]) + tx = vx[-1:] + ty = vy[-1:] + if tx.isdigit(): + x = int(tx) + else: + x = 0 + if ty.isdigit(): + y = int(ty) + else: + y = 0 + + if ix > iy: + return 1 + elif ix == iy: + if x > y: + return 1 + elif x == y: + return 0 + else: + return -1 + else: + if x > y: + return 1 + elif x == y: + return 0 + else: + return -1 + + +def sortList(lista, typeMess): + for mol, ll in list(mapResults[typeMess].items()): + if len(ll) == 2: + lista[0].append(mol) + elif len(ll) == 1: + if ll[0] == ""pdb"": + lista[1].append(mol) + elif ll[0] == ""ideal"": + lista[2].append(mol) + else: + print(""problem with"", typeMess, mol, ll) + return lista + + +def printResults(lista, subHead, header=None): + """""" + print results as + -------------------------------------------------------------------------------- + + *** For results [1], [2], [3], totally empty dirs (NO mol2 input files for either PDB or IDEAL): + + [1] Dirs missing pdb.mol2 input files for both PDB and Ideal: + 0 [] + + [2] Dirs missing pdb.mol2 input files with PDB ONLY, besides [1]: + 0 [] + + [3] Dirs missing pdb.mol2 input files with IDEAL ONLY, besides [1]: + 1 ['006'] + PDB Total: 0 of 20 (0.00%) + IDEAL Total: 1 of 20 (5.00%) + Total: 1 of 20 (5.00%) + -------------------------------------------------------------------------------- + """""" + global id + dList, pList, iList = lista + if not dList and not pList and not iList: + return 0 + dList.sort() + pList.sort() + iList.sort() + id1 = id + 1 + id2 = id + 2 + print(80 * ""-"") + if header: + print(""\n*** For results [%i], [%i], [%i], %s:"" % (id, id1, id2, header)) + print(""\n[%i] %s for both PDB and Ideal:\n%i\t %s"" % (id, subHead, len(dList), str(dList))) + print(""\n[%i] %s with PDB ONLY, besides [%i]:\n%i\t %s"" % (id1, subHead, id, len(pList), str(pList))) + print(""\n[%i] %s with IDEAL ONLY, besides [%i]:\n%i\t %s"" % (id2, subHead, id, len(iList), str(iList))) + pTotal = len(dList) + len(pList) + iTotal = len(dList) + len(iList) + total = pTotal + iTotal + per = total / (allTotal * 0.01) + perPdb = pTotal / (allTotal * 0.01) + perIdeal = iTotal / (allTotal * 0.01) + print(""PDB Total: %i of %i (%3.2f%%)"" % (pTotal, allTotal, perPdb)) + print(""IDEAL Total: %i of %i (%3.2f%%)"" % (iTotal, allTotal, perIdeal)) + print(""Total: %i of %i (%3.2f%%)"" % (total, allTotal, per)) + print(80 * ""-"") + id += 3 + return total + + +def elapsedTime(seconds, suffixes=[""y"", ""w"", ""d"", ""h"", ""m"", ""s""], add_s=False, separator="" ""): + """""" + Takes an amount of seconds and turns it into a human-readable amount of time. + """""" + # the formatted time string to be returned + if seconds == 0: + return ""0s"" + time = [] + + # the pieces of time to iterate over (days, hours, minutes, etc) + # - the first piece in each tuple is the suffix (d, h, w) + # - the second piece is the length in seconds (a day is 60s * 60m * 24h) + parts = [ + (suffixes[0], 60 * 60 * 24 * 7 * 52), + (suffixes[1], 60 * 60 * 24 * 7), + (suffixes[2], 60 * 60 * 24), + (suffixes[3], 60 * 60), + (suffixes[4], 60), + (suffixes[5], 1), + ] + + # for each time piece, grab the value and remaining seconds, and add it to + # the time string + for suffix, length in parts: + value = seconds / length + if value > 0: + seconds = seconds % length + time.append(""{}{}"".format(str(value), (suffix, (suffix, suffix + ""s"")[value > 1])[add_s])) + if seconds < 1: + break + + return separator.join(time) + + +def convertStringTime2Seconds(stringTime): + if ""less"" in stringTime: + return 0 + vecTime = stringTime.split() + totalSec = 0 + for n in vecTime: + if ""h"" in n: + totalSec += eval(n[:-1]) * 3600 + elif ""m"" in n: + totalSec += eval(n[:-1]) * 60 + elif ""s"" in n: + totalSec += eval(n[:-1]) + return totalSec + + +def locate(pattern, root=os.curdir): + """"""Locate all files matching supplied filename pattern in and below + supplied root directory."""""" + for path, _dirs, files in os.walk(os.path.abspath(root)): + for filename in fnmatch.filter(files, pattern): + yield os.path.join(path, filename) + + +os.chdir(""other"") + +# Only run this on 'other'! +if len(sys.argv) > 1: + args = sys.argv[1:] + if args[0].startswith(""n=""): + num = int(args[0][2:]) + ccpCodes = ccpCodes[:num] + else: + args = list(set(eval(args[0]))) + args.sort() + ccpCodes = args + +for molDir in ccpCodes: + # files = os.listdir(molDir) + files = [] + # for dirpath, dirnames, filenames in os.walk(molDir): + # files += filenames + files = list(locate(""*"", molDir)) + results[molDir] = [] + pdb = False + ideal = False + pdbMol2 = False + idealMol2 = False + countPdbMol2 = 1 + countIdealMol2 = 1 + out1 = """" + out2 = """" + pass1 = False + pass2 = False + if not files: + emptyDir.append(molDir) + for file in files: + if ""pdb_NEW.pdb"" in file: + pdb = True + results[molDir].append(""pdb_OK"") + totalPdbOkCount += 1 + elif ""ideal_NEW.pdb"" in file: + ideal = True + results[molDir].append(""ideal_OK"") + totalIdealOkCount += 1 + elif ""ideal.out"" in file: + out1 = analyseFile(molDir, ""ideal"", os.path.join(molDir, file)) + results[molDir].append(""ideal: "" + out1) + elif ""pdb.out"" in file: + out2 = analyseFile(molDir, ""pdb"", os.path.join(molDir, file)) + results[molDir].append(""pdb: "" + out2) + elif "".ideal.mol2"" in file: + if idealMol2: + countIdealMol2 += 1 + else: + idealMol2 = True + totalIdealMol2Count += 1 + elif "".pdb.mol2"" in file: + if pdbMol2: + countPdbMol2 += 1 + else: + pdbMol2 = True + totalPdbMol2Count += 1 + elif "".ideal.acpype/sqm.out"" in file: + content = open(file).read() + if ""No convergence in SCF after"" in content: + SCFfailedList.append(""{}_{}"".format(molDir, ""ideal"")) + elif "".pdb.acpype/sqm.out"" in file: + content = open(file).read() + if ""No convergence in SCF after"" in content: + SCFfailedList.append(""{}_{}"".format(molDir, ""pdb"")) + if countIdealMol2 > 2: + multIdealMol2.append(molDir) + if countPdbMol2 > 2: + multPdbMol2.append(molDir) + if not pdbMol2: + missPdbMol2.append(molDir) + if not idealMol2: + missIdealMol2.append(molDir) + if not pdb: + failedPdb.append(molDir) + if not ideal: + failedIdeal.append(molDir) + if not pdb and not ideal: + failedBoth.append(molDir) + +a, b, c = set(emptyDir), set(missPdbMol2), set(missIdealMol2) +pdbList = list(b.difference(a)) +idealList = list(c.difference(a)) +groupResults[0].append([emptyDir, pdbList, idealList]) + +c = 1 +while c < len(groupResults): + groupResults[c].append([[], [], []]) + c += 1 + +keys = list(mapResults.keys()) +keys.sort() +keys.sort(cmp=myComp) + +# Print messages that was not classified yet +groupMess = [] +for m in groupResults: + groupMess += m[2] +for typeMess in keys: + if typeMess not in groupMess: + size = len(typeMess) + txt = str(mapResults[typeMess]) + Nboth = txt.count(""['pdb', 'ideal']"") + txt.count(""['ideal', 'pdb']"") + Npdb = txt.count(""['pdb']"") + Nideal = txt.count(""['ideal']"") + print(""*%s*%s%i %i %i"" % (typeMess, (40 - size) * "" "", 2 * Nboth, Npdb, Nideal)) + +# Append to groupResults[index] a list of Mols belonging to this group +for typeMess in keys: + index = 0 + for group in groupResults: + msg = group[2] + if typeMess in msg: + groupResults[index][3] = sortList(groupResults[index][3], typeMess) + index += 1 + +allTotal = len(ccpCodes) * 2 +jobsOK = [] # list of Mols that have at least a PDB or IDEAL clean: [[both],[pdb,ideal]] +totalTxt = """" +for group in groupResults: + header, subHead, dummy, lista = group + if ""Mols clean"" == subHead: + jobsOK = lista + subTot = printResults(lista, subHead, header) + if not subTot: + continue + totalTxt += ""+ %i "" % subTot +totalTxt = totalTxt[2:] +sumVal = eval(totalTxt) +print(f""{totalTxt}= {sumVal}"") + +# print results + +# print 'execTime', execTime + +# print 'jobsOK', jobsOK + +if atomicDetailed: + print(""\n>>> Detailed report per atom <<<\n"") + + if ET1: + print(""=>Mols have duplicated coordinates"") + for molLabel in ET1: + mol, structure = molLabel.split(""_"") + cmd = f""grep -e '^ATOM' {mol}/*{structure}.out"" + out = _getoutput(cmd) + print(""# %s #"" % molLabel) + print(out, ""\n"") + + if WT7: + print(""=>Mols have atoms in close contact"") + for molLabel in WT7: + mol, structure = molLabel.split(""_"") + cmd = f""grep -e '^Warning: Close contact of' {mol}/*{structure}.out"" + out = _getoutput(cmd) + print(""# %s #"" % molLabel) + print(out, ""\n"") + + if WT5: + print(""=>Mols have irregular bonds"") + for molLabel in WT5: + mol, structure = molLabel.split(""_"") + cmd = f""grep -A 1 -e '^WARNING: There is a bond of' {mol}/*{structure}.out"" + out = _getoutput(cmd) + print(""# %s #"" % molLabel) + print(out, ""\n"") + + if ET2: + print(""=>Mols have atoms too close"") + for molLabel in ET2: + mol, structure = molLabel.split(""_"") + cmd = f""grep -e '^ .*ATOM' {mol}/*{structure}.out"" + out = _getoutput(cmd) + print(""# %s #"" % molLabel) + print(out, ""\n"") + + if ET3: + print(""=>Mols have atoms too alone"") + for molLabel in ET3: + mol, structure = molLabel.split(""_"") + cmd = rf""""""grep -e ""^\['ATOM"" {mol}/*{structure}.out"""""" + out = _getoutput(cmd) + print(""# %s #"" % molLabel) + print(out, ""\n"") + +# mols with MOL2 charge different from ACPYPE guessed charge +if compareCharges: + print(""\n>>> Mols with MOL2 charge different from ACPYPE guessed charge <<<\n"") + lCC = list(compareCharges) + lCC.sort() + print(len(lCC), lCC) + +maxExecTime = 0 +firstPass = True +maxMolTime = None +minMolTime = None +totalCleanExecTime = 0 +nJobs = 0 +listMolTime = [] +for mol in jobsOK[0]: + listMolTime.append([mol + ""_pdb"", execTime[mol][""pdb""]]) + listMolTime.append([mol + ""_ideal"", execTime[mol][""ideal""]]) +for mol in jobsOK[1]: + listMolTime.append([mol + ""_pdb"", execTime[mol][""pdb""]]) +for mol in jobsOK[2]: + listMolTime.append([mol + ""_ideal"", execTime[mol][""ideal""]]) + +# print 'listMolTime', listMolTime +# print jobsOK + +if SCFfailedList: + SCFfailedList.sort() + print(""\n>>>Mol Jobs whose sqm.out has 'No convergence in SCF'<<<\n"") + print(len(SCFfailedList), SCFfailedList) + molsOKinSCFfailedList = [] + for item in SCFfailedList: + if item in [x[0] for x in listMolTime]: + molsOKinSCFfailedList.append(item) + if molsOKinSCFfailedList: + molsOKinSCFfailedList.sort() + print(""\n>>>Mol Jobs whose sqm.out has 'No convergence in SCF' but finished OK<<<\n"") + print(len(molsOKinSCFfailedList), molsOKinSCFfailedList) + +for item in listMolTime: + mol, jtime = item + tSec = convertStringTime2Seconds(jtime) + # print 'tSec', tSec + if firstPass: + minExecTime = tSec + firstPass = False + # print 'firstPass' + if tSec >= maxExecTime: + maxExecTime = tSec + maxMolTime = mol + if tSec <= minExecTime: + minExecTime = tSec + minMolTime = mol + totalCleanExecTime += tSec + nJobs += 1 + +print(""\n>>> Time Job Execution Summary <<<\n"") +if listMolTime: + # print maxExecTime, minExecTime + print(""Number of clean jobs:"", nJobs) + print(f""Longest job: Mol='{maxMolTime}', time= {elapsedTime(maxExecTime)}"") + print(f""Fatest job: Mol='{minMolTime}', time= {elapsedTime(minExecTime)}"") + print(""Average time of execution per clean job: %s"" % elapsedTime(totalCleanExecTime / nJobs)) +else: + print(""NO time stats available for clean jobs"") + +# Global average exec time +totalGlobalExecTime = 0 +nGJobs = 0 +for item in list(execTime.items()): + mol, tDict = item + if ""pdb"" in tDict: + totalGlobalExecTime += convertStringTime2Seconds(tDict[""pdb""]) + nGJobs += 1 + if ""ideal"" in tDict: + totalGlobalExecTime += convertStringTime2Seconds(tDict[""ideal""]) + nGJobs += 1 +print(""\nTotal number of jobs:"", nGJobs) +if nGJobs: + print(""Global average time of execution per job: %s"" % elapsedTime(totalGlobalExecTime / nGJobs)) + +# mols with charge not 0 +# print WT3 +","Python" +"Computational Biochemistry","alanwilter/acpype","scripts/ambXgmxEner.py",".py","2427","96",""""""" +Script to get energies from AMBER and GROMACS +for a given system and compare them +"""""" + +import re +import sys + +import sander + +from acpype.utils import _getoutput + + +def error(v1, v2): + """"""percentage relative error"""""" + if v1 == v2: + return 0 + return abs(v1 - v2) / max(abs(v1), abs(v2)) * 100 + + +ff = 4.1840 + +vv = [""ANGLE"", ""BOND"", ""DIHED"", ""EPTOT"", ""VDW14"", ""VDW"", ""QQ14"", ""QQ""] +norm_gmx = {""POTENTIAL"": ""EPTOT"", ""LJ-14"": ""VDW14"", ""LJ_SR"": ""VDW"", ""COULOMB-14"": ""QQ14"", ""COULOMB_SR"": ""QQ""} +norm_amb = {""1-4_NB"": ""VDW14"", ""VDWAALS"": ""VDW"", ""1-4_EEL"": ""QQ14"", ""EELEC"": ""QQ""} + +(e_amb, e_gmx) = sys.argv[1:] + +cmd_amb = f""cat {e_amb}"" +cmd_gmx = f""echo 1 2 3 4 5 6 7 8 9 | gmx energy -f {e_gmx}.edr"" + +amb_out = { + y[0].upper(): float(y[1]) * ff + for y in [ + x.split(""="") for x in re.sub(r""\s+=\s+"", ""="", _getoutput(cmd_amb)).strip().replace(""1-4 "", ""1-4_"").split() + ] +} + +for k in list(amb_out.keys())[:]: + v = norm_amb.get(k) + if v: + amb_out[v] = amb_out[k] + +gmx_out = { + y[0].upper(): float(y[1]) + for y in [ + x.split()[:2] + for x in _getoutput(cmd_gmx) + .split(""-"" * 3)[-1][2:] + .replace("" Dih."", ""_Dih"") + .replace("" (SR)"", ""_SR"") + .splitlines() + ] +} +gmx_out[""DIHED""] = gmx_out.get(""PROPER_DIH"", 0) + gmx_out.get(""IMPROPER_DIH"", 0) + gmx_out.get(""RYCKAERT-BELL."", 0) +for k in list(gmx_out.keys())[:]: + v = norm_gmx.get(k) + if v: + gmx_out[v] = gmx_out[k] + +for ii in vv: + print(f""{ii:<10}: {error(gmx_out[ii],amb_out[ii]):-2.5f}%"") + +# DIHED = PROPER_DIH + IMPROPER_DIH + RYCKAERT-BELL. +# VDW14 : LJ-14, 1-4_NB +# VDW : LJ_SR, VDWAALS +# QQ14 : COULOMB-14, 1-4_EEL +# QQ : COULOMB_SR, EELEC + + +# Using gas-phase calculations +inp = sander.gas_input() +f_amb = e_amb.split(""."")[0] +sander.setup(f""{f_amb}.prmtop"", f""{f_amb}.inpcrd"", box=None, mm_options=inp) +e, f = sander.energy_forces() + +ll = [ + (""angle"", ""ANGLE""), + (""bond"", ""BOND""), + (""dihedral"", ""DIHED""), + (""vdw_14"", ""VDW14""), + (""vdw"", ""VDW""), + (""elec_14"", ""QQ14""), + (""elec"", ""QQ""), + (""tot"", ""EPTOT""), +] + +for pp in ll: + v1, v2 = e.__getattribute__(pp[0]), amb_out[pp[1]] / ff + print(f""error {pp[0]:<8}: {error(v1,v2):>10.5f} %\t{v1:>10.5f} x {v2:>10.5f}"") + +# with round() +for pp in ll: + v1, v2 = round(e.__getattribute__(pp[0]), 4), amb_out[pp[1]] / ff + print(f""error {pp[0]:<8}: {error(v1,v2):>10.5f} %\t{v1:>10.5f} x {v2:>10.5f}"") +","Python" +"Computational Biochemistry","alanwilter/acpype","tests/test_mol.py",".py","1349","37","from acpype.mol import Angle, Atom, Bond, Dihedral + +r = ""<[, , , ], ang=0.00>"" + + +def test_atom(): + atom = Atom(""C1"", ""c3"", 3, 5, 12.0, 0.5, (1.0, 0.9, 0.5)) + assert str(atom) == """" + + +def test_bond(): + a1 = Atom(""C1"", ""c3"", 3, 5, 12.0, 0.5, (1.0, 0.9, 0.5)) + a2 = Atom(""H"", ""hc"", 4, 5, 1.0, -0.5, (2.0, 1.9, 1.5)) + bond = Bond([a1, a2], 330.0, 1.0969) + assert str(bond) == repr(bond) == ""<[, ], r=1.0969>"" + + +def test_angle(): + a1 = Atom(""C1"", ""c3"", 3, 5, 12.0, 0.5, (1.0, 0.9, 0.5)) + a2 = Atom(""H"", ""hc"", 4, 5, 1.0, -0.5, (2.0, 1.9, 1.5)) + a3 = Atom(""H"", ""hc"", 5, 5, 1.0, 0.1, (0.0, 0.1, -0.5)) + angle = Angle([a1, a2, a3], 46.3, 1.91637234) + assert ( + str(angle) + == repr(angle) + == ""<[, , ], ang=109.80>"" + ) + + +def test_dihedral(): + a1 = Atom(""C1"", ""c3"", 3, 5, 12.0, 0.5, (1.0, 0.9, 0.5)) + a2 = Atom(""H"", ""hc"", 4, 5, 1.0, -0.5, (2.0, 1.9, 1.5)) + a3 = Atom(""H"", ""hc"", 5, 5, 1.0, 0.1, (0.0, 0.1, -0.5)) + a4 = Atom(""H"", ""hc"", 6, 5, 1.0, -0.1, (0.0, 0.1, 2.0)) + dih = Dihedral([a1, a2, a3, a4], 0.16, 3, 0.0) + assert str(dih) == repr(dih) == r +","Python" +"Computational Biochemistry","alanwilter/acpype","tests/test_scenarios.py",".py","2546","71","import sys +from unittest.mock import patch + +import pytest + +from acpype.cli import _chk_py_ver, init_main +from acpype.utils import _getoutput + + +def test_no_ac(janitor, capsys): + binaries = {""ac_bin"": ""no_ac"", ""obabel_bin"": ""obabel""} + msg = f""ERROR: no '{binaries['ac_bin']}' executable... aborting!"" + inp = ""AAA.mol2"" + with pytest.raises(SystemExit) as e_info: + init_main(argv=[""-di"", inp, ""-c"", ""gas""], binaries=binaries) + captured = capsys.readouterr() + assert msg in captured.out + assert e_info.typename == ""SystemExit"" + assert e_info.value.code == 19 + + +def test_only_ac(janitor, capsys): + binaries = {""ac_bin"": ""antechamber"", ""obabel_bin"": ""no_obabel""} + msg1 = f""WARNING: no '{binaries['obabel_bin']}' executable, no PDB file can be used as input!"" + msg2 = ""Total time of execution:"" + msg3 = ""WARNING: No Openbabel python module, no chiral groups"" + inp = ""AAA.mol2"" + temp_base = ""vir_temp"" + init_main(argv=[""-di"", inp, ""-c"", ""gas"", ""-b"", temp_base], binaries=binaries) + captured = capsys.readouterr() + assert msg1 in captured.out + assert msg2 in captured.out + assert msg3 in captured.out + _getoutput(f""rm -vfr {temp_base}* .*{temp_base}*"") + + +@pytest.mark.parametrize( + (""inp"", ""msg""), + [ + (""AAA.pdb"", ""ERROR: no 'no_obabel' executable; you need it if input is PDB or SMILES""), + (""cccc"", ""WARNING: your input may be a SMILES but""), + ], +) +def test_no_obabel(janitor, capsys, inp, msg): + binaries = {""ac_bin"": ""antechamber"", ""obabel_bin"": ""no_obabel""} + with pytest.raises(SystemExit) as e_info: + init_main(argv=[""-di"", inp, ""-c"", ""gas""], binaries=binaries) + captured = capsys.readouterr() + assert msg in captured.out + assert e_info.typename == ""SystemExit"" + assert e_info.value.code == 19 + + +def test_amb2gmx_no_bins(janitor, capsys): + binaries = {""ac_bin"": ""no_ac"", ""obabel_bin"": ""no_obabel""} + argv = [""-x"", ""Base.inpcrd"", ""-p"", ""Base.prmtop""] + temp_base = ""vir_temp"" + init_main(argv=[*argv, ""-b"", temp_base], binaries=binaries) + captured = capsys.readouterr() + assert ""Total time of execution:"" in captured.out + _getoutput(f""rm -vfr {temp_base}* .*{temp_base}*"") + + +def test_chk_py_ver_python(): + _chk_py_ver() + with patch.object(sys, ""version_info"", (3, 7)): + with pytest.raises(Exception, match=""Sorry, you need python 3.8 or higher""): + # This should raise an exception for Python 3.8 + # Ensure that the exception message matches the expected one + _chk_py_ver() +","Python" +"Computational Biochemistry","alanwilter/acpype","tests/test_acpype.py",".py","10752","270","import os + +import pytest +from pytest import approx + +from acpype import __version__ as version +from acpype.cli import init_main +from acpype.topol import ACTopol +from acpype.utils import _getoutput + + +@pytest.mark.parametrize( + (""issorted"", ""charge"", ""msg""), + [ + (False, 0.240324, "">""), + (True, 0.240324, "">""), + ], +) +def test_mol2_sorted(janitor, issorted, charge, msg): + molecule = ACTopol(""AAA.mol2"", chargeType=""gas"", debug=True, is_sorted=issorted) + molecule.createACTopol() + molecule.createMolTopol() + assert molecule + assert molecule.molTopol.atomTypes[0].__repr__() == """" + assert len(molecule.molTopol.atoms) == 33 + assert len(molecule.molTopol.properDihedrals) == 91 + assert len(molecule.molTopol.improperDihedrals) == 5 + assert molecule.molTopol.totalCharge == 0 + assert molecule.molTopol.atoms[0].charge == approx(charge) + assert molecule.molTopol.atoms[-1].__repr__() == msg + janitor.append(molecule.absHomeDir) + janitor.append(molecule.tmpDir) + + +def test_pdb(janitor, capsys): + molecule = ACTopol(""FFF.pdb"", chargeType=""gas"", debug=True, force=False) + molecule.createACTopol() + molecule.createMolTopol() + assert len(molecule.molTopol.atoms) == 63 + assert len(molecule.molTopol.properDihedrals) == 181 + assert len(molecule.molTopol.improperDihedrals) == 23 + assert molecule.molTopol.atoms[0].__repr__() == "">"" + # check gaff2 and force + molecule = ACTopol(""FFF.pdb"", chargeType=""gas"", debug=True, atomType=""gaff2"", force=True) + molecule.createACTopol() + molecule.createMolTopol() + captured = capsys.readouterr() + assert len(molecule.molTopol.atoms) == 63 + assert len(molecule.molTopol.properDihedrals) == 181 + assert len(molecule.molTopol.improperDihedrals) == 23 + assert molecule.molTopol.atoms[0].__repr__() == "">"" + assert ""==> Overwriting pickle file FFF.pkl"" in captured.out + # check for already present + molecule = ACTopol(""FFF.mol2"", chargeType=""gas"", debug=True) + molecule.createACTopol() + molecule.createMolTopol() + captured = capsys.readouterr() + assert molecule + assert ""==> Pickle file FFF.pkl already present... doing nothing"" in captured.out + janitor.append(molecule.absHomeDir) + janitor.append(molecule.tmpDir) + + +@pytest.mark.parametrize( + (""force"", ""at"", ""ndih""), + [(False, ""amber"", 189), (True, ""amber2"", 197)], +) +def test_amber(janitor, force, at, ndih): + molecule = ACTopol(""FFF.mol2"", chargeType=""gas"", debug=True, atomType=at, force=force) + molecule.createACTopol() + molecule.createMolTopol() + assert molecule + assert len(molecule.molTopol.atoms) == 63 + assert len(molecule.molTopol.properDihedrals) == ndih + assert len(molecule.molTopol.improperDihedrals) == 23 + assert molecule.molTopol.atoms[0].__repr__() == "">"" + janitor.append(molecule.absHomeDir) + janitor.append(molecule.tmpDir) + + +def test_charges_chiral(janitor): + molecule = ACTopol(""KKK.mol2"", chargeType=""gas"", debug=True, chiral=True) + molecule.createACTopol() + molecule.createMolTopol() + assert molecule + assert len(molecule.molTopol.atoms) == 69 + assert len(molecule.molTopol.properDihedrals) == 205 + assert len(molecule.molTopol.improperDihedrals) == 5 + assert len(molecule.molTopol.chiralGroups) == 3 + assert molecule.chargeVal == ""3"" + assert molecule.molTopol.totalCharge == 3 + assert molecule.molTopol.chiralGroups[-1][-1] == approx(66.713290) + janitor.append(molecule.absHomeDir) + janitor.append(molecule.tmpDir) + + +@pytest.mark.parametrize( + (""base"", ""msg""), + [(None, ""smiles_molecule.mol2""), (""thalidomide_smiles"", ""thalidomide_smiles.mol2"")], +) +def test_smiles(janitor, base, msg): + smiles = ""c1ccc2c(c1)C(=O)N(C2=O)C3CCC(=NC3=O)O"" + molecule = ACTopol(smiles, basename=base, chargeType=""gas"", debug=True) + molecule.createACTopol() + molecule.createMolTopol() + assert molecule + assert molecule.inputFile == msg + assert len(molecule.molTopol.atoms) == 29 + janitor.append(molecule.absHomeDir) + janitor.append(molecule.tmpDir) + os.remove(molecule.absInputFile) + + +@pytest.mark.parametrize( + (""ct"", ""ft"", ""msg""), + [ + ( + ""bcc"", + ""pdb"", + ""-dr no -i 'benzene.mol2' -fi mol2 -o 'benzene_bcc_gaff2.mol2' -fo mol2 -c bcc -nc 0 -m 1 -s 2 -df 2 -at gaff2"", + ), + ( + ""bcc"", + ""mol"", + ""-dr no -i 'benzene.mol' -fi mdl -o 'benzene_bcc_gaff2.mol2' -fo mol2 -c bcc -nc 0 -m 1 -s 2 -df 2 -at gaff2"", + ), + ( + ""bcc"", + ""mdl"", + ""-dr no -i 'benzene.mdl' -fi mdl -o 'benzene_bcc_gaff2.mol2' -fo mol2 -c bcc -nc 0 -m 1 -s 2 -df 2 -at gaff2"", + ), + (""user"", ""pdb"", ""cannot read charges from a PDB file""), + ], +) +def test_sqm_tleap(janitor, capsys, ct, ft, msg): + # check chargeType user with PDB -> use bcc + # .mol and .mdl are the same file type + molecule = ACTopol(f""benzene.{ft}"", chargeType=ct, debug=True) + molecule.createACTopol() + molecule.createMolTopol() + captured = capsys.readouterr() + assert molecule + assert len(molecule.molTopol.atoms) == 12 + assert len(molecule.molTopol.properDihedrals) == 24 + assert len(molecule.molTopol.improperDihedrals) == 6 + assert molecule.molTopol.atoms[0].charge == approx(-0.13) + assert molecule.molTopol.atoms[-1].charge == approx(0.13) + assert msg in captured.out + janitor.append(molecule.absHomeDir) + janitor.append(molecule.tmpDir) + + +def test_ekFlag(janitor): + molecule = ACTopol( + ""benzene.pdb"", + ekFlag='''""qm_theory='AM1', grms_tol=0.0005, scfconv=1.d-10, ndiis_attempts=700, qmcharge=0""''', + gmx4=True, + ) + molecule.createACTopol() + molecule.createMolTopol() + assert molecule + assert len(molecule.molTopol.atoms) == 12 + janitor.append(molecule.absHomeDir) + janitor.append(molecule.tmpDir) + + +def test_time_limit(janitor): + molecule = ACTopol(""KKK.pdb"", chargeType=""bcc"", debug=True, timeTol=2) + with pytest.raises(Exception) as e_info: + molecule.createACTopol() + assert e_info.value.args[0] == ""Semi-QM taking too long to finish... aborting!"" + janitor.append(molecule.absHomeDir) + janitor.append(molecule.tmpDir) + + +def test_charge_user(janitor): + molecule = ACTopol(""ADPMg.mol2"", chargeType=""user"", debug=True) + molecule.createACTopol() + molecule.createMolTopol() + assert molecule + assert len(molecule.molTopol.atoms) == 39 + assert len(molecule.molTopol.properDihedrals) == 125 + assert len(molecule.molTopol.improperDihedrals) == 7 + assert molecule.molTopol.atoms[0].charge == 0.1667 + assert molecule.molTopol.atoms[15].charge == -0.517 + janitor.append(molecule.absHomeDir) + janitor.append(molecule.tmpDir) + + +@pytest.mark.parametrize( + (""argv"", ""msg""), + [ + ([""-i"", ""cccc""], ""Total time of execution:""), + ([""-x"", ""Base.inpcrd"", ""-p"", ""Base.prmtop"", ""-b"", ""vir_temp""], ""Total time of execution:""), + ([""-wi"", ""cccc"", ""-b"", ""vir_temp""], """"), + ( + [""-i"", ""wrong_res_set.pdb"", ""-b"", ""vir_temp""], + ""In vir_temp_AC.lib, residue name will be 'RSET' instead of 'SET' elsewhere"", + ), + ( + [""-i"", ""wrong_res_num.pdb"", ""-b"", ""vir_temp""], + ""In vir_temp_AC.lib, residue name will be 'R100' instead of '100' elsewhere"", + ), + ( + [""-i"", ""wrong_res_sym.pdb"", ""-b"", ""vir_temp""], + ""In vir_temp_AC.lib, residue name will be 'MOL' instead of '+++' elsewhere"", + ), + ( + [""-i"", ""lower_res.pdb"", ""-b"", ""vir_temp""], + ""WARNING: this may raise problem with some applications like CNS"", + ), + ( + [""-fi"", ""too_close.pdb"", ""-b"", ""vir_temp""], + ""You chose to proceed anyway with '-f' option. GOOD LUCK!"", + ), + ( + [""-i"", ""no_res.pdb"", ""-b"", ""vir_temp""], + ""No residue name identified, using default resname: 'LIG'"", + ), + ( + [""-i"", ""drift.mol2"", ""-c"", ""user"", ""-b"", ""vir_temp""], + ""Net charge drift '0.02020' bigger than tolerance '0.01000'"", + ), + ], +) +def test_inputs(janitor, capsys, argv, msg): + temp_base = ""vir_temp"" + init_main(argv=argv) + captured = capsys.readouterr() + assert msg in captured.out + _getoutput(f""rm -vfr {temp_base}* .*{temp_base}* smiles_molecule.acpype"") + + +@pytest.mark.parametrize( + (""argv"", ""code"", ""msg""), + [ + (None, 2, "" error: ""), # NOTE: None -> sys.argv from pytest + ([""-v""], 0, version), + ([], 2, ""error: missing input files""), + ([""-d"", ""-w""], 2, ""error: argument -w/--verboseless: not allowed with argument -d/--debug""), + ([""-di"", ""AAAx.mol2""], 19, ""ACPYPE FAILED: Input file AAAx.mol2 DOES NOT EXIST""), + ([""-zx"", ""ILDN.inpcrd"", ""-p"", ""ILDN.prmtop""], 19, ""Likely trying to convert ILDN to RB""), + ([""-x"", ""glycam_exe.inpcrd"", ""-p"", ""glycam_corrupt.prmtop""], 19, ""Skipping non-existent attributes dihedral_p""), + ([""-x"", ""glycam_exe.inpcrd"", ""-p"", ""glycam_empty.prmtop""], 19, ""ERROR: ACPYPE FAILED: PRMTOP file empty?""), + ([""-x"", ""glycam_empty.inpcrd"", ""-p"", ""glycam_exe.prmtop""], 19, ""ERROR: ACPYPE FAILED: INPCRD file empty?""), + ([""-di"", ""cccccc"", ""-n"", ""-1"", ""-b"", ""vir_temp""], 19, ""Fatal Error!""), + ([""-di"", "" 123"", ""-b"", ""vir_temp""], 19, ""ACPYPE FAILED: [Errno 2] No such file or directory""), + ([""-i"", ""double_res.pdb"", ""-b"", ""vir_temp""], 19, ""Only ONE Residue is allowed for ACPYPE to work""), + ([""-i"", ""same_coord.pdb"", ""-b"", ""vir_temp""], 19, ""Atoms with same coordinates in""), + ([""-i"", ""too_close.pdb"", ""-b"", ""vir_temp""], 19, ""Atoms TOO close (<""), + ([""-i"", ""too_far.pdb"", ""-b"", ""vir_temp""], 19, ""Atoms TOO scattered (>""), + ([""-di"", "" 123"", ""-x"", ""abc""], 2, ""either '-i' or ('-p', '-x'), but not both""), + ([""-di"", "" 123"", ""-u""], 2, ""option -u is only meaningful in 'amb2gmx' mode (args '-p' and '-x')""), + ( + [""-di"", ""HEM.pdb"", ""-b"", ""vir_temp""], + 19, + ""No Gasteiger parameter for atom (ID: 42, Name: FE, Type: DU)"", + # Only Allowed: C, N, O, S, P, H, F, Cl, Br and I + ), + ], +) +def test_args_wrong_inputs(janitor, capsys, argv, code, msg): + with pytest.raises(SystemExit) as e_info: + init_main(argv=argv) + captured = capsys.readouterr() + assert msg in captured.err + captured.out + assert e_info.typename == ""SystemExit"" + assert e_info.value.code == code + _getoutput(""rm -vfr vir_temp* .*vir_temp*"") +","Python" +"Computational Biochemistry","alanwilter/acpype","tests/__init__.py",".py","0","0","","Python" +"Computational Biochemistry","alanwilter/acpype","tests/test_acs_api.py",".py","1300","55","import json +from glob import glob + +from acpype.acs_api import acpype_api + +file_types = ( + (""file_name""), + (""em_mdp""), + (""AC_frcmod""), + (""AC_inpcrd""), + (""AC_lib""), + (""AC_prmtop""), + (""mol2""), + (""CHARMM_inp""), + (""CHARMM_prm""), + (""CHARMM_rtf""), + (""CNS_inp""), + (""CNS_par""), + (""CNS_top""), + (""GMX_OPLS_itp""), + (""GMX_OPLS_top""), + (""GMX_gro""), + (""GMX_itp""), + (""GMX_top""), + (""NEW_pdb""), + (""md_mdp""), +) + + +def test_json_simple(janitor): + jj = json.loads(acpype_api(inputFile=""benzene.pdb"", debug=True)) + assert min(len(jj.get(x)) for x in file_types) >= 7 + assert jj.get(""file_name"") == ""benzene"" + janitor.append(""../.acpype_tmp_benzene"") + + +def test_json_failed(janitor): + jj = json.loads(acpype_api(inputFile=""_fake_"", debug=True)) + assert ""ERROR: [Errno 2] No such file or directory"" in jj.get(""file_name"") + assert ""tests/_fake_"" in jj.get(""file_name"") + for ii in glob("".*_fake_*""): + janitor.append(ii) + + +def get_json(): + json_output = acpype_api(inputFile=""AAA.mol2"", chargeType=""gas"", atomType=""gaff2"", debug=True, basename=""AAA"") + return json.loads(json_output) + + +def test_json(janitor): + jj = get_json() + janitor.append(""../.acpype_tmp_AAA"") + for ft in file_types: + assert len(jj.get(ft)) > 2 +","Python" +"Computational Biochemistry","alanwilter/acpype","tests/test_amb2gmx.py",".py","3472","84","import pytest + +from acpype.topol import MolTopol + + +def test_glycam(janitor): + molecule = MolTopol(acFileTop=""glycam_exe.prmtop"", acFileXyz=""glycam_exe.inpcrd"", debug=True, amb2gmx=True) + molecule.writeGromacsTopolFiles() + molecule.writeCnsTopolFiles() + assert molecule + assert molecule.topo14Data.hasNondefault14() + assert len(molecule.topo14Data.scnb_scale_factor) == 31 + janitor.append(molecule.absHomeDir) + + +@pytest.mark.parametrize( + (""dd"", ""g4"", ""ntext""), + [(False, False, 14193), (True, False, 31516), (False, True, 12124), (True, True, 29447)], +) +def test_amb2gmx(janitor, dd, g4, ntext): + # oct box with water and ions + # modified from https://ambermd.org/tutorials/basic/tutorial7/index.php + # using addIonsRand separated for each ion and TIP3PBOX + molecule = MolTopol(acFileTop=""RAMP1_ion.prmtop"", acFileXyz=""RAMP1_ion.inpcrd"", debug=True, direct=dd, gmx4=g4) + molecule.writeGromacsTopolFiles() + assert molecule + assert len(molecule.topText) == ntext + assert not molecule.topo14Data.hasNondefault14() + assert molecule.atoms[1300].__repr__() == "">"" + assert molecule.atoms[1310].__repr__() == "">"" + assert len(molecule.atoms) == 18618 + janitor.append(molecule.absHomeDir) + + +@pytest.mark.parametrize( + (""merge"", ""gaff"", ""n_at"", ""acoef"", ""bcoef"", ""msg""), + [ + (False, ""1"", 50, 379876.399, 564.885984, """"), + (False, ""2"", 50, 376435.47, 469.350655, """"), + (True, ""1"", 41, 361397.723, 495.732238, """"), + (True, ""2"", 50, 376435.47, 469.350655, """"), + ], +) +def test_merge(janitor, merge, gaff, n_at, acoef, bcoef, msg): + molecule = MolTopol(acFileTop=f""ComplexG{gaff}.prmtop"", acFileXyz=f""ComplexG{gaff}.inpcrd"", debug=True, merge=merge) + molecule.writeGromacsTopolFiles() + assert molecule + assert len(molecule.atomTypesGromacs) == n_at + assert molecule.atomTypesGromacs[31].ACOEF == acoef + assert molecule.atomTypesGromacs[31].BCOEF == bcoef + assert molecule.atomTypesGromacs[31].__repr__() == msg + janitor.append(molecule.absHomeDir) + + +@pytest.mark.parametrize( + (""mol"", ""n1"", ""n2"", ""n3"", ""n4"", ""n5"", ""msg""), + [(""ILDN"", 24931, 12230, 577, 0, 47, """"), (""Base"", 24931, 12044, 577, 0, 43, """")], +) +def test_ildn(janitor, mol, n1, n2, n3, n4, n5, msg): + molecule = MolTopol(acFileTop=f""{mol}.prmtop"", acFileXyz=f""{mol}.inpcrd"", debug=True) + molecule.writeGromacsTopolFiles() + assert molecule + assert len(molecule.atoms) == n1 + assert len(molecule.properDihedrals) == n2 + assert len(molecule.improperDihedrals) == n3 + assert molecule.totalCharge == n4 + assert len(molecule.atomTypes) == n5 + assert molecule.atomTypes[23].__repr__() == msg + janitor.append(molecule.absHomeDir) + + +def test_ildn_gmx4_fail(janitor): + molecule = MolTopol(acFileTop=""ILDN.prmtop"", acFileXyz=""ILDN.inpcrd"", debug=True, gmx4=True) + with pytest.raises(Exception) as e_info: + molecule.writeGromacsTopolFiles() + assert e_info.value.args[0] == ""Likely trying to convert ILDN to RB, DO NOT use option '-z'"" + janitor.append(molecule.absHomeDir) + + +def test_wrong_input(janitor): + with pytest.raises(Exception) as e_info: + MolTopol(acFileTop=""nope.prmtop"", acFileXyz=""ILDN.inpcrd"", debug=True, gmx4=True) + assert e_info.value.args == (2, ""No such file or directory"") +","Python" +"Computational Biochemistry","alanwilter/acpype","tests/conftest.py",".py","510","31",""""""" +Requirements: +* pytest +* pytest-html + +To run: +pytest -s --html=report.html +pytest --cov=acpype --cov-report=term-missing:skip-covered +"""""" + +import os +from shutil import rmtree + +import pytest + +from acpype import __version__ as version + + +def pytest_report_header(config): + return f"">>>\tVersion: {version}\n"" + + +@pytest.fixture +def janitor(): + os.chdir(os.path.dirname(__file__)) + to_delete = [] + yield to_delete + for item in to_delete: + if os.path.exists(item): + rmtree(item) +","Python" +"Computational Biochemistry","LeidelLab/SMITER","setup.py",".py","1458","58","#!/usr/bin/env python + +""""""The setup script."""""" + +from setuptools import find_packages, setup + +with open(""README.rst"") as readme_file: + readme = readme_file.read() + +with open(""HISTORY.rst"") as history_file: + history = history_file.read() + +requirements = [ + ""Click>=7.0"", +] + +setup_requirements = [ + ""pytest-runner"", +] + +test_requirements = [ + ""pytest>=3"", +] + +setup( + author=""Manuel Kösters"", + author_email=""manuel.koesters@dcb.unibe.ch"", + python_requires="">=3.7"", + classifiers=[ + ""Development Status :: 2 - Pre-Alpha"", + ""Intended Audience :: Developers"", + ""License :: OSI Approved :: MIT License"", + ""Natural Language :: English"", + ""Programming Language :: Python :: 3.7"", + ""Programming Language :: Python :: 3.8"", + ""Programming Language :: Python :: 3.9"", + ], + description=""Library to create synthetic mzMLs file based on chemical formulas"", + entry_points={ + ""console_scripts"": [ + ""smiter=smiter.cli:main"", + ], + }, + install_requires=requirements, + license=""MIT license"", + long_description=readme + ""\n\n"" + history, + include_package_data=True, + keywords=""smiter"", + name=""smiter"", + packages=find_packages(include=[""smiter"", ""smiter.*""]), + setup_requires=setup_requirements, + test_suite=""tests"", + tests_require=test_requirements, + url=""https://github.com/MKoesters/smiter"", + version=""0.1.0"", + zip_safe=False, +) +","Python" +"Computational Biochemistry","LeidelLab/SMITER","check_and_fix_style.sh",".sh","164","10","echo ""Black Fix"" +black smiter tests +echo +echo 'Isort Fix' +isort -rc smiter tests +echo +# echo 'MyPy Check' +# mypy --ignore-missing-imports --pretty -p smiter +# echo +","Shell" +"Computational Biochemistry","LeidelLab/SMITER","example_scripts/simulate_fasta.py",".py","5718","181","#!/usr/bin/env python +import os +import sys +import time + +import warnings +import deeplc +import pandas as pd +import ursgal +from loguru import logger +from numpy.random import choice, normal, random, seed, uniform +from pyqms.chemical_composition import ChemicalComposition +from tqdm import tqdm +import tensorflow as tf +import smiter +import matplotlib.pyplot as plt +import seaborn as sns +import pymzml + +# sns.set_style('darkgrid') +plt.style.use('ggplot') + +# seed(42) +warnings.simplefilter(""ignore"") +os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' +tf.get_logger().setLevel('ERROR') + + +def main(fasta_file, evidences=None): + peak_props = {} + cc = ChemicalComposition() + + if evidences is not None: + ev = pd.read_csv(evidences) + train_df = pd.DataFrame() + train_df['seq'] = ev['Sequence'] + train_df['modifications'] = ev['Modifications'].fillna('') + train_df['tr'] = ev['Retention Time (s)'] + dlc = deeplc.DeepLC() + logger.info(f'Train DeepLC on {evidences}') + dlc.calibrate_preds(seq_df=train_df) + # breakpoint() + + start = time.time() + logger.info(""Parsing fasta and calculating peak Properties"") + no_peptides = 0 + with open(fasta_file) as fin: + for _id, seq in tqdm( + ursgal.ucore.parse_fasta(fin), + total=6691, + # total=75004, + desc=""Calculating peak properties"", + ): + peptides = ursgal.ucore.digest(seq, (""KR"", ""C""), no_missed_cleavages=True) + + r = uniform(1e4, 1e6) + for p in peptides: + + if len(p) > 30 or len(p) < 10: + continue + r_number = random() + if r_number < 0.6: + continue + no_peptides += 1 + peak_function = choice([""gauss"", ""gauss_tail""], p=[0, 1.0]) + if peak_function == ""gauss"": + peak_params = {""sigma"": 2} + elif peak_function == ""gauss_tail"": + peak_params = {""sigma"": 2} + try: + cc.use(p) + except: + continue + # logger.info(f'Add {p}') + # r = random() + scale_factor = uniform(r*1, r*2) + charge_state = choice([2, 3, 4], 1, p=[0.6, 0.3, 0.1])[0] + peak_width = uniform(0.3, 0.5) + formula = cc.hill_notation_unimod() + predicted_start = uniform(0, 120 * 60) + # TODO run RT prediction before + + peak_props[p] = { + ""chemical_formula"": f""+{formula}"", + ""trivial_name"": p, + ""charge"": charge_state, + ""scan_start_time"": predicted_start, + # ""scan_start_time"": deeplc_predicted_rt, + ""peak_width"": peak_width, + ""peak_function"": peak_function, + ""peak_params"": peak_params, + ""peak_scaling_factor"": normal(loc=scale_factor, scale=1), + } + + logger.info(f""Predict RT for {no_peptides} simulated molecules"") + pred_df = pd.DataFrame() + pred_df['seq'] = list(peak_props.keys()) + pred_df['modifications'] = '' + rts = dlc.make_preds(seq_df=pred_df) + pred_df['tr'] = rts + + # logger.info(""Updating predicted RTs in peak properties"") + for i, line in pred_df.iterrows(): + peak_props[line['seq']]['scan_start_time'] = line['tr'] + duration = time.time() - start + + pred_df['tr'].plot.histo() + plt.show() + + + # d = {} + # from pprint import pprint + # for p in peak_props.keys(): + # if peak_props[p]['peak_function'] == 'gauss_tail': + # pprint(peak_props[p]) + # _t = round(peak_props[p]['scan_start_time'] + peak_props[p]['peak_width']) + # if _t not in d: + # d[_t] = 1 + # else: + # d[_t] += 1 + # t = [] + # count = [] + # for rt in sorted(d.keys()): + # t.append(rt) + # count.append(d[rt]) + # plt.plot(t, count); plt.show() + mzml_params = { + ""gradient_length"": 120 * 60, # in minutes + ""ms_rt_diff"": 0.001 * 60, # in minutes + ""min_intensity"": 0 + } + + # _t = [] + # t = [] + # i = [] + # tree = smiter.synthetic_mzml.genereate_interval_tree(peak_props) + # for x in range(0, mzml_params['gradient_length']): + # # x /= 2 + # l = len(tree.at(x)) + # t.append(x) + # i.append(l) + # # _t.append(x) + # plt.plot(t, i); plt.show() + # sns.distplot(i, bins=100);plt.show() + # breakpoint() + + logger.info(f""Simulated {len(peak_props)} peptides in {duration} seconds"") + + smiter.lib.peak_properties_to_csv( + peak_props, ""/mnt/Data/Proteomics/testing/test.csv"" + ) + + fragmentor = smiter.fragmentation_functions.PeptideFragmentor() + fragmentor = smiter.fragmentation_functions.PeptideFragmentorPyteomics() + noise_injector = smiter.noise_functions.JamssNoiseInjector() + file = ""/mnt/Data/Proteomics/testing/test.mzML"" + + start = time.time() + mzml_path = smiter.synthetic_mzml.write_mzml( + file, peak_props, fragmentor, noise_injector, mzml_params + ) + logger.info(f'Wrote mzML to {file}') + # logger.info(f""Wrote mzML in {time.time() - start} seconds"") + with pymzml.run.Reader(file) as run: + rt = [] + tic = [] + for spec in run: + rt.append(spec.scan_time_in_minutes()) + tic.append(spec.i.sum()) + plt.plot(rt, tic) + plt.ylabel('TIC') + plt.xlabel('time') + plt.show() + + +if __name__ == ""__main__"": + if len(sys.argv) == 2: + main(sys.argv[1]) + else: + main(sys.argv[1], sys.argv[2]) +","Python" +"Computational Biochemistry","LeidelLab/SMITER","example_scripts/write_peptides.py",".py","1224","43","#!//usr/bin/env python +from tempfile import NamedTemporaryFile +import smiter +from smiter.fragmentation_functions import ( + AbstractFragmentor, + NucleosideFragmentor, + PeptideFragmentor, +) +from smiter.noise_functions import GaussNoiseInjector, UniformNoiseInjector +from smiter.synthetic_mzml import write_mzml + + +def main(): + file = NamedTemporaryFile(""wb"") + peak_props = { + ""ELVISLIVES"": { + ""trivial_name"": ""ELVISLIVES"", + ""charge"": 2, + ""scan_start_time"": 0, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 3}, # 10% of peak width + }, + ""ELVISLIVSE"": { + ""charge"": 2, + ""trivial_name"": ""ELVISLIVSE"", + ""scan_start_time"": 15, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 3}, # 10% of peak width, + }, + } + mzml_params = { + ""gradient_length"": 45, + } + fragmentor = PeptideFragmentor() + noise_injector = GaussNoiseInjector(variance=0.05) + mzml_path = write_mzml(file, peak_props, fragmentor, noise_injector, mzml_params) + + +if __name__ == '__main__': + main() +","Python" +"Computational Biochemistry","LeidelLab/SMITER","example_scripts/write_simulated_mzML.py",".py","895","32","#!/usr/bin/env python3 +import numpy as np +import pymzml +from pymzml.plot import Factory + +from smiter.fragmentation_functions import NucleosideFragmentor +from smiter.noise_functions import UniformNoiseInjector +from smiter.synthetic_mzml import write_mzml + + +def main(): + peak_props = { + ""inosine"": { + ""charge"": 1, + ""scan_start_time"": 0, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 3}, + ""trivial_name"": ""inosine"", + ""chemical_formula"": ""+C(10)H(12)N(4)O(5)"", + } + } + mzml_params = {""gradient_length"": 30, ""ms_rt_diff"": 0.01} + file = ""inosine.mzML"" + fragmentor = NucleosideFragmentor() + noise_injector = UniformNoiseInjector() + mzml_path = write_mzml(file, peak_props, fragmentor, noise_injector, mzml_params) + + +if __name__ == ""__main__"": + main() +","Python" +"Computational Biochemistry","LeidelLab/SMITER","example_scripts/inspect_simulated_peak.py",".py","2082","79","import smiter +import matplotlib.pyplot as plt + + +def main(): + peak_props = { + ""inosine"": { + ""trivial_name"": ""inosine"", + ""chemical_formula"": ""+C(10)H(12)N(4)O(5)"", + ""charge"": 2, + ""scan_start_time"": .0, + ""peak_width"": 2, # minutes + ""peak_function"": ""gauss_tail"", + ""peak_scaling_factor"": 1e3, + } + } + mzml_params = { + 'gradient_length': 3, + 'min_intensity': 50, + 'isolation_window_width': 0.7, + ""ms_rt_diff"": 0.001, # in minutes + } + + noise_injector = smiter.noise_functions.JamssNoiseInjector() + fragmentor = smiter.fragmentation_functions.NucleosideFragmentor() + + interval_tree = smiter.synthetic_mzml.genereate_interval_tree(peak_props) + trivial_names = { + val[""chemical_formula""]: key for key, val in peak_props.items() + } + isotopologue_lib = smiter.synthetic_mzml.generate_molecule_isotopologue_lib( + peak_props, trivial_names=trivial_names + ) + + fig, (ax1, ax2) = plt.subplots(1, 2) + scans_noise, scan_dict = smiter.synthetic_mzml.generate_scans( + isotopologue_lib, + peak_props, + interval_tree, + fragmentor, + noise_injector, + mzml_params, + ) + t = [scan['rt'] for scan, _ in scans_noise] + i = [sum(scan['i']) for scan, _ in scans_noise] + ax1.plot(t, i) + ax1.set_title(""With noise"") + # plt.show() + + noise_injector = smiter.noise_functions.UniformNoiseInjector( + dropout=0, + ppm_noise=0, + intensity_noise=0, + ) + scans, scan_dict = smiter.synthetic_mzml.generate_scans( + isotopologue_lib, + peak_props, + interval_tree, + fragmentor, + noise_injector, + mzml_params, + ) + t = [scan['rt'] for scan, _ in scans] + i = [sum(scan['i']) for scan, _ in scans] + ax2.plot(t, i) + ax2.set_title(""Without noise"") + plt.show() + + for s, _ in scans_noise: + plt.title(f'Spectrum {s.id}') + plt.bar(s.mz, s.i) + plt.show() + + + + +if __name__ == '__main__': + main() +","Python" +"Computational Biochemistry","LeidelLab/SMITER","example_scripts/write_simulated_peaks_adenosine_inosine.py",".py","2418","80","#!/usr/bin/env python3 +""""""Write file containing inosine and adenosine peak."""""" +import os + +import click +import matplotlib.pyplot as plt +import numpy as np +import pymzml +import warnings + +from smiter.fragmentation_functions import AbstractFragmentor, NucleosideFragmentor +from smiter.noise_functions import UniformNoiseInjector, JamssNoiseInjector +from smiter.synthetic_mzml import write_mzml + +warnings.simplefilter(""ignore"") + + +@click.command() +@click.argument(""file_path"") +def main(file_path): + peak_props = { + ""uridine"": { + ""charge"": 2, + ""chemical_formula"": ""+C(9)H(11)N(2)O(6)"", + ""trivial_name"": ""uridine"", + ""scan_start_time"": 0, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 1}, # 10% of peak width, + ""peak_scaling_factor"": 0.5 * 1e6, + }, + ""pseudouridine"": { + ""chemical_formula"": ""+C(9)H(11)N(2)O(6)"", + ""trivial_name"": ""pseudouridine"", + ""charge"": 2, + ""scan_start_time"": 15, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 1}, # 10% of peak width, + ""peak_scaling_factor"": 1e6, + }, + } + mzml_params = { + ""gradient_length"": 45, + ""min_intensity"": 10, + } + fragmentor = NucleosideFragmentor() + # noise_injector= UniformNoiseInjector() + noise_injector = JamssNoiseInjector() + with open(file_path, ""wb"") as fin: + mzml_path = write_mzml(fin, peak_props, fragmentor, noise_injector, mzml_params) + + reader = pymzml.run.Reader(file_path) + + ino_rt = [] + ino_intensities = [] + adeno_rt = [] + adeno_intensities = [] + + ino_mono = 244.06898754897 + adeno_mono = 244.06898754897 + + for spec in reader: + if spec.ms_level == 1: + ino_i = spec.i[abs(spec.mz - ino_mono) < 0.001] + adeno_i = spec.i[abs(spec.mz - adeno_mono) < 0.001] + if len(adeno_i) > 0: + adeno_intensities.append(adeno_i[0]) + adeno_rt.append(spec.scan_time[0]) + if len(ino_i) > 0: + ino_intensities.append(ino_i[0]) + ino_rt.append(spec.scan_time[0]) + plt.plot(ino_rt, ino_intensities) + plt.plot(adeno_rt, adeno_intensities) + plt.savefig(os.path.splitext(file_path)[0]) + + +if __name__ == ""__main__"": + main() +","Python" +"Computational Biochemistry","LeidelLab/SMITER","example_scripts/complex_mix_simulation.py",".py","1171","45","import csv +from pprint import pprint + +import click +import matplotlib.pyplot as plt +import pymzml + +import smiter +import warnings + +warnings.simplefilter(""ignore"") + + +@click.command() +@click.argument(""input_csv"") +@click.argument(""output_mzml"") +def main(input_csv, output_mzml): + peak_properties = smiter.lib.csv_to_peak_properties(input_csv) + pprint(peak_properties) + fragmentor = smiter.fragmentation_functions.NucleosideFragmentor() + noise_injector = smiter.noise_functions.UniformNoiseInjector( + dropout=0.3, ppm_noise=5e-6, intensity_noise=0.05 + ) + # noise_injector = smiter.noise_functions.UniformNoiseInjector( + # dropout=0.0, ppm_noise=0, intensity_noise=0 + # ) + + mzml_params = {""gradient_length"": 60} + smiter.synthetic_mzml.write_mzml( + output_mzml, peak_properties, fragmentor, noise_injector, mzml_params + ) + + rt = [] + i = [] + with pymzml.run.Reader(output_mzml) as run: + for spec in run: + if spec.ms_level == 1: + rt.append(spec.scan_time_in_minutes() * 60) + i.append(spec.i.sum()) + plt.plot(rt, i) + plt.show() + +if __name__ == ""__main__"": + main() +","Python" +"Computational Biochemistry","LeidelLab/SMITER","example_scripts/write_filtered_mzml.py",".py","2048","73","#!/usr/bin/env python3 + +import sys +import os +import pymzml + +from smiter.synthetic_mzml import write_scans + + +def main(mzml_path, file_name, start_scan, stop_scan): + ''' + Write filtered mzML from file in the defined spectrum ID range. + + Please define full paths to input and output mzml file. Start and stop scan + have to be integers. If the start_scan is no MS1, the next MS1 scan will + be used as first scan. + + usage: + ./write_filtered_mzml.py mzml_file file_name_to_write start_scan stop_scan + + ''' + mzml_basename = mzml_path + dirname = os.path.dirname(mzml_path) + + # [(MS1,[MS2,MS2]),...] + scans = [] + + run = pymzml.run.Reader(mzml_path) + + id_range = [n for n in range(int(start_scan),int(stop_scan),1)] + num_scans = len(id_range) + scan_set = None + total_scans = 0 + for spec_pos, spec_id in enumerate(id_range): + spectrum = run[spec_id] + ms_level = spectrum.ms_level + # update scan object + spectrum.id = spectrum.ID + spectrum.retention_time = spectrum.scan_time[0] + print(spec_id) + if ms_level == 1: + if scan_set is not None: + scans.append(scan_set) + scan_set = [ spectrum, [] ] + total_scans+=1 + else: + spectrum.precursor_mz = spectrum.selected_precursors[0]['mz'] + + precursor_i = spectrum.selected_precursors[0].get('i',0) + spectrum.precursor_i = precursor_i + + charge = spectrum.selected_precursors[0].get('charge',1) + spectrum.precursor_charge = charge + total_scans += 1 + if scan_set is not None: + scan_set[1].append(spectrum) + # write rest of MS2 if no MS1 scans follows anymore + if spec_pos + 1 == num_scans: + scans.append(scan_set) + + write_scans( + file_name, + scans + ) + + +if __name__ == ""__main__"": + if len(sys.argv) < 5: + print(main.__doc__) + exit() + else: + main(*sys.argv[1:]) +","Python" +"Computational Biochemistry","LeidelLab/SMITER","example_scripts/plot_simulated_chromatogram.py",".py","2393","83","#!/usr/bin/env python3 + +from tempfile import NamedTemporaryFile + +import pymzml +from pymzml.plot import Factory + +from smiter.fragmentation_functions import NucleosideFragmentor +from smiter.noise_functions import UniformNoiseInjector, JamssNoiseInjector +from smiter.synthetic_mzml import write_mzml + + +def main(): + peak_props = { + ""inosine"": { + ""trivial_name"": ""inosine"", + ""chemical_formula"": ""+C(10)H(12)N(4)O(5)"", + ""charge"": 2, + ""scan_start_time"": 0, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss_tail"", + ""peak_params"": {""sigma"": 3}, + ""peak_scaling_factor"": 1e6, + }, + ""+C(9)H(12)N(2)O(6)"": { + ""trivial_name"": ""pseudouridine"", + ""charge"": 2, + ""scan_start_time"": 30, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss_tail"", + ""peak_scaling_factor"": 2e6, + ""peak_params"": {""sigma"": 3}, + }, + ""+C(10)H(13)N(5)O(7)"": { + ""trivial_name"": ""spiroiminodihydantoin"", + ""charge"": 2, + ""scan_start_time"": 60, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss_tail"", + ""peak_params"": {""sigma"": 3}, + ""peak_scaling_factor"": 3e6, + } + + } + mzml_params = { + ""gradient_length"": 30, + ""min_intensity"": 1, + } + + fragmentor = NucleosideFragmentor() + noise_injector = UniformNoiseInjector() + noise_injector = UniformNoiseInjector( + dropout=0.0, ppm_noise=0, intensity_noise=0 + ) + noise_injector = JamssNoiseInjector() + + + file = NamedTemporaryFile(""wb"") + mzml_path = write_mzml(file, peak_props, fragmentor, noise_injector, mzml_params) + reader = pymzml.run.Reader(mzml_path) + tic_tuples = [] + for pos, spec in enumerate(reader): + if spec.ms_level == 1: + scan_time, scan_unit = spec.scan_time + if scan_unit == ""second"": + scan_time /= 60 + tic_tuples.append((scan_time, spec.TIC)) + + pf = Factory() + pf.new_plot() + pf.add(tic_tuples, color=(0, 0, 0), style=""lines"", title=""TIC"") + pf.save( + ""example_chromatogram.html"", + layout={ + ""xaxis"": {""title"": ""Retention time [minutes]""}, + ""yaxis"": {""title"": ""TIC""}, + }, + ) + + +if __name__ == ""__main__"": + main() +","Python" +"Computational Biochemistry","LeidelLab/SMITER","smiter/todos.md",".md","218","7","# TODOs + +- allow multiple precursors in one ms1 spec with different elution profiles +- implement proper fragmentation functions for peptides and nucleosides +- add intensity scaling parameter for different molecules +- +","Markdown" +"Computational Biochemistry","LeidelLab/SMITER","smiter/peak_distribution.py",".py","1588","75","#!/usr/bin/env python3 +""""""Distribution funtion for chromo peaks. + +Attributes: + distributions (dict): mapping distribution name to distribution function +"""""" +import math +from typing import Callable, Dict + +from loguru import logger +from scipy.stats import gamma + + +def gauss_dist(x: float, sigma: float = 1, mu: float = 0): + """"""Calc Gauss distribution. + + Args: + x (float): x + sigma (float, optional): standard deviation + mu (float, optional): mean + + Returns: + float: y + """""" + # logger.debug(f""Sigma: {sigma}"") + # print(f'Sigma: {sigma}') + return ( + ( + 1 + / (sigma * math.sqrt(2 * math.pi)) + * pow(math.e, (-0.5 * pow(((x - mu) / sigma), 2))) + ) + / 0.3989422804014327 + * sigma + ) + + +def gauss_tail( + x: float, + mu: float, + sigma: float, + scan_start_time: float, + h: float = 1, + t: float = 0.2, + f: float = 0.01, +) -> float: + # h = 1 + ## should be a parameter + # t = 0.2 + # f = 0.01 + sigma = t * (x - scan_start_time) + f # / (x + 0.00001) + i = h * math.e ** (-0.5 * ((x - mu) / sigma) ** 2) + return i + + +def gamma_dist(x: float, a: float = 5, scale: float = 0.33): + """"""Calc gamma distribution. + + Args: + x (float): Description + a (float, optional): Description + scale (float, optional): Description + + Returns: + float: y + """""" + return gamma.pdf(x, a=a, scale=scale) + + +distributions = { + ""gauss"": gauss_dist, + ""gamma"": gamma_dist, + ""gauss_tail"": gauss_tail, +} # type: Dict[str, Callable] +","Python" +"Computational Biochemistry","LeidelLab/SMITER","smiter/__init__.py",".py","565","28","""""""Top-level package for SMITER."""""" + +__author__ = """"""Manuel Kösters"""""" +__email__ = ""manuel.koesters@dcb.unibe.ch"" +__version__ = ""0.1.0"" + +import os +import sys +import tempfile + +from loguru import logger + +import smiter.synthetic_mzml + +config = { + ""handlers"": [ + {""sink"": sys.stdout, ""level"": ""INFO""}, + { + ""sink"": os.path.join(tempfile.gettempdir(), ""smiter.log""), + ""compression"": ""gz"", + ""rotation"": ""100 MB"", + ""level"": ""DEBUG"", + ""backtrace"": True, + }, + ], +} +logger.configure(**config) +","Python" +"Computational Biochemistry","LeidelLab/SMITER","smiter/fragmentation_functions.py",".py","6900","216","""""""Callables for fragmenting molecules. + +Upon calling the callabe, a list/np.array of mz and intensities should be returned. +Arguments should be passed via *args and **kwargs +"""""" + +from abc import ABC, abstractmethod +from typing import Dict, List, Tuple, Union +import sys +import shutil +import subprocess +import os +import csv + +import numpy as np +import pandas as pd +import pyqms +from loguru import logger +from pyteomics import mass + +import smiter +from peptide_fragmentor import PeptideFragment0r +from smiter.ext.nucleoside_fragment_kb import ( + KB_FRAGMENTATION_INFO as pyrnams_nucleoside_fragment_kb, +) +from smiter.lib import calc_mz + +try: + from smiter.ext.nucleoside_fragment_kb import KB_FRAGMENTATION_INFO +except ImportError: # pragma: no cover + print(""Nucleoside fragmentation KB not available"") # pragma: no cover + + +class AbstractFragmentor(ABC): + """"""Summary."""""" + + @abstractmethod + def __init__(self): + """"""Summary."""""" + pass # pragma: no cover + + @abstractmethod + def fragment(self, entity): + """"""Summary. + + Args: + entity (TYPE): Description + """""" + pass # pragma: no cover + + +class PeptideFragmentor(AbstractFragmentor): + """"""Summary."""""" + + def __init__(self, *args, **kwargs): + """"""Summary."""""" + logger.info(""Initialize PeptideFragmentor"") + self.args = args + self.kwargs = kwargs + self.fragger = PeptideFragment0r() + + # @profile + def fragment(self, entities): + """"""Summary. + + Args: + entity (TYPE): Description + """""" + if isinstance(entities, str): + entities = [entities] + frames = [] + for entity in entities: + # logger.debug(f""Fragment {entity}"") + results_table = self.fragger.fragment(entity, **self.kwargs) + frames.append(results_table) + final_table = pd.concat(frames) + i = np.array([100 for i in range(len(final_table))]) + mz_i = np.stack((final_table[""mz""], i), axis=1) + return mz_i + + +class PeptideFragmentorPyteomics(AbstractFragmentor): + def __init__(self, *args, **kwargs): + pass + + # @profile + def _fragments(self, peptide, types=(""b"", ""y""), maxcharge=1): + for i in range(1, len(peptide) - 1): + for ion_type in types: + for charge in range(1, maxcharge + 1): + if ion_type[0] in ""abc"": + yield mass.fast_mass( + peptide[:i], ion_type=ion_type, charge=charge + ) + else: + yield mass.fast_mass( + peptide[i:], ion_type=ion_type, charge=charge + ) + + # @profile + def fragment(self, entities): + mz = [] + for e in entities: + a = list(self._fragments(e)) + mz.extend(a) + i = np.array([100 for x in range(len(mz))]) + mz = np.array(mz) + mz_i = np.stack((mz, i), axis=1) + return mz_i + + +class NucleosideFragmentor(AbstractFragmentor): + """"""Summary."""""" + + def __init__( + self, + nucleotide_fragment_kb: Dict[str, dict] = None, + raise_error_for_non_existing_fragments=True, + ): + """"""Summary."""""" + logger.info(""Initialize NucleosideFragmentor"") + if nucleotide_fragment_kb is None: + nucleoside_fragment_kb = pyrnams_nucleoside_fragment_kb + self.raise_error_for_non_existing_fragments = ( + raise_error_for_non_existing_fragments + ) + nuc_to_fragments: Dict[str, List[float]] = {} + cc = pyqms.chemical_composition.ChemicalComposition() + for nuc_name, nuc_dict in nucleoside_fragment_kb.items(): + nuc_to_fragments[nuc_name] = [] + for frag_name, frag_cc_dict in nucleoside_fragment_kb[nuc_name][ + ""fragments"" + ].items(): + cc.use(f""+{frag_cc_dict['formula']}"") + m = cc._mass() + nuc_to_fragments[nuc_name].append(calc_mz(m, 1)) + self.nuc_to_fragments = nuc_to_fragments + + def fragment( + self, entities: Union[list, str], raise_error_for_non_existing_fragments=False + ): + """"""Summary. + + Args: + entity (TYPE): Description + """""" + if isinstance(entities, str): + entities = [entities] + m = [] + for entity in entities: + if raise_error_for_non_existing_fragments is True: + masses = self.nuc_to_fragments[entity] + else: + masses = self.nuc_to_fragments.get(entity, []) + m.extend(masses) + # logger.debug(masses) + # should overlapping peaks be divided into two very similar ones? + m = sorted(list(set(m))) + # logger.debug(m) + return np.array([(mass, 1) for mass in m]) + + +class LipidFragmentor(AbstractFragmentor): + """"""Summary."""""" + + def __init__( + self, + lipid_input_csv: str = None, + raise_error_for_non_existing_fragments=True, + ): + """"""Use LipidCreator to calculate precursor transitions of lipids."""""" + self.lip_to_fragments = {} + # TODO run lipid fragmenter here, read output file and collect results in dict + commands: List[str] = [] + if sys.platform == ""linux"" or sys.platform == ""darwin"": + commands.append(""mono"") + lipid_creator_path = shutil.which(""LipidCreator.exe"") + else: + # will this work under windows? + lipid_creator_path = ""LipidCreator"" + commands.extend( + [lipid_creator_path, ""transitionlist"", lipid_input_csv, ""lipid_output.csv""] + ) + proc = subprocess.run(commands) + with open(""lipid_output.csv"") as fin: + for line in csv.DictReader(fin): + if line[""PrecursorName""] not in self.lip_to_fragments: + self.lip_to_fragments[line[""PrecursorName""]] = [] + self.lip_to_fragments[line[""PrecursorName""]].append( + float(line[""ProductMz""]) + ) + os.remove(""lipid_output.csv"") + + def fragment( + self, entities: Union[list, str], raise_error_for_non_existing_fragments=False + ): + """"""Summary. + + Args: + entity (TYPE): Description + """""" + if isinstance(entities, str): + entities = [entities] + m = [] + for entity in entities: + if raise_error_for_non_existing_fragments is True: + masses = self.lip_to_fragments[entity] + else: + masses = self.lip_to_fragments.get(entity, []) + m.extend(masses) + # logger.debug(masses) + # should overlapping peaks be divided into two very similar ones? + m = sorted(list(set(m))) + # logger.debug(m) + return np.array([(mass, 1) for mass in m]) +","Python" +"Computational Biochemistry","LeidelLab/SMITER","smiter/noise_functions.py",".py","14777","456","""""""Callables for injection noise into scans. + +Upon calling the callabe, a list/np.array of mz and intensities should be returned. +Arguments should be passed via *args and **kwargs +"""""" + +import math +from abc import ABC, abstractmethod +from typing import Dict, List, Tuple + +import numpy as np +import pyqms +from loguru import logger + +import smiter +from smiter.lib import calc_mz + +# from smiter.synthetic_mzml import Scan +# import smiter.synthetic_mzml + + +class AbstractNoiseInjector(ABC): + """"""Summary."""""" + + def __init__(self, *args, **kwargs): + """"""Initialize noise injector."""""" + pass # pragma: no cover + + @abstractmethod + def inject_noise(self, scan, *args, **kwargs): + """"""Main noise injection method. + + Args: + scan (Scan): Scan object + *args: Description + **kwargs: Description + + """""" + pass # pragma: no cover + + @abstractmethod + def _ms1_noise(self, scan, *args, **kwargs): + pass # pragma: no cover + + @abstractmethod + def _msn_noise(self, scan, *args, **kwargs): + pass # pragma: no cover + + +class GaussNoiseInjector(AbstractNoiseInjector): + def __init__(self, *args, **kwargs): + # np.random.seed(1312) + logger.info(""Initialize GaussNoiseInjector"") + self.args = args + self.kwargs = kwargs + + def inject_noise(self, scan, *args, **kwargs): + """"""Main noise injection method. + + Args: + scan (Scan): Scan object + *args: Description + **kwargs: Description + + """""" + self.kwargs.update(kwargs) + # self.args += args + if scan.ms_level == 1: + scan = self._ms1_noise(scan, *self.args, **self.kwargs) + elif scan.ms_level > 1: + scan = self._msn_noise(scan, *args, **kwargs) + return scan + + def _ms1_noise(self, scan, *args, **kwargs): + """"""Generate ms1 noise. + + Args: + scan (Scan): Description + *args: Description + **kwargs: Description + """""" + mz_noise = self._generate_mz_noise(scan, *args, **kwargs) + intensity_noise = self._generate_intensity_noise(scan, *args, **kwargs) + scan.mz += mz_noise + scan.i += intensity_noise + scan.i[scan.i < 0] = 0 + return scan + + def _msn_noise(self, scan, *args, **kwargs): + """"""Generate msn noise. + + Args: + scan (Scan): Description + *args: Description + **kwargs: Description + """""" + mz_noise = self._generate_mz_noise(scan, *args, **kwargs) + intensity_noise = self._generate_intensity_noise(scan, *args, **kwargs) + scan.mz += mz_noise + scan.i += intensity_noise + scan.i[scan.i < 0] = 0 + # remove some mz values + dropout = kwargs.get(""dropout"", 0.1) + dropout_mask = [ + False if c < dropout else True for c in np.random.random(len(scan.mz)) + ] + scan.mz = scan.mz[dropout_mask] + scan.i = scan.i[dropout_mask] + return scan + + def _generate_mz_noise(self, scan, *args, **kwargs): + """"""Generate noise for mz_array. + + Args: + scan (Scan): Scan object + *args: Description + **kwargs: Description + """""" + ppm_offset = kwargs.get(""ppm_offset"", 0) + ppm_var = kwargs.get(""ppm_var"", 1) + noise_level = np.random.normal(0, ppm_var * 1e-6, len(scan.mz)) + # noise_level = np.zeros(len(scan.mz)) + noise = scan.mz * noise_level + # noise = np.zeros(len(scan.mz)) + return noise + + def _generate_intensity_noise(self, scan, *args, **kwargs): + """"""Generate intensity noise. + + Args: + scan (Scan): Scan object + *args: Description + **kwargs: Description + """""" + noise = np.random.normal( + # np.array(np.zeros(len(scan.i))), + np.array(scan.i), + np.array(scan.i) * kwargs.get(""variance"", 0.02), + len(scan.i), + ) + return noise - scan.i + + +class UniformNoiseInjector(AbstractNoiseInjector): + def __init__(self, *args, **kwargs): + # np.random.seed(1312) + logger.info(""Initialize UniformNoiseInjector"") + self.args = args + self.kwargs = kwargs + + def inject_noise(self, scan, *args, **kwargs): + """"""Main noise injection method. + + Args: + scan (Scan): Scan object + *args: Description + **kwargs: Description + + """""" + self.kwargs.update(kwargs) + # self.args += args + if scan.ms_level == 1: + scan = self._ms1_noise(scan, *self.args, **self.kwargs) + elif scan.ms_level > 1: + scan = self._msn_noise(scan, *self.args, **self.kwargs) + return scan + + def _ms1_noise(self, scan, *args, **kwargs): + """"""Generate ms1 noise. + + Args: + scan (Scan): Description + *args: Description + **kwargs: Description + """""" + mz_noise = self._generate_mz_noise(scan, *args, **kwargs) + intensity_noise = self._generate_intensity_noise(scan, *args, **kwargs) + scan.mz += mz_noise + scan.i += intensity_noise + scan.i[scan.i < 0] = 0 + return scan + + def _msn_noise(self, scan, *args, **kwargs): + """"""Generate msn noise. + + Args: + scan (Scan): Description + *args: Description + **kwargs: Description + """""" + mz_noise = self._generate_mz_noise(scan, *args, **kwargs) + intensity_noise = self._generate_intensity_noise(scan, *args, **kwargs) + scan.mz += mz_noise + scan.i += intensity_noise + scan.i[scan.i < 0] = 0 + # scan.mz[scan.mz < 0] = 0 + dropout = kwargs.get(""dropout"", 0.1) + dropout_mask = [ + False if c < dropout else True for c in np.random.random(len(scan.mz)) + ] + scan.mz = scan.mz[dropout_mask] + scan.i = scan.i[dropout_mask] + return scan + + def _generate_mz_noise(self, scan, *args, **kwargs): + """"""Generate noise for mz_array. + + Args: + scan (Scan): Scan object + *args: Description + **kwargs: Description + """""" + # noise_level = np.random.normal(ppm_offset * 5e-6, ppm_var * 5e-6, len(scan.mz)) + # get scaling from kwargs + noise = np.random.uniform( + (scan.mz * kwargs.get(""ppm_noise"", 5e-6)) * -1, + scan.mz * kwargs.get(""ppm_noise"", 5e-6), + ) + # noise = scan.mz * noise_level + return noise + + def _generate_intensity_noise(self, scan, *args, **kwargs): + """"""Generate intensity noise. + + Args: + scan (Scan): Scan object + *args: Description + **kwargs: Description + """""" + # get scaling from kwargs + noise = np.random.uniform( + (scan.i * kwargs.get(""intensity_noise"", 0.2)) * -1, + scan.i * kwargs.get(""intensity_noise"", 0.2), + ) + return noise + + +class PPMShiftInjector(AbstractNoiseInjector): + def __init__(self, *args, **kwargs): + # np.random.seed(1312) + logger.info(""Initialize PPMShiftInjector"") + self.args = args + self.kwargs = kwargs + + def inject_noise(self, scan, *args, **kwargs): + """"""Main noise injection method. + + Args: + scan (Scan): Scan object + *args: Description + **kwargs: Description + + """""" + self.kwargs.update(kwargs) + # self.args += args + if scan.ms_level == 1: + scan = self._ms1_noise(scan, *self.args, **self.kwargs) + elif scan.ms_level > 1: + scan = self._msn_noise(scan, *self.args, **self.kwargs) + return scan + + def _ms1_noise(self, scan, *args, **kwargs): + """"""Generate ms1 noise. + + Args: + scan (Scan): Description + *args: Description + **kwargs: Description + """""" + mz_noise = self._generate_mz_noise(scan, *args, **kwargs) + intensity_noise = self._generate_intensity_noise(scan, *args, **kwargs) + scan.mz += mz_noise + scan.i += intensity_noise + scan.i[scan.i < 0] = 0 + return scan + + def _msn_noise(self, scan, *args, **kwargs): + """"""Generate msn noise. + + Args: + scan (Scan): Description + *args: Description + **kwargs: Description + """""" + mz_noise = self._generate_mz_noise(scan, *args, **kwargs) + intensity_noise = self._generate_intensity_noise(scan, *args, **kwargs) + scan.mz += mz_noise + scan.i += intensity_noise + scan.i[scan.i < 0] = 0 + # scan.mz[scan.mz < 0] = 0 + dropout = kwargs.get(""dropout"", 0.1) + dropout_mask = [ + False if c < dropout else True for c in np.random.random(len(scan.mz)) + ] + scan.mz = scan.mz[dropout_mask] + scan.i = scan.i[dropout_mask] + return scan + + def _generate_mz_noise(self, scan, *args, **kwargs): + """"""Generate noise for mz_array. + + Args: + scan (Scan): Scan object + *args: Description + **kwargs: Description + """""" + # noise_level = np.random.normal(ppm_offset * 5e-6, ppm_var * 5e-6, len(scan.mz)) + # get scaling from kwargs + offset = self.kwargs[""offset""] + sigma = self.kwargs[""sigma""] + noise = np.random.normal(offset, sigma, len(scan.mz)) + noise = noise * scan.mz + return noise + + def _generate_intensity_noise(self, scan, *args, **kwargs): + """"""Generate intensity noise. + + Args: + scan (Scan): Scan object + *args: Description + **kwargs: Description + """""" + # get scaling from kwargs + noise = [0 for x in range(len(scan.i))] + return noise + + +# TODO add white noise params +# TODO should be called MSpireNoiseInjector +class JamssNoiseInjector(AbstractNoiseInjector): + def __init__(self, *args, **kwargs): + """"""Noise injector based on this paper: + https://academic.oup.com/bioinformatics/article/31/5/791/318378 + + Args: + **kwargs: fine tuning for mz and itensity sigma + - m: scale mz noise sigma by this value + - y: controll falling of mz sigma with higher intensities with this + - a: scale intensity sigma by this + - b: controll falling of intensity sigma with higher intensities with this + - c: constant to add to intensity sigma + """""" + # np.random.seed(1312) + logger.info(""Initialize JamssNoiseInjector"") + self.args = args + self.kwargs = kwargs + + def inject_noise(self, scan, *args, **kwargs): + self.kwargs.update(kwargs) + if scan.ms_level == 1: + scan = self._ms1_noise(scan, *self.args, **self.kwargs) + elif scan.ms_level > 1: + scan = self._msn_noise(scan, *self.args, **self.kwargs) + return scan + + def _add_white_noise(self, scan): + n = int(np.random.uniform(100, 500)) + if sum(scan.i) == 0: + total_tic = 5e6 + else: + total_tic = sum(scan.i) + total_tic = 5e6 + # logger.info(f""Total TIC: {sum(scan.i)}"") + white_noise_i = np.random.uniform(1, 100, n) + max_perc_noise = 0.75 + min_perc_noise = 0.5 + white_noise_i = ( + white_noise_i + / white_noise_i.sum() + * np.random.uniform(min_perc_noise, max_perc_noise) + * total_tic + ) + # logger.info(f'Add white noise intensity: {white_noise_i}') + # scale = np.random.uniform(1e5, 1e8) / n + # white_noise_i *= scale + # logger.info(f""Noise: {sum(white_noise_i)}"") + white_noise_mz = np.random.uniform(0, 1200, n) + new_i = np.concatenate((scan.i, white_noise_i)) + new_mz = np.concatenate((scan.mz, white_noise_mz)) + # logger.info(f'Add new white noise {new_i}') + sort = new_mz.argsort() + scan.mz = new_mz[sort] + scan.i = new_i[sort] + return scan + + def _ms1_noise(self, scan, *args, **kwargs): + # i_b = sum(scan.i) + scan = self._add_white_noise(scan) + mz_noise = self._generate_mz_noise(scan, *args, **kwargs) + # logger.debug(f""MS1 mz noise: {mz_noise}"") + intensity_noise = self._generate_intensity_noise(scan, *args, **kwargs) + scan.mz += mz_noise + scan.i += intensity_noise + + # i_a = sum(scan.i) + # print(f'S2I: {i_b/i_a}') + scan.i[scan.i < 0] = 0 + return scan + + def _msn_noise(self, scan, *args, **kwargs): + mz_noise = self._generate_mz_noise(scan, *args, **kwargs) + # logger.debug(f""MSn mz noise: {mz_noise}"") + intensity_noise = self._generate_intensity_noise(scan, *args, **kwargs) + scan.mz += mz_noise + scan.i += intensity_noise + scan.i[scan.i < 0] = 0 + # scan.mz[scan.mz < 0] = 0 + dropout = kwargs.get(""dropout"", 0.1) + # logger.debug(f""Dropout: {dropout}"") + dropout_mask = [ + False if c < dropout else True for c in np.random.random(len(scan.mz)) + ] + scan.mz = scan.mz[dropout_mask] + scan.i = scan.i[dropout_mask] + scan = self._add_white_noise(scan) + return scan + + def _generate_mz_noise(self, scan, *args, **kwargs): + try: + norm_int = scan.i / max(scan.i) * 100 + except ValueError: + norm_int = np.array([]) + # TODO make variable parameters + # TODO Check mspire paper again for variables + # TODO pass data structure with max_i in elution profile and mzs calculate noise to intensity/max_i_in_profile + m = 0.001701 + # m = 0.1701 + y = 0.543 + y = 0.2 + sigma = m * norm_int ** (-y) + noise = np.random.normal(loc=scan.mz, scale=sigma) + noise -= scan.mz + noise_mock = np.zeros(len(scan.mz)) + return noise + + def _generate_intensity_noise(self, scan, *args, **kwargs): + try: + norm_int = scan.i / max(scan.i) * 100 + except ValueError: + norm_int = np.array([]) + # TODO make variable parameters + # TODO Check mspire paper again for variables + # TODO pass data structure with max_i in elution profile and mzs calculate noise to intensity/max_i_in_profile + m = 0.001701 + m = 10.34 + c = 0.00712 + d = 0.12 + sigma = m * (1 - math.e ** (-c * norm_int)) + d + noise = np.random.normal(loc=0, scale=sigma) + if len(scan.i) > 0: + noise *= max(scan.i) / 100 + else: + noise = np.array([]) + # TODO add white noise points with noise = x * tic (0 < x < 1) + return noise +","Python" +"Computational Biochemistry","LeidelLab/SMITER","smiter/cli.py",".py","380","18","""""""Console script for smiter."""""" + +import sys + +import click + + +@click.command() +def main(args=None): + """"""Console script for smiter."""""" + click.echo(""Replace this message by putting your code into smiter.cli.main"") + click.echo(""See click documentation at https://click.palletsprojects.com/"") + return 0 + + +if __name__ == ""__main__"": + sys.exit(main()) # pragma: no cover +","Python" +"Computational Biochemistry","LeidelLab/SMITER","smiter/synthetic_mzml.py",".py","22598","660","""""""Main module."""""" + +import io +import pathlib +import time +import warnings +from pprint import pformat +from typing import Callable, Dict, List, Tuple, Union +from collections import Counter + +import numpy as np +import pyqms +import scipy as sci +from intervaltree import IntervalTree +from loguru import logger +from psims.mzml import MzMLWriter +from tqdm import tqdm + +import smiter +from smiter.fragmentation_functions import AbstractFragmentor +from smiter.lib import ( + calc_mz, + check_mzml_params, + check_peak_properties, + peak_properties_to_csv, +) +from smiter.noise_functions import AbstractNoiseInjector +from smiter.peak_distribution import distributions + +warnings.filterwarnings(""ignore"") + + +class Scan(dict): + """"""Summary."""""" + + def __init__(self, data: dict = None): + """"""Summary. + + Args: + dict (TYPE): Description + """""" + if data is not None: + self.update(data) + + @property + def mz(self): + """"""Summary."""""" + v = self.get(""mz"", None) + return v + + @mz.setter + def mz(self, mz): + """"""Summary."""""" + self[""mz""] = mz + + @property + def i(self): + """"""Summary."""""" + v = self.get(""i"", None) + return v + + @i.setter + def i(self, i): + """"""Summary."""""" + self[""i""] = i + + @property + def id(self): + """"""Summary."""""" + v = self.get(""id"", None) + return v + + @property + def precursor_mz(self): + """"""Summary."""""" + v = self.get(""precursor_mz"", None) + return v + + @property + def precursor_i(self): + """"""Summary."""""" + v = self.get(""precursor_i"", None) + return v + + @property + def precursor_charge(self): + """"""Summary."""""" + v = self.get(""precursor_charge"", None) + return v + + # @property + # def precursor_scan_id(self): + # """"""Summary."""""" + # v = self.get(""precursor_scan_id"", None) + # return v + + @property + def retention_time(self): + """"""Summary."""""" + v = self.get(""rt"", None) + return v + + @property + def ms_level(self): + """"""Summary. + + Returns: + TYPE: Description + """""" + v = self.get(""ms_level"", None) + return v + + +def generate_interval_tree(peak_properties): + """"""Conctruct an interval tree containing the elution windows of the analytes. + + Args: + peak_properties (dict): Description + + Returns: + IntervalTree: Description + """""" + tree = IntervalTree() + for key, data in peak_properties.items(): + start = data[""scan_start_time""] + end = start + data[""peak_width""] + tree[start:end] = key + return tree + + +# @profile +def write_mzml( + file: Union[str, io.TextIOWrapper], + peak_properties: Dict[str, dict], + fragmentor: AbstractFragmentor, + noise_injector: AbstractNoiseInjector, + mzml_params: Dict[str, Union[int, float, str]], +) -> str: + """"""Write mzML file with chromatographic peaks and fragment spectra for the given molecules. + + Args: + file (Union[str, io.TextIOWrapper]): Description + molecules (List[str]): Description + fragmentation_function (Callable[[str], List[Tuple[float, float]]], optional): Description + peak_properties (Dict[str, dict], optional): Description + """""" + # check params and raise Exception(s) if necessary + logger.info(""Start generating mzML"") + mzml_params = check_mzml_params(mzml_params) + peak_properties = check_peak_properties(peak_properties) + + interval_tree = generate_interval_tree(peak_properties) + + filename = file if isinstance(file, str) else file.name + scans = [] + + trivial_names = {} + charges = set() + for key, val in peak_properties.items(): + trivial_names[val[""chemical_formula""]] = key + charges.add(val[""charge""]) + # trivial_names = { + # val[""chemical_formula""]: key for key, val in peak_properties.items() + # } + # dicts are sorted, language specification since python 3.7+ + + isotopologue_lib = generate_molecule_isotopologue_lib( + peak_properties, trivial_names=trivial_names, charges=charges + ) + scans, scan_dict = generate_scans( + isotopologue_lib, + peak_properties, + interval_tree, + fragmentor, + noise_injector, + mzml_params, + ) + logger.info(""Delete interval tree"") + del interval_tree + write_scans(file, scans) + if not isinstance(file, str): + file_path = file.name + else: + file_path = file + path = pathlib.Path(file_path) + summary_path = path.parent.resolve() / ""molecule_summary.csv"" + peak_properties_to_csv(peak_properties, summary_path) + return filename + + +# @profile +def rescale_intensity( + i: float, rt: float, molecule: str, peak_properties: dict, isotopologue_lib: dict +): + """"""Rescale intensity value for a given molecule according to scale factor and distribution function. + + Args: + i (TYPE): Description + rt (TYPE): Description + molecule (TYPE): Description + peak_properties (TYPE): Description + isotopologue_lib (TYPE): Description + + Returns: + TYPE: Description + """""" + scale_func = peak_properties[f""{molecule}""][""peak_function""] + rt_max = ( + peak_properties[f""{molecule}""][""scan_start_time""] + + peak_properties[f""{molecule}""][""peak_width""] + ) + + if scale_func == ""gauss"": + mu = ( + peak_properties[f""{molecule}""][""scan_start_time""] + + 0.5 * peak_properties[f""{molecule}""][""peak_width""] + ) + dist_scale_factor = distributions[scale_func]( + rt, + mu=mu, + sigma=peak_properties[f""{molecule}""][""peak_params""].get( + ""sigma"", peak_properties[f""{molecule}""][""peak_width""] / 10 + ), + ) + elif scale_func == ""gamma"": + dist_scale_factor = distributions[scale_func]( + rt, + a=peak_properties[f""{molecule}""][""peak_params""][""a""], + scale=peak_properties[f""{molecule}""][""peak_params""][""scale""], + ) + elif scale_func == ""gauss_tail"": + mu = ( + peak_properties[f""{molecule}""][""scan_start_time""] + + 0.3 * peak_properties[f""{molecule}""][""peak_width""] + ) + dist_scale_factor = distributions[scale_func]( + rt, + mu=mu, + sigma=0.12 * (rt - peak_properties[f""{molecule}""][""scan_start_time""]) + 2, + scan_start_time=peak_properties[f""{molecule}""][""scan_start_time""], + ) + elif scale_func is None: + dist_scale_factor = 1 + # TODO use ionization_effiency here + i *= ( + dist_scale_factor + * peak_properties[f""{molecule}""].get(""peak_scaling_factor"", 1e3) + * peak_properties[f""{molecule}""].get(""ionization_effiency"", 1) + ) + return i + + +def generate_scans( + isotopologue_lib: dict, + peak_properties: dict, + interval_tree: IntervalTree, + fragmentor: AbstractFragmentor, + noise_injector: AbstractNoiseInjector, + mzml_params: dict, +): + """"""Summary. + + Args: + isotopologue_lib (TYPE): Description + peak_properties (TYPE): Description + fragmentation_function (A): Description + mzml_params (TYPE): Description + """""" + logger.info(""Initialize chimeric spectra counter"") + chimeric_count = 0 + chimeric = Counter() + logger.info(""Start generating scans"") + t0 = time.time() + gradient_length = mzml_params[""gradient_length""] + ms_rt_diff = mzml_params.get(""ms_rt_diff"", 0.03) + t: float = 0 + + mol_scan_dict: Dict[str, Dict[str, list]] = {} + scans: List[Tuple[Scan, List[Scan]]] = [] + # i: int = 0 + spec_id: int = 1 + de_tracker: Dict[str, int] = {} + de_stats: dict = {} + + mol_scan_dict = { + mol: {""ms1_scans"": [], ""ms2_scans"": []} for mol in isotopologue_lib + } + molecules = list(isotopologue_lib.keys()) + + progress_bar = tqdm( + total=gradient_length, + desc=""Generating scans"", + bar_format=""{desc}: {percentage:3.0f}%|{bar}| {n:.2f}/{total_fmt} [{elapsed}<{remaining}"", + ) + while t < gradient_length: + scan_peaks: List[Tuple[float, float]] = [] + scan_peaks = {} + mol_i = [] + mol_monoisotopic = {} + candidates = interval_tree.at(t) + # print(len(candidates)) + for mol in candidates: + # if len(candidates) > 1: + mol = mol.data + mol_plus = f""{mol}"" + mz = np.array(isotopologue_lib[mol][""mz""]) + intensity = np.array(isotopologue_lib[mol][""i""]) + intensity = rescale_intensity( + intensity, t, mol, peak_properties, isotopologue_lib + ) + + mask = intensity > mzml_params[""min_intensity""] + intensity = intensity[mask] + + # clip max intensity + intensity = np.clip( + intensity, a_min=None, a_max=mzml_params.get(""max_intensity"", 1e10) + ) + + mz = mz[mask] + mol_peaks = list(zip(mz, intensity)) + mol_peaks = {round(mz, 6): _i for mz, _i in list(zip(mz, intensity))} + # !FIXED! multiple molecules which share mz should have summed up intensityies for that shared mzs + if len(mol_peaks) > 0: + mol_i.append((mol, mz[0], sum(intensity))) + # scan_peaks.extend(mol_peaks) + for mz, intensity in mol_peaks.items(): + if mz in scan_peaks: + scan_peaks[mz] += intensity + else: + scan_peaks[mz] = intensity + mol_scan_dict[mol][""ms1_scans""].append(spec_id) + highest_peak = max(mol_peaks.items(), key=lambda x: x[1]) + mol_monoisotopic[mol] = { + ""mz"": highest_peak[0], + ""i"": highest_peak[1], + } + scan_peaks = sorted(list(scan_peaks.items()), key=lambda x: x[1]) + if len(scan_peaks) > 0: + mz, inten = zip(*scan_peaks) + else: + mz, inten = [], [] + + s = Scan( + { + ""mz"": np.array(mz), + ""i"": np.array(inten), + ""id"": spec_id, + ""rt"": t, + ""ms_level"": 1, + } + ) + prec_scan_id = spec_id + spec_id += 1 + + sorting = s.mz.argsort() + s.mz = s.mz[sorting] + s.i = s.i[sorting] + + # add noise + s = noise_injector.inject_noise(s) + + # i += 1 + scans.append((s, [])) + t += ms_rt_diff + progress_bar.update(ms_rt_diff) + + if t > gradient_length: + break + + fragment_spec_index = 0 + max_ms2_spectra = mzml_params.get(""max_ms2_spectra"", 10) + if len(mol_i) < max_ms2_spectra: + max_ms2_spectra = len(mol_i) + ms2_scan = None + mol_i = sorted(mol_i, key=lambda x: x[2], reverse=True) + logger.debug(f""All molecules eluting: {len(mol_i)}"") + logger.debug(f""currently # fragment spectra {len(scans[-1][1])}"") + + mol_i = [ + mol + for mol in mol_i + if (de_tracker.get(mol[0], None) is None) + or (t - de_tracker[mol[0]]) > mzml_params[""dynamic_exclusion""] + ] + logger.debug(f""All molecules eluting after DE filtering: {len(mol_i)}"") + while len(scans[-1][1]) != max_ms2_spectra: + logger.debug(f""Frag spec index {fragment_spec_index}"") + if fragment_spec_index > len(mol_i) - 1: + # we evaluated fragmentation for every potential mol + # and all will be skipped + logger.debug(f""All possible mol are skipped due to DE"") + break + mol = mol_i[fragment_spec_index][0] + _mz = mol_i[fragment_spec_index][1] + _intensity = mol_i[fragment_spec_index][2] + fragment_spec_index += 1 + mol_plus = f""{mol}"" + all_mols_in_mz_and_rt_window = [ + mol.data + for mol in candidates + if ( + abs(isotopologue_lib[mol.data][""mz""][0] - _mz) + < mzml_params[""isolation_window_width""] + ) + ] + if len(all_mols_in_mz_and_rt_window) > 1: + chimeric_count += 1 + chimeric[len(all_mols_in_mz_and_rt_window)] += 1 + if mol is None: + # dont add empty MS2 scans but have just a much scans as precursors + breakpoint() + ms2_scan = Scan( + { + ""mz"": np.array([]), + ""i"": np.array([]), + ""rt"": t, + ""id"": spec_id, + ""precursor_mz"": 0, + ""precursor_i"": 0, + ""precursor_charge"": 1, + ""precursor_scan_id"": prec_scan_id, + ""ms_level"": 2, + } + ) + spec_id += 1 + t += ms_rt_diff + progress_bar.update(ms_rt_diff) + + if t > gradient_length: + break + elif (peak_properties[mol_plus][""scan_start_time""] <= t) and ( + ( + peak_properties[mol_plus][""scan_start_time""] + + peak_properties[mol_plus][""peak_width""] + ) + >= t + ): + # fragment all molecules in isolation and rt window + # check if molecule needs to be fragmented according to dynamic_exclusion rule + if ( + de_tracker.get(mol, None) is None + or (t - de_tracker[mol]) > mzml_params[""dynamic_exclusion""] + ): + logger.debug(""Generate Fragment spec"") + de_tracker[mol] = t + if mol not in de_stats: + de_stats[mol] = {""frag_events"": 0, ""frag_spec_ids"": []} + de_stats[mol][""frag_events""] += 1 + de_stats[mol][""frag_spec_ids""].append(spec_id) + peaks = fragmentor.fragment(all_mols_in_mz_and_rt_window) + frag_mz = peaks[:, 0] + frag_i = peaks[:, 1] + ms2_scan = Scan( + { + ""mz"": frag_mz, + ""i"": frag_i, + ""rt"": t, + ""id"": spec_id, + ""precursor_mz"": mol_monoisotopic[mol][""mz""], + ""precursor_i"": mol_monoisotopic[mol][""i""], + ""precursor_charge"": peak_properties[mol][""charge""], + ""precursor_scan_id"": prec_scan_id, + ""ms_level"": 2, + } + ) + spec_id += 1 + ms2_scan.i = rescale_intensity( + ms2_scan.i, t, mol, peak_properties, isotopologue_lib + ) + ms2_scan = noise_injector.inject_noise(ms2_scan) + ms2_scan.i *= 0.5 + else: + logger.debug(f""Skip {mol} due to dynamic exclusion"") + continue + t += ms_rt_diff + progress_bar.update(ms_rt_diff) + if t > gradient_length: + break + else: + logger.debug(f""Skip {mol} since not in RT window"") + continue + if mol is not None: + mol_scan_dict[mol][""ms2_scans""].append(spec_id) + if ms2_scan is None: + # there are molecules in mol_i + # however all molecules are excluded from fragmentation_function + # => Don't do a scan and break the while loop + # => We should rather continue and try to fragment the next mol! + logger.debug(f""Continue and fragment next mol since MS2 scan is None"") + continue + if ( + len(ms2_scan.mz) > -1 + ): # TODO -1 to also add empty ms2 specs; 0 breaks tests currently .... + sorting = ms2_scan.mz.argsort() + ms2_scan.mz = ms2_scan.mz[sorting] + ms2_scan.i = ms2_scan.i[sorting] + logger.debug(f""Append MS2 scan with {mol}"") + scans[-1][1].append(ms2_scan) + progress_bar.close() + t1 = time.time() + logger.info(""Finished generating scans"") + logger.info(f""Generating scans took {t1-t0:.2f} seconds"") + logger.info(f""Found {chimeric_count} chimeric scans"") + + return scans, mol_scan_dict + + +# @profile +def generate_molecule_isotopologue_lib( + peak_properties: Dict[str, dict], + charges: List[int] = None, + trivial_names: Dict[str, str] = None, +): + """"""Summary. + + Args: + molecules (TYPE): Description + """""" + logger.info(""Generate Isotopolgue Library"") + start = time.time() + duplicate_formulas: Dict[str, List[str]] = {} + for key in peak_properties: + duplicate_formulas.setdefault( + peak_properties[key][""chemical_formula""], [] + ).append(key) + if charges is None: + charges = [1] + if len(peak_properties) > 0: + molecules = [d[""chemical_formula""] for d in peak_properties.values()] + lib = pyqms.IsotopologueLibrary( + molecules=molecules, + charges=charges, + verbose=False, + trivial_names=trivial_names, + ) + reduced_lib = {} + # TODO fix to support multiple charge states + for mol in molecules: + formula = lib.lookup[""molecule to formula""][mol] + data = lib[formula][""env""][((""N"", ""0.000""),)] + for triv in lib.lookup[""formula to trivial name""][formula]: + reduced_lib[triv] = { + ""mz"": data[peak_properties[triv][""charge""]][""mz""], + ""i"": data[""relabun""], + } + else: + reduced_lib = {} + tmp = {} + for mol in reduced_lib: + cc = peak_properties[mol][""chemical_formula""] + for triv in duplicate_formulas[cc]: + if triv not in reduced_lib: + tmp[triv] = reduced_lib[mol] + reduced_lib.update(tmp) + logger.info( + f""Generating IsotopologueLibrary took {(time.time() - start)/60} minutes"" + ) + return reduced_lib + + +# @profile +def write_scans( + file: Union[str, io.TextIOWrapper], scans: List[Tuple[Scan, List[Scan]]] +) -> None: + """"""Generate given scans to mzML file. + + Args: + file (Union[str, io.TextIOWrapper]): Description + scans (List[Tuple[Scan, List[Scan]]]): Description + + Returns: + None: Description + """""" + t0 = time.time() + logger.info(""Start writing Scans"") + ms1_scans = len(scans) + ms2_scans = 0 + ms2_scan_list = [] + for s in scans: + ms2_scans += len(s[1]) + ms2_scan_list.append(len(s[1])) + logger.info(""Write {0} MS1 and {1} MS2 scans"".format(ms1_scans, ms2_scans)) + id_format_str = ""controllerType=0 controllerNumber=1 scan={i}"" + with MzMLWriter(file) as writer: + # Add default controlled vocabularies + writer.controlled_vocabularies() + writer.format() + # Open the run and spectrum list sections + time_array = [] + intensity_array = [] + with writer.run(id=""Simulated Run""): + spectrum_count = len(scans) + sum([len(products) for _, products in scans]) + with writer.spectrum_list(count=spectrum_count): + for scan, products in scans: + # Write Precursor scan + try: + index_of_max_i = np.argmax(scan.i) + max_i = scan.i[index_of_max_i] + mz_at_max_i = scan.mz[index_of_max_i] + except ValueError: + mz_at_max_i = 0 + max_i = 0 + spec_tic = sum(scan.i) + writer.write_spectrum( + scan.mz, + scan.i, + id=id_format_str.format(i=scan.id), + params=[ + ""MS1 Spectrum"", + {""ms level"": 1}, + { + ""scan start time"": scan.retention_time, + ""unit_name"": ""seconds"", + }, + {""total ion current"": spec_tic}, + {""base peak m/z"": mz_at_max_i, ""unitName"": ""m/z""}, + { + ""base peak intensity"": max_i, + ""unitName"": ""number of detector counts"", + }, + ], + ) + time_array.append(scan.retention_time) + intensity_array.append(spec_tic) + # Write MSn scans + for prod in products: + writer.write_spectrum( + prod.mz, + prod.i, + id=id_format_str.format(i=prod.id), + params=[ + ""MSn Spectrum"", + {""ms level"": 2}, + { + ""scan start time"": prod.retention_time, + ""unit_name"": ""seconds"", + }, + {""total ion current"": sum(prod.i)}, + ], + precursor_information={ + ""mz"": prod.precursor_mz, + ""intensity"": prod.precursor_i, + ""charge"": prod.precursor_charge, + ""scan_id"": id_format_str.format(i=scan.id), + ""spectrum_reference"": id_format_str.format(i=scan.id), + ""activation"": [""HCD"", {""collision energy"": 25.0}], + }, + ) + with writer.chromatogram_list(count=1): + writer.write_chromatogram( + time_array, + intensity_array, + id=""TIC"", + chromatogram_type=""total ion current"", + ) + t1 = time.time() + logger.info(f""Writing mzML took {(t1-t0)/60:.2f} minutes"") + return +","Python" +"Computational Biochemistry","LeidelLab/SMITER","smiter/lib.py",".py","4563","139","""""""Core functionality."""""" + +import csv +from io import TextIOWrapper +from tempfile import _TemporaryFileWrapper + +from loguru import logger + +from smiter.params.default_params import default_mzml_params, default_peak_properties + +PROTON = 1.00727646677 + + +def calc_mz(mass: float, charge: int): + """"""Calculate m/z. + + Args: + mass (TYPE): Description + charge (TYPE): Description + """""" + mass = float(mass) + charge = int(charge) + calc_mz = (mass + (charge * PROTON)) / charge + return calc_mz + + +def check_mzml_params(mzml_params: dict) -> dict: + """"""Summary. + + Args: + mzml_params (dict): Description + + Returns: + dict: Description + + Raises: + Exception: Description + """""" + logger.info(""Checking mzML params"") + for default_param, default_value in default_mzml_params.items(): + # param not set and default param required + if (mzml_params.get(default_param, None) is None) and (default_value is None): + raise Exception(f""mzml parameter {default_param} is required by not set!"") + elif mzml_params.get(default_param, None) is None: + mzml_params[default_param] = default_value + return mzml_params + + +def check_peak_properties(peak_properties: dict) -> dict: + """"""Summary. + + Args: + peak_properties (dict): Description + + Returns: + dict: Description + + Raises: + Exception: Description + """""" + logger.info(""Checking peak properties"") + for mol, properties in peak_properties.items(): + for default_param, default_value in default_peak_properties.items(): + if (properties.get(default_param, None) is None) and ( + default_value is None + ): + raise Exception( + f""mzml parameter {default_param} is required by not set!"" + ) + elif properties.get(default_param, None) is None: + properties[default_param] = default_value + return peak_properties + + +def csv_to_peak_properties(csv_file): + logger.info(f""Read peak properties from {csv_file}"") + peak_properties = {} + with open(csv_file) as fin: + reader = csv.DictReader(fin) + for line_dict in reader: + cc = line_dict[""chemical_formula""] + tn = line_dict[""trivial_name""] + peak_properties[tn] = { + ""trivial_name"": line_dict[""trivial_name""], + ""chemical_formula"": cc, + ""charge"": int(line_dict.get(""charge"", 2)), + ""scan_start_time"": float(line_dict[""scan_start_time""]), + # currently only gaussian peaks from csv + ""peak_function"": ""gauss_tail"", + # ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": float(line_dict.get(""sigma"", 2))}, + ""peak_scaling_factor"": float(line_dict[""peak_scaling_factor""]), + ""peak_width"": float(line_dict.get(""peak_width"", 30)), + } + return peak_properties + + +def peak_properties_to_csv(peak_properties, csv_file): + logger.info(f""Write peak properties to {csv_file}"") + if not isinstance(csv_file, TextIOWrapper): + csv_file = open(csv_file, ""w"") + csv_filename = csv_file.name + fieldnames = [ + ""chemical_formula"", + ""trivial_name"", + ""charge"", + ""scan_start_time"", + ""peak_width"", + ""peak_scaling_factor"", + ""peak_function"", + ""peak_params"", + ] + writer = csv.DictWriter(csv_file, fieldnames=fieldnames) + writer.writeheader() + for trivial_name, attribs in peak_properties.items(): + line = { + ""chemical_formula"": peak_properties[trivial_name].get( + ""chemical_formula"", """" + ), + # ""trivial_name"": peak_properties[cc].get(""trivial_name"", """"), + ""trivial_name"": trivial_name, + ""charge"": peak_properties[trivial_name].get(""charge"", 2), + ""scan_start_time"": peak_properties[trivial_name][""scan_start_time""], + ""peak_function"": peak_properties[trivial_name][""peak_function""], + ""peak_params"": "","".join( + [ + f""{key}={val}"" + for key, val in peak_properties[trivial_name][""peak_params""].items() + ] + ), + ""peak_scaling_factor"": peak_properties[trivial_name].get( + ""peak_scaling_factor"", 1e3 + ), + ""peak_width"": peak_properties[trivial_name][""peak_width""], + } + writer.writerow(line) + csv_file.close() + return csv_filename +","Python" +"Computational Biochemistry","LeidelLab/SMITER","smiter/params/header_param.py",".py","87","5","#!/usr/bin/env python +""""""Param sets for mzML header section."""""" + +orbitrap_generic = [] +","Python" +"Computational Biochemistry","LeidelLab/SMITER","smiter/params/default_params.py",".py","601","23","# None means required, other is default value +# non existent params are optional +default_peak_properties = { + # trivial_name + ""charge"": 2, + ""scan_start_time"": None, # required + ""peak_width"": None, # required + # ""peak_function"": ""gauss"", +} + +default_mzml_params = { + ""gradient_length"": None, + ""min_intensity"": 100, + ""max_intensity"": 1e10, # what would be reasonable? + ""isolation_window_width"": 0.5, + ""ion_target"": 3e6, + ""ms_rt_diff"": 0.03, + ""dynamic_exclusion"": 30, # in seconds + ""max_ms2_spectra"": 10, + ""mz_lower_limit"": 100, + ""mz_upper_limit"": 1600, +} +","Python" +"Computational Biochemistry","LeidelLab/SMITER","smiter/ext/trim_lines.py",".py","461","23","#!/usr/bin/env python +import errno +import fileinput +import sys + + +def main(): + try: + for i, line in enumerate(fileinput.input()): + if i == 0: + sys.stdout.write(line) + continue + line = line.split("","")[2:] + sys.stdout.write("","".join(line)) + sys.stdout.flush() + except IOError as e: + if e.errno == errno.EPIPE: + sys.exit(1) + + +if __name__ == ""__main__"": + main() +","Python" +"Computational Biochemistry","LeidelLab/SMITER","smiter/ext/__init__.py",".py","26","2","""""""External resources."""""" +","Python" +"Computational Biochemistry","LeidelLab/SMITER","smiter/ext/nucleoside_fragment_kb.py",".py","55218","1497","""""""Mapping nucleoside names to its fragments."""""" + +KB_FRAGMENTATION_INFO: dict = { + ""uridine"": { + # U + ""comments"": ""precursor can not be seen in MS2 in some cases"", + ""references"": [""Jora et al. 2018""], + ""fragments"": { + ""uridine -Ribose"": {""formula"": ""C(4)H(4)N(2)O(2)""}, # 113.0345538436 + ""uridine -Ribose -N(1)H(3)"": { + ""formula"": ""C(4)H(1)N(1)O(2)"", # 96.0080047430 + ""hcd"": True, + }, + }, + ""precursors"": { + ""uridine"": {}, + ""uridine dimer"": {}, + }, + }, + ""5-methyluridine"": { + # m5U + ""comments"": """", + ""references"": [""Jora et al. 2018""], + ""precursors"": { + ""5-methyluridine"": {}, + ""5-methyluridine +N(1)H(2)"": {""formula"": ""C(10)H(16)N(3)O(6)""}, + ""5-methyluridine dimer"": {}, + }, + ""fragments"": { + ""5-methyluridine -Ribose"": {""formula"": ""C(5)H(6)N(2)O(2)""}, + ""5-methyluridine -Ribose -N(1)H(3)"": { + ""formula"": ""C(5)H(3)N(1)O(2)"", # 110.0236548074 + ""hcd"": True, + }, + ""5-methyluridine -Ribose -H(2)O(1)"": { + ""formula"": ""C(5)H(4)N(2)O(1)"", # 109.0396392236 + ""hcd"": True, + }, + # '5-methyluridine -Ribose -C(1)H(1)N(1)O(1)' : { + # 'formula': 'C(4)H(5)N(1)O(1)', #84.04 + # 'hcd':True + # }, + # '5-methyluridine -Ribose -C(1)H(3)N(1)O(1)' : { + # 'formula': 'C(4)H(3)N(1)O(1)', #82.028 + # 'hcd':True + # }, + # '5-methyluridine -Ribose -C(2)H(2)N(2)O(1)' : { + # 'formula': 'C(3)H(4)O(1)', #57.033 + # 'hcd':True + # }, + # '5-methyluridine -Ribose -C(2)H(1)N(1)O(2)' : { + # 'formula': 'C(3)H(5)N(1)', #56.050 + # 'hcd':True + # }, + # '5-methyluridine -Ribose -C(2)H(3)N(1)O(2)' : { + # 'formula': 'C(3)H(3)N(1)', #53.034 + # 'hcd':True + # }, + }, + ""exclusion_fragments"": { + ""5-methyluridine -Methylated ribose"": { + ""formula"": ""C(4)H(4)N(2)O(2)"" # 113.0345538436 + } + }, + }, + ""3-methyluridine"": { + # m3U + ""comments"": ""Exclusion fragments are partly m5U specific fragments"", + ""references"": [""Jora et al. 2018""], + ""precursors"": { + ""3-methyluridine"": {}, + ""3-methyluridine +N(1)H(2)"": {""formula"": ""C(10)H(16)N(3)O(6)""}, + ""3-methyluridine dimer"": {}, + }, + ""fragments"": { + ""3-methyluridine -Ribose"": {""formula"": ""C(5)H(6)N(2)O(2)""}, + ""3-methyluridine -Ribose -C(1)H(5)N(1)"": { + ""formula"": ""C(4)H(1)N(1)O(2)"", # 96 + ""hcd"": True, + }, + }, + ""exclusion_fragments"": { + ""3-methyluridine -Methylated ribose"": { + ""formula"": ""C(4)H(4)N(2)O(2)"" # 113.0345538436 + }, + ""3-methyluridine -Ribose -N(1)H(3)"": { + ""formula"": ""C(5)H(3)N(1)O(2)"", # 110.02 + ""hcd"": True, + }, + ""3-methyluridine -Ribose -H(2)O(1)"": { + ""formula"": ""C(5)H(4)N(2)O(1)"", # 109.03 + ""hcd"": True, + }, + }, + }, + ""2′-O-methyluridine"": { + ""comments"": """", + ""references"": [""Jora et al. 2018""], + ""precursors"": {""2′-O-methyluridine"": {}}, + ""fragments"": { + ""2′-O-methyluridine -Methylated ribose"": { + ""formula"": ""C(4)H(4)N(2)O(2)"" # 113.035 + }, + ""2′-O-methyluridine -Methylated ribose -H(3)N(1)"": { + ""formula"": ""C(4)H(1)N(1)O(2)"", # 96.008 + ""hcd"": True, + }, + }, + ""exclusion_fragments"": { + ""2′-O-methyluridine -Ribose"": {""formula"": ""C(5)H(6)N(2)O(2)""} # 127 + }, + }, + ""2′-O-methylpseudouridine"": { + ""comments"": ""Verification required"", + ""references"": [], + ""precursors"": {""2′-O-methylpseudouridine"": {}}, + ""fragments"": { + ""2′-O-methylpseudouridine -H(4)O(4)"": {""formula"": ""C(10)H(10)N(2)O(4)""} + }, + }, + ""pseudouridine"": { + ""references"": [""Dudley et al. 2005"", ""Pomerantz et al. 2005""], + ""comments"": ""peak 209.0556832124: ribose is doubly dehydrated; peak 191.0451185280: ribose is triply dehydrated"", + ""fragments"": { + ""pseudouridine -H(4)O(2)"": { + ""formula"": ""C(9)H(8)N(2)O(4)"", # 209.0556832124 + ""hcd"": False, + }, + ""pseudouridine -H(6)O(3)"": { + ""formula"": ""C(9)H(6)N(2)O(3)"", # 191.0451185280 + ""hcd"": False, + }, + ""pseudouridine -C(3)H(6)O(3)"": { + ""formula"": ""C(6)H(6)N(2)O(3)"", # 155.0451185280 + ""hcd"": False, + }, + ""pseudouridine -C(4)H(8)O(4)"": { + ""formula"": ""C(5)H(4)N(2)O(2)"", # 125.0345538436 + ""hcd"": True, + }, + ""pseudouridine -C(5)H(7)N(1)O(4)"": { + ""formula"": ""C(4)H(5)N(1)O(2)"", # 100.0393048718 + ""hcd"": True, + }, + ""pseudouridine -C(5)H(9)N(1)O(5)"": { + ""formula"": ""C(4)H(3)N(1)O(1)"", # 82.0287401874 + ""hcd"": True, + }, + ""pseudouridine -C(5)H(6)N(1)O(6)"": { + ""formula"": ""C(4)H(5)N(1)"", # 68.0494756318 + ""hcd"": True, + }, + }, + ""precursors"": { + ""pseudouridine K adduct"": {""formula"": ""C(9)H(11)N(2)O(6)K(1)""}, + ""pseudouridine"": {}, + ""pseudouridine +N(1)H(2)"": {""formula"": ""C(9)H(14)N(3)O(6""}, + # 'pseudouridine dimer' : {}, + # 'pseudouridine K adduct' : { + # 'formula' : 'C(9)H(11)N(2)O(6)K(1)' + # }, + # 'pseudouridine +Ammonia' : { + # 'formula' : 'C(9)H(15)N(3)O(6)' + # }, + }, + }, + ""1-methylpseudouridine"": { + # m1Y + ""references"": [""Dudley et al. 2005""], + ""comments"": ""Peaks similar to pseudouridine with addtional +C(1)H(2)"", + ""fragments"": { + ""1-methylpseudouridine -H(4)O(2)"": { + ""formula"": ""C(10)H(10)N(2)O(4)"", # 223.0713332768 + ""hcd"": False, + }, + ""1-methylpseudouridine -H(6)O(3)"": { + ""formula"": ""C(10)H(8)N(2)O(3)"", # 205.0607685924 + ""hcd"": False, + }, + ""1-methylpseudouridine -C(3)H(6)O(3)"": { + ""formula"": ""C(7)H(8)N(2)O(3)"", # 169.0607685924 + ""hcd"": False, + }, + ""1-methylpseudouridine -C(4)H(8)O(4)"": { + ""formula"": ""C(6)H(6)N(2)O(2)"", # 139.0502039080 + ""hcd"": True, + }, + ""1-methylpseudouridine -C(5)H(9)N(1)O(5)"": { + ""formula"": ""C(5)H(5)N(1)O(1)"", # 96.0443902518 + ""hcd"": True, + }, + }, + ""precursors"": { + ""1-methylpseudouridine K adduct"": {}, + ""1-methylpseudouridine"": {}, + ""1-methylpseudouridine dimer"": {}, + }, + }, + ""3-methylpseudouridine"": { + # m3Y + ""references"": [""Dudley et al. 2005""], + ""comments"": ""Verification required; Peaks similar to pseudouridine with addtional +C(1)H(2)"", + ""fragments"": { + ""3-methylpseudouridine -H(4)O(2)"": { + ""formula"": ""C(10)H(10)N(2)O(4)"", # 223.0713332768 + ""hcd"": False, + }, + ""3-methylpseudouridine -H(6)O(3)"": { + ""formula"": ""C(10)H(8)N(2)O(3)"", # 205.0607685924 + ""hcd"": False, + }, + ""3-methylpseudouridine -C(3)H(6)O(3)"": { + ""formula"": ""C(7)H(8)N(2)O(3)"", # 169.0607685924 + ""hcd"": False, + }, + ""3-methylpseudouridine -C(4)H(8)O(4)"": { + ""formula"": ""C(6)H(6)N(2)O(2)"", # 139.0502039080 + ""hcd"": True, + }, + ""3-methylpseudouridine -C(5)H(9)N(1)O(5)"": { + ""formula"": ""C(5)H(5)N(1)O(1)"", # 96.0443902518 + ""hcd"": True, + }, + }, + ""precursors"": { + ""3-methylpseudouridine K adduct"": {}, + ""3-methylpseudouridine"": {}, + ""3-methylpseudouridine dimer"": {}, + }, + }, + ""inosine"": { + # I + ""references"": [], + ""comments"": ""Precursor ion can not be seen in MS2 in most cases"", + ""fragments"": { + ""inosine -Ribose"": {""formula"": ""C(5)H(4)N(4)O(1)""} # 137.0457872316 + }, + ""precursors"": {""inosine"": {}, ""inosine dimer"": {}}, + }, + ""1-methylinosine"": { + # m1I + ""references"": [], + ""comments"": """", + ""precursors"": {""1-methylinosine"": {}, ""1-methylinosine dimer"": {}}, + ""fragments"": { + ""1-methylinosine -Ribose"": { + ""formula"": ""C(6)H(6)N(4)O(1)"" # 151.06143729597002 + } + }, + ""exclusion_fragments"": { + ""1-methylinosine -Methylated ribose"": { + ""formula"": ""C(5)H(4)N(4)O(1)"" # 137.04578723157002 + } + }, + }, + ""2′-O-methylinosine"": { + # Im + ""references"": [], + ""comments"": """", + ""precursors"": {""2′-O-methylinosine"": {}, ""2′-O-methylinosine dimer"": {}}, + ""fragments"": { + ""2′-O-methylinosine -Methylated ribose"": { + ""formula"": ""C(5)H(4)N(4)O(1)"" # 137.04578723157002 + } + }, + ""exclusion_fragments"": { + ""2′-O-methylinosine -Ribose"": { + ""formula"": ""C(6)H(6)N(4)O(1)"" # 151.06143729597002 + } + }, + }, + ""N6-isopentenyladenosine"": { + # i6A + ""references"": [""modomics.org""], + ""comments"": """", + ""precursors"": {""N6-isopentenyladenosine"": {}}, + ""fragments"": { + ""N6-isopentenyladenosine -Ribose"": { + ""formula"": ""C(10)H(13)N(5)"", # 204.1243719054 + ""hcd"": False, + }, + ""N6-isopentenyladenosine -Ribose -C(4)H(8)"": { + ""formula"": ""C(6)H(5)N(5)"", # 148.0617716478 + ""hcd"": True, + }, + ""N6-isopentenyladenosine -Ribose -C(5)H(8)"": { + ""formula"": ""C(5)H(5)N(5)"", # 136.0617716478 + ""hcd"": True, + }, + }, + }, + ""N6-formyladenosine"": { + # f6A + ""references"": [""Fu et al. 2013""], + ""comments"": ""Verification by standard required"", + ""precursors"": {""N6-formyladenosine"": {}}, + ""fragments"": { + ""N6-formyladenosine -Ribose"": { + ""formula"": ""C(6)H(5)N(5)O(1)"", # 164.05668626777 + ""hcd"": False, + }, + ""N6-formyladenosine -Ribose -C(1)O(1)"": { + ""formula"": ""C(5)H(5)N(5)"", # 136.0617716478 + ""hcd"": True, + }, + }, + }, + ""5-methoxyuridine"": { + # mo5U + ""comment"": ""Can be a co-eluting fragment (in-source?) of cm5U but with different fragments"", + ""references"": [""Nelson and McCloskey 1994""], + ""fragments"": { + ""5-methoxyuridine -Ribose"": { + ""formula"": ""C(5)H(6)N(2)O(3)"", # 143.0451185280 + ""hcd"": False, + }, + # ""5-methoxyuridine -Ribose -N(1)H(3)"": { + # ""formula"": ""C(5)H(3)N(1)O(3)"", # 126.0185694274 + # ""hcd"": True, + # }, + }, + ""precursors"": { + ""5-methoxyuridine"": {}, + ""5-methoxyuridine dimer"": {}, + ""5-methoxyuridine K adduct"": {}, + }, + }, + ""N6-threonylcarbamoyladenosine"": { + # t6A + ""comments"": ""120, 136, 162 and 281 are major peaks"", + ""references"": [""Nagao et al. 2017""], + ""fragments"": { + # 'N6-threonylcarbamoyladenosine -Ribose' : { + # 'formula' : 'C(10)H(12)N(6)O(4)' # 281.0992793572 + # }, + ""N6-threonylcarbamoyladenosine -Ribose -C(4)H(9)N(1)O(3)"": { + ""formula"": ""C(6)H(3)N(5)O(1)"" # 162.0410362034 + }, + ""N6-threonylcarbamoyladenosine -Ribose -C(5)H(7)N(1)O(4)"": { + ""formula"": ""C(5)H(5)N(5)"" # 136.0617716478 + }, + ""N6-threonylcarbamoyladenosine -Ribose -C(6)H(3)N(5)O(1)"": { + ""formula"": ""C(4)H(9)N(1)O(3)"", # 120.0655196206 + ""hcd"": False, + }, + }, + ""precursors"": { + ""N6-threonylcarbamoyladenosine"": { + ""formula"": ""C(15)H(20)N(6)O(8)"" # 413.1415380948 + } + }, + }, + ""cyclic N6-threonylcarbamoyladenosine"": { + ""references"": [""Myauchi et al. 2013""], + ""comments"": """", + ""precursors"": {""cyclic N6-threonylcarbamoyladenosine"": {}}, + ""fragments"": { + ""cyclic N6-threonylcarbamoyladenosine -Ribose"": { + ""formula"": ""C(10)H(10)N(6)O(3)"" # 263.0887146728 + }, + ""cyclic N6-threonylcarbamoyladenosine -Ribose -C(2)H(4)O(1)"": { + ""formula"": ""C(8)H(6)N(6)O(2)"" # 219.0624999240 + }, + ""cyclic N6-threonylcarbamoyladenosine -Ribose -C(4)H(7)N(1)O(2)"": { + ""formula"": ""C(6)H(3)N(5)O(1)"" # 162.0410362034 + }, + }, + }, + ""guanosine"": { + ""references"": [], + ""comments"": """", + ""precursors"": { + ""guanosine dimer"": {""formula"": ""C(20)H(26)N(10)O(10)""}, + ""guanosine"": {""formula"": ""C(10)H(13)N(5)O(5)""}, + ""guanosine K adduct"": {""formula"": ""C(10)H(12)K(1)N(5)O(5)""}, + }, + ""fragments"": { + # 'guanosine': { + # 'formula': 'C(10)H(13)N(5)O(5)' + # }, + ""guanosine -Ribose"": {""formula"": ""C(5)H(5)N(5)O(1)""}, # 152.0566862678 + ""guanosine -Ribose -H(1)N(1) +O(1)"": { + ""formula"": ""C(5)H(4)N(4)O(2)"", # 153.0407018516 + ""hcd"": True, + }, + ""guanosine -Ribose -H(3)N(1)"": { + ""formula"": ""C(5)H(2)N(4)O(1)"", # 135.0301371672 + ""hcd"": True, + }, + }, + }, + ""cytidine"": { + ""references"": [], + ""comments"": """", + ""precursors"": { + ""cytidine dimer"": {}, + ""cytidine"": {}, + }, + ""fragments"": { + # 'cytidine': { + # 'formula': 'C(9)H(13)N(3)O(5)' + # }, + ""cytidine -Ribose"": {""formula"": ""C(4)H(5)N(3)O(1)""} # 112.0505382598 + }, + }, + ""3-methylcytidine"": { + # m3C + ""comments"": ""No dimer is formed! Methyl group blocks dimer formation?"", + ""references"": [""Jora et al. 2018""], + ""precursors"": { + # + # '3-methylcytidine dimer' : { 'formula' : '' }, + # 'cytidine dimer semi-labeled' : { 'formula' : '' }, + ""3-methylcytidine"": {""formula"": """"} + }, + ""fragments"": { + ""3-methylcytidine -Ribose"": { + ""formula"": ""C(5)H(7)N(3)O(1)"" # 126.0661883242 + }, + ""3-methylcytidine -Ribose -H(3)N(1)"": { + ""formula"": ""C(5)H(4)N(2)O(1)"", # 109.0396392236 + ""hcd"": True, + }, + ""3-methylcytidine -Ribose -C(1)H(5)N(1)"": { + ""formula"": ""C(4)H(2)N(2)O(1)"", # 95.0239891592 + ""hcd"": True, + }, + }, + ""exclusion_fragments"": { + ""3-methylcytidine -Methylated ribose"": { + ""formula"": ""C(4)H(5)N(3)O(1)"", # 112.0505382598 + # 'hcd' : True + }, + # '3-methylcytidine -Ribose' : { + # 'formula': 'C(5)H(7)N(3)O(1)', + # 'hcd': True + # }, + }, + ""dimer_possible"": False, + }, + ""5-methylcytidine"": { + # m5C + ""comments"": """", + ""references"": [""Jora et al. 2018""], + ""precursors"": { + ""5-methylcytidine dimer"": {}, + ""5-methylcytidine"": {}, + }, + ""fragments"": { + ""5-methylcytidine -Ribose"": { + ""formula"": ""C(5)H(7)N(3)O(1)"" # 126.0661883242 + }, + ""5-methylcytidine -Ribose -H(3)N(1)"": { + ""formula"": ""C(5)H(4)N(2)O(1)"", # 109.0396392236 + ""hcd"": True, + }, + ""5-methylcytidine -Ribose -H(2)O(1)"": { + ""formula"": ""C(5)H(5)N(3)"", # 108.0556236398 + ""hcd"": True, + }, + # '5-methylcytidine -Ribose -C(1)H(1)N(1)O(1)' : { + # 'formula': 'C(4)H(6)N(2)', # 83.0603746680 + # 'hcd': True + # }, + }, + ""exclusion_fragments"": { + ""5-methylcytidine -Methylated ribose"": { + ""formula"": ""C(4)H(5)N(3)O(1)"", # 112.0505382598 + ""hcd"": False, + }, + ""5-methylcytidine -Ribose -C(1)H(5)N(1)"": { + ""formula"": ""C(4)H(2)N(2)O(1)"", # 95.0239891592 + ""hcd"": True, + }, + }, + }, + ""N4-methylcytidine"": { + # m4C + ""comments"": """", + ""references"": [""Jora et al. 2018""], + ""precursors"": { + ""N4-methylcytidine dimer"": {}, + ""N4-methylcytidine"": {}, + }, + ""fragments"": { + ""N4-methylcytidine -Ribose"": { + ""formula"": ""C(5)H(7)N(3)O(1)"" # 126.0661883242 + }, + ""N4-methylcytidine -Ribose -H(3)N(1)"": { + ""formula"": ""C(5)H(4)N(2)O(1)"", # 109.0396392236 + ""hcd"": True, + }, + ""N4-methylcytidine -Ribose -H(2)O(1)"": { + ""formula"": ""C(5)H(5)N(3)"", # 108.0556236398 + ""hcd"": True, + }, + ""N4-methylcytidine -Ribose -C(1)H(5)N(1)"": { + ""formula"": ""C(4)H(2)N(2)O(1)"", # 95.0239891592 + ""hcd"": True, + }, + ""N4-methylcytidine -Ribose -C(1)H(1)N(1)O(1)"": { + ""formula"": ""C(4)H(6)N(2)"", # 83.0603746680 + ""hcd"": True, + }, + }, + ""exclusion_fragments"": { + ""N4-methylcytidine -Methylated ribose"": { + ""formula"": ""C(4)H(5)N(3)O(1)"" # 112.0505382598 + } + }, + }, + ""2′-O-methylcytidine"": { + # Cm + ""comments"": """", + ""references"": [], + ""precursors"": {""2′-O-methylcytidine"": {""formula"": """"}}, + ""fragments"": { + ""2′-O-methylcytidine -Methylated ribose"": { + ""formula"": ""C(4)H(5)N(3)O(1)"" # 112.0505382598 + }, + ""2′-O-methylcytidine -Methylated ribose -H(3)N(1)"": { + ""formula"": ""C(4)H(2)N(2)O(1)"", # 95.0239891592 + ""hcd"": True, + }, + # '2′-O-methylcytidine -Methylated ribose -C(1)H(1)N(1)O(1)' : { + # 'formula': 'C(3)H(4)N(2)', # 69.044 + # 'hcd': True + # }, + }, + ""exclusion_fragments"": { + ""2′-O-methylcytidine -Ribose"": { + ""formula"": ""C(5)H(7)N(3)O(1)"" # 126.0661883242 + } + }, + }, + ""5-methoxycarbonylmethyluridine"": { + # mcm5U + ""comments"": """", + ""references"": [], + ""fragments"": { + ""5-methoxycarbonylmethyluridine -Ribose"": { + ""formula"": ""C(7)H(8)N(2)O(4)"", # 185.0556832124 + ""hcd"": False, + }, + ""5-methoxycarbonylmethyluridine -Ribose -C(1)H(4)O(1)"": { + ""formula"": ""C(6)H(4)N(2)O(3)"", # 153.0294684636 + ""hcd"": False, + }, + ""5-methoxycarbonylmethyluridine -Ribose -C(2)H(4)O(2)"": { + ""formula"": ""C(5)H(4)N(2)O(2)"" # 125.0345538436 + }, + ""5-methoxycarbonylmethyluridine -Ribose -C(3)H(3)N(1)O(2)"": { + ""formula"": ""C(4)H(5)N(1)O(2)"", # 100.0393048718 + ""hcd"": True, + }, + # '5-methoxycarbonylmethyluridine -Ribose -C(3)H(5)N(1)O(1)' : { + # 'formula': 'C(4)H(3)N(1)O(1)', # 82.0287401874 + # 'hcd':True + # }, + # '5-methoxycarbonylmethyluridine -Ribose -C(4)H(5)N(1)O(2)' : { + # 'formula': 'C(3)H(3)N(1)', # 54.0338255674 + # 'hcd':True + # }, + }, + ""precursors"": { + ""5-methoxycarbonylmethyluridine"": {}, + ""5-methoxycarbonylmethyluridine +H(3)N(1)"": { + ""formula"": ""C(12)H(19)N(3)O(8)"" + }, + ""5-methoxycarbonylmethyluridine dimer"": {}, + ""5-methoxycarbonylmethyluridine dimer +H(3)N(1)"": { + ""formula"": ""C(24)H(35)N(5)O(16)"" + }, + }, + }, + ""5-methoxycarbonylmethyl-2-thiouridine"": { + # mcm5s2U + ""comments"": """", + ""references"": [], + ""fragments"": { + ""5-methoxycarbonylmethyl-2-thiouridine -Ribose"": { + ""formula"": ""C(7)H(8)N(2)O(3)S(1)"", # 201.0328397664 + ""hcd"": False, + }, + ""5-methoxycarbonylmethyl-2-thiouridine -Ribose -C(1)H(4)O(1)"": { + ""formula"": ""C(6)H(4)N(2)O(2)S(1)"", # 169.0066250176 + ""hcd"": False, + }, + ""5-methoxycarbonylmethyl-2-thiouridine -Ribose -C(2)H(4)O(2)"": { + ""formula"": ""C(5)H(4)N(2)O(1)S(1)"", # 141.0117103976 + ""hcd"": True, + }, + ""5-methoxycarbonylmethyl-2-thiouridine -Ribose -C(3)H(3)N(1)O(1)S(1)"": { + ""formula"": ""C(4)H(5)N(1)O(2)"", # 100.0393048718 + ""hcd"": True, + }, + }, + ""precursors"": {""5-methoxycarbonylmethyl-2-thiouridine"": {}}, + }, + ""5-carbamoylmethyluridine"": { + # ncm5U + ""comments"": """", + ""references"": [], + ""precursors"": {""5-carbamoylmethyluridine"": {}}, + ""fragments"": { + ""5-carbamoylmethyluridine -Ribose"": { + ""formula"": ""C(6)H(7)N(3)O(3)"", # 170.0560175642 + ""hcd"": False, + }, + ""5-carbamoylmethyluridine -Ribose -N(1)H(3)"": { + ""formula"": ""C(6)H(4)N(2)O(3)"", # 153.0294684636 + ""hcd"": False, + }, + ""5-carbamoylmethyluridine -Ribose -C(1)H(3)N(1)O(1)"": { + ""formula"": ""C(5)H(4)N(2)O(2)"" # 125.0345538436 + }, + ""5-carbamoylmethyluridine -Ribose -C(2)H(2)N(2)O(1)"": { + ""formula"": ""C(4)H(5)N(1)O(2)"", # 100.0393048718 + ""hcd"": True, + }, + ""5-carbamoylmethyluridine -Ribose -C(2)H(4)N(2)O(2)"": { + ""formula"": ""C(4)H(3)N(1)O(1)"", # 82.0287401874 + ""hcd"": True, + }, + }, + }, + ""5-methoxycarbonylmethyl-2′-O-methyluridine"": { + # mcm5Um + ""comments"": """", + ""references"": [], + ""precursors"": { + ""5-methoxycarbonylmethyl-2′-O-methyluridine"": { + ""formula"": ""C(13)H(18)N(2)O(8)"" # 331.1135920144 + } + }, + ""fragments"": { + ""5-methoxycarbonylmethyl-2′-O-methyluridine -Methylated ribose"": { + ""formula"": ""C(7)H(8)N(2)O(4)"", # 185.0556832124 + ""hcd"": False, + }, + ""5-methoxycarbonylmethyl-2′-O-methyluridine -Methylated ribose -C(2)H(4)O(2)"": { + ""formula"": ""C(5)H(4)N(2)O(2)"" # 125.0345538436 + }, + ""5-methoxycarbonylmethyl-2′-O-methyluridine -Methylated ribose -C(3)H(3)N(1)O(2)"": { + ""formula"": ""C(4)H(5)N(1)O(2)"", # 100.0393048718 + ""hcd"": True, + }, + ""5-methoxycarbonylmethyl-2′-O-methyluridine -Methylated ribose -C(3)H(4)N(1)O(3)"": { + ""formula"": ""C(4)H(3)N(1)O(1)"", # 82.0287401874 + ""hcd"": True, + }, + }, + }, + ""5-carboxymethyluridine"": { + # cm5U + ""comments"": """", + ""references"": [], + ""precursors"": {""5-carboxymethyluridine"": {}}, + ""fragments"": { + ""5-carboxymethyluridine -Ribose"": { + ""formula"": ""C(6)H(6)N(2)O(4)"", # 171.0400331480 + ""hcd"": False, + }, + ""5-carboxymethyluridine -Ribose -H(2)O(1)"": { + ""formula"": ""C(6)H(4)N(2)O(3)"", # 153.0294684636 + ""hcd"": False, + }, # 153 + ""5-carboxymethyluridine -Ribose -C(1)H(2)O(2)"": { + ""formula"": ""C(5)H(4)N(2)O(2)"" # 125.0345538436 + }, + ""5-carbamoylmethyluridine -Ribose -C(2)H(2)N(2)O(1)"": { + ""formula"": ""C(4)H(5)N(1)O(2)"", # 100.0393048718 + ""hcd"": True, + }, + ""5-carbamoylmethyluridine -Ribose -C(2)H(4)N(2)O(2)"": { + ""formula"": ""C(4)H(3)N(1)O(1)"", # 82.0287401874 + ""hcd"": True, + }, + }, + }, + ""5-carbamoylmethyl-2-thiouridine"": { + # ncm5s2U + ""comments"": """", + ""references"": [], + ""precursors"": {""5-carbamoylmethyl-2-thiouridine"": {}}, + ""fragments"": { + ""5-carbamoylmethyl-2-thiouridine -Ribose"": { + ""formula"": ""C(6)H(7)N(3)O(2)S(1)"", # 186.0331741182 + ""hcd"": False, + }, + ""5-carbamoylmethyl-2-thiouridine -Ribose -H(3)N(1)"": { + ""formula"": ""C(6)H(4)N(2)O(2)S(1)"", # 169.0066250176 + ""hcd"": False, + }, + ""5-carbamoylmethyl-2-thiouridine -Ribose -C(1)H(3)O(1)N(1)"": { + ""formula"": ""C(5)H(4)N(2)O(1)S(1)"" # 141.0117103976 + }, + ""5-carbamoylmethyl-2-thiouridine -Ribose -C(2)H(2)N(2)O(1)S(1)"": { + ""formula"": ""C(4)H(5)N(1)O(2)"", # 100.0393048718 + ""hcd"": True, + }, + ""5-carbamoylmethyl-2-thiouridine -Ribose -C(2)H(4)N(2)O(2)S(1)"": { + ""formula"": ""C(4)H(3)N(1)O(1)"", # 82.0287401874 + ""hcd"": True, + }, + }, + }, + ""5-carboxymethyl-2-thiouridine"": { + # cm5s2U + ""comments"": """", + ""references"": [], + ""precursors"": {""5-carboxymethyl-2-thiouridine"": {}}, + ""fragments"": { + ""5-carboxymethyl-2-thiouridine -Ribose"": { + ""formula"": ""C(6)H(6)N(2)O(3)S(1)"", # 187.01718970197 + ""hcd"": False, + }, + ""5-carboxymethyl-2-thiouridine -Ribose -C(1)H(2)O(2)"": { + ""formula"": ""C(5)H(4)N(2)O(1)S(1)"" # 141.0117103976 + }, # 141 + ""5-carboxymethyl-2-thiouridine -Ribose -C(2)H(1)N(2)O(1)S(1)"": { + ""formula"": ""C(4)H(5)N(1)O(2)"", # 100.0393048718 + ""hcd"": True, + }, + ""5-carboxymethyl-2-thiouridine -Ribose -C(2)H(3)N(1)O(2)S(1)"": { + ""formula"": ""C(4)H(3)N(1)O(1)"", # 82.0287401874 + ""hcd"": True, + }, + }, + }, + ""5-carbamoylhydroxymethyluridine"": { + # nchm5U + ""comments"": """", + ""references"": [], + ""precursors"": {""5-carbamoylhydroxymethyluridine"": {}}, + ""fragments"": { + ""5-carbamoylhydroxymethyluridine -Ribose"": { + ""formula"": ""C(6)H(7)N(3)O(4)"", # 186.0509321842 + ""hcd"": False, + }, + ""5-carbamoylhydroxymethyluridine -Ribose -C(1)H(3)N(1)O(1)"": { + ""formula"": ""C(5)H(4)N(2)O(3)"", # 141.0294684636 + ""hcd"": True, + }, + ""5-carbamoylhydroxymethyluridine -Ribose -C(1)H(2)O(2)"": { + ""formula"": ""C(5)H(5)N(3)O(2)"", # 140.0454528798 + ""hcd"": True, + }, + ""5-carbamoylhydroxymethyluridine -Ribose -C(1)H(2)O(2)"": { + ""formula"": ""C(4)H(4)N(2)O(1)"", # 97.039639 + ""hcd"": True, + }, + ""5-carbamoylhydroxymethyluridine -Ribose -C(1)H(2)O(2)"": { + ""formula"": ""C(3)H(3)N(1)O(1)"", # 70.0287401874 + ""hcd"": True, + }, + }, + }, + ""5-methyl-2-thiouridine"": { + # m5s2U + ""comments"": """", + ""references"": [], + ""precursors"": {""5-methyl-2-thiouridine"": {""formula"": ""C(10)H(14)N(2)O(5)S(1)""}}, + ""fragments"": { + ""5-methyl-2-thiouridine -Ribose"": { + ""formula"": ""C(5)H(6)N(2)O(1)S(1)"" # 143.0273604620 + }, + ""5-methyl-2-thiouridine -Ribose -N(1)H(3)"": { + ""formula"": ""C(5)H(3)N(1)O(1)S(1)"", # 126.0008113614 + ""hcd"": True, + }, + }, + }, + ""5-aminomethyl-2-thiouridine"": { + # nm5s2U + ""comments"": """", + ""references"": [], + ""precursors"": { + ""5-aminomethyl-2-thiouridine"": {""formula"": ""C(10)H(15)N(3)O(5)S(1)""} + }, + ""fragments"": { + ""5-aminomethyl-2-thiouridine -Ribose"": { + ""formula"": ""C(5)H(7)N(3)O(1)S(1)"" # 158.038663833319 + }, + # ""5-aminomethyl-2-thiouridine -Ribose -H(1)S(1)"": { + # ""formula"": ""C(5)H(6)N(3)O(1)"",# 125.05836329197 + # ""hcd"" : True + # not verified!!! + # }, + }, + }, + ""5-hydroxyuridine"": { + # ho5U + ""comments"": """", + ""references"": [""Nelson and McCloskey 1994""], + ""precursors"": {""5-hydroxyuridine"": {}}, + ""fragments"": { + ""5-hydroxyuridine -Ribose"": { + ""formula"": ""C(4)H(4)N(2)O(3)"" # 129.0294684636 + }, + # ""5-hydroxyuridine -Ribose -N(1)H(3)"": { + # ""formula"": ""C(4)H(1)N(1)O(3)"", # 112.0029193630 + # ""hcd"":True + # }, + # ""5-hydroxyuridine -Ribose -C(1)H(3)N(1)O(1)"": { + # ""formula"": ""C(3)H(1)N(1)O(2)"", # 84.0080047430 + # ""hcd"":True + # }, + }, + }, + # ""5,2′-O-dimethyluridine"": { + # # m5Um + # ""comments"" : ""Fragments similar to m5U (less similar to m3U, Verification required"", + # ""references"" : [""Jora et al. 2018""], + # ""precursors"": { + # ""5,2′-O-dimethyluridine"": { + # ""formula"": ""C(11)H(16)N(2)O(6)"" # 273.1081127100 + # } + # }, + # ""fragments"": { + # ""5,2′-O-dimethyluridine -Ribose"": { + # ""formula"": ""C(6)H(8)N(2)O(2)"" # 141.06585397237 + # }, + # ""5,2′-O-dimethyluridine -Methylated ribose -N(1)H(3)"": { + # ""formula"": ""C(5)H(3)N(1)O(2)"", # 110.0236548074 + # ""hcd"": True, + # }, + # ""5,2′-O-dimethyluridine -Methylated ribose -H(2)O(1)"": { + # ""formula"": ""C(5)H(4)N(2)O(1)"", # 109.0396392236 + # ""hcd"": True, + # }, + # # '5,2′-O-dimethyluridine -Ribose -C(1)H(1)N(1)O(1)' : { + # # 'formula': 'C(4)H(5)N(1)O(1)', #84.0443902518 + # # 'hcd':True + # # }, + # }, + # }, + # ""3,2′-O-dimethyluridine"": { + # # m3Um + # ""comments"" : ""Similarity to m3U assumed, Verfication required"", + # ""references"" : [""Jora et al. 2018""], + # ""precursors"": { + # ""3,2′-O-dimethyluridine"": { + # ""formula"": ""C(11)H(16)N(2)O(6)"" # 273.1081127100 + # } + # }, + # ""fragments"": { + # ""3,2′-O-dimethyluridine -Ribose"": { + # ""formula"": ""C(6)H(8)N(2)O(2)"", # 141.06585397237 + # ""hcd"": True, + # }, + # ""3,2′-O-dimethyluridine -Ribose -C(1)H(5)N(1)"": { + # ""formula"": ""C(4)H(1)N(1)O(2)"", # 96.0080047430 + # ""hcd"": True, + # }, + # }, + # }, + ""5-hydroxymethylcytidine"": { + ""comments"": ""Elutes with m3C. Verification required. You et al. report peak 124.1"", + ""references"": [""You et al. 2019""], + ""precursors"": {""5-hydroxymethylcytidine"": {""formula"": """"}}, + ""fragments"": { + ""5-hydroxymethylcytidine -Ribose"": { + ""formula"": ""C(5)H(7)N(3)O(2)"", # 142.0611029442 + ""hcd"": False, + }, + ""5-hydroxymethylcytidine -Ribose -O(1)"": { + ""formula"": ""C(5)H(7)N(3)O(1)"", # 126.0661883242 + ""hcd"": True, + }, + ""5-hydroxymethylcytidine -Ribose -H(3)N(1)O(1)"": { + ""formula"": ""C(5)H(4)N(2)O(1)"", # 109.0396392236 + ""hcd"": True, + }, + ""5-hydroxymethylcytidine -Ribose -C(1)H(5)N(1)O(1)"": { + ""formula"": ""C(4)H(2)N(2)O(1)"", # 95.0239891592 + ""hcd"": True, + }, + }, + }, + ""N4,2′-O-dimethylcytidine"": { + # m4Cm + ""comments"": """", + ""references"": [""Jora et al. 2018""], + ""precursors"": {""N4,2′-O-dimethylcytidine"": {}}, + ""fragments"": { + ""N4,2′-O-dimethylcytidine -Methylated ribose"": { + ""formula"": ""C(5)H(7)N(3)O(1)"" # 126.0661883242 + }, + ""N4,2′-O-dimethylcytidine -Methylated ribose -H(3)N(1)"": { + ""formula"": ""C(5)H(4)N(2)O(1)"", # 109.0396392236 + ""hcd"": True, + }, + ""N4,2′-O-dimethylcytidine -Methylated ribose -H(2)O(1)"": { + ""formula"": ""C(5)H(5)N(3)"", # 108.0556236398 + ""hcd"": True, + }, + ""N4,2′-O-dimethylcytidine -Methylated ribose -C(1)H(5)N(1)"": { + ""formula"": ""C(4)H(2)N(2)O(1)"", # 95.0239891592 + ""hcd"": True, + }, + ""N4,2′-O-dimethylcytidine -Methylated ribose -C(1)H(1)N(1)O(1)"": { + ""formula"": ""C(4)H(6)N(2)"", # 83.0603746680 + ""hcd"": True, + }, + }, + }, + ""5,2′-O-dimethylcytidine"": { + # m5Cm + ""comments"": """", + ""references"": [""Jora et al. 2018""], + ""precursors"": {""5,2′-O-dimethylcytidine"": {}}, + ""fragments"": { + ""5,2′-O-dimethylcytidine -Methylated ribose"": { + ""formula"": ""C(5)H(7)N(3)O(1)"" # 126.0661883242 + }, + ""5,2′-O-dimethylcytidine -Methylated ribose -H(3)N(1)"": { + ""formula"": ""C(5)H(4)N(2)O(1)"", # 109.0396392236 + ""hcd"": True, + }, + ""5,2′-O-dimethylcytidine -Methylated ribose -H(2)O(1)"": { + ""formula"": ""C(5)H(5)N(3)"", # 108.0556236398 + ""hcd"": True, + }, + }, + ""exclusion_fragments"": { + ""5,2′-O-dimethylcytidine -Methylated ribose -C(1)H(5)N(1)"": { # + ""formula"": ""C(4)H(2)N(2)O(1)"", # 95.0239891592 + ""hcd"": True, + } + }, + }, + ""N4,N4-dimethylcytidine"": { + # m4Cm + ""comments"": ""Verification required"", + ""references"": [], + ""precursors"": {""N4,N4-dimethylcytidine"": {}}, + ""fragments"": { + ""N4,N4-dimethylcytidine -Ribose"": { + ""formula"": ""C(6)H(9)N(3)O(1)"" # 140.0818383886 + } + }, + }, + ""1-methylguanosine"": { + # m1G + ""comments"": """", + ""references"": [""Jora et al. 2018""], + ""precursors"": {""1-methylguanosine"": {}, ""1-methylguanosine -Ribose"": {}}, + ""fragments"": { + ""1-methylguanosine -Ribose"": { + ""formula"": ""C(6)H(7)N(5)O(1)"" # 166.0723363322 + }, + ""1-methylguanosine -Ribose -H(1)N(1) +O(1)"": { + ""formula"": ""C(6)H(6)N(4)O(2)"", # 167.0563519160 + ""hcd"": True, + }, + ""1-methylguanosine -Ribose -C(1)H(3)N(1) +O(1)"": { + ""formula"": ""C(5)H(4)N(4)O(2)"", # 153.0407018516 + ""hcd"": True, + }, + ""1-methylguanosine -Ribose -H(3)N(1)"": { + ""formula"": ""C(6)H(4)N(4)O(1)"", # 149.0457872316 + ""hcd"": True, + }, + }, + ""exclusion_fragments"": { + ""7-O-methylguanosine -Methylated ribose"": { + ""formula"": ""C(5)H(5)N(5)O(1)"" # 152.0566862678 + } + }, + }, + ""N2-methylguanosine"": { + # m2G + ""comments"": """", + ""references"": [""Jora et al. 2018""], + ""precursors"": {""N2-methylguanosine"": {}, ""N2-methylguanosine -Ribose"": {}}, + ""fragments"": { + ""N2-methylguanosine -Ribose"": { + ""formula"": ""C(6)H(7)N(5)O(1)"", # 166.0723363322 + ""hcd"": False, + }, + ""N2-methylguanosine -Ribose -H(1)N(1) +O(1)"": { + ""formula"": ""C(6)H(6)N(4)O(2)"", # 167.0563519160 + ""hcd"": True, + }, + ""N2-methylguanosine -Ribose -H(3)N(1)"": { + ""formula"": ""C(6)H(4)N(4)O(1)"", # 149.0457872316 + ""hcd"": True, + }, + ""N2-methylguanosine -Ribose -C(2)H(2)N(2) +O(1)"": { + ""formula"": ""C(4)H(5)N(3)O(2)"", # 128.0454528798 + ""hcd"": True, + }, + ""N2-methylguanosine -Ribose -C(2)H(4)N(2)"": { + ""formula"": ""C(4)H(3)N(3)O(1)"", # 110.0348881954 + ""hcd"": True, + }, + }, + ""exclusion_fragments"": { + ""N2-methylguanosine -Methylated ribose"": { + ""formula"": ""C(5)H(5)N(5)O(1)"" # 152.0566862678 + }, + ""N2-methylguanosine -Ribose"": { + ""formula"": ""C(6)H(7)N(5)O(1)"", # 166.0723363322 + ""hcd"": True, + }, + }, + }, + ""7-methylguanosine"": { + # m7G + ""comments"": """", + ""references"": [""Jora et al. 2018""], + ""precursors"": {""7-methylguanosine"": {}, ""7-methylguanosine -Ribose"": {}}, + ""fragments"": { + ""7-methylguanosine -Ribose"": { + ""formula"": ""C(6)H(7)N(5)O(1)"" # 166.0723363322 + }, + ""7-methylguanosine -Ribose -H(1)N(1) +O(1)"": { + ""formula"": ""C(6)H(6)N(4)O(2)"", # 167.0563519160 + ""hcd"": True, + }, + ""7-methylguanosine -Ribose -H(3)N(1)"": { + ""formula"": ""C(6)H(4)N(4)O(1)"", # 149.0457872316 + ""hcd"": True, + }, + # '7-methylguanosine -Ribose -C(1)N(2) +O(1)': { #too low abudant for 5% TIC threshold + # 'formula': 'C(5)H(7)N(3)O(2)', # 142 + # 'hcd': True, + # }, + ""7-methylguanosine -Ribose -C(1)H(2)N(2)"": { + ""formula"": ""C(5)H(5)N(3)O(1)"", # 124.0505382598 + ""hcd"": True, + }, + }, + ""exclusion_fragments"": { + ""7-O-methylguanosine -Methylated ribose"": {""formula"": ""C(5)H(5)N(5)O(1)""} + }, + }, + ""2′-O-methylguanosine"": { + # Cm + ""comments"": """", + ""references"": [""Jora et al. 2018""], + ""precursors"": { + ""2′-O-methylguanosine"": {}, + ""2′-O-methylguanosine -Methylated ribose"": {}, + ""2′-O-methylguanosine K adduct"": {}, + ""2′-O-methylguanosine dimer"": {}, + ""2′-O-methylguanosine K adduct dimer"": {}, + }, + ""fragments"": { + ""2′-O-methylguanosine -Methylated ribose"": { + ""formula"": ""C(5)H(5)N(5)O(1)"" # 152.0566862678 + }, + ""2′-O-methylguanosine -Methylated ribose -H(1)N(1) +O(1)"": { + ""formula"": ""C(5)H(4)N(4)O(2)"", # 153.0407018516 + ""hcd"": True, + }, + ""2′-O-methylguanosine -Methylated ribose -H(3)N(1)"": { + ""formula"": ""C(5)H(2)N(4)O(1)"", # 135.0301371672 + ""hcd"": True, + }, + ""2′-O-methylguanosine -Methylated ribose -C(1)H(2)N(2)"": { + ""formula"": ""C(4)H(3)N(3)O(1)"", # 110.0348881954 + ""hcd"": True, + }, + # '7-methylguanosine -Ribose -C(1)N(2) +O(1)': { #too low abudant for 5% TIC threshold + # 'formula': 'C(5)H(7)N(3)O(2)', # 142 + # 'hcd': True, + # }, + }, + ""exclusion_fragments"": { + ""2′-O-methylguanosine -Ribose"": { + ""formula"": ""C(6)H(7)N(5)O(1)"", # 166.0723363322 + } + }, + }, + ""N2,N2-dimethylguanosine"": { + # m2,2G + ""comments"": """", + ""references"": [""Giessing et al. 2011""], + ""precursors"": { + ""N2,N2-dimethylguanosine"": {}, + ""N2,N2-dimethylguanosine dimer"": {}, + }, + ""fragments"": { + ""N2,N2-dimethylguanosine -Ribose"": { + ""formula"": ""C(7)H(9)N(5)O(1)"" # 180.08798639657002 + }, + ""N2,N2-dimethylguanosine -Ribose -C(2)H(5)N(1) +O(1)"": { + ""formula"": ""C(5)H(4)N(4)O(2)"", # 153.0407018516 + ""hcd"": True, + }, + ""N2,N2-dimethylguanosine -Ribose -C(2)H(7)N(1)"": { + ""formula"": ""C(5)H(2)N(4)O(1)"", # 135.0301371672 + ""hcd"": True, + }, + ""N2,N2-dimethylguanosine -Ribose -C(3)H(6)N(2)"": { + ""formula"": ""C(4)H(3)N(3)O(1)"", # 110.0348881954 + ""hcd"": True, + }, + }, + }, + # ""7-aminomethyl-7-deazaguanosine"": { + # # is not validated! + # ""precursors"": {""7-aminomethyl-7-deazaguanosine"": {}}, + # ""fragments"": { + # ""7-aminomethyl-7-deazaguanosine -Ribose"": { + # ""formula"": ""C(7)H(9)N(5)O(1)"" # 180.0879863966 + # }, + # ""7-aminomethyl-7-deazaguanosine -Ribose -H(3)N(1)"": { + # ""formula"": ""C(7)H(6)N(4)O(1)"", # 163.0614372960 + # ""hcd"": True, + # }, + # }, + # }, + ""adenosine"": { + # A + ""comments"": """", + ""references"": [], + ""precursors"": {""adenosine"": {}}, + ""fragments"": { + ""adenosine -Ribose"": {""formula"": ""C(5)H(5)N(5)""}, # 136.0617716478 + ""adenosine -Ribose -H(3)N(1)"": { + ""formula"": ""C(5)H(2)N(4)"", # 119.03522254717 + ""hcd"": True, + }, + }, + }, + ""2′-O-methyladenosine"": { + # Am + ""comments"": """", + ""references"": [""Jora et al. 2018""], + ""precursors"": { + ""2′-O-methyladenosine"": {""formula"": ""C(11)H(15)N(5)O(4)""}, # 282.1196804498 + ""2′-O-methyladenosine dimer"": {}, + }, + ""fragments"": { + ""2′-O-methyladenosine -Methylated ribose"": { + ""formula"": ""C(5)H(5)N(5)"" # 136.0617716478 + }, + # '2′-O-methyladenosine': {'formula': 'C(11)H(15)N(5)O(4)'} + }, + ""exclusion_fragments"": { + ""2′-O-methyladenosine -Ribose"": { + ""formula"": ""C(6)H(7)N(5)"" # 150.0774217122 + } + }, + }, + ""1-methyladenosine"": { + # m1A + ""comments"": """", + ""references"": [""Jora et al. 2018""], + ""precursors"": { + ""1-methyladenosine"": {""formula"": ""C(11)H(15)N(5)O(4)""}, + ""1-methyladenosine dimer"": {}, + ""1-methyladenosine K adduct dimer"": {}, + }, + ""fragments"": { + ""1-methyladenosine -Ribose"": {""formula"": ""C(6)H(7)N(5)""}, # 150.0774217122 + ""1-methyladenosine -Ribose -N(1)H(3)"": { + ""formula"": ""C(6)H(4)N(4)"", # 133.0508726116 + ""hcd"": True, + }, + ""1-methyladenosine -Ribose -C(2)N(1)H(3)"": { + ""formula"": ""C(4)H(4)N(4)"", # 109.0508726116 + ""hcd"": True, + }, + }, + ""exclusion_fragments"": { + ""1-methyladenosine -Methylated ribose"": { + ""formula"": ""C(5)H(5)N(5)"" # 136.0617716478 + } + }, + }, + ""1,2′-O-dimethyladenosine"": { + # m1Am + ""comments"": """", + ""references"": [], + ""precursors"": {""1,2′-O-dimethyladenosine"": {""formula"": ""C(12)H(17)N(5)O(4)""}}, + ""fragments"": { + ""1,2′-O-dimethyladenosine -Methylated ribose"": { + ""formula"": ""C(6)H(7)N(5)"" # 150.0774217122 + }, + ""1,2′-O-dimethyladenosine -Methylated ribose -N(1)H(3)"": { + ""formula"": ""C(6)H(4)N(4)"", # 133.0508726116 + ""hcd"": True, + }, + ""1,2′-O-dimethyladenosine -Methylated ribose -C(2)N(1)H(3)"": { + ""formula"": ""C(4)H(4)N(4)"", # 109.0508726116 + ""hcd"": True, + }, + }, + }, + ""N6,N6-dimethyladenosine"": { + # m6,6A + ""comments"": """", + ""references"": [""Chan et al. 2011""], + ""precursors"": { + ""N6,N6-dimethyladenosine"": { + ""formula"": ""C(12)H(17)N(5)O(4)"" # 296.1353305142 + } + }, + ""fragments"": { + ""N6,N6-dimethyladenosine -Ribose"": { + ""formula"": ""C(7)H(9)N(5)"" # 164.0930717766 + }, + ""N6,N6-dimethyladenosine -Ribose -C(1)H(3)"": { + ""formula"": ""C(6)H(6)N(5)"", # 149.06959667997 + ""hcd"": True, + }, + ""N6,N6-dimethyladenosine -Ribose -C(2)H(5)N(1)"": { + ""formula"": ""C(5)H(4)N(4)"", # 121.05087261157 + ""hcd"": True, + }, + }, + }, + ""N6,2′-O-dimethyladenosine"": { + # m6Am + ""comments"": """", + ""references"": [], + ""precursors"": { + ""N6,2′-O-dimethyladenosine"": { + ""formula"": ""C(12)H(17)N(5)O(4)"" # 296.1353305142 + } + }, + ""fragments"": { + ""N6,2′-O-dimethyladenosine -Methylated ribose"": { + ""formula"": ""C(6)H(7)N(5)"" # 150.0774217122 + }, + ""N6,2′-O-dimethyladenosine -Methylated ribose -C(1)H(1)N(1)"": { + ""formula"": ""C(5)H(6)N(4)"", # 123.0665226760 + ""hcd"": True, + }, + ""N6,2′-O-dimethyladenosine -Methylated ribose -C(2)H(4)N(2)"": { + ""formula"": ""C(4)H(3)N(3)"", # 94.0399735754 + ""hcd"": True, + }, + }, + }, + ""2,8-dimethyladenosine"": { + # m2,8A + ""comments"": ""Verification required"", + ""references"": [""Giessing et al. 2009""], + ""precursors"": {""2,8-dimethyladenosine"": {}}, + ""fragments"": { + ""2,8-dimethyladenosine -Ribose"": { + ""formula"": ""C(7)H(9)N(5)"" # 164.0930717766 + }, + ""2,8-dimethyladenosine -Ribose -H(3)N(1)"": { + ""formula"": ""C(7)H(6)N(4)"", # 147.0665226760 + ""hcd"": True, + }, + }, + }, + ""2-methyladenosine"": { + # m2A + ""comments"": """", + ""references"": [""Jora et al. 2018""], + ""precursors"": { + ""2-methyladenosine"": {}, + ""2-methyladenosine dimer"": {}, + ""2-methyladenosine K adduct dimer"": {}, + }, + ""fragments"": { + ""2-methyladenosine -Ribose"": {""formula"": ""C(6)H(7)N(5)""}, # 150.0774217122 + ""2-methyladenosine -Ribose -N(1)H(3)"": { + ""formula"": ""C(6)H(4)N(4)"", # 133.0508726116 + ""hcd"": True, + }, + ""2-methyladenosine -Ribose -C(2)N(2)H(6)"": { + ""formula"": ""C(4)H(1)N(3)"", # 92.0243235110 + ""hcd"": True, + }, + }, + ""exclusion_fragments"": { + ""2-methyladenosine -Methylated ribose"": { + ""formula"": ""C(5)H(5)N(5)"" # 136.0617716478 + } + }, + }, + ""8-methyladenosine"": { + # m8A + ""comments"": """", + ""references"": [""Jora et al. 2018""], + ""precursors"": { + ""8-methyladenosine"": {}, + ""8-methyladenosine dimer"": {}, + ""8-methyladenosine K adduct dimer"": {}, + }, + ""fragments"": { + ""8-methyladenosine -Ribose"": {""formula"": ""C(6)H(7)N(5)""}, # 150.0774217122 + ""8-methyladenosine -Ribose -N(1)H(3)"": { + ""formula"": ""C(6)H(4)N(4)"", # 133.0508726116 + ""hcd"": True, + }, + ""8-methyladenosine -Ribose -C(1)N(2)H(2)"": { + ""formula"": ""C(5)H(5)N(3)"", # 108.0556236398 + ""hcd"": True, + }, + ""8-methyladenosine -Ribose -C(1)N(2)H(4)"": { + ""formula"": ""C(5)H(3)N(3)"", # 106.0399735754 + ""hcd"": True, + }, + }, + ""exclusion_fragments"": { + ""8-methyladenosine -Methylated ribose"": { + ""formula"": ""C(5)H(5)N(5)"" # 136.0617716478 + } + }, + }, + ""N6-methyladenosine"": { + # m6A + ""comments"": """", + ""references"": [""Jora et al. 2018""], + ""precursors"": { + ""N6-methyladenosine"": {}, + ""N6-methyladenosine dimer"": {}, + ""N6-methyladenosine K adduct dimer"": {}, + }, + ""fragments"": { + ""N6-methyladenosine -Ribose"": {""formula"": ""C(6)H(7)N(5)""}, # 150.0774217122 + ""N6-methyladenosine -Ribose -C(1)H(1)N(1)"": { + ""formula"": ""C(5)H(6)N(4)"", # 123.0665226760 + ""hcd"": True, + }, + ""N6-methyladenosine -Ribose -C(2)H(4)N(2)"": { + ""formula"": ""C(4)H(3)N(3)"", # 94.0399735754 + ""hcd"": True, + }, + }, + ""exclusion_fragments"": { + ""N6-methyladenosine -Methylated ribose"": { + ""formula"": ""C(5)H(5)N(5)"" # 136.0617716478 + } + }, + }, + # 'N6-acetyladenosine': { + # ""references"":['Sauerwald et al. 2005'], + # 'precursors':{ + # 'N6-acetyladenosine': {'formula': 'C(12)H(15)N(5)O(5)'} + # }, + # 'fragments' : { + # 'N6-acetyladenosine -Ribose': { + # 'formula': 'C(7)H(7)N(5)O(1)', + # 'hcd' : False + # }, + # 'N6-acetyladenosine -Ribose -C(1)O(1)': { + # 'formula': 'C(6)H(7)N(5)', + # 'hcd' : True + # }, + # 'N6-acetyladenosine -Ribose -C(2)H(1)N(1)O(1)': { + # 'formula': 'C(5)H(6)N(4)', #123.06 + # 'hcd' : True + # }, + # 'N6-acetyladenosine -Ribose -C(3)H(4)N(2)O(1)': { + # 'formula': 'C(4)H(3)N(3)', #94.04 + # 'hcd' : True + # }, + # }, + # }, + ""N6-hydroxymethyladenosine"": { + # hm6A + ""comments"": ""Verification required"", + ""references"": [""modomics.org"", ""You et al. 2019"", ""Fu et al. 2013""], + ""fragments"": { + ""N6-hydroxymethyladenosine"": { + ""formula"": ""C(11)H(15)N(5)O(5)"" # 298.1145950698 + }, + ""adenosine"": {""formula"": ""C(10)H(13)N(5)O(4)""}, # 268.1040303854 + ""adenosine -Ribose"": {""formula"": ""C(5)H(5)N(5)""}, # 136.0617716478 + }, + ""precursors"": {""N6-hydroxymethyladenosine"": {}}, + }, + ""N4-acetylcytidine"": { + # ac4C + ""comments"": ""Verification required"", + ""references"": [""modomics.org""], + ""fragments"": { + ""N4-acetylcytidine -Ribose"": { + ""formula"": ""C(6)H(7)N(3)O(2)"", # 154.0611029442 + ""hcd"": False, + }, + ""cytidine -Ribose"": {""formula"": ""C(4)H(5)N(3)O(1)""}, # 112.0505382598 + ""cytidine -Ribose -C(1)H(5)N(1)"": { + ""formula"": ""C(4)H(2)N(2)O(1)"", # 95.0239891592 + ""hcd"": True, + }, + }, + ""precursors"": {""N4-acetylcytidine"": {}, ""N4-acetylcytidine K adduct"": {}}, + }, + ""5-formyl-2′-O-methylcytidine"": { + # f5Cm + ""comments"": ""Verification required"", + ""references"": [""modomics.org""], + ""fragments"": { + ""5-formyl-2′-O-methylcytidine -Methylated ribose"": { + ""formula"": ""C(5)H(5)N(3)O(2)"" # 140.0454528798 + } + }, + ""precursors"": {""5-formyl-2′-O-methylcytidine"": {}}, + }, + ""4-thiouridine"": { + # s4U + ""comments"": """", + ""references"": [""Jora et al. 2018""], + ""precursors"": {""4-thiouridine"": {}}, + ""fragments"": { + ""4-thiouridine -Ribose"": { + ""formula"": ""C(4)H(4)N(2)O(1)S(1)"" # 129.0117103976 + }, + ""4-thiouridine -Ribose -H(3)N(1)"": { + ""formula"": ""C(4)H(1)N(1)O(1)S(1)"", # 111.9851612970 + ""hcd"": True, + }, + ""4-thiouridine -Ribose -C(1)H(1)N(1)O(1)"": { + ""formula"": ""C(3)H(3)N(1)S(1)"", # 86.0058967414 + ""hcd"": True, + }, + }, + }, + ""2-thiouridine"": { + # s2U + ""comments"": """", + ""references"": [""Jora et al. 2018""], + ""precursors"": { + ""2-thiouridine"": {}, + ""2-thiouridine isotope_1"": { + ""formula"": ""+C(9)H(12)N(2)O(5)S(1)"", + ""isotope_position"": 1, + }, # refers to pos 1 in most abundant precursors + # default would be 0, following the ursgal nomenclature, see below + }, + ""fragments"": { + ""2-thiouridine -Ribose"": { + ""formula"": ""C(4)H(4)N(2)O(1)S(1)"" # 129.0117103976 + }, + ""2-thiouridine -Ribose -H(3)N(1)"": { + ""formula"": ""C(4)H(1)N(1)O(1)S(1)"", # 111.9851612970 + ""hcd"": True, + }, + ""2-thiouridine -Ribose -C(1)H(1)N(1)S(1)"": { + ""formula"": ""C(3)H(3)N(1)O(1)"", # 70.0287401874 + ""hcd"": True, + }, + }, + }, + ""spiroiminodihydantoin"": { + ""comments"": """", + ""references"": [""Martinez et al. 2007""], + ""precursors"": { + ""spiroiminodihydantoin"": {""formula"": ""C(10)H(13)N(5)O(7)""} # 316.0887742454 + }, + ""fragments"": { + ""spiroiminodihydantoin -Ribose"": { + ""formula"": ""C(5)H(5)N(5)O(3)"", # 184.0465155078 + ""hcd"": False, + }, + ""spiroiminodihydantoin -Ribose -C(2)H(2)N(2)O(1)"": { + ""formula"": ""C(3)H(3)N(3)O(2)"", # 114.0298028154 + ""hcd"": True, + }, + ""spiroiminodihydantoin -Ribose -C(2)H(1)N(1)O(2)"": { + ""formula"": ""C(3)H(4)N(4)O(1)"", # 113.0457872316 + ""hcd"": True, + }, + ""spiroiminodihydantoin -Ribose -C(3)H(2)N(2)O(2)"": { + ""formula"": ""C(2)H(3)N(3)O(1)"", # 86.0348881954 + ""hcd"": True, + }, + }, + }, + ""queuosine"": { + # Q + ""comments"": """", + ""references"": [""Zallot et al. 2014"", ""Giessing et al. 2009""], + ""precursors"": {""queuosine"": {""formula"": ""C(17)H(23)N(5)O(7)""}}, + ""fragments"": { + ""queuosine -C(5)H(9)N(1)O(2)"": { + ""formula"": ""C(12)H(14)N(4)O(5)"", # 295.10369603357 + ""hcd"": False, + }, + ""queuosine -C(10)H(17)N(1)O(6)"": { + ""formula"": ""C(7)H(6)N(4)O(1)"", # 163.0614372959700 + # 'hcd' : False + }, + ""queuosine -C(10)H(20)N(2)O(6)"": { + ""formula"": ""C(7)H(3)N(3)O(1)"", # 146.0348881954 + ""hcd"": True, + }, + ""queuosine -C(11)H(19)N(3)O(6)"": { + ""formula"": ""C(6)H(4)N(2)O(1)"", # 121.0396392236 + ""hcd"": True, + }, + }, + }, +} +","Python" +"Computational Biochemistry","LeidelLab/SMITER","smiter/ext/get_modomics_csv.sh",".sh","306","6","(wget ""http://www.genesilico.pl/modomics/api/modifications?id=1&format=csv"" -q -O modomics.csv ) && + sed -i -e ""s:
:\n:g"" -e ""s:
:\n:g"" -e ""s:
::g"" -e ""s:
::g"" modomics.csv && + cat modomics.csv | python trim_lines.py >> modomics2.csv && + rm modomics.csv && + mv modomics2.csv modomics.csv +","Shell" +"Computational Biochemistry","LeidelLab/SMITER","docs/conf.py",".py","4774","163","#!/usr/bin/env python +# +# smiter documentation build configuration file, created by +# sphinx-quickstart on Fri Jun 9 13:47:02 2017. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another +# directory, add these directories to sys.path here. If the directory is +# relative to the documentation root, use os.path.abspath to make it +# absolute, like shown here. +# +import os +import sys +sys.path.insert(0, os.path.abspath('..')) + +import smiter + +# -- General configuration --------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'SMITER' +copyright = ""2020, Manuel Kösters"" +author = ""Manuel Kösters"" + +# The version info for the project you're documenting, acts as replacement +# for |version| and |release|, also used in various other places throughout +# the built documents. +# +# The short X.Y version. +version = smiter.__version__ +# The full version, including alpha/beta/rc tags. +release = smiter.__version__ + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set ""language"" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'alabaster' + +# Theme options are theme-specific and customize the look and feel of a +# theme further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named ""default.css"" will overwrite the builtin ""default.css"". +html_static_path = ['_static'] + + +# -- Options for HTMLHelp output --------------------------------------- + +# Output file base name for HTML help builder. +htmlhelp_basename = 'smiterdoc' + + +# -- Options for LaTeX output ------------------------------------------ + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass +# [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'smiter.tex', + 'SMITER Documentation', + 'Manuel Kösters', 'manual'), +] + + +# -- Options for manual page output ------------------------------------ + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'smiter', + 'SMITER Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ---------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'smiter', + 'SMITER Documentation', + author, + 'smiter', + 'One line description of project.', + 'Miscellaneous'), +] + + + +","Python" +"Computational Biochemistry","LeidelLab/SMITER","tests/test_synthetic_mzml.py",".py","19768","622","from tempfile import NamedTemporaryFile + +import numpy as np +import pymzml +import pytest +from scipy.signal import find_peaks +from scipy.stats import kstest, normaltest + +import smiter +from smiter.fragmentation_functions import ( + AbstractFragmentor, + NucleosideFragmentor, + PeptideFragmentor, +) +from smiter.noise_functions import GaussNoiseInjector, UniformNoiseInjector +from smiter.synthetic_mzml import ( + generate_interval_tree, + generate_molecule_isotopologue_lib, + generate_scans, + write_mzml, +) + + +class TestFragmentor(AbstractFragmentor): + def __init__(self): + print(""Fragmentor goes chop chop chop chop chop ..."") + + def fragment(self, mol): + return np.array([(200, 1e5)]) + + +fragmentor = TestFragmentor() +noise_injector = GaussNoiseInjector(variance=0.05) + + +def test_write_mzml(): + """"""Write a mzML without spectra readable by pymzML."""""" + file = NamedTemporaryFile(""wb"") + peak_props = {} + mzml_params = { + ""gradient_length"": 0, + } + mzml_path = write_mzml(file, peak_props, fragmentor, noise_injector, mzml_params) + reader = pymzml.run.Reader(mzml_path) + assert reader.get_spectrum_count() == 0 + + +def test_write_empty_mzml(): + """"""Write a mzML without spectra readable by pymzML."""""" + file = NamedTemporaryFile(""wb"") + peak_props = {} + mzml_params = { + ""gradient_length"": 5, + } + mzml_path = write_mzml(file, peak_props, fragmentor, noise_injector, mzml_params) + reader = pymzml.run.Reader(mzml_path) + assert reader.get_spectrum_count() == 167 + + +def test_write_inosine_flat_mzml(): + file = NamedTemporaryFile(""wb"") + peak_props = { + ""inosine"": { + ""chemical_formula"": ""+C(10)H(12)N(4)O(5)"", + ""trivial_name"": ""inosine"", + ""charge"": 2, + ""scan_start_time"": 0, + ""peak_width"": 30, # seconds + ""peak_function"": None, + ""peak_params"": {}, + } + } + mzml_params = { + ""gradient_length"": 30, + } + mzml_path = write_mzml(file, peak_props, fragmentor, noise_injector, mzml_params) + reader = pymzml.run.Reader(mzml_path) + assert reader.get_spectrum_count() == 1000 + + +def test_write_inosine_gauss_mzml(): + file = NamedTemporaryFile(""wb"") + peak_props = { + ""inosine"": { + ""chemical_formula"": ""+C(10)H(12)N(4)O(5)"", + ""trivial_name"": ""inosine"", + ""charge"": 2, + ""scan_start_time"": 0, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 3}, # 10% of peak width + } + } + mzml_params = { + ""gradient_length"": 30, + } + mzml_path = write_mzml(file, peak_props, fragmentor, noise_injector, mzml_params) + reader = pymzml.run.Reader(mzml_path) + assert reader.get_spectrum_count() == 1000 + intensities = [] + for spec in reader: + if spec.ms_level == 1: + if len(spec.i) > 0: + intensities.append(spec.i[0]) + _, p = normaltest(intensities) + print(intensities) + # assert p < 5e-4 + + +def test_write_mzml_get_TIC(): + file = NamedTemporaryFile(""wb"") + peak_props = { + ""inosine"": { + ""chemical_formula"": ""+C(10)H(12)N(4)O(5)"", + ""trivial_name"": ""inosine"", + ""charge"": 2, + ""scan_start_time"": 0, + ""peak_width"": 30, # seconds + ""peak_function"": None, + ""peak_params"": {}, + } + } + mzml_params = { + ""gradient_length"": 30, + } + noise_injector = GaussNoiseInjector(variance=0.0) + mzml_path = write_mzml(file, peak_props, fragmentor, noise_injector, mzml_params) + reader = pymzml.run.Reader(mzml_path) + assert reader.get_spectrum_count() == 1000 + reader = pymzml.run.Reader(mzml_path) + tics = [] + for spec in reader: + if spec.ms_level == 1: + tics.append(sum(spec.i)) + tic = reader[""TIC""] + assert tic.peaks()[:, 1] == pytest.approx(np.array(tics, dtype=""float32"")) + + +def test_write_inosine_gamma_mzml(): + file = NamedTemporaryFile(""wb"") + peak_props = { + ""inosine"": { + ""chemical_formula"": ""+C(10)H(12)N(4)O(5)"", + ""trivial_name"": ""inosine"", + ""charge"": 2, + ""scan_start_time"": 0, + ""peak_width"": 30, # seconds + ""peak_function"": ""gamma"", + ""peak_scaling_factor"": 1e6, + ""peak_params"": {""a"": 3, ""scale"": 20}, # 10% of peak width, + } + } + mzml_params = { + ""gradient_length"": 30, + } + mzml_path = write_mzml(file, peak_props, fragmentor, noise_injector, mzml_params) + reader = pymzml.run.Reader(mzml_path) + assert reader.get_spectrum_count() == 1000 + intensities = [] + for spec in reader: + if spec.ms_level == 1: + if len(spec.i) > 0: + intensities.append(spec.i[0]) + ## what is a reasonable p-value cutoff here? + # assert t.pvalue < 1e-100 + + +def test_write_inosine_adenosine_gauss_mzml(): + file = NamedTemporaryFile(""wb"") + peak_props = { + ""inosine"": { + ""chemical_formula"": ""+C(10)H(12)N(4)O(5)"", + ""charge"": 1, + ""trivial_name"": ""inosine"", + ""scan_start_time"": 0, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 3}, # 10% of peak width, + ""peak_scaling_factor"": 1e3, + }, + ""+C(10)H(13)N(5)O(4)"": { + ""chemical_formula"": ""+C(10)H(13)N(5)O(4)"", + ""trivial_name"": ""adenosine"", + ""charge"": 1, + ""scan_start_time"": 0, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 3}, # 10% of peak width, + }, + } + mzml_params = {""gradient_length"": 30, ""min_intensity"": 0} + mzml_path = write_mzml(file, peak_props, fragmentor, noise_injector, mzml_params) + reader = pymzml.run.Reader(mzml_path) + assert reader.get_spectrum_count() == 1000 + + ino_rt = [] + ino_intensities = [] + adeno_rt = [] + adeno_intensities = [] + + ino_mono = 269.0880 + adeno_mono = 268.1040 + + for spec in reader: + if spec.ms_level == 1: + ino_i = spec.i[abs(spec.mz - ino_mono) < 0.001] + adeno_i = spec.i[abs(spec.mz - adeno_mono) < 0.001] + if len(adeno_i) > 0: + adeno_intensities.append(adeno_i[0]) + adeno_rt.append(spec.scan_time[0]) + if len(ino_i) > 0: + ino_intensities.append(ino_i[0]) + ino_rt.append(spec.scan_time[0]) + + _, p = normaltest(ino_intensities) + # assert p < 5e-4 + _, p = normaltest(adeno_intensities) + # assert p < 5e-4 + + +def test_write_inosine_adenosine_gauss_shift_mzml(): + file = NamedTemporaryFile(""wb"") + peak_props = { + ""inosine"": { + ""chemical_formula"": ""+C(10)H(12)N(4)O(5)"", + ""charge"": 1, + ""trivial_name"": ""inosine"", + ""scan_start_time"": 0, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 3}, # 10% of peak width, + ""peak_scaling_factor"": 1e6, + }, + ""+C(10)H(13)N(5)O(4)"": { + ""chemical_formula"": ""+C(10)H(13)N(5)O(4)"", + ""trivial_name"": ""adenosine"", + ""charge"": 1, + ""scan_start_time"": 15, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 3}, # 10% of peak width, + ""peak_scaling_factor"": 1e6, + }, + } + mzml_params = { + ""gradient_length"": 45, + } + noise_injector = GaussNoiseInjector(variance=0.0) + # noise_injector = UniformformNoiseInjector() + mzml_path = write_mzml(file, peak_props, fragmentor, noise_injector, mzml_params) + reader = pymzml.run.Reader(mzml_path) + assert reader.get_spectrum_count() == 1500 + + ino_rt = [] + ino_intensities = [] + adeno_rt = [] + adeno_intensities = [] + + ino_mono = 269.0880 + adeno_mono = 268.1040 + + for spec in reader: + if spec.ms_level == 1: + ino_i = spec.i[abs(spec.mz - ino_mono) < 0.001] + adeno_i = spec.i[abs(spec.mz - adeno_mono) < 0.001] + if len(adeno_i) > 0: + adeno_intensities.append(adeno_i[0]) + adeno_rt.append(spec.scan_time[0]) + if len(ino_i) > 0: + ino_intensities.append(ino_i[0]) + ino_rt.append(spec.scan_time[0]) + # assert rt max diff is about 15 + m_i = np.argmax(ino_intensities) + m_a = np.argmax(adeno_intensities) + mean_i_rt = ino_rt[m_i] + mean_a_rt = adeno_rt[m_a] + assert 14 < (mean_a_rt - mean_i_rt) < 16 + + +def test_write_inosine_proper_fragments_mzml(): + file = NamedTemporaryFile(""wb"") + peak_props = { + ""inosine"": { + ""chemical_formula"": ""+C(10)H(12)N(4)O(5)"", + ""charge"": 1, + ""trivial_name"": ""inosine"", + ""scan_start_time"": 0, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 3}, # 10% of peak width, + ""peak_scaling_factor"": 1e6, + }, + } + mzml_params = { + ""gradient_length"": 30, + } + + nucl_fragmentor = NucleosideFragmentor() + mzml_path = write_mzml( + file, peak_props, nucl_fragmentor, noise_injector, mzml_params + ) + reader = pymzml.run.Reader(mzml_path) + assert reader.get_spectrum_count() == 1000 + + ino_rt = [] + ino_intensities = [] + ino_fragments = [] + + ino_mono = 269.0880 + + for spec in reader: + if spec.ms_level == 1: + ino_i = spec.i[abs(spec.mz - ino_mono) < 0.001] + if len(ino_i) > 0: + ino_intensities.append(ino_i[0]) + ino_rt.append(spec.scan_time[0]) + + _, p = normaltest(ino_intensities) + expected_frags = np.array([137.0457872316]) + + for frag_list in ino_fragments: + assert len(frag_list) == len(expected_frags) + sorted_frags = np.sort(frag_list) + assert abs(sorted_frags - expected_frags) < 0.001 + + +@pytest.mark.slow() +def test_write_peptide_gauss_mzml(): + file = NamedTemporaryFile(""wb"") + peak_props = { + ""ELVISLIVES"": { + ""chemical_formula"": ""ELVISLIVES"", + ""trivial_name"": ""ELVISLIVES"", + ""charge"": 2, + ""scan_start_time"": 0, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 3}, # 10% of peak width + }, + ""ELVISLIVSE"": { + ""charge"": 2, + ""trivial_name"": ""ELVISLIVSE"", + ""chemical_formula"": ""ELVISLIVSE"", + ""scan_start_time"": 15, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 3}, # 10% of peak width, + }, + } + mzml_params = { + ""gradient_length"": 45, + } + fragmentor = PeptideFragmentor() + mzml_path = write_mzml(file, peak_props, fragmentor, noise_injector, mzml_params) + reader = pymzml.run.Reader(mzml_path) + assert reader.get_spectrum_count() == 1500 + intensities = [] + for spec in reader: + if spec.ms_level == 1: + if len(spec.i) > 0: + intensities.append(sum(spec.i)) + _, p = normaltest(intensities) + # assert p < 5e-4 + + +def test_write_2_mols_same_cc(): + file = NamedTemporaryFile(""wb"") + peak_props = { + ""uridine"": { + ""charge"": 2, + ""chemical_formula"": ""+C(9)H(11)N(2)O(6)"", + ""trivial_name"": ""uridine"", + ""scan_start_time"": 0, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 1}, # 10% of peak width, + ""peak_scaling_factor"": 0.5 * 1e6, + }, + ""pseudouridine"": { + ""chemical_formula"": ""+C(9)H(11)N(2)O(6)"", + ""trivial_name"": ""pseudouridine"", + ""charge"": 2, + ""scan_start_time"": 15, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 1}, # 10% of peak width, + ""peak_scaling_factor"": 1e6, + }, + } + mzml_params = { + ""gradient_length"": 45, + ""min_intensity"": 10, + } + mzml_params = { + ""gradient_length"": 45, + } + fragmentor = NucleosideFragmentor() + noise_injector = GaussNoiseInjector(variance=0.0) + mzml_path = write_mzml(file, peak_props, fragmentor, noise_injector, mzml_params) + reader = pymzml.run.Reader(mzml_path) + # assert reader.get_spectrum_count() == 1499 + intensities = [] + for spec in reader: + if spec.ms_level == 1: + if len(spec.i) > 0: + intensities.append(sum(spec.i)) + peaks, _ = find_peaks(intensities) + assert len(peaks) == 2 + + +def test_rescale_intensity(): + i = 100 + rt = 15 + molecule = """" + peak_props = { + ""uridine"": { + ""charge"": 2, + ""chemical_formula"": ""+C(9)H(11)N(2)O(6)"", + ""trivial_name"": ""uridine"", + ""scan_start_time"": 0, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 1}, # 10% of peak width, + ""peak_scaling_factor"": 0.5, + } + } + iso_lib = {} + + i_rescaled = smiter.synthetic_mzml.rescale_intensity( + i, rt, ""uridine"", peak_props, iso_lib + ) + # should be max_i @ half peak width, with half peak width = 15 and max_i = 50 (100 * 0.5) + assert round(i_rescaled, 2) == 50 + + +def test_generate_interval_tree(): + peak_props = { + ""uridine"": { + ""charge"": 2, + ""chemical_formula"": ""+C(9)H(11)N(2)O(6)"", + ""trivial_name"": ""uridine"", + ""scan_start_time"": 0, + ""peak_width"": 5, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 1}, # 10% of peak width, + ""peak_scaling_factor"": 1, + }, + ""pseudouridine"": { + ""charge"": 2, + ""chemical_formula"": ""+C(9)H(11)N(2)O(6)"", + ""trivial_name"": ""uridine"", + ""scan_start_time"": 4, + ""peak_width"": 5, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 1}, # 10% of peak width, + ""peak_scaling_factor"": 1, + }, + } + tree = generate_interval_tree(peak_props) + + # only uridine + tree_3 = tree[3] + assert len(tree_3) == 1 + for entry in tree_3: + assert entry.data == ""uridine"" + assert entry.length() == 5 + + # only pseudouridine + tree_8 = tree[8] + assert len(tree_3) == 1 + for entry in tree_8: + assert entry.data == ""pseudouridine"" + assert entry.length() == 5 + + # uridine and pseudouridine + tree_4 = tree[4] + assert len(tree_4) == 2 + items = [""pseudouridine"", ""uridine""] + for entry in tree_4: + items.remove(entry.data) + assert entry.length() == 5 + assert len(items) == 0 + + +def test_generate_scans_simple(): + # generate 1 MS1 and 1 MS2 scan + # peak width is as long as gradient and two times ms_rt_diff + peak_props = { + ""uridine"": { + ""charge"": 2, + ""chemical_formula"": ""+C(9)H(11)N(2)O(6)"", + ""trivial_name"": ""uridine"", + ""scan_start_time"": 0, + ""peak_width"": 0.06, # peak as long as ms_rt_diff and gradient length + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 1}, # 10% of peak width, + ""peak_scaling_factor"": 1, + } + } + trivial_names = {val[""chemical_formula""]: key for key, val in peak_props.items()} + scans, mol_scan_dict = generate_scans( + generate_molecule_isotopologue_lib(peak_props, [1, 2, 3], trivial_names), + peak_props, + generate_interval_tree(peak_props), + NucleosideFragmentor(), + UniformNoiseInjector(), + {""gradient_length"": 0.06, ""min_intensity"": 0, ""isolation_window_width"": 0.2}, + ) + assert len(scans) == 1 # one MS1 with related MS2 scans + assert len(scans[0]) == 2 # first element is a MS1 scan and a list of MS2 scans + assert len(scans[0][1]) == 1 # list of MS2 scans has one scan + + +def test_generate_molecule_isotopologue_lib(): + peak_props = { + ""uridine"": { + ""charge"": 2, + ""chemical_formula"": ""+C(9)H(11)N(2)O(6)"", + ""trivial_name"": ""uridine"", + ""scan_start_time"": 0, + ""peak_width"": 0.06, # peak as long as ms_rt_diff and gradient length + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 1}, # 10% of peak width, + ""peak_scaling_factor"": 1, + } + } + charges = [1, 2, 3] + trivial_names = {""+C(9)H(11)N(2)O(6)"": ""uridine""} + lib = generate_molecule_isotopologue_lib(peak_props, charges, trivial_names) + assert list(lib.keys()) == [""uridine""] + assert np.isclose( + lib[""uridine""][""mz""], + [ + 122.53813200786999, + 123.03962222482085, + 123.54123939611428, + 124.04272136528171, + 124.5442376065953, + 125.04387103562883, + 125.54630817011011, + ], + ).all() + assert np.isclose( + lib[""uridine""][""i""], + [ + 1.0, + 0.10819885003176334, + 0.01762911869579814, + 0.0013546885053562444, + 6.246133599652487e-05, + 4.563511253647458e-07, + 4.800737885333426e-10, + ], + ).all() + + +def test_write_mzml_one_spec(): + tempfile = NamedTemporaryFile(""wb"") + peak_props = { + ""uridine"": { + ""charge"": 2, + ""chemical_formula"": ""+C(9)H(11)N(2)O(6)"", + ""trivial_name"": ""uridine"", + ""scan_start_time"": 0, + ""peak_width"": 0.03, # peak as long as ms_rt_diff and gradient length + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 1}, # 10% of peak width, + ""peak_scaling_factor"": 1, + } + } + fragmentor = NucleosideFragmentor() + noise = UniformNoiseInjector() + mzml_params = {""gradient_length"": 0.03, ""ms_rt_diff"": 0.03} + + write_mzml(tempfile, peak_props, fragmentor, noise, mzml_params) + reader = pymzml.run.Reader(tempfile.name) + assert reader.get_spectrum_count() == 1 + + +def test_dynacmic_exclusion(): + tempfile = NamedTemporaryFile(""wb"") + peak_props = { + ""uridine"": { + ""charge"": 2, + ""chemical_formula"": ""+C(9)H(11)N(2)O(6)"", + ""trivial_name"": ""uridine"", + ""scan_start_time"": 0, + ""peak_width"": 5, # peak as long as ms_rt_diff and gradient length + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 1}, # 10% of peak width, + ""peak_scaling_factor"": 1e5, + } + } + trivial_names = {""+C(9)H(11)N(2)O(6)"": ""uridine""} + # dynamic_exclusion is bigger than gradient length, so we expect only one MS2 fragment spectrum + default_mzml_params = { + ""gradient_length"": 5, + ""min_intensity"": 100, + ""isolation_window_width"": 0.5, + ""ion_target"": 3e6, + ""ms_rt_diff"": 0.03, + ""dynamic_exclusion"": 30, # in seconds + } + scans, mol_scan_dict = generate_scans( + generate_molecule_isotopologue_lib(peak_props, [1, 2, 3], trivial_names), + peak_props, + generate_interval_tree(peak_props), + NucleosideFragmentor(), + UniformNoiseInjector(), + default_mzml_params, + ) + number_fragment_specs = 0 + for ms1, ms2_list in scans: + for ms2 in ms2_list: + if len(ms2[""mz""]) > 0: + number_fragment_specs += 1 + # fails when dynamic_exclusion is set to 0 + # since there will be 15 fragments specs + assert number_fragment_specs == 1 + + # breakpoint() +","Python" +"Computational Biochemistry","LeidelLab/SMITER","tests/test_peak_distribution.py",".py","121","12","""""""Summary."""""" + + +def test_gauss_dist(): + """"""Summary."""""" + pass + + +def test_gamma_dist(): + """"""Summary."""""" + pass +","Python" +"Computational Biochemistry","LeidelLab/SMITER","tests/test_smiter_cli.py",".py","513","20","#!/usr/bin/env python + +""""""Tests for `smiter` package."""""" + +import pytest +from click.testing import CliRunner + +from smiter import cli, synthetic_mzml + + +def test_command_line_interface(): + """"""Test the CLI."""""" + runner = CliRunner() + result = runner.invoke(cli.main) + assert result.exit_code == 0 + assert ""smiter.cli.main"" in result.output + help_result = runner.invoke(cli.main, [""--help""]) + assert help_result.exit_code == 0 + assert ""--help Show this message and exit."" in help_result.output +","Python" +"Computational Biochemistry","LeidelLab/SMITER","tests/__init__.py",".py","36","2","""""""Unit test package for smiter."""""" +","Python" +"Computational Biochemistry","LeidelLab/SMITER","tests/test_noise_injection.py",".py","7149","237","""""""Summary."""""" +import numpy as np +import pytest + +import smiter +from smiter.noise_functions import ( + GaussNoiseInjector, + UniformNoiseInjector, + JamssNoiseInjector, +) +from smiter.synthetic_mzml import Scan + +# np.random.seed(1312) + +# make it a test class +# integration test, test GaussNoiseInjector methods by themselves! +def test_GaussNoiseInjector_intensity_noise_ms1(): + i_array = np.array([1e6, 2e6, 3e6], dtype=""float32"") + scan = Scan( + { + ""mz"": np.array([100, 200, 300], dtype=""float32""), + ""i"": i_array, + ""ms_level"": 1, + } + ) + noise_injector = GaussNoiseInjector(variance=0.2) + scan = noise_injector.inject_noise(scan) + # breakpoint() + # assert abs((scan.i - 3e6) < 3e6 * 0.05).all() + assert (scan.i - i_array < i_array * 0.2).all() + + +# make it a test class +# integration test, test GaussNoiseInjector methods by themselves! +def test_GaussNoiseInjector_intensity_noise_ms2(): + i_array = np.array([1e6, 2e6, 3e6], dtype=""float32"") + scan = Scan( + { + ""mz"": np.array([100, 200, 300], dtype=""float32""), + ""i"": i_array, + ""ms_level"": 2, + } + ) + noise_injector = GaussNoiseInjector() + scan = noise_injector.inject_noise(scan, dropout=0.0) + assert (scan.i - i_array < i_array * 0.2).all() + + +def test_GaussNoiseInjector_intensity_noise_ms2_drop_all(): + i_array = np.array([1e6, 2e6, 3e6], dtype=""float32"") + scan = Scan( + { + ""mz"": np.array([100, 200, 300], dtype=""float32""), + ""i"": i_array, + ""ms_level"": 2, + } + ) + noise_injector = GaussNoiseInjector() + scan = noise_injector.inject_noise(scan, dropout=1.0) + assert len(scan.mz) == 0 + assert len(scan.i) == 0 + + +def test_GaussNoiseInjector_generate_intensity_noise(): + i_array = np.array([1e6, 2e6, 3e6], dtype=""float32"") + scan = Scan( + { + ""mz"": np.array([100, 200, 300], dtype=""float32""), + ""i"": i_array, + ""ms_level"": 1, + } + ) + noise_injector = GaussNoiseInjector() + noise = noise_injector._generate_intensity_noise(scan) + assert (abs(noise) < i_array * 0.2).all() + + +def test_GaussNoiseInjector_generate_mz_noise(): + i_array = np.array([1e6, 2e6, 3e6], dtype=""float32"") + scan = Scan( + { + ""mz"": np.array([100, 200, 300], dtype=""float32""), + ""i"": i_array, + ""ms_level"": 1, + } + ) + noise_injector = GaussNoiseInjector() + noise = noise_injector._generate_mz_noise(scan) + # breakpoint() + assert (abs(noise) < scan.mz * 1e-5).all() + + +def test_gauss_mz_noise_ms1(): + i_array = np.array([1e6, 2e6, 3e6], dtype=""float32"") + scan = Scan( + { + ""mz"": np.array([100, 200, 300], dtype=""float32""), + ""i"": i_array, + ""ms_level"": 1, + } + ) + noise_injector = GaussNoiseInjector() + scan = noise_injector.inject_noise(scan) + # breakpoint() + assert ( + abs(scan.mz - np.array([100, 200, 300], dtype=""float32"")) + < np.array([100, 200, 300], dtype=""float32"") * 1e-5 + ).all() + + +def test_uniform_intensity_noise_ms1(): + i_array = np.array([1e6, 2e6, 3e6], dtype=""float32"") + i_array = np.array([1e6, 2e6, 3e6], dtype=""float32"") + scan = Scan( + { + ""mz"": np.array([100, 200, 300], dtype=""float32""), + ""i"": i_array, + ""ms_level"": 1, + } + ) + noise_injector = UniformNoiseInjector(ppm_noise=5e-6, intensity_noise=0.4) + scan = noise_injector.inject_noise(scan) + assert (abs(scan.i - i_array) < i_array * 0.4).all() + + +# make it a test class +# integration test, test UniformNoiseInjector methods by themselves! +def test_uniform_intensity_noise_ms2(): + i_array = np.array([1e6, 2e6, 3e6], dtype=""float32"") + i_array = np.array([1e6, 2e6, 3e6], dtype=""float32"") + scan = Scan( + { + ""mz"": np.array([100, 200, 300], dtype=""float32""), + ""i"": i_array, + ""ms_level"": 2, + } + ) + noise_injector = UniformNoiseInjector(ppm_noise=5e-6, intensity_noise=0.4) + scan = noise_injector.inject_noise(scan, dropout=0.0) + # breakpoint() + print(""before"", i_array) + print(""after"", scan.i) + print(abs(i_array - scan.i)) + print() + assert (abs(scan.i - i_array) < i_array * 0.4).all() + + +def test_uniform_intensity_noise_ms2_drop_all(): + i_array = np.array([1e6, 2e6, 3e6], dtype=""float32"") + i_array = np.array([1e6, 2e6, 3e6], dtype=""float32"") + scan = Scan( + { + ""mz"": np.array([100, 200, 300], dtype=""float32""), + ""i"": i_array, + ""ms_level"": 2, + } + ) + # breakpoint() + noise_injector = UniformNoiseInjector(dropout=1.0) + scan = noise_injector.inject_noise(scan) + # breakpoint() + assert len(scan.mz) == 0 + assert len(scan.i) == 0 + + +def test_UniformNoiseInjector_generate_intensity_noise(): + i_array = np.array([1e6, 2e6, 3e6], dtype=""float32"") + scan = Scan( + { + ""mz"": np.array([100, 200, 300], dtype=""float32""), + ""i"": i_array, + ""ms_level"": 1, + } + ) + noise_injector = UniformNoiseInjector(ppm_noise=5e-6, intensity_noise=0.4) + noise = noise_injector._generate_intensity_noise(scan, intensity_noise=0.4) + assert (abs(noise) < i_array * 0.4).all() + + +def test_UniformNoiseInjector_generate_mz_noise(): + i_array = np.array([1e6, 2e6, 3e6], dtype=""float32"") + scan = Scan( + { + ""mz"": np.array([100, 200, 300], dtype=""float32""), + ""i"": i_array, + ""ms_level"": 1, + } + ) + noise_injector = UniformNoiseInjector(ppm_noise=5e-6, intensity_noise=0.4) + noise = noise_injector._generate_mz_noise(scan, ppm_noise=5e-6) + # breakpoint() + assert (abs(noise) < scan.mz * 5e-6).all() + + +def test_UniformNoiseInjector_mz_noise_ms1(): + i_array = np.array([1e6, 2e6, 3e6], dtype=""float32"") + scan = Scan( + { + ""mz"": np.array([100, 200, 300], dtype=""float32""), + ""i"": i_array, + ""ms_level"": 1, + } + ) + noise_injector = UniformNoiseInjector(ppm_noise=5e-6, intensity_noise=0.4) + scan = noise_injector.inject_noise(scan) + # breakpoint() + assert ( + abs(scan.mz - np.array([100, 200, 300], dtype=""float32"")) + < np.array([100, 200, 300], dtype=""float32"") * 5e-6 + ).all() + + +# def test_JamssNoiseInjector_mz_noise_ms1(): +# i_array = np.array([1e6, 2e6, 3e6], dtype=""float32"") +# scan = Scan( +# { +# ""mz"": np.array([100, 200, 300], dtype=""float32""), +# ""i"": i_array, +# ""ms_level"": 1, +# } +# ) +# noise_injector = JamssNoiseInjector(ppm_noise=5e-6, intensity_noise=0.4) +# scan = noise_injector.inject_noise(scan) + + +def test_JamssNoiseInjector_intensity_noise_ms1(): + i_array = np.array([1e6, 2e6, 3e6], dtype=""float32"") + scan = Scan( + { + ""mz"": np.array([100, 200, 300], dtype=""float32""), + ""i"": i_array, + ""ms_level"": 1, + } + ) + noise_injector = JamssNoiseInjector(ppm_noise=5e-6, intensity_noise=0.4) + scan = noise_injector.inject_noise(scan) +","Python" +"Computational Biochemistry","LeidelLab/SMITER","tests/test_lib.py",".py","4723","146","""""""Summary. +"""""" +import csv +import os +from tempfile import NamedTemporaryFile + +import pytest + +from smiter.lib import ( + check_mzml_params, + check_peak_properties, + csv_to_peak_properties, + peak_properties_to_csv, +) + + +def test_check_mzml_params(): + mzml_params = { + ""gradient_length"": 45, + } + mzml_params = check_mzml_params(mzml_params) + assert mzml_params[""gradient_length""] == 45 + + +def test_check_faulty_mzml_params(): + mzml_params = {} + with pytest.raises(Exception): + mzml_params = check_mzml_params(mzml_params) + + +def test_check_peak_properties_missing_default(): + peak_props = { + ""ELVISLIVES"": { + ""trivial_name"": ""ELVISLIVES"", + ""scan_start_time"": 0, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 3}, # 10% of peak width + }, + } + peak_props = check_peak_properties(peak_props) + assert peak_props[""ELVISLIVES""][""charge""] == 2 + + +def test_check_peak_properties_missing_opt(): + peak_props = { + ""ELVISLIVES"": { + ""scan_start_time"": 0, + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 3}, # 10% of peak width + }, + } + peak_props = check_peak_properties(peak_props) + # sets charge but leaves out trivial_name + assert peak_props[""ELVISLIVES""][""charge""] == 2 + assert ""trivial_name"" not in peak_props[""ELVISLIVES""] + + +def test_check_peak_properties_missing_required(): + peak_props = { + ""ELVISLIVES"": { + ""trivial_name"": ""ELVISLIVES"", + ""peak_width"": 30, # seconds + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 3}, # 10% of peak width + }, + } + with pytest.raises(Exception): + peak_props = check_peak_properties(peak_props) + + +def test_csv_to_peak_properties(): + csv_file = os.path.join(os.path.dirname(__file__), ""data"", ""molecules_test.csv"") + peak_properties = csv_to_peak_properties(csv_file) + assert ""2′-O-methylcytidine"" in peak_properties + assert ( + peak_properties[""2′-O-methylcytidine""][""trivial_name""] == ""2′-O-methylcytidine"" + ) + assert peak_properties[""2′-O-methylcytidine""][""scan_start_time""] == 10 + assert peak_properties[""2′-O-methylcytidine""][""peak_scaling_factor""] == 1e6 + # default + assert peak_properties[""2′-O-methylcytidine""][""charge""] == 2 + + assert ""5-methoxycarbonylmethyluridine"" in peak_properties + assert ( + peak_properties[""5-methoxycarbonylmethyluridine""][""trivial_name""] + == ""5-methoxycarbonylmethyluridine"" + ) + assert peak_properties[""5-methoxycarbonylmethyluridine""][""scan_start_time""] == 12 + assert ( + peak_properties[""5-methoxycarbonylmethyluridine""][""peak_scaling_factor""] == 2e6 + ) + # default + assert peak_properties[""5-methoxycarbonylmethyluridine""][""charge""] == 2 + + +def test_peak_properties_to_csv(): + peak_properties = { + ""2′-O-methylcytidine"": { + ""trivial_name"": ""2′-O-methylcytidine"", + ""chemical_formula"": ""+C(10)H(15)N(3)O(5)"", + ""charge"": 2, + ""scan_start_time"": 10.0, + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 2}, + ""peak_scaling_factor"": 1000000.0, + ""peak_width"": 30, + }, + ""5-methoxycarbonylmethyluridine"": { + ""trivial_name"": ""5-methoxycarbonylmethyluridine"", + ""chemical_formula"": ""+C(12)H(16)N(2)O(8)"", + ""charge"": 2, + ""scan_start_time"": 12.0, + ""peak_function"": ""gauss"", + ""peak_params"": {""sigma"": 2}, + ""peak_scaling_factor"": 2000000.0, + ""peak_width"": 30, + }, + } + csv_file = ""out.csv"" + fname = peak_properties_to_csv(peak_properties, csv_file) + assert fname == csv_file + with open(csv_file) as fout: + reader = csv.DictReader(fout) + lines = [l for l in reader] + print(lines) + + assert lines[0][""chemical_formula""] == ""+C(10)H(15)N(3)O(5)"" + assert lines[0][""scan_start_time""] == ""10.0"" + assert lines[0][""peak_function""] == ""gauss"" + assert lines[0][""peak_params""] == ""sigma=2"" + assert lines[0][""peak_scaling_factor""] == ""1000000.0"" + assert lines[0][""peak_width""] == ""30"" + # default + assert lines[0][""charge""] == ""2"" + + assert lines[1][""chemical_formula""] == ""+C(12)H(16)N(2)O(8)"" + assert lines[1][""scan_start_time""] == ""12.0"" + assert lines[1][""peak_function""] == ""gauss"" + assert lines[1][""peak_params""] == ""sigma=2"" + assert lines[1][""peak_scaling_factor""] == ""2000000.0"" + assert lines[1][""peak_width""] == ""30"" + # default + assert lines[0][""charge""] == ""2"" +","Python" +"Computational Biochemistry","LeidelLab/SMITER","tests/test_fragmentation.py",".py","1085","40","""""""Summary."""""" +import os +import numpy as np +import pytest + +import smiter +from smiter.fragmentation_functions import ( + NucleosideFragmentor, + PeptideFragmentor, + LipidFragmentor, +) + + +def test_fragment_peptide(): + """"""Summary."""""" + fragger = PeptideFragmentor(charges=1, ions=[""y""]) + peaks = fragger.fragment(""L"") + expected_mzs = np.array([132.101]) + assert ((peaks[:, 0] - expected_mzs) < 0.001).all() + + +def test_fragment_nucleotide(): + """"""Summary."""""" + fragger = NucleosideFragmentor() + peaks = fragger.fragment(""adenosine"") + expected_mzs = np.array([119.03522254717, 136.0617716478]) + assert ((peaks[:, 0] - expected_mzs) < 0.001).all() + + +@pytest.mark.skip() +def test_fragment_lipid(): + test_lipid_file = ""test_lipids.txt"" + test_lipid_file = os.path.abspath(test_lipid_file) + with open(test_lipid_file, ""wt"") as fout: + fout.write(""PC 18:0/12:0\n"") + fout.write(""PE 18:3;1-16:2"") + fragger = LipidFragmentor(test_lipid_file) + masses = fragger.fragment(""PC 18:0/12:0"") + assert np.allclose(masses, np.array([184.0733])) +","Python" +"Computational Biochemistry","t-/acpype","acpype.py",".py","146156","3591","#!/usr/bin/env python +from __future__ import print_function +from datetime import datetime +from shutil import copy2 +from shutil import rmtree +import traceback +import signal +import time +import optparse +import math +import os +import pickle +import sys +import subprocess as sub +import re + +"""""" + Requirements: Python 2.6 or higher or Python 3.x + Antechamber (from AmberTools preferably) + OpenBabel (optional, but strongly recommended) + + This code is released under GNU General Public License V3. + + <<< NO WARRANTY AT ALL!!! >>> + + It was inspired by: + + - amb2gmx.pl (Eric Sorin, David Mobley and John Chodera) + and depends on Antechamber and Openbabel + + - YASARA Autosmiles: + http://www.yasara.org/autosmiles.htm (Elmar Krieger) + + - topolbuild (Bruce Ray) + + - xplo2d (G.J. Kleywegt) + + For Antechamber, please cite: + 1. Wang, J., Wang, W., Kollman P. A.; Case, D. A. ""Automatic atom type and + bond type perception in molecular mechanical calculations"". Journal of + Molecular Graphics and Modelling , 25, 2006, 247260. + 2. Wang, J., Wolf, R. M.; Caldwell, J. W.; Kollman, P. A.; Case, D. A. + ""Development and testing of a general AMBER force field"". Journal of + Computational Chemistry, 25, 2004, 1157-1174. + + If you use this code, I am glad if you cite: + + SOUSA DA SILVA, A. W. & VRANKEN, W. F. + ACPYPE - AnteChamber PYthon Parser interfacE. + BMC Research Notes 2012, 5:367 doi:10.1186/1756-0500-5-367 + http://www.biomedcentral.com/1756-0500/5/367 + + Alan Wilter Sousa da Silva, D.Sc. + Bioinformatician, UniProt, EMBL-EBI + Hinxton, Cambridge CB10 1SD, UK. + >>http://www.ebi.ac.uk/~awilter<< + + alanwilter _at_ gmail _dot_ com +"""""" + +svnId = '$Id$' +try: + svnRev, svnDate, svnTime = svnId.split()[2:5] +except: + svnRev, svnDate, svnTime = '0', '0', '0' +year = datetime.today().year +tag = ""%s %s Rev: %s"" % (svnDate, svnTime, svnRev) + +lineHeader = \ + ''' +| ACPYPE: AnteChamber PYthon Parser interfacE v. %s (c) %s AWSdS | +''' % (tag, year) +frameLine = (len(lineHeader) - 2) * '=' +header = '%s%s%s' % (frameLine, lineHeader, frameLine) + +# TODO: +# Howto Charmm and Amber with NAMD +# Howto build topology for a modified amino acid +# CYANA topology files + +# List of Topology Formats created by acpype so far: +outTopols = ['gmx', 'cns', 'charmm'] +qDict = {'mopac': 0, 'divcon': 1, 'sqm': 2} + +# Residues that are not solute, to be avoided when balancing charges in +# amb2gmx mode +ionOrSolResNameList = ['Cl-', 'Na+', 'K+', 'CIO', 'Cs+', 'IB', 'Li+', 'MG2', + 'Rb+', 'WAT', 'MOH', 'NMA'] + +leapGaffFile = 'leaprc.gaff' +# leapAmberFile = 'leaprc.ff99SB' # 'leaprc.ff10' and 'leaprc.ff99bsc0' has extra Atom Types not in parm99.dat +leapAmberFile = 'leaprc.ff12SB' + +# ""qm_theory='AM1', grms_tol=0.0002, maxcyc=999, tight_p_conv=1, scfconv=1.d-10,"" +# ""AM1 ANALYT MMOK GEO-OK PRECISE"" + +cal = 4.184 +Pi = 3.141593 +qConv = 18.222281775 # 18.2223 +radPi = 57.295780 # 180/Pi +maxDist = 3.0 +minDist = 0.5 +maxDist2 = maxDist ** 2 # squared Ang. +minDist2 = minDist ** 2 # squared Ang. +diffTol = 0.01 + +dictAmbAtomType2AmbGmxCode = \ + {'BR': '1', 'C': '2', 'CA': '3', 'CB': '4', 'CC': '5', 'CK': '6', 'CM': '7', 'CN': '8', 'CQ': '9', + 'CR': '10', 'CT': '11', 'CV': '12', 'CW': '13', 'C*': '14', 'Ca': '15', 'F': '16', 'H': '17', + 'HC': '18', 'H1': '19', 'H2': '20', 'H3': '21', 'HA': '22', 'H4': '23', 'H5': '24', 'HO': '25', + 'HS': '26', 'HW': '27', 'HP': '28', 'I': '29', 'Cl': '30', 'Na': '31', 'IB': '32', 'Mg': '33', + 'N': '34', 'NA': '35', 'NB': '36', 'NC': '37', 'N2': '38', 'N3': '39', 'N*': '40', 'O': '41', + 'OW': '42', 'OH': '43', 'OS': '44', 'O2': '45', 'P': '46', 'S': '47', 'SH': '48', 'CU': '49', + 'FE': '50', 'K': '51', 'Rb': '52', 'Cs': '53', 'Li': '56', 'Zn': '57', 'Sr': '58', 'Ba': '59', + 'MCH3A': 'MCH3A', 'MCH3B': 'MCH3B', 'MNH2': 'MNH2', 'MNH3': 'MNH3', 'MW': 'MW'} + +dictOplsAtomType2OplsGmxCode = \ + {'Ac3+': ['697'], 'Am3+': ['699'], 'Ar': ['Ar', '097'], 'Ba2+': ['414'], + 'Br': ['722', '730'], 'Br-': ['402'], + 'CT': ['064', '076', '122', '135', '136', '137', '138', '139', '148', '149', '152', '157', '158', '159', '161', '173', '174', '175', '181', '182', '183', '184', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '223', '224', '225', '229', '230', '242', '243', '244', '256', '257', '258', '259', '273', '274', '275', '276', '291', '292', '293', '294', '297', '305', '306', '307', '308', '331', '371', '373', '375', '391', '396', '421', '431', '443', '448', '453', '455', '458', '461', '468', '476', '482', '484', '486', '490', '491', '492', '498', '499', '505', '515', '516', '645', '670', '671', '672', '673', '674', '675', '676', '677', '678', '679', '680', '681', '701', '725', '747', '748', '755', '756', '757', '758', '762', '764', '765', '766', '774', '775', '776', '782', '783', '903', '904', '905', '906', '907', '908', '912', '913', '914', '915', '942', '943', '944', '945', '951', '957', '959', '960', '961', '962', '963', '964'], + 'CA': ['053', '145', '147', '166', '199', '221', '228', '260', '263', '266', '302', '312', '315', '317', '336', '351', '362', '380', '457', '460', '463', '472', '488', '521', '522', '523', '528', '532', '533', '538', '539', '551', '582', '590', '591', '592', '593', '604', '605', '606', '607', '608', '609', '610', '611', '612', '625', '644', '647', '648', '649', '650', '651', '652', '714', '716', '718', '720', '724', '727', '729', '731', '735', '736', '737', '738', '739', '742', '752', '768', '916', '917', '918'], + 'C3': ['007', '010', '036', '039', '063', '065', '067', '068', '069', '070', '080', '088', '090', '092', '096', '106', '107', '109', '126', '132', '415', '418', '425', '429'], + 'C': ['001', '017', '026', '058', '095', '131', '231', '234', '235', '247', '252', '267', '320', '322', '334', '366', '378', '470', '471', '772', '952'], + 'C2': ['005', '009', '015', '016', '019', '022', '027', '028', '031', '034', '037', '056', '057', '061', '071', '081', '089', '091', '093', '110'], + 'CT_2': ['223B', '224B', '225B', '246', '283', '284', '285', '292B', '293B', '295', '298', '299', '906B', '912B'], + 'CM': ['141', '142', '143', '227', '323', '324', '337', '338', '381', '382', '517', '518', '708'], + 'CW': ['508', '514', '543', '552', '561', '567', '575', '583', '588', '637'], + 'CB': ['050', '349', '350', '364', '365', '501', '595', '623', '624'], + 'CH': ['006', '008', '014', '025', '029', '030', '060', '073'], + 'CZ': ['261', '423', '754', '925', '927', '928', '929', '931'], + 'CO': ['189', '191', '193', '195', '197', '198'], + 'C_2': ['232', '233', '277', '280', '465'], + 'CR': ['506', '509', '558', '572', '634'], + 'CQ': ['347', '531', '621', '642'], + 'CV': ['507', '560', '574', '636'], + 'CY': ['711', '712', '713', '733'], + 'CS': ['544', '568', '589'], + 'CK': ['353', '627'], 'CN': ['502', '594'], 'CP': ['043', '048'], 'CU': ['550', '581'], + 'CT_3': ['245', '296'], 'C=': ['150', '178'], 'CD': ['011', '075'], + 'C4': ['066'], 'C7': ['077'], 'C8': ['074'], 'C9': ['072'], 'CX': ['510'], + 'C!': ['145B'], 'C*': ['500'], 'C+': ['700'], 'C_3': ['271'], + 'CC': ['045'], 'CF': ['044'], 'CG': ['049'], 'CT_4': ['160'], + 'Ca2+': ['412'], + 'Cl': ['123', '151', '226', '264'], + 'Cl-': ['401', '709'], + 'Cs+': ['410'], 'Cu2+': ['Cu2+'], 'Eu3+': ['705'], + 'F': ['164', '719', '721', '726', '728', '786', '956', '965'], + 'F-': ['400'], 'Fe2+': ['Fe2+'], 'Gd3+': ['706'], + 'HA': ['146', '316', '318', '389', '524', '525', '526', '529', '534', '535', '536', '540', '541', '546', '547', '554', '555', '556', '563', '564', '565', '569', '570', '576', '577', '578', '584', '585', '586', '597', '598', '599', '600', '601', '602', '613', '614', '615', '616', '617', '618', '619', '629', '630', '631', '638', '639', '640', '643', '653', '654', '655', '656', '715', '717', '740', '741', '746'], + 'HC': ['140', '144', '153', '156', '165', '176', '185', '190', '192', '194', '196', '255', '279', '282', '329', '330', '332', '344', '372', '374', '376', '392', '416', '419', '422', '426', '430', '432', '444', '449', '454', '456', '459', '462', '469', '477', '483', '485', '487', '702', '710', '759', '763', '777', '778', '779', '784', '911', '926', '930', '950', '958'], + 'H': ['004', '013', '041', '047', '128', '240', '241', '250', '254', '314', '325', '327', '339', '342', '343', '357', '358', '360', '367', '369', '383', '385', '387', '388', '428', '479', '481', '504', '513', '545', '553', '562', '596', '632', '744', '745', '909', '910'], + 'H3': ['021', '052', '055', '104', '105', '289', '290', '301', '304', '310', '941', '955'], + 'HO': ['024', '079', '155', '163', '168', '170', '172', '188', '270', '435'], + 'HS': ['033', '086', '087', '204', '205'], + 'HW': ['112', '114', '117', '119', '796'], + 'H4': ['345', '390'], 'H5': ['355', '359'], + 'He': ['130'], 'I': ['732'], 'I-': ['403'], 'K+': ['408'], 'Kr': ['098'], + 'LP': ['433', '797'], 'La3+': ['703'], 'Li+': ['404', '406'], + 'MCH3A': ['MCH3A'], 'MCH3B': ['MCH3B'], 'MNH2': ['MNH2'], 'MNH3': ['MNH3'], + 'MW': ['MW', '115'], 'Mg2+': ['411'], + 'NA': ['040', '046', '319', '321', '333', '354', '361', '377', '379', '503', '512', '542', '548', '557', '587', '628'], + 'NC': ['311', '335', '346', '348', '363', '520', '527', '530', '537', '603', '620', '622', '641', '646'], + 'N': ['003', '012', '094', '237', '238', '239', '249', '251', '265', '478', '480', '787'], + 'N3': ['020', '101', '102', '103', '286', '287', '288', '309', '427', '940', '953'], + 'N2': ['051', '054', '300', '303', '313', '341', '356', '368', '386', '743'], + 'NB': ['042', '352', '511', '549', '559', '573', '580', '626', '635'], + 'N*': ['319B', '333B', '354B', '377B'], + 'NT': ['127', '900', '901', '902'], + 'NZ': ['262', '424', '750', '753'], + 'NO': ['760', '767'], 'NY': ['749', '751'], + 'Na+': ['405', '407'], 'Nd3+': ['704'], 'Ne': ['129'], + 'OS': ['062', '108', '179', '180', '186', '395', '442', '447', '452', '467', '473', '566', '571', '579', '773'], + 'O': ['002', '059', '236', '248', '253', '326', '328', '340', '370', '384', '771', '788'], + 'OH': ['023', '078', '154', '162', '167', '169', '171', '187', '268', '420', '434'], + 'O2': ['018', '125', '272', '394', '441', '446', '451', '954'], + 'OW': ['111', '113', '116', '118', '795'], + 'O_2': ['278', '281', '466'], + 'OY': ['475', '494', '497'], + 'OL': ['120'], 'ON': ['761'], 'OU': ['437'], 'O_3': ['269'], + 'P': ['393', '440', '445', '450', '785'], + 'P+': ['781'], 'Rb+': ['409'], + 'S': ['035', '038', '084', '085', '124', '202', '203', '222', '633'], + 'SH': ['032', '082', '083', '200', '201', '417', '734'], + 'SI': ['SI'], 'SY': ['474'], 'SY2': ['493'], 'SZ': ['496'], 'Sr2+': ['413'], + 'Th4+': ['698'], 'U': ['436'], 'Xe': ['099'], 'Yb3+': ['707'], 'Zn2+': ['Zn2+']} + +# reverse dictOplsAtomType2OplsGmxCode +oplsCode2AtomTypeDict = {} +for k, v in list(dictOplsAtomType2OplsGmxCode.items()): + for code in v: + oplsCode2AtomTypeDict[code] = k +# if code in oplsCode2AtomTypeDict.keys(): +# oplsCode2AtomTypeDict[code].append(k) +# else: +# oplsCode2AtomTypeDict[code] = [k] + +# Cross dictAmbAtomType2AmbGmxCode with dictOplsAtomType2OplsGmxCode & add H1,HP,H2 +dictAtomTypeAmb2OplsGmxCode = {'H1': ['140', '1.00800'], 'HP': ['140', '1.00800'], 'H2': ['140', '1.00800']} +dictOplsMass = {'SY2': ['32.06000'], 'Zn2+': ['65.37000'], 'CQ': ['12.01100'], 'CP': ['12.01100'], 'Nd3+': ['144.24000'], 'Br-': ['79.90400'], 'Cu2+': ['63.54600'], 'Br': ['79.90400'], 'H': ['1.00800'], 'P': ['30.97376'], 'Sr2+': ['87.62000'], 'ON': ['15.99940'], 'OL': ['0.00000'], 'OH': ['15.99940'], 'OY': ['15.99940'], 'OW': ['15.99940'], 'OU': ['15.99940'], 'OS': ['15.99940'], 'Am3+': ['243.06000'], 'HS': ['1.00800'], 'HW': ['1.00800'], 'HO': ['1.00800'], 'HC': ['1.00800'], 'HA': ['1.00800'], 'O2': ['15.99940'], 'Ca2+': ['40.08000'], 'Th4+': ['232.04000'], 'He': ['4.00260'], 'C': ['12.01100'], 'Cs+': ['132.90540'], 'O': ['15.99940'], 'Gd3+': ['157.25000'], 'S': ['32.06000'], 'P+': ['30.97376'], 'La3+': ['138.91000'], 'H3': ['1.00800'], 'H4': ['1.00800'], 'MNH2': ['0.00000'], 'MW': ['0.00000'], 'NB': ['14.00670'], 'K+': ['39.09830'], 'Ne': ['20.17970'], 'Rb+': ['85.46780'], 'C+': ['12.01100'], 'C*': ['12.01100'], 'NO': ['14.00670'], 'CT_4': ['12.01100'], 'NA': ['14.00670'], 'C!': ['12.01100'], 'NC': ['14.00670'], 'NZ': ['14.00670'], 'CT_2': ['12.01100'], 'CT_3': ['12.01100'], 'NY': ['14.00670'], 'C9': ['14.02700'], 'C8': ['13.01900'], 'C=': ['12.01100'], 'Yb3+': ['173.04000'], 'C3': ['15.03500', '12.01100'], 'C2': ['14.02700'], 'C7': ['12.01100'], 'C4': ['16.04300'], 'CK': ['12.01100'], 'Cl-': ['35.45300'], 'N*': ['14.00670'], 'CH': ['13.01900'], 'CO': ['12.01100'], 'CN': ['12.01100'], 'CM': ['12.01100'], 'F': ['18.99840'], 'CC': ['12.01100'], 'CB': ['12.01100'], 'CA': ['12.01100'], 'CG': ['12.01100'], 'CF': ['12.01100'], 'N': ['14.00670'], 'CZ': ['12.01100'], 'CY': ['12.01100'], 'CX': ['12.01100'], 'Ac3+': ['227.03000'], 'CS': ['12.01100'], 'CR': ['12.01100'], 'N2': ['14.00670'], 'N3': ['14.00670'], 'CW': ['12.01100'], 'CV': ['12.01100'], 'CU': ['12.01100'], 'CT': ['12.01100'], 'SZ': ['32.06000'], 'SY': ['32.06000'], 'Cl': ['35.45300'], 'NT': ['14.00670'], 'O_2': ['15.99940'], 'Xe': ['131.29300'], 'SI': ['28.08000'], 'SH': ['32.06000'], 'Eu3+': ['151.96000'], 'F-': ['18.99840'], 'MNH3': ['0.00000'], 'H5': ['1.00800'], 'C_3': ['12.01100'], 'C_2': ['12.01100'], 'I-': ['126.90450'], 'LP': ['0.00000'], 'I': ['126.90450'], 'Na+': ['22.98977'], 'Li+': ['6.94100'], 'U': ['0.00000'], 'MCH3A': ['0.00000'], 'MCH3B': ['0.00000'], 'CD': ['13.01900', '12.01100'], 'O_3': ['15.99940'], 'Kr': ['83.79800'], 'Fe2+': ['55.84700'], 'Ar': ['39.94800'], 'Mg2+': ['24.30500'], 'Ba2+': ['137.33000']} +for ambKey in dictAmbAtomType2AmbGmxCode: + if ambKey in dictOplsAtomType2OplsGmxCode: + dictAtomTypeAmb2OplsGmxCode[ambKey] = dictOplsAtomType2OplsGmxCode[ambKey] + list(dictOplsMass[ambKey]) + +# learnt from 22 residues test. +dictAtomTypeAmb2OplsGmxCode = {'HS': ['204', '1.008'], 'HP': ['140', '1.008'], 'HO': ['155', '168', '1.008'], 'HC': ['140', '1.008'], 'HA': ['146', '1.008'], 'O2': ['272', '15.9994'], 'C*': ['500', '12.011'], 'NA': ['503', '512', '14.0067'], 'NB': ['511', '14.0067'], 'CB': ['501', '12.011'], 'C': ['235', '271', '12.011'], 'CN': ['502', '12.011'], 'CM': ['302', '12.011'], 'CC': ['507', '508', '510', '12.011'], 'H': ['240', '241', '290', '301', '304', '310', '504', '513', '1.008'], 'CA': ['145', '166', '12.011'], 'O': ['236', '15.9994'], 'N': ['237', '238', '239', '14.0067'], 'S': ['202', '32.06'], 'CR': ['506', '509', '12.011'], 'N2': ['300', '303', '14.0067'], 'N3': ['287', '309', '14.0067'], 'CW': ['508', '510', '514', '12.011'], 'CV': ['507', '12.011'], 'CT': ['135', '136', '137', '149', '157', '158', '206', '209', '210', '223B', '224B', '245', '246', '274', '283', '284', '285', '292', '292B', '293B', '296', '307', '308', '505', '12.011'], 'OH': ['154', '167', '15.9994'], 'H1': ['140', '1.008'], 'H4': ['146', '1.008'], 'H5': ['146', '1.008'], 'SH': ['200', '32.06']} + +# learnt from 22 residues test. +dictAtomTypeGaff2OplsGmxCode = {'cc': ['500', '506', '507', '508', '514', '12.011'], 'ca': ['145', '166', '501', '502', '12.011'], 'h1': ['140', '1.008'], 'h4': ['146', '1.008'], 'h5': ['146', '1.008'], 'cz': ['302', '12.011'], 'c2': ['509', '510', '12.011'], 'nh': ['300', '303', '14.0067'], 'ha': ['146', '1.008'], 'na': ['503', '512', '14.0067'], 'nc': ['511', '14.0067'], 'nd': ['511', '14.0067'], 'hx': ['140', '1.008'], 'hs': ['204', '1.008'], 'hn': ['240', '241', '290', '301', '304', '310', '504', '513', '1.008'], 'ho': ['155', '168', '1.008'], 'c3': ['135', '136', '137', '149', '157', '158', '206', '209', '210', '223B', '224B', '245', '246', '274', '283', '284', '285', '292', '292B', '293B', '296', '307', '308', '505', '12.011'], 'hc': ['140', '1.008'], 'cd': ['500', '506', '507', '508', '514', '12.011'], 'c': ['235', '271', '12.011'], 'oh': ['154', '167', '15.9994'], 'ss': ['202', '32.06'], 'o': ['236', '272', '15.9994'], 'n': ['237', '238', '239', '14.0067'], 'sh': ['200', '32.06'], 'n4': ['287', '309', '14.0067']} + +# draft +atomTypeAmber2oplsDict = {'HS': ['HS'], 'HP': ['HC'], 'HO': ['HO'], 'HC': ['HC'], + 'HA': ['HA'], 'O2': ['O2'], 'C*': ['C*'], 'NA': ['NA'], + 'NB': ['NB'], 'CB': ['CB'], 'CN': ['CN'], 'CV': ['CV'], + 'CM': ['CA'], 'CA': ['CA'], 'CR': ['CR'], 'OH': ['OH'], + 'H1': ['HC'], 'H4': ['HA'], 'N2': ['N2'], 'N3': ['N3'], + 'H5': ['HA'], 'SH': ['SH'], 'N': ['N'], 'S': ['S'], 'O': ['O'], + 'C': ['C', 'C_3'], 'CW': ['CW', 'CX'], 'H': ['H', 'H3'], + 'CC': ['CX', 'CW', 'CV'], 'CT': ['CT', 'CT_2', 'CT_3']} + +# draft +a2oD = {'amber99_2': ['opls_235', 'opls_271'], + 'amber99_3': ['opls_302', 'opls_145'], + 'amber99_5': ['opls_507', 'opls_508', 'opls_510'], + 'amber99_11': ['opls_209', 'opls_158', 'opls_283', 'opls_223B', 'opls_293B', + 'opls_284', 'opls_292B', 'opls_274', 'opls_136', 'opls_135', + 'opls_292', 'opls_157', 'opls_206', 'opls_137', 'opls_505', + 'opls_224B', 'opls_307', 'opls_308', 'opls_210', 'opls_149'], + 'amber99_13': ['opls_514'], + 'amber99_14': ['opls_500'], + 'amber99_17': ['opls_504', 'opls_241', 'opls_240', 'opls_290', 'opls_301', + 'opls_310', 'opls_304', 'opls_513'], + 'amber99_18': ['opls_140'], + 'amber99_19': ['opls_140'], + 'amber99_22': ['opls_146'], + 'amber99_23': ['opls_146'], + 'amber99_25': ['opls_155'], + 'amber99_26': ['opls_204'], + 'amber99_28': ['opls_140'], + 'amber99_34': ['opls_238', 'opls_239', 'opls_237'], + 'amber99_35': ['opls_512', 'opls_503'], + 'amber99_36': ['opls_511'], + 'amber99_38': ['opls_300', 'opls_303'], + 'amber99_39': ['opls_309', 'opls_287'], + 'amber99_41': ['opls_236'], + 'amber99_43': ['opls_154'], + 'amber99_45': ['opls_272'], + 'amber99_47': ['opls_202'], + 'amber99_48': ['opls_200'], + } + +global pid +pid = 0 + +head = ""%s created by acpype (Rev: "" + svnRev + "") on %s\n"" + +date = datetime.now().ctime() + +usage = \ + """""" + acpype -i _file_ [-c _string_] [-n _int_] [-m _int_] [-a _string_] [-f] etc. or + acpype -p _prmtop_ -x _inpcrd_ [-d]"""""" + +epilog = \ + """""" + + output: assuming 'root' is the basename of either the top input file, + the 3-letter residue name or user defined (-b option) + root_bcc_gaff.mol2: final mol2 file with 'bcc' charges and 'gaff' atom type + root_AC.inpcrd : coord file for AMBER + root_AC.prmtop : topology and parameter file for AMBER + root_AC.lib : residue library file for AMBER + root_AC.frcmod : modified force field parameters + root_GMX.gro : coord file for GROMACS + root_GMX.top : topology file for GROMACS + root_GMX.itp : molecule unit topology and parameter file for GROMACS + root_GMX_OPLS.itp : OPLS/AA mol unit topol & par file for GROMACS (experimental!) + em.mdp, md.mdp : run parameters file for GROMACS + root_NEW.pdb : final pdb file generated by ACPYPE + root_CNS.top : topology file for CNS/XPLOR + root_CNS.par : parameter file for CNS/XPLOR + root_CNS.inp : run parameters file for CNS/XPLOR + root_CHARMM.rtf : topology file for CHARMM + root_CHARMM.prm : parameter file for CHARMM + root_CHARMM.inp : run parameters file for CHARMM"""""" + +SLEAP_TEMPLATE = \ + """""" +source %(leapAmberFile)s +source %(leapGaffFile)s +set default fastbld on +#set default disulfide auto +%(res)s = loadpdb %(baseOrg)s.pdb +#check %(res)s +saveamberparm %(res)s %(acBase)s.prmtop %(acBase)s.inpcrd +saveoff %(res)s %(acBase)s.lib +quit +"""""" + +TLEAP_TEMPLATE = \ + """""" +verbosity 1 +source %(leapAmberFile)s +source %(leapGaffFile)s +mods = loadamberparams %(acBase)s.frcmod +%(res)s = loadmol2 %(acMol2FileName)s +check %(res)s +saveamberparm %(res)s %(acBase)s.prmtop %(acBase)s.inpcrd +saveoff %(res)s %(acBase)s.lib +quit +"""""" + + +def dotproduct(aa, bb): + return sum((a * b) for a, b in zip(aa, bb)) + + +def crosproduct(a, b): + c = [a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0]] + return c + + +def length(v): + return math.sqrt(dotproduct(v, v)) + + +def vec_sub(aa, bb): + return [a - b for a, b in zip(aa, bb)] + + +def imprDihAngle(a, b, c, d): + ba = vec_sub(a, b) + bc = vec_sub(c, b) + cb = vec_sub(b, c) + cd = vec_sub(d, c) + n1 = crosproduct(ba, bc) + n2 = crosproduct(cb, cd) + angle = math.acos(dotproduct(n1, n2) / (length(n1) * length(n2))) * 180 / Pi + cp = crosproduct(n1, n2) + if (dotproduct(cp, bc) < 0): + angle = -1 * angle + return angle + + +def invalidArgs(text=None): + if text: + print('ERROR: ' + text) + sys.exit(1) + +# verNum = string.split(sys.version)[0] +verNum = re.sub('[^0-9\.]', '', sys.version.split()[0]) +version = verNum.split('.') # string.split(verNum, ""."") +verList = list(map(int, version)) +if verList < [2, 6, 0]: + invalidArgs(text=""Python version %s\n Sorry, you need python 2.6 or higher"" % verNum) + +try: + set() +except NameError: + from sets import Set as set # @UnresolvedImport + + +def elapsedTime(seconds, suffixes=['y', 'w', 'd', 'h', 'm', 's'], add_s=False, separator=' '): + """""" + Takes an amount of seconds and turns it into a human-readable amount of time. + """""" + # the formatted time string to be returned + time = [] + + # the pieces of time to iterate over (days, hours, minutes, etc) + # - the first piece in each tuple is the suffix (d, h, w) + # - the second piece is the length in seconds (a day is 60s * 60m * 24h) + parts = [(suffixes[0], 60 * 60 * 24 * 7 * 52), + (suffixes[1], 60 * 60 * 24 * 7), + (suffixes[2], 60 * 60 * 24), + (suffixes[3], 60 * 60), + (suffixes[4], 60), + (suffixes[5], 1)] + + # for each time piece, grab the value and remaining seconds, and add it to + # the time string + for suffix, length in parts: + value = seconds // length + if value > 0: + seconds = seconds % length + time.append('%s%s' % (str(value), + (suffix, (suffix, suffix + 's')[value > 1])[add_s])) + if seconds < 1: + break + + return separator.join(time) + + +def splitBlock(dat): + '''split a amber parm dat file in blocks + 0 = mass, 1 = extra + bond, 2 = angle, 3 = dihedral, 4 = improp, 5 = hbond + 6 = equiv nbon, 7 = nbon, 8 = END, 9 = etc. + ''' + dict_ = {} + count = 0 + for line in dat: + line = line.rstrip() + if count in dict_: + dict_[count].append(line) + else: + dict_[count] = [line] + if not line: + count += 1 + return dict_ + + +def getParCode(line): + key = line.replace(' -', '-').replace('- ', '-').split()[0] + return key + + +def parseFrcmod(lista): + heads = ['MASS', 'BOND', 'ANGL', 'DIHE', 'IMPR', 'HBON', 'NONB'] + dict_ = {} + for line in lista[1:]: + line = line.strip() + if line[:4] in heads: + head = line[:4] + dict_[head] = [] + dd = {} + continue + elif line: + key = line.replace(' -', '-').replace('- ', '-').split()[0] + if key in dd: + if not dd[key].count(line): + dd[key].append(line) + else: + dd[key] = [line] + dict_[head] = dd + for k in dict_.keys(): + if not dict_[k]: + dict_.pop(k) + return dict_ + + +def parmMerge(fdat1, fdat2, frcmod=False): + '''merge two amber parm dat/frcmod files and save in /tmp''' + name1 = os.path.basename(fdat1).split('.dat')[0] + if frcmod: + name2 = os.path.basename(fdat2).split('.')[1] + else: + name2 = os.path.basename(fdat2).split('.dat')[0] + mname = '/tmp/' + name1 + name2 + '.dat' + mdatFile = open(mname, 'w') + mdat = ['merged %s %s' % (name1, name2)] + + # if os.path.exists(mname): return mname + dat1 = splitBlock(open(fdat1).readlines()) + + if frcmod: + dHeads = {'MASS': 0, 'BOND': 1, 'ANGL': 2, 'DIHE': 3, 'IMPR': 4, 'HBON': 5, 'NONB': 7} + dat2 = parseFrcmod(open(fdat2).readlines()) # dict + for k in dat2: + for parEntry in dat2[k]: + idFirst = None + for line in dat1[dHeads[k]][:]: + if line: + key = line.replace(' -', '-').replace('- ', '-').split()[0] + if key == parEntry: + if not idFirst: + idFirst = dat1[dHeads[k]].index(line) + dat1[dHeads[k]].remove(line) + rev = dat2[k][parEntry][:] + rev.reverse() + if idFirst is None: + idFirst = 0 + for ll in rev: + if dHeads[k] in [0, 1, 7]: # MASS has title in index 0 and so BOND, NONB + dat1[dHeads[k]].insert(idFirst + 1, ll) + else: + dat1[dHeads[k]].insert(idFirst, ll) + dat1[0][0] = mdat[0] + for k in dat1: + for line in dat1[k]: + mdatFile.write(line + '\n') + return mname + + dat2 = splitBlock(open(fdat2).readlines()) + for k in dat1.keys()[:8]: + if k == 0: + lines = dat1[k][1:-1] + dat2[k][1:-1] + [''] + for line in lines: + mdat.append(line) + if k == 1: + for i in dat1[k]: + if '-' in i: + id1 = dat1[k].index(i) + break + for j in dat2[k]: + if '-' in j: + id2 = dat2[k].index(j) + break + l1 = dat1[k][:id1] + l2 = dat2[k][:id2] + line = '' + for item in l1 + l2: + line += item.strip() + ' ' + mdat.append(line) + lines = dat1[k][id1:-1] + dat2[k][id2:-1] + [''] + for line in lines: + mdat.append(line) + if k in [2, 3, 4, 5, 6]: # angles, p dih, imp dih + lines = dat1[k][:-1] + dat2[k][:-1] + [''] + for line in lines: + mdat.append(line) + if k == 7: + lines = dat1[k][:-1] + dat2[k][1:-1] + [''] + for line in lines: + mdat.append(line) + for k in dat1.keys()[8:]: + for line in dat1[k]: + mdat.append(line) + for k in dat2.keys()[9:]: + for line in dat2[k]: + mdat.append(line) + for line in mdat: + mdatFile.write(line + '\n') + mdatFile.close() + + return mname + + +def _getoutput(cmd): + '''to simulate commands.getoutput in order to work with python 2.6 up to 3.x''' + out = sub.Popen(cmd, shell=True, stderr=sub.STDOUT, stdout=sub.PIPE).communicate()[0][:-1] + try: + o = str(out.decode()) + except: + o = str(out) + return o + + +class AbstractTopol(object): + + """""" + Super class to build topologies + """""" + + def __init__(self): + if self.__class__ is AbstractTopol: + raise TypeError(""Attempt to create istance of abstract class AbstractTopol"") + + def printDebug(self, text=''): + if self.debug: + print('DEBUG: %s' % text) + + def printWarn(self, text=''): + if self.verbose: + print('WARNING: %s' % text) + + def printError(self, text=''): + if self.verbose: + print('ERROR: %s' % text) + + def printMess(self, text=''): + if self.verbose: + print('==> %s' % text) + + def printQuoted(self, text=''): + if self.verbose: + print(10 * '+' + 'start_quote' + 59 * '+') + print(text) + print(10 * '+' + 'end_quote' + 61 * '+') + + def guessCharge(self): + """""" + Guess the charge of a system based on antechamber + Returns None in case of error + """""" + done = False + error = False + charge = self.chargeVal + localDir = os.path.abspath('.') + if not os.path.exists(self.tmpDir): + os.mkdir(self.tmpDir) + if not os.path.exists(os.path.join(self.tmpDir, self.inputFile)): + copy2(self.absInputFile, self.tmpDir) + os.chdir(self.tmpDir) + + if self.chargeType == 'user': + if self.ext == '.mol2': + self.printMess(""Reading user's charges from mol2 file..."") + charge = self.readMol2TotalCharge(self.inputFile) + done = True + else: + self.printWarn(""cannot read charges from a PDB file"") + self.printWarn(""using now 'bcc' method for charge"") + + if self.chargeVal is None and not done: + self.printWarn(""no charge value given, trying to guess one..."") + mol2FileForGuessCharge = self.inputFile + if self.ext == "".pdb"": + cmd = '%s -ipdb %s -omol2 %s.mol2' % (self.babelExe, self.inputFile, + self.baseName) + self.printDebug(""guessCharge: "" + cmd) + out = _getoutput(cmd) + self.printDebug(out) + mol2FileForGuessCharge = os.path.abspath(self.baseName + "".mol2"") + in_mol = 'mol2' + else: + in_mol = self.ext[1:] + if in_mol == 'mol': + in_mol = 'mdl' + + cmd = '%s -i %s -fi %s -o tmp -fo mol2 -c gas -pf y' % \ + (self.acExe, mol2FileForGuessCharge, in_mol) + + if self.debug: + self.printMess(""Debugging..."") + cmd = cmd.replace('-pf y', '-pf n') + print(cmd) + + log = _getoutput(cmd).strip() + + if os.path.exists('tmp'): + charge = self.readMol2TotalCharge('tmp') + else: + try: + charge = float(log.strip().split('equal to the total charge (')[-1].split(') based on Gasteiger atom type, exit')[0]) + except: + error = True + + if error: + self.printError(""guessCharge failed"") + os.chdir(localDir) + self.printQuoted(log) + self.printMess(""Trying with net charge = 0 ..."") +# self.chargeVal = 0 + return None + charge = float(charge) + charge2 = int(round(charge)) + drift = abs(charge2 - charge) + self.printDebug(""Net charge drift '%3.6f'"" % drift) + if drift > diffTol: + self.printError(""Net charge drift '%3.5f' bigger than tolerance '%3.5f'"" % (drift, diffTol)) + if not self.force: + sys.exit(1) + self.chargeVal = str(charge2) + self.printMess(""... charge set to %i"" % charge2) + os.chdir(localDir) + + def setResNameCheckCoords(self): + """"""Set a 3 letter residue name + and check coords duplication + """""" + exit_ = False + localDir = os.path.abspath('.') + if not os.path.exists(self.tmpDir): + os.mkdir(self.tmpDir) + # if not os.path.exists(os.path.join(tmpDir, self.inputFile)): + copy2(self.absInputFile, self.tmpDir) + os.chdir(self.tmpDir) + + exten = self.ext[1:] + if self.ext == '.pdb': + tmpFile = open(self.inputFile, 'r') + else: + if exten == 'mol': + exten = 'mdl' + cmd = '%s -i %s -fi %s -o tmp -fo ac -pf y' % \ + (self.acExe, self.inputFile, exten) + self.printDebug(cmd) + out = _getoutput(cmd) + if not out.isspace(): + self.printDebug(out) + try: + tmpFile = open('tmp', 'r') + except: + rmtree(self.tmpDir) + raise + + tmpData = tmpFile.readlines() + residues = set() + coords = {} + for line in tmpData: + if 'ATOM ' in line or 'HETATM' in line: + residues.add(line[17:20]) + at = line[0:17] + cs = line[30:54] + if cs in coords: + coords[cs].append(at) + else: + coords[cs] = [at] + # self.printDebug(coords) + + if len(residues) > 1: + self.printError(""more than one residue detected '%s'"" % str(residues)) + self.printError(""verify your input file '%s'. Aborting ..."" % self.inputFile) + sys.exit(1) + + dups = """" + shortd = """" + longd = """" + longSet = set() + id_ = 0 + items = list(coords.items()) + l = len(items) + for item in items: + id_ += 1 + if len(item[1]) > 1: # if True means atoms with same coordinates + for i in item[1]: + dups += ""%s %s\n"" % (i, item[0]) + +# for i in xrange(0,len(data),f): +# fdata += (data[i:i+f])+' ' + + for id2 in range(id_, l): + item2 = items[id2] + c1 = list(map(float, [item[0][i:i + 8] for i in range(0, 24, 8)])) + c2 = list(map(float, [item2[0][i:i + 8] for i in range(0, 24, 8)])) + dist2 = self.distance(c1, c2) + if dist2 < minDist2: + dist = math.sqrt(dist2) + shortd += ""%8.5f %s %s\n"" % (dist, item[1], item2[1]) + if dist2 < maxDist2: # and not longOK: + longSet.add(str(item[1])) + longSet.add(str(item2[1])) + if str(item[1]) not in longSet and l > 1: + longd += ""%s\n"" % item[1] + + if dups: + self.printError(""Atoms with same coordinates in '%s'!"" % self.inputFile) + self.printQuoted(dups[:-1]) + exit_ = True + + if shortd: + self.printError(""Atoms TOO close (< %s Ang.)"" % minDist) + self.printQuoted(""Dist (Ang.) Atoms\n"" + shortd[:-1]) + exit_ = True + + if longd: + self.printError(""Atoms TOO alone (> %s Ang.)"" % maxDist) + self.printQuoted(longd[:-1]) + exit_ = True + + if exit_: + if self.force: + self.printWarn(""You chose to proceed anyway with '-f' option. GOOD LUCK!"") + else: + self.printError(""Use '-f' option if you want to proceed anyway. Aborting ..."") + rmtree(self.tmpDir) + sys.exit(1) + + resname = list(residues)[0].strip() + newresname = resname + + # To avoid resname likes: 001 (all numbers), 1e2 (sci number), ADD : reserved terms for leap + leapWords = ['_cmd_options_', '_types_', 'add', 'addAtomTypes', 'addIons', + 'addIons2', 'addPath', 'addPdbAtomMap', 'addPdbResMap', 'alias', + 'alignAxes', 'bond', 'bondByDistance', 'center', 'charge', + 'check', 'clearPdbAtomMap', 'clearPdbResMap', 'clearVariables', + 'combine', 'copy', 'createAtom', 'createParmset', 'createResidue', + 'createUnit', 'crossLink', 'debugOff', 'debugOn', 'debugStatus', + 'deleteBond', 'deleteOffLibEntry', 'deleteRestraint', 'desc', + 'deSelect', 'displayPdbAtomMap', 'displayPdbResMap', 'edit', + 'flip', 'groupSelectedAtoms', 'help', 'impose', 'list', 'listOff', + 'loadAmberParams', 'loadAmberPrep', 'loadMol2', 'loadOff', + 'loadPdb', 'loadPdbUsingSeq', 'logFile', 'matchVariables', + 'measureGeom', 'quit', 'relax', 'remove', 'restrainAngle', + 'restrainBond', 'restrainTorsion', 'saveAmberParm', + 'saveAmberParmPert', 'saveAmberParmPol', 'saveAmberParmPolPert', + 'saveAmberPrep', 'saveMol2', 'saveOff', 'saveOffParm', 'savePdb', + 'scaleCharges', 'select', 'sequence', 'set', 'setBox', 'solvateBox', + 'solvateCap', 'solvateDontClip', 'solvateOct', 'solvateShell', + 'source', 'transform', 'translate', 'verbosity', 'zMatrix'] + isLeapWord = False + for word in leapWords: + if resname.upper().startswith(word.upper()): + self.printDebug(""Residue name is a reserved word: '%s'"" % word.upper()) + isLeapWord = True + try: + float(resname) + self.printDebug(""Residue name is a 'number': '%s'"" % resname) + isNumber = True + except ValueError: + isNumber = False + + if resname[0].isdigit() or isNumber or isLeapWord: + newresname = 'R' + resname + if not resname.isalnum(): + newresname = 'MOL' + if newresname != resname: + self.printWarn(""In %s.lib, residue name will be '%s' instead of '%s' elsewhere"" + % (self.acBaseName, newresname, resname)) + + self.resName = newresname + + os.chdir(localDir) + self.printDebug(""setResNameCheckCoords done"") + + def distance(self, c1, c2): + # print c1, c2 + dist2 = (c1[0] - c2[0]) ** 2 + (c1[1] - c2[1]) ** 2 + (c1[0] - c2[0]) ** 2 + \ + (c1[2] - c2[2]) ** 2 + # dist2 = math.sqrt(dist2) + return dist2 + + def readMol2TotalCharge(self, mol2File): + """"""Reads the charges in given mol2 file and returns the total + """""" + charge = 0.0 + ll = [] + cmd = '%s -i %s -fi mol2 -o tmp -fo mol2 -c wc -cf tmp.crg -pf y' % \ + (self.acExe, mol2File) + if self.debug: + self.printMess(""Debugging..."") + cmd = cmd.replace('-pf y', '-pf n') + + self.printDebug(cmd) + + log = _getoutput(cmd) + + if os.path.exists('tmp.crg'): + tmpFile = open('tmp.crg', 'r') + tmpData = tmpFile.readlines() + for line in tmpData: + ll += line.split() + charge = sum(map(float, ll)) + if not log.isspace() and self.debug: + self.printQuoted(log) + + self.printDebug(""readMol2TotalCharge: "" + str(charge)) + + return charge + + def execAntechamber(self, chargeType=None, atomType=None): + """""" AmaberTools 1.3 + To call Antechamber and execute it + +Usage: antechamber -i input file name + -fi input file format + -o output file name + -fo output file format + -c charge method + -cf charge file name + -nc net molecular charge (int) + -a additional file name + -fa additional file format + -ao additional file operation + crd only read in coordinate + crg only read in charge + name only read in atom name + type only read in atom type + bond only read in bond type + -m multiplicity (2S+1), default is 1 + -rn residue name, overrides input file, default is MOL + -rf residue toplogy file name in prep input file, + default is molecule.res + -ch check file name for gaussian, default is molecule + -ek mopac or sqm keyword, inside quotes + -gk gaussian keyword, inside quotes + -df am1-bcc flag, 2 - use sqm(default); 0 - use mopac + -at atom type, can be gaff (default), amber, bcc and sybyl + -du fix duplicate atom names: yes(y)[default] or no(n) + -j atom type and bond type prediction index, default is 4 + 0 no assignment + 1 atom type + 2 full bond types + 3 part bond types + 4 atom and full bond type + 5 atom and part bond type + -s status information: 0(brief), 1(default) or 2(verbose) + -pf remove intermediate files: yes(y) or no(n)[default] + -i -o -fi and -fo must appear; others are optional + + List of the File Formats + + file format type abbre. index | file format type abbre. index + --------------------------------------------------------------- + Antechamber ac 1 | Sybyl Mol2 mol2 2 + PDB pdb 3 | Modified PDB mpdb 4 + AMBER PREP (int) prepi 5 | AMBER PREP (car) prepc 6 + Gaussian Z-Matrix gzmat 7 | Gaussian Cartesian gcrt 8 + Mopac Internal mopint 9 | Mopac Cartesian mopcrt 10 + Gaussian Output gout 11 | Mopac Output mopout 12 + Alchemy alc 13 | CSD csd 14 + MDL mdl 15 | Hyper hin 16 + AMBER Restart rst 17 | Jaguar Cartesian jcrt 18 + Jaguar Z-Matrix jzmat 19 | Jaguar Output jout 20 + Divcon Input divcrt 21 | Divcon Output divout 22 + Charmm charmm 23 | SQM Output sqmout 24 + -------------------------------------------------------------- + + AMBER restart file can only be read in as additional file. + + List of the Charge Methods + + charge method abbre. index | charge method abbre. index + ---------------------------------------------------------------- + RESP resp 1 | AM1-BCC bcc 2 + CM1 cm1 3 | CM2 cm2 4 + ESP (Kollman) esp 5 | Mulliken mul 6 + Gasteiger gas 7 | Read in charge rc 8 + Write out charge wc 9 | Delete Charge dc 10 + ---------------------------------------------------------------- +a """""" + global pid + + self.printMess(""Executing Antechamber..."") + + self.makeDir() + + ct = chargeType or self.chargeType + at = atomType or self.atomType + + if ct == 'user': + ct = '' + else: + ct = '-c %s' % ct + + exten = self.ext[1:] + if exten == 'mol': + exten = 'mdl' + + cmd = '%s -i %s -fi %s -o %s -fo mol2 %s -nc %s -m %s -s 2 -df %i -at\ + %s -pf y %s' % (self.acExe, self.inputFile, exten, self.acMol2FileName, + ct, self.chargeVal, self.multiplicity, self.qFlag, at, + self.ekFlag) + + if self.debug: + self.printMess(""Debugging..."") + cmd = cmd.replace('-pf y', '-pf n') + + self.printDebug(cmd) + + if os.path.exists(self.acMol2FileName) and not self.force: + self.printMess(""AC output file present... doing nothing"") + else: + try: + os.remove(self.acMol2FileName) + except: + pass + signal.signal(signal.SIGALRM, self.signal_handler) + signal.alarm(self.timeTol) + p = sub.Popen(cmd, shell=True, stderr=sub.STDOUT, stdout=sub.PIPE) + pid = p.pid + + out = str(p.communicate()[0].decode()) # p.stdout.read() + self.acLog = out + + if os.path.exists(self.acMol2FileName): + self.printMess(""* Antechamber OK *"") + else: + self.printQuoted(self.acLog) + return True + + def signal_handler(self, _signum, _frame): # , pid = 0): + global pid + pids = self.job_pids_family(pid) + self.printDebug(""PID: %s, PIDS: %s"" % (pid, pids)) + self.printMess(""Timed out! Process %s killed, max exec time (%ss) exceeded"" + % (pids, self.timeTol)) + # os.system('kill -15 %s' % pids) + for i in pids.split(): + os.kill(int(i), 15) + raise Exception(""Semi-QM taking too long to finish... aborting!"") + + def job_pids_family(self, jpid): + '''INTERNAL: Return all job processes (PIDs)''' + pid = repr(jpid) + dict_pids = {} + pids = [pid] + cmd = ""ps -A -o uid,pid,ppid|grep %i"" % os.getuid() + out = _getoutput(cmd).split('\n') # getoutput(""ps -A -o uid,pid,ppid|grep %i"" % os.getuid()).split('\n') + for item in out: + vec = item.split() + dict_pids[vec[2]] = vec[1] + while 1: + try: + pid = dict_pids[pid] + pids.append(pid) + except KeyError: + break + return ' '.join(pids) + + def delOutputFiles(self): + delFiles = ['mopac.in', 'tleap.in', 'sleap.in', 'fixbo.log', + 'addhs.log', 'ac_tmp_ot.mol2', 'frcmod.ac_tmp', 'fragment.mol2', + self.tmpDir] # , 'divcon.pdb', 'mopac.pdb', 'mopac.out'] #'leap.log' + self.printMess(""Removing temporary files..."") + for file_ in delFiles: + file_ = os.path.join(self.absHomeDir, file_) + if os.path.exists(file_): + if os.path.isdir(file_): + rmtree(file_) + else: + os.remove(file_) + + def checkXyzAndTopFiles(self): + fileXyz = self.acXyzFileName + fileTop = self.acTopFileName + if os.path.exists(fileXyz) and os.path.exists(fileTop): + # self.acXyz = fileXyz + # self.acTop = fileTop + return True + return False + + def execSleap(self): + global pid + self.makeDir() + + if self.ext == '.mol2': + self.printWarn(""Sleap doesn't work with mol2 files yet..."") + return True + + if self.chargeType != 'bcc': + self.printWarn(""Sleap works only with bcc charge method"") + return True + + if self.atomType != 'gaff': + self.printWarn(""Sleap works only with gaff atom type"") + return True + + sleapScpt = SLEAP_TEMPLATE % self.acParDict + + fp = open('sleap.in', 'w') + fp.write(sleapScpt) + fp.close() + + cmd = '%s -f sleap.in' % self.sleapExe + + if self.checkXyzAndTopFiles() and not self.force: + self.printMess(""Topologies files already present... doing nothing"") + else: + try: + os.remove(self.acTopFileName) + os.remove(self.acXyzFileName) + except: + pass + self.printMess(""Executing Sleap..."") + self.printDebug(cmd) + + p = sub.Popen(cmd, shell=True, stderr=sub.STDOUT, stdout=sub.PIPE) + pid = p.pid + signal.signal(signal.SIGALRM, self.signal_handler) + signal.alarm(self.timeTol) + + out = str(p.communicate()[0].decode()) # p.stdout.read() + + self.sleapLog = out + self.checkLeapLog(self.sleapLog) + + if self.checkXyzAndTopFiles(): + self.printMess("" * Sleap OK *"") + else: + self.printQuoted(self.sleapLog) + return True + + def execTleap(self): + + fail = False + + self.makeDir() + + if self.ext == "".pdb"": + self.printMess('... converting pdb input file to mol2 input file') + if self.convertPdbToMol2(): + self.printError(""convertPdbToMol2 failed"") + + # print self.chargeVal + + if self.execAntechamber(): + self.printError(""Antechamber failed"") + fail = True + # sys.exit(1) + + if self.execParmchk(): + self.printError(""Parmchk failed"") + fail = True + # sys.exit(1) + + if fail: + return True + + tleapScpt = TLEAP_TEMPLATE % self.acParDict + + fp = open('tleap.in', 'w') + fp.write(tleapScpt) + fp.close() + + cmd = '%s -f tleap.in' % self.tleapExe + + if self.checkXyzAndTopFiles() and not self.force: + self.printMess(""Topologies files already present... doing nothing"") + else: + try: + os.remove(self.acTopFileName) + os.remove(self.acXyzFileName) + except: + pass + self.printMess(""Executing Tleap..."") + self.printDebug(cmd) + self.tleapLog = _getoutput(cmd) + self.checkLeapLog(self.tleapLog) + + if self.checkXyzAndTopFiles(): + self.printMess(""* Tleap OK *"") + else: + self.printQuoted(self.tleapLog) + return True + + def checkLeapLog(self, log): + log = log.splitlines(True) + check = '' + block = False + for line in log: + # print ""*""+line+""*"" + if ""Checking '"" in line: + # check += line + block = True + if ""Checking Unit."" in line: + block = False + if block: + check += line + self.printQuoted(check[:-1]) + + def locateDat(self, aFile): + '''locate a file pertinent to $AMBERHOME/dat/leap/parm/''' + amberhome = os.environ.get('AMBERHOME') + if amberhome: + aFileF = os.path.join(amberhome, 'dat/leap/parm', aFile) + if os.path.exists(aFileF): + return aFileF + aFileF = os.path.join(os.path.dirname(self.acExe), '../dat/leap/parm', aFile) + if os.path.exists(aFileF): + return aFileF + return None + + def execParmchk(self): + + self.makeDir() + cmd = '%s -i %s -f mol2 -o %s' % (self.parmchkExe, self.acMol2FileName, + self.acFrcmodFileName) + + if self.atomType == 'amber': + gaffFile = self.locateDat('gaff.dat') + parm99file = self.locateDat('parm99.dat') + frcmodff99SB = self.locateDat('frcmod.ff99SB') + # frcmodparmbsc0 = self.locateDat('frcmod.parmbsc0') + parm99gaffFile = parmMerge(parm99file, gaffFile) + parm99gaffff99SBFile = parmMerge(parm99gaffFile, frcmodff99SB, frcmod=True) + # parm99gaffff99SBparmbsc0File = parmMerge(parm99gaffff99SBFile, frcmodparmbsc0, frcmod = True) + # parm10file = self.locateDat('parm10.dat') # PARM99 + frcmod.ff99SB + frcmod.parmbsc0 in AmberTools 1.4 + + cmd += ' -p %s' % parm99gaffff99SBFile # Ignoring parm10.dat and BSC0 + + self.parmchkLog = _getoutput(cmd) + + self.printDebug(cmd) + + if os.path.exists(self.acFrcmodFileName): + check = self.checkFrcmod() + if check: + self.printWarn(""Couldn't determine all parameters:"") + self.printMess(""From file '%s'\n"" % self.acFrcmodFileName + check) + else: + self.printMess(""* Parmchk OK *"") + else: + self.printQuoted(self.parmchkLog) + return True + + def checkFrcmod(self): + check = """" + frcmodContent = open(self.acFrcmodFileName, 'r').readlines() + for line in frcmodContent: + if ""ATTN, need revision"" in line: + check += line + return check + + def convertPdbToMol2(self): + if self.ext == '.pdb': + if self.execBabel(): + self.printError(""convert pdb to mol2 via babel failed"") + return True + + def execBabel(self): + + self.makeDir() + + cmd = '%s -ipdb %s -omol2 %s.mol2' % (self.babelExe, self.inputFile, + self.baseName) + self.printDebug(cmd) + self.babelLog = _getoutput(cmd) + self.ext = '.mol2' + self.inputFile = self.baseName + self.ext + self.acParDict['ext'] = 'mol2' + if os.path.exists(self.inputFile): + self.printMess(""* Babel OK *"") + else: + self.printQuoted(self.babelLog) + return True + + def makeDir(self): + + os.chdir(self.rootDir) + self.absHomeDir = os.path.abspath(self.homeDir) + if not os.path.exists(self.homeDir): + os.mkdir(self.homeDir) + os.chdir(self.homeDir) + copy2(self.absInputFile, '.') + + return True + + def createACTopol(self): + """""" + If successful, Amber Top and Xyz files will be generated + """""" + # sleap = False + if self.engine == 'sleap': + if self.execSleap(): + self.printError(""Sleap failed"") + self.printMess(""... trying Tleap"") + if self.execTleap(): + self.printError(""Tleap failed"") + if self.engine == 'tleap': + if self.execTleap(): + self.printError(""Tleap failed"") + if self.extOld == '.pdb': + self.printMess(""... trying Sleap"") + self.ext = self.extOld + self.inputFile = self.baseName + self.ext + if self.execSleap(): + self.printError(""Sleap failed"") + if not self.debug: + self.delOutputFiles() + + def createMolTopol(self): + """""" + Create molTop obj + """""" + self.topFileData = open(self.acTopFileName, 'r').readlines() + self.molTopol = MolTopol(self, verbose=self.verbose, debug=self.debug, + gmx45=self.gmx45, disam=self.disam, direct=self.direct, + is_sorted=self.sorted, chiral=self.chiral) + if self.outTopols: + if 'cns' in self.outTopols: + self.molTopol.writeCnsTopolFiles() + if 'gmx' in self.outTopols: + self.molTopol.writeGromacsTopolFiles() + if 'charmm' in self.outTopols: + self.writeCharmmTopolFiles() + self.pickleSave() + + def pickleSave(self): + """""" + To restore: + from acpype import * + #import cPickle as pickle + import pickle + o = pickle.load(open('DDD.pkl','rb')) + NB: It fails to restore with ipython in Mac (Linux OK) + """""" + pklFile = self.baseName + "".pkl"" + dumpFlag = False + if not os.path.exists(pklFile): + mess = ""Writing pickle file %s"" % pklFile + dumpFlag = True + elif self.force: + mess = ""Overwriting pickle file %s"" % pklFile + dumpFlag = True + else: + mess = ""Pickle file %s already present... doing nothing"" % pklFile + self.printMess(mess) + if dumpFlag: + with open(pklFile, ""wb"") as f: # for python 2.6 or higher + # f = open(pklFile, ""wb"") + if verList[0] == 3: + pickle.dump(self, f, protocol=2, fix_imports=True) + else: + pickle.dump(self, f, protocol=2) + + def getFlagData(self, flag): + """""" + For a given acFileTop flag, return a list of the data related + """""" + block = False + tFlag = '%FLAG ' + flag + data = '' + + if len(self.topFileData) == 0: + raise Exception(""PRMTOP file empty?"") + + for rawLine in self.topFileData: + line = rawLine[:-1] + if tFlag in line: + block = True + continue + if block and '%FLAG ' in line: + break + if block: + if '%FORMAT' in line: + line = line.strip().strip('%FORMAT()').split('.')[0] + for c in line: + if c.isalpha(): + f = int(line.split(c)[1]) + break + continue + data += line + # data need format + sdata = [data[i:i + f].strip() for i in range(0, len(data), f)] + if '+' and '.' in data: # it's a float + ndata = list(map(float, sdata)) + elif flag != 'RESIDUE_LABEL': + try: # try if it's integer + ndata = list(map(int, sdata)) + except: # it's string + ndata = sdata + else: + ndata = sdata + if flag == 'AMBER_ATOM_TYPE': + nn = [] + ll = set() + prefixed = False + for ii in ndata: + prefixed = True + if ii[0].isdigit(): + ll.add(ii) + ii = 'A' + ii + nn.append(ii) + if prefixed: + self.printDebug(""GMX does not like atomtype starting with Digit"") + self.printDebug(""prefixing AtomType %s with 'A'."" % list(ll)) + ndata = nn + return ndata # a list + + def getResidueLabel(self): + """""" + Get a 3 capital letters code from acFileTop + Returns a list. + """""" + residueLabel = self.getFlagData('RESIDUE_LABEL') + residueLabel = list(map(str, residueLabel)) + if residueLabel[0] != residueLabel[0].upper(): + self.printWarn(""residue label '%s' in '%s' is not all UPPERCASE"" % + (residueLabel[0], self.inputFile)) + self.printWarn(""this may raise problem with some applications like CNS"") + self.residueLabel = residueLabel + + def getCoords(self): + """""" + For a given acFileXyz file, return a list of coords as: + [[x1,y1,z1],[x2,y2,z2], etc.] + """""" + if len(self.xyzFileData) == 0: + raise Exception(""INPCRD file empty?"") + data = '' + for rawLine in self.xyzFileData[2:]: + line = rawLine[:-1] + data += line + l = len(data) + ndata = list(map(float, [data[i:i + 12] for i in range(0, l, 12)])) + + gdata = [] + for i in range(0, len(ndata), 3): + gdata.append([ndata[i], ndata[i + 1], ndata[i + 2]]) + + self.printDebug(""getCoords done"") + + return gdata + + def getAtoms(self): + """""" + Set a list with all atoms objects build from dat in acFileTop + Set also if molTopol atom type system is gaff or amber + Set also list atomTypes + Set also resid + Set also molTopol total charge + """""" + atomNameList = self.getFlagData('ATOM_NAME') + atomTypeNameList = self.getFlagData('AMBER_ATOM_TYPE') + self._atomTypeNameList = atomTypeNameList + massList = self.getFlagData('MASS') + chargeList = self.getFlagData('CHARGE') +# totalCharge = sum(chargeList) +# self.printDebug('charge to be balanced: total %13.10f' % (totalCharge/qConv)) + + resIds = self.getFlagData('RESIDUE_POINTER') + [0] + # to guess the resId of the last residue before ion or water +# for resTemp in self.residueLabel: +# if resTemp in ionOrWaterResNameList: +# lastSoluteResId = self.residueLabel.index(resTemp) - 1 +# break + # print lastSoluteResId, self.residueLabel[lastSoluteResId] + # uniqAtomTypeId = self.getFlagData('ATOM_TYPE_INDEX') # for LJ +# balanceChargeList = self.balanceCharges(chargeList) + coords = self.getCoords() + ACOEFs, BCOEFs = self.getABCOEFs() + + atoms = [] + atomTypes = [] + tmpList = [] # a list with unique atom types + totalCharge = 0.0 + countRes = 0 + id_ = 0 + FirstNonSoluteId = None + for atomName in atomNameList: + if atomName != atomName.upper(): + self.printDebug(""atom name '%s' HAS to be all UPPERCASE... Applying this here."" % + atomName) + atomName = atomName.upper() + atomTypeName = atomTypeNameList[id_] + if id_ + 1 == resIds[countRes]: + resid = countRes # self.residueLabel[countRes] + countRes += 1 + resName = self.residueLabel[resid] + if resName in ionOrSolResNameList and not FirstNonSoluteId: + FirstNonSoluteId = id_ + # print id_, resid, resName + mass = massList[id_] + # charge = balanceChargeList[id_] + charge = chargeList[id_] + chargeConverted = charge / qConv + totalCharge += charge + coord = coords[id_] + ACOEF = ACOEFs[id_] + BCOEF = BCOEFs[id_] + atomType = AtomType(atomTypeName, mass, ACOEF, BCOEF) + if atomTypeName not in tmpList: + tmpList.append(atomTypeName) + atomTypes.append(atomType) + atom = Atom(atomName, atomType, id_ + 1, resid, mass, chargeConverted, coord) + atoms.append(atom) + id_ += 1 + + balanceChargeList, balanceValue, balanceIds = self.balanceCharges(chargeList, FirstNonSoluteId) + + for id_ in balanceIds: + atoms[id_].charge = balanceValue / qConv + # self.printDebug(""atom ids and balanced charges: %s, %3f10"" % (balanceIds, balanceValue/qConv)) + + if atomTypeName[0].islower(): + self.atomTypeSystem = 'gaff' + else: + self.atomTypeSystem = 'amber' + + self.printDebug('Balanced TotalCharge %13.10f' % float(sum(balanceChargeList) / qConv)) + self.totalCharge = int(totalCharge) + + self.atoms = atoms + self.atomTypes = atomTypes + + self.pbc = None + if len(coords) == len(atoms) + 2: + self.pbc = [coords[-2], coords[-1]] + self.printDebug(""PBC = '%s"" % self.pbc) + self.printDebug(""getAtoms done"") + + def getBonds(self): + uniqKbList = self.getFlagData('BOND_FORCE_CONSTANT') + uniqReqList = self.getFlagData('BOND_EQUIL_VALUE') + bondCodeHList = self.getFlagData('BONDS_INC_HYDROGEN') + bondCodeNonHList = self.getFlagData('BONDS_WITHOUT_HYDROGEN') + bondCodeList = bondCodeHList + bondCodeNonHList + bonds = [] + for i in range(0, len(bondCodeList), 3): + idAtom1 = bondCodeList[i] // 3 # remember python starts with id 0 + idAtom2 = bondCodeList[i + 1] // 3 + bondTypeId = bondCodeList[i + 2] - 1 + atom1 = self.atoms[idAtom1] + atom2 = self.atoms[idAtom2] + kb = uniqKbList[bondTypeId] + req = uniqReqList[bondTypeId] + atoms = [atom1, atom2] + bond = Bond(atoms, kb, req) + bonds.append(bond) + self.bonds = bonds + self.printDebug(""getBonds done"") + + def getAngles(self): + uniqKtList = self.getFlagData('ANGLE_FORCE_CONSTANT') + uniqTeqList = self.getFlagData('ANGLE_EQUIL_VALUE') + # for list below, true atom number = index/3 + 1 + angleCodeHList = self.getFlagData('ANGLES_INC_HYDROGEN') + angleCodeNonHList = self.getFlagData('ANGLES_WITHOUT_HYDROGEN') + angleCodeList = angleCodeHList + angleCodeNonHList + angles = [] + for i in range(0, len(angleCodeList), 4): + idAtom1 = angleCodeList[i] // 3 # remember python starts with id 0 + idAtom2 = angleCodeList[i + 1] // 3 + idAtom3 = angleCodeList[i + 2] // 3 + angleTypeId = angleCodeList[i + 3] - 1 + atom1 = self.atoms[idAtom1] + atom2 = self.atoms[idAtom2] + atom3 = self.atoms[idAtom3] + kt = uniqKtList[angleTypeId] + teq = uniqTeqList[angleTypeId] # angle given in rad in prmtop + atoms = [atom1, atom2, atom3] + angle = Angle(atoms, kt, teq) + angles.append(angle) + self.angles = angles + self.printDebug(""getAngles done"") + + def getDihedrals(self): + """""" + Get dihedrals (proper and imp), condensed list of prop dih and + atomPairs + """""" + uniqKpList = self.getFlagData('DIHEDRAL_FORCE_CONSTANT') + uniqPeriodList = self.getFlagData('DIHEDRAL_PERIODICITY') + uniqPhaseList = self.getFlagData('DIHEDRAL_PHASE') + # for list below, true atom number = abs(index)/3 + 1 + dihCodeHList = self.getFlagData('DIHEDRALS_INC_HYDROGEN') + dihCodeNonHList = self.getFlagData('DIHEDRALS_WITHOUT_HYDROGEN') + dihCodeList = dihCodeHList + dihCodeNonHList + properDih = [] + improperDih = [] + condProperDih = [] # list of dihedrals condensed by the same quartet + # atomPairs = [] + atomPairs = set() + for i in range(0, len(dihCodeList), 5): + idAtom1 = dihCodeList[i] // 3 # remember python starts with id 0 + idAtom2 = dihCodeList[i + 1] // 3 + # 3 and 4 indexes can be negative: if id3 < 0, end group interations + # in amber are to be ignored; if id4 < 0, dihedral is improper + idAtom3raw = dihCodeList[i + 2] // 3 # can be negative -> exclude from 1-4vdw + idAtom4raw = dihCodeList[i + 3] // 3 # can be negative -> Improper + idAtom3 = abs(idAtom3raw) + idAtom4 = abs(idAtom4raw) + dihTypeId = dihCodeList[i + 4] - 1 + atom1 = self.atoms[idAtom1] + atom2 = self.atoms[idAtom2] + atom3 = self.atoms[idAtom3] + atom4 = self.atoms[idAtom4] + kPhi = uniqKpList[dihTypeId] # already divided by IDIVF + period = int(uniqPeriodList[dihTypeId]) # integer + phase = uniqPhaseList[dihTypeId] # angle given in rad in prmtop + if phase == kPhi == 0: + period = 0 # period is set to 0 + atoms = [atom1, atom2, atom3, atom4] + dihedral = Dihedral(atoms, kPhi, period, phase) + if idAtom4raw > 0: + try: + atomsPrev = properDih[-1].atoms + except: + atomsPrev = [] + properDih.append(dihedral) + if idAtom3raw < 0 and atomsPrev == atoms: + condProperDih[-1].append(dihedral) + else: + condProperDih.append([dihedral]) + pair = (atom1, atom4) + # if atomPairs.count(pair) == 0 and idAtom3raw > 0: + if idAtom3raw > 0: + atomPairs.add(pair) + else: + improperDih.append(dihedral) + try: + atomPairs = sorted(atomPairs) + except: + pass + self.properDihedrals = properDih + self.improperDihedrals = improperDih + self.condensedProperDihedrals = condProperDih # [[],[],...] + self.atomPairs = atomPairs # set((atom1, atom2), ...) + self.printDebug(""getDihedrals done"") + + def getChirals(self): + """""" + Get chiral atoms, its 4 neighbours and improper dihedral angle + """""" + self.chiralGroups = [] + if self.obchiralExe: + # print (self.obchiralExe, os.getcwd()) + cmd = '%s %s' % (self.obchiralExe, self.inputFile) + # print(cmd) + out = map(int, re.findall('Atom (\d+) Is', _getoutput(cmd))) + # print(""*%s*"" % out) + chiralGroups = [] + for id_ in out: + atChi = self.atoms[id_ - 1] + quad = [] + for bb in self.bonds: + bAts = bb.atoms[:] + if atChi in bAts: + bAts.remove(atChi) + quad.append(bAts[0]) + if len(quad) != 4: + if self.chiral: + self.printWarn(""Atom %s has less than 4 connections to 4 different atoms. It's NOT Chiral!"" % atChi) + continue + v1, v2, v3, v4 = [x.coords for x in quad] + chiralGroups.append((atChi, quad, imprDihAngle(v1, v2, v3, v4))) + self.chiralGroups = chiralGroups + + def sortAtomsForGromacs(self): + """""" + Re-sort atoms for gromacs, which expects all hydrogens to immediately + follow the heavy atom they are bonded to and belong to the same charge + group. + + Currently, atom mass < 1.2 is taken to denote a proton. This behavior + may be changed by modifying the 'is_hydrogen' function within. + + JDC 2011-02-03 + """""" + + # Build dictionary of bonded atoms. + bonded_atoms = dict() + for atom in self.atoms: + bonded_atoms[atom] = list() + for bond in self.bonds: + [atom1, atom2] = bond.atoms + bonded_atoms[atom1].append(atom2) + bonded_atoms[atom2].append(atom1) + + # Define hydrogen and heavy atom classes. + def is_hydrogen(atom): + return (atom.mass < 1.2) + + def is_heavy(atom): + return not is_hydrogen(atom) + + # Build list of sorted atoms, assigning charge groups by heavy atom. + sorted_atoms = list() + cgnr = 1 # charge group number: each heavy atoms is assigned its own charge group + # First pass: add heavy atoms, followed by the hydrogens bonded to them. + for atom in self.atoms: + if is_heavy(atom): + # Append heavy atom. + atom.cgnr = cgnr + sorted_atoms.append(atom) + # Append all hydrogens. + for bonded_atom in bonded_atoms[atom]: + if is_hydrogen(bonded_atom) and not (bonded_atom in sorted_atoms): + # Append bonded hydrogen. + bonded_atom.cgnr = cgnr + sorted_atoms.append(bonded_atom) + cgnr += 1 + + # Second pass: Add any remaining atoms. + if len(sorted_atoms) < len(self.atoms): + for atom in self.atoms: + if not (atom in sorted_atoms): + atom.cgnr = cgnr + sorted_atoms.append(atom) + cgnr += 1 + + # Replace current list of atoms with sorted list. + self.atoms = sorted_atoms + + # Renumber atoms in sorted list, starting from 1. + for (index, atom) in enumerate(self.atoms): + atom.id = index + 1 + + return + + def setAtomPairs(self): + """""" + Set a list of pair of atoms pertinent to interaction 1-4 for vdw. + WRONG: Deprecated + """""" + atomPairs = [] + for item in self.condensedProperDihedrals: + dih = item[0] + atom1 = dih.atoms[0] + atom2 = dih.atoms[3] + pair = [atom1, atom2] + if atomPairs.count(pair) == 0: + atomPairs.append(pair) + self.atomPairs = atomPairs # [[atom1, atom2], ...] + self.printDebug(""atomPairs done"") + + def getExcludedAtoms(self): + """""" + Returns a list of atoms with a list of its excluded atoms up to 3rd + neighbour. + It's implicitly indexed, i.e., a sequence of atoms in position n in + the excludedAtomsList corresponds to atom n (self.atoms) and so on. + NOT USED + """""" + excludedAtomsIdList = self.getFlagData('EXCLUDED_ATOMS_LIST') + numberExcludedAtoms = self.getFlagData('NUMBER_EXCLUDED_ATOMS') + atoms = self.atoms + interval = 0 + excludedAtomsList = [] + for number in numberExcludedAtoms: + temp = excludedAtomsIdList[interval:interval + number] + if temp == [0]: + excludedAtomsList.append([]) + else: + excludedAtomsList.append([atoms[a - 1] for a in temp]) + interval += number + self.excludedAtoms = excludedAtomsList + self.printDebug(""getExcludedAtoms"") + + def balanceCharges(self, chargeList, FirstNonSoluteId=None): + """""" + Note that python is very annoying about floating points. + Even after balance, there will always be some residue of order e-12 + to e-16, which is believed to vanished once one writes a topology + file, say, for CNS or GMX, where floats are represented with 4 or 5 + maximum decimals. + """""" + limIds = [] + # self.printDebug(chargeList) + total = sum(chargeList) + totalConverted = total / qConv + self.printDebug('charge to be balanced: total %13.10f' % (totalConverted)) + maxVal = max(chargeList[:FirstNonSoluteId]) + minVal = min(chargeList[:FirstNonSoluteId]) + if abs(maxVal) >= abs(minVal): + lim = maxVal + else: + lim = minVal + nLims = chargeList.count(lim) + # limId = chargeList.index(lim) + diff = totalConverted - round(totalConverted) + fix = lim - diff * qConv / nLims + id_ = 0 + for c in chargeList: + if c == lim: + limIds.append(id_) + chargeList[id_] = fix + id_ += 1 + # self.printDebug(chargeList) + self.printDebug(""balanceCharges done"") + return chargeList, fix, limIds + + def getABCOEFs(self): + uniqAtomTypeIdList = self.getFlagData('ATOM_TYPE_INDEX') + nonBonIdList = self.getFlagData('NONBONDED_PARM_INDEX') + rawACOEFs = self.getFlagData('LENNARD_JONES_ACOEF') + rawBCOEFs = self.getFlagData('LENNARD_JONES_BCOEF') + # print nonBonIdList, len(nonBonIdList), rawACOEFs, len(rawACOEFs) + ACOEFs = [] + BCOEFs = [] + ntypes = max(uniqAtomTypeIdList) + # id_ = 0 + # for atName in self._atomTypeNameList: + for id_ in range(len(self._atomTypeNameList)): + # id_ = self._atomTypeNameList.index(atName) + atomTypeId = uniqAtomTypeIdList[id_] + index = ntypes * (atomTypeId - 1) + atomTypeId + nonBondId = nonBonIdList[index - 1] + # print ""*****"", index, ntypes, atName, id_, atomTypeId, nonBondId + ACOEFs.append(rawACOEFs[nonBondId - 1]) + BCOEFs.append(rawBCOEFs[nonBondId - 1]) + # id_ += 1 + # print ACOEFs + self.printDebug(""getABCOEFs done"") + return ACOEFs, BCOEFs + + def setProperDihedralsCoef(self): + """""" + It takes self.condensedProperDihedrals and returns + self.properDihedralsCoefRB, a reduced list of quartet atoms + RB. + Coeficients ready for GMX (multiplied by 4.184) + + self.properDihedralsCoefRB = [ [atom1,..., atom4], C[0:5] ] + + For proper dihedrals: a quartet of atoms may appear with more than + one set of parameters and to convert to GMX they are treated as RBs. + + The resulting coefs calculated here may look slighted different from + the ones calculated by amb2gmx.pl because python is taken full float + number from prmtop and not rounded numbers from rdparm.out as + amb2gmx.pl does. + """""" + properDihedralsCoefRB = [] + properDihedralsAlphaGamma = [] + properDihedralsGmx45 = [] + for item in self.condensedProperDihedrals: + V = 6 * [0.0] + C = 6 * [0.0] + for dih in item: + period = dih.period # Pn + kPhi = dih.kPhi # in rad + phaseRaw = dih.phase * radPi # in degree + phase = int(phaseRaw) # in degree + if period > 4 and not self.gmx45: + self.printError(""Likely trying to convert ILDN to RB, use option '-r' for GMX45"") + sys.exit(1) + if phase in [0, 180]: + properDihedralsGmx45.append([item[0].atoms, phaseRaw, kPhi, period]) + if not self.gmx45: + if kPhi > 0: + V[period] = 2 * kPhi * cal + if period == 1: + C[0] += 0.5 * V[period] + if phase == 0: + C[1] -= 0.5 * V[period] + else: + C[1] += 0.5 * V[period] + elif period == 2: + if phase == 180: + C[0] += V[period] + C[2] -= V[period] + else: + C[2] += V[period] + elif period == 3: + C[0] += 0.5 * V[period] + if phase == 0: + C[1] += 1.5 * V[period] + C[3] -= 2 * V[period] + else: + C[1] -= 1.5 * V[period] + C[3] += 2 * V[period] + elif period == 4: + if phase == 180: + C[2] += 4 * V[period] + C[4] -= 4 * V[period] + else: + C[0] += V[period] + C[2] -= 4 * V[period] + C[4] += 4 * V[period] + else: + properDihedralsAlphaGamma.append([item[0].atoms, phaseRaw, kPhi, period]) + # print phaseRaw, kPhi, period + if phase in [0, 180]: + properDihedralsCoefRB.append([item[0].atoms, C]) + + # print properDihedralsCoefRB + # print properDihedralsAlphaGamma + + self.printDebug(""setProperDihedralsCoef done"") + + self.properDihedralsCoefRB = properDihedralsCoefRB + self.properDihedralsAlphaGamma = properDihedralsAlphaGamma + self.properDihedralsGmx45 = properDihedralsGmx45 + + def writeCharmmTopolFiles(self): + + self.printMess(""Writing CHARMM files\n"") + + # self.makeDir() + + at = self.atomType + self.getResidueLabel() + res = self.resName # self.residueLabel[0] + # print res, self.residueLabel, type(self.residueLabel) + + cmd = '%s -i %s -fi mol2 -o %s -fo charmm -s 2 -at %s \ + -pf y -rn %s' % (self.acExe, self.acMol2FileName, self.charmmBase, + at, res) + + if self.debug: + cmd = cmd.replace('-pf y', '-pf n') + self.printDebug(cmd) + _log = _getoutput(cmd) + + def writePdb(self, file_): + """""" + Write a new PDB file_ with the atom names defined by Antechamber + Input: file_ path string + The format generated here use is slightly different from + http://www.wwpdb.org/documentation/format23/sect9.html respected to + atom name + """""" + # TODO: assuming only one residue ('1') + pdbFile = open(file_, 'w') + fbase = os.path.basename(file_) + pdbFile.write(""REMARK "" + head % (fbase, date)) + id_ = 1 + for atom in self.atoms: + # id_ = self.atoms.index(atom) + 1 + aName = atom.atomName + if len(aName) == 2: + aName = ' %s ' % aName + elif len(aName) == 1: + aName = ' %s ' % aName + for l in aName: + if l.isalpha(): + s = l + break + rName = self.residueLabel[0] + x = atom.coords[0] + y = atom.coords[1] + z = atom.coords[2] + line = ""%-6s%5d %4s %3s Z%4d%s%8.3f%8.3f%8.3f%6.2f%6.2f%s%2s\n"" % \ + ('ATOM', id_, aName, rName, 1, 4 * ' ', x, y, z, 1.0, 0.0, 10 * ' ', s) + pdbFile.write(line) + id_ += 1 + pdbFile.write('END\n') + + def writeGromacsTopolFiles(self, amb2gmx=False): + """""" + # from ~/Programmes/amber10/dat/leap/parm/gaff.dat + #atom type atomic mass atomic polarizability comments + ca 12.01 0.360 Sp2 C in pure aromatic systems + ha 1.008 0.135 H bonded to aromatic carbon + + #bonded atoms harmonic force kcal/mol/A^2 eq. dist. Ang. comments + ca-ha 344.3* 1.087** SOURCE3 1496 0.0024 0.0045 + * for gmx: 344.3 * 4.184 * 100 * 2 = 288110 kJ/mol/nm^2 (why factor 2?) + ** convert Ang to nm ( div by 10) for gmx: 1.087 A = 0.1087 nm + # CA HA 1 0.10800 307105.6 ; ged from 340. bsd on C6H6 nmodes; PHE,TRP,TYR (from ffamber99bon.itp) + # CA-HA 367.0 1.080 changed from 340. bsd on C6H6 nmodes; PHE,TRP,TYR (from parm99.dat) + + # angle HF kcal/mol/rad^2 eq angle degrees comments + ca-ca-ha 48.5* 120.01 SOURCE3 2980 0.1509 0.2511 + * to convert to gmx: 48.5 * 4.184 * 2 = 405.848 kJ/mol/rad^2 (why factor 2?) + # CA CA HA 1 120.000 418.400 ; new99 (from ffamber99bon.itp) + # CA-CA-HA 50.0 120.00 (from parm99.dat) + + # dihedral idivf barrier hight/2 kcal/mol phase degrees periodicity comments + X -ca-ca-X 4 14.500* 180.000 2.000 intrpol.bsd.on C6H6 + * to convert to gmx: 14.5/4 * 4.184 * 2 (?) (yes in amb2gmx, not in topolbuild, why?) = 30.334 or 15.167 kJ/mol + # X -CA-CA-X 4 14.50 180.0 2. intrpol.bsd.on C6H6 (from parm99.dat) + # X CA CA X 3 30.33400 0.00000 -30.33400 0.00000 0.00000 0.00000 ; intrpol.bsd.on C6H6 + ;propers treated as RBs in GROMACS to use combine multiple AMBER torsions per quartet (from ffamber99bon.itp) + + # impr. dihedral barrier hight/2 phase degrees periodicity comments + X -X -ca-ha 1.1* 180. 2. bsd.on C6H6 nmodes + * to convert to gmx: 1.1 * 4.184 = 4.6024 kJ/mol/rad^2 + # X -X -CA-HA 1.1 180. 2. bsd.on C6H6 nmodes (from parm99.dat) + # X X CA HA 1 180.00 4.60240 2 ; bsd.on C6H6 nmodes + ;impropers treated as propers in GROMACS to use correct AMBER analytical function (from ffamber99bon.itp) + + # 6-12 parms sigma = 2 * r * 2^(-1/6) epsilon + # atomtype radius Ang. pot. well depth kcal/mol comments + ha 1.4590* 0.0150** Spellmeyer + ca 1.9080 0.0860 OPLS + * to convert to gmx: + sigma = 1.4590 * 2^(-1/6) * 2 = 2 * 1.29982 Ang. = 2 * 0.129982 nm = 1.4590 * 2^(5/6)/10 = 0.259964 nm + ** to convert to gmx: 0.0150 * 4.184 = 0.06276 kJ/mol + # amber99_3 CA 0.0000 0.0000 A 3.39967e-01 3.59824e-01 (from ffamber99nb.itp) + # amber99_22 HA 0.0000 0.0000 A 2.59964e-01 6.27600e-02 (from ffamber99nb.itp) + # C* 1.9080 0.0860 Spellmeyer + # HA 1.4590 0.0150 Spellmeyer (from parm99.dat) + # to convert r and epsilon to ACOEF and BCOEF + # ACOEF = sqrt(e1*e2) * (r1 + r2)^12 ; BCOEF = 2 * sqrt(e1*e2) * (r1 + r2)^6 = 2 * ACOEF/(r1+r2)^6 + # to convert ACOEF and BCOEF to r and epsilon + # r = 0.5 * (2*ACOEF/BCOEF)^(1/6); ep = BCOEF^2/(4*ACOEF) + # to convert ACOEF and BCOEF to sigma and epsilon (GMX) + # sigma = (ACOEF/BCOEF)^(1/6) * 0.1 ; epsilon = 4.184 * BCOEF^2/(4*ACOEF) + # ca ca 819971.66 531.10 + # ca ha 76245.15 104.66 + # ha ha 5716.30 18.52 + + For proper dihedrals: a quartet of atoms may appear with more than + one set of parameters and to convert to GMX they are treated as RBs; + use the algorithm: + for(my $j=$i;$j<=$lines;$j++){ + my $period = $pn{$j}; + if($pk{$j}>0) { + $V[$period] = 2*$pk{$j}*$cal; + } + # assign V values to C values as predefined # + if($period==1){ + $C[0]+=0.5*$V[$period]; + if($phase{$j}==0){ + $C[1]-=0.5*$V[$period]; + }else{ + $C[1]+=0.5*$V[$period]; + } + }elsif($period==2){ + if(($phase{$j}==180)||($phase{$j}==3.14)){ + $C[0]+=$V[$period]; + $C[2]-=$V[$period]; + }else{ + $C[2]+=$V[$period]; + } + }elsif($period==3){ + $C[0]+=0.5*$V[$period]; + if($phase{$j}==0){ + $C[1]+=1.5*$V[$period]; + $C[3]-=2*$V[$period]; + }else{ + $C[1]-=1.5*$V[$period]; + $C[3]+=2*$V[$period]; + } + }elsif($period==4){ + if(($phase{$j}==180)||($phase{$j}==3.14)){ + $C[2]+=4*$V[$period]; + $C[4]-=4*$V[$period]; + }else{ + $C[0]+=$V[$period]; + $C[2]-=4*$V[$period]; + $C[4]+=4*$V[$period]; + } + } + } + """""" + + self.printMess(""Writing GROMACS files\n"") + + self.setAtomType4Gromacs() + + self.writeGroFile() + + self.writeGromacsTop(amb2gmx=amb2gmx) + + self.writeMdpFiles() + + def setAtomType4Gromacs(self): + """"""Atom types names in Gromacs TOP file are not case sensitive; + this routine will append a '_' to lower case atom type. + E.g.: CA and ca -> CA and ca_ + """""" + if self.disam: + self.printMess(""Disambiguating lower and uppercase atomtypes in GMX top file.\n"") + self.atomTypesGromacs = self.atomTypes + self.atomsGromacs = self.atoms + return + + atNames = [at.atomTypeName for at in self.atomTypes] + # print atNames + delAtomTypes = [] + modAtomTypes = [] + atomTypesGromacs = [] + dictAtomTypes = {} + for at in self.atomTypes: + atName = at.atomTypeName + dictAtomTypes[atName] = at + if atName.islower() and atName.upper() in atNames: + # print atName, atName.upper() + atUpper = self.atomTypes[atNames.index(atName.upper())] + # print at.atomTypeName,at.mass, at.ACOEF, at.BCOEF + # print atUpper.atomTypeName, atUpper.mass, atUpper.ACOEF, atUpper.BCOEF + if at.ACOEF is atUpper.ACOEF and at.BCOEF is at.BCOEF: + delAtomTypes.append(atName) + else: + newAtName = atName + '_' + modAtomTypes.append(atName) + atomType = AtomType(newAtName, at.mass, at.ACOEF, at.BCOEF) + atomTypesGromacs.append(atomType) + dictAtomTypes[newAtName] = atomType + else: + atomTypesGromacs.append(at) + + atomsGromacs = [] + for a in self.atoms: + atName = a.atomType.atomTypeName + if atName in delAtomTypes: + atom = Atom(a.atomName, dictAtomTypes[atName.upper()], a.id, + a.resid, a.mass, a.charge, a.coords) + atom.cgnr = a.cgnr + atomsGromacs.append(atom) + elif atName in modAtomTypes: + atom = Atom(a.atomName, dictAtomTypes[atName + '_'], a.id, + a.resid, a.mass, a.charge, a.coords) + atom.cgnr = a.cgnr + atomsGromacs.append(atom) + else: + atomsGromacs.append(a) + + self.atomTypesGromacs = atomTypesGromacs + self.atomsGromacs = atomsGromacs + # print [i.atomTypeName for i in atomTypesGromacs] + # print modAtomTypes + # print delAtomTypes + + def writeGromacsTop(self, amb2gmx=False): + if self.atomTypeSystem == 'amber': + d2opls = dictAtomTypeAmb2OplsGmxCode + else: + d2opls = dictAtomTypeGaff2OplsGmxCode + + topText = [] + itpText = [] + oitpText = [] + otopText = [] + top = self.baseName + '_GMX.top' + itp = self.baseName + '_GMX.itp' + otop = self.baseName + '_GMX_OPLS.top' + oitp = self.baseName + '_GMX_OPLS.itp' + + headDefault = \ + """""" +[ defaults ] +; nbfunc comb-rule gen-pairs fudgeLJ fudgeQQ +1 2 yes 0.5 0.8333 +"""""" + headItp = \ + """""" +; Include %s topology +#include ""%s"" +"""""" + headOpls = \ + """""" +; Include forcefield parameters +#include ""ffoplsaa.itp"" +"""""" + headSystem = \ + """""" +[ system ] + %s +"""""" + headMols = \ + """""" +[ molecules ] +; Compound nmols +"""""" + headAtomtypes = \ + """""" +[ atomtypes ] +;name bond_type mass charge ptype sigma epsilon Amb +"""""" + headAtomtypesOpls = \ + """""" +; For OPLS atomtypes manual fine tuning +; AC_at:OPLS_at:OPLScode: Possible_Aternatives (see ffoplsaa.atp and ffoplsaanb.itp) +"""""" + headMoleculetype = \ + """""" +[ moleculetype ] +;name nrexcl + %-16s 3 +"""""" + headAtoms = \ + """""" +[ atoms ] +; nr type resi res atom cgnr charge mass ; qtot bond_type +"""""" + headBonds = \ + """""" +[ bonds ] +; ai aj funct r k +"""""" + headPairs = \ + """""" +[ pairs ] +; ai aj funct +"""""" + headAngles = \ + """""" +[ angles ] +; ai aj ak funct theta cth +"""""" + headProDih = \ + """""" +[ dihedrals ] ; propers +; treated as RBs in GROMACS to use combine multiple AMBER torsions per quartet +; i j k l func C0 C1 C2 C3 C4 C5 +"""""" + + headProDihAlphaGamma = """"""; treated as usual propers in GROMACS since Phase angle diff from 0 or 180 degrees +; i j k l func phase kd pn +"""""" + + headProDihGmx45 = \ + """""" +[ dihedrals ] ; propers +; for gromacs 4.5 or higher, using funct 9 +; i j k l func phase kd pn +"""""" + + headImpDih = \ + """""" +[ dihedrals ] ; impropers +; treated as propers in GROMACS to use correct AMBER analytical function +; i j k l func phase kd pn +"""""" + _headTopWaterTip3p = \ + """""" +[ bondtypes ] + ; i j func b0 kb + OW HW 1 0.09572 462750.4 ; TIP3P water + HW HW 1 0.15139 462750.4 ; TIP3P water + +[ angletypes ] + ; i j k func th0 cth + HW OW HW 1 104.520 836.800 ; TIP3P water + HW HW OW 1 127.740 0.000 ; (found in crystallographic water with 3 bonds) +"""""" + + _headTopWaterSpce = \ + """""" +[ bondtypes ] + ; i j func b0 kb + OW HW 1 0.1 462750.4 ; SPCE water + HW HW 1 0.1633 462750.4 ; SPCE water + +[ angletypes ] + ; i j k func th0 cth + HW OW HW 1 109.47 836.800 ; SPCE water + HW HW OW 1 125.265 0.000 ; SPCE water +"""""" +# NOTE: headTopWaterTip3p and headTopWaterSpce actually do NOTHING + headNa = \ + """""" +[ moleculetype ] + ; molname nrexcl + NA+ 1 + +[ atoms ] + ; id_ at type res nr residu name at name cg nr charge mass + 1 IP 1 NA+ NA+ 1 1 22.9898 +"""""" + headCl = \ + """""" +[ moleculetype ] + ; molname nrexcl + CL- 1 + +[ atoms ] + ; id_ at type res nr residu name at name cg nr charge mass + 1 IM 1 CL- CL- 1 -1 35.45300 +"""""" + headK = \ + """""" +[ moleculetype ] + ; molname nrexcl + K+ 1 + +[ atoms ] + ; id_ at type res nr residu name at name cg nr charge mass + 1 K 1 K+ K+ 1 1 39.100 +"""""" + headWaterTip3p = \ + """""" +[ moleculetype ] +; molname nrexcl ; TIP3P model + WAT 2 + +[ atoms ] +; nr type resnr residue atom cgnr charge mass + 1 OW 1 WAT O 1 -0.834 16.00000 + 2 HW 1 WAT H1 1 0.417 1.00800 + 3 HW 1 WAT H2 1 0.417 1.00800 + +#ifdef FLEXIBLE +[ bonds ] +; i j funct length force.c. +1 2 1 0.09572 462750.4 0.09572 462750.4 +1 3 1 0.09572 462750.4 0.09572 462750.4 + +[ angles ] +; i j k funct angle force.c. +2 1 3 1 104.520 836.800 104.520 836.800 +#else +[ settles ] +; i j funct length +1 1 0.09572 0.15139 + +[ exclusions ] +1 2 3 +2 1 3 +3 1 2 +#endif +"""""" + + headWaterSpce = \ + """""" +[ moleculetype ] +; molname nrexcl ; SPCE model + WAT 2 + +[ atoms ] +; nr type resnr residue atom cgnr charge mass + 1 OW 1 WAT O 1 -0.8476 15.99940 + 2 HW 1 WAT H1 1 0.4238 1.00800 + 3 HW 1 WAT H2 1 0.4238 1.00800 + +#ifdef FLEXIBLE +[ bonds ] +; i j funct length force.c. +1 2 1 0.1 462750.4 0.1 462750.4 +1 3 1 0.1 462750.4 0.1 462750.4 + +[ angles ] +; i j k funct angle force.c. +2 1 3 1 109.47 836.800 109.47 836.800 +#else +[ settles ] +; OW funct doh dhh +1 1 0.1 0.16330 + +[ exclusions ] +1 2 3 +2 1 3 +3 1 2 +#endif +"""""" + if self.direct and amb2gmx: + self.printMess(""Converting directly from AMBER to GROMACS.\n"") + + # Dict of ions dealt by acpype emulating amb2gmx + ionsDict = {'Na+': headNa, 'Cl-': headCl, 'K+': headK} + ionsSorted = [] +# NOTE: headWaterTip3p and headWaterSpce actually do the real thing +# so, skipping headTopWaterTip3p and headWaterTip3p + # headTopWater = headTopWaterTip3p + headWater = headWaterTip3p + + nWat = 0 + # topFile.write(""; "" + head % (top, date)) + topText.append(""; "" + head % (top, date)) + otopText.append(""; "" + head % (otop, date)) + # topFile.write(headDefault) + topText.append(headDefault) + + nSolute = 0 + if not amb2gmx: + topText.append(headItp % (itp, itp)) + otopText.append(headOpls) + otopText.append(headItp % (itp, itp)) + itpText.append(""; "" + head % (itp, date)) + oitpText.append(""; "" + head % (oitp, date)) + + self.printDebug(""atomTypes %i"" % len(self.atomTypesGromacs)) + temp = [] + otemp = [] + for aType in self.atomTypesGromacs: + aTypeName = aType.atomTypeName + oaCode = d2opls.get(aTypeName, ['x', '0'])[:-1] + aTypeNameOpls = oplsCode2AtomTypeDict.get(oaCode[0], 'x') + A = aType.ACOEF + B = aType.BCOEF + # one cannot infer sigma or epsilon for B = 0, assuming 0 for them + if B == 0.0: + sigma, epsilon, r0, epAmber = 0, 0, 0, 0 + else: + r0 = 0.5 * math.pow((2 * A / B), (1.0 / 6)) + epAmber = 0.25 * B * B / A + sigma = 0.1 * math.pow((A / B), (1.0 / 6)) + epsilon = cal * epAmber + if aTypeName == 'OW': + if A == 629362.166 and B == 625.267765: + # headTopWater = headTopWaterSpce + headWater = headWaterSpce + # OW 629362.166 625.267765 spce + # OW 581935.564 594.825035 tip3p + # print aTypeName, A, B + line = "" %-8s %-11s %3.5f %3.5f A %13.5e %13.5e"" % \ + (aTypeName, aTypeName, 0.0, 0.0, sigma, epsilon) + \ + "" ; %4.2f %1.4f\n"" % (r0, epAmber) + oline = ""; %s:%s:opls_%s: %s\n"" % (aTypeName, aTypeNameOpls, oaCode[0], repr(oaCode[1:])) + # tmpFile.write(line) + temp.append(line) + otemp.append(oline) + if amb2gmx: + topText.append(headAtomtypes) + topText += temp + nWat = self.residueLabel.count('WAT') + for ion in ionsDict: + nIon = self.residueLabel.count(ion) + if nIon > 0: + idIon = self.residueLabel.index(ion) + ionsSorted.append((idIon, nIon, ion)) + ionsSorted.sort() + else: + itpText.append(headAtomtypes) + itpText += temp + oitpText.append(headAtomtypesOpls) + oitpText += otemp + self.printDebug(""GMX atomtypes done"") + + if len(self.atoms) > 3 * nWat + sum([x[1] for x in ionsSorted]): + nSolute = 1 + + if nWat: + # topText.append(headTopWater) + self.printDebug(""type of water '%s'"" % headWater[43:48].strip()) + + if nSolute: + if amb2gmx: + topText.append(headMoleculetype % self.baseName) + else: + itpText.append(headMoleculetype % self.baseName) + oitpText.append(headMoleculetype % self.baseName) + + self.printDebug(""atoms %i"" % len(self.atoms)) + qtot = 0.0 + count = 1 + temp = [] + otemp = [] + id2oplsATDict = {} + for atom in self.atomsGromacs: + resid = atom.resid + resname = self.residueLabel[resid] + if not self.direct: + if resname in list(ionsDict.keys()) + ['WAT']: + break + aName = atom.atomName + aType = atom.atomType.atomTypeName + oItem = d2opls.get(aType, ['x', 0]) + oplsAtName = oplsCode2AtomTypeDict.get(oItem[0], 'x') + id_ = atom.id + id2oplsATDict[id_] = oplsAtName + oaCode = 'opls_' + oItem[0] + cgnr = id_ + if self.sorted: + cgnr = atom.cgnr # JDC + charge = atom.charge + mass = atom.mass + omass = float(oItem[-1]) + qtot += charge + resnr = resid + 1 + line = ""%6d %4s %5d %5s %5s %4d %12.6f %12.5f ; qtot %1.3f\n"" % \ + (id_, aType, resnr, resname, aName, cgnr, charge, mass, qtot) # JDC + oline = ""%6d %4s %5d %5s %5s %4d %12.6f %12.5f ; qtot % 3.3f %-4s\n"" % \ + (id_, oaCode, resnr, resname, aName, cgnr, charge, omass, qtot, oplsAtName) # JDC + count += 1 + temp.append(line) + otemp.append(oline) + if temp: + if amb2gmx: + topText.append(headAtoms) + topText += temp + else: + itpText.append(headAtoms) + itpText += temp + oitpText.append(headAtoms) + oitpText += otemp + self.printDebug(""GMX atoms done"") + + # remove bond of water + self.printDebug(""bonds %i"" % len(self.bonds)) + temp = [] + otemp = [] + for bond in self.bonds: + res1 = self.residueLabel[bond.atoms[0].resid] + res2 = self.residueLabel[bond.atoms[0].resid] + if 'WAT' in [res1, res2]: + continue + a1Name = bond.atoms[0].atomName + a2Name = bond.atoms[1].atomName + id1 = bond.atoms[0].id + id2 = bond.atoms[1].id + oat1 = id2oplsATDict.get(id1) + oat2 = id2oplsATDict.get(id2) + line = ""%6i %6i %3i %13.4e %13.4e ; %6s - %-6s\n"" % (id1, id2, 1, + bond.rEq * 0.1, bond.kBond * 200 * cal, a1Name, a2Name) + oline = ""%6i %6i %3i ; %13.4e %13.4e ; %6s - %-6s %6s - %-6s\n"" % \ + (id1, id2, 1, bond.rEq * 0.1, bond.kBond * 200 * cal, a1Name, + a2Name, oat1, oat2) + temp.append(line) + otemp.append(oline) + temp.sort() + otemp.sort() + if temp: + if amb2gmx: + topText.append(headBonds) + topText += temp + else: + itpText.append(headBonds) + itpText += temp + oitpText.append(headBonds) + oitpText += otemp + self.printDebug(""GMX bonds done"") + + self.printDebug(""atomPairs %i"" % len(self.atomPairs)) + temp = [] + for pair in self.atomPairs: + # if not printed: + # tmpFile.write(headPairs) + # printed = True + a1Name = pair[0].atomName + a2Name = pair[1].atomName + id1 = pair[0].id + id2 = pair[1].id + # id1 = self.atoms.index(pair[0]) + 1 + # id2 = self.atoms.index(pair[1]) + 1 + line = ""%6i %6i %6i ; %6s - %-6s\n"" % (id1, id2, 1, a1Name, + a2Name) + temp.append(line) + temp.sort() + if temp: + if amb2gmx: + topText.append(headPairs) + topText += temp + else: + itpText.append(headPairs) + itpText += temp + oitpText.append(headPairs) + oitpText += temp + self.printDebug(""GMX pairs done"") + + self.printDebug(""angles %i"" % len(self.angles)) + temp = [] + otemp = [] + for angle in self.angles: + a1 = angle.atoms[0].atomName + a2 = angle.atoms[1].atomName + a3 = angle.atoms[2].atomName + id1 = angle.atoms[0].id + id2 = angle.atoms[1].id + id3 = angle.atoms[2].id + oat1 = id2oplsATDict.get(id1) + oat2 = id2oplsATDict.get(id2) + oat3 = id2oplsATDict.get(id3) + line = ""%6i %6i %6i %6i %13.4e %13.4e ; %6s - %-6s - %-6s\n"" % (id1, id2, + id3, 1, angle.thetaEq * radPi, 2 * cal * angle.kTheta, a1, a2, a3) + oline = ""%6i %6i %6i %6i ; %13.4e %13.4e ; %6s - %-4s - %-6s %4s - %+4s - %-4s\n"" % \ + (id1, id2, id3, 1, angle.thetaEq * radPi, 2 * cal * angle.kTheta, + a1, a2, a3, oat1, oat2, oat3) + temp.append(line) + otemp.append(oline) + temp.sort() + otemp.sort() + if temp: + if amb2gmx: + topText.append(headAngles) + topText += temp + else: + itpText.append(headAngles) + itpText += temp + oitpText.append(headAngles) + oitpText += otemp + self.printDebug(""GMX angles done"") + + self.setProperDihedralsCoef() + self.printDebug(""properDihedralsCoefRB %i"" % len(self.properDihedralsCoefRB)) + self.printDebug(""properDihedralsAlphaGamma %i"" % len(self.properDihedralsAlphaGamma)) + self.printDebug(""properDihedralsGmx45 %i"" % len(self.properDihedralsGmx45)) + temp = [] + otemp = [] + if not self.gmx45: + for dih in self.properDihedralsCoefRB: + a1 = dih[0][0].atomName + a2 = dih[0][1].atomName + a3 = dih[0][2].atomName + a4 = dih[0][3].atomName + id1 = dih[0][0].id + id2 = dih[0][1].id + id3 = dih[0][2].id + id4 = dih[0][3].id + oat1 = id2oplsATDict.get(id1) + oat2 = id2oplsATDict.get(id2) + oat3 = id2oplsATDict.get(id3) + oat4 = id2oplsATDict.get(id4) + c0, c1, c2, c3, c4, c5 = dih[1] + line = \ + ""%6i %6i %6i %6i %6i %10.5f %10.5f %10.5f %10.5f %10.5f %10.5f"" % \ + (id1, id2, id3, id4, 3, c0, c1, c2, c3, c4, c5) \ + + "" ; %6s-%6s-%6s-%6s\n"" % (a1, a2, a3, a4) + oline = \ + ""%6i %6i %6i %6i %6i ; %10.5f %10.5f %10.5f %10.5f %10.5f %10.5f"" % \ + (id1, id2, id3, id4, 3, c0, c1, c2, c3, c4, c5) \ + + "" ; %6s-%6s-%6s-%6s %4s-%4s-%4s-%4s\n"" % (a1, a2, a3, a4, oat1, oat2, oat3, oat4) + temp.append(line) + otemp.append(oline) + temp.sort() + otemp.sort() + if temp: + if amb2gmx: + topText.append(headProDih) + topText += temp + else: + itpText.append(headProDih) + itpText += temp + oitpText.append(headProDih) + oitpText += otemp + self.printDebug(""GMX proper dihedrals done"") + else: + self.printMess(""Writing GMX dihedrals for GMX 4.5.\n"") + funct = 9 # 9 + for dih in self.properDihedralsGmx45: + a1 = dih[0][0].atomName + a2 = dih[0][1].atomName + a3 = dih[0][2].atomName + a4 = dih[0][3].atomName + id1 = dih[0][0].id + id2 = dih[0][1].id + id3 = dih[0][2].id + id4 = dih[0][3].id + ph = dih[1] # phase already in degree + kd = dih[2] * cal # kPhi PK + pn = dih[3] # .period + line = ""%6i %6i %6i %6i %6i %8.2f %9.5f %3i ; %6s-%6s-%6s-%6s\n"" % \ + (id1, id2, id3, id4, funct, ph, kd, pn, a1, a2, a3, a4) + oline = ""%6i %6i %6i %6i %6i ; %8.2f %9.5f %3i ; %6s-%6s-%6s-%6s\n"" % \ + (id1, id2, id3, id4, funct, ph, kd, pn, a1, a2, a3, a4) + temp.append(line) + otemp.append(oline) + temp.sort() + otemp.sort() + if temp: + if amb2gmx: + topText.append(headProDihGmx45) + topText += temp + else: + itpText.append(headProDihGmx45) + itpText += temp + oitpText.append(headProDihGmx45) + oitpText += otemp + + # for properDihedralsAlphaGamma + if self.gmx45: + funct = 4 # 4 + else: + funct = 1 + temp = [] + otemp = [] + for dih in self.properDihedralsAlphaGamma: + a1 = dih[0][0].atomName + a2 = dih[0][1].atomName + a3 = dih[0][2].atomName + a4 = dih[0][3].atomName + id1 = dih[0][0].id + id2 = dih[0][1].id + id3 = dih[0][2].id + id4 = dih[0][3].id + ph = dih[1] # phase already in degree + kd = dih[2] * cal # kPhi PK + pn = dih[3] # .period + line = ""%6i %6i %6i %6i %6i %8.2f %9.5f %3i ; %6s-%6s-%6s-%6s\n"" % \ + (id1, id2, id3, id4, funct, ph, kd, pn, a1, a2, a3, a4) + oline = ""%6i %6i %6i %6i %6i ; %8.2f %9.5f %3i ; %6s-%6s-%6s-%6s\n"" % \ + (id1, id2, id3, id4, funct, ph, kd, pn, a1, a2, a3, a4) + temp.append(line) + otemp.append(oline) + temp.sort() + otemp.sort() + if temp: + if amb2gmx: + topText.append(headProDihAlphaGamma) + topText += temp + else: + itpText.append(headProDihAlphaGamma) + itpText += temp + oitpText.append(headProDihAlphaGamma) + oitpText += otemp + self.printDebug(""GMX special proper dihedrals done"") + + self.printDebug(""improperDihedrals %i"" % len(self.improperDihedrals)) + temp = [] + otemp = [] + for dih in self.improperDihedrals: + a1 = dih.atoms[0].atomName + a2 = dih.atoms[1].atomName + a3 = dih.atoms[2].atomName + a4 = dih.atoms[3].atomName + id1 = dih.atoms[0].id + id2 = dih.atoms[1].id + id3 = dih.atoms[2].id + id4 = dih.atoms[3].id + kd = dih.kPhi * cal + pn = dih.period + ph = dih.phase * radPi + line = ""%6i %6i %6i %6i %6i %8.2f %9.5f %3i ; %6s-%6s-%6s-%6s\n"" % \ + (id1, id2, id3, id4, funct, ph, kd, pn, a1, a2, a3, a4) + oline = ""%6i %6i %6i %6i %6i ; %8.2f %9.5f %3i ; %6s-%6s-%6s-%6s\n"" % \ + (id1, id2, id3, id4, funct, ph, kd, pn, a1, a2, a3, a4) + temp.append(line) + otemp.append(oline) + temp.sort() + otemp.sort() + if temp: + if amb2gmx: + topText.append(headImpDih) + topText += temp + else: + itpText.append(headImpDih) + itpText += temp + oitpText.append(headImpDih) + oitpText += otemp + self.printDebug(""GMX improper dihedrals done"") + + if not self.direct: + for ion in ionsSorted: + topText.append(ionsDict[ion[2]]) + + if nWat: + topText.append(headWater) + + topText.append(headSystem % (self.baseName)) + topText.append(headMols) + otopText.append(headSystem % (self.baseName)) + otopText.append(headMols) + + if nSolute > 0: + topText.append("" %-16s %-6i\n"" % (self.baseName, nSolute)) + otopText.append("" %-16s %-6i\n"" % (self.baseName, nSolute)) + + if not self.direct: + for ion in ionsSorted: + topText.append("" %-16s %-6i\n"" % (ion[2].upper(), ion[1])) + + if nWat: + topText.append("" %-16s %-6i\n"" % ('WAT', nWat)) + + gmxDir = os.path.abspath('.') + topFileName = os.path.join(gmxDir, top) + topFile = open(topFileName, 'w') + topFile.writelines(topText) + + if not amb2gmx: + itpFileName = os.path.join(gmxDir, itp) + itpFile = open(itpFileName, 'w') + itpFile.writelines(itpText) + oitpFileName = os.path.join(gmxDir, oitp) + oitpFile = open(oitpFileName, 'w') + oitpFile.writelines(oitpText) + otopFileName = os.path.join(gmxDir, otop) + otopFile = open(otopFileName, 'w') + otopFile.writelines(otopText) + + def writeGroFile(self): + # print ""Writing GROMACS GRO file\n"" + self.printDebug(""writing GRO file"") + gro = self.baseName + '_GMX.gro' + gmxDir = os.path.abspath('.') + groFileName = os.path.join(gmxDir, gro) + groFile = open(groFileName, 'w') + groFile.write(head % (gro, date)) + groFile.write("" %i\n"" % len(self.atoms)) + count = 1 + for atom in self.atoms: + coords = [c * 0.1 for c in atom.coords] + resid = atom.resid + line = ""%5d%5s%5s%5d%8.3f%8.3f%8.3f\n"" % \ + (resid + 1, self.residueLabel[resid], atom.atomName, + count, coords[0], coords[1], coords[2]) + count += 1 + if count == 100000: + count = 0 + groFile.write(line) + if self.pbc: + boxX = self.pbc[0][0] * 0.1 + boxY = self.pbc[0][1] * 0.1 + boxZ = self.pbc[0][2] * 0.1 + vX = self.pbc[1][0] + # vY = self.pbc[1][1] + # vZ = self.pbc[1][2] + if vX == 90.0: + self.printDebug(""PBC triclinic"") + text = ""%11.5f %11.5f %11.5f\n"" % (boxX, boxY, boxZ) + elif round(vX, 2) == 109.47: + self.printDebug(""PBC octahedron"") + f1 = 0.471405 # 1/3 * sqrt(2) + f2 = 0.333333 * boxX + v22 = boxY * 2 * f1 + v33 = boxZ * f1 * 1.73205 # f1 * sqrt(3) + v21 = v31 = v32 = 0.0 + v12 = f2 + v13 = -f2 + v23 = f1 * boxX + text = ""%11.5f %11.5f %11.5f %11.5f %11.5f %11.5f %11.5f %11.5f %11.5f\n"" % \ + (boxX, v22, v33, v21, v31, v12, v32, v13, v23) + else: + self.printDebug(""Box size estimated"") + X = [a.coords[0] * 0.1 for a in self.atoms] + Y = [a.coords[1] * 0.1 for a in self.atoms] + Z = [a.coords[2] * 0.1 for a in self.atoms] + boxX = max(X) - min(X) # + 2.0 # 2.0 is double of rlist + boxY = max(Y) - min(Y) # + 2.0 + boxZ = max(Z) - min(Z) # + 2.0 + text = ""%11.5f %11.5f %11.5f\n"" % (boxX, boxY, boxZ) + groFile.write(text) + + def writeMdpFiles(self): + emMdp = """"""; to test +; grompp -f em.mdp -c {base}_GMX.gro -p {base}_GMX.top -o em.tpr -v +; mdrun -v -deffnm em +integrator = steep +nsteps = 500 +"""""".format(base=self.baseName) + mdMdp = """"""; to test +; grompp -f md.mdp -c em.gro -p {base}_GMX.top -o md.tpr +; mdrun -v -deffnm md +integrator = md +nsteps = 1000 +"""""".format(base=self.baseName) + emMdpFile = open('em.mdp', 'w') + mdMdpFile = open('md.mdp', 'w') + emMdpFile.write(emMdp) + mdMdpFile.write(mdMdp) + + def writeCnsTopolFiles(self): + autoAngleFlag = True + autoDihFlag = True + cnsDir = os.path.abspath('.') + + pdb = self.baseName + '_NEW.pdb' + par = self.baseName + '_CNS.par' + top = self.baseName + '_CNS.top' + inp = self.baseName + '_CNS.inp' + + pdbFileName = os.path.join(cnsDir, pdb) + parFileName = os.path.join(cnsDir, par) + topFileName = os.path.join(cnsDir, top) + inpFileName = os.path.join(cnsDir, inp) + + self.CnsTopFileName = topFileName + self.CnsInpFileName = inpFileName + self.CnsParFileName = parFileName + self.CnsPdbFileName = pdbFileName + + parFile = open(parFileName, 'w') + topFile = open(topFileName, 'w') + inpFile = open(inpFileName, 'w') + + self.printMess(""Writing NEW PDB file\n"") + self.writePdb(pdbFileName) + + self.printMess(""Writing CNS/XPLOR files\n"") + + # print ""Writing CNS PAR file\n"" + parFile.write(""Remarks "" + head % (par, date)) + parFile.write(""\nset echo=false end\n"") + + parFile.write(""\n{ Bonds: atomType1 atomType2 kb r0 }\n"") + lineSet = [] + for bond in self.bonds: + a1Type = bond.atoms[0].atomType.atomTypeName + '_' + a2Type = bond.atoms[1].atomType.atomTypeName + '_' + kb = 1000.0 + if not self.allhdg: + kb = bond.kBond + r0 = bond.rEq + line = ""BOND %5s %5s %8.1f %8.4f\n"" % (a1Type, a2Type, kb, r0) + lineRev = ""BOND %5s %5s %8.1f %8.4f\n"" % (a2Type, a1Type, kb, r0) + if line not in lineSet: + if lineRev not in lineSet: + lineSet.append(line) + for item in lineSet: + parFile.write(item) + + parFile.write(""\n{ Angles: aType1 aType2 aType3 kt t0 }\n"") + lineSet = [] + for angle in self.angles: + a1 = angle.atoms[0].atomType.atomTypeName + '_' + a2 = angle.atoms[1].atomType.atomTypeName + '_' + a3 = angle.atoms[2].atomType.atomTypeName + '_' + kt = 500.0 + if not self.allhdg: + kt = angle.kTheta + t0 = angle.thetaEq * radPi + line = ""ANGLe %5s %5s %5s %8.1f %8.2f\n"" % (a1, a2, a3, kt, t0) + lineRev = ""ANGLe %5s %5s %5s %8.1f %8.2f\n"" % (a3, a2, a1, kt, t0) + if line not in lineSet: + if lineRev not in lineSet: + lineSet.append(line) + for item in lineSet: + parFile.write(item) + + parFile.write(""\n{ Proper Dihedrals: aType1 aType2 aType3 aType4 kt per\ +iod phase }\n"") + lineSet = set() + for item in self.condensedProperDihedrals: + seq = '' + id_ = 0 + for dih in item: + # id_ = item.index(dih) + l = len(item) + a1 = dih.atoms[0].atomType.atomTypeName + '_' + a2 = dih.atoms[1].atomType.atomTypeName + '_' + a3 = dih.atoms[2].atomType.atomTypeName + '_' + a4 = dih.atoms[3].atomType.atomTypeName + '_' + kp = 750.0 + if not self.allhdg: + kp = dih.kPhi + p = dih.period + ph = dih.phase * radPi + if l > 1: + if id_ == 0: + line = ""DIHEdral %5s %5s %5s %5s MULT %1i %7.3f %4i %8\ +.2f\n"" % (a1, a2, a3, a4, l, kp, p, ph) + else: + line = ""%s %7.3f %4i %8.2f\n"" % (40 * "" "", kp, p, ph) + else: + line = ""DIHEdral %5s %5s %5s %5s %15.3f %4i %8.2f\n"" % (a1, + a2, a3, a4, kp, p, ph) + seq += line + id_ += 1 + lineSet.add(seq) + for item in lineSet: + parFile.write(item) + + parFile.write(""\n{ Improper Dihedrals: aType1 aType2 aType3 aType4 kt p\ +eriod phase }\n"") + lineSet = set() + for idh in self.improperDihedrals: + a1 = idh.atoms[0].atomType.atomTypeName + '_' + a2 = idh.atoms[1].atomType.atomTypeName + '_' + a3 = idh.atoms[2].atomType.atomTypeName + '_' + a4 = idh.atoms[3].atomType.atomTypeName + '_' + kp = 750.0 + if not self.allhdg: + kp = idh.kPhi + p = idh.period + ph = idh.phase * radPi + line = ""IMPRoper %5s %5s %5s %5s %13.1f %4i %8.2f\n"" % (a1, a2, a3, + a4, kp, p, ph) + lineSet.add(line) + + if self.chiral: + for idhc in self.chiralGroups: + _atc, neig, angle = idhc + a1 = neig[0].atomType.atomTypeName + '_' + a2 = neig[1].atomType.atomTypeName + '_' + a3 = neig[2].atomType.atomTypeName + '_' + a4 = neig[3].atomType.atomTypeName + '_' + kp = 11000.0 + p = 0 + ph = angle + line = ""IMPRoper %5s %5s %5s %5s %13.1f %4i %8.2f\n"" % (a1, a2, a3, + a4, kp, p, ph) + lineSet.add(line) + + for item in lineSet: + parFile.write(item) + + parFile.write(""\n{ Nonbonded: Type Emin sigma; (1-4): Emin/2 sigma }\n"") + for at in self.atomTypes: + A = at.ACOEF + B = at.BCOEF + atName = at.atomTypeName + '_' + if B == 0.0: + sigma = epAmber = ep2 = sig2 = 0.0 + else: + epAmber = 0.25 * B * B / A + ep2 = epAmber / 2.0 + sigma = math.pow((A / B), (1.0 / 6)) + sig2 = sigma + line = ""NONBonded %5s %11.6f %11.6f %11.6f %11.6f\n"" % (atName, + epAmber, sigma, ep2, sig2) + parFile.write(line) + parFile.write(""\nset echo=true end\n"") + + # print ""Writing CNS TOP file\n"" + topFile.write(""Remarks "" + head % (top, date)) + topFile.write(""\nset echo=false end\n"") + topFile.write(""\nautogenerate angles=%s dihedrals=%s end\n"" % + (autoAngleFlag, autoDihFlag)) + + topFile.write(""\n{ atomType mass }\n"") + for at in self.atomTypes: + atType = at.atomTypeName + '_' + mass = at.mass + line = ""MASS %-5s %8.3f\n"" % (atType, mass) + topFile.write(line) + + topFile.write(""\nRESIdue %s\n"" % self.residueLabel[0]) + topFile.write(""\nGROUP\n"") + + topFile.write(""\n{ atomName atomType Charge }\n"") + for at in self.atoms: + atName = at.atomName + atType = at.atomType.atomTypeName + '_' + charge = at.charge + line = ""ATOM %-5s TYPE= %-5s CHARGE= %8.4f END\n"" % (atName, atType, + charge) + topFile.write(line) + + topFile.write(""\n{ Bonds: atomName1 atomName2 }\n"") + for bond in self.bonds: + a1Name = bond.atoms[0].atomName + a2Name = bond.atoms[1].atomName + line = ""BOND %-5s %-5s\n"" % (a1Name, a2Name) + topFile.write(line) + + if not autoAngleFlag or 1: # generating angles anyway + topFile.write(""\n{ Angles: atomName1 atomName2 atomName3}\n"") + for angle in self.angles: + a1Name = angle.atoms[0].atomName + a2Name = angle.atoms[1].atomName + a3Name = angle.atoms[2].atomName + line = ""ANGLe %-5s %-5s %-5s\n"" % (a1Name, a2Name, a3Name) + topFile.write(line) + + if not autoDihFlag or 1: # generating angles anyway + topFile.write(""\n{ Proper Dihedrals: name1 name2 name3 name4 }\n"") + for item in self.condensedProperDihedrals: + for dih in item: + l = len(item) + a1Name = dih.atoms[0].atomName + a2Name = dih.atoms[1].atomName + a3Name = dih.atoms[2].atomName + a4Name = dih.atoms[3].atomName + line = ""DIHEdral %-5s %-5s %-5s %-5s\n"" % (a1Name, a2Name, + a3Name, a4Name) + break + topFile.write(line) + + topFile.write(""\n{ Improper Dihedrals: aName1 aName2 aName3 aName4 }\n"") + for dih in self.improperDihedrals: + a1Name = dih.atoms[0].atomName + a2Name = dih.atoms[1].atomName + a3Name = dih.atoms[2].atomName + a4Name = dih.atoms[3].atomName + line = ""IMPRoper %-5s %-5s %-5s %-5s\n"" % (a1Name, a2Name, a3Name, + a4Name) + topFile.write(line) + + if self.chiral: + for idhc in self.chiralGroups: + _atc, neig, angle = idhc + a1Name = neig[0].atomName + a2Name = neig[1].atomName + a3Name = neig[2].atomName + a4Name = neig[3].atomName + line = ""IMPRoper %-5s %-5s %-5s %-5s\n"" % (a1Name, a2Name, a3Name, + a4Name) + topFile.write(line) + + topFile.write(""\nEND {RESIdue %s}\n"" % self.residueLabel[0]) + + topFile.write(""\nset echo=true end\n"") + + # print ""Writing CNS INP file\n"" + inpFile.write(""Remarks "" + head % (inp, date)) + inpData = \ + """""" +topology + @%(CNS_top)s +end + +parameters + @%(CNS_par)s + nbonds + atom cdie shift eps=1.0 e14fac=0.4 tolerance=0.5 + cutnb=9.0 ctonnb=7.5 ctofnb=8.0 + nbxmod=5 vswitch wmin 1.0 + end + remark dielectric constant eps set to 1.0 +end + +flags exclude elec ? end + +segment name="" "" + chain + coordinates @%(NEW_pdb)s + end +end +coordinates @%(NEW_pdb)s +coord copy end + +! Remarks If you want to shake up the coordinates a bit ... + vector do (x=x+6*(rand()-0.5)) (all) + vector do (y=y+6*(rand()-0.5)) (all) + vector do (z=z+6*(rand()-0.5)) (all) + write coordinates output=%(CNS_ran)s end + +! Remarks RMS diff after randomisation and before minimisation +coord rms sele=(known and not hydrogen) end + +print threshold=0.02 bonds +print threshold=3.0 angles +print threshold=3.0 dihedrals +print threshold=3.0 impropers + +! Remarks Do Powell energy minimisation +minimise powell + nstep=250 drop=40.0 +end + +write coordinates output=%(CNS_min)s end +write structure output=%(CNS_psf)s end + +! constraints interaction (not hydro) (not hydro) end + +print threshold=0.02 bonds +print threshold=3.0 angles +print threshold=3.0 dihedrals +print threshold=3.0 impropers + +flags exclude * include vdw end energy end +distance from=(not hydro) to=(not hydro) cutoff=2.6 end + +! Remarks RMS fit after minimisation +coord fit sele=(known and not hydrogen) end + +stop +"""""" + dictInp = {} + dictInp['CNS_top'] = top + dictInp['CNS_par'] = par + dictInp['NEW_pdb'] = pdb + dictInp['CNS_min'] = self.baseName + '_NEW_min.pdb' + dictInp['CNS_psf'] = self.baseName + '_CNS.psf' + dictInp['CNS_ran'] = self.baseName + '_rand.pdb' + line = inpData % dictInp + inpFile.write(line) + if os.path.exists(self.obchiralExe): + self.printDebug(""chiralGroups %i"" % len(self.chiralGroups)) + else: + self.printDebug(""No 'obchiral' to process chiral atoms. Consider installing http://openbabel.org"") + + +class ACTopol(AbstractTopol): + + """""" + Class to build the AC topologies (Antechamber AmberTools) + """""" + + def __init__(self, inputFile, chargeType='bcc', chargeVal=None, + multiplicity='1', atomType='gaff', force=False, basename=None, + debug=False, outTopol='all', engine='tleap', allhdg=False, + timeTol=36000, qprog='sqm', ekFlag=None, verbose=True, + gmx45=False, disam=False, direct=False, is_sorted=False, chiral=False): + + self.debug = debug + self.verbose = verbose + self.gmx45 = gmx45 + self.disam = disam + self.direct = direct + self.sorted = is_sorted + self.chiral = chiral + self.inputFile = os.path.basename(inputFile) + self.rootDir = os.path.abspath('.') + self.absInputFile = os.path.abspath(inputFile) + if not os.path.exists(self.absInputFile): + self.printWarn(""input file doesn't exist"") + baseOriginal, ext = os.path.splitext(self.inputFile) + base = basename or baseOriginal + self.baseOriginal = baseOriginal + self.baseName = base # name of the input file without ext. + self.timeTol = timeTol + self.printDebug(""Max execution time tolerance is %s"" % elapsedTime(self.timeTol)) + self.ext = ext + if ekFlag == '""None""' or ekFlag is None: + self.ekFlag = '' + else: + self.ekFlag = '-ek %s' % ekFlag + self.extOld = ext + self.homeDir = self.baseName + '.acpype' + self.chargeType = chargeType + self.chargeVal = chargeVal + self.multiplicity = multiplicity + self.atomType = atomType + self.force = force + self.engine = engine + self.allhdg = allhdg + self.acExe = '' + dirAmber = os.getenv('AMBERHOME', os.getenv('ACHOME')) + if dirAmber: + for ac_bin in ['bin', 'exe']: + ac_path = os.path.join(dirAmber, ac_bin, 'antechamber') + if os.path.exists(ac_path): + self.acExe = ac_path + break + if not self.acExe: + self.acExe = _getoutput('which antechamber') or '' # '/Users/alan/Programmes/antechamber-1.27/exe/antechamber' + if not os.path.exists(self.acExe): + self.printError(""no 'antechamber' executable!"") + return None + self.tleapExe = _getoutput('which tleap') or '' + self.sleapExe = _getoutput('which sleap') or '' + self.parmchkExe = _getoutput('which parmchk') or '' + self.babelExe = _getoutput('which babel') or '' + if not os.path.exists(self.babelExe): + if self.ext != '.mol2' and self.ext != '.mdl': # and self.ext != '.mol': + self.printError(""no 'babel' executable; you need it if input is PDB"") + self.printError(""otherwise use only MOL2 or MDL file as input ... aborting!"") + sys.exit(1) + else: + self.printWarn(""no 'babel' executable, no PDB file as input can be used!"") + acBase = base + '_AC' + self.acBaseName = acBase + self.acXyzFileName = acBase + '.inpcrd' + self.acTopFileName = acBase + '.prmtop' + self.acFrcmodFileName = acBase + '.frcmod' + self.tmpDir = os.path.join(self.rootDir, '.acpype_tmp_%s' % os.path.basename(base)) + self.setResNameCheckCoords() + self.guessCharge() + acMol2FileName = '%s_%s_%s.mol2' % (base, chargeType, atomType) + self.acMol2FileName = acMol2FileName + self.charmmBase = '%s_CHARMM' % base + # check for which version of antechamber + if 'amber10' in self.acExe: + if qprog == 'sqm': + self.printWarn(""SQM is not implemented in AmberTools 1.2"") + self.printWarn(""Setting mopac for antechamber"") + qprog = 'mopac' + elif qprog == 'divcon': + if not os.path.exists(os.path.join(os.path.dirname(self.acExe), qprog)): + self.printWarn(""DIVCON is not installed"") + self.printWarn(""Setting mopac for antechamber"") + qprog = 'mopac' + elif 'amber1' in self.acExe: + if qprog == 'divcon': + self.printWarn(""DIVCON is not implemented in AmberTools > 1.3 anymore"") + self.printWarn(""Setting sqm for antechamber"") + qprog = 'sqm' + elif qprog == 'mopac': + if not os.path.exists(os.path.join(os.path.dirname(self.acExe), qprog)): + self.printWarn(""MOPAC is not installed"") + self.printWarn(""Setting sqm for antechamber"") + return None + qprog = 'sqm' + else: + self.printWarn(""Old version of antechamber. Strongly consider upgrading to AmberTools"") + self.printWarn(""Setting mopac for antechamber"") + qprog = 'mopac' + self.qFlag = qDict[qprog] + self.outTopols = [outTopol] + if outTopol == 'all': + self.outTopols = outTopols + self.acParDict = {'base': base, 'ext': ext[1:], 'acBase': acBase, + 'acMol2FileName': acMol2FileName, 'res': self.resName, + 'leapAmberFile': leapAmberFile, 'baseOrg': self.baseOriginal, + 'leapGaffFile': leapGaffFile} + + +class MolTopol(ACTopol): + + """""""" + Class to write topologies and parameters files for several applications + + http://amber.scripps.edu/formats.html (not updated to amber 10 yet) + + Parser, take information in AC xyz and top files and convert to objects + + INPUTS: acFileXyz and acFileTop + RETURN: molTopol obj or None + """""" + + def __init__(self, acTopolObj=None, acFileXyz=None, acFileTop=None, + debug=False, basename=None, verbose=True, gmx45=False, + disam=False, direct=False, is_sorted=False, chiral=False): + + self.chiral = chiral + self.obchiralExe = _getoutput('which obchiral') or '' + self.allhdg = False + self.debug = debug + self.gmx45 = gmx45 + self.disam = disam + self.direct = direct + self.sorted = is_sorted + self.verbose = verbose + self.inputFile = acFileTop + if acTopolObj: + if not acFileXyz: + acFileXyz = acTopolObj.acXyzFileName + if not acFileTop: + acFileTop = acTopolObj.acTopFileName + self._parent = acTopolObj + self.allhdg = self._parent.allhdg + self.debug = self._parent.debug + self.inputFile = self._parent.inputFile + if not os.path.exists(acFileXyz) and not os.path.exists(acFileTop): + self.printError(""Files '%s' and '%s' don't exist"") + self.printError(""molTopol object won't be created"") + return None + +# if not os.path.exists(self.obchiralExe) and self.chiral: +# self.printError(""no 'obchiral' executable, it won't work to store non-planar improper dihedrals!"") +# self.printWarn(""Consider installing http://openbabel.org"") + + self.xyzFileData = open(acFileXyz, 'r').readlines() + self.topFileData = open(acFileTop, 'r').readlines() + self.printDebug(""prmtop and inpcrd files loaded"") + +# self.pointers = self.getFlagData('POINTERS') + + self.getResidueLabel() + if len(self.residueLabel) > 1: + self.baseName = basename or os.path.splitext(os.path.basename(acFileTop))[0] # 'solute' + else: + self.baseName = basename or self.residueLabel[0] # 3 caps letters + if acTopolObj: + self.baseName = basename or acTopolObj.baseName + self.printDebug(""basename defined = '%s'"" % self.baseName) + + self.getAtoms() + + self.getBonds() + + self.getAngles() + + self.getDihedrals() + + self.getChirals() + if not os.path.exists(self.obchiralExe) and self.chiral: + self.printError(""no 'obchiral' executable, it won't work to store non-planar improper dihedrals!"") + self.printWarn(""Consider installing http://openbabel.org"") + elif self.chiral and not self.chiralGroups: + self.printWarn(""No chiral atoms found"") + + # self.setAtomPairs() + + # self.getExcludedAtoms() + + # a list of FLAGS from acTopFile that matter +# self.flags = ( 'POINTERS', 'ATOM_NAME', 'CHARGE', 'MASS', 'ATOM_TYPE_INDEX', +# 'NUMBER_EXCLUDED_ATOMS', 'NONBONDED_PARM_INDEX', +# 'RESIDUE_LABEL', 'BOND_FORCE_CONSTANT', 'BOND_EQUIL_VALUE', +# 'ANGLE_FORCE_CONSTANT', 'ANGLE_EQUIL_VALUE', +# 'DIHEDRAL_FORCE_CONSTANT', 'DIHEDRAL_PERIODICITY', +# 'DIHEDRAL_PHASE', 'AMBER_ATOM_TYPE' ) + + # Sort atoms for gromacs output. # JDC + if self.sorted: + self.printMess(""Sorting atoms for gromacs ordering.\n"") + self.sortAtomsForGromacs() + + +class Atom(object): + + """""" + Charges in prmtop file has to be divide by 18.2223 to convert to charge + in units of the electron charge. + To convert ACOEF and BCOEF to r0 (Ang.) and epsilon (kcal/mol), as seen + in gaff.dat for example; same atom type (i = j): + r0 = 1/2 * (2 * ACOEF/BCOEF)^(1/6) + epsilon = 1/(4 * A) * BCOEF^2 + To convert r0 and epsilon to ACOEF and BCOEF + ACOEF = sqrt(ep_i * ep_j) * (r0_i + r0_j)^12 + BCOEF = 2 * sqrt(ep_i * ep_j) * (r0_i + r0_j)^6 + = 2 * ACOEF/(r0_i + r0_j)^6 + where index i and j for atom types. + Coord is given in Ang. and mass in Atomic Mass Unit. + """""" + + def __init__(self, atomName, atomType, id_, resid, mass, charge, coord): + self.atomName = atomName + self.atomType = atomType + self.id = id_ + self.cgnr = id_ + self.resid = resid + self.mass = mass + self.charge = charge # / qConv + self.coords = coord + + def __str__(self): + return '' % (self.id, self.atomName, self.atomType) + + def __repr__(self): + return '' % (self.id, self.atomName, self.atomType) + + +class AtomType(object): + + """""" + AtomType per atom in gaff or amber. + """""" + + def __init__(self, atomTypeName, mass, ACOEF, BCOEF): + self.atomTypeName = atomTypeName + self.mass = mass + self.ACOEF = ACOEF + self.BCOEF = BCOEF + + def __str__(self): + return '' % self.atomTypeName + + def __repr__(self): + return '' % self.atomTypeName + + +class Bond(object): + + """""" + attributes: pair of Atoms, spring constant (kcal/mol), dist. eq. (Ang) + """""" + + def __init__(self, atoms, kBond, rEq): + self.atoms = atoms + self.kBond = kBond + self.rEq = rEq + + def __str__(self): + return '<%s, r=%s>' % (self.atoms, self.rEq) + + def __repr__(self): + return '<%s, r=%s>' % (self.atoms, self.rEq) + + +class Angle(object): + + """""" + attributes: 3 Atoms, spring constant (kcal/mol/rad^2), angle eq. (rad) + """""" + + def __init__(self, atoms, kTheta, thetaEq): + self.atoms = atoms + self.kTheta = kTheta + self.thetaEq = thetaEq # rad, to convert to degree: thetaEq * 180/Pi + + def __str__(self): + return '<%s, ang=%.2f>' % (self.atoms, self.thetaEq * 180 / Pi) + + def __repr__(self): + return '<%s, ang=%.2f>' % (self.atoms, self.thetaEq * 180 / Pi) + + +class Dihedral(object): + + """""" + attributes: 4 Atoms, spring constant (kcal/mol), periodicity, + phase (rad) + """""" + + def __init__(self, atoms, kPhi, period, phase): + self.atoms = atoms + self.kPhi = kPhi + self.period = period + self.phase = phase # rad, to convert to degree: kPhi * 180/Pi + + def __str__(self): + return '<%s, ang=%.2f>' % (self.atoms, self.phase * 180 / Pi) + + def __repr__(self): + return '<%s, ang=%.2f>' % (self.atoms, self.phase * 180 / Pi) + +if __name__ == '__main__': + t0 = time.time() + print(header) + + parser = optparse.OptionParser(usage=usage + epilog) + parser.add_option('-i', '--input', + action=""store"", + dest='input', + help=""input file name with either extension '.pdb', '.mdl' or '.mol2' (mandatory if -p and -x not set)"",) + parser.add_option('-b', '--basename', + action=""store"", + dest='basename', + help='a basename for the project (folder and output files)',) + parser.add_option('-x', '--inpcrd', + action=""store"", + dest='inpcrd', + help=""amber inpcrd file name (always used with -p)"",) + parser.add_option('-p', '--prmtop', + action=""store"", + dest='prmtop', + help=""amber prmtop file name (always used with -x)"",) + parser.add_option('-c', '--charge_method', + type='choice', + choices=['gas', 'bcc', 'user'], + action=""store"", + default='bcc', + dest='charge_method', + help=""charge method: gas, bcc (default), user (user's charges in mol2 file)"",) + parser.add_option('-n', '--net_charge', + action=""store"", + type='int', + default=0, + dest='net_charge', + help=""net molecular charge (int), for gas default is 0"",) + parser.add_option('-m', '--multiplicity', + action=""store"", + type='int', + default=1, + dest='multiplicity', + help=""multiplicity (2S+1), default is 1"",) + parser.add_option('-a', '--atom_type', + type='choice', + choices=['gaff', 'amber'], # , 'bcc', 'sybyl'] + action=""store"", + default='gaff', + dest='atom_type', + help=""atom type, can be gaff or amber (AMBER99+SB), default is gaff"",) + parser.add_option('-q', '--qprog', + type='choice', + choices=['mopac', 'sqm', 'divcon'], + action=""store"", + default='sqm', + dest='qprog', + help=""am1-bcc flag, sqm (default), divcon, mopac"",) + parser.add_option('-k', '--keyword', + action=""store"", + dest='keyword', + help=""mopac or sqm keyword, inside quotes"",) + parser.add_option('-f', '--force', + action=""store_true"", + dest='force', + help='force topologies recalculation anew',) + parser.add_option('-d', '--debug', + action=""store_true"", + dest='debug', + help='for debugging purposes, keep any temporary file created',) + parser.add_option('-o', '--outtop', + type='choice', + choices=['all'] + outTopols, + action=""store"", + default='all', + dest='outtop', + help=""output topologies: all (default), gmx, cns or charmm"",) + parser.add_option('-r', '--gmx45', + action=""store_true"", + dest='gmx45', + help='write GMX dihedrals for GMX 4.5',) + parser.add_option('-t', '--cnstop', + action=""store_true"", + dest='cnstop', + help='write CNS topology with allhdg-like parameters (experimental)',) + parser.add_option('-e', '--engine', + type='choice', + choices=['tleap', 'sleap'], + action=""store"", + default='tleap', + dest='engine', + help=""engine: tleap (default) or sleap (not fully matured)"",) + parser.add_option('-s', '--max_time', + action=""store"", + type='int', + default=36000, + dest='max_time', + help=""max time (in sec) tolerance for sqm/mopac, default is 10 hours"",) + parser.add_option('-y', '--ipython', + action=""store_true"", + dest='ipython', + help='start iPython interpreter',) + parser.add_option('-w', '--verboseless', + action=""store_false"", + default=True, + dest='verboseless', + help='print nothing',) + parser.add_option('-g', '--disambiguate', + action=""store_true"", + dest='disambiguate', + help='disambiguate lower and uppercase atomtypes in GMX top file',) + parser.add_option('-u', '--direct', + action=""store_true"", + dest='direct', + help=""for 'amb2gmx' mode, does a direct conversion, for any solvent"",) + parser.add_option('-l', '--sorted', + action=""store_true"", + dest='sorted', + help=""sort atoms for GMX ordering"",) + parser.add_option('-j', '--chiral', + action=""store_true"", + dest='chiral', + help=""create improper dihedral parameters for chiral atoms in CNS"",) + + options, remainder = parser.parse_args() + + amb2gmx = False + +# if options.chiral: +# options.cnstop = True + + if not options.input: + amb2gmx = True + if not options.inpcrd or not options.prmtop: + parser.error(""missing input files"") + elif options.inpcrd or options.prmtop: + parser.error(""either '-i' or ('-p', '-x'), but not both"") + + if options.debug: + text = ""Python Version %s"" % verNum + print('DEBUG: %s' % text) + + if options.direct and not amb2gmx: + parser.error(""option -u is only meaningful in 'amb2gmx' mode"") + + try: + if amb2gmx: + print(""Converting Amber input files to Gromacs ..."") + system = MolTopol(acFileXyz=options.inpcrd, acFileTop=options.prmtop, + debug=options.debug, basename=options.basename, + verbose=options.verboseless, gmx45=options.gmx45, + disam=options.disambiguate, direct=options.direct, + is_sorted=options.sorted, chiral=options.chiral) + system.printDebug(""prmtop and inpcrd files parsed"") + system.writeGromacsTopolFiles(amb2gmx=True) + else: + molecule = ACTopol(options.input, chargeType=options.charge_method, + chargeVal=options.net_charge, debug=options.debug, + multiplicity=options.multiplicity, atomType=options.atom_type, + force=options.force, outTopol=options.outtop, + engine=options.engine, allhdg=options.cnstop, + basename=options.basename, timeTol=options.max_time, + qprog=options.qprog, ekFlag='''""%s""''' % options.keyword, + verbose=options.verboseless, gmx45=options.gmx45, + disam=options.disambiguate, direct=options.direct, + is_sorted=options.sorted, chiral=options.chiral) + + if not molecule.acExe: + molecule.printError(""no 'antechamber' executable... aborting ! "") + hint1 = ""HINT1: is 'AMBERHOME' or 'ACHOME' environment variable set?"" + hint2 = ""HINT2: is 'antechamber' in your $PATH?\n What 'which antechamber' in your terminal says?\n 'alias' doesn't work for ACPYPE."" + molecule.printMess(hint1) + molecule.printMess(hint2) + sys.exit(1) + + molecule.createACTopol() + molecule.createMolTopol() + acpypeFailed = False + except: + exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() + print(""ACPYPE FAILED: %s"" % exceptionValue) + if options.debug: + traceback.print_tb(exceptionTraceback, file=sys.stdout) + acpypeFailed = True + + execTime = int(round(time.time() - t0)) + if execTime == 0: + msg = ""less than a second"" + else: + msg = elapsedTime(execTime) + print(""Total time of execution: %s"" % msg) + + if options.ipython: + try: + from IPython.Shell import IPShellEmbed # @UnresolvedImport @UnusedImport + except: + from IPython.frontend.terminal.embed import InteractiveShellEmbed as IPShellEmbed # @UnresolvedImport @Reimport + ipshell = IPShellEmbed() + ipshell() + + try: + rmtree(molecule.tmpDir) + except: + pass + if acpypeFailed: + sys.exit(1) + try: + os.chdir(molecule.rootDir) + except: + pass +","Python" +"Computational Biochemistry","t-/acpype","__init__.py",".py","0","0","","Python" +"Computational Biochemistry","t-/acpype","CcpnToAcpype.py",".py","11752","324","from shutil import rmtree +from acpype import elapsedTime, header, ACTopol +import time +import traceback +import sys +import os +import string +import random + +from ccpnmr.format.converters import PdbFormat +from ccpnmr.format.converters import Mol2Format + +def dirWalk(dir): + ""walk all files for a dir"" + for f in os.listdir(dir): + fullpath = os.path.abspath(os.path.join(dir, f)) + if os.path.isdir(fullpath) and not os.path.islink(fullpath): + for x in dirWalk(fullpath): # recurse into subdir + yield x + else: + yield fullpath + +def addMolPep(cnsPepPath, molName): + """""" + Add info about MOL in CNS topol*.pep file + input: cns pep file path to be modified and MOL name + """""" + txt = ""first IONS tail + %s end\nlast IONS head - %s end\n\n"" % (molName, molName) + pepFile = file(cnsPepPath).read() + if txt in pepFile: + print(""%s already added to %s"" % (molName, cnsPepPath)) + return False + pepFile = pepFile.splitlines(1) + pepFile.reverse() + for line in pepFile: + if line != '\n': + if 'SET ECHO' in line.upper(): + id = pepFile.index(line) + pepFile.insert(id + 1, txt) + break + pepFile.reverse() + nPepFile = open(cnsPepPath, 'w') + nPepFile.writelines(pepFile) + nPepFile.close() + print(""%s added to %s"" % (molName, cnsPepPath)) + return True + +def addMolPar(cnsParPath, molParPath): + """""" + Add parameters of MOL.par in CNS paralldhg*.pro file + input: cns par file path to be modified and MOL.par file + """""" + def formatLine(line, n): + items = line.split() + mult = eval(items[6]) + if len(items) < len(items) + (mult - 1) * 3: + for i in range(1, mult): + line += molFile[n + i] + n += (mult - 1) + return line, n + + pars = ['BOND', 'ANGLe', 'DIHEdral', 'IMPRoper', 'NONBonded'] + molName = os.path.basename(molParPath).split('_')[0] + txt = ""! Parameters for Heterocompound %s\n"" % molName + end = ""! end %s\n\n"" % molName + + parFile = file(cnsParPath).read() + if txt in parFile: + print(""%s already added to %s"" % (molName, cnsParPath)) + return False + + molFile = file(molParPath).readlines() + molList = [] + n = 0 + for n in range(len(molFile)): + line = molFile[n] + if line.strip()[0:4] in [x[0:4] for x in pars]: + if 'DIHE' in line and 'MULT' in line: + line, n = formatLine(line, n) + elif 'IMPR' in line and 'MULT' in line: + line, n = formatLine(line, n) + molList.append(line) + n += 1 + + parList = parFile.splitlines(1) + parList.reverse() + for line in parList: + if line != '\n': + if 'SET ECHO' in line.upper(): + id = parList.index(line) + break + parList.insert(id + 1, txt) + for line in molList: # NOTE: Check if pars are there, but using string size, need to be smarter + if pars[0][:4] in line: # BOND + parTxt = line[:16] + revParTxt = reverseParLine(parTxt) + if parTxt not in parFile and revParTxt not in parFile: + parList.insert(id + 1, line) + if pars[4][:4] in line: # NONB + if line[:16] not in parFile: + parList.insert(id + 1, line) + if pars[1][:4] in line: # ANGLe + parTxt = line[:23] + revParTxt = reverseParLine(parTxt) + if parTxt not in parFile and revParTxt not in parFile: + parList.insert(id + 1, line) + if pars[2][:4] in line or pars[3][:4] in line: # DIHE and IMPR + if line[:32] not in parFile: + parList.insert(id + 1, line) + parList.insert(id + 1, end) + + parList.reverse() + nParFile = open(cnsParPath, 'w') + nParFile.writelines(parList) + nParFile.close() + print(""%s added to %s"" % (molName, cnsParPath)) + return True + +def reverseParLine(txt): + lvec = txt.split() + head = lvec[0] + pars = lvec[1:] + pars.reverse() + for item in [ ""%6s"" % x for x in pars]: + head += item + return head + +def addMolTop(cnsTopPath, molTopPath): + """""" + Add topol of MOL.top in CNS topalldhg*.pro file + input: cns top file path to be modified and MOL.top file + """""" + keys = ['RESIdue', 'GROUP', 'ATOM', 'BOND', 'ANGLe', 'DIHEdral', 'IMPRoper'] + molName = os.path.basename(molTopPath).split('_')[0] + ions = '\nPRESidue IONS\nEND\n\n' + + txt = ""! Topol for Heterocompound %s\n"" % molName + end = ""\n"" + + topFile = file(cnsTopPath).read() + if txt in topFile: + print(""%s already added to %s"" % (molName, cnsTopPath)) + return False + + molFile = file(molTopPath).readlines() + molMass = [] + molTop = [] + + for line in molFile: + if line.strip()[0:4] == 'MASS': + molMass.append(line) + if line.strip()[0:4] in [x[0:4] for x in keys]: + molTop.append(line) + if line.strip()[0:3] == 'END': + molTop.append(line) + + topList = topFile.splitlines(1) + topList.reverse() + for line in topList: + if line != '\n': + if 'SET ECHO' in line.upper(): + id = topList.index(line) + break + + if ions not in topFile: + topList.insert(id + 1, ions) + + topList.insert(id + 1, txt) + for line in molMass: + if line not in topFile:#NOTE: comparing strings! + topList.insert(id + 1, line) + for line in molTop: + topList.insert(id + 1, line) + topList.insert(id + 1, end) + + topList.reverse() + nTopFile = open(cnsTopPath, 'w') + nTopFile.writelines(topList) + nTopFile.close() + print(""%s added to %s"" % (molName, cnsTopPath)) + return True + +class AcpypeForCcpnProject: + ''' + Class to take a Ccpn project, check if it has an + unusual chem comp and call ACPYPE API to generate + a folder with acpype results + usage: + acpypeProject = AcpypeForCcpnProject(ccpnProject) + acpypeProject.run(kw**) + acpypeDictFilesList = acpypeProject.acpypeDictFiles + returns a dict with list of the files inside chem chomp acpype folder + or None + ''' + + def __init__(self, project): + + self.project = project + self.heteroMols = None + self.acpypeDictFiles = None + + def getHeteroMols(self): + '''Return a list [] of chains obj''' + ccpnProject = self.project + maxNumberAtoms = 300 # MAXATOM in AC is 256, then it uses memory reallocation + other = [] + molSys = ccpnProject.findFirstMolSystem() + for chain in molSys.chains: + if chain.molecule.molType == 'other': + numRes = len(chain.residues) + if numRes == 1: + numberAtoms = [len(x.atoms) for x in chain.residues][0] + if numberAtoms > maxNumberAtoms: + print(""molecule with %i (> %i) atoms; skipped by acpype"" % (numberAtoms, maxNumberAtoms)) + else: + other.append(chain) + else: + print(""molType 'other', chain %s with %i residues; skipped by acpype"" % (chain, numRes)) + self.heteroMols = other + return other + + + def run(self, chain = None, chargeType = 'bcc', chargeVal = None, guessCharge = False, + multiplicity = '1', atomType = 'gaff', force = False, basename = None, + debug = False, outTopol = 'all', engine = 'tleap', allhdg = False, + timeTol = 36000, qprog = 'sqm', ekFlag = None, outType='mol2'): + + ccpnProject = self.project + + if chain: + other = [chain] + else: + other = self.getHeteroMols() + + if not other: + print(""WARN: no molecules entitled for ACPYPE"") + return None + + acpypeDict = {} + + for chain in other: + if chargeVal == None and not guessCharge: + chargeVal = chain.molecule.formalCharge +# pdbCode = ccpnProject.name + res = chain.findFirstResidue() + resName = res.ccpCode.upper() + if chargeVal == None: + print(""Running ACPYPE for '%s : %s' and trying to guess net charge"" % (resName, chain.molecule.name)) + else: + print(""Running ACPYPE for '%s : %s' with charge '%s'"" % (resName, chain.molecule.name, chargeVal)) + random.seed() + d = [random.choice(string.letters) for x in xrange(10)] + randString = """".join(d) + randString = 'test' + dirTemp = '/tmp/ccpn2acpype_%s' % randString + if not os.path.exists(dirTemp): + os.mkdir(dirTemp) + + if outType == 'mol2': + resTempFile = os.path.join(dirTemp, '%s.mol2' % resName) + else: + resTempFile = os.path.join(dirTemp, '%s.pdb' % resName) + + entry = ccpnProject.currentNmrEntryStore.findFirstEntry() + strucGen = entry.findFirstStructureGeneration() + refStructure = strucGen.structureEnsemble.sortedModels()[0] + + if outType == 'mol2': + mol2Format = Mol2Format.Mol2Format(ccpnProject) + mol2Format.writeChemComp(resTempFile, chemCompVar=chain.findFirstResidue().chemCompVar,coordSystem='pdb', minimalPrompts = True, forceNamingSystemName = 'XPLOR') + else: + pdbFormat = PdbFormat.PdbFormat(ccpnProject) + pdbFormat.writeCoordinates(resTempFile, exportChains = [chain], structures = [refStructure], minimalPrompts = True, forceNamingSystemName = 'XPLOR') + + origCwd = os.getcwd() + os.chdir(dirTemp) + + t0 = time.time() + print(header) + + try: + molecule = ACTopol(resTempFile, chargeType = chargeType, + chargeVal = chargeVal, debug = debug, multiplicity = multiplicity, + atomType = atomType, force = force, outTopol = outTopol, + engine = engine, allhdg = allhdg, basename = basename, + timeTol = timeTol, qprog = qprog, ekFlag = '''""%s""''' % ekFlag) + + if not molecule.acExe: + molecule.printError(""no 'antechamber' executable... aborting!"") + hint1 = ""HINT1: is 'AMBERHOME' or 'ACHOME' environment variable set?"" + hint2 = ""HINT2: is 'antechamber' in your $PATH?\n What 'which antechamber' in your terminal says?\n 'alias' doesn't work for ACPYPE."" + molecule.printMess(hint1) + molecule.printMess(hint2) + sys.exit(1) + + molecule.createACTopol() + molecule.createMolTopol() + acpypeFailed = False + except: + raise + _exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() + print(""ACPYPE FAILED: %s"" % exceptionValue) + if debug: + traceback.print_tb(exceptionTraceback, file = sys.stdout) + acpypeFailed = True + + execTime = int(round(time.time() - t0)) + + if execTime == 0: + msg = ""less than a second"" + else: + msg = elapsedTime(execTime) + try: rmtree(molecule.tmpDir) + except: raise + print(""Total time of execution: %s"" % msg) + if not acpypeFailed: + acpypeDict[resName] = [x for x in dirWalk(os.path.join(dirTemp, '%s.acpype' % resName))] + else: + acpypeDict[resName] = [] +# sys.exit(1) + + os.chdir(origCwd) + self.acpypeDictFiles = acpypeDict +","Python" +"Computational Biochemistry","t-/acpype","test/run_test_acpype_db_ligands.py",".py","4961","155","#!/usr/bin/env python + +# usage: ./run_test_acpype_db_ligands.py (opt: n=10 or ""['001','Rca']"") + +import sys, os, time + +from subprocess import Popen + +numCpu = 20 + +def elapsedTime(seconds, suffixes = ['y', 'w', 'd', 'h', 'm', 's'], add_s = False, separator = ' '): + """""" + Takes an amount of seconds and turns it into a human-readable amount of time. + """""" + # the formatted time string to be returned + if seconds == 0: + return '0s' + time = [] + + # the pieces of time to iterate over (days, hours, minutes, etc) + # - the first piece in each tuple is the suffix (d, h, w) + # - the second piece is the length in seconds (a day is 60s * 60m * 24h) + parts = [(suffixes[0], 60 * 60 * 24 * 7 * 52), + (suffixes[1], 60 * 60 * 24 * 7), + (suffixes[2], 60 * 60 * 24), + (suffixes[3], 60 * 60), + (suffixes[4], 60), + (suffixes[5], 1)] + + # for each time piece, grab the value and remaining seconds, and add it to + # the time string + for suffix, length in parts: + value = seconds / length + if value > 0: + seconds = seconds % length + time.append('%s%s' % (str(value), + (suffix, (suffix, suffix + 's')[value > 1])[add_s])) + if seconds < 1: + break + + return separator.join(time) + +def runConversionJobs(chemCompVarFiles, scriptName): + + _timeStamp = time.strftime(""%Y_%m_%d_%H_%M_%S"") + + startCode = 'start' + + currentChemCompVarFile = None + currentProcesses = {startCode: None} + currentJobOut = {} + currentIndex = -1 + endChemCompVarFile = chemCompVarFiles[-1] + + outputHandle = sys.__stdout__ + + while (currentProcesses): + + if startCode in currentProcesses.keys(): + del(currentProcesses[startCode]) + + if len(currentProcesses.keys()) < numCpu: + + tempIndex = currentIndex + 1 + for _i in range(currentIndex, currentIndex + numCpu - len(currentProcesses.keys())): + # Don't start a job if it's at the end! + if currentChemCompVarFile != endChemCompVarFile: + + chemCompVarFile = chemCompVarFiles[tempIndex] + + # + # TODO: ensure that stdout and stdin OK for this job!! Might want to reroute!! + # + + currentOutFile = chemCompVarFile.replace('.mol2', '.out') + jobOut = open(currentOutFile, 'w') + + varDir, varFile = os.path.split(chemCompVarFile) + os.chdir(varDir) + process = Popen(['nice', '-19', scriptName, '-i', varFile, '-d'], stdout = jobOut, stderr = jobOut) + + currentJobOut[chemCompVarFile] = jobOut + currentProcesses[chemCompVarFile] = process + currentChemCompVarFile = chemCompVarFile + + outputHandle.write(""\n*** Job %s started ***\n\n"" % chemCompVarFile) + + tempIndex += 1 + + # Allow jobs to start one by one... nicer for output + time.sleep(1) + + currentIndex = tempIndex - 1 + + time.sleep(3) + + # + # Check if finished + # + + for chemCompVarFile in currentProcesses.keys(): + + # Finished... + if currentProcesses[chemCompVarFile].poll() != None: + del(currentProcesses[chemCompVarFile]) + currentJobOut[chemCompVarFile].close() + del(currentJobOut[chemCompVarFile]) + outputHandle.write(""\n *** Job %s finished ***\n"" % chemCompVarFile) + if not currentProcesses: + currentProcesses = {startCode: None} + + outputHandle.flush() + +if __name__ == '__main__': + + t0 = time.time() + + chemCompVarFiles = [] + curDir = os.getcwd() + ccpCodes = os.listdir('other') + ccpCodes.sort() + + # Only run this on 'other'! + if len(sys.argv) > 1: + args = sys.argv[1:] + if args[0].startswith('n='): + num = int(args[0][2:]) + ccpCodes = ccpCodes[:num] + else: + args = list(set(eval(args[0]))) + args.sort() + ccpCodes = args + + for ccpCode in ccpCodes: + # HACK to restart after powercut + #if ccpCode < 'NA': + # continue + + ccvNames = os.listdir(os.path.join('other', ccpCode)) + + for ccvName in ccvNames: + if ccvName[-5:] == '.mol2' and not ccvName.count(""bcc_gaff""): + chemCompVarFiles.append(os.path.join(curDir, 'other', ccpCode, ccvName)) + + runConversionJobs(chemCompVarFiles, 'acpype') + execTime = int(round(time.time() - t0)) + msg = elapsedTime(execTime) + print(""Total time of execution: %s"" % msg) + print(""ALL DONE"") + +# nohup ./run_test_acpype_db_ligands.py & +# grep started nohup.out | wc -l ; grep finished nohup.out | wc -l # 17405 17405 +# grep -r ""FAILED: semi-QM taking"" other/* +# grep -r ""invalid"" other/* +","Python" +"Computational Biochemistry","t-/acpype","test/check_acpype.py",".py","25645","741","#!/usr/bin/env python +import sys #@UnusedImport +import os +from acpype import ACTopol +from acpype import _getoutput +import shutil +from glob import glob + +usePymol = True +ffType = 'amber' # gaff +cType = 'gas' #'gas' +debug = False + +water = ' -water none' + +print('usePymol: %s, ffType: %s, cType: %s' % (usePymol, ffType, cType)) + +tmpDir = '/tmp/testAcpype' + +delList = ['topol.top', 'posre.itp'] + +#create Dummy PDB +tpdb = '/tmp/tmp.pdb' +dummyLine = 'ATOM 1 N ALA A 1 -1.188 -0.094 0.463 1.00 0.00 N\n' +open(tpdb, 'w').writelines(dummyLine) +tempObj = ACTopol(tpdb, chargeVal = 0, verbose = False) + +# Binaries for ambertools +acExe = tempObj.acExe +tleapExe = tempObj.tleapExe +sanderExe = os.path.join(os.path.dirname(acExe), 'sander') +ambpdbExe = os.path.join(os.path.dirname(acExe), 'ambpdb') + +exePymol = '/sw/bin/pymol' + +# Binaries for gromacs +gpath = '/sw/' +gmxTopDir = gpath + ""share"" +pdb2gmx = gpath + 'bin/pdb2gmx' +grompp = gpath + 'bin/grompp' +mdrun = gpath + 'bin/mdrun' +g_energy = gpath + 'bin/g_energy' #'/sw/bin/g_energy' +gmxdump = gpath + 'bin/gmxdump' + +amberff = ""leaprc.ff99SB"" + +genPdbTemplate = \ +''' +source %(amberff)s +mol = sequence {N%(res1)s %(res)s C%(res1)s} +savepdb mol %(aai3)s.pdb +saveamberparm mol prmtop inpcrd +quit +''' + +spe_mdp = \ +"""""" +# Create SPE.mdp file #single point energy +cat << EOF >| SPE.mdp +define = -DFLEXIBLE +integrator = md +nsteps = 0 +dt = 0.001 +constraints = none +emtol = 10.0 +emstep = 0.01 +nstcomm = 1 +ns_type = simple +nstlist = 0 +rlist = 0 +rcoulomb = 0 +rvdw = 0 +Tcoupl = no +Pcoupl = no +gen_vel = no +nstxout = 1 +pbc = no +nstlog = 1 +nstenergy = 1 +nstvout = 1 +nstfout = 1 +nstxtcout = 1 +comm_mode = ANGULAR +continuation = yes +EOF +"""""" + +aa_dict = {'A':'ala', 'C':'cys', 'D':'asp', 'E':'glu', 'F':'phe', 'G':'gly', + 'H':'hie', 'J':'hip', 'O':'hid', 'I':'ile', 'K':'lys', 'L':'leu', + 'M':'met', 'N':'asn', 'P':'pro', 'Q':'gln', 'R':'arg', 'S':'ser', + 'T':'thr', 'V':'val', 'W':'trp', 'Y':'tyr'} + +#hisDictConv = {'HHH':['HIE', 'HISB'], 'JJJ':['HIP', 'HISH'], 'OOO':['HID', 'HISA']} + + +hisDictConv = {'HHH':['HIE', 'HISE'], 'JJJ':['HIP', 'HISH'], 'OOO':['HID', 'HISD']} + +pymolScript = 'aa_dict = %s' % str(aa_dict) + \ +''' +def build3(object_name, sequence, first_residue = ""1""): + if len(sequence): + codeNT, code, codeCT = sequence + cmd.fragment('nt_'+aa_dict[codeNT],object_name) + cmd.alter(object_name,'resi=""%s""'%first_residue) + cmd.edit(object_name+"" and name C"") + for code in sequence[1:-1]: + editor.attach_amino_acid(""pk1"",aa_dict[code]) + editor.attach_amino_acid(""pk1"",'ct_'+aa_dict[codeCT]) + cmd.edit() + +seqi=aa_dict.keys() + +count=0 + +cmd.delete('all') + +for aai in seqi: + aai3=3*aai + build3(aai3,aai3) + cmd.alter(aai3,""chain='%s'""%aai3) + cmd.translate([15*count,0,0],aai3) + cmd.sculpt_activate(aai3) + for n in range(100): + cmd.sculpt_iterate(aai3) + count=count+1 + aafile = aai3+'.pdb' + cmd.set('pdb_conect_all') + cmd.save(aafile,'all') + cmd.delete('all') +''' + +def pdebug(msg): + if debug: + print('DEBUG: %s' % msg) + +def perror(msg): + if debug: + print('ERROR: %s' % msg) + +def createAmberPdb(fpdb, opt): + '''pdb -> apdb (amber) + opt = 0 : pymol pdb to apdb + opt = 1 : ogpdb to apdb + ''' + fLines = file(fpdb).readlines() + fName = 'a' + fpdb + famb = open(fName, 'w') + for line in fLines: + if 'ATOM ' in line: + if opt == 0: + if 'AAA' not in fpdb: + line = line.replace(' HB3 ', ' HB1 ') + line = line.replace('CD1 ILE', 'CD ILE') + line = line.replace(' HG3 ', ' HG1 ') + line = line.replace(' HA3 GLY', ' HA1 GLY') + line = line.replace('HG13 ILE', 'HG11 ILE') + line = line.replace('HG13 ILE', 'HG11 ILE') + if line[22:26] == ' 3': + line = line.replace(' O ', ' OC1').replace(' OXT', ' OC2') + elif opt == 1: + if line[22:26] == ' 3': + line = line.replace(' O1 ', ' OC1').replace(' O2 ', ' OC2') + if line[22:26] == ' 1': + res = line[17:20] + line = line.replace('%s ' % res, 'N%s' % res) + if line[22:26] == ' 3': + res = line[17:20] + line = line.replace('%s ' % res, 'C%s' % res) + famb.write(line) ### pay attention here! + famb.close() + return fName + +def createAmberPdb3(fpdb): + '''Add N and C XXX --> NXXX, CXXX''' + fLines = file(fpdb).readlines() + fName = fpdb.replace('_', 'a') + famb = open(fName, 'w') + for line in fLines: + if 'ATOM ' in line: + if line[22:26] == ' 1': + res = line[17:20] + line = line.replace('%s ' % res, 'N%s' % res) + if line[22:26] == ' 3': + res = line[17:20] + line = line.replace('%s ' % res, 'C%s' % res) + famb.write(line) ### pay attention here! + famb.close() + return fName + +def createAmberPdb2(fpdb, opt): + ''' + use formatConverter + Add N and C XXX --> NXXX, CXXX and OC1 & OC2 + ''' + projectName = 'testImport' + if os.path.exists(projectName): + shutil.rmtree(projectName) + _fpdb = ""_%s"" % fpdb + + fLines = file(_fpdb).readlines() + fName = 'a' + fpdb + famb = open(fName, 'w') + for line in fLines: + if 'ATOM ' in line: + line = line.replace('CYS', 'CYN') + line = line.replace('LYS', 'LYP') + if opt == 0: + if line[22:26] == ' 3': + line = line.replace(' O ', ' OC1 ').replace(' OXT ', ' OC2 ') + elif opt == 1: + if line[22:26] == ' 3': + line = line.replace(' O1 ', ' OC1').replace(' O2 ', ' OC2') + if line[22:26] == ' 1': + res = line[17:20] + line = line.replace('%s ' % res, 'N%s' % res) + if line[22:26] == ' 3': + res = line[17:20] + line = line.replace('%s ' % res, 'C%s' % res) + famb.write(line) ### pay attention here! + famb.close() + return fName + +def createOldPdb2(fpdb): + '''using my own dict for e.g. 2HB = HB2 -> HB1''' + defHB1 = [' HB2', '2HB ', ' HB1'] + defHB2 = [' HB3', '3HB ', ' HB2'] + defHG1 = [' HG2', '2HG ', ' HG1'] + defHG2 = [' HG3', '3HG ', ' HG2'] + defHD1 = [' HD2', '2HD ', ' HD1'] + defHD2 = [' HD3', '3HD ', ' HD2'] + def1HG2 = ['HG21', '1HG2'] + def2HG2 = ['HG22', '2HG2'] + def3HG2 = ['HG23', '3HG2'] + + dictPdb2GmxAtomNames = {'ALA':(), 'VAL':() + , 'CYS':(defHB1, defHB2) + , 'ASP':(defHB1, defHB2) + , 'GLU':(defHB1, defHB2, defHG1, defHG2) + , 'PHE':(defHB1, defHB2) + , 'GLY':([' HA2 ', ' HA ', ' HA1 '], [' HA3', '3HA ', ' HA2']) + , 'HIE':(defHB1, defHB2) + , 'ILE':(['CD1', 'CD '], ['HG12', '2HG1', '1HG1'], ['HG13', '3HG1', '2HG1'], def1HG2, def2HG2, def3HG2, ['HD11', '1HD1', ' HD1'], ['HD12', '2HD1', ' HD2'], ['HD13', '3HD1', ' HD3']) + , 'HIP':(defHB1, defHB2) + , 'HID':(defHB1, defHB2) + , 'LYS':(defHB1, defHB2, defHG1, defHG2, defHD1, defHD2, [' HE2', '2HE ', ' HE1'], [' HE3', '3HE ', ' HE2']) + , 'LEU':(defHB1, defHB2) + , 'MET':(defHB1, defHB2, defHG1, defHG2) + , 'ASN':(defHB1, defHB2) + , 'PRO':(defHB1, defHB2, defHG1, defHG2, defHD1, defHD2, [' H3 ', '3H ', ' H1 ']) + , 'GLN':(defHB1, defHB2, defHG1, defHG2, ['HE21', '1HE2'], ['HE22', '2HE2']) + , 'ARG':(defHB1, defHB2, defHG1, defHG2, defHD1, defHD2) + , 'SER':(defHB1, defHB2) + , 'THR':(def1HG2, def2HG2, def3HG2) + , 'TRP':(defHB1, defHB2) + , 'TYR':(defHB1, defHB2) + } + fName = '_' + fpdb + fLines = file(fpdb).readlines() + aLines = [] + for line in fLines: + if 'ATOM ' in line: + aLines.append(line) + nRes = int(aLines[-1][22:26]) + nLines = [] + for line in aLines: + res = line[17:20] + nResCur = int(line[22:26]) + for item in dictPdb2GmxAtomNames.get(res): + #line = line.replace('%s %s' % (item[0], res), '%s %s' % (item[2], res)).replace('%s %s' % (item[1], res), '%s %s' % (item[2], res)) + atAim = item[-1] + for at in item[:-1]: + #print(at, atAim) + #print(line) + line = line.replace('%s' % at, '%s' % atAim) + #print(line) + if nResCur == nRes: + line = line.replace('O %s' % res, 'OC1 %s' % res) + line = line.replace('OXT %s' % res, 'OC2 %s' % res) + nLines.append(line) + file(fName, 'w').writelines(nLines) + return fName + +def parseTopFile(lista): + ''' lista = top file in list format + return a (dict,dict) with fields''' + defDict = {} + parDict = {} + for line in lista: + line = line.split(';')[0] + line = line.strip() + if line.startswith('#def'): + vals = line.split() + defDict[vals[1]] = map(eval, vals[2:]) + elif line and not line.startswith('#'): + if line.startswith('[ '): + flag = line.split()[1] + if not parDict.has_key(flag): + parDict[flag] = [] + else: + u = [] + t = line.split() + for i in t: + try: v = eval(i) + except: v = i + u.append(v) + parDict[flag].append(u) + return parDict, defDict + +def nbDict(lista): + tdict = {} + for line in lista: + line = line.split(';')[0] + line = line.strip() + if line and not line.startswith('#') and not line.startswith('['): + name, type_ = line.split()[0:2] + tdict[name] = type_ + return tdict + +def roundAllFloats(lista, l): + """"""Round to 3 decimals"""""" + nlista = [] + for ii in lista: + tt = ii[:l + 1] + for jj in ii[l + 1:]: + if jj > 100.0: + jj = round(jj, -1) + nn = round(jj, 3) + tt.append(nn) + nlista.append(tt) + return nlista + +def checkTopAcpype(res): + '''Compare acpype gmx itp against amber pdb2gmx results''' + os.chdir(tmpDir) + def addParam(l, item): + ''' l : index for bonded types + item : set of atomtypes''' + dict_ = {2:'bondtypes', 3:'angletypes', 4:'dihedraltypes'} + dType = {} # dict_ + for type_ in ffBon[0][dict_[l]]: + i = type_[:l + 1] + j = type_[l + 1:] + dType[str(i)] = j # dict_ {[atomtypes,funct] : parameters} + entries = [] + lNum = item[l] # funct + ent = [ffDictAtom[x] for x in item[:l]] # convert atomtypes ids to atomtypes names + rent = ent[:] + rent.reverse() + entries.append(ent + [lNum]) + entries.append(rent + [lNum]) + if l == 4: + if len(item) == 6: + par = ffBon[1][item[5]] + return par + tent = ent[:] + rtent = rent[:] + if lNum in [3, 9]: # dih proper + tent[0] = 'X' + entries.append(tent + [lNum]) + tent.reverse() + entries.append(tent + [lNum]) + tent[0] = 'X' + entries.append(tent + [lNum]) + tent.reverse() + entries.append(tent + [lNum]) + rtent[0] = 'X' + entries.append(rtent + [lNum]) + rtent.reverse() + entries.append(rtent + [lNum]) + if lNum in [1, 4]: # dih improp + tent[0] = 'X' + entries.append(tent + [lNum]) + tent[1] = 'X' + entries.append(tent + [lNum]) + rtent[0] = 'X' + entries.append(rtent + [lNum]) + rtent[1] = 'X' + entries.append(rtent + [lNum]) + found = False + for e in entries: + try: + par = dType[str(e)] + found = True + break + except: pass + if not found: + print(""%s %s %s not found in %s Bon"" % (dict_[l], ent, item, ffType)) + #print(item, e, par) + return par + + compareParameters = True + + agRes = parseTopFile(file('ag%s.top' % (res)).readlines()) + acRes = parseTopFile(file('ag%s.acpype/ag%s_GMX.itp' % (res, res)).readlines()) + _ffNb = aNb + ffBon = aBon + ffgRes = agRes + + atError = False + print("" ==> Comparing atomtypes AC x AMBER"") + + ffDictAtom = {} # dict link res atom numbers to amber atom types + for item in ffgRes[0]['atoms']: + i, j = item[:2] # id, at + ambat = j + ffDictAtom[i] = ambat + # compare atom types AC x Amber + acat = acRes[0]['atoms'][i - 1][1] + if ambat != acat: + print("" %i %s AC: %s x AMB: %s"" % (i, item[4], acat, ambat)) + atError = True + + if not atError: + print("" atomtypes OK"") + + acDictAtom = {} + for item in acRes[0]['atoms']: + i, j = item[:2] + acDictAtom[i] = j # dict for atom id -> atom type from acpype itp file + + + flags = [('pairs', 2), ('bonds', 2), ('angles', 3), ('dihedrals', 4)] #, ['dihedraltypes', 'angletypes', 'bondtypes'] + + for flag, l in flags: + print("" ==> Comparing %s"" % flag) + if flag != flags[0][0] and compareParameters: # not 'pairs' + agres = [] + tAgRes = ffgRes[0][flag] # e.g. dic 'bonds' from gmx top file + for item in tAgRes: + if flag == flags[1][0]: # 'bonds' + par = addParam(l, item) + elif flag == flags[2][0]: # 'angles' + par = addParam(l, item) + elif flag == flags[3][0]: # 'dihedrals', e.g. item = [2, 1, 5, 6, 9] + par = addParam(l, item) + if len(item) == 6: + item.pop() + agres.append(item + par) + if compareParameters: acres = acRes[0][flag] + else: + if flag == flags[3][0]: + agres = [x[:l + 1] for x in ffgRes[0][flag]] + else: agres = ffgRes[0][flag] + if compareParameters: acres = acRes[0][flag] + else: acres = [x[:l + 1] for x in acRes[0][flag]] + + act = acres[:] + agt = agres[:] + + if compareParameters: + if flag != flags[0][0]: + # round parameters + act = roundAllFloats(act, l) + agt = roundAllFloats(agt, l) + act2 = act[:] + agt2 = agt[:] + + if not compareParameters or flag == flags[0][0]: + act2 = act[:] + agt2 = agt[:] + + for ac in act: + if str(ac) in str(agt): + act2.remove(ac) + agt2.remove(ac) + else: + t = ac[:-1] + t.reverse() + acr = t + [ac[-1]] + if str(acr) in str(agt): + act2.remove(ac) + agt2.remove(acr) + + act3 = act2[:] + agt3 = agt2[:] + + if act2 and agt2: + # specially for dih since it may need to resort indexes + agl = {} + for ag in agt3: + t = ag[:-1] + t.sort() + ags = t + [ag[-1]] + agl[str(ags)] = ag + for ac in act2: + t = ac[:-1] + t.sort() + acs = t + [ac[-1]] + if str(acs) in str(agl.keys()): + act3.remove(ac) + agt3.remove(agl[str(acs)]) + + act4 = [] + agt4 = [] + + for ac in act3: + if ac[:5] not in tAgRes: + if flag == flags[3][0]: + if ac[6]: + act4.append(ac) + else: + act4.append(ac) + + tAcRes = [x[:5] for x in acres] + for ac in agt3: + if ag[:5] not in tAcRes: + act4.append(ac) + + if flag == flags[3][0]: + for ac in act4: + if not ac[6]: + act4.remove(ac) + for ag in agt4: + if not ag[6]: + agt4.remove(ac) + + if act4: + act4.sort() + print("" ac: "", act4) + if agt4: + agt4.sort() + print("" %sg: "" % ff, agt4) + + if not act4 and not agt4: + print("" %s OK"" % flag) + +def parseOut(out): + lines = out.splitlines() + #for line in lines: + count = 0 + while count < len(lines): + line = lines[count] + if 'WARNING' in line.upper(): + if 'will be determined based' in line: + pass + elif 'Problems reading a PDB file' in line: + pass + elif 'Open Babel Warning' in line: + pass + elif 'no charge value given' in line: + pass + elif 'audit log messages' in line: + pass + elif 'all CONECT' in line: + pass + elif 'with zero occupancy' in line: + pass + elif 'check: Warnings:' in line: + pass + else: + print(line) + elif 'Total charge' in line: + print("" "", line) + elif 'ERROR' in line.upper(): + if 'Fatal error' in line: + print(line, lines[count + 1]) + else: + print(line) + count += 1 + +def fixRes4Acpype(fpdb): + code = fpdb[2] + fLines = file(fpdb).readlines() + famb = open(fpdb, 'w') + for line in fLines: + if 'ATOM ' in line: + line = line[:17] + aa_dict[code].upper() + line[20:] + famb.write(line) + famb.close() + +def build_residues_tleap(): + """"""Build residues tripeptides with tleap and minimise with sander"""""" + mdin = '''Minimization\n&cntrl\nimin=1, maxcyc=200, ntmin=2, ntb=0, igb=0,cut=999,/\n''' + open('mdin', 'w').writelines(mdin) + seqi = aa_dict.keys() + for aai in seqi: + #if aai != 'H': continue + aai3 = 3 * aai + res = aa_dict.get(aai).upper() + res1 = res + leapDict = {'amberff' : amberff, 'res' : res, 'aai3' : aai3, 'res1':res1} + tleapin = genPdbTemplate % leapDict + open('tleap.in', 'w').writelines(tleapin) + cmd = ""%s -f tleap.in"" % (tleapExe) + _getoutput(cmd) + #cmd = ""%s -O; %s < restrt > %s.pdb; mv mdinfo %s.mdinfo"" % (sanderExe, ambpdbExe, aai3, aai3) # -i mdin -o mdout -p prmtop -c inpcrd"" % (sanderExe) + cmd = ""%s -O; %s < restrt > %s.pdb"" % (sanderExe, ambpdbExe, aai3) + _getoutput(cmd) + _getoutput('rm -f mdout mdinfo mdin restrt tleap.in prmtop inpcrd leap.log') + +def error(v1, v2): + '''percentage relative error''' + return abs(v1 - v2) / max(abs(v1), abs(v2)) * 100 + +def calcGmxPotEnerDiff(res): + def getEnergies(template): + cmd = template % cmdDict + pdebug(cmd) + out = _getoutput(cmd) + out = out.split('\n')[-nEner:] + dictEner = {} + for item in out: + k, v = item.replace(' Dih.', '_Dih.').replace(' (SR)', '_(SR)').replace('c En.', 'c_En.').replace(' (bar)', '_(bar)').replace('l E', 'l_E').split()[:2] + v = eval(v) + dictEner[k] = v + if 'Dih.' in k or 'Bell.' in k: + if 'Dihedral P+I' in list(dictEner.keys()): + dictEner['Dihedral P+I'] = dictEner['Dihedral P+I'] + v + else: + dictEner['Dihedral P+I'] = v + if 'Coulomb' in k or 'LJ' in k: + if 'TotalNonBonded' in list(dictEner.keys()): + dictEner['TotalNonBonded'] = dictEner['TotalNonBonded'] + v + else: + dictEner['TotalNonBonded'] = v + dictEner['Total_Bonded'] = dictEner.get('Potential') - dictEner.get('TotalNonBonded') + return dictEner + + os.chdir(tmpDir) + nEner = 9 # number of energy entries from g_energy + tEner = ' '.join([str(x) for x in range(1, nEner + 1)]) + open('SPE.mdp', 'w').writelines(spe_mdp) + cmdDict = {'pdb2gmx':pdb2gmx, 'grompp':grompp, 'mdrun':mdrun, 'res':res, + 'g_energy':g_energy, 'tEner':tEner, 'water':water, 'gmxdump':gmxdump} + + # calc Pot Ener for aXXX.pdb (AMB_GMX) + template = '''%(pdb2gmx)s -ff amber99sb -f a%(res)s.pdb -o a%(res)s_.pdb -p a%(res)s.top %(water)s + %(grompp)s -c a%(res)s_.pdb -p a%(res)s.top -f SPE.mdp -o a%(res)s.tpr -pp a%(res)sp.top + %(mdrun)s -v -deffnm a%(res)s + echo %(tEner)s | %(g_energy)s -f a%(res)s.edr + ''' + dictEnerAMB = getEnergies(template) + #print(dictEnerAMB) + + #calc Pot Ener for agXXX.acpype/agXXX.pdb (ACPYPE_GMX) + template = '''%(grompp)s -c ag%(res)s.acpype/ag%(res)s_NEW.pdb -p ag%(res)s.acpype/ag%(res)s_GMX.top -f SPE.mdp -o ag%(res)s.tpr -pp ag%(res)sp.top + %(mdrun)s -v -deffnm ag%(res)s + echo %(tEner)s | %(g_energy)s -f ag%(res)s.edr + ''' + dictEnerACPYPE = getEnergies(template) + #print(dictEnerACPYPE) + + order = ['LJ-14', 'LJ_(SR)', 'Coulomb-14', 'Coulomb_(SR)', 'TotalNonBonded', 'Potential', 'Angle', 'Bond', 'Proper_Dih.', 'Improper_Dih.', 'Dihedral P+I', 'Total_Bonded'] #sorted(dictEnerAMB.items()) + for k in order: + v = dictEnerAMB.get(k) + v2 = dictEnerACPYPE.get(k) + rerror = error(v2, v) + if rerror > 0.1: + print(""%15s %.3f %5.6f x %5.6f"" % (k, rerror, v2, v)) + else: + print(""%15s %.3f"" % (k, rerror)) + + cmd = ""%(gmxdump)s -s a%(res)s.tpr"" % cmdDict + amb = _getoutput(cmd) + cmd = ""%(gmxdump)s -s ag%(res)s.tpr"" % cmdDict + acp = _getoutput(cmd) + + #dihAmb = [x.split(']=')[-1] for x in amb.splitlines() if ('PIDIHS' in x or 'PDIHS' in x) and 'functype' in x ] + #dihAcp = [x.split(']=')[-1] for x in acp.splitlines() if ('PIDIHS' in x or 'PDIHS' in x) and 'functype' in x ] + + dihAmb = [x.split('PIDIHS')[-1][2:] for x in amb.splitlines() if ('PIDIHS' in x)] + dihAcp = [x.split('PIDIHS')[-1][2:] for x in acp.splitlines() if ('PIDIHS' in x)] + + dAcp = set(dihAcp).difference(set(dihAmb)) + dAmb = set(dihAmb).difference(set(dihAcp)) + rAcp = [' '.join(reversed(x.split())) for x in dAcp] + rAmb = [' '.join(reversed(x.split())) for x in dAmb] + ddAmb = sorted(dAmb.difference(rAcp)) + ddAcp = sorted(dAcp.difference(rAmb)) + if ddAmb: print('IDIH: Amb diff Acp', ddAmb) + if ddAcp: print('IDIH: Acp diff Amb', ddAcp) + + return dihAmb, dihAcp + + +if __name__ == '__main__': + + '''order: (tleap/EM or pymol) AAA.pdb -f-> _AAA.pdb -f-> aAAA.pdb --> (pdb2gmx) agAAA.pdb -f-> agAAA.pdb --> acpype + ''' + aNb = nbDict(file(gmxTopDir + '/gromacs/top/amber99sb.ff/ffnonbonded.itp').readlines()) + aBon = parseTopFile(file(gmxTopDir + '/gromacs/top/amber99sb.ff/ffbonded.itp').readlines()) + + tmpFile = 'tempScript.py' + if not os.path.exists(tmpDir): + os.mkdir(tmpDir) + os.chdir(tmpDir) + os.system('rm -fr \#* *.acpype') + #create res.pdb + if usePymol: + ff = open(tmpFile, 'w') + ff.writelines(pymolScript) + ff.close() + cmd = ""%s -qc %s"" % (exePymol, tmpFile) + os.system(cmd) + else: + build_residues_tleap() + listRes = os.listdir('.') # list all res.pdb + listRes = glob('???.pdb') + listRes.sort() + for resFile in listRes: + res, ext = os.path.splitext(resFile) # eg. res = 'AAA' + #if res != 'RRR': continue + if len(resFile) == 7 and ext == "".pdb"" and resFile[:3].isupper(): + print(""\nFile %s : residue %s"" % (resFile, aa_dict[res[0]].upper())) + + _pdb = createOldPdb2(resFile) # using my own dict + apdb = createAmberPdb3(_pdb) # create file aAAA.pdb with NXXX, CXXX + + # from ogpdb to amber pdb and top + agpdb = 'ag%s.pdb' % res # output name + agtop = 'ag%s.top' % res + cmd = ' %s -f %s -o %s -p %s -ff amber99sb %s' % (pdb2gmx, apdb, agpdb, agtop, water) + pdebug(cmd) + out = _getoutput(cmd) + #print(out) + #parseOut(out) + + # acpype on agpdb file + fixRes4Acpype(agpdb) + cv = None + #cmd = ""%s -dfi %s -c %s -a %s"" % (acpypeExe, agpdb, cType, ffType) + if res in ['JJJ', 'RRR'] and cType == 'bcc': cv = 3 #cmd += ' -n 3' # acpype failed to get correct charge + mol = ACTopol(agpdb, chargeType = cType, atomType = ffType, chargeVal = cv, + debug = False, verbose = debug, gmx45 = True) + mol.createACTopol() + mol.createMolTopol() + + #out = commands.getstatusoutput(cmd) + #parseOut(out[1]) + print(""Compare ACPYPE x GMX AMBER99SB topol & param"") + checkTopAcpype(res) + # calc Pot Energy + print(""Compare ACPYPE x GMX AMBER99SB Pot. Energy (|ERROR|%)"") + # calc gmx amber energies + dihAmb, dihAcp = calcGmxPotEnerDiff(res) + # calc gmx acpype energies + + os.system('rm -f %s/\#* posre.itp tempScript.py' % tmpDir) + os.system(""find . -name 'ag*GMX*.itp' | xargs grep -v 'created by acpype on' > standard_ag_itp.txt"") + +","Python" +"Computational Biochemistry","t-/acpype","test/script_test.sh",".sh","5872","178","#!/bin/sh + +rm -fr temp_test + +mkdir -p temp_test + +cd temp_test + +pdb2gmx=""/sw/bin/pdb2gmx"" +editconf=""/sw/bin/editconf"" +genbox=""/sw/bin/genbox"" +genion=""/sw/bin/genion"" +grompp=""/sw/bin/grompp"" +mdrun=""/sw/bin/mdrun"" +mrun="""" #""${mrun}"" + +echo ""\n#=#=# Test DMP from 1BVG for GROMACS #=#=#\n"" + +wget -c ""http://www.pdbe.org/download/1BVG"" -O 1BVG.pdb +grep 'ATOM ' 1BVG.pdb>| Protein.pdb +grep 'HETATM' 1BVG.pdb>| Ligand.pdb + +echo ""\n#=#=# CHECK 1BVG.pdb"" >| diff_out.log +diff 1BVG.pdb ../Data/1BVG.pdb >> diff_out.log + +# Edit Protein.pdb according to ffAMBER (http://ffamber.cnsm.csulb.edu/#usage) +sed s/PRO\ A\ \ \ 1/NPROA\ \ \ 1/g Protein.pdb | sed s/PRO\ B\ \ \ 1/NPROB\ \ \ 1/g \ +| sed s/PHE\ A\ \ 99/CPHEA\ \ 99/g | sed s/PHE\ B\ \ 99/CPHEB\ \ 99/g \ +| sed s/O\ \ \ CPHE/OC1\ CPHE/g | sed s/OXT\ CPHE/OC2\ CPHE/g \ +| sed s/HIS\ /HID\ /g | sed s/LYS\ /LYP\ /g | sed s/CYS\ /CYN\ /g >| ProteinAmber.pdb + +\cp Protein.pdb ProteinAmber.pdb + +# Process with pdb2gmx and define water +${pdb2gmx} -ff amber99sb -f ProteinAmber.pdb -o Protein2.pdb -p Protein.top -water spce -ignh + +# Generate Ligand topology file with acpype (GAFF) +acpype -i Ligand.pdb + +# Merge Protein2.pdb + updated Ligand_NEW.pdb -> Complex.pdb +grep -h ATOM Protein2.pdb Ligand.acpype/Ligand_NEW.pdb >| Complex.pdb + +# Edit Protein.top -> Complex.top +\cp Ligand.acpype/Ligand_GMX.itp Ligand.itp +\cp Protein.top Complex.top +# '#include ""Ligand.itp""' has to be inserted right after ffamber**.itp line and before Protein_*.itp line in Complex.top. +cat Complex.top | sed '/forcefield\.itp\""/a\ +#include ""Ligand.itp"" +' >| Complex2.top +echo ""Ligand 1"" >> Complex2.top +\mv Complex2.top Complex.top + +echo ""\n#=#=# CHECK parm99gaffff99SBparmbsc0File"" >> diff_out.log +# Generate Ligand topology file with acpype (AMBERbsc0) +acpype -i Ligand.pdb -a amber -b Ligand_Amber -c gas +diff -w /tmp/parm99gaffff99SB.dat ../../ffamber_additions/parm99SBgaff.dat >> diff_out.log + +echo ""\n#=#=# CHECK Ligand.itp"" >> diff_out.log +diff Ligand.itp ../Data/Ligand.itp >> diff_out.log + +# Setup the box and add water +${editconf} -bt triclinic -f Complex.pdb -o Complex.pdb -d 1.0 +${genbox} -cp Complex.pdb -cs ffamber_tip3p.gro -o Complex_b4ion.pdb -p Complex.top + +# Create em.mdp file +cat << EOF >| EM.mdp +define = -DFLEXIBLE +integrator = cg ; steep +nsteps = 200 +constraints = none +emtol = 1000.0 +nstcgsteep = 10 ; do a steep every 10 steps of cg +emstep = 0.01 ; used with steep +nstcomm = 1 +coulombtype = PME +ns_type = grid +rlist = 1.0 +rcoulomb = 1.0 +rvdw = 1.4 +Tcoupl = no +Pcoupl = no +gen_vel = no +nstxout = 0 ; write coords every # step +optimize_fft = yes +EOF + +# Create md.mdp file +cat << EOF >| MD.mdp +integrator = md +nsteps = 1000 +dt = 0.002 +constraints = all-bonds +nstcomm = 1 +ns_type = grid +rlist = 1.2 +rcoulomb = 1.1 +rvdw = 1.0 +vdwtype = shift +rvdw-switch = 0.9 +coulombtype = PME-Switch +Tcoupl = v-rescale +tau_t = 0.1 0.1 +tc-grps = protein non-protein +ref_t = 300 300 +Pcoupl = parrinello-rahman +Pcoupltype = isotropic +tau_p = 0.5 +compressibility = 4.5e-5 +ref_p = 1.0 +gen_vel = yes +nstxout = 2 ; write coords every # step +lincs-iter = 2 +DispCorr = EnerPres +optimize_fft = yes +EOF + +# Setup ions +${grompp} -f EM.mdp -c Complex_b4ion.pdb -p Complex.top -o Complex_b4ion.tpr +\cp Complex.top Complex_ion.top +echo 15| ${genion} -s Complex_b4ion.tpr -o Complex_b4em.pdb -neutral -conc 0.15 -p Complex_ion.top -norandom +\mv Complex_ion.top Complex.top + +# Run minimisaton +#${grompp} -f EM.mdp -c Complex_b4em.pdb -p Complex.top -o em.tpr +#${mdrun} -v -deffnm em + +# Run a short simulation +#${grompp} -f MD.mdp -c em.gro -p Complex.top -o md.tpr +#${mdrun} -v -deffnm md + +# or with openmpi, for a dual core +${grompp} -f EM.mdp -c Complex_b4em.pdb -p Complex.top -o em.tpr +${mrun} ${mdrun} -v -deffnm em +${grompp} -f MD.mdp -c em.gro -p Complex.top -o md.tpr +${mrun} ${mdrun} -v -deffnm md +# vmd md.gro md.trr + +echo ""\n#=#=# Test 'amb2gmx' Function on 1BVG #=#=#\n"" + +# Edit 1BVG.pdb and create ComplexAmber.pdb +sed s/HIS\ /HID\ /g 1BVG.pdb | sed s/H1\ \ PRO/H3\ \ PRO/g >| ComplexAmber.pdb + +# Create a input file with commands for tleap and run it +cat << EOF >| leap.in +verbosity 1 +source leaprc.ff99SB +source leaprc.gaff +loadoff Ligand.acpype/Ligand_AC.lib +loadamberparams Ligand.acpype/Ligand_AC.frcmod +complex = loadpdb ComplexAmber.pdb +solvatebox complex TIP3PBOX 10.0 +addions complex Na+ 23 +addions complex Cl- 27 +saveamberparm complex ComplexAmber.prmtop ComplexAmber.inpcrd +savepdb complex ComplexNAMD.pdb +quit +EOF +tleap -f leap.in >| leap.out + +# convert AMBER to GROMACS +acpype -p ComplexAmber.prmtop -x ComplexAmber.inpcrd + +echo ""\n#=#=# CHECK ComplexAmber_GMX.top & ComplexAmber_GMX.gro"" >> diff_out.log +diff ComplexAmber_GMX.top ../Data/ComplexAmber_GMX.top >> diff_out.log +diff ComplexAmber_GMX.gro ../Data/ComplexAmber_GMX.gro >> diff_out.log + +# Run EM and MD +${grompp} -f EM.mdp -c ComplexAmber_GMX.gro -p ComplexAmber_GMX.top -o em.tpr +${mrun} ${mdrun} -v -deffnm em +${grompp} -f MD.mdp -c em.gro -p ComplexAmber_GMX.top -o md.tpr +${mrun} ${mdrun} -v -deffnm md +# vmd md.gro md.trr + +echo ""############################"" +echo ""####### DIFF SUMMARY #######"" +echo ""############################"" +cat diff_out.log +","Shell" +"Computational Biochemistry","t-/acpype","test/compare_itps.py",".py","2942","98","#!/usr/bin/env python +import sys + +def parseItpFile(lista): + parDict = {} + for line in lista: + line = line.split(';')[0] + line = line.strip() + if line and not line.startswith('#'): + if line.startswith('[ '): + flag = line.split()[1] + if not parDict.has_key(flag): + parDict[flag] = [] + else: + u = [] + t = line.split() + for i in t: + try: v = eval(i) + except: v = i + u.append(v) + parDict[flag].append(u) + return parDict + +def compareDicts(d1,d2): + flags = [('pairs',2), ('bonds',2), ('angles',3), ('dihedrals',4)] + + for flag, l in flags: + print "" ==> Comparing %s"" % flag + flagD1 = [x[:l+1] for x in d1[flag]] + flagD2 = [x[:l+1] for x in d2[flag]] + + tempD1 = flagD1[:] + tempD2 = flagD2[:] + + _tempD1 = tempD1[:] + _tempD2 = tempD2[:] + + + for item in tempD1: + if str(item) in str(tempD2): + try: _tempD1.remove(item) + except: print ""\tDuplicate item %s in %s itp2"" % (`item`, flag) + try: _tempD2.remove(item) + except: print ""\tDuplicate item %s in %s itp1"" % (`item`, flag) + else: + t = item[:-1] + t.reverse() + itemRev = t + [item[-1]] + if str(itemRev) in str(tempD2): + try: _tempD1.remove(item) + except: print ""\tDuplicate item %s in %s itp2"" % (`item`, flag) + try: _tempD2.remove(itemRev) + except: print ""\tDuplicate item %s in %s itp1"" % (`item`, flag) + + tD1 = _tempD1[:] + tD2= _tempD2[:] + + if _tempD1 and _tempD2: + # specially for dih since it may need to resort indexes + i2l = {} + for i2 in tD2: + t = i2[:-1] + t.sort() + i2s = t + [i2[-1]] + i2l[str(i2s)] = i2 + for i1 in tD1: + t = i1[:-1] + t.sort() + i1s = t + [i1[-1]] + if str(i1s) in str(i2l.keys()): + tD1.remove(i1) + tD2.remove(i2l[str(i1s)]) + + if tD1: + tD1.sort() + print "" itp1: "", tD1 + if tD2: + tD2.sort() + print "" itp2: "", tD2 + + if not tD1 and not tD2: + print "" %s OK"" % flag + +if __name__ == '__main__': + if len(sys.argv) != 3: + print ""ERROR: it needs 2 itp file as input"" + print "" compare_itps.py file1.itp file2.itp"" + sys.exit() + itp1,itp2 = sys.argv[1:3] + + listItp1 = file(itp1).readlines() + listItp2 = file(itp2).readlines() + + dictItp1 = parseItpFile(listItp1) + dictItp2 = parseItpFile(listItp2) + + compareDicts(dictItp1, dictItp2) +","Python" +"Computational Biochemistry","t-/acpype","test/analyse_test_acpype_db_ligands.py",".py","30087","752","#!/usr/bin/env python +from commands import getoutput + +# Gmm with 200 atoms, biggest OK + +# usage: ./analyse_test_acpype_db_ligands.py (opt: n=10 or ""['001','Rca']"") + +# semi-QM = mopac (AT 1.2) or sqm (AT 1.3) + +import os, sys, fnmatch + +global id +id = 1 + +atomicDetailed = True + +checkChargeComparison = True + +results = {} + +ccpCodes = os.listdir('other') +ccpCodes.sort() + +groupResults = [ + [""dirs totally empty or at least missing one *.mol2 input files for either PDB or IDEAL)"", ""Dirs missing *.mol2 input files"", + []], + [""still running presumably"", ""Mols still running presumably"", + ['0 E, 0 W, ET , WT ']], + [""mols clean, no erros or warnings"",""Mols clean"", + ['0 E, 1 W, ET , WT _0','0 E, 2 W, ET , WT _0_1', + '0 E, 2 W, ET , WT _0_2','0 E, 3 W, ET , WT _0_1_2', + '0 E, 2 W, ET , WT _0_3','0 E, 3 W, ET , WT _0_1_3', + '0 E, 3 W, ET , WT _0_2_3','0 E, 4 W, ET , WT _0_1_2_3', + '0 E, 2 W, ET , WT _0_8']], + [""only guessCharge failed, but running semi-QM with charge = 0 finished fine"",""Mols only guessCharge failed"", + ['1 E, 1 W, ET _0, WT _0', '1 E, 2 W, ET _0, WT _0_1', + '1 E, 2 W, ET _0, WT _0_2', '1 E, 3 W, ET _0, WT _0_1_2']], + [""atoms in close contact"", ""Mols have atoms in close contact"", + ['0 E, 2 W, ET , WT _0_7', '0 E, 3 W, ET , WT _0_1_7', + '0 E, 3 W, ET , WT _0_2_7', '0 E, 3 W, ET , WT _0_3_7', + '0 E, 4 W, ET , WT _0_1_2_7', '0 E, 4 W, ET , WT _0_1_3_7', + '0 E, 4 W, ET , WT _0_2_3_7', '0 E, 5 W, ET , WT _0_1_2_3_7']], + [""irregular bonds"", ""Mols have irregular bonds"", + ['0 E, 2 W, ET , WT _0_5', '0 E, 3 W, ET , WT _0_1_5', + '0 E, 3 W, ET , WT _0_2_5', '0 E, 4 W, ET , WT _0_1_2_5']], + [""irregular bonds and atoms in close contact"", ""Mols have irregular bonds and atoms in close contact"", + ['0 E, 3 W, ET , WT _0_5_7', '0 E, 4 W, ET , WT _0_1_5_7', + '0 E, 4 W, ET , WT _0_2_5_7', '0 E, 5 W, ET , WT _0_1_2_5_7', + '0 E, 6 W, ET , WT _0_1_2_3_5_7', '0 E, 4 W, ET , WT _0_3_5_7']], + [""couldn't determine all parameters"", ""Mols have missing parameters"", + ['0 E, 3 W, ET , WT _0_2_4', '0 E, 3 W, ET , WT _0_1_4', '0 E, 2 W, ET , WT _0_4']], + [""missing parameters and atoms in close contact"", ""Mols have missing parameters and atoms in close contact"", + ['0 E, 4 W, ET , WT _0_1_4_7']], + [""missing parameters, irregular bonds and atoms in close contact"", ""Mols have missing parameters, irregular bonds and atoms in close contact"", + ['0 E, 5 W, ET , WT _0_2_4_5_7']], + [""missing parameters, irregular bonds, maybe wrong atomtype and atoms in close contact"", ""Mols have missing parameters, irregular bonds, maybe wrong atomtype and atoms in close contact"", + ['0 E, 5 W, ET , WT _0_4_5_6_7']], + [""no 'tmp', acpype did nothing at all"", ""Mols have no 'tmp'"", + ['1 E, 0 W, ET _7, WT ']], + [""atoms with same coordinates"", ""Mols have duplicated coordinates"", + ['1 E, 0 W, ET _1, WT ']], + [""maybe wrong atomtype"", ""Mols with maybe wrong atomtype"", + ['0 E, 2 W, ET , WT _0_6','0 E, 3 W, ET , WT _0_1_6','0 E, 4 W, ET , WT _0_1_3_6','0 E, 3 W, ET , WT _0_3_6']], + [""maybe wrong atomtype and atoms in close contact"", ""Mols with maybe wrong atomtype and atoms in close contact"", + ['0 E, 4 W, ET , WT _0_1_6_7', '0 E, 3 W, ET , WT _0_6_7', '0 E, 4 W, ET , WT _0_3_6_7']], + [""irregular bonds, maybe wrong atomtype and atoms in close contact"", ""Mols with irregular bonds, maybe wrong atomtype and atoms in close contact"", + ['0 E, 5 W, ET , WT _0_1_5_6_7']], + [""guessCharge failed and atoms in close contact"", ""Mols have guessCharge failed and atoms in close contact"", + ['1 E, 3 W, ET _0, WT _0_1_7', '1 E, 3 W, ET _0, WT _0_2_7', + '1 E, 4 W, ET _0, WT _0_1_2_7']], + [""guessCharge failed and missing parameters"", ""Mols have guessCharge failed and missing parameters"", + ['1 E, 2 W, ET _0, WT _0_4', '1 E, 3 W, ET _0, WT _0_1_4', + '1 E, 3 W, ET _0, WT _0_2_4', '1 E, 4 W, ET _0, WT _0_1_2_4']], + [""guessCharge failed and maybe wrong atomtype"", ""Mols have guessCharge failed and maybe wrong atomtype"", + ['1 E, 2 W, ET _0, WT _0_6', '1 E, 3 W, ET _0, WT _0_1_6', + '1 E, 3 W, ET _0, WT _0_2_6', '1 E, 4 W, ET _0, WT _0_1_2_6']], + [""guessCharge failed and irregular bonds"", ""Mols have guessCharge failed and irregular bonds"", + ['1 E, 3 W, ET _0, WT _0_2_5']], + [""guessCharge failed, missing parameters and maybe wrong atomtype"", ""Mols have guessCharge failed, missing parameters and maybe wrong atomtype"", + ['1 E, 3 W, ET _0, WT _0_4_6', '1 E, 4 W, ET _0, WT _0_1_4_6', + '1 E, 4 W, ET _0, WT _0_2_4_6']], + [""guessCharge failed, irregular bonds and maybe wrong atomtype"", ""Mols have guessCharge failed, irregular bonds and maybe wrong atomtype"", + ['1 E, 4 W, ET _0, WT _0_2_5_6', '0 E, 3 W, ET , WT _0_5_6']], + [""guessCharge failed, missing parameters and atoms in close contact"", ""Mols have guessCharge failed, missing parameters and atoms in close contact"", + ['1 E, 3 W, ET _0, WT _0_4_7', '1 E, 4 W, ET _0, WT _0_2_4_7']], + [""guessCharge failed, maybe wrong atomtype and atoms in close contact"", ""Mols have guessCharge failed, maybe wrong atomtype and atoms in close contact"", + ['1 E, 3 W, ET _0, WT _0_6_7', '1 E, 4 W, ET _0, WT _0_1_6_7', + '1 E, 4 W, ET _0, WT _0_2_6_7', '1 E, 5 W, ET _0, WT _0_1_2_6_7']], + [""guessCharge failed, irregular bonds and atoms in close contact"", ""Mols have guessCharge failed, irregular bonds and atoms in close contact"", + ['1 E, 4 W, ET _0, WT _0_2_5_7']], + [""guessCharge failed, irregular bonds, maybe wrong atomtype and atoms in close contact"", ""Mols have guessCharge failed, irregular bonds, maybe wrong atomtype and atoms in close contact"", + ['1 E, 5 W, ET _0, WT _0_1_5_6_7', '1 E, 5 W, ET _0, WT _0_2_5_6_7']], + [""atoms too close"", ""Mols have atoms too close"", + ['1 E, 0 W, ET _2, WT ']], + [""atoms too alone"", ""Mols have atoms too alone"", + ['1 E, 0 W, ET _3, WT ']], + [""tleap failed"", ""Mols have tleap failed"", + ['3 E, 1 W, ET _4_5_6, WT _0', '3 E, 2 W, ET _4_5_6, WT _0_1']], + [""tleap failed, maybe wrong atomtype"", ""Mols have tleap failed and maybe wrong atomtype"", + ['3 E, 3 W, ET _4_5_6, WT _0_1_6', '3 E, 2 W, ET _4_5_6, WT _0_6']], + [""semi-QM timeout"", ""Mols have semi-QM timeout"", + ['1 E, 2 W, ET _9, WT _0_1', '1 E, 1 W, ET _9, WT _0']], + [""semi-QM timeout and maybe wrong atomtype"", ""Mols have semi-QM timeout and maybe wrong atomtype"", + ['1 E, 3 W, ET _9, WT _0_1_6', '1 E, 2 W, ET _9, WT _0_6']], + [""guessCharge and tleap failed"", ""Mols have guessCharge and tleap failed"", + ['4 E, 1 W, ET _0_4_5_6, WT _0', '4 E, 2 W, ET _0_4_5_6, WT _0_1']], + [""guessCharge and tleap failed, maybe wrong atomtype"", ""Mols have guessCharge and tleap failed, maybe wrong atomtype"", + ['4 E, 2 W, ET _0_4_5_6, WT _0_6', '4 E, 3 W, ET _0_4_5_6, WT _0_1_6']], + [""guessCharge failed and semi-QM timeout"", ""Mols have guessCharge failed and semi-QM timeout"", + ['2 E, 1 W, ET _0_9, WT _0']], + [""atoms with same coordinates and maybe wrong atomtype"", ""Mols have atoms with same coordinates and maybe wrong atomtype"", + ['1 E, 1 W, ET _1, WT _6']], + [""atoms too close and maybe wrong atomtype"", ""Mols have atoms too close and maybe wrong atomtype"", + ['1 E, 1 W, ET _2, WT _6']], + [""atoms too alone and maybe wrong atomtype"", ""Mols have atoms too alone and maybe wrong atomtype"", + ['1 E, 1 W, ET _3, WT _6']], + [""atoms with same coordinates and too close"", ""Mols have atoms with same coordinates and too close"", + ['2 E, 0 W, ET _1_2, WT ']], + [""atoms with same coordinates and too alone"", ""Mols have atoms with same coordinates and too alone"", + ['2 E, 0 W, ET _1_3, WT ']], + [""atoms with same coordinates, too alone and maybe wrong atomtype"", ""Mols have atoms with same coordinates, too alone and maybe wrong atomtype"", + ['2 E, 1 W, ET _1_3, WT _6']], + [""atoms with same coordinates, too close and too alone"", ""Mols have atoms with same coordinates, too close and too alone"", + ['3 E, 0 W, ET _1_2_3, WT ']], + ] + +error_warn_messages = \ +''' + warnType 0 = 'no charge value given, trying to guess one...' + warnType 1 = ""In ..., residue name will be 'R instead of ... elsewhere"" + warnType 2 = 'residue label ... is not all UPPERCASE' + + # mild warning (need to be sure the charge guessed is correct) + warnType 3 = ""The unperturbed charge of the unit ... is not zero"" + + # serious warnings (topology not reliable): + warnType 4 = ""Couldn't determine all parameters"" + warnType 5 = 'There is a bond of ... angstroms between' + warnType 6 = 'atom type may be wrong' + warnType 7 = 'Close contact of ... angstroms between ...' + + #warnType 8 = 'no 'babel' executable, no PDB file as input can be used!' + warnType 8 = ""residue name will be 'MOL' instead of"" + warnType 9 = 'UNKNOWN WARN' + + errorType 0 = 'guessCharge failed' # (not so serious if only err or because semi-QM worked with charge Zero) + errorType 1 = 'Atoms with same coordinates in' + errorType 2 = 'Atoms TOO close' + errorType 3 = 'Atoms TOO alone' + errorType 4 = 'Antechamber failed' + errorType 5 = 'Parmchk failed' + errorType 6 = 'Tleap failed' + errorType 7 = ""No such file or directory: 'tmp'"" # can be bondtyes wrong or wrong frozen atom type + errorType 8 = 'syntax error' + errorType 9 = 'Semi-QM taking too long to finish' + errorType 10 = 'UNKNOWN ERROR' +''' + +totalPdbOkCount = 0 +totalIdealOkCount = 0 +totalIdealMol2Count = 0 +totalPdbMol2Count = 0 + +emptyDir = [] +failedPdb = [] +failedIdeal = [] +failedBoth = [] +missPdbMol2 = [] +missIdealMol2 = [] +multIdealMol2 = [] +multPdbMol2 = [] + +ET0 = [] +ET1 = [] +ET2 = [] +ET3 = [] +ET4 = [] +ET5 = [] +ET6 = [] +ET7 = set() +ET8 = set() +ET9 = [] + +WT3 = set() +WT4 = [] +WT5 = set() +WT6 = set() +WT7 = set() + +mapResults = {} + +execTime = {} + +compareCharges = set() +compareChargesOK = set() +# ==> Trying with net charge = 0 ... +# ==> ... charge set to 0 +# Overall charge: 0 + +SCFfailedList = [] + +def analyseFile(mol, structure, file): + """""" + mol = string molDir, e.g. 'Gnp' + structure = string 'pdb' or 'ideal' + file = string e.g. '10a/10a.none_neutral.pdb.out' + returns e.g. 'pdb: 0 E, 3 W, ET , WT _0_1_7' + """""" + _flagChargeType = None # if charge was guesed correctly ('Y') or tried with 0 ('Z' for Zero) + guessChargeValue = None + warnTypes = '' + errorTypes = '' + tmpFile = open(file, 'r') + content = tmpFile .readlines() + for line in content: + if 'WARNING: ' in line: + if ""no charge value given"" in line: + warnTypes += '_0' + elif ""residue name will be 'R"" in line: + warnTypes += '_1' + elif ""not all UPPERCASE"" in line: + warnTypes += '_2' + elif ""applications like CNS"" in line: + pass + elif ""The unperturbed charge of the"" in line: + warnTypes += '_3' + charge = round(float(line[44:54])) + WT3.add('%s: %s' % (mol, charge)) + elif ""Couldn't determine all parameters"" in line: + warnTypes += '_4' + WT4.append('%s_%s'% (mol, structure)) + elif ""There is a bond of"" in line: + warnTypes += '_5' + _dist = round(float(line[27:37])) + WT5.add('%s_%s' % (mol, structure)) + elif ' atom type of ' in line: + warnTypes += '_6' + WT6.add('%s_%s'% (mol, structure)) + #elif ""no 'babel' executable, no PDB"" in line: + elif ""residue name will be 'MOL' instead of"" in line: + warnTypes += '_8' + else: + print ""UNKNOWN WARN:"", file, line + warnTypes += '_9' + if 'Warning: Close contact of ' in line: + warnTypes += '_7' + WT7.add('%s_%s'% (mol, structure)) + + if 'ERROR: ' in line: + if 'guessCharge failed' in line: + errorTypes += '_0' + ET0.append('%s_%s'% (mol, structure)) + elif 'Atoms with same coordinates in' in line: + errorTypes += '_1' + ET1.append('%s_%s'% (mol, structure)) + elif 'Atoms TOO close' in line: + errorTypes += '_2' + ET2.append('%s_%s'% (mol, structure)) + elif 'Atoms TOO alone' in line: + errorTypes += '_3' + ET3.append('%s_%s'% (mol, structure)) + elif 'Antechamber failed' in line: + errorTypes += '_4' + ET4.append('%s_%s'% (mol, structure)) + elif 'Parmchk failed' in line: + errorTypes += '_5' + ET5.append('%s_%s'% (mol, structure)) + elif 'Tleap failed' in line: + errorTypes += '_6' + ET6.append('%s_%s'% (mol, structure)) + elif 'syntax error' in line: + errorTypes += '_8' + ET8.add('%s_%s'% (mol, structure)) + elif ""Use '-f' option if you want to proceed anyway. Aborting"" in line: + pass + else: + print ""UNKNOWN ERROR:"", file, line + errorTypes += '_10' + if ""No such file or directory: 'tmp'"" in line: + errorTypes += '_7' + ET7.add('%s_%s'% (mol, structure)) + if ""Semi-QM taking too long to finish"" in line: + errorTypes += '_9' + ET9.append('%s_%s'% (mol, structure)) + if ""Total time of execution:"" in line: + if execTime.has_key(mol): + #execTime[mol].append({structure:line[:-1].split(':')[1]}) + execTime[mol][structure] = line[:-1].split(':')[1] + else: + #execTime[mol] = [{structure:line[:-1].split(':')[1]}] + execTime[mol] = {structure:line[:-1].split(':')[1]} + # to compare charges from acpype out with input mol2 + if ""==> ... charge set to"" in line: + guessChargeValue = int(line.split('to')[1]) + _flagChargeType = 'Y' + #print ""*%s*"" % guessChargeValue + elif ""Trying with net charge ="" in line: + guessChargeValue = 0 + _flagChargeType = 'Z' + + if checkChargeComparison: + mol2FileName = file.replace('.out','.mol2') + mol2File = open(mol2FileName,'r').readlines() + for line in mol2File: + if ""# Overall charge:"" in line: + mol2Charge = int(line.split(':')[1]) + if guessChargeValue: + if mol2Charge != guessChargeValue: + compareCharges.add(""%s_%i_%i"" % (mol,mol2Charge, guessChargeValue)) + else: + compareChargesOK.add(""%s_%i"" % (mol, mol2Charge)) + # this excpetion should happen only if acpype early aborted for both outs + #if mol not in `compareChargesOK.union(compareCharges)`: + if mol not in `compareChargesOK` and mol not in `compareCharges`: + print ""!!!! Unable to compare. Failed to guess charge for"", mol, structure + + out = parseSummurisedLine(warnTypes, errorTypes) + if mapResults.has_key(out): + if mapResults[out].has_key(mol): + mapResults[out][mol].append(structure) + else: + mapResults[out][mol] = [structure] + else: + mapResults[out] = {mol:[structure]} + return out + +def parseSummurisedLine(warnTypes, errorTypes): + wt = list(set(warnTypes.split('_'))) + if wt != ['']: + wt = wt[1:] + wt.sort(cmp=lambda x,y: int(x)-int(y)) + warnTypes = '' + for i in wt: + if i: warnTypes += '_'+i + countWarn = warnTypes.count('_') + et = list(set(errorTypes.split('_'))) + et.sort() + errorTypes = '' + for j in et: + if j: errorTypes += '_'+j + countError = errorTypes.count('_') + return ""%i E, %i W, ET %s, WT %s"" % (countError, countWarn, errorTypes, warnTypes) + +def parseChargeList(WT, dList): + listOk = [] + for wt in WT: + if wt.split(':')[0] in dList: + listOk.append(wt) + listOk.sort() + return listOk + +def myComp(vx,vy): + ix = int(vx.split()[0]) + iy = int(vy.split()[0]) + tx = vx[-1:] + ty = vy[-1:] + if tx.isdigit(): x = int(tx) + else: x = 0 + if ty.isdigit(): y = int(ty) + else: y = 0 + + if ix>iy: + return 1 + elif ix==iy: + if x>y: + return 1 + elif x==y: + return 0 + else: + return -1 + else: + if x>y: + return 1 + elif x==y: + return 0 + else: + return -1 + +def sortList(lista,typeMess): + for mol, l in mapResults[typeMess].items(): + if len(l) == 2: + lista[0].append(mol) + elif len(l) == 1: + if l[0] == 'pdb': lista[1].append(mol) + elif l[0] == 'ideal': lista[2].append(mol) + else: + print ""problem with"", typeMess, mol, l + return lista + +def printResults(lista, subHead, header=None): + ''' + print results as + -------------------------------------------------------------------------------- + + *** For results [1], [2], [3], totally empty dirs (NO mol2 input files for either PDB or IDEAL): + + [1] Dirs missing pdb.mol2 input files for both PDB and Ideal: + 0 [] + + [2] Dirs missing pdb.mol2 input files with PDB ONLY, besides [1]: + 0 [] + + [3] Dirs missing pdb.mol2 input files with IDEAL ONLY, besides [1]: + 1 ['006'] + PDB Total: 0 of 20 (0.00%) + IDEAL Total: 1 of 20 (5.00%) + Total: 1 of 20 (5.00%) + -------------------------------------------------------------------------------- + ''' + global id + dList, pList, iList = lista + if not dList and not pList and not iList: + return 0 + dList.sort() + pList.sort() + iList.sort() + id1 = id + 1 + id2 = id + 2 + print 80*'-' + if header: + print ""\n*** For results [%i], [%i], [%i], %s:"" % (id,id1,id2,header) + print '\n[%i] %s for both PDB and Ideal:\n%i\t %s' % (id, subHead, len(dList), str(dList)) + print '\n[%i] %s with PDB ONLY, besides [%i]:\n%i\t %s' % (id1, subHead, id, len(pList), str(pList)) + print '\n[%i] %s with IDEAL ONLY, besides [%i]:\n%i\t %s' % (id2, subHead, id, len(iList), str(iList)) + pTotal = len(dList)+len(pList) + iTotal = len(dList)+len(iList) + total = pTotal+iTotal + per = total / (allTotal * 0.01) + perPdb = pTotal / (allTotal * 0.01) + perIdeal = iTotal / (allTotal * 0.01) + print ""PDB Total: %i of %i (%3.2f%%)"" % (pTotal, allTotal, perPdb) + print ""IDEAL Total: %i of %i (%3.2f%%)"" % (iTotal, allTotal, perIdeal) + print ""Total: %i of %i (%3.2f%%)"" % (total, allTotal, per) + print 80*'-' + id += 3 + return total + +def elapsedTime(seconds, suffixes=['y','w','d','h','m','s'], add_s=False, separator=' '): + """""" + Takes an amount of seconds and turns it into a human-readable amount of time. + """""" + # the formatted time string to be returned + if seconds == 0: + return '0s' + time = [] + + # the pieces of time to iterate over (days, hours, minutes, etc) + # - the first piece in each tuple is the suffix (d, h, w) + # - the second piece is the length in seconds (a day is 60s * 60m * 24h) + parts = [(suffixes[0], 60 * 60 * 24 * 7 * 52), + (suffixes[1], 60 * 60 * 24 * 7), + (suffixes[2], 60 * 60 * 24), + (suffixes[3], 60 * 60), + (suffixes[4], 60), + (suffixes[5], 1)] + + # for each time piece, grab the value and remaining seconds, and add it to + # the time string + for suffix, length in parts: + value = seconds / length + if value > 0: + seconds = seconds % length + time.append('%s%s' % (str(value), + (suffix, (suffix, suffix + 's')[value > 1])[add_s])) + if seconds < 1: + break + + return separator.join(time) + +def convertStringTime2Seconds(stringTime): + if 'less' in stringTime: + return 0 + vecTime = stringTime.split() + totalSec = 0 + for n in vecTime: + if 'h' in n: + totalSec += eval(n[:-1])*3600 + elif 'm' in n: + totalSec += eval(n[:-1])*60 + elif 's' in n: + totalSec += eval(n[:-1]) + return totalSec + +def locate(pattern, root=os.curdir): + '''Locate all files matching supplied filename pattern in and below + supplied root directory.''' + for path, _dirs, files in os.walk(os.path.abspath(root)): + for filename in fnmatch.filter(files, pattern): + yield os.path.join(path, filename) + +os.chdir('other') + +# Only run this on 'other'! +if len(sys.argv) > 1: + args = sys.argv[1:] + if args[0].startswith('n='): + num = int(args[0][2:]) + ccpCodes = ccpCodes[:num] + else: + args = list(set(eval(args[0]))) + args.sort() + ccpCodes = args + +for molDir in ccpCodes: +# files = os.listdir(molDir) + files = [] +# for dirpath, dirnames, filenames in os.walk(molDir): +# files += filenames + files = list(locate(""*"",molDir)) + results[molDir] = [] + pdb = False + ideal = False + pdbMol2 = False + idealMol2 = False + countPdbMol2 = 1 + countIdealMol2 = 1 + out1 = '' + out2 = '' + pass1 = False + pass2 = False + if not files: + emptyDir.append(molDir) + for file in files: + if 'pdb_NEW.pdb' in file: + pdb = True + results[molDir].append('pdb_OK') + totalPdbOkCount += 1 + elif 'ideal_NEW.pdb' in file: + ideal = True + results[molDir].append('ideal_OK') + totalIdealOkCount += 1 + elif 'ideal.out' in file: + out1 = analyseFile(molDir, 'ideal', os.path.join(molDir, file)) + results[molDir].append('ideal: '+out1) + elif 'pdb.out' in file: + out2 = analyseFile(molDir, 'pdb', os.path.join(molDir, file)) + results[molDir].append('pdb: '+out2) + elif '.ideal.mol2' in file: + if idealMol2: + countIdealMol2 +=1 + else: + idealMol2 = True + totalIdealMol2Count += 1 + elif '.pdb.mol2' in file: + if pdbMol2: + countPdbMol2 +=1 + else: + pdbMol2 = True + totalPdbMol2Count += 1 + elif "".ideal.acpype/sqm.out"" in file: + content = open(file, 'r').read() + if ""No convergence in SCF after"" in content: + SCFfailedList.append(""%s_%s"" % (molDir, 'ideal')) + elif "".pdb.acpype/sqm.out"" in file: + content = open(file, 'r').read() + if ""No convergence in SCF after"" in content: + SCFfailedList.append(""%s_%s"" % (molDir, 'pdb')) + if countIdealMol2 > 2: multIdealMol2.append(molDir) + if countPdbMol2 > 2: multPdbMol2.append(molDir) + if not pdbMol2: missPdbMol2.append(molDir) + if not idealMol2: missIdealMol2.append(molDir) + if not pdb: failedPdb.append(molDir) + if not ideal: failedIdeal.append(molDir) + if not pdb and not ideal: failedBoth.append(molDir) + +a, b, c = set(emptyDir), set(missPdbMol2), set(missIdealMol2) +pdbList = list(b.difference(a)) +idealList = list(c.difference(a)) +groupResults[0].append([emptyDir, pdbList, idealList]) + +c = 1 +while c < len(groupResults): + groupResults[c].append([[],[],[]]) + c += 1 + +keys = mapResults.keys() +keys.sort() +keys.sort(cmp=myComp) + +# Print messages that was not classified yet +groupMess = [] +for m in groupResults: + groupMess += m[2] +for typeMess in keys: + if typeMess not in groupMess: + size = len(typeMess) + txt = str(mapResults[typeMess]) + Nboth = txt.count(""['pdb', 'ideal']"") + txt.count(""['ideal', 'pdb']"") + Npdb = txt.count(""['pdb']"") + Nideal = txt.count(""['ideal']"") + print '*%s*%s%i %i %i' % (typeMess,(40-size)*' ', 2*Nboth, Npdb, Nideal) + +# Append to groupResults[index] a list of Mols belonging to this group +for typeMess in keys: + index = 0 + for group in groupResults: + msg = group[2] + if typeMess in msg: + groupResults[index][3] = sortList(groupResults[index][3], typeMess) + index += 1 + +allTotal = len(ccpCodes) *2 +jobsOK = [] # list of Mols that have at least a PDB or IDEAL clean: [[both],[pdb,ideal]] +totalTxt = '' +for group in groupResults: + header, subHead, dummy, lista = group + if ""Mols clean"" == subHead: + jobsOK = lista + subTot = printResults(lista, subHead, header) + if not subTot: continue + totalTxt += ""+ %i "" % subTot +totalTxt = totalTxt[2:] +sumVal = eval(totalTxt) +print ""%s= %s"" % (totalTxt, sumVal) + +#print results + +#print 'execTime', execTime + +#print 'jobsOK', jobsOK + +if atomicDetailed: + print ""\n>>> Detailed report per atom <<<\n"" + + if ET1: + print ""=>Mols have duplicated coordinates"" + for molLabel in ET1: + mol,structure = molLabel.split('_') + cmd = ""grep -e '^ATOM' %s/*%s.out"" % (mol, structure) + out = getoutput(cmd) + print ""# %s #"" % molLabel + print out,""\n"" + + if WT7: + print ""=>Mols have atoms in close contact"" + for molLabel in WT7: + mol,structure = molLabel.split('_') + cmd = ""grep -e '^Warning: Close contact of' %s/*%s.out"" % (mol, structure) + out = getoutput(cmd) + print ""# %s #"" % molLabel + print out,""\n"" + + if WT5: + print ""=>Mols have irregular bonds"" + for molLabel in WT5: + mol,structure = molLabel.split('_') + cmd = ""grep -A 1 -e '^WARNING: There is a bond of' %s/*%s.out"" % (mol, structure) + out = getoutput(cmd) + print ""# %s #"" % molLabel + print out,""\n"" + + if ET2: + print ""=>Mols have atoms too close"" + for molLabel in ET2: + mol,structure = molLabel.split('_') + cmd = ""grep -e '^ .*ATOM' %s/*%s.out"" % (mol, structure) + out = getoutput(cmd) + print ""# %s #"" % molLabel + print out,""\n"" + + if ET3: + print ""=>Mols have atoms too alone"" + for molLabel in ET3: + mol,structure = molLabel.split('_') + cmd = '''grep -e ""^\['ATOM"" %s/*%s.out''' % (mol, structure) + out = getoutput(cmd) + print ""# %s #"" % molLabel + print out,""\n"" + +# mols with MOL2 charge different from ACPYPE guessed charge +if compareCharges: + print ""\n>>> Mols with MOL2 charge different from ACPYPE guessed charge <<<\n"" + lCC = list(compareCharges) + lCC.sort() + print len(lCC), lCC + +maxExecTime = 0 +firstPass = True +maxMolTime = None +minMolTime = None +totalCleanExecTime = 0 +nJobs = 0 +listMolTime = [] +for mol in jobsOK[0]: + listMolTime.append([mol+'_pdb',execTime[mol]['pdb']]) + listMolTime.append([mol+'_ideal',execTime[mol]['ideal']]) +for mol in jobsOK[1]: + listMolTime.append([mol+'_pdb',execTime[mol]['pdb']]) +for mol in jobsOK[2]: + listMolTime.append([mol+'_ideal',execTime[mol]['ideal']]) + +#print 'listMolTime', listMolTime +#print jobsOK + +if SCFfailedList: + SCFfailedList.sort() + print ""\n>>>Mol Jobs whose sqm.out has 'No convergence in SCF'<<<\n"" + print len(SCFfailedList), SCFfailedList + molsOKinSCFfailedList = [] + for item in SCFfailedList: + if item in [x[0] for x in listMolTime]: + molsOKinSCFfailedList.append(item) + if molsOKinSCFfailedList: + molsOKinSCFfailedList.sort() + print ""\n>>>Mol Jobs whose sqm.out has 'No convergence in SCF' but finished OK<<<\n"" + print len(molsOKinSCFfailedList), molsOKinSCFfailedList + +for item in listMolTime: + mol, jtime = item + tSec = convertStringTime2Seconds(jtime) +# print 'tSec', tSec + if firstPass: + minExecTime = tSec + firstPass = False +# print 'firstPass' + if tSec >= maxExecTime: + maxExecTime = tSec + maxMolTime = mol + if tSec <= minExecTime: + minExecTime = tSec + minMolTime = mol + totalCleanExecTime += tSec + nJobs += 1 + +print ""\n>>> Time Job Execution Summary <<<\n"" +if listMolTime: + #print maxExecTime, minExecTime + print ""Number of clean jobs:"", nJobs + print ""Longest job: Mol='%s', time= %s"" % (maxMolTime, elapsedTime(maxExecTime)) + print ""Fatest job: Mol='%s', time= %s"" % (minMolTime, elapsedTime(minExecTime)) + print ""Average time of execution per clean job: %s"" % elapsedTime(totalCleanExecTime/nJobs) +else: + print ""NO time stats available for clean jobs"" + +# Global average exec time +totalGlobalExecTime = 0 +nGJobs = 0 +for item in execTime.items(): + mol, tDict = item + if tDict.has_key('pdb'): + totalGlobalExecTime += convertStringTime2Seconds(tDict['pdb']) + nGJobs += 1 + if tDict.has_key('ideal'): + totalGlobalExecTime += convertStringTime2Seconds(tDict['ideal']) + nGJobs += 1 +print ""\nTotal number of jobs:"", nGJobs +if nGJobs: + print ""Global average time of execution per job: %s"" % elapsedTime(totalGlobalExecTime/nGJobs) + +# mols with charge not 0 +#print WT3 +","Python"