Commit 1be60c10 authored by Berk Onat's avatar Berk Onat
Browse files

One Cmake call for all

parent 086f4be1
from __future__ import absolute_import
import warnings
try:
from .molfile import libpymolfile
except ImportError:
warnings.warn("libpymolfile package not available, pymolfile does not work without its library!")
from . import plugin_list
from . import pymolfile
__all__ = [ "pymolfile" ]
from .pymolfile import OpenMolfile, list_plugins
# Stand-alone python bindings for libpymolfile
# Copyright (c) 2017 Berk Onat <b.onat@warwick.ac.uk>
# Published under the UIUC OpenSource LICENSE
"""libpymolfile library.
"""
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.12
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
"""
:Author: Berk Onat <b.onat@warwick.ac.uk>
:Year: 2017
:Licence: UIUC LICENSE
"""
from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (2, 7, 0):
def swig_import_helper():
import importlib
pkg = __name__.rpartition('.')[0]
mname = '.'.join((pkg, '_libpymolfile')).lstrip('.')
try:
return importlib.import_module(mname)
except ImportError:
return importlib.import_module('_libpymolfile')
_libpymolfile = swig_import_helper()
del swig_import_helper
elif _swig_python_version_info >= (2, 6, 0):
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_libpymolfile', [dirname(__file__)])
except ImportError:
import _libpymolfile
return _libpymolfile
try:
_mod = imp.load_module('_libpymolfile', fp, pathname, description)
finally:
if fp is not None:
fp.close()
return _mod
_libpymolfile = swig_import_helper()
del swig_import_helper
else:
import _libpymolfile
del _swig_python_version_info
try:
_swig_property = property
except NameError:
pass # Python < 2.2 doesn't have 'property'.
try:
import builtins as __builtin__
except ImportError:
import __builtin__
def _swig_setattr_nondynamic(self, class_type, name, value, static=1):
if (name == "thisown"):
return self.this.own(value)
if (name == "this"):
if type(value).__name__ == 'SwigPyObject':
self.__dict__[name] = value
return
method = class_type.__swig_setmethods__.get(name, None)
if method:
return method(self, value)
if (not static):
if _newclass:
object.__setattr__(self, name, value)
else:
self.__dict__[name] = value
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self, class_type, name, value):
return _swig_setattr_nondynamic(self, class_type, name, value, 0)
def _swig_getattr(self, class_type, name):
if (name == "thisown"):
return self.this.own()
method = class_type.__swig_getmethods__.get(name, None)
if method:
return method(self)
raise AttributeError("'%s' object has no attribute '%s'" % (class_type.__name__, name))
def _swig_repr(self):
try:
strthis = "proxy of " + self.this.__repr__()
except __builtin__.Exception:
strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
try:
_object = object
_newclass = 1
except __builtin__.Exception:
class _object:
pass
_newclass = 0
def molfile_plugin_list(maxsize: 'int') -> "PyObject *":
"""molfile_plugin_list(maxsize) -> PyObject *"""
return _libpymolfile.molfile_plugin_list(maxsize)
def molfile_init() -> "int":
"""molfile_init() -> int"""
return _libpymolfile.molfile_init()
def molfile_finish() -> "int":
"""molfile_finish() -> int"""
return _libpymolfile.molfile_finish()
def get_plugin(molcapsule: 'PyObject *', plug_no: 'int') -> "PyObject *":
"""get_plugin(molcapsule, plug_no) -> PyObject *"""
return _libpymolfile.get_plugin(molcapsule, plug_no)
def molfile_plugin_info(molcapsule: 'PyObject *', plugin_no: 'int') -> "PyObject *":
"""molfile_plugin_info(molcapsule, plugin_no) -> PyObject *"""
return _libpymolfile.molfile_plugin_info(molcapsule, plugin_no)
def open_file_read(molcapsule: 'PyObject *', fname: 'char *', ftype: 'char *', natoms: 'int') -> "PyObject *":
"""open_file_read(molcapsule, fname, ftype, natoms) -> PyObject *"""
return _libpymolfile.open_file_read(molcapsule, fname, ftype, natoms)
def close_file_read(molpack: 'PyObject *') -> "PyObject *":
"""close_file_read(molpack) -> PyObject *"""
return _libpymolfile.close_file_read(molpack)
def read_fill_structure(molpack: 'PyObject *', prototype: 'PyObject *') -> "PyObject *":
"""read_fill_structure(molpack, prototype) -> PyObject *"""
return _libpymolfile.read_fill_structure(molpack, prototype)
def read_fill_bonds(molpack: 'PyObject *') -> "PyObject *":
"""read_fill_bonds(molpack) -> PyObject *"""
return _libpymolfile.read_fill_bonds(molpack)
def read_fill_angles(molpack: 'PyObject *') -> "PyObject *":
"""read_fill_angles(molpack) -> PyObject *"""
return _libpymolfile.read_fill_angles(molpack)
def read_fill_next_timestep(molpack: 'PyObject *') -> "PyObject *":
"""read_fill_next_timestep(molpack) -> PyObject *"""
return _libpymolfile.read_fill_next_timestep(molpack)
def are_plugins_same(molpack_a: 'PyObject *', molpack_b: 'PyObject *') -> "PyObject *":
"""are_plugins_same(molpack_a, molpack_b) -> PyObject *"""
return _libpymolfile.are_plugins_same(molpack_a, molpack_b)
def are_filehandles_same(molpack_a: 'PyObject *', molpack_b: 'PyObject *') -> "PyObject *":
"""are_filehandles_same(molpack_a, molpack_b) -> PyObject *"""
return _libpymolfile.are_filehandles_same(molpack_a, molpack_b)
# This file is compatible with both classic and new-style classes.
import warnings
import sys
from .molfile import libpymolfile
try:
from .molfile import libpymolfile
except ImportError:
warnings.warn("libpymolfile package not available, pymolfile does not work without its library!")
MAX_NUM_PLUGINS = 200
C_MOLFILE_PLUGINS = libpymolfile.molfile_plugin_list(MAX_NUM_PLUGINS)
def byte_str_decode(data, dectype=None):
try:
return data.decode(dectype).replace('\x00', '')
except AttributeError:
return data
def plugins():
""" Information on the available molfile plugins
Example tuple: ('psf', 'psf', 1, 1, 1, 0, 1, 1, 1, 0,
'CHARMM,NAMD,XPLOR PSF', 'mol file reader',
'Justin Gullingsrud, John Stone', 1, 9, 17, 1)
The fields in the tuple represent info in ordered as follows:
1: format extension
2: format name
3: read_structure is avaliable if 1
4: read_bonds is avaliable if 1
5: read_angles is avaliable if 1
6: read_next_timestep is avaliable if 1
7: write_structure is avaliable if 1
8: write_bonds is avaliable if 1
9: write_angles is avaliable if 1
10: write_timestep is avaliable if 1
11: long name of the plugin
12: type of plugin
13: authors of the plugin
14: major version of the plugin
15: minor version of the plugin
16: ABI version of the plugin
17: 1 if is reentrant (returns is_reentrant)
Returns: A list of tuples that includes the information and
capabilities of each molfile plugin. The information is
extracted from molfile_plugin_t.
"""
global C_MOLFILE_PLUGINS
numlist = libpymolfile.molfile_init()
if sys.version_info > (3,):
basestring = str
plugins_list = [
[byte_str_decode(item,
dectype="unicode_escape") for item in libpymolfile.molfile_plugin_info(
C_MOLFILE_PLUGINS, i)
] for i in range(numlist)
]
libpymolfile.molfile_finish()
return plugins_list
MOLFILE_PLUGINS = plugins()
from __future__ import absolute_import
from __future__ import print_function
import os
import re
import sys
import numpy as np
from contextlib import contextmanager
import warnings
if sys.version_info > (3,):
long = int
try:
from .molfile import libpymolfile
except ImportError:
warnings.warn("libpymolfile package not available, pymolfile does not work without its library!")
from .plugin_list import plugins, byte_str_decode, MOLFILE_PLUGINS, C_MOLFILE_PLUGINS
def list_plugins():
global MOLFILE_PLUGINS
return MOLFILE_PLUGINS[:]
def decode_array(inarray):
return np.array([
[byte_str_decode(element,
dectype="unicode_escape") for element in item
] for item in inarray
])
# The function stdout_redirected is taken from
# https://stackoverflow.com/questions/5081657/how-do-i-prevent-a-c-shared-library-to-print-on-stdout-in-python
# to supress the plugins from printing to standard output (stdout)
@contextmanager
def stdout_redirected(to=os.devnull):
'''
import os
with stdout_redirected(to=filename):
print("from Python")
os.system("echo non-Python applications are also supported")
'''
fd = sys.stdout.fileno()
##### assert that Python and C stdio write using the same file descriptor
####assert libc.fileno(ctypes.c_void_p.in_dll(libc, "stdout")) == fd == 1
def _redirect_stdout(to):
sys.stdout.close() # + implicit flush()
os.dup2(to.fileno(), fd) # fd writes to 'to' file
sys.stdout = os.fdopen(fd, 'w') # Python writes to fd
with os.fdopen(os.dup(fd), 'w') as old_stdout:
with open(to, 'w') as file:
_redirect_stdout(to=file)
try:
yield # allow code to be run with the redirected stdout
finally:
_redirect_stdout(to=old_stdout) # restore stdout.
# buffering and flags such as
# CLOEXEC may be different
def get_dir_base_extension(file_name):
""" Splits directory, file base and file extensions
Returns: directory without leading '/',
file base name, and file extension without '.'
"""
file_base, file_extension_with_dot = os.path.splitext(os.path.basename(file_name))
file_extension = file_extension_with_dot.split(".")[-1]
file_dir = os.path.dirname(file_name)
return file_dir, file_base, file_extension
def get_listof_parts( filename, filepath, fileformats ):
pattern = re.escape(filename[1:-4]) + "\.part[0-9]{4,4}\.(xtc|trr)$"
parts = []
for f in os.listdir(directory):
m = re.match(pattern, f)
if m and os.path.isfile(os.path.join(directory, f)):
parts.append(os.path.join(directory, f))
return sorted(parts)
def get_extension(file_name):
""" Gets file extension of a file
Returns: file extension without '.'
"""
file_extension_with_dot = os.path.splitext(os.path.basename(file_name))[1]
return file_extension_with_dot.split(".")[-1]
def get_plugin_with_ext(file_ext):
""" Search molfile plugins list and returns the plugin info
for the first matching extension.
Returns: Plugin no in the list and the list item (the plugin info tuple)
"""
global MOLFILE_PLUGINS
if not MOLFILE_PLUGINS:
MOLFILE_PLUGINS = plugins()
if MOLFILE_PLUGINS:
plugin_no = -1
for plugin_info in MOLFILE_PLUGINS:
plugin_no += 1
plugin_ext_info = str(plugin_info[0]).replace('*|',
'').replace('*', '').replace('|', ',').replace(' ', '')
for ext_item in str(plugin_ext_info).split(','):
if str(file_ext) == str(ext_item):
return (plugin_no, plugin_info)
return None
def plugins_same(plugin_one, plugin_two):
if((plugin_one[0] == plugin_two[0]) and
(plugin_one[1][1] == plugin_two[1][1])):
return True
else:
return False
def get_plugin_with_name(plugin_name):
""" Search molfile plugins list and returns the plugin info
for the first matching name in plugin name field.
Returns: Plugin no in the list and the list item (the plugin info tuple)
"""
global MOLFILE_PLUGINS
if not MOLFILE_PLUGINS:
MOLFILE_PLUGINS = plugins()
if MOLFILE_PLUGINS:
plugin_no = -1
for plugin_info in MOLFILE_PLUGINS:
plugin_no += 1
if(str(plugin_name) in str(plugin_info[1]) or
str(plugin_name) in str(plugin_info[10])):
return (plugin_no, plugin_info)
return None
class Topology(object):
def __init__(self, fplugin, fname, ftype, natoms, silent):
self.natoms = None
self.structure = None
self.bonds = None
self.angles = None
self._structure = None
self._bonds = None
self._angles = None
self.pluginhandle = None
self.silent = silent
try:
if self.silent:
with stdout_redirected():
self.pluginhandle = libpymolfile.open_file_read(fplugin,
fname, ftype, natoms)
else:
self.pluginhandle = libpymolfile.open_file_read(fplugin,
fname, ftype, natoms)
self.natoms = self.pluginhandle.natoms
except (IOError, OSError, AttributeError):
pass
def read_structure(self, prototype):
try:
if self.silent:
with stdout_redirected():
self._structure = libpymolfile.read_fill_structure(
self.pluginhandle, prototype)
else:
self._structure = libpymolfile.read_fill_structure(
self.pluginhandle, prototype)
return self._structure
except (OSError, IOError, AttributeError, SystemError):
return None
def read_bonds(self):
try:
if self.silent:
with stdout_redirected():
self._bonds = libpymolfile.read_fill_bonds(self.pluginhandle)
else:
self._bonds = libpymolfile.read_fill_bonds(self.pluginhandle)
return self._bonds
except (OSError, IOError, AttributeError, SystemError):
return None
def read_angles(self):
try:
if self.silent:
with stdout_redirected():
self._angles = libpymolfile.read_fill_angles(self.pluginhandle)
else:
self._angles = libpymolfile.read_fill_angles(self.pluginhandle)
return self._angles
except (OSError, IOError, AttributeError, SystemError):
return None
def __del__( self ):
pass
#if self.pluginhandle is not None:
# libpymolfile.close_file_read(self.pluginhandle)
class Trajectory(object):
def __init__(self, file_name, file_format, plugin, natoms, silent):
global MOLFILE_PLUGINS
global C_MOLFILE_PLUGINS
self.natoms = None
self.atoms = None
self.plugin = None
self.handle = None
self.fname = None
self.ftype = None
self.fname = file_name
self.ftype = file_format
self.plugin = plugin
self.natoms = 0
self.silent = silent
if natoms is not None:
self.natoms = natoms
numlist = libpymolfile.molfile_init()
self.fplugin = libpymolfile.get_plugin(C_MOLFILE_PLUGINS,
self.plugin[0])
self.pluginhandle = None
if self.natoms > 0:
try:
if self.silent:
with stdout_redirected():
self.pluginhandle = libpymolfile.open_file_read(self.fplugin,
self.fname, self.ftype, self.natoms)
else:
self.pluginhandle = libpymolfile.open_file_read(self.fplugin,
self.fname, self.ftype, self.natoms)
except (IOError, OSError, AttributeError):
pass
#if self.pluginhandle is not None:
# libpymolfile.close_file_read(self.pluginhandle)
def read_next(self):
return libpymolfile.read_fill_next_timestep(self.pluginhandle)
def iter_on_traj(self):
try:
empty = False
self.step = 0
while not empty:
x = self.read_next()
if x is None:
empty = True
else:
self.step += 1
yield x
except (IOError, AttributeError, OSError):
return
def iread(self):
iter_obj = iter(self.iter_on_traj())
try:
while True:
self.atoms = next(iter_obj)
return self.atoms
except StopIteration:
pass
finally:
del iter_obj
# def read_frame(self, index_no):
# numlist = libpymolfile.molfile_init()
# tplugin = libpymolfile.get_plugin(C_MOLFILE_PLUGINS,
# self.plugin[1])
# pluginhandle = libpymolfile.open_file_read(tplugin,
# file_name, file_format, natoms)
# libpymolfile.molfile_finish()
# def read(self, index_list, chunk=None):
# numlist = libpymolfile.molfile_init()
# tplugin = libpymolfile.get_plugin(C_MOLFILE_PLUGINS,
# self.plugin[1])
# pluginhandle = libpymolfile.open_file_read(tplugin,
# file_name, file_format, natoms)
# libpymolfile.molfile_finish()
def __del__(self):
pass
#if self.pluginhandle is not None:
# libpymolfile.close_file_read(self.pluginhandle)
def read_topology(file_name, file_format, plugin, silent):
""" Reads structure, bonds, angles, dihedrals, impropers and
additional informations through molfile_plugin if the
data is available
The topology data in pymolfile is a list of tuples that include
the following fields:
(name, type, resname, resid, segid, chain, altloc, insertion,
occupancy, bfactor, mass, charge, radius, atomicnumber)
The data types are as follows in the tuple:
s = string, i = integer, f = float
(s, s, s, i, s, s, s, s, f, f, f, f, f, i)
Returns: Topology class if at least one of the topology
data is available. If non of the data is accessible,
function returns None
"""
topo = None
structure = None
bonds = None
angles = None
if(file_name is not None and
file_format is not None and
plugin is not None):
natoms=0
topo = Topology(plugin, file_name, file_format, natoms, silent)
#if 0 && vmdplugin_ABIVERSION > 17
# /* The new PDB file formats allows for much larger structures, */
# /* which can therefore require longer chain ID strings. The */
# /* new PDBx/mmCIF file formats do not have length limits on */
# /* fields, so PDB chains could be arbitrarily long strings */
# /* in such files. At present, we know we need at least 3-char */
# /* chains for existing PDBx/mmCIF files. */
# char chain[4]; /**< required chain name, or "" */
#else
# char chain[2]; /**< required chain name, or "" */
#endif
#
# Change 'chain', S2 to S4
#