Commit 034da510 authored by Berk Onat's avatar Berk Onat
Browse files

Changed C API Numpy library to directly access molfile structure data

parent 672baac3
%{
#define SWIG_FILE_WITH_INIT
%}
%include "numpy.i"
%init %{
import_array();
%}
%module (docstring="This is a Python SWIG-wrapped module") numpy_swig
%{
#include "numpy_swig.h"
#include <numpy/arrayobject.h>
#if PY_VERSION_HEX >= 0x03000000
NPY_NO_EXPORT void
gentype_struct_free(PyObject *ptr)
{
PyArrayInterface *arrif;
PyObject *context;
arrif = (PyArrayInterface*)PyCapsule_GetPointer(ptr, NULL);
context = (PyObject *)PyCapsule_GetContext(ptr);
Py_DECREF(context);
Py_XDECREF(arrif->descr);
PyArray_free(arrif->shape);
PyArray_free(arrif);
}
static NPY_INLINE PyObject *
NpyCapsule_FromVoidPtr(void *ptr, void (*dtor)(PyObject *))
{
PyObject *ret = PyCapsule_New(ptr, NULL, dtor);
if (ret == NULL) {
PyErr_Clear();
}
return ret;
}
static NPY_INLINE PyObject *
NpyCapsule_FromVoidPtrAndDesc(void *ptr, void* context, void (*dtor)(PyObject *))
{
PyObject *ret = NpyCapsule_FromVoidPtr(ptr, dtor);
if (ret != NULL && PyCapsule_SetContext(ret, context) != 0) {
PyErr_Clear();
Py_DECREF(ret);
ret = NULL;
}
return ret;
}
#else
NPY_NO_EXPORT void
gentype_struct_free(void *ptr, void *arg)
{
PyArrayInterface *arrif = (PyArrayInterface *)ptr;
Py_DECREF((PyObject *)arg);
Py_XDECREF(arrif->descr);
PyArray_free(arrif->shape);
PyArray_free(arrif);
}
NpyCapsule_FromVoidPtrAndDesc(void *ptr, void* context,
void (*dtor)(void *, void *))
{
return PyCObject_FromVoidPtrAndDesc(ptr, context, dtor);
}
#endif
#ifndef Py_CAPSULE_H
typedef void(*PyCapsule_Destructor)(void *, void *);
#endif
void delete_SignedIntBuf(SignedIntBuf* buffer)
{
free(buffer->data);
free(buffer);
}
void free_array_interface( void* ptr, void *arr )
{
PyArrayInterface* inter;
PyObject* arrpy;
inter = (PyArrayInterface*)ptr;
arrpy = (PyObject*)arr;
Py_DECREF(arrpy);
free(inter);
}
void free_capsule(PyObject* arr)
{
PyArrayInterface* inter;
inter = (PyArrayInterface*) PyCapsule_GetPointer(arr, "struct SignedIntBuf");
Py_DECREF(arr);
free(inter);
}
%}
%inline %{PyObject* get__array_struct__(PyObject* self)
{
PyArrayInterface *inter;
PyObject *obj;
int nd;
nd = 2;
Py_intptr_t *shape, *strides;
void *data = NULL;
shape = (Py_intptr_t *)malloc(nd*sizeof(Py_intptr_t));
strides = (Py_intptr_t *)malloc(nd*sizeof(Py_intptr_t));
inter = (PyArrayInterface*)malloc(sizeof(PyArrayInterface));
if (inter==NULL)
return PyErr_NoMemory();
inter->two = 2;
inter->nd = nd;
inter->typekind = 'i';
inter->itemsize = sizeof(int);
inter->flags = NPY_ARRAY_NOTSWAPPED | NPY_ARRAY_ALIGNED | NPY_ARRAY_WRITEABLE;
inter->strides = strides;
inter->shape = shape;
inter->data = (void*) data;
Py_INCREF(self);
obj = NpyCapsule_FromVoidPtrAndDesc(inter, self, gentype_struct_free);
/*
#ifdef Py_CAPSULE_H
obj = PyCapsule_New((void*)inter, "struct SignedIntBuf", free_capsule);
#else
obj = PyCObject_FromVoidPtrAndDesc((void*)inter, (void*)self, free_array_interface);
#endif
*/
return obj;
}
%}
%include numpy_swig.h
%extend SignedIntBuf{
%feature("autodoc", "The comment docstring")SignedIntBuf;
SignedIntBuf(int width, int height)
{
SignedIntBuf* buffer = (SignedIntBuf*) malloc(sizeof(SignedIntBuf));
int shape[2] = { height, width };
int strides[2] = { width * sizeof(int), sizeof(int) };
buffer->shape[0] = shape[0];
buffer->shape[1] = shape[1];
buffer->strides[0] = strides[0];
buffer->strides[1] = strides[1];
buffer->data = (int*) malloc(width*height*sizeof(int));
return buffer;
}
~SignedIntBuf();
char *__str__()
{
static char tmp[1024];
int i, j;
int used = 0;
used += sprintf(tmp, "Array:\n");
for(i=0; i < $self->shape[0]; i++)
{
for(j=0; j < $self->shape[1]; j++)
used += sprintf(tmp + used, "%d\t", $self->data[j + i*$self->shape[1]]);
used += sprintf(tmp + used, "\n");
}
return tmp;
}
%pythoncode
{
def __array_struct__get(self):
return get__array_struct__(self)
property __array_struct__:
"Allows other numerical packages to obtain a new object."
def __get__(self):
return __array_struct__get(self)
}
};
# 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.
"""This is a Python SWIG-wrapped module"""
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, '_numpy_swig')).lstrip('.')
try:
return importlib.import_module(mname)
except ImportError:
return importlib.import_module('_numpy_swig')
_numpy_swig = 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('_numpy_swig', [dirname(__file__)])
except ImportError:
import _numpy_swig
return _numpy_swig
try:
_mod = imp.load_module('_numpy_swig', fp, pathname, description)
finally:
if fp is not None:
fp.close()
return _mod
_numpy_swig = swig_import_helper()
del swig_import_helper
else:
import _numpy_swig
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 get__array_struct__(arg1: 'PyObject *') -> "PyObject *":
return _numpy_swig.get__array_struct__(arg1)
get__array_struct__ = _numpy_swig.get__array_struct__
class SignedIntBuf(_object):
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, SignedIntBuf, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, SignedIntBuf, name)
__repr__ = _swig_repr
__swig_setmethods__["data"] = _numpy_swig.SignedIntBuf_data_set
__swig_getmethods__["data"] = _numpy_swig.SignedIntBuf_data_get
if _newclass:
data = _swig_property(_numpy_swig.SignedIntBuf_data_get, _numpy_swig.SignedIntBuf_data_set)
__swig_setmethods__["shape"] = _numpy_swig.SignedIntBuf_shape_set
__swig_getmethods__["shape"] = _numpy_swig.SignedIntBuf_shape_get
if _newclass:
shape = _swig_property(_numpy_swig.SignedIntBuf_shape_get, _numpy_swig.SignedIntBuf_shape_set)
__swig_setmethods__["strides"] = _numpy_swig.SignedIntBuf_strides_set
__swig_getmethods__["strides"] = _numpy_swig.SignedIntBuf_strides_get
if _newclass:
strides = _swig_property(_numpy_swig.SignedIntBuf_strides_get, _numpy_swig.SignedIntBuf_strides_set)
def __init__(self, width: 'int', height: 'int'):
"""The comment docstring"""
this = _numpy_swig.new_SignedIntBuf(width, height)
try:
self.this.append(this)
except __builtin__.Exception:
self.this = this
__swig_destroy__ = _numpy_swig.delete_SignedIntBuf
__del__ = lambda self: None
def __str__(self) -> "char *":
return _numpy_swig.SignedIntBuf___str__(self)
def __array_struct__get(self):
return get__array_struct__(self)
property __array_struct__:
"Allows other numerical packages to obtain a new object."
def __get__(self):
return __array_struct__get(self)
SignedIntBuf_swigregister = _numpy_swig.SignedIntBuf_swigregister
SignedIntBuf_swigregister(SignedIntBuf)
# This file is compatible with both classic and new-style classes.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
......@@ -30,6 +30,7 @@ extern "C"
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <numpy/arrayobject.h>
enum { pluginOK, pluginNOINIT, pluginCLOSE, pluginNOMEM,
pluginENDOFFILE, pluginFILENOTFOUND, pluginFORMATERROR };
......@@ -119,7 +120,7 @@ static PyMemberDef MolObject_members[] = {
"file handle for plugin"},
{"natoms", T_INT, offsetof(MolObject, natoms), 0,
"number of atoms"},
{NULL, NULL, 0, NULL} /* Sentinel */
{NULL} /* Sentinel */
};
static PyMethodDef MolObject_methods[] = {
......@@ -132,7 +133,7 @@ static PyMethodDef MolObject_methods[] = {
{"get_natoms", (PyCFunction)MolObject_natoms, METH_NOARGS,
"Return the number of atoms"
},
{NULL, NULL, 0, NULL} /* Sentinel */
{NULL} /* Sentinel */
};
......@@ -183,6 +184,7 @@ static PyTypeObject MolObjectType = {
MolObject_new, /* tp_new */
};
#if 0
struct MolAtom {
PyObject_HEAD
char* name;
......@@ -257,8 +259,8 @@ static PyMemberDef MolAtom_members[] = {
{"segid", T_STRING, offsetof(MolAtom, segid), 0,""},
{"chain", T_STRING, offsetof(MolAtom, chain), 0,""},
{"altloc", T_STRING, offsetof(MolAtom, altloc), 0,""},
{"insertion", T_STRING, offsetof(MolAtom, occupancy), 0,""},
{"occupancy", T_FLOAT, offsetof(MolAtom, ), 0,""},
{"insertion", T_STRING, offsetof(MolAtom, insertion), 0,""},
{"occupancy", T_FLOAT, offsetof(MolAtom, occupancy), 0,""},
{"bfactor", T_FLOAT, offsetof(MolAtom, bfactor), 0,""},
{"mass", T_FLOAT, offsetof(MolAtom, mass), 0,""},
{"charge", T_FLOAT, offsetof(MolAtom, charge), 0,""},
......@@ -309,8 +311,11 @@ static PyTypeObject MolAtomType = {
0, /* tp_alloc */
MolAtom_new, /* tp_new */
};
#endif
PyObject * my_read_structure(PyObject* molpack);
PyObject * read_fill_structure(PyObject* molpack, PyObject* prototype);
PyObject * get_structure(PyObject* molpack);
PyObject * print_array_struct(PyObject* prototype);
#if 0
typedef struct DICTHOLDER {
......
Cython -a numind.pyx --cplus
g++ -fPIC -Wall -Wextra -Wunused-function -shared -I/labEnv3/lib/python3.6/site-packages/numpy/core/include/ numind.cpp -o numind.so -I/labEnv3/include/python3.6m/ -L/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib -lpython3.6
#error Do not use this file, it is the result of a failed Cython compilation.
#ifndef NUMIND_H
#define NUMIND_H
typedef struct SignedIntBuf
{
int* data;
int shape[2];
int strides[2];
} SignedIntBuf;
#endif
This diff is collapsed.
This diff is collapsed.
import numpy
import ctypes
import numind
# Create an arbitrary object for each package
np=numpy.arange(12, dtype=numpy.float)
#np=numpy.arange(12)
np.shape = (4,3)
#ns = _numpy_swig(2,2)
#print(ns)
# Wrap the different objects with the NumInd class
# and execute some actions on it
##for obj in [np]:
# ni = _numpy_swig
# print("original object type-->", type(ni.inter))
# # Print some values
# #print("typestr --> {0}", ni.typestr)
# #print("shape --> {0}", ni.shape)
# #print("strides --> {0}", ni.strides)
# npa = numpy.asarray(ni)
# print("object after a numpy re-wrapping --> " , npa)
# #ni.modify()
# #print("object after modification in C space --> {0}", npa)
# Wrap the different objects with the NumInd class
# and execute some actions on it
for obj in [np]:
ni = numind.NumInd(obj)
print("original object type-->", type(ni.undarray))
# Print some values
print("typestr -->", ni.typestr)
print("typekind -->", ni.typekind)
print("shape -->", ni.shape)
print("strides -->", ni.strides)
npa = numpy.asarray(ni)
print("object after a numpy re-wrapping -->", npa)
ni.modify()
print("object after modification in C space -->", npa)
This diff is collapsed.
......@@ -131,12 +131,29 @@ for i in range(numlist):
testplugin = mylib.molfile_plugin_info(mylist, i)
print(i, testplugin)
plugin = mylib.get_plugin(mylist, 81)
#plugin = mylib.get_plugin(mylist, 99) #pdb
#plugin = mylib.get_plugin(mylist, 83) #trr
#plugin = mylib.get_plugin(mylist, 85) #xtc
plugin = mylib.get_plugin(mylist, 105) #psf
#plugin = mylib.get_plugin(mylist, 81) #gro
#plugin = mylib.get_plugin(mylist, 69) #dcd
print(plugin)
natoms=0
numatoms=molnatoms(natoms)
fname="../../test/md.gro"
ftype="gro"
#fname="../../test/DPDP.pdb"
#fname="../../test/md.gro"
#fname="../../test/ala3.dcd"
#fname="../../test/ala3.pdb"
fname="../../test/ala3.psf"
#fname="../../test/md.trr"
#fname="../../test/md.xtc"
#fname="../../test/md_1u19.xtc"
#ftype="pdb"
#ftype="trr"
#ftype="xtc"
ftype="psf"
#ftype="gro"
#ftype="dcd"
pluginhandle = mylib.open_file_read(plugin, fname, ftype, natoms)
print("This passed")
......@@ -144,8 +161,31 @@ print(pluginhandle)
print("This passed too")
print(pluginhandle.natoms)
print("Here")
outarray = mylib.read_structure(pluginhandle)
print(outarray)
x = numpy.array([
('C1','C','ACE',0,'','','','',1.0,1.0,12.011,6,1.0,6),
('C2','C','ACE',0,'','','','',1.0,1.0,12.011,6,1.0,6)
],
dtype=[
('name', 'S16'), ('type', 'S16'), ('resname', 'S8'),
('resid', 'i4'), ('segid', 'S8'), ('chain', 'S2'),
('altloc', 'S2'), ('insertion', 'S2'), ('occupancy', 'f8'),
('bfactor', 'f8'), ('mass', 'f8'), ('charge', 'f8'),
('radius', 'f8'), ('atomicnumber', 'i4')
]
)
print(x)
print(x.__array_interface__)
print(x.__array_interface__["descr"])
print(x.__array_struct__)
y = mylib.read_fill_structure(pluginhandle, x)
#y = mylib.print_array_struct(x)
print(y)
print(len(y))
print(y.__array_interface__)
print(y.__array_interface__["descr"])
#outarray = mylib.get_structure(pluginhandle)
#print(outarray)
#print(type(outarray))
#for i in outarray:
# print(i)
......
import numpy
import ctypes
import _numpy_swig
#import numind
ns = _numpy_swig
# Create an arbitrary object for each package
np=numpy.arange(12)
np.shape = (4,3)
newSIB = ns.new_SignedIntBuf(np.shape[0], np.shape[1])
print(newSIB)
struct = ns.get__array_struct__(np)
print(struct)
ns.delete_SignedIntBuf(newSIB)
# Wrap the different objects with the NumInd class
# and execute some actions on it
#for obj in [np]:
# ni = _numpy_swig
# print("original object type-->", ni)
# # Print some values
# #print("typestr --> {0}", ni.typestr)
# #print("shape --> {0}", ni.shape)
# print("strides --> {0}", ni)
# npa = numpy.asarray(ni)
# print("object after a numpy re-wrapping --> " , npa)
# #ni.modify()
# #print("object after modification in C space --> {0}", npa)
# Wrap the different objects with the NumInd class
# and execute some actions on it
#for obj in [np]:
# ni = numind.NumInd(obj)
# print("original object type-->", type(ni.undarray))
# # Print some values
# print("typestr -->", ni.typestr)
# print("shape -->", ni.shape)
# print("strides -->", ni.strides)
# npa = numpy.asarray(ni)
# print("object after a numpy re-wrapping -->", npa)
# ni.modify()
# print("object after modification in C space -->", npa)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment