Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Main page
Recent changes
Random page
Help
Special pages
SBGrid Resources
SBGrid Consortium
SBGrid Data Bank
Software Webinars
PyMOL Webinar
PyMOL Wiki
Search
Search
Appearance
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
Advanced Scripting
(section)
Page
Discussion
English
Read
Edit
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Page information
Appearance
move to sidebar
hide
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Python, PyMOL and C === Here, I will show you how to write a C-module that plugs into Python and talks nicely with PyMOL. The example actually shows how to make a generic C-function and use it in Python. First, let's assume that we want to call a function, let's call it '''funName'''. Let's assume '''funName''' will take a Python list of lists and return a list---for example passing the C++ program the XYZ coordinates of each atom, and returning a list of certain atoms with some property. I will also assume we have '''funName.h''' and '''funName.c''' for C code files. I have provided this, a more complex example, to show a real-world problem. If you were just sending an integer or float instead of packaged lists, the code is simpler; if you understand unpacking the lists then you'll certainly understand unpacking a simple scalar. ===== C++ ===== If you tell Python that you're using C++ code (see the setup below) then it'll automatically call the C++ compiler instead of the C compiler. There are [http://docs.python.org/ext/cplusplus.html warnings] you may want to be aware of though. My experience with this has been pretty easy. I simple renamed my ".c" files to ".cpp", caught the few errors (darn it, I didn't typecast a few pointers from malloc) and the code compiled fine. My experience with this is also quite limited, YMMV. ==== Calling the External Function ==== So, to start, let's look at the Python code that will call the C-function: <source lang="python"> # # -- in someCode.py # # Call funName. Pass it a list () of lists. (sel1 and sel2 are lists.) # Get the return value into rValFromC. # rValFromC = funName( (sel1, sel2) ); </source> where '''sel1''' and '''sel2''' could be any list of atom coordinates, say, from PyMOL. (See above.) Ok, this isn't hard. Now, we need to see what the code that receives this function call in C, looks like. Well, first we need to let C know we're integrating with Python. So, in your [http://docs.python.org/api/includes.html header file] of '''funName.h''' we put: <source lang="c"> // in funName.h #include <Python.h> </source> Next, by default your C-function's name is '''funName_funName''' (and that needs to be setup, I'll show how, later). So, let's define funName: <source lang="c"> static PyObject* funName_funName(PyObject* self, PyObject* args) { ...more code... </source> This is the generic call. '''funName''' is taking two pointers to [http://docs.python.org/api/common-structs.html PyObjects]. It also returns a PyObject. This is how you get the Python data into and out of C. It shows up in "[http://docs.python.org/api/arg-parsing.html args]" array of packaged Python objects and we then unpack it into C, using some [http://docs.python.org/api/arg-parsing.html helper methods]. Upon completion of unpacking, we perform our C/C++ procedure with the data, package up the results using the [http://docs.python.org/api/api.html Python API], and send the results back to Python/PyMOL. ==== Unpacking the Data ==== Let's unpack the data in '''args'''. Remember, '''args''' has a Python [http://docs.python.org/lib/typesseq.html list of lists]. So, to unpack that we do the following inside of funName: <source lang="c"> static PyObject* funName_funName(PyObject* self, PyObject* args) { PyObject *listA, *listB; if ( ! PyArg_ParseTuple(args, "(OO)", &listA, &listB) ) { printf("Could not unparse objects\n"); return NULL; } // let Python know we made two lists Py_INCREF(listA); Py_INCREF(listB); ... more code ... </source> Line 4 creates the two C objects that we will unpack the lists into. They are pointers to PyObjects. Line 6 is where the magic happens. We call, '''[http://docs.python.org/api/arg-parsing.html PyArg_ParseTuple]''' passing it the args we got from Python. The '''(OO)''' is Python's code for ''I'm expecting two <u>O</u>bjects inside a list <u>()</u>''. Were it three objects, then '''(OOO)'''. The first object will be put into '''&listA''' and the second into '''&listB'''. The exact [http://docs.python.org/api/arg-parsing.html argument building specifications] are very useful. ==== Reference Counting ==== Next, we check for success. Unpacking could fail. If it does, complain and quit. Else, '''listA''' and '''listB''' now have data in them. To avoid memory leaks we need to [http://docs.python.org/api/countingRefs.html manually keep track of PyObjects] we're tooling around with. That is, I can create PyObjects in C (being sneaky and not telling Python) and then when Python quits later on, it'll not know it was supposed to clean up after those objects (making a leak). To, we let Python know about each list with '''Py_INCREF(listA)''' and '''Py_INCREF(listB)'''. This is [http://docs.python.org/api/countingRefs.html reference counting]. Now, just for safety, let's check the lists to make sure they actually were passed something. A tricky user could have given us empty lists, looking to hose the program. So, we do: <source lang="c"> // handle empty selections (should probably do this in Python, it's easier) const int lenA = PyList_Size(listA); if ( lenA < 1 ) { printf("ERROR: First selection didn't have any atoms. Please check your selection.\n"); // let Python remove the lists Py_DECREF(listA); Py_DECREF(listB); return NULL; } </source> We check the list size with, '''[http://docs.python.org/api/listObjects.html PyList_Size]''' and if it's 0 -- we quit. But, before quitting we give control of the lists back to Python so it can clean up after itself. We do that with '''Py_DECREF'''. ==== More Complex Unpacking ==== If you're dealing with simple scalars, then you might be able to skip this portion. Now, we should have access to the data the user sent us, in '''listA''' and '''listB,''' and it should be there and be clean. But, not forgetting that '''listA''' and '''listB''' are list of 3D coordinates, let's unpack them further into sets of coordinates. Because we know the length of the lists, we can do something like the following: <source lang="c"> // make space for the current coords; pcePoint is just a float[3] pcePoint coords = (pcePoint) malloc(sizeof(cePoint)*length); // loop through the arguments, pulling out the // XYZ coordinates. int i; for ( i = 0; i < length; i++ ) { PyObject* curCoord = PyList_GetItem(listA,i); Py_INCREF(curCoord); PyObject* curVal = PyList_GetItem(curCoord,0); Py_INCREF(curVal); coords[i].x = PyFloat_AsDouble(curVal); Py_DECREF(curVal); curVal = PyList_GetItem(curCoord,1); Py_INCREF(curVal); coords[i].y = PyFloat_AsDouble(curVal); Py_DECREF(curVal); curVal = PyList_GetItem(curCoord,2); Py_INCREF(curVal); coords[i].z = PyFloat_AsDouble(curVal); Py_DECREF(curVal); Py_DECREF(curCoord); } ... more code ... </source> Where, '''pcePoint''' is just a float[3]. Line 2 just gets some memory ready for the 3xlenght list of coordinates. Then, for each item for 1..length, we unpack the list using '''[http://docs.python.org/api/listObjects.html PyList_GetItem]''', into '''curCoord'''. This then gets further unpacked into the float[3], '''coords'''. We now have the data in C++/C data structures that the user passed from PyMOL. Now, perform your task in C/C++ and then return the data to PyMOL.
Summary:
Please note that all contributions to PyMOL Wiki are considered to be released under the GNU Free Documentation License 1.2 (see
PyMOL Wiki:Copyrights
for details). If you do not want your writing to be edited mercilessly and redistributed at will, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource.
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Search
Search
Editing
Advanced Scripting
(section)
Add topic