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

Initial commit

parents
No related branches found
No related tags found
No related merge requests found
*~
*.swp
*.pyc
*.so
bin
eggs
parts
.installed.cfg
.mr.developer.cfg
*.egg-info
develop-eggs
sphinx
dist
.nfs*
.gdb_history
build
*.egg
src/
opsnr.stt
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
recursive-include xbob/machine/data *.*
.. vim: set fileencoding=utf-8 :
.. Andre Anjos <andre.anjos@idiap.ch>
.. Fri 13 Dec 2013 12:35:22 CET
=================================
Python bindings for bob.machine
=================================
This package contains a set of Pythonic bindings for Bob's machine 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 xbob.machine
.. 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.machine
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 = xbob.blitz xbob.math xbob.io xbob.math scripts
eggs = xbob.math
ipdb
extensions = mr.developer
auto-checkout = *
prefixes = /idiap/group/torch5spro/nightlies/last/install/linux-x86_64-release
debug = true
verbose = true
[sources]
xbob.buildout = git git@github.com:bioidiap/xbob.buildout
xbob.extension = git git@github.com:bioidiap/xbob.extension branch=xbob
[xbob.blitz]
recipe = xbob.buildout:develop
setup = src/xbob.blitz
eggs = xbob.buildout xbob.extension
[xbob.math]
recipe = xbob.buildout:develop
setup = src/xbob.math
eggs = xbob.blitz xbob.buildout xbob.extension
[xbob.io]
recipe = xbob.buildout:develop
setup = src/xbob.io
eggs = xbob.blitz xbob.buildout xbob.extension
[xbob.math]
recipe = xbob.buildout:develop
eggs = xbob.blitz
[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.machine`` allows users to leverage from automatic
converters for classes in :py:class:`xbob.machine`. To use the C API, clients
should first, include the header file ``<xbob.machine/api.h>`` on their
compilation units and then, make sure to call once ``import_xbob_machine()`` 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.machine/api.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_xbob_blitz();
// imports xbob.io C-API
import_xbob_io();
// imports xbob.machine C-API
import_xbob_machine();
}
.. note::
The include directory can be discovered using
:py:func:`xbob.machine.get_include`.
Activation Support
------------------
.. cpp:type:: PyBobMachineActivationObject
The pythonic object representation for a ``bob::machine::Activation``
object.
.. code-block:: cpp
typedef struct {
PyObject_HEAD
boost::shared_ptr<bob::machine::Activation> a;
} PyBobIoFileObject;
.. cpp:member:: boost::shared_ptr<bob::machine::Activation> a
A pointer to the activation function implementation
.. 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.machine'
import time
copyright = u'%s, Idiap Research Institute' % time.strftime('%Y')
# Grab the setup entry
distribution = pkg_resources.require('xbob.machine')[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_machine'
# 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_machine_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_machine.tex', u'Bob Machines',
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
.. |project| replace:: Bob
""" % (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_machine', u'Bob Machines 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
This diff is collapsed.
.. vim: set fileencoding=utf-8 :
.. Andre Anjos <andre.anjos@idiap.ch>
.. Fri 13 Dec 2013 12:50:06 CET
..
.. Copyright (C) 2011-2013 Idiap Research Institute, Martigny, Switzerland
==============
Bob Machines
==============
This module contains base functionality from Bob bound to Python, available in
the C++ counter-part ``bob::machine``. It includes machines from our Machine
Learning core.
Reference
---------
.. toctree::
:maxdepth: 2
guide
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
.. _argparse: http://code.google.com/p/argparse/
.. _blitz++: http://www.oonumerics.org/blitz
.. _bob's idiap guide: http://github.com/idiap/bob/wiki/Using-Bob-at-Idiap
.. _bob's website: https://www.idiap.ch/software/bob
.. _boost: http://www.boost.org
.. _buildbot: http://trac.buildbot.net
.. _buildout: http://pypi.python.org/pypi/zc.buildout/
.. _c++: http://www2.research.att.com/~bs/C++.html
.. _cmake: http://www.cmake.org
.. _doxygen: http://www.doxygen.org
.. _dvipng: http://savannah.nongnu.org/projects/dvipng/
.. _ffmpeg: http://ffmpeg.org
.. _libav: http://libav.org
.. _fftw: http://www.fftw.org/
.. _fink: http://www.finkproject.org
.. _git: http://git-scm.com/
.. _github: http://github.com/
.. _google perftools: http://code.google.com/p/google-perftools
.. _hdf5: http://www.hdfgroup.org/HDF5
.. _idiap: http://www.idiap.ch
.. _ipython: http://ipython.scipy.org
.. _lapack: http://www.netlib.org/lapack
.. _latex: http://www.latex-project.org/
.. _libjpeg: http://libjpeg.sourceforge.net/
.. _libnetpbm: http://netpbm.sourceforge.net/doc/libnetpbm.html
.. _libpng: http://libpng.org/pub/png/libpng.html
.. _libsvm: http://www.csie.ntu.edu.tw/~cjlin/libsvm/
.. _libtiff: http://www.remotesensing.org/libtiff/
.. _giflib: http://giflib.sourceforge.net/
.. _macports installation instructions: http://www.macports.org/install.php
.. _macports: http://www.macports.org
.. _matio: http://matio.sourceforge.net
.. _matlab: http://www.mathworks.ch/products/matlab/
.. _matplotlib: http://matplotlib.sourceforge.net
.. _numpy: http://numpy.scipy.org
.. _nose: http://nose.readthedocs.org
.. _opencv: http://opencv.willowgarage.com/
.. _pil: http://www.pythonware.com/products/pil/
.. _pillow: https://pypi.python.org/pypi/Pillow/
.. _python: http://www.python.org
.. _pypi: http://pypi.python.org
.. _qt4: http://qt.nokia.com/
.. _satellite packages: https://github.com/idiap/bob/wiki/Satellite-Packages
.. _scipy: http://www.scipy.org
.. _setuptools: http://trac.edgewall.org/wiki/setuptools
.. _sphinx: http://sphinx.pocoo.org
.. _sqlalchemy: http://www.sqlalchemy.org/
.. _sqlite: http://www.sqlite.org/
.. _submit a new bug report: https://github.com/idiap/bob/issues
.. _torch 3 vision: http://torch3vision.idiap.ch
.. _torch 3: http://www.torch.ch
.. _torch 5: http://torch5.sourceforge.net
.. _torch: https://github.com/andresy/torch
.. _vlfeat launchpad webpage: https://launchpad.net/~gezakovacs/+archive/vlfeat
.. _vlfeat: http://www.vlfeat.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>
.. Sat 16 Nov 20:52:58 2013
============
Python API
============
This section includes information for using the pure Python API of
``xbob.machine``.
.. automodule:: xbob.machine
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
dist.Distribution(dict(setup_requires=['xbob.blitz']))
from xbob.blitz.extension import Extension
packages = ['bob-machine >= 1.3']
version = '2.0.0a0'
setup(
name='xbob.machine',
version=version,
description='Bindings for bob.machine',
url='http://github.com/anjos/xbob.machine',
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',
'xbob.blitz',
'xbob.io',
],
namespace_packages=[
"xbob",
],
ext_modules = [
Extension("xbob.machine._externals",
[
"xbob/io/externals.cpp",
],
packages = packages,
include_dirs = include_dirs,
version = version,
),
Extension("xbob.machine._library",
[
#"xbob/measure/activation.cpp",
"xbob/measure/main.cpp",
],
packages = packages,
version = version,
),
],
entry_points={
'console_scripts': [
],
},
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__)
/**
* @author Andre Anjos <andre.anjos@idiap.ch>
* @date Wed 11 Dec 08:42:53 2013
*
* @brief Some C++ tricks to make our life dealing with Python references a bit
* easier
*/
#include <Python.h>
#include <memory>
/**
* Calls Py_DECREF(x) on the input object x. Usage pattern:
*
* PyObject* x = ... // builds x with a new python reference
* auto protected_x = make_safe(x);
*
* After this point, no need to worry about DECREF'ing x anymore.
* You can still use `x' inside your code, or protected_x.get().
*/
template <typename T> std::shared_ptr<T> make_safe(T* o) {
return std::shared_ptr<T>(o, [&](T* p){Py_DECREF(p);});
}
/**
* Calls Py_XDECREF(x) on the input object x. Usage pattern:
*
* PyObject* x = ... // builds x with a new python reference, x may be NULL
* auto protected_x = make_xsafe(x);
*
* After this point, no need to worry about XDECREF'ing x anymore.
* You can still use `x' inside your code, or protected_x.get(). Note
* `x' may be NULL with this method.
*/
template <typename T> std::shared_ptr<T> make_xsafe(T* o) {
return std::shared_ptr<T>(o, [&](T* p){Py_XDECREF(p);});
}
from ._library import *
from . import __linear__
from . import __mlp__
def ztnorm_same_value(vect_a, vect_b):
"""Computes the matrix of boolean D for the ZT-norm, which indicates where
the client ids of the T-Norm models and Z-Norm samples match.
vect_a An (ordered) list of client_id corresponding to the T-Norm models
vect_b An (ordered) list of client_id corresponding to the Z-Norm impostor samples
"""
from .. import core
import numpy as np
sameMatrix = np.ndarray((len(vect_a), len(vect_b)), 'bool')
for j in range(len(vect_a)):
for i in range(len(vect_b)):
sameMatrix[j, i] = (vect_a[j] == vect_b[i])
return sameMatrix
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.dos.anjos@gmail.com>
# Mon 24 Jun 11:03:59 2013
"""LinearMachine additions
"""
from . import LinearMachine, IdentityActivation
def linearmachine_repr(self):
"""A funky way to display a bob Linear Machine"""
if self.activation == IdentityActivation():
return '<LinearMachine %s@%s>' % (self.weights.dtype, self.weights.shape)
else:
return '<LinearMachine %s@%s [act: %s]>' % (self.weights.dtype, self.weights.shape, self.activation)
LinearMachine.__repr__ = linearmachine_repr
del linearmachine_repr
def linearmachine_str(self):
"""A funky way to print a bob Linear Machine"""
act = ""
if self.activation != IdentityActivation():
act = " [act: %s]" % self.activation
sub = ""
if not (self.input_subtract == 0.0).all():
sub = "\n subtract: %s" % self.input_subtract
div = ""
if not (self.input_divide == 1.0).all():
div = "\n divide: %s" % self.input_divide
bias = ""
if not (self.biases == 0.0).all():
bias = "\n bias: %s" % self.biases
shape = self.weights.shape
return 'LinearMachine (%s) %d inputs, %d outputs%s%s%s%s\n %s' % \
(self.weights.dtype, shape[0], shape[1], act, sub, div,
bias, self.weights)
LinearMachine.__str__ = linearmachine_str
del linearmachine_str
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Andre Anjos <andre.dos.anjos@gmail.com>
# Mon 24 Jun 11:01:07 2013
"""MLP additions
"""
from . import MLP
def mlp_repr(self):
"""A funky way to display a bob MLP"""
bias = False
for i, k in enumerate(self.biases):
if not (k == 0.0).all(): bias = True
if self.hidden_activation != self.output_activation:
return '<MLP %s@%s [bias: %s][act: {hidden}%s | {output}%s]>' % (self.weights[0].dtype, self.shape, str(bias).lower(), self.hidden_activation, self.output_activation)
else:
return '<MLP %s@%s [bias: %s][act: %s]>' % (self.weights[0].dtype, self.shape, str(bias).lower(), self.hidden_activation)
MLP.__repr__ = mlp_repr
del mlp_repr
def mlp_str(self):
"""A funky way to print a bob MLP"""
if self.hidden_activation != self.output_activation:
act = "[act: {hidden}%s | {output}%s]" % (self.hidden_activation, self.output_activation)
else:
act = "[act: %s]" % self.hidden_activation
sub = ""
if not (self.input_subtract == 0.0).all():
sub = "\n subtract: %s" % self.input_subtract
div = ""
if not (self.input_divide == 1.0).all():
div = "\n divide: %s" % self.input_divide
has_bias = False
bias = ""
for i, k in enumerate(self.biases):
if not (k == 0.0).all():
has_bias = True
bias += "\n bias[%d]:\n %s" % (i, k)
weight = ""
for i, k in enumerate(self.weights):
weight += "\n weight[%d]:\n %s" % (i, k)
return 'MLP %s@%s [bias: %s]%s%s%s%s%s' % \
(self.weights[0].dtype, self.shape, str(has_bias).lower(),
act, sub, div, bias, weight)
MLP.__str__ = mlp_str
del mlp_str
/**
* @file machine/python/activation.cc
* @date Thu Jul 7 16:49:35 2011 +0200
* @author Andre Anjos <andre.anjos@idiap.ch>
*
* Copyright (C) 2011-2013 Idiap Research Institute, Martigny, Switzerland
*/
#include <boost/python.hpp>
#include <boost/function.hpp>
#include <bob/python/ndarray.h>
#include <bob/machine/Activation.h>
#include <bob/machine/ActivationRegistry.h>
using namespace boost::python;
static bool activation_is_equal(boost::shared_ptr<bob::machine::Activation> a,
boost::shared_ptr<bob::machine::Activation> b) {
return a->str() == b->str();
}
/**
* Maps all elements of arr through function() into retval
*/
static void apply(boost::function<double (double)> function, bob::python::const_ndarray arr, bob::python::ndarray retval) {
const bob::core::array::typeinfo& info = arr.type();
if (!info.is_compatible(retval.type())) {
PYTHON_ERROR(RuntimeError, "input and output arrays are incompatible - input = %s; output = %s", info.str().c_str(), retval.type().str().c_str());
}
if (info.nd == 1) {
blitz::Array<double,1> arr_ = arr.bz<double,1>();
blitz::Array<double,1> retval_ = retval.bz<double,1>();
for (int k=0; k<arr_.extent(0); ++k)
retval_(k) = function(arr_(k));
}
else if (info.nd == 2) {
blitz::Array<double,2> arr_ = arr.bz<double,2>();
blitz::Array<double,2> retval_ = retval.bz<double,2>();
for (int k=0; k<arr_.extent(0); ++k)
for (int l=0; l<arr_.extent(1); ++l)
retval_(k,l) = function(arr_(k,l));
}
else if (info.nd == 3) {
blitz::Array<double,3> arr_ = arr.bz<double,3>();
blitz::Array<double,3> retval_ = retval.bz<double,3>();
for (int k=0; k<arr_.extent(0); ++k)
for (int l=0; l<arr_.extent(1); ++l)
for (int m=0; m<arr_.extent(2); ++m)
retval_(k,l,m) = function(arr_(k,l,m));
}
else if (info.nd == 4) {
blitz::Array<double,4> arr_ = arr.bz<double,4>();
blitz::Array<double,4> retval_ = retval.bz<double,4>();
for (int k=0; k<arr_.extent(0); ++k)
for (int l=0; l<arr_.extent(1); ++l)
for (int m=0; m<arr_.extent(2); ++m)
for (int n=0; n<arr_.extent(3); ++n)
retval_(k,l,m,n) = function(arr_(k,l,m,n));
}
else {
PYTHON_ERROR(RuntimeError, "function only accepts 1, 2, 3 or 4-dimensional double arrays (not %dD arrays)", (int)info.nd);
}
}
static object activation_f_ndarray_1(boost::shared_ptr<bob::machine::Activation> a, bob::python::const_ndarray arr, bob::python::ndarray retval) {
apply(boost::bind(&bob::machine::Activation::f, a, _1), arr, retval);
return retval.self();
}
static object activation_f_ndarray_2(boost::shared_ptr<bob::machine::Activation> a, bob::python::const_ndarray arr) {
bob::python::ndarray retval(arr.type());
return activation_f_ndarray_1(a, arr, retval);
}
static object activation_f_prime_ndarray_1(boost::shared_ptr<bob::machine::Activation> a, bob::python::const_ndarray arr, bob::python::ndarray retval) {
apply(boost::bind(&bob::machine::Activation::f_prime, a, _1), arr, retval);
return retval.self();
}
static object activation_f_prime_ndarray_2(boost::shared_ptr<bob::machine::Activation> a, bob::python::const_ndarray arr) {
bob::python::ndarray retval(arr.type());
return activation_f_prime_ndarray_1(a, arr, retval);
}
static object activation_f_prime_from_f_ndarray_1(boost::shared_ptr<bob::machine::Activation> a, bob::python::const_ndarray arr, bob::python::ndarray retval) {
apply(boost::bind(&bob::machine::Activation::f_prime_from_f, a, _1), arr, retval);
return retval.self();
}
static object activation_f_prime_from_f_ndarray_2(boost::shared_ptr<bob::machine::Activation> a, bob::python::const_ndarray arr) {
bob::python::ndarray retval(arr.type());
return activation_f_prime_from_f_ndarray_1(a, arr, retval);
}
void bind_machine_activation() {
class_<bob::machine::Activation, boost::shared_ptr<bob::machine::Activation>, boost::noncopyable>("Activation",
"Base class for activation functions", no_init)
.def("f", &activation_f_ndarray_1, (arg("self"), arg("z"), arg("res")), "Computes the activated value, given an input array ``z``, placing results in ``res`` (and returning it)")
.def("f", &activation_f_ndarray_2, (arg("self"), arg("z")), "Computes the activated value, given an input array ``z``. Returns a newly allocated array with the answers")
.def("f", &bob::machine::Activation::f, (arg("self"), arg("z")), "Computes the activated value, given an input ``z``")
.def("__call__", &activation_f_ndarray_1, (arg("self"), arg("z"), arg("res")), "Computes the activated value, given an input array ``z``, placing results in ``res`` (and returning it)")
.def("__call__", &activation_f_ndarray_2, (arg("self"), arg("z")), "Computes the activated value, given an input array ``z``. Returns a newly allocated array with the same size as ``z``")
.def("__call__", &bob::machine::Activation::f, (arg("self"), arg("z")), "Computes the activated value, given an input ``z``")
.def("f_prime", &activation_f_prime_ndarray_1, (arg("self"), arg("z"), arg("res")), "Computes the derivative of the activated value, placing results in ``res`` (and returning it)")
.def("f_prime", &activation_f_prime_ndarray_2, (arg("self"), arg("z")), "Computes the derivative of the activated value, given an input array ``z``. Returns a newly allocated array with the same size as ``z``")
.def("f_prime", &bob::machine::Activation::f_prime, (arg("self"), arg("z")), "Computes the derivative of the activated value.")
.def("f_prime_from_f", &activation_f_prime_from_f_ndarray_1, (arg("self"), arg("a"), arg("res")), "Computes the derivative of the activated value, given **the activated value** ``a``, placing results in ``res`` (and returning it)")
.def("f_prime_from_f", &activation_f_prime_from_f_ndarray_2, (arg("self"), arg("z")), "Computes the derivative of the activated value, given **the activated value** ``a``. Returns a newly allocated array with the same size as ``a`` with the answer.")
.def("f_prime_from_f", &bob::machine::Activation::f_prime_from_f, (arg("self"), arg("a")), "Computes the derivative of the activation value, given **the activated value** ``a``.")
.def("save", &bob::machine::Activation::save, (arg("self"), arg("h5f")),
"Saves itself to a :py:class:`bob.io.HDF5File`")
.def("load", &bob::machine::Activation::load, (arg("self"), arg("h5f")),
"Loads itself from a :py:class:`bob.io.HDF5File`")
.def("unique_identifier",
&bob::machine::Activation::unique_identifier, (arg("self")),
"Returns a unique identifier, used by this class in connection to the Activation registry.")
.def("__str__", &bob::machine::Activation::str)
.def("__eq__", &activation_is_equal)
;
class_<bob::machine::IdentityActivation, boost::shared_ptr<bob::machine::IdentityActivation>, bases<bob::machine::Activation> >("IdentityActivation", "Computes :math:`f(z) = z` as activation function", init<>((arg("self"))))
;
class_<bob::machine::LinearActivation, boost::shared_ptr<bob::machine::LinearActivation>, bases<bob::machine::Activation> >("LinearActivation", "Computes :math:`f(z) = C \\cdot z` as activation function", init<optional<double> >((arg("self"), arg("C")=1.), "Builds a new linear activation function with a given constant. Don't use this if you just want to set constant to the default value (1.0). In such a case, prefer to use the more efficient :py:class:`bob.machine.IdentityActivation`."))
.add_property("C", &bob::machine::LinearActivation::C, "The multiplication factor for the linear function")
;
class_<bob::machine::HyperbolicTangentActivation, boost::shared_ptr<bob::machine::HyperbolicTangentActivation>, bases<bob::machine::Activation> >("HyperbolicTangentActivation", "Computes :math:`f(z) = \\tanh(z)` as activation function", init<>((arg("self"))))
;
class_<bob::machine::MultipliedHyperbolicTangentActivation, boost::shared_ptr<bob::machine::MultipliedHyperbolicTangentActivation>, bases<bob::machine::Activation> >("MultipliedHyperbolicTangentActivation", "Computes :math:`f(z) = C \\cdot \\tanh(Mz)` as activation function", init<optional<double, double> >((arg("self"), arg("C")=1., arg("M")=1.), "Builds a new hyperbolic tangent activation fucntion with a given constant for the inner and outter products. Don't use this if you just want to set the constants to the default values (1.0). In such a case, prefer to use the more efficient :py:class:`bob.machine.HyperbolicTangentActivation`."))
.add_property("C", &bob::machine::MultipliedHyperbolicTangentActivation::C, "The outside multiplication factor for the hyperbolic tangent function")
.add_property("M", &bob::machine::MultipliedHyperbolicTangentActivation::M, "The inner multiplication factor for the argument")
;
class_<bob::machine::LogisticActivation, boost::shared_ptr<bob::machine::LogisticActivation>, bases<bob::machine::Activation> >("LogisticActivation", "Computes :math:`f(z)=1/(1+ e^{-z})` as activation function", init<>((arg("self"))))
;
}
/**
* @file machine/python/bic.cc
* @date Wed Jun 6 10:29:09 CEST 2012
* @author Manuel Guenther <Manuel.Guenther@idiap.ch>
*
* Copyright (C) 2011-2013 Idiap Research Institute, Martigny, Switzerland
*/
#include <bob/python/ndarray.h>
#include <boost/python.hpp>
#include <bob/machine/BICMachine.h>
#include <bob/io/HDF5File.h>
#include <bob/python/exception.h>
static double bic_call_(const bob::machine::BICMachine& machine, bob::python::const_ndarray input){
double o;
machine.forward_(input.bz<double,1>(), o);
return o;
}
static double bic_call(const bob::machine::BICMachine& machine, bob::python::const_ndarray input){
double o;
machine.forward(input.bz<double,1>(), o);
return o;
}
void bind_machine_bic(){
// bind BICMachine
boost::python::class_<bob::machine::BICMachine, boost::shared_ptr<bob::machine::BICMachine> > (
"BICMachine",
"This machine is designed to classify image differences to be either intrapersonal or extrapersonal. "
"There are two possible implementations of the BIC:\n"
"\n"
"* 'The Bayesian Intrapersonal/Extrapersonal Classifier' from Teixeira [1]_. "
" A full projection of the data is performed. No prior for the classes has to be selected.\n"
"* 'Face Detection and Recognition using Maximum Likelihood Classifiers on Gabor Graphs' from Guenther and Wuertz [2]_."
" Only mean and variance of the difference vectors are calculated. There is no subspace truncation and no priors.\n"
"\n"
"What kind of machine is used is dependent on the way, this class is trained via the BICTrainer.\n"
"\n"
".. [1] Marcio Luis Teixeira. The Bayesian intrapersonal/extrapersonal classifier. Colorado State University, 2003.\n"
".. [2] Manuel Guenther and Rolf P. Wuertz. Face detection and recognition using maximum likelihood classifiers on Gabor graphs. International Journal of Pattern Recognition and Artificial Intelligence, 23(3):433-461, 2009.",
boost::python::init<bool>(
(boost::python::arg("self"), boost::python::arg("use_dffs") = false),
"Initializes an empty BICMachine. The optional boolean parameter specifies whether to use the DFFS in the BIC implementation. \n\n.. warning :: Use this flag with care, the default value 'False' is usually the best choice!"
)
)
.def(
boost::python::init<const bob::machine::BICMachine&>(
(boost::python::arg("self"), boost::python::arg("other")),
"Constructs one BICMachine from another one by doing a deep copy."
)
)
.def(
boost::python::self == boost::python::self
)
.def(
"is_similar_to",
&bob::machine::BICMachine::is_similar_to,
(boost::python::arg("self"), boost::python::arg("other"), boost::python::arg("r_epsilon") = 1e-5, boost::python::arg("a_epsilon") = 1e-8),
"Compares this BICMachine with the 'other' one to be approximately the same."
)
.def(
"load",
&bob::machine::BICMachine::load,
(boost::python::arg("self"), boost::python::arg("file")),
"Loads the configuration parameters from an hdf5 file."
)
.def(
"save",
&bob::machine::BICMachine::save,
(boost::python::arg("self"), boost::python::arg("file")),
"Saves the configuration parameters to an hdf5 file."
)
.def(
"__call__",
&bic_call,
(
boost::python::arg("self"),
boost::python::arg("input")
),
"Computes the BIC or IEC score for the given input vector, which results of a comparison of two (facial) images. "
"The resulting value is returned as a single float value. "
"The score itself is the log-likelihood score of the given input vector belonging to the intrapersonal class. "
"No sanity checks of input and output are performed."
)
.def(
"forward_",
&bic_call_,
(
boost::python::arg("self"),
boost::python::arg("input")
),
"Computes the BIC or IEC score for the given input vector, which results of a comparison of two (facial) images. "
"The score itself is the log-likelihood score of the given input vector belonging to the intrapersonal class. "
"No sanity checks of input are performed."
)
.def(
"forward",
&bic_call,
(
boost::python::arg("self"),
boost::python::arg("input")
),
"Computes the BIC or IEC score for the given input vector, which results of a comparison of two (facial) images. "
"The score itself is the log-likelihood score of the given input vector belonging to the intrapersonal class. "
"Sanity checks of input shape are performed."
)
.add_property(
"use_dffs",
// cast overloaded function with the same name to its type...
static_cast<bool (bob::machine::BICMachine::*)() const>(&bob::machine::BICMachine::use_DFFS),
static_cast<void (bob::machine::BICMachine::*)(bool)>(&bob::machine::BICMachine::use_DFFS),
"Should the Distance From Feature Space (DFFS) measure be added during scoring? \n\n.. warning :: Only set this flag to True if the number of intrapersonal and extrapersonal training pairs is approximately equal. Otherwise, weird thing may happen!"
);
}
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