14 Commits

Author SHA1 Message Date
33ddc0079d add new type to xvg converter 2016-01-19 18:18:10 +03:00
2c44b229ee rewrite trajectory format to store coordinates 2015-11-01 00:10:42 +03:00
ae9957b621 remove O3 flag 2014-12-29 03:48:06 +03:00
703ab513c0 add dynamic-hb.py 2014-12-10 06:13:42 +03:00
96b642c12a update pkgbild 2014-12-09 01:29:16 +03:00
7f328e7746 fix #1
some edit of python files
2014-12-06 01:07:15 +03:00
f7e9ea8049 fix path 2014-06-13 16:40:47 +04:00
7ffb0de47d change default averaging time to 1 2014-06-13 16:28:43 +04:00
e1badd963f add combine-qti 2014-06-13 16:26:24 +04:00
f27efd5325 fix error 2014-06-12 16:59:42 +04:00
3081f79a32 add xvg2csv 2014-06-12 16:03:50 +04:00
c35b81ded0 added hb-select script 2014-04-10 11:13:39 +04:00
2a02a497e3 added get-dipole 2014-03-28 21:37:53 +04:00
071affe7ad fixed building library 2014-01-29 04:46:39 +04:00
22 changed files with 703 additions and 64 deletions

104
combine-qti/combine-qti.py Executable file
View File

@ -0,0 +1,104 @@
#!/usr/bin/python2
# combine-qti
# Copyright (C) 2014 Evgeniy Alekseev <esalexeev@gmail.com>
#
# 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 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, see <http://www.gnu.org/licenses/>.
import argparse, os
def readData(file):
"""function to read data"""
windows = 0
data = []
# preread
with open (file, "r") as input:
for line in input:
if (line.split('\t')[0] == "<windows>"):
windows = int(line.split('\t')[1].strip())
with open (file, "r") as input:
for window in range(windows):
for line in input:
if (line.strip() == "<table>"):
data.append("<table>\n")
break
elif (line.strip() == "<multiLayer>"):
data.append("<multiLayer>\n")
break
for line in input:
if (line.strip() == '</table>'):
data.append("</table>\n")
break
elif (line.strip() == '</multiLayer>'):
data.append("</multiLayer>\n")
break
data.append(line)
return windows, data
def printHeader(file, windowsNum=1):
"""function to print header"""
iter = 0
suffix = ""
while (os.path.exists(file + suffix)):
suffix = ".%i" % (iter)
iter = iter + 1
if (suffix != ""):
os.rename(file, file + suffix)
with open(file, "w") as output:
output.write("QtiPlot 0.9.8 project file\n")
output.write("<scripting-lang>\tPython\n")
output.write("<windows>\t%i\n" % (windowsNum))
def printData(file, data):
"""function to print data"""
with open(file, "a") as output:
for line in data:
output.write(line)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description = 'Combine several *.qti files into one')
parser.add_argument('-d', '--directory', dest = 'dir',
help = 'Directory with input files or use --input', action = 'store', default = False)
parser.add_argument('-i', '--input', dest = 'input',
help = 'Input files, comma separated', action = 'store', default = False)
parser.add_argument('-o', '--output', dest = 'output',
help = 'Output file', action = 'store', default = False)
args = parser.parse_args()
input = []
if (args.dir):
if (os.path.isdir(args.dir)):
input = [os.path.join(args.dir, file) for file in os.listdir(args.dir) if (os.path.splitext(file)[1] == ".qti")]
else:
if (args.input):
for file in args.input.split(','):
if (os.path.isfile(file)): input.append(file)
output = args.output
if (not input) or (not output):
print ("Files are not set")
exit()
totalWindows = 0
totalData = []
for file in input:
windows, data = readData(file)
totalWindows = totalWindows + windows
totalData.append(data)
printHeader(output, totalWindows)
for data in totalData:
printData(output, data)

109
dynamic-hb/dynamic-hb.py Normal file
View File

@ -0,0 +1,109 @@
#!/usr/bin/python
import argparse
import os
def calculate(splited, system):
"""function to calculate results"""
matrix = []
for i in range(system['mols']):
matrix.append(0)
for file in splited:
for aggl in file:
matrix[len(aggl)-1] += 1
results = {}
while matrix[-1] == 0:
matrix.pop(-1)
for i, item in enumerate(matrix, start = 1):
results[i] = item
summ = 0
for i in results:
if i == 1: continue
results[i] = i * results[i] / (system['steps'] * system['mols'])
summ += results[i]
results[1] = 1.0 - summ
return results
def parse_file(splited):
"""function to parse input file"""
for file in splited:
for agl in file:
for i, molecule in enumerate(agl):
agl[i] = [int(molecule.split('=')[0]), [int(conn) for conn in molecule.split('=')[1].split(',') if conn]]
return splited
def print_result(output, matrix):
"""function to print result to file"""
with open(output, 'w') as out:
out.write("| n | p |\n-----------------\n")
for i in matrix:
out.write(" %7i %7.5f \n" % (i, matrix[i]))
out.write("-----------------\n")
def read_file(input_file):
"""function to read file from statgen"""
file = open(input_file).read()
if not file.startswith("statgen"):
print("It is not a statgen file")
exit(2)
prepare = file.split("\n")
system = {'steps': 0, 'mols': 0}
while not prepare[-1].startswith("SUMMARY STATISTIC"):
statistic = prepare.pop(-1)
if not statistic.startswith(" 1"): continue
values = [float(item) for item in statistic.split()]
system['steps'] = int(round(values[1] / values[2], 0))
system['mols'] = int(round(values[2] / values[3], 0))
prepare.pop(-1)
splited = '\n'.join(prepare).split("FILE")[1:]
for i, item in enumerate(splited):
text = item.split("AGL")[1:]
for j, agl in enumerate(text):
text[j] = [single for single in agl.split("\n")[1:] if single]
text[-1].pop(-1)
splited[i] = text
return splited, system
def select_aggl(splited, step):
"""function to select agglomerates"""
for i, file in enumerate(splited):
first = (i - step) if (i - step) > 0 else 0
last = (i + step) if (i + step) < (len(splited) - 1) else (len(splited) - 1)
for j, aggl in enumerate(file):
for k, mol in enumerate(aggl):
table = []
for other_file in splited[first:last]:
for aggl_other in other_file:
if not mol[0] in [other_single[0] for other_single in aggl_other]: continue
table.extend(mols for other_single in aggl_other for mols in other_single[1] if other_single[0] == mol[0])
for l, conn in enumerate(mol[1]):
if table.count(conn) == last - first: continue
splited[i][j][k][1].pop(l)
if len(mol[1]) == 0:
splited[i][j].pop(k)
if len(aggl) == 0:
splited[i].pop(j)
return splited
if __name__ == "__main__":
parser = argparse.ArgumentParser(description = "Sort agglomerates using dynamic criteria")
parser.add_argument('input', help = "file from statgen")
parser.add_argument('-s', '--step', type = int, help = "step to check agglomerates",
default = 1)
parser.add_argument('-o', '--output', help = "output file", default = "dhb-output.dat")
args = parser.parse_args()
if not os.path.isfile(args.input):
print("Could not find file %s" % args.input)
exit(1)
splited, system = read_file(args.input)
splited = parse_file(splited)
matrix = calculate(select_aggl(splited, args.step), system)
print_result(args.output, matrix)

70
get_dipole/get-dipole.py Executable file
View File

@ -0,0 +1,70 @@
#!/usr/bin/python2
import argparse, math
def get_aver_dipole(dipole):
"""function to get average dipole moment"""
aver_dipole = math.sqrt((dipole[0] * dipole[0] +
dipole[1] * dipole[1] +
dipole[2] * dipole[2]))
aver_dipole = round(aver_dipole, 4)
return aver_dipole
def get_charges(file_name):
"""function to get charges from GROMACS files"""
charges = {}
with open(file_name, 'r') as input_file:
for line in input_file:
try:
charges[line.split()[0]] = float(line.split()[2])
except:
pass
return charges
def get_coordinates(file_name):
"""function to get coordinates from PDB"""
coords = []
with open(file_name, 'r') as input_file:
for line in input_file:
if ((line[0:4] == "ATOM") or (line[0:6] == "HETATM")):
coords.append({"type":line.split()[2], "coords":[float(line[30:38]), float(line[38:46]), float(line[46:54])]})
return coords
def get_dipole(charges, coords):
"""function to get dipole moment"""
dipole = [0.0, 0.0, 0.0]
for atom in coords:
dipole[0] = dipole[0] + charges[atom["type"]] * atom["coords"][0]
dipole[1] = dipole[1] + charges[atom["type"]] * atom["coords"][1]
dipole[2] = dipole[2] + charges[atom["type"]] * atom["coords"][2]
dipole[0] = math.fabs(round(16.0218 * dipole[0] / 3.3356, 4))
dipole[1] = math.fabs(round(16.0218 * dipole[1] / 3.3356, 4))
dipole[2] = math.fabs(round(16.0218 * dipole[2] / 3.3356, 4))
return dipole
if __name__ == "__main__":
parser = argparse.ArgumentParser(description = 'Calculate dipole moment from PDB')
parser.add_argument('-i', '--input', dest = 'input',
help = 'File with charges', action = 'store')
parser.add_argument('-c', '--coord', dest = 'coord',
help = 'File with coordinates', action = 'store')
parser.add_argument('-v', '--vector', dest = 'vector',
help = 'Return vector', action = 'store_true', default = False)
args = parser.parse_args()
if ((not args.input) or (not args.coord)):
print "Input files are not set"
exit()
charges = get_charges(args.input)
coords = get_coordinates(args.coord)
if (args.vector):
print get_dipole(charges, coords)
else:
print get_aver_dipole(get_dipole(charges, coords))

70
hb-select/hb-select.py Executable file
View File

@ -0,0 +1,70 @@
#!/usr/bin/python2
import argparse
def readAtoms(file):
"""function to read *gro file"""
atoms = {}
with open(file, 'r') as coordFile:
coordFile.readline()
num = int(coordFile.readline())
for i in range(num):
line = coordFile.readline()
resNum = int(line[0:5])
atomNum = int(line[15:20])
atoms[atomNum] = resNum
return atoms
def readHb(files):
"""function to read *.ndx file"""
hbs = []
start = False
for file in files:
with open(file, 'r') as ndxFile:
for line in ndxFile:
if (line[0:9] == "[ hbonds_"):
start = True
continue
elif (line.count('[') > 0):
start = False
continue
elif (start):
donor = int(line[0:7])
hydrogen = int(line[7:14])
acceptor = int(line[14:21])
if (hbs.count([donor, hydrogen, acceptor]) == 0):
hbs.append([donor, hydrogen, acceptor])
return hbs
def selectHb(atoms, hbs):
"""funtion to select hydrogen bond"""
selectedHbs = []
for hb in hbs:
if ((atoms[hb[0]] - atoms[hb[2]]) > 5):
selectedHbs.append(hb)
return selectedHbs
def printToFile(selectedHbs, file):
"""function to print results"""
with open(file, 'w') as ndxFile:
ndxFile.write("[ sel_hbs ]\n")
for hb in selectedHbs:
ndxFile.write("%7i%7i%7i\n" % (hb[0], hb[1], hb[2]))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description = 'Select hidrogen bond from GROMACS index file')
parser.add_argument('-i', '--input', dest = 'input',
help = '*.gro file', action = 'store')
parser.add_argument('-n', '--ndx', dest = 'ndx',
help = '*.ndx files, comma separated', action = 'store')
parser.add_argument('-o', '--output', dest = 'output',
help = 'output *.ndx file', action = 'store')
args = parser.parse_args()
atoms = readAtoms(args.input)
hbs = readHb(args.ndx.split(','))
selectedHbs = selectHb(atoms, hbs)
printToFile(selectedHbs, args.output)

View File

@ -46,7 +46,7 @@ if ( CMAKE_COMPILER_IS_GNUCXX )
set (ADD_CXX_FLAGS "-Wall")
set (CMAKE_CXX_FLAGS "-O0 ${ADD_CXX_FLAGS}")
set (CMAKE_CXX_FLAGS_DEBUG "-g -O0")
set (CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG")
set (CMAKE_CXX_FLAGS_RELEASE "-O2 -DNDEBUG")
elseif ( MSVC )
set (ADD_CXX_FLAGS "/W4")
set (CMAKE_CXX_FLAGS "${ADD_CXX_FLAGS}")
@ -67,4 +67,4 @@ endforeach ()
# set docs file
if (ADD_DOCS)
include (docs.cmake)
endif ()
endif ()

View File

@ -1,17 +1,17 @@
# Author: Evgeniy "arcanis" Alexeev <esalexeev@gmail.com>
# Maintainer: Evgeniy "arcanis" Alexeev <esalexeev@gmail.com>
# Author: Evgeniy "arcanis" Alexeev <arcanis.arch at gmail dot com>
# Maintainer: Evgeniy "arcanis" Alexeev <arcanis.arch at gmail dot com>
pkgname=mathmech
pkgver=1.2.0
pkgrel=1
pkgrel=2
pkgdesc="Software package for analysis of molecular dynamics trajectories"
arch=(any)
arch=('i686' 'x86_64')
url="http://arcan1s.github.io/projects/moldyn"
license=('Beerware')
depends=('qt4' 'qwt')
depends=('qwt')
makedepends=('cmake' 'automoc4')
source=(https://github.com/arcan1s/moldyn/releases/download/mm-${pkgver}/${pkgname}-${pkgver}-src.zip)
md5sums=('f3f01c7eefdedf23b4eadfbf59058332')
md5sums=('de893eee2230269b10099c5fd925502b')
_cmakekeys="-DCMAKE_INSTALL_PREFIX=/usr
-DQWT_INCLUDE_PATH=/usr/include/qwt
-DQWT_LIBRARY_PATH=/usr/lib
@ -25,7 +25,7 @@ prepare() {
mkdir "${srcdir}/build"
}
build () {
build() {
cd "${srcdir}/build"
cmake ${_cmakekeys} ../
make
@ -34,6 +34,6 @@ build () {
package() {
cd "${srcdir}/build"
make DESTDIR="${pkgdir}" install
install -Dm644 "${srcdir}/COPYING" "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"
install -Dm644 "${srcdir}/COPYING" "${pkgdir}/usr/share/licenses/${pkgname}/COPYING"
}

40
mathmech/PKGBUILD-mingw Normal file
View File

@ -0,0 +1,40 @@
# Author: Evgeniy "arcanis" Alexeev <arcanis.arch at gmail dot com>
# Maintainer: Evgeniy "arcanis" Alexeev <arcanis.arch at gmail dot com>
pkgname=mathmech
pkgver=1.2.0
pkgrel=2
pkgdesc="Software package for analysis of molecular dynamics trajectories"
arch=('any')
url="http://arcan1s.github.io/projects/moldyn"
license=('Beerware')
depends=('mingw-w64-qwt')
makedepends=('mingw-w64-cmake' 'automoc4')
source=(https://github.com/arcan1s/moldyn/releases/download/mm-${pkgver}/${pkgname}-${pkgver}-src.zip)
md5sums=('46d8e1a3d6bc30d5b0b57ccf485986b1')
_cmakekeys="-DCMAKE_INSTALL_PREFIX=/usr
-DQWT_INCLUDE_PATH=/usr/x86_64-w64-mingw32/qwt
-DQWT_LIBRARY_PATH=/usr/x86_64-w64-mingw32/lib
-DMM_PREFIX=mm_
-DADD_DOCS:BOOL=1
-DADD_INCLUDE:BOOL=1
-DCMAKE_BUILD_TYPE=Release"
prepare() {
[[ -d ${srcdir}/build ]] && rm -rf "${srcdir}/build"
mkdir "${srcdir}/build"
}
build() {
unset LDFLAGS
cd "${srcdir}/build"
x86_64-w64-mingw32-cmake ${_cmakekeys} ../
make
}
package() {
cd "${srcdir}/build"
make DESTDIR="${pkgdir}" install
install -Dm644 "${srcdir}/COPYING" "${pkgdir}/usr/share/licenses/${pkgname}/COPYING"
}

View File

@ -27,8 +27,6 @@
int error_checking (const char *aglinp, const system_info _system_info, const char *input,
const char *output)
{
if ((_system_info.cell[0] == 0.0) || (_system_info.cell[1] == 0.0) || (_system_info.cell[2] == 0.0))
return 11;
if (input[0] == '#')
return 12;
if (output[0] == '#')

View File

@ -81,11 +81,10 @@ int main(int argc, char *argv[])
sprintf (tmp_str, "%s Evgeniy Alekseev aka arcanis\n", tmp_str);
sprintf (tmp_str, "%s E-mail : esalexeev@gmail.com\n\n", tmp_str);
sprintf (tmp_str, "%sUsage:\n", tmp_str);
sprintf (tmp_str, "%smm_agl -a AGL_INP -i INPUT -c X,Y,Z -o OUTPUT [ -l LOGFILE ] [ -q ] [ -h ]\n\n", tmp_str);
sprintf (tmp_str, "%smm_agl -a AGL_INP -i INPUT -o OUTPUT [ -l LOGFILE ] [ -q ] [ -h ]\n\n", tmp_str);
sprintf (tmp_str, "%sParametrs:\n", tmp_str);
sprintf (tmp_str, "%s -a - input file with agglomerates (in format statgen)\n", tmp_str);
sprintf (tmp_str, "%s -i - input file with coordinates\n", tmp_str);
sprintf (tmp_str, "%s -c - cell size (float), A\n", tmp_str);
sprintf (tmp_str, "%s -o - output file name\n", tmp_str);
sprintf (tmp_str, "%s -l - log enable\n", tmp_str);
sprintf (tmp_str, "%s -q - quiet enable\n", tmp_str);
@ -105,13 +104,6 @@ int main(int argc, char *argv[])
strcpy (input, argv[i+1]);
i++;
}
else if ((argv[i][0] == '-') && (argv[i][1] == 'c') && (argv[i][2] == '\0'))
// cell size
{
sscanf (argv[i+1], "%f,%f,%f", &_system_info.cell[0], &_system_info.cell[1],
&_system_info.cell[2]);
i++;
}
else if ((argv[i][0] == '-') && (argv[i][1] == 'o') && (argv[i][2] == '\0'))
// output file
{

View File

@ -27,8 +27,6 @@
int error_checking (const system_info _system_info, const char *input,
const char *output)
{
if ((_system_info.cell[0] == 0.0) || (_system_info.cell[1] == 0.0) || (_system_info.cell[2] == 0.0))
return 11;
if (input[0] == '#')
return 12;
if (output[0] == '#')

View File

@ -81,11 +81,10 @@ int main(int argc, char *argv[])
sprintf (tmp_str, "%s Evgeniy Alekseev aka arcanis\n", tmp_str);
sprintf (tmp_str, "%s E-mail : esalexeev@gmail.com\n\n", tmp_str);
sprintf (tmp_str, "%sUsage:\n", tmp_str);
sprintf (tmp_str, "%smm_envir -i INPUT -c X,Y,Z -o OUTPUT [ -n NUM_OF_MOLECULE ] [ -r RADIUS ]\n", tmp_str);
sprintf (tmp_str, "%s [ -l LOGFILE ] [ -q ] [ -h ]\n\n", tmp_str);
sprintf (tmp_str, "%smm_envir -i INPUT -o OUTPUT [ -n NUM_OF_MOLECULE ] [ -r RADIUS ]\n", tmp_str);
sprintf (tmp_str, "%s [ -l LOGFILE ] [ -q ] [ -h ]\n\n", tmp_str);
sprintf (tmp_str, "%sParametrs:\n", tmp_str);
sprintf (tmp_str, "%s -i - input file name\n", tmp_str);
sprintf (tmp_str, "%s -c - cell size (float), A\n", tmp_str);
sprintf (tmp_str, "%s -o - output file name\n", tmp_str);
sprintf (tmp_str, "%s -n - number of molecule for search (integer). Default is 1\n", tmp_str);
sprintf (tmp_str, "%s -r - radius of environment (float). Default is 6.0\n", tmp_str);
@ -101,12 +100,6 @@ int main(int argc, char *argv[])
strcpy (input, argv[i+1]);
i++;
}
else if ((argv[i][0] == '-') && (argv[i][1] == 'c') && (argv[i][2] == '\0'))
// cell size
{
sscanf (argv[i+1], "%f,%f,%f", &_system_info.cell[0], &_system_info.cell[1], &_system_info.cell[2]);
i++;
}
else if ((argv[i][0] == '-') && (argv[i][1] == 'o') && (argv[i][2] == '\0'))
// output file
{

View File

@ -33,12 +33,13 @@
* @param ch_atom_types massive of char atom types
* @param atom_types massive of atom types
* @param coords massive of coordinates
* @param cell cell size
*
* @return 0 - exit without errors
*/
int printing_trj (const char *filename, const int atoms, const int num_types, const int *num_mol,
const int *num_atoms, const char *ch_atom_types, const int *atom_types,
const float *coords);
const float *coords, const float *cell);
#endif /* PRINT_TRJ_H */

View File

@ -15,12 +15,15 @@ message (STATUS "${SUBPROJECT} HEADERS: ${HEADERS}")
# link libraries and compile
add_library (${SUBPROJECT} SHARED ${SOURCES} ${HEADERS})
add_library (${SUBPROJECT} STATIC ${SOURCES} ${HEADERS})
set_target_properties (${SUBPROJECT} PROPERTIES SOVERSION ${PROJECT_VERSION})
target_link_libraries (${SUBPROJECT} ${ADDITIONAL_LIB})
add_library (${SUBPROJECT}_STATIC STATIC ${SOURCES} ${HEADERS})
set_target_properties(${SUBPROJECT}_STATIC PROPERTIES OUTPUT_NAME ${SUBPROJECT})
target_link_libraries (${SUBPROJECT} ${ADDITIONAL_LIB})
# install properties
install (TARGETS ${SUBPROJECT} DESTINATION lib)
install (TARGETS ${SUBPROJECT}_STATIC DESTINATION lib)
if (ADD_INCLUDE)
install (DIRECTORY ${SUBPROJECT_INCLUDE_DIR}/ DESTINATION include/)
endif ()

View File

@ -29,7 +29,7 @@ int reading_coords (const int mode, const char *filename, const int type_inter,
{
char at_symb[32], file_string[256];
int atoms, cur_at_num, cur_at_type, cur_mol, i, j, tr_num_atoms, ref_mol, x, y;
float cur_coords[3], ref[3];
float cur_coords[3], ref[3], cur_cell[3];
FILE *inp;
/* cur_* temp variables
@ -132,6 +132,13 @@ int reading_coords (const int mode, const char *filename, const int type_inter,
default: return 2;
}
}
// cell sizes
fgets (file_string, 256, inp);
sscanf (file_string, "%f,%f,%f", &cur_cell[0], &cur_cell[1],
&cur_cell[2]);
(*_system_info).cell[0] = cur_cell[0];
(*_system_info).cell[1] = cur_cell[1];
(*_system_info).cell[2] = cur_cell[2];
fclose (inp);
/// <pre> translation </pre>

View File

@ -24,7 +24,7 @@
*/
int printing_trj (const char *filename, const int atoms, const int num_types, const int *num_mol,
const int *num_atoms, const char *ch_atom_types, const int *atom_types,
const float *coords)
const float *coords, const float *cell)
{
int cur_mol, cur_type[2], i, j, k, l;
FILE *f_out;
@ -60,6 +60,8 @@ coords[3*i+1], coords[3*i+2], atom_types[cur_type[1]], cur_mol);
cur_type[0] += num_atoms[j];
}
}
fprintf (f_out, "%lf,%lf,%lf\n", cell[0], cell[1], cell[2]);
fclose (f_out);

View File

@ -126,7 +126,7 @@ int rw_gmx (const char *input, const int step, const char *output, const int num
// write to output
printing_trj (filename, atoms, num_types, num_mol, num_atoms, ch_atom_types,
atom_types, coords);
atom_types, coords, cell);
}
fclose (f_inp);

View File

@ -78,7 +78,7 @@ int rw_puma (const char *input, const int step, const char *output, const int nu
// write to output
printing_trj (filename, atoms, num_types, num_mol, num_atoms, ch_atom_types,
atom_types, coords);
atom_types, coords, cell);
}
fclose (f_inp);

View File

@ -28,8 +28,6 @@
int error_checking (const char *input, const int num_needed_at, const int *needed_at,
const char *output, const system_info _system_info)
{
if ((_system_info.cell[0] == 0.0) || (_system_info.cell[1] == 0.0) || (_system_info.cell[2] == 0.0))
return 11;
if (input[0] == '#')
return 12;
if (output[0] == '#')

View File

@ -81,13 +81,12 @@ int main(int argc, char *argv[])
sprintf (tmp_str, "%s Evgeniy Alekseev aka arcanis\n", tmp_str);
sprintf (tmp_str, "%s E-mail : esalexeev@gmail.com\n\n", tmp_str);
sprintf (tmp_str, "%sUsage:\n", tmp_str);
sprintf (tmp_str, "%smm_radf -i INPUT -s FIRST,LAST -c X,Y,Z -at ... -o OUTPUT [ -r MIN,MAX ]\n", tmp_str);
sprintf (tmp_str, "%s [ -rs R_STEP ] [ -a MIN,MAX ] [ -as ANG_STEP ] [ -m ]\n", tmp_str);
sprintf (tmp_str, "%s [ -l LOGFILE ] [ -q ] [ -h ]\n\n", tmp_str);
sprintf (tmp_str, "%smm_radf -i INPUT -s FIRST,LAST -at ... -o OUTPUT [ -r MIN,MAX ] [ -rs R_STEP ]\n", tmp_str);
sprintf (tmp_str, "%s [ -a MIN,MAX ] [ -as ANG_STEP ] [ -m ]\n", tmp_str);
sprintf (tmp_str, "%s [ -l LOGFILE ] [ -q ] [ -h ]\n\n", tmp_str);
sprintf (tmp_str, "%sParametrs:\n", tmp_str);
sprintf (tmp_str, "%s -i - mask of input files\n", tmp_str);
sprintf (tmp_str, "%s -s - trajectory steps (integer)\n", tmp_str);
sprintf (tmp_str, "%s -c - cell size (float), A\n", tmp_str);
sprintf (tmp_str, "%s -at - atom types (integer). Format: 'AT1-AT2' or 'A1,A2,A3-B1,B2,B3'\n", tmp_str);
sprintf (tmp_str, "%s (will enable RDF calculation for center mass automaticaly)\n", tmp_str);
sprintf (tmp_str, "%s -o - output file name\n", tmp_str);
@ -123,12 +122,6 @@ int main(int argc, char *argv[])
}
i++;
}
else if ((argv[i][0] == '-') && (argv[i][1] == 'c') && (argv[i][2] == '\0'))
// cell size
{
sscanf (argv[i+1], "%f,%f,%f", &_system_info.cell[0], &_system_info.cell[1], &_system_info.cell[2]);
i++;
}
else if ((argv[i][0] == '-') && (argv[i][1] == 'a') && (argv[i][2] == 't') && (argv[i][3] == '\0'))
// atom types
{
@ -248,12 +241,12 @@ int main(int argc, char *argv[])
_atom_info = (atom_info *) malloc (8 * _system_info.num_atoms * sizeof (atom_info));
if (mode == 2)
{
i = (_radf_info.r_max - _radf_info.r_min) / _radf_info.r_step;
j = (_radf_info.ang_max - _radf_info.ang_min) / _radf_info.ang_step;
i = 1 + (_radf_info.r_max - _radf_info.r_min) / _radf_info.r_step;
j = 1 + (_radf_info.ang_max - _radf_info.ang_min) / _radf_info.ang_step;
i *= j;
}
else
i = (_radf_info.r_max - _radf_info.r_min) / _radf_info.r_step;
i = 1 + (_radf_info.r_max - _radf_info.r_min) / _radf_info.r_step;
radf = (int *) malloc (i * sizeof (int));
for (j=0; j<i; j++)
radf[j] = 0;

View File

@ -30,8 +30,6 @@ int error_checking (const system_info _system_info, const char *input, const int
{
if ((type_inter == 0) || (type_inter > 4))
return 11;
if ((_system_info.cell[0] == 0.0) || (_system_info.cell[1] == 0.0) || (_system_info.cell[2] == 0.0))
return 12;
if ((_system_info.to == -1) || (_system_info.from == -1))
return 13;
if (num_of_inter == 0)

View File

@ -107,12 +107,11 @@ int main (int argc, char *argv[])
sprintf (tmp_str, "%s Evgeniy Alekseev aka arcanis\n", tmp_str);
sprintf (tmp_str, "%s E-mail : esalexeev@gmail.com\n\n", tmp_str);
sprintf (tmp_str, "%sUsage:\n", tmp_str);
sprintf (tmp_str, "%smm_statgen -i INPUT -s FIRST,LAST -c X,Y,Z -a ... -r ... -o OUTPUT [ -g DEPTH ]\n", tmp_str);
sprintf (tmp_str, "%s [ -l LOGFILE ] [ -q ] [ -h ]\n\n", tmp_str);
sprintf (tmp_str, "%smm_statgen -i INPUT -s FIRST,LAST -a ... -r ... -o OUTPUT [ -g DEPTH ]\n", tmp_str);
sprintf (tmp_str, "%s [ -l LOGFILE ] [ -q ] [ -h ]\n\n", tmp_str);
sprintf (tmp_str, "%sParametrs:\n", tmp_str);
sprintf (tmp_str, "%s -i - mask of input files\n", tmp_str);
sprintf (tmp_str, "%s -s - trajectory steps (integer)\n", tmp_str);
sprintf (tmp_str, "%s -c - cell size (float), A\n", tmp_str);
sprintf (tmp_str, "%s -a - atom types (integer). Format: 'ATOM1' or 'ATOM1,ATOM2' or etc\n", tmp_str);
sprintf (tmp_str, "%s -r - criteria (float), A. Format: '0-0:2.4,0-1:3.0' means 0-0\n", tmp_str);
sprintf (tmp_str, "%s interaction (<2.4 A) and 0-1 (<3.0) are needed. This flag can be\n", tmp_str);
@ -144,12 +143,6 @@ int main (int argc, char *argv[])
}
i++;
}
else if ((argv[i][0] == '-') && (argv[i][1] == 'c') && (argv[i][2] == '\0'))
// cell size
{
sscanf (argv[i+1], "%f,%f,%f", &_system_info.cell[0], &_system_info.cell[1], &_system_info.cell[2]);
i++;
}
else if ((argv[i][0] == '-') && (argv[i][1] == 'a') && (argv[i][2] == '\0'))
// atom types
{

270
xvg2csv/xvg2csv.py Executable file
View File

@ -0,0 +1,270 @@
#!/usr/bin/python2
# xvg2csv
# Copyright (C) 2014 Evgeniy Alekseev <esalexeev@gmail.com>
#
# 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 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, see <http://www.gnu.org/licenses/>.
import argparse, datetime, os
def defineType(file):
"""function to define type of input file"""
type = None
with open(file, 'r') as input:
for line in input:
if (line[0] == '@') and (line.find("title") > -1):
if (line.find("RMSD") > -1):
type = "rmsd"
elif (line.find("istance") > -1):
type = "dist"
elif (line.find("Angle") > -1):
type = "angl"
elif (line.find("Number") > -1):
type = "num"
break
return type
def getAngleOutput(file, first=True):
"""function to parse angle file"""
data = []
with open(file, 'r') as input:
for line in input:
if ((line[0] == '@') or (line[0] == '#')):
continue
try:
if ((not first) and (float(line.split()[0]) == 0.0)):
continue
data.append(float(line.split()[2]))
except:
pass
return data
def getDistanceOutput(file, first=True):
"""function to parse distance file"""
data = []
with open(file, 'r') as input:
for line in input:
if ((line[0] == '@') or (line[0] == '#')):
continue
try:
if ((not first) and (float(line.split()[0]) == 0.0)):
continue
data.append(float(line.split()[1]) * 10.0)
except:
pass
return data
def getNumberOutput(file, first=True):
"""function to parse distance file"""
data = []
with open(file, 'r') as input:
for line in input:
if ((line[0] == '@') or (line[0] == '#')):
continue
try:
if ((not first) and (float(line.split()[0]) == 0.0)):
continue
data.append(float(line.split()[1]))
except:
pass
return data
def getRmsdOutput(file, first=True):
"""function to parse rmsd files"""
data = []
with open(file, 'r') as input:
for line in input:
if ((line[0] == '@') or (line[0] == '#')):
continue
try:
if ((not first) and (float(line.split()[0]) == 0.0)):
continue
data.append(float(line.split()[1]) * 10.0)
except:
pass
return data
def getFullFileList(dirs):
"""function to get full file list"""
fileList = {}
for dir in dirs:
directory = os.path.abspath(dir)
if (os.path.exists(directory)) and (os.path.isdir(directory)):
newFileList = getFileList(directory)
for label in newFileList.keys():
if (not fileList.has_key(label)): fileList[label] = {}
for system in newFileList[label].keys():
if (not fileList[label].has_key(system)): fileList[label][system] = []
fileList[label][system].append(newFileList[label][system])
return fileList
def getFileList(directory):
"""function to get file list"""
rawFileList = [file for file in os.listdir(directory) if (os.path.splitext(file)[1] == ".xvg")]
rawFileList.sort()
return parseFileList(directory, rawFileList)
def parseFileList(directory, rawFileList):
"""function to parse file list"""
fileList = {}
for file in rawFileList:
fullFileName = os.path.join(directory, file)
label = os.path.splitext(file)[0].split('_')[-2]
system = '_'.join(os.path.splitext(file)[0].split('_')[:-2])
if (not fileList.has_key(label)): fileList[label] = {}
if (not fileList[label].has_key(system)): fileList[label][system] = []
if (fileList[label][system].count(fullFileName) == 0):
fileList[label][system].append(fullFileName)
return fileList
def getAveragingData(rawData, time):
"""function to get averaging data"""
data = {}
for system in rawData.keys():
if (not data.has_key(system)): data[system] = []
count = len(rawData[system]) / time
for i in range(count):
value = sum(rawData[system][i*time:(i+1)*time]) / float(time)
data[system].append(value)
return data
def getData(fileList):
"""function to get data from files"""
rawData = {}
for system in fileList.keys():
first = True
type = None
if (not rawData.has_key(system)): rawData[system] = []
for files in fileList[system]:
for file in files:
if (first):
type = defineType(file)
if (type == "rmsd"):
rawData[system] = rawData[system] + getRmsdOutput(file, first)
elif (type == "dist"):
rawData[system] = rawData[system] + getDistanceOutput(file, first)
elif (type == "angl"):
rawData[system] = rawData[system] + getAngleOutput(file, first)
elif (type == "num"):
rawData[system] = rawData[system] + getNumberOutput(file, first)
if (first):
first = False
return rawData
def createCsv(directory, label, data, timeStep):
"""function to create *.csv file"""
file = os.path.join(directory, label + ".csv")
iter = 0
suffix = ""
while (os.path.exists(file + suffix)):
suffix = ".%i" % (iter)
iter = iter + 1
if (suffix != ""):
os.rename(file, file + suffix)
with open(file, "w") as output:
output.write("t\t%s\n" % ('\t'.join(data.keys())))
count = max([len(data[system]) for system in data.keys()])
for i in range(count):
line = "%.3f" % (i * timeStep + timeStep / 2.0)
for system in data.keys():
if (len(data[system]) > i):
line = "%s\t%.5f" % (line, data[system][i])
else:
line = "%s\t" % (line)
output.write(line + "\n")
def createQti(directory, label, data, timeStep):
"""function to create *.qti file"""
file = os.path.join(directory, label + ".qti")
iter = 0
suffix = ""
while (os.path.exists(file + suffix)):
suffix = ".%i" % (iter)
iter = iter + 1
if (suffix != ""):
os.rename(file, file + suffix)
with open(file, "w") as output:
count = max([len(data[system]) for system in data.keys()])
timestamp = datetime.datetime.now().strftime("%d.%m.%y %H:%M")
output.write("QtiPlot 0.9.8 project file\n")
output.write("<scripting-lang>\tPython\n")
output.write("<windows>\t1\n")
output.write("<table>\n")
output.write("%s\t%i\t%i\t%s\n" % (label, count, len(data.keys()) + 1, timestamp))
output.write("geometry\t0\t0\t445\t220\t\n")
output.write("header\tt[X]\t%s[Y]\n" % ('[Y]\t'.join(data.keys())))
output.write("ColWidth\t100")
for system in data.keys(): output.write("\t100")
output.write("\n<com>\n</com>\n")
output.write("ColType\t0;0/13")
for system in data.keys(): output.write("\t0;0/13")
output.write("\nReadOnlyColumn\t0")
for system in data.keys(): output.write("\t0")
output.write("\nHiddenColumn\t0")
for system in data.keys(): output.write("\t0")
output.write("\nComments\t\t")
for system in data.keys(): output.write("\t")
output.write("\nWindowLabel\t\t2\n<data>\n")
for i in range(count):
line = "%i\t%.3f" % (i, i * timeStep + timeStep / 2.0)
for system in data.keys():
if (len(data[system]) > i):
line = "%s\t%.8f" % (line, data[system][i])
else:
line = "%s\t" % (line)
output.write(line + "\n")
output.write("</data>\n</table>\n")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description = 'Convert GROMACS *.xvg files to *.csv and *.qti. Example filename is "system_label_number.xvg"')
parser.add_argument('-d', '--directories', dest = 'dirs',
help = 'Directories, comma separared', action = 'store', default = ".")
parser.add_argument('-o', '--output', dest = 'output',
help = 'Output directory', action = 'store', default = ".")
parser.add_argument('-nc', '--nocsv', dest = 'nocsv',
help = 'Do not create *.csv file', action = 'store_true', default = False)
parser.add_argument('-nq', '--noqti', dest = 'noqti',
help = 'Do not create *.qti file', action = 'store_true', default = False)
parser.add_argument('-t', '--time', dest = 'time', type = int,
help = 'Averaging time', action = 'store', default = 1)
parser.add_argument('-s', '--step', dest = 'step', type = float,
help = 'Time step', action = 'store', default = 1.0)
args = parser.parse_args()
dirs = args.dirs.split(',')
output = os.path.abspath(args.output)
if not os.path.exists(output): os.makedirs(output)
fileList = getFullFileList(dirs)
for label in fileList.keys():
rawData = getData(fileList[label])
data = getAveragingData(rawData, args.time)
if (not args.nocsv):
createCsv(output, label, data, args.step)
if (not args.noqti):
createQti(output, label, data, args.step)