Commit 5cc0d4c7 authored by Manuel Günther's avatar Manuel Günther

Added source files for example classes to repo

parent f4a28e0e
*~
*.swp
*.pyc
bin
eggs
parts
.installed.cfg
.mr.developer.cfg
*.egg-info
src
develop-eggs
sphinx
dist
This diff is collapsed.
include README.rst bootstrap.py buildout.cfg COPYING
recursive-include doc *.py *.rst
Example buildout environment
============================
This simple example demonstrates how to wrap Bob-based scripts on buildout
environments. This may be useful for homework assignments, tests or as a way to
distribute code to reproduce your publication. In summary, if you need to give
out code to others, we recommend you do it following this template so your code
can be tested, documented and run in an orderly fashion.
Installation
------------
.. note::
To follow these instructions locally you will need a local copy of this
package. For that, you can use the github tarball API to download the package::
$ wget --no-check-certificate https://github.com/idiap/bob.project.example/tarball/master -O- | tar xz
$ mv idiap-bob.project* bob.project.example
Documentation and Further Information
-------------------------------------
Please refer to the latest Bob user guide, accessing from the `Bob website
<http://idiap.github.com/bob/>`_ for how to create your own packages based on
this example. In particular, the Section entitled `Organize Your Work in
Satellite Packages <http://www.idiap.ch/software/bob/docs/releases/last/sphinx/html/OrganizeYourCode.html>`_
contains details on how to setup, build and roll out your code.
#see http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages
__import__('pkg_resources').declare_namespace(__name__)
#see http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages
__import__('pkg_resources').declare_namespace(__name__)
#include <blitz/array.h>
/**
Simple example of a function dealing with a blitz array
*/
blitz::Array<double,1> reverse (const blitz::Array<double,1>& array){
// create new array in the desired shape
blitz::Array<double,1> retval(array.shape());
// copy data
for (int i = 0, j = array.extent(0)-1; i < array.extent(0); ++i, --j){
retval(j) = array(i);
}
// return the copied data
return retval;
}
# import all packages with direct dependencies
# (This will load their pure C++ libraries, if needed)
import bob.blitz
# ... in fact, bob.blitz does not have a C++ library and it would not be needed to import it here
# ... nevertheless, it stays here not to forget it!
# import the C++ function ``reverse`` from the library
from ._library import reverse
# import the ``version`` library as well
from . import version as _version
version = _version.module
def get_config():
"""Returns a string containing the configuration information.
"""
import pkg_resources
packages = pkg_resources.require(__name__)
this = packages[0]
deps = packages[1:]
retval = "%s: %s (%s)\n" % (this.key, this.version, this.location)
retval += " - c/c++ dependencies:\n"
for k in sorted(_version.externals): retval += " - %s: %s\n" % (k, _version.externals[k])
retval += " - python dependencies:\n"
for d in deps: retval += " - %s: %s (%s)\n" % (d.key, d.version, d.location)
return retval.strip()
# gets sphinx autodoc done right - don't remove it
__all__ = [_ for _ in dir() if not _.startswith('_')]
// include directly and indirectly dependent libraries
#ifdef NO_IMPORT_ARRAY
#undef NO_IMPORT_ARRAY
#endif
#include <bob.blitz/cppapi.h>
#include <bob.blitz/cleanup.h>
#include <bob.extension/documentation.h>
// declare C++ function
extern blitz::Array<double,1> reverse (const blitz::Array<double,1>&);
// use the documentation classes to document the function
static bob::extension::FunctionDoc reverse_doc = bob::extension::FunctionDoc(
"reverse",
"This is a simple example of bridging between blitz arrays (C++) and numpy.ndarrays (Python)",
"Detailed documentation of the function goes here."
)
.add_prototype("array", "reversed")
.add_parameter("array", "array_like (1D, float)", "The array to reverse")
.add_return("reversed", "array_like (1D, float)", "A copy of the ``array`` with reversed order of entries")
;
// declare the function
// we use the default Python C-API here.
static PyObject* PyReverse(PyObject*, PyObject* args, PyObject* kwargs) {
// declare the expected parameter names
char* kwlist[] = {const_cast<char*>("array"), NULL};
// declare an object of the bridging type
PyBlitzArrayObject* array;
// ... and get the command line argument
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&", kwlist, &PyBlitzArray_Converter, &array)) return 0;
// since PyBlitzArray_Converter increased the reference count of array,
// assure that the reference is decreased when the function exits (either way)
auto array_ = make_safe(array);
// check that the array has the expected properties
if (array->type_num != NPY_FLOAT64 || array->ndim != 1){
PyErr_Format(PyExc_TypeError, "%s : Only 1D arrays of type float are allowed", reverse_doc.name());
return 0;
}
// extract the actual blitz array from the Python type
blitz::Array<double, 1> bz = *PyBlitzArrayCxx_AsBlitz<double, 1>(array);
// call the C++ function
blitz::Array<double, 1> reversed = reverse(bz);
// convert the blitz array back to numpy and return it
return PyBlitzArrayCxx_AsNumpy(reversed);
}
//////////////////////////////////////////////////////////////////////////
/////// Python module declaration ////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// module-wide methods
static PyMethodDef module_methods[] = {
{
reverse_doc.name(),
(PyCFunction)PyReverse,
METH_VARARGS|METH_KEYWORDS,
reverse_doc.doc()
},
{NULL} // Sentinel
};
// module documentation
PyDoc_STRVAR(module_docstr, "Exemplary Python Bindings");
// module definition
#if PY_VERSION_HEX >= 0x03000000
static PyModuleDef module_definition = {
PyModuleDef_HEAD_INIT,
BOB_EXT_MODULE_NAME,
module_docstr,
-1,
module_methods,
0, 0, 0, 0
};
#endif
// create the module
static PyObject* create_module (void) {
# if PY_VERSION_HEX >= 0x03000000
PyObject* module = PyModule_Create(&module_definition);
# else
PyObject* module = Py_InitModule3(BOB_EXT_MODULE_NAME, module_methods, module_docstr);
# endif
if (!module) return 0;
auto module_ = make_safe(module); ///< protects against early returns
if (PyModule_AddStringConstant(module, "__version__", BOB_EXT_MODULE_VERSION) < 0) return 0;
/* imports bob.blitz C-API + dependencies */
if (import_bob_blitz() < 0) return 0;
Py_INCREF(module);
return module;
}
PyMODINIT_FUNC BOB_EXT_ENTRY_NAME (void) {
# if PY_VERSION_HEX >= 0x03000000
return
# endif
create_module();
}
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.dos.anjos@gmail.com>
# Sun 15 Apr 14:01:39 2012
#
# Copyright (C) 2011-2013 Idiap Research Institute, Martigny, Switzerland
#
# 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, version 3 of the License.
#
# 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/>.
"""Inverts the list of floating point numbers given on command line
"""
from .._library import reverse
def main():
"""Main routine, called by the script that gets the configuration of bob.blitz"""
import sys
if len(sys.argv) == 1:
print ("Usage: %s <numbers>\n" % sys.argv[0])
return
numbers = [float(n) for n in sys.argv[1:]]
print (numbers)
rev = reverse(numbers)
print ("%s reversed is %s" % (numbers, rev))
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.dos.anjos@gmail.com>
# Sun 15 Apr 14:01:39 2012
#
# Copyright (C) 2011-2013 Idiap Research Institute, Martigny, Switzerland
#
# 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, version 3 of the License.
#
# 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/>.
"""Prints the version of bob and exits
"""
def main():
"""Main routine, called by the script that gets the configuration of bob.blitz"""
import bob.blitz
print (bob.blitz.get_config())
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.dos.anjos@gmail.com>
# Wed 15 Aug 09:59:33 2012
#
# Copyright (C) 2011-2013 Idiap Research Institute, Martigny, Switzerland
#
# 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, version 3 of the License.
#
# 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/>.
"""Test Units
"""
def test_reverse():
from . import reverse
source = [0., 1., 2., 3., 4.]
target = reverse(source)
for i in range(5):
assert target[i] == source[4-i]
/**
* @author Andre Anjos <andre.anjos@idiap.ch>
* @date Thu 7 Nov 13:50:16 2013
*
* @brief Binds configuration information available from bob
*/
#ifdef NO_IMPORT_ARRAY
#undef NO_IMPORT_ARRAY
#endif
#include <bob.blitz/capi.h>
#include <bob.blitz/cleanup.h>
#include <string>
#include <cstdlib>
#include <blitz/blitz.h>
#include <boost/preprocessor/stringize.hpp>
#include <boost/version.hpp>
#include <boost/format.hpp>
static int dict_set(PyObject* d, const char* key, const char* value) {
PyObject* v = Py_BuildValue("s", value);
if (!v) return 0;
auto v_ = make_safe(v);
int retval = PyDict_SetItemString(d, key, v);
if (retval == 0) return 1; //all good
return 0; //a problem occurred
}
static int dict_steal(PyObject* d, const char* key, PyObject* value) {
if (!value) return 0;
auto value_ = make_safe(value);
int retval = PyDict_SetItemString(d, key, value);
if (retval == 0) return 1; //all good
return 0; //a problem occurred
}
/***********************************************************
* Version number generation
***********************************************************/
/**
* Describes the compiler version
*/
static PyObject* compiler_version() {
# if defined(__GNUC__) && !defined(__llvm__)
boost::format f("%s.%s.%s");
f % BOOST_PP_STRINGIZE(__GNUC__);
f % BOOST_PP_STRINGIZE(__GNUC_MINOR__);
f % BOOST_PP_STRINGIZE(__GNUC_PATCHLEVEL__);
return Py_BuildValue("{ssss}", "name", "gcc", "version", f.str().c_str());
# elif defined(__llvm__) && !defined(__clang__)
return Py_BuildValue("{ssss}", "name", "llvm-gcc", "version", __VERSION__);
# elif defined(__clang__)
return Py_BuildValue("{ssss}", "name", "clang", "version", __clang_version__);
# else
return Py_BuildValue("{ssss}", "name", "unsupported", "version", "unknown");
# endif
}
/**
* Python version with which we compiled the extensions
*/
static PyObject* python_version() {
boost::format f("%s.%s.%s");
f % BOOST_PP_STRINGIZE(PY_MAJOR_VERSION);
f % BOOST_PP_STRINGIZE(PY_MINOR_VERSION);
f % BOOST_PP_STRINGIZE(PY_MICRO_VERSION);
return Py_BuildValue("s", f.str().c_str());
}
/**
* Numpy version
*/
static PyObject* numpy_version() {
return Py_BuildValue("{ssss}", "abi", BOOST_PP_STRINGIZE(NPY_VERSION), "api", BOOST_PP_STRINGIZE(NPY_API_VERSION));
}
/**
* bob.blitz c/c++ api version
*/
static PyObject* bob_blitz_version() {
return Py_BuildValue("{ss}", "api", BOOST_PP_STRINGIZE(BOB_BLITZ_API_VERSION));
}
// builds the dictionary of versions
static PyObject* build_version_dictionary() {
PyObject* retval = PyDict_New();
if (!retval) return 0;
auto retval_ = make_safe(retval);
if (!dict_steal(retval, "Compiler", compiler_version())) return 0;
if (!dict_steal(retval, "Python", python_version())) return 0;
if (!dict_steal(retval, "NumPy", numpy_version())) return 0;
if (!dict_set(retval, "Blitz++", BZ_VERSION)) return 0;
if (!dict_steal(retval, "bob.blitz", bob_blitz_version())) return 0;
Py_INCREF(retval);
Py_INCREF(retval);
return retval;
}
static PyMethodDef module_methods[] = {
{0} /* Sentinel */
};
PyDoc_STRVAR(module_docstr,
"Information about software used to compile the C++ Bob API"
);
#if PY_VERSION_HEX >= 0x03000000
static PyModuleDef module_definition = {
PyModuleDef_HEAD_INIT,
BOB_EXT_MODULE_NAME,
module_docstr,
-1,
module_methods,
0, 0, 0, 0
};
#endif
static PyObject* create_module (void) {
# if PY_VERSION_HEX >= 0x03000000
PyObject* m = PyModule_Create(&module_definition);
# else
PyObject* m = Py_InitModule3(BOB_EXT_MODULE_NAME, module_methods, module_docstr);
# endif
if (!m) return 0;
auto m_ = make_safe(m); ///< protects against early returns
/* register version numbers and constants */
if (PyModule_AddStringConstant(m, "module", BOB_EXT_MODULE_VERSION) < 0)
return 0;
if (PyModule_AddObject(m, "externals", build_version_dictionary()) < 0) return 0;
/* imports dependencies */
if (import_bob_blitz() < 0) {
PyErr_Print();
PyErr_Format(PyExc_ImportError, "cannot import `%s'", BOB_EXT_MODULE_NAME);
return 0;
}
Py_INCREF(m);
return m;
}
PyMODINIT_FUNC BOB_EXT_ENTRY_NAME (void) {
# if PY_VERSION_HEX >= 0x03000000
return
# endif
create_module();
}
##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Bootstrap a buildout-based project
Simply run this script in a directory containing a buildout.cfg.
The script accepts buildout command-line options, so you can
use the -c option to specify an alternate configuration file.
"""
import os
import shutil
import sys
import tempfile
from optparse import OptionParser
tmpeggs = tempfile.mkdtemp()
usage = '''\
[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options]
Bootstraps a buildout-based project.
Simply run this script in a directory containing a buildout.cfg, using the
Python that you want bin/buildout to use.
Note that by using --find-links to point to local resources, you can keep
this script from going over the network.
'''
parser = OptionParser(usage=usage)
parser.add_option("-v", "--version", help="use a specific zc.buildout version")
parser.add_option("-t", "--accept-buildout-test-releases",
dest='accept_buildout_test_releases',
action="store_true", default=False,
help=("Normally, if you do not specify a --version, the "
"bootstrap script and buildout gets the newest "
"*final* versions of zc.buildout and its recipes and "
"extensions for you. If you use this flag, "
"bootstrap and buildout will get the newest releases "
"even if they are alphas or betas."))
parser.add_option("-c", "--config-file",
help=("Specify the path to the buildout configuration "
"file to be used."))
parser.add_option("-f", "--find-links",
help=("Specify a URL to search for buildout releases"))
options, args = parser.parse_args()
######################################################################
# load/install setuptools
to_reload = False
try:
import pkg_resources
import setuptools
except ImportError:
ez = {}
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
# XXX use a more permanent ez_setup.py URL when available.
exec(urlopen('https://bitbucket.org/pypa/setuptools/raw/0.7.2/ez_setup.py'
).read(), ez)
setup_args = dict(to_dir=tmpeggs, download_delay=0)
ez['use_setuptools'](**setup_args)
if to_reload:
reload(pkg_resources)
import pkg_resources
# This does not (always?) update the default working set. We will
# do it.
for path in sys.path:
if path not in pkg_resources.working_set.entries:
pkg_resources.working_set.add_entry(path)
######################################################################
# Try to best guess the version of buildout given setuptools
if options.version is None:
try:
from distutils.version import LooseVersion
package = pkg_resources.require('setuptools')[0]
v = LooseVersion(package.version)
if v < LooseVersion('0.7'):
options.version = '2.1.1'
except:
pass
######################################################################
# Install buildout
ws = pkg_resources.working_set
cmd = [sys.executable, '-c',
'from setuptools.command.easy_install import main; main()',
'-mZqNxd', tmpeggs]
find_links = os.environ.get(
'bootstrap-testing-find-links',
options.find_links or
('http://downloads.buildout.org/'
if options.accept_buildout_test_releases else None)
)
if find_links:
cmd.extend(['-f', find_links])
setuptools_path = ws.find(
pkg_resources.Requirement.parse('setuptools')).location
requirement = 'zc.buildout'
version = options.version
if version is None and not options.accept_buildout_test_releases:
# Figure out the most recent final version of zc.buildout.
import setuptools.package_index
_final_parts = '*final-', '*final'
def _final_version(parsed_version):
for part in parsed_version:
if (part[:1] == '*') and (part not in _final_parts):
return False
return True
index = setuptools.package_index.PackageIndex(
search_path=[setuptools_path])
if find_links:
index.add_find_links((find_links,))
req = pkg_resources.Requirement.parse(requirement)
if index.obtain(req) is not None:
best = []
bestv = None
for dist in index[req.project_name]:
distv = dist.parsed_version
if _final_version(distv):
if bestv is None or distv > bestv:
best = [dist]
bestv = distv
elif distv == bestv:
best.append(dist)
if best:
best.sort()
version = best[-1].version
if version:
requirement = '=='.join((requirement, version))
cmd.append(requirement)
import subprocess
if subprocess.call(cmd, env=dict(os.environ, PYTHONPATH=setuptools_path)) != 0:
raise Exception(
"Failed to execute command:\n%s",
repr(cmd)[1:-1])
######################################################################
# Import and run buildout
ws.add_entry(tmpeggs)
ws.require(requirement)
import zc.buildout.buildout
if not [a for a in args if '=' not in a]:
args.append('bootstrap')
# if -c was provided, we push it back into args for buildout' main function
if options.config_file is not None:
args[0:0] = ['-c', options.config_file]
zc.buildout.buildout.main(args)
shutil.rmtree(tmpeggs)
; vim: set fileencoding=utf-8 :
; Manuel Guenther <manuel.guenther@idiap.ch>
; Thu Oct 9 16:51:06 CEST 2014
[buildout]
parts = scripts
eggs = bob.example.extension
extensions = bob.buildout