Skip to content
Snippets Groups Projects
Commit 0a199877 authored by André Anjos's avatar André Anjos :speech_balloon:
Browse files

Initial commit with base structure

parents
No related branches found
No related tags found
No related merge requests found
Showing with 1408 additions and 0 deletions
*~
*.swp
*.pyc
*.so
bin
eggs
parts
.installed.cfg
.mr.developer.cfg
*.egg-info
develop-eggs
sphinx
dist
.nfs*
.gdb_history
build
*.egg
src/
LICENSE 0 → 100644
Copyright (c) 2013, Andre Anjos - Idiap Research Institute
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer. Redistributions in binary
form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with
the distribution. Neither the name of the Idiap Research Institute nor the
names of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
include LICENSE README.rst bootstrap.py buildout.cfg
recursive-include doc conf.py *.rst
recursive-include xbob *.cpp *.h
.. vim: set fileencoding=utf-8 :
.. Andre Anjos <andre.anjos@idiap.ch>
.. Thu 29 Aug 2013 16:07:57 CEST
============================
Python bindings for bob.io
============================
This package contains a set of Pythonic bindings for Bob's io packages and
functionality.
Installation
------------
Install it through normal means, via PyPI or use ``zc.buildout`` to bootstrap
the package and run test units.
Documentation
-------------
You can generate the documentation for this package, after installation, using
Sphinx::
$ sphinx-build -b html doc sphinx
This shall place in the directory ``sphinx``, the current version for the
documentation of the package.
Testing
-------
You can run a set of tests using the nose test runner::
$ nosetests -sv blitz
.. warning::
If Bob <= 1.2.1 is installed on your python path, nose will automatically
load the old version of the insulate plugin available in Bob, which will
trigger the loading of incompatible shared libraries (from Bob itself), in
to your working binary. This will cause a stack corruption. Either remove
the centrally installed version of Bob, or build your own version of Python
in which Bob <= 1.2.1 is not installed.
You can run our documentation tests using sphinx itself::
$ sphinx-build -b doctest doc sphinx
You can test overall test coverage with::
$ nosetests --with-coverage --cover-package=xbob.io
The ``coverage`` egg must be installed for this to work properly.
Development
-----------
To develop this package, install using ``zc.buildout``, using the buildout
configuration found on the root of the package:
$ python bootstrap.py
...
$ ./bin/buildout
Tweak the options in ``buildout.cfg`` to disable/enable verbosity and debug
builds.
##############################################################################
#
# 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 :
; Andre Anjos <andre.anjos@idiap.ch>
; Mon 16 Apr 08:29:18 2012 CEST
[buildout]
parts = blitz.array xbob.io scripts
eggs = xbob.io
ipdb
extensions = mr.developer
auto-checkout = *
prefixes = /Users/andre/work/bob/b/dbg
debug = true
verbose = true
[sources]
xbob.buildout = git git@github.com:bioidiap/xbob.buildout
pypkg = git git@github.com:anjos/pypkg
[blitz.array]
recipe = xbob.buildout:develop
setup = src/blitz.array
eggs = pypkg
[xbob.io]
recipe = xbob.buildout:develop
eggs = blitz.array pypkg
[scripts]
recipe = xbob.buildout:scripts
.. vim: set fileencoding=utf-8 :
.. Andre Anjos <andre.dos.anjos@gmail.com>
.. Tue 15 Oct 14:59:05 2013
=========
C++ API
=========
The C++ API of ``xbob.core`` allows users to leverage from automatic converters
for classes in :py:class:`xbob.core.random`. To use the C API, clients should
first, include the header file ``<xbob.core/random.h>`` on their compilation
units and then, make sure to call once ``import_xbob_core_random()`` at their
module instantiation, as explained at the `Python manual
<http://docs.python.org/2/extending/extending.html#using-capsules>`_.
Here is a dummy C example showing how to include the header and where to call
the import function:
.. code-block:: c++
#include <xbob.core/random.h>
PyMODINIT_FUNC initclient(void) {
PyObject* m Py_InitModule("client", ClientMethods);
if (!m) return;
// imports the NumPy C-API
import_array();
// imports blitz.array C-API
import_blitz_array();
// imports xbob.core.random C-API
import_xbob_core_random();
}
.. note::
The include directory can be discovered using
:py:func:`xbob.core.get_include`.
Mersenne Twister Random Number Generator (mt19937)
--------------------------------------------------
This package contains bindings to ``boost::random::mt19937``, which is a
powerful random number generator available within the Boost_ C++ library.
.. cpp:type:: PyBoostMt19937Object
The pythonic object representation for a ``boost::random::mt19937`` object.
.. code-block:: c
typedef struct {
PyObject_HEAD
boost::random::mt19937* rng;
} PyBoostMt19937Object;
.. c:member:: boost::random::mt19937* rng
A direct pointer to the boost random number generator. You can use this
pointer in your C/C++ code if required.
.. cpp:function:: int PyBoostMt19937_Check(PyObject* o)
Checks if the input object ``o`` is a ``PyBoostMt19937Object``. Returns
``1`` if it is, and ``0`` otherwise.
.. cpp:function:: int PyBoostMt19937_Converter(PyObject* o, PyBoostMt19937Object** a)
This function is meant to be used with :c:func:`PyArg_ParseTupleAndKeywords`
family of functions in the Python C-API. It checks the input
object to be of type ``PyBoostMt19937Object`` and sets a **new
reference** to it (in ``*a``) if it is the case. Returns ``0`` in case of
failure, ``1`` in case of success.
.. cpp:function:: PyObject* PyBoostMt19937_SimpleNew()
Creates a new instance of :cpp:type:`PyBoostMt19937Object`, with the default
seed. Returns a **new reference**.
.. cpp:function:: PyObject* PyBoostMt19937_NewWithSeed(Py_ssize_t seed)
Creates a new instance of :cpp:type:`PyBoostMt19937Object`, with a user
given seed. Returns a **new reference**.
Distribution API
----------------
Together with the boost random number generator ``mt19937``, this package
provides bindings to these ``boost::random`` distributions:
* Uniform
* Normal (or Gaussian)
* Log-normal
* Gamma
* Binomial
Distributions wrap the random number generator, skewing the distribution of
numbers according to their parametrization. Distributions are *templated*
according to the scalar data types they produce. Different distributions
support a different set of scalar types:
============== =================================================
Distribution Scalars supported
============== =================================================
Uniform bool, int8/16/32/64, uint8/16/32/64, float32/64
Normal float32/64
Log-normal float32/64
Gamma float32/64
Binomial float32/64 (internally using int64)
============== =================================================
.. cpp:type:: PyBoostUniformObject
The pythonic object representation for a ``boost::random::uniform_*``
object.
.. code-block:: c
typedef struct {
PyObject_HEAD
int type_num;
boost::shared_ptr<void> distro;
} PyUniformObject;
.. c:member:: int type_num;
The NumPy type number of scalars produced by this distribution. Accepted
values match the scalar type produced:
============= ========================================
Scalar type NumPy scalar type number (enumeration)
============= ========================================
bool ``NPY_BOOL``
int8 ``NPY_INT8``
int16 ``NPY_INT16``
int32 ``NPY_INT32``
int64 ``NPY_INT64``
int8 ``NPY_INT8``
int16 ``NPY_INT16``
int32 ``NPY_INT32``
int64 ``NPY_INT64``
float32 ``NPY_FLOAT32``
float64 ``NPY_FLOAT64``
============= ========================================
.. c:member:: boost::shared_ptr<void> distro
A direct pointer to the boost distribution. The underlying allocated type
changes with the scalar that is produced by the distribution:
============= ==============================================
Scalar type C++ data type
============= ==============================================
bool ``boost::random::uniform_smallint<uint8_t>``
int8 ``boost::random::uniform_int<int8_t>``
int16 ``boost::random::uniform_int<int16_t>``
int32 ``boost::random::uniform_int<int32_t>``
int64 ``boost::random::uniform_int<int64_t>``
uint8 ``boost::random::uniform_int<uint8_t>``
uint16 ``boost::random::uniform_int<uint16_t>``
uint32 ``boost::random::uniform_int<uint32_t>``
uint64 ``boost::random::uniform_int<uint64_t>``
float32 ``boost::random::uniform_real<float>``
float64 ``boost::random::uniform_real<double>``
============= ==============================================
In order to use the distribution in your C/C++ code, you must first cast the
shared pointer using ``boost::static_pointer_cast<D>``, with ``D`` matching
one of the distributions listed above, depending on the value of
.. cpp:type:: PyBoostNormalObject
The pythonic object representation for a
``boost::random::normal_distribution`` object.
.. code-block:: c
typedef struct {
PyObject_HEAD
int type_num;
boost::shared_ptr<void> distro;
} PyUniformObject;
.. c:member:: int type_num;
The NumPy type number of scalars produced by this distribution. Accepted
values match the scalar type produced:
============= ========================================
Scalar type NumPy scalar type number (enumeration)
============= ========================================
float32 ``NPY_FLOAT32``
float64 ``NPY_FLOAT64``
============= ========================================
.. c:member:: boost::shared_ptr<void> distro
A direct pointer to the boost distribution. The underlying allocated type
changes with the scalar that is produced by the distribution:
============= ================================================
Scalar type C++ data type
============= ================================================
float32 ``boost::random::normal_distribution<float>``
float64 ``boost::random::normal_distribution<double>``
============= ================================================
.. cpp:type:: PyBoostLogNormalObject
The pythonic object representation for a
``boost::random::lognormal_distribution`` object.
.. code-block:: c
typedef struct {
PyObject_HEAD
int type_num;
boost::shared_ptr<void> distro;
} PyUniformObject;
.. c:member:: int type_num;
The NumPy type number of scalars produced by this distribution. Accepted
values match the scalar type produced:
============= ========================================
Scalar type NumPy scalar type number (enumeration)
============= ========================================
float32 ``NPY_FLOAT32``
float64 ``NPY_FLOAT64``
============= ========================================
.. c:member:: boost::shared_ptr<void> distro
A direct pointer to the boost distribution. The underlying allocated type
changes with the scalar that is produced by the distribution:
============= ===================================================
Scalar type C++ data type
============= ===================================================
float32 ``boost::random::lognormal_distribution<float>``
float64 ``boost::random::lognormal_distribution<double>``
============= ===================================================
.. cpp:type:: PyBoostGammaObject
The pythonic object representation for a
``boost::random::gamma_distribution`` object.
.. code-block:: c
typedef struct {
PyObject_HEAD
int type_num;
boost::shared_ptr<void> distro;
} PyUniformObject;
.. c:member:: int type_num;
The NumPy type number of scalars produced by this distribution. Accepted
values match the scalar type produced:
============= ========================================
Scalar type NumPy scalar type number (enumeration)
============= ========================================
float32 ``NPY_FLOAT32``
float64 ``NPY_FLOAT64``
============= ========================================
.. c:member:: boost::shared_ptr<void> distro
A direct pointer to the boost distribution. The underlying allocated type
changes with the scalar that is produced by the distribution:
============= ===============================================
Scalar type C++ data type
============= ===============================================
float32 ``boost::random::gamma_distribution<float>``
float64 ``boost::random::gamma_distribution<double>``
============= ===============================================
.. cpp:type:: PyBoostBinomialObject
The pythonic object representation for a
``boost::random::binomial_distribution`` object.
.. code-block:: c
typedef struct {
PyObject_HEAD
int type_num;
boost::shared_ptr<void> distro;
} PyUniformObject;
.. c:member:: int type_num;
The NumPy type number of scalars produced by this distribution. Accepted
values match the scalar type produced:
============= ========================================
Scalar type NumPy scalar type number (enumeration)
============= ========================================
float32 ``NPY_FLOAT32``
float64 ``NPY_FLOAT64``
============= ========================================
.. c:member:: boost::shared_ptr<void> distro
A direct pointer to the boost distribution. The underlying allocated type
changes with the scalar that is produced by the distribution:
============= ==========================================================
Scalar type C++ data type
============= ==========================================================
float32 ``boost::random::binomial_distribution<int64_t,float>``
float64 ``boost::random::binomial_distribution<int64_t,double>``
============= ==========================================================
.. cpp:function:: int PyBoostUniform_Check(PyObject* o)
.. cpp:function:: int PyBoostNormal_Check(PyObject* o)
.. cpp:function:: int PyBoostLogNormal_Check(PyObject* o)
.. cpp:function:: int PyBoostGamma_Check(PyObject* o)
.. cpp:function:: int PyBoostBinomial_Check(PyObject* o)
Checks if the input object ``o`` is a ``PyBoost<Distribution>Object``.
Returns ``1`` if it is, and ``0`` otherwise.
.. cpp:function:: int PyBoostUniform_Converter(PyObject* o, PyBoostUniformObject** a)
.. cpp:function:: int PyBoostNormal_Converter(PyObject* o, PyBoostNormalObject** a)
.. cpp:function:: int PyBoostLogNormal_Converter(PyObject* o, PyBoostLogNormalObject** a)
.. cpp:function:: int PyBoostGamma_Converter(PyObject* o, PyBoostGammaObject** a)
.. cpp:function:: int PyBoostBinomial_Converter(PyObject* o, PyBoostBinomialObject** a)
This function is meant to be used with :c:func:`PyArg_ParseTupleAndKeywords`
family of functions in the Python C-API. It checks the input object to be of
type ``PyBoost<Distribution>Object`` and returns a **new reference** to it
(in ``*a``) if it is the case. Returns ``0`` in case of failure, ``1`` in
case of success.
.. cpp:function:: PyObject* PyBoostUniform_SimpleNew(int type_num, PyObject* min, PyObject* max)
Creates a new instance of :cpp:type:`PyBoostUniformObject`, with the input
scalar establishing the minimum and the maximum of the distribution. Note
that ``bool`` distributions will raise an exception if one tries to set the
minimum and the maximum, since that is non-sensical.
The parameter ``type_num`` may be set to one of the supported ``NPY_``
enumeration values (e.g. ``NPY_UINT16``).
.. warning::
For integral uniform distributions the range of numbers produced is
defined as :math:`[min, max]`. For real-valued distributions, the range of
numbers produced lies on the interval :math:`[min, max[`.
.. cpp:function:: PyObject* PyBoostNormal_SimpleNew(int type_num, PyObject* mean, PyObject* sigma)
.. cpp:function:: PyObject* PyBoostLogNormal_SimpleNew(int type_num, PyObject* mean, PyObject* sigma)
.. cpp:function:: PyObject* PyBoostGamma_SimpleNew(int type_num, PyObject* alpha, PyObject* beta)
.. cpp:function:: PyObject* PyBoostBinomial_SimpleNew(int type_num, PyObject* t, PyObject* p)
Depending on the distribution, which may be one of ``Normal``,
``LogNormal``, ``Gamma`` or ``Binomial``, each of the parameters assume a
different function:
============== ============= ============================
Distribution Parameter 1 Parameter 2
============== ============= ============================
Normal mean sigma (standard deviation)
LogNormal mean sigma (standard deviation)
Gamma alpha beta
Binomial t p
============== ============= ============================
The parameter ``type_num`` may be set to one of the supported ``NPY_``
enumeration values (e.g. ``NPY_FLOAT64``).
.. include:: links.rst
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Tue 15 Oct 16:37:18 2013 CEST
#
# 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/>.
import os
import sys
import glob
import pkg_resources
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.pngmath',
'sphinx.ext.ifconfig',
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'matplotlib.sphinxext.plot_directive',
]
# The viewcode extension appeared only on Sphinx >= 1.0.0
import sphinx
if sphinx.__version__ >= "1.0":
extensions.append('sphinx.ext.viewcode')
# Always includes todos
todo_include_todos = True
# If we are on OSX, the 'dvipng' path maybe different
dvipng_osx = '/opt/local/libexec/texlive/binaries/dvipng'
if os.path.exists(dvipng_osx): pngmath_dvipng = dvipng_osx
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'xbob.io'
import time
copyright = u'%s, Idiap Research Institute' % time.strftime('%Y')
# Grab the setup entry
distribution = pkg_resources.require('xbob.io')[0]
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = distribution.version
# The full version, including alpha/beta/rc tags.
release = distribution.version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['links.rst']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
if sphinx.__version__ >= "1.0":
html_theme = 'nature'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = 'xbob_io'
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = ''
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = ''
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'xbob_io_doc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
latex_paper_size = 'a4'
# The font size ('10pt', '11pt' or '12pt').
latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'xbob_io.tex', u'Bob I/O Routines',
u'Biometrics Group, Idiap Research Institute', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
latex_logo = ''
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# Included after all input documents
rst_epilog = """
.. |version| replace:: %s
""" % (version,)
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'xbob_io', u'Bob I/O Routines Documentation', [u'Idiap Research Institute'], 1)
]
# Default processing flags for sphinx
autoclass_content = 'both'
autodoc_member_order = 'bysource'
autodoc_default_flags = ['members', 'undoc-members', 'inherited-members', 'show-inheritance']
def smaller_than(v1, v2):
"""Compares scipy/numpy version numbers"""
c1 = v1.split('.')
c2 = v2.split('.')[:len(c1)] #clip to the compared version
for i, k in enumerate(c2):
n1 = c1[i]
n2 = c2[i]
try:
n1 = int(n1)
n2 = int(n2)
except ValueError:
n1 = str(n1)
n2 = str(n2)
if n1 > n2: return False
return True
# Some name mangling to find the correct sphinx manuals for some packages
numpy_version = __import__('numpy').version.version
if smaller_than(numpy_version, '1.5.z'):
numpy_version = '.'.join(numpy_version.split('.')[:-1]) + '.x'
else:
numpy_version = '.'.join(numpy_version.split('.')[:-1]) + '.0'
numpy_manual = 'http://docs.scipy.org/doc/numpy-%s/' % numpy_version
# For inter-documentation mapping:
intersphinx_mapping = {
'http://docs.python.org/%d.%d/' % sys.version_info[:2]: None,
numpy_manual: None,
}
def setup(app):
pass
.. vim: set fileencoding=utf-8 :
.. Andre Anjos <andre.anjos@idiap.ch>
.. Mon 4 Nov 20:58:04 2013 CET
..
.. 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/>.
.. Master file, created by sphinx-quickstart on Mon Mar 21 18:07:34 2011. You
can adapt this file completely to your liking, but it should at least contain
the root `toctree` directive.
=====================
Bob's Core Routines
=====================
This module contains base functionality from Bob bound to Python, available in
the C++ counter-part ``bob::core``. It includes basic conversion routines,
random number generation and central logging facilities.
Reference
---------
.. toctree::
:maxdepth: 2
py_api
c_cpp_api
Indices and tables
------------------
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
.. include:: links.rst
.. vim: set fileencoding=utf-8 :
.. Andre Anjos <andre.anjos@idiap.ch>
.. Tue 20 Mar 2012 08:57:32 CET
..
.. 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/>.
.. This file contains all links we use for documentation in a centralized place
.. Place here references to all citations in lower case
.. _boost: http://www.boost.org
.. _buildout: http://pypi.python.org/pypi/zc.buildout/
.. _c++: http://www2.research.att.com/~bs/C++.html
.. _numpy: http://numpy.scipy.org
.. _nose: http://nose.readthedocs.org
.. _pypi: http://pypi.python.org
.. _scipy: http://www.scipy.org
.. _setuptools: http://trac.edgewall.org/wiki/setuptools
.. _sphinx: http://sphinx.pocoo.org
.. Place here references to licenses
.. _apache-2.0: http://www.opensource.org/licenses/Apache-2.0
.. _artistic-2.0: http://www.opensource.org/licenses/Artistic-2.0
.. _bsd-2-clause: http://www.opensource.org/licenses/BSD-2-Clause
.. _bsd-3-clause: http://www.opensource.org/licenses/BSD-3-Clause
.. _bsl-1.0: http://www.opensource.org/licenses/BSL-1.0
.. _gpl-2.0: http://www.opensource.org/licenses/GPL-2.0
.. _gpl-3.0: http://www.opensource.org/licenses/GPL-3.0
.. _hdf5 license: ftp://ftp.hdfgroup.org/HDF5/current/src/unpacked/COPYING
.. _lgpl-2.1: http://www.opensource.org/licenses/LGPL-2.1
.. _libpng license: http://www.libpng.org/pub/png/src/libpng-LICENSE.txt
.. _mit: http://www.opensource.org/licenses/MIT
.. _python-2.0: http://www.opensource.org/licenses/Python-2.0
.. vim: set fileencoding=utf-8 :
.. Andre Anjos <andre.dos.anjos@gmail.com>
.. Tue 15 Oct 17:41:52 2013
.. testsetup:: coretest
import numpy
import xbob.core
============
User Guide
============
Array Conversion
----------------
The function :py:func:`xbob.core.convert` allows you to convert objects of type
:py:class:`numpy.ndarray` between different types, with range compression or
decompression. For example, here we demonstrate a conversion using default
ranges. In this type of conversion, our implementation will assume that the
source array contains values within the range of ``uint8_t`` numbers and will
expand it to the range of ``uint16_t`` numbers, as desired by the programmer:
.. doctest:: coretest
:options: +NORMALIZE_WHITESPACE
>>> x = numpy.array([0,255,0,255,0,255], 'uint8').reshape(2,3)
>>> x
array([[ 0, 255, 0],
[255, 0, 255]], dtype=uint8)
>>> xbob.core.convert(x, 'uint16')
array([[ 0, 65535, 0],
[65535, 0, 65535]], dtype=uint16)
The user can optionally specify source, destination ranges or both. For
example:
.. doctest:: coretest
:options: +NORMALIZE_WHITESPACE
>>> x = numpy.array([0, 10, 20, 30, 40], 'uint8')
>>> xbob.core.convert(x, 'float64', source_range=(0,40), dest_range=(0.,1.))
array([ 0. , 0.25, 0.5 , 0.75, 1. ])
Any range not specified is assumed to default on the type range.
Random Number Generation
------------------------
You can build a new random number generator (RNG) of type
:py:class:`xbob.core.random.mt19937` using one of two possible ways:
1. Use the default constructor, which initializes with the default seed:
.. doctest:: coretest
:options: +NORMALIZE_WHITESPACE
>>> xbob.core.random.mt19937()
xbob.core.random.mt19937()
2. Pass a seed while initializing:
.. doctest:: coretest
:options: +NORMALIZE_WHITESPACE
>>> rng = xbob.core.random.mt19937(34)
RNGs can be compared for equality. The ``==`` operator checks if both
generators are on the exact same state and would generate the same sequence of
numbers when exposed to the same distributions. For example:
.. doctest:: coretest
:options: +NORMALIZE_WHITESPACE
>>> rng1 = xbob.core.random.mt19937(111)
>>> rng2 = xbob.core.random.mt19937(111)
>>> rng1 == rng2
True
>>> rng3 = xbob.core.random.mt19937(12)
>>> rng1 == rng3
False
The seed can be re-initialized at any point in time, which can be used to sync
two RNGs:
.. doctest:: coretest
:options: +NORMALIZE_WHITESPACE
>>> rng3.seed(111)
>>> rng1 == rng3
True
Distributions skew numbers produced by the RNG so they look like the
parameterized distribution. By calling a distribution with an RNG, one
effectively generates random numbers:
.. doctest:: coretest
:options: +NORMALIZE_WHITESPACE
>>> rng = xbob.core.random.mt19937()
>>> # creates an uniform distribution of integers inside [0, 10]
>>> u = xbob.core.random.uniform(int, 0, 10)
>>> u(rng) # doctest: +SKIP
8
At our reference guide (see below), you will find more implemented
distributions you can use on your programs. To simplify the task of generating
random numbers, we provide a class that mimics the behavior of
``boost::random::variate_generator``, in Python:
.. doctest:: coretest
:options: +NORMALIZE_WHITESPACE
>>> ugen = xbob.core.random.variate_generator(rng, u)
>>> ugen() # doctest: +SKIP
6
You can also pass an optional shape when you call the variate generator, in
which case it generates a :py:class:`numpy.ndarray` of the specified size:
.. doctest:: coretest
:options: +NORMALIZE_WHITESPACE
>>> ugen((3,3)) # doctest: +SKIP
array([[ 3, 1, 6],
[ 3, 2, 6],
[10, 10, 10]])
Reference
---------
This section includes information for using the pure Python API of
``xbob.core``.
.. autofunction:: xbob.core.get_include
.. autofunction:: xbob.core.convert
.. autoclass:: xbob.core.random.mt19937
.. autoclass:: xbob.core.random.uniform
.. autoclass:: xbob.core.random.normal
.. autoclass:: xbob.core.random.lognormal
.. autoclass:: xbob.core.random.gamma
.. autoclass:: xbob.core.random.binomial
.. autoclass:: xbob.core.random.variate_generator
setup.py 0 → 100644
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.anjos@idiap.ch>
# Mon 16 Apr 08:18:08 2012 CEST
from setuptools import setup, find_packages, dist
from distutils.extension import Extension
from distutils.version import LooseVersion
dist.Distribution(dict(setup_requires=['pypkg', 'numpy', 'blitz.array']))
import pypkg
import numpy
import blitz
import platform
# Minimum version requirements for pkg-config packages
MINIMAL_BLITZ_VERSION_REQUIRED = '0.10'
MINIMAL_BOB_VERSION_REQUIRED = '1.3'
# Pkg-config dependencies
blitz_pkg = pypkg.pkgconfig('blitz')
if blitz_pkg < MINIMAL_BLITZ_VERSION_REQUIRED:
raise RuntimeError("This package requires Blitz++ %s or superior, but you have %s" % (MINIMAL_BLITZ_VERSION_REQUIRED, blitz_pkg.version))
bob_pkg = pypkg.pkgconfig('bob-io')
if bob_pkg < MINIMAL_BOB_VERSION_REQUIRED:
raise RuntimeError("This package requires Bob %s or superior, but you have %s" % (MINIMAL_BOB_VERSION_REQUIRED, bob_pkg.version))
# Make-up the names of versioned Bob libraries we must link against
if platform.system() == 'Darwin':
bob_libraries=['%s.%s' % (k, bob_pkg.version) for k in bob_pkg.libraries()]
elif platform.system() == 'Linux':
bob_libraries=[':lib%s.so.%s' % (k, bob_pkg.version) for k in bob_pkg.libraries()]
else:
raise RuntimeError("This package currently only supports MacOSX and Linux builds")
# Add system include directories
extra_compile_args = []
system_includes = \
[blitz.get_include()] + \
blitz_pkg.include_directories() + \
[numpy.get_include()]
for k in system_includes: extra_compile_args += ['-isystem', k]
# NumPy API macros necessary?
define_macros=[
("PY_ARRAY_UNIQUE_SYMBOL", "XBOB_IO_PY_ARRAY_API"),
("NO_IMPORT_ARRAY", "1"),
]
import numpy
from distutils.version import StrictVersion
if StrictVersion(numpy.__version__) >= StrictVersion('1.7'):
define_macros.append(("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION"))
# Compilation options
if platform.system() == 'Darwin':
extra_compile_args += ['-std=c++11', '-Wno-#warnings']
else:
extra_compile_args += ['-std=c++11']
# Local include directory
import os
package_dir = os.path.dirname(os.path.realpath(__file__))
package_dir = os.path.join(package_dir, 'xbob', 'io', 'include')
include_dirs = [package_dir]
# Define package version
version = '2.0.0a0'
define_macros += [
("XBOB_CORE_VERSION", version),
]
setup(
name='xbob.io',
version=version,
description='Bindings for bob.io',
url='http://github.com/anjos/xbob.io',
license='BSD',
author='Andre Anjos',
author_email='andre.anjos@idiap.ch',
long_description=open('README.rst').read(),
packages=find_packages(),
include_package_data=True,
install_requires=[
'setuptools',
'blitz.array',
],
namespace_packages=[
"xbob",
],
ext_modules = [
Extension("xbob.io._library",
[
"xbob/io/file.cpp",
],
define_macros=define_macros,
include_dirs=include_dirs + bob_pkg.include_directories(),
extra_compile_args=extra_compile_args,
library_dirs=bob_pkg.library_directories(),
runtime_library_dirs=bob_pkg.library_directories(),
libraries=bob_libraries,
language="c++",
),
],
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
#see http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages
__import__('pkg_resources').declare_namespace(__name__)
from ._convert import convert
from . import log
from . import random
def get_include():
"""Returns the directory containing the C/C++ API include directives"""
return __import__('pkg_resources').resource_filename(__name__, 'include')
__all__ = ['convert', 'log', 'random']
/**
* @author Andre Anjos <andre.anjos@idiap.ch>
* @date Fri 1 Nov 07:10:59 2013
*
* @brief General directives for all modules in xbob.core
*/
#ifndef XBOB_CORE_CONFIG_H
#define XBOB_CORE_CONFIG_H
/* Macros that define versions and important names */
#define XBOB_IO_API_VERSION 0x0200
#endif /* XBOB_CORE_CONFIG_H */
xbob/io/test/data/img_indexed_color.png

1.06 KiB

File added
File added
xbob/io/test/data/test.jpg

216 B

0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment