2
0
mirror of https://github.com/boostorg/python.git synced 2026-01-19 04:22:16 +00:00
This commit is contained in:
Stefan Seefeld
2016-10-07 20:03:12 -04:00
64 changed files with 5131 additions and 35 deletions

4
.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
bin.SCons
*.pyc
*~
\#*\#

23
LICENSE_1_0.txt Normal file
View File

@@ -0,0 +1,23 @@
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@@ -68,4 +68,4 @@ Run
```
scons doc
```
to build the documentation.
to build the documentation.

View File

@@ -1,34 +0,0 @@
# -*- python -*-
Import("env")
env.Append(CPPPATH = "#/include",CPPDEFINES = ["BOOST_ALL_NO_LIB=1"])
env.AppendUnique(CPPDEFINES = ["${LINK_DYNAMIC and 'BOOST_PYTHON_DYN_LINK=1' or []}"])
for variant in env["variant"]:
env["current_variant"] = variant
env.SetProperty(profile = False)
if variant == "release":
env.SetProperty(optimize = "speed", debug = False)
elif variant == "debug":
env.SetProperty(optimize = "no", debug = True)
elif variant == "profile":
env.SetProperty(optimize = "speed", profile = True, debug = True)
for linking in env["link"]:
env["linking"] = linking
if linking == "dynamic":
env["LINK_DYNAMIC"] = True
else:
env["LINK_DYNAMIC"] = False
for threading in env["threading"]:
env["current_threading"] = threading
env.SetProperty(threading = threading)
variant_dir=env.subst("$BOOST_CURRENT_VARIANT_DIR")
env.SConscript("src/SConscript", variant_dir=variant_dir + '/src',
exports = { "env" : env.Clone(BOOST_LIB = 'python') })
if GetOption("test"):
test_env = env.Clone(BOOST_LIB = 'python', BOOST_TEST = True)
test_env.BoostUseLib('python')
env.SConscript("test/SConscript", variant_dir=variant_dir + '/test',
exports = { "env" : test_env })

132
doc/numpy/Makefile Normal file
View File

@@ -0,0 +1,132 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest
all: html
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/BoostNumPy.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/BoostNumPy.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/BoostNumPy"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/BoostNumPy"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
make -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."

View File

@@ -0,0 +1,66 @@
/*=============================================================================
Copyright 2002 William E. Kempf
Distributed under the Boost Software License, Version 1.0. (See accompany-
ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
H1
{
FONT-SIZE: 200%;
COLOR: #00008B;
}
H2
{
FONT-SIZE: 150%;
}
H3
{
FONT-SIZE: 125%;
}
H4
{
FONT-SIZE: 108%;
}
BODY
{
FONT-SIZE: 100%;
BACKGROUND-COLOR: #ffffff;
COLOR: #000000;
}
PRE
{
MARGIN-LEFT: 2em;
FONT-FAMILY: Courier,
monospace;
}
CODE
{
FONT-FAMILY: Courier,
monospace;
}
CODE.as_pre
{
white-space: pre;
}
.index
{
TEXT-ALIGN: left;
}
.page-index
{
TEXT-ALIGN: left;
}
.definition
{
TEXT-ALIGN: left;
}
.footnote
{
FONT-SIZE: 66%;
VERTICAL-ALIGN: super;
TEXT-DECORATION: none;
}
.function-semantics
{
CLEAR: left;
}

BIN
doc/numpy/_static/boost.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

BIN
doc/numpy/_static/home.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 358 B

BIN
doc/numpy/_static/next.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 336 B

BIN
doc/numpy/_static/prev.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 334 B

View File

@@ -0,0 +1,11 @@
@import url(boost.css);
#contents
{
/* border-bottom: solid thin black;*/
}
.highlight
{
border: 1px solid #aaaaaa;
}

BIN
doc/numpy/_static/up.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 370 B

View File

@@ -0,0 +1,120 @@
{%- macro navbar() %}
<div class="navbar" style="text-align:right;">
{#%- if parents|count > 0 %#}
{#{ parents[1].title }#}
{%- if prev %}
<a class="prev" title="{{ prev.title|striptags|e }}" href="{{ prev.link|e }}"><img src="{{ pathto('_static/prev.png', 1) }}" alt="prev"/></a>
{%- endif %}
{%- if parents %}
<a class="up" title="{{ parents[-1].title|striptags|e }}" href="{{ parents[-1].link|e }}"><img src="{{ pathto('_static/up.png', 1) }}" alt="up"/></a>
{%- endif %}
{%- if next %}
<a class="next" title="{{ next.title|striptags|e }}" href="{{ next.link|e }}"><img src="{{ pathto('_static/next.png', 1) }}" alt="next"/></a>
{%- endif %}
{#%- endif %#}
</div>
{%- endmacro %}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
{{ metatags }}
{%- if builder != 'htmlhelp' %}
{%- set titlesuffix = docstitle|e %}
{%- set titlesuffix = " - " + titlesuffix %}
{%- endif %}
<title>{{ title|striptags }}{{ titlesuffix }}</title>
{%- if builder == 'web' %}
<link rel="stylesheet" href="{{ pathto('index') }}?do=stylesheet{%
if in_admin_panel %}&admin=yes{% endif %}" type="text/css" />
{%- for link, type, title in page_links %}
<link rel="alternate" type="{{ type|e(true) }}" title="{{ title|e(true) }}" href="{{ link|e(true) }}" />
{%- endfor %}
{%- else %}
<link rel="stylesheet" href="{{ pathto('_static/style.css', 1) }}" type="text/css" />
<link rel="stylesheet" href="{{ pathto('_static/pygments.css', 1) }}" type="text/css" />
{%- endif %}
{%- if builder != 'htmlhelp' %}
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '{{ pathto("", 1) }}',
VERSION: '{{ release|e }}',
COLLAPSE_MODINDEX: false,
FILE_SUFFIX: '{{ file_suffix }}'
};
</script>
{%- for scriptfile in script_files %}
<script type="text/javascript" src="{{ pathto(scriptfile, 1) }}"></script>
{%- endfor %}
{%- if use_opensearch %}
<link rel="search" type="application/opensearchdescription+xml"
title="{% trans docstitle=docstitle|e %}Search within {{ docstitle }}{% endtrans %}"
href="{{ pathto('_static/opensearch.xml', 1) }}"/>
{%- endif %}
{%- if favicon %}
<link rel="shortcut icon" href="{{ pathto('_static/' + favicon, 1) }}"/>
{%- endif %}
{%- endif %}
{%- block linktags %}
{%- if hasdoc('about') %}
<link rel="author" title="{{ _('About these documents') }}" href="{{ pathto('about') }}" />
{%- endif %}
<link rel="index" title="{{ _('Index') }}" href="{{ pathto('genindex') }}" />
<link rel="search" title="{{ _('Search') }}" href="{{ pathto('search') }}" />
{%- if hasdoc('copyright') %}
<link rel="copyright" title="{{ _('Copyright') }}" href="{{ pathto('copyright') }}" />
{%- endif %}
<link rel="top" title="{{ docstitle|e }}" href="{{ pathto('index') }}" />
{%- if parents %}
<link rel="up" title="{{ parents[-1].title|striptags }}" href="{{ parents[-1].link|e }}" />
{%- endif %}
{%- if next %}
<link rel="next" title="{{ next.title|striptags }}" href="{{ next.link|e }}" />
{%- endif %}
{%- if prev %}
<link rel="prev" title="{{ prev.title|striptags }}" href="{{ prev.link|e }}" />
{%- endif %}
{%- endblock %}
{%- block extrahead %} {% endblock %}
</head>
<body>
<div class="header">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary=
"header">
<tr>
<td valign="top" width="300">
<h3><a href="{{ pathto('index') }}"><img height="86" width="277"
alt="C++ Boost" src="{{ pathto('_static/' + logo, 1) }}" border="0"></a></h3>
</td>
<td valign="top">
<h1 align="center"><a href="{{ pathto('index') }}">Boost.NumPy</a></h1>
<!-- <h2 align="center">CallPolicies Concept</h2>-->
</td>
<td>
{%- if pagename != "search" %}
<div id="searchbox" style="display: none">
<form class="search" action="{{ pathto('search') }}" method="get">
<input type="text" name="q" size="18" />
<input type="submit" value="{{ _('Search') }}" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
{%- endif %}
</td>
</tr>
</table>
</div>
<hr/>
<div class="content">
{%- block top_navbar %}{{ navbar() }}{% endblock %}
{% block body %} {% endblock %}
{%- block bottom_navbar %}{{ navbar() }}{% endblock %}
</div>
</body>
</html>

219
doc/numpy/conf.py Normal file
View File

@@ -0,0 +1,219 @@
# -*- coding: utf-8 -*-
#
# Boost.NumPy documentation build configuration file, created by
# sphinx-quickstart on Thu Oct 27 09:04:58 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# 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 = []
# 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'Boost.NumPy'
copyright = u'2011, Stefan Seefeld'
# 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 = '1.0'
# The full version, including alpha/beta/rc tags.
release = '1.0'
# 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 = ['_build']
# 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 = 'default'
highlight_language = 'c++'
# 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.
html_theme = 'default'
# 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 = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = '_static/boost.png'
# 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 = None
# 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 = 'BoostNumPydoc'
html_add_permalinks = False
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# 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', 'BoostNumPy.tex', u'Boost.NumPy Documentation',
u'Stefan Seefeld', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# 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
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'boostnumpy', u'Boost.NumPy Documentation',
[u'Stefan Seefeld'], 1)
]

17
doc/numpy/index.rst Normal file
View File

@@ -0,0 +1,17 @@
.. Boost.NumPy documentation master file, created by
sphinx-quickstart on Thu Oct 27 09:04:58 2011.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to Boost.NumPy's documentation!
=======================================
Contents:
.. toctree::
:maxdepth: 2
Tutorial <tutorial/index>
Reference <reference/index>
cmakeBuild.rst

170
doc/numpy/make.bat Normal file
View File

@@ -0,0 +1,170 @@
@ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. changes to make an overview over all changed/added/deprecated items
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\BoostNumPy.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\BoostNumPy.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
:end

View File

@@ -0,0 +1,104 @@
binary_ufunc
============
.. contents ::
A ``binary_ufunc`` is a struct used as an intermediate step to broadcast two arguments so that a C++ function can be converted to a ufunc like function
``<boost/numpy/ufunc.hpp>`` contains the ``binary_ufunc`` structure definitions
synopsis
--------
::
namespace boost
{
namespace numpy
{
template <typename TBinaryFunctor,
typename TArgument1=typename TBinaryFunctor::first_argument_type,
typename TArgument2=typename TBinaryFunctor::second_argument_type,
typename TResult=typename TBinaryFunctor::result_type>
struct binary_ufunc
{
static python::object call(TBinaryFunctor & self,
python::object const & input1,
python::object const & input2,
python::object const & output);
static python::object make();
};
}
}
constructors
------------
::
struct example_binary_ufunc
{
typedef any_valid first_argument_type;
typedef any_valid second_argument_type;
typedef any_valid result_type;
};
:Requirements: The ``any_valid`` type must be defined using typedef as a valid C++ type in order to use the struct methods correctly
:Note: The struct must be exposed as a Python class, and an instance of the class must be created to use the ``call`` method corresponding to the ``__call__`` attribute of the Python object
accessors
---------
::
template <typename TBinaryFunctor,
typename TArgument1=typename TBinaryFunctor::first_argument_type,
typename TArgument2=typename TBinaryFunctor::second_argument_type,
typename TResult=typename TBinaryFunctor::result_type>
static python::object call(TBinaryFunctor & self,
python::object const & input,
python::object const & output);
:Requires: Typenames ``TBinaryFunctor`` and optionally ``TArgument1`` and ``TArgument2`` for argument type and ``TResult`` for result type
:Effects: Passes a Python object to the underlying C++ functor after broadcasting its arguments
::
template <typename TBinaryFunctor,
typename TArgument1=typename TBinaryFunctor::first_argument_type,
typename TArgument2=typename TBinaryFunctor::second_argument_type,
typename TResult=typename TBinaryFunctor::result_type>
static python::object make();
:Requires: Typenames ``TBinaryFunctor`` and optionally ``TArgument1`` and ``TArgument2`` for argument type and ``TResult`` for result type
:Returns: A Python function object to call the overloaded () operator in the struct (in typical usage)
Example(s)
----------
::
struct BinarySquare
{
typedef double first_argument_type;
typedef double second_argument_type;
typedef double result_type;
double operator()(double a,double b) const { return (a*a + b*b) ; }
};
p::object ud = p::class_<BinarySquare, boost::shared_ptr<BinarySquare> >("BinarySquare").def("__call__", np::binary_ufunc<BinarySquare>::make());
p::object inst = ud();
result_array = inst.attr("__call__")(demo_array,demo_array) ;
std::cout << "Square of list with binary ufunc is " << p::extract <char const * > (p::str(result_array)) << std::endl ;

View File

@@ -0,0 +1,86 @@
dtype
=====
.. contents ::
A `dtype`_ is an object describing the type of the elements of an ndarray
.. _dtype: http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html#data-type-objects-dtype
``<boost/numpy/dtype.hpp>`` contains the method calls necessary to generate a python object equivalent to a numpy.dtype from builtin C++ objects, as well as to create custom dtypes from user defined types
synopsis
--------
::
namespace boost
{
namespace numpy
{
class dtype : public python::object
{
static python::detail::new_reference convert(python::object::object_cref arg, bool align);
public:
// Convert an arbitrary Python object to a data-type descriptor object.
template <typename T>
explicit dtype(T arg, bool align=false);
// Get the built-in numpy dtype associated with the given scalar template type.
template <typename T> static dtype get_builtin();
// Return the size of the data type in bytes.
int get_itemsize() const;
};
}
constructors
------------
::
template <typename T>
explicit dtype(T arg, bool align=false)
:Requirements: ``T`` must be either :
* a built-in C++ typename convertible to object
* a valid python object or convertible to object
:Effects: Constructs an object from the supplied python object / convertible
to object / builtin C++ data type
:Throws: Nothing
::
template <typename T> static dtype get_builtin();
:Requirements: The typename supplied, ``T`` must be a builtin C++ type also supported by numpy
:Returns: Numpy dtype corresponding to builtin C++ type
accessors
---------
::
int get_itemsize() const;
:Returns: the size of the data type in bytes.
Example(s)
----------
::
namespace np = boost::numpy;
np::dtype dtype = np::dtype::get_builtin<double>();
p::tuple for_custom_dtype = p::make_tuple("ha",dtype);
np::dtype custom_dtype = np::dtype(list_for_dtype);

View File

@@ -0,0 +1,14 @@
Boost.NumPy Reference
=====================
Contents:
.. toctree::
:maxdepth: 2
dtype
ndarray
unary_ufunc
binary_ufunc
multi_iter

View File

@@ -0,0 +1,91 @@
multi_iter
==========
.. contents ::
A ``multi_iter`` is a Python object, intended to be used as an iterator It should generally only be used in loops.
``<boost/numpy/ufunc.hpp>`` contains the class definitions for ``multi_iter``
synopsis
--------
::
namespace boost
{
namespace numpy
{
class multi_iter : public python::object
{
public:
void next();
bool not_done() const;
char * get_data(int n) const;
int const get_nd() const;
Py_intptr_t const * get_shape() const;
Py_intptr_t const shape(int n) const;
};
multi_iter make_multi_iter(python::object const & a1);
multi_iter make_multi_iter(python::object const & a1, python::object const & a2);
multi_iter make_multi_iter(python::object const & a1, python::object const & a2, python::object const & a3);
}
}
constructors
------------
::
multi_iter make_multi_iter(python::object const & a1);
multi_iter make_multi_iter(python::object const & a1, python::object const & a2);
multi_iter make_multi_iter(python::object const & a1, python::object const & a2, python::object const & a3);
:Returns: A Python iterator object broadcasting over one, two or three sequences as supplied
accessors
---------
::
void next();
:Effects: Increments the iterator
::
bool not_done() const;
:Returns: boolean value indicating whether the iterator is at its end
::
char * get_data(int n) const;
:Returns: a pointer to the element of the nth broadcasted array.
::
int const get_nd() const;
:Returns: the number of dimensions of the broadcasted array expression
::
Py_intptr_t const * get_shape() const;
:Returns: the shape of the broadcasted array expression as an array of integers.
::
Py_intptr_t const shape(int n) const;
:Returns: the shape of the broadcasted array expression in the nth dimension.

View File

@@ -0,0 +1,377 @@
ndarray
=======
.. contents ::
A `ndarray`_ is an N-dimensional array which contains items of the same type and size, where N is the number of dimensions and is specified in the form of a ``shape`` tuple. Optionally, the numpy ``dtype`` for the objects contained may also be specified.
.. _ndarray: http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html
.. _dtype: http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html#data-type-objects-dtype
``<boost/numpy/ndarray.hpp>`` contains the structures and methods necessary to move raw data between C++ and Python and create ndarrays from the data
synopsis
--------
::
namespace boost
{
namespace numpy
{
class ndarray : public python::object
{
public:
enum bitflag
{
NONE=0x0, C_CONTIGUOUS=0x1, F_CONTIGUOUS=0x2, V_CONTIGUOUS=0x1|0x2,
ALIGNED=0x4, WRITEABLE=0x8, BEHAVED=0x4|0x8,
CARRAY_RO=0x1|0x4, CARRAY=0x1|0x4|0x8, CARRAY_MIS=0x1|0x8,
FARRAY_RO=0x2|0x4, FARRAY=0x2|0x4|0x8, FARRAY_MIS=0x2|0x8,
UPDATE_ALL=0x1|0x2|0x4, VARRAY=0x1|0x2|0x8, ALL=0x1|0x2|0x4|0x8
};
ndarray view(dtype const & dt) const;
ndarray astype(dtype const & dt) const;
ndarray copy() const;
int const shape(int n) const;
int const strides(int n) const;
char * get_data() const;
dtype get_dtype() const;
python::object get_base() const;
void set_base(object const & base);
Py_intptr_t const * get_shape() const;
Py_intptr_t const * get_strides() const;
int const get_nd() const;
bitflag const get_flags() const;
ndarray transpose() const;
ndarray squeeze() const;
ndarray reshape(python::tuple const & shape) const;
python::object scalarize() const;
};
ndarray zeros(python::tuple const & shape, dtype const & dt);
ndarray zeros(int nd, Py_intptr_t const * shape, dtype const & dt);
ndarray empty(python::tuple const & shape, dtype const & dt);
ndarray empty(int nd, Py_intptr_t const * shape, dtype const & dt);
ndarray array(python::object const & obj);
ndarray array(python::object const & obj, dtype const & dt);
template <typename Container>
ndarray from_data(void * data,dtype const & dt,Container shape,Container strides,python::object const & owner);
template <typename Container>
ndarray from_data(void const * data, dtype const & dt, Container shape, Container strides, python::object const & owner);
ndarray from_object(python::object const & obj, dtype const & dt,int nd_min, int nd_max, ndarray::bitflag flags=ndarray::NONE);
ndarray from_object(python::object const & obj, dtype const & dt,int nd, ndarray::bitflag flags=ndarray::NONE);
ndarray from_object(python::object const & obj, dtype const & dt, ndarray::bitflag flags=ndarray::NONE);
ndarray from_object(python::object const & obj, int nd_min, int nd_max,ndarray::bitflag flags=ndarray::NONE);
ndarray from_object(python::object const & obj, int nd, ndarray::bitflag flags=ndarray::NONE);
ndarray from_object(python::object const & obj, ndarray::bitflag flags=ndarray::NONE)
ndarray::bitflag operator|(ndarray::bitflag a, ndarray::bitflag b) ;
ndarray::bitflag operator&(ndarray::bitflag a, ndarray::bitflag b);
}
constructors
------------
::
ndarray view(dtype const & dt) const;
:Returns: new ndarray with old ndarray data cast as supplied dtype
::
ndarray astype(dtype const & dt) const;
:Returns: new ndarray with old ndarray data converted to supplied dtype
::
ndarray copy() const;
:Returns: Copy of calling ndarray object
::
ndarray transpose() const;
:Returns: An ndarray with the rows and columns interchanged
::
ndarray squeeze() const;
:Returns: An ndarray with all unit-shaped dimensions removed
::
ndarray reshape(python::tuple const & shape) const;
:Requirements: The new ``shape`` of the ndarray must be supplied as a tuple
:Returns: An ndarray with the same data but reshaped to the ``shape`` supplied
::
python::object scalarize() const;
:Returns: A scalar if the ndarray has only one element, otherwise it returns the entire array
::
ndarray zeros(python::tuple const & shape, dtype const & dt);
ndarray zeros(int nd, Py_intptr_t const * shape, dtype const & dt);
:Requirements: The following parameters must be supplied as required :
* the ``shape`` or the size of all dimensions, as a tuple
* the ``dtype`` of the data
* the ``nd`` size for a square shaped ndarray
* the ``shape`` Py_intptr_t
:Returns: A new ndarray with the given shape and data type, with data initialized to zero.
::
ndarray empty(python::tuple const & shape, dtype const & dt);
ndarray empty(int nd, Py_intptr_t const * shape, dtype const & dt);
:Requirements: The following parameters must be supplied :
* the ``shape`` or the size of all dimensions, as a tuple
* the ``dtype`` of the data
* the ``shape`` Py_intptr_t
:Returns: A new ndarray with the given shape and data type, with data left uninitialized.
::
ndarray array(python::object const & obj);
ndarray array(python::object const & obj, dtype const & dt);
:Returns: A new ndarray from an arbitrary Python sequence, with dtype of each element specified optionally
::
template <typename Container>
inline ndarray from_data(void * data,dtype const & dt,Container shape,Container strides,python::object const & owner)
:Requirements: The following parameters must be supplied :
* the ``data`` which is a generic C++ data container
* the dtype ``dt`` of the data
* the ``shape`` of the ndarray as Python object
* the ``strides`` of each dimension of the array as a Python object
* the ``owner`` of the data, in case it is not the ndarray itself
:Returns: ndarray with attributes and data supplied
:Note: The ``Container`` typename must be one that is convertible to a std::vector or python object type
::
ndarray from_object(python::object const & obj, dtype const & dt,int nd_min, int nd_max, ndarray::bitflag flags=ndarray::NONE);
:Requirements: The following parameters must be supplied :
* the ``obj`` Python object to convert to ndarray
* the dtype ``dt`` of the data
* minimum number of dimensions ``nd_min`` of the ndarray as Python object
* maximum number of dimensions ``nd_max`` of the ndarray as Python object
* optional ``flags`` bitflags
:Returns: ndarray constructed with dimensions and data supplied as parameters
::
inline ndarray from_object(python::object const & obj, dtype const & dt, int nd, ndarray::bitflag flags=ndarray::NONE);
:Requirements: The following parameters must be supplied :
* the ``obj`` Python object to convert to ndarray
* the dtype ``dt`` of the data
* number of dimensions ``nd`` of the ndarray as Python object
* optional ``flags`` bitflags
:Returns: ndarray with dimensions ``nd`` x ``nd`` and suplied parameters
::
inline ndarray from_object(python::object const & obj, dtype const & dt, ndarray::bitflag flags=ndarray::NONE)
:Requirements: The following parameters must be supplied :
* the ``obj`` Python object to convert to ndarray
* the dtype ``dt`` of the data
* optional ``flags`` bitflags
:Returns: Supplied Python object as ndarray
::
ndarray from_object(python::object const & obj, int nd_min, int nd_max, ndarray::bitflag flags=ndarray::NONE);
:Requirements: The following parameters must be supplied :
* the ``obj`` Python object to convert to ndarray
* minimum number of dimensions ``nd_min`` of the ndarray as Python object
* maximum number of dimensions ``nd_max`` of the ndarray as Python object
* optional ``flags`` bitflags
:Returns: ndarray with supplied dimension limits and parameters
:Note: dtype need not be supplied here
::
inline ndarray from_object(python::object const & obj, int nd, ndarray::bitflag flags=ndarray::NONE);
:Requirements: The following parameters must be supplied :
* the ``obj`` Python object to convert to ndarray
* the dtype ``dt`` of the data
* number of dimensions ``nd`` of the ndarray as Python object
* optional ``flags`` bitflags
:Returns: ndarray of ``nd`` x ``nd`` dimensions constructed from the supplied object
::
inline ndarray from_object(python::object const & obj, ndarray::bitflag flags=ndarray::NONE)
:Requirements: The following parameters must be supplied :
* the ``obj`` Python object to convert to ndarray
* optional ``flags`` bitflags
:Returns: ndarray of same dimensions and dtype as supplied Python object
accessors
---------
::
int const shape(int n) const;
:Returns: The size of the n-th dimension of the ndarray
::
int const strides(int n) const;
:Returns: The stride of the nth dimension.
::
char * get_data() const;
:Returns: Array's raw data pointer as a char
:Note: This returns char so stride math works properly on it.User will have to reinterpret_cast it.
::
dtype get_dtype() const;
:Returns: Array's data-type descriptor object (dtype)
::
python::object get_base() const;
:Returns: Object that owns the array's data, or None if the array owns its own data.
::
void set_base(object const & base);
:Returns: Set the object that owns the array's data. Exercise caution while using this
::
Py_intptr_t const * get_shape() const;
:Returns: Shape of the array as an array of integers
::
Py_intptr_t const * get_strides() const;
:Returns: Stride of the array as an array of integers
::
int const get_nd() const;
:Returns: Number of array dimensions
::
bitflag const get_flags() const;
:Returns: Array flags
::
inline ndarray::bitflag operator|(ndarray::bitflag a, ndarray::bitflag b)
:Returns: bitflag logically OR-ed as (a | b)
::
inline ndarray::bitflag operator&(ndarray::bitflag a, ndarray::bitflag b)
:Returns: bitflag logically AND-ed as (a & b)
Example(s)
----------
::
p::object tu = p::make_tuple('a','b','c') ;
np::ndarray example_tuple = np::array (tu) ;
p::list l ;
np::ndarray example_list = np::array (l) ;
np::dtype dt = np::dtype::get_builtin<int>();
np::ndarray example_list1 = np::array (l,dt);
int data[] = {1,2,3,4} ;
p::tuple shape = p::make_tuple(4) ;
p::tuple stride = p::make_tuple(4) ;
p::object own ;
np::ndarray data_ex = np::from_data(data,dt,shape,stride,own);
uint8_t mul_data[][4] = {{1,2,3,4},{5,6,7,8},{1,3,5,7}};
shape = p::make_tuple(3,2) ;
stride = p::make_tuple(4,2) ;
np::dtype dt1 = np::dtype::get_builtin<uint8_t>();
np::ndarray mul_data_ex = np::from_data(mul_data,dt1, p::make_tuple(3,4),p::make_tuple(4,1),p::object());
mul_data_ex = np::from_data(mul_data,dt1, shape,stride,p::object());

View File

@@ -0,0 +1,97 @@
unary_ufunc
===========
.. contents ::
A ``unary_ufunc`` is a struct used as an intermediate step to broadcast a single argument so that a C++ function can be converted to a ufunc like function
``<boost/numpy/ufunc.hpp>`` contains the ``unary_ufunc`` structure definitions
synopsis
--------
::
namespace boost
{
namespace numpy
{
template <typename TUnaryFunctor,
typename TArgument=typename TUnaryFunctor::argument_type,
typename TResult=typename TUnaryFunctor::result_type>
struct unary_ufunc
{
static python::object call(TUnaryFunctor & self,
python::object const & input,
python::object const & output) ;
static python::object make();
};
}
}
constructors
------------
::
struct example_unary_ufunc
{
typedef any_valid_type argument_type;
typedef any_valid_type result_type;
};
:Requirements: The ``any_valid`` type must be defined using typedef as a valid C++ type in order to use the struct methods correctly
:Note: The struct must be exposed as a Python class, and an instance of the class must be created to use the ``call`` method corresponding to the ``__call__`` attribute of the Python object
accessors
---------
::
template <typename TUnaryFunctor,
typename TArgument=typename TUnaryFunctor::argument_type,
typename TResult=typename TUnaryFunctor::result_type>
static python::object call(TUnaryFunctor & self,
python::object const & input,
python::object const & output);
:Requires: Typenames ``TUnaryFunctor`` and optionally ``TArgument`` for argument type and ``TResult`` for result type
:Effects: Passes a Python object to the underlying C++ functor after broadcasting its arguments
::
template <typename TUnaryFunctor,
typename TArgument=typename TUnaryFunctor::argument_type,
typename TResult=typename TUnaryFunctor::result_type>
static python::object make();
:Requires: Typenames ``TUnaryFunctor`` and optionally ``TArgument`` for argument type and ``TResult`` for result type
:Returns: A Python function object to call the overloaded () operator in the struct (in typical usage)
Example(s)
----------
::
struct UnarySquare
{
typedef double argument_type;
typedef double result_type;
double operator()(double r) const { return r * r;}
};
p::object ud = p::class_<UnarySquare, boost::shared_ptr<UnarySquare> >("UnarySquare").def("__call__", np::unary_ufunc<UnarySquare>::make());
p::object inst = ud();
std::cout << "Square of unary scalar 1.0 is " << p::extract <char const * > (p::str(inst.attr("__call__")(1.0))) << std::endl ;

149
doc/numpy/rst.css Normal file
View File

@@ -0,0 +1,149 @@
@import url("doc/src/boostbook.css");
@import url("doc/src/docutils.css");
/* Copyright David Abrahams 2006. Distributed under the Boost
Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
dl.docutils dt {
font-weight: bold }
img.boost-logo {
border: none;
vertical-align: middle
}
pre.literal-block span.concept {
font-style: italic;
}
.nav {
display: inline;
list-style-type: none;
}
.prevpage {
padding-top: -5px;
text-align: left;
float: left;
}
.nextpage {
padding-top: -20px;
text-align: right;
float: right;
}
div.small {
font-size: smaller }
h2 a {
font-size: 90%;
}
h3 a {
font-size: 80%;
}
h4 a {
font-size: 70%;
}
h5 a {
font-size: 60%;
}
dl,table
{
text-align: left;
font-size: 10pt;
line-height: 1.15;
}
/*=============================================================================
Tables
=============================================================================*/
/* The only clue docutils gives us that tables are logically tables,
and not, e.g., footnotes, is that they have border="1". Therefore
we're keying off of that. We used to manually patch docutils to
add a "table" class to all logical tables, but that proved much too
fragile.
*/
table[border="1"]
{
width: 92%;
margin-left: 4%;
margin-right: 4%;
}
table[border="1"]
{
padding: 4px;
}
/* Table Cells */
table[border="1"] tr td
{
padding: 0.5em;
text-align: left;
font-size: 9pt;
}
table[border="1"] tr th
{
padding: 0.5em 0.5em 0.5em 0.5em;
border: 1pt solid white;
font-size: 80%;
}
@media screen
{
/* Tables */
table[border="1"] tr td
{
border: 1px solid #DCDCDC;
}
table[border="1"] tr th
{
background-color: #F0F0F0;
border: 1px solid #DCDCDC;
}
pre,
.screen
{
border: 1px solid #DCDCDC;
}
td pre
td .screen
{
border: 0px
}
.sidebar pre
{
border: 0px
}
}
pre,
.screen
{
font-size: 9pt;
display: block;
margin: 1pc 4% 0pc 4%;
padding: 0.5pc 0.5pc 0.5pc 0.5pc;
}
/* Program listings in tables don't get borders */
td pre,
td .screen
{
margin: 0pc 0pc 0pc 0pc;
padding: 0pc 0pc 0pc 0pc;
}

View File

@@ -0,0 +1,55 @@
How to use dtypes
=================
Here is a brief tutorial to show how to create ndarrays with built-in python data types, and extract the types and values of member variables
Like before, first get the necessary headers, setup the namespaces and initialize the Python runtime and numpy module::
#include <boost/numpy.hpp>
#include <iostream>
namespace p = boost::python;
namespace np = boost::numpy;
int main(int argc, char **argv)
{
Py_Initialize();
np::initialize();
Next, we create the shape and dtype. We use the get_builtin method to get the numpy dtype corresponding to the builtin C++ dtype
Here, we will create a 3x3 array passing a tuple with (3,3) for the size, and double as the data type ::
p::tuple shape = p::make_tuple(3, 3);
np::dtype dtype = np::dtype::get_builtin<double>();
np::ndarray a = np::zeros(shape, dtype);
Finally, we can print the array using the extract method in the python namespace.
Here, we first convert the variable into a string, and then extract it as a C++ character array from the python string using the <char const \* > template ::
std::cout << "Original array:\n" << p::extract<char const *>(p::str(a)) << std::endl;
We can also print the dtypes of the data members of the ndarray by using the get_dtype method for the ndarray ::
std::cout << "Datatype is:\n" << p::extract<char const *>(p::str(a.get_dtype())) << std::endl ;
We can also create custom dtypes and build ndarrays with the custom dtypes
We use the dtype constructor to create a custom dtype. This constructor takes a list as an argument.
The list should contain one or more tuples of the format (variable name, variable type)
So first create a tuple with a variable name and its dtype, double, to create a custom dtype ::
p::tuple for_custom_dtype = p::make_tuple("ha",dtype) ;
Next, create a list, and add this tuple to the list. Then use the list to create the custom dtype ::
p::list list_for_dtype ;
list_for_dtype.append(for_custom_dtype) ;
np::dtype custom_dtype = np::dtype(list_for_dtype) ;
We are now ready to create an ndarray with dimensions specified by \*shape\* and of custom dtpye ::
np::ndarray new_array = np::zeros(shape,custom_dtype);
}

View File

@@ -0,0 +1,51 @@
How to access data using raw pointers
=====================================
One of the advantages of the ndarray wrapper is that the same data can be used in both Python and C++ and changes can be made to reflect at both ends.
The from_data method makes this possible.
Like before, first get the necessary headers, setup the namespaces and initialize the Python runtime and numpy module::
#include <boost/numpy.hpp>
#include <iostream>
namespace p = boost::python;
namespace np = boost::numpy;
int main(int argc, char **argv)
{
Py_Initialize();
np::initialize();
Create an array in C++ , and pass the pointer to it to the from_data method to create an ndarray::
int arr[] = {1,2,3,4,5} ;
np::ndarray py_array = np::from_data(arr, np::dtype::get_builtin<int>() , p::make_tuple(5), p::make_tuple(sizeof(int)), p::object());
Print the source C++ array, as well as the ndarray, to check if they are the same::
std::cout << "C++ array :" << std::endl ;
for (int j=0;j<4;j++)
{
std::cout << arr[j] << ' ' ;
}
std::cout << std::endl << "Python ndarray :" << p::extract<char const *>(p::str(py_array)) << std::endl;
Now, change an element in the Python ndarray, and check if the value changed correspondingly in the source C++ array::
py_array[1] = 5 ;
std::cout << "Is the change reflected in the C++ array used to create the ndarray ? " << std::endl ;
for (int j = 0; j < 5; j++)
{
std::cout << arr[j] << ' ' ;
}
Next, change an element of the source C++ array and see if it is reflected in the Python ndarray::
arr[2] = 8 ;
std::cout << std::endl << "Is the change reflected in the Python ndarray ?" << std::endl << p::extract<char const *>(p::str(py_array)) << std::endl;
}
As we can see, the changes are reflected across the ends. This happens because the from_data method passes the C++ array by reference to create the ndarray, and thus uses the same locations for storing data.

View File

@@ -0,0 +1,14 @@
Boost.NumPy Tutorial
====================
Contents:
.. toctree::
:maxdepth: 2
simple
dtype
ndarray
ufunc
fromdata

View File

@@ -0,0 +1,94 @@
Creating ndarrays
=================
The Boost.Numpy library exposes quite a few methods to create ndarrays. ndarrays can be created in a variety of ways, include empty arrays and zero filled arrays.
ndarrays can also be created from arbitrary python sequences as well as from data and dtypes.
This tutorial will introduce you to some of the ways in which you can create ndarrays. The methods covered here include creating ndarrays from arbitrary Python sequences, as well as from C++ containers, using both unit and non-unit strides
First, as before, initialise the necessary namepaces and runtimes ::
#include <boost/numpy.hpp>
#include <iostream>
namespace p = boost::python;
namespace np = boost::numpy;
int main(int argc, char **argv)
{
Py_Initialize();
np::initialize();
Let's now create an ndarray from a simple tuple. We first create a tuple object, and then pass it to the array method, to generate the necessary tuple ::
p::object tu = p::make_tuple('a','b','c') ;
np::ndarray example_tuple = np::array(tu) ;
Let's now try the same with a list. We create an empty list, add an element using the append method, and as before, call the array method ::
p::list l ;
l.append('a') ;
np::ndarray example_list = np::array (l) ;
Optionally, we can also specify a dtype for the array ::
np::dtype dt = np::dtype::get_builtin<int>();
np::ndarray example_list1 = np::array (l,dt);
We can also create an array by supplying data arrays and a few other parameters.
First,create an integer array ::
int data[] = {1,2,3,4,5} ;
Create a shape, and strides, needed by the function ::
p::tuple shape = p::make_tuple(5) ;
p::tuple stride = p::make_tuple(sizeof(int)) ;
Here, shape is (4,) , and the stride is `sizeof(int)``.
A stride is the number of bytes that must be traveled to get to the next desired element while constructing the ndarray.
The function also needs an owner, to keep track of the data array passed. Passing none is dangerous ::
p::object own ;
The from_data function takes the data array, datatype,shape,stride and owner as arguments and returns an ndarray ::
np::ndarray data_ex1 = np::from_data(data,dt, shape,stride,own);
Now let's print the ndarray we created ::
std::cout << "Single dimensional array ::" << std::endl << p::extract < char const * > (p::str(data_ex)) << std::endl ;
Let's make it a little more interesting. Lets make an 3x2 ndarray from a multi-dimensional array using non-unit strides
First lets create a 3x4 array of 8-bit integers ::
uint8_t mul_data[][4] = {{1,2,3,4},{5,6,7,8},{1,3,5,7}};
Now let's create an array of 3x2 elements, picking the first and third elements from each row . For that, the shape will be 3x2.
The strides will be 4x2 i.e. 4 bytes to go to the next desired row, and 2 bytes to go to the next desired column ::
shape = p::make_tuple(3,2) ;
stride = p::make_tuple(sizeof(uint8_t)*2,sizeof(uint8_t)) ;
Get the numpy dtype for the built-in 8-bit integer data type ::
np::dtype dt1 = np::dtype::get_builtin<uint8_t>();
Now lets first create and print out the ndarray as is.
Notice how we can pass the shape and strides in the function directly, as well as the owner. The last part can be done because we don't have any use to
manipulate the "owner" object ::
np::ndarray mul_data_ex = np::from_data(mul_data,dt1, p::make_tuple(3,4),p::make_tuple(4,1),p::object());
std::cout << "Original multi dimensional array :: " << std::endl << p::extract < char const * > (p::str(mul_data_ex)) << std::endl ;
Now create the new ndarray using the shape and strides and print out the array we created using non-unit strides ::
mul_data_ex = np::from_data(mul_data,dt1, shape,stride,p::object());
std::cout << "Selective multidimensional array :: "<<std::endl << p::extract < char const * > (p::str(mul_data_ex)) << std::endl ;
Note : The from_data method will throw "error_already_set" if the number of elements dictated by the shape and the corresponding strides don't match
}

View File

@@ -0,0 +1,41 @@
A simple tutorial on Arrays
===========================
Let's start with a simple tutorial to create and modify arrays.
Get the necessary headers for numpy components and set up necessary namespaces::
#include <boost/numpy.hpp>
#include <iostream>
namespace p = boost::python;
namespace np = boost::numpy;
Initialise the Python runtime, and the numpy module. Failure to call these results in segmentation errors::
int main(int argc, char **argv)
{
Py_Initialize();
np::initialize();
Zero filled n-dimensional arrays can be created using the shape and data-type of the array as a parameter. Here, the shape is 3x3 and the datatype is the built-in float type::
p::tuple shape = p::make_tuple(3, 3);
np::dtype dtype = np::dtype::get_builtin<float>();
np::ndarray a = np::zeros(shape, dtype);
You can also create an empty array like this ::
np::ndarray b = np::empty(shape,dtype);
Print the original and reshaped array. The array a which is a list is first converted to a string, and each value in the list is extracted using extract< >::
std::cout << "Original array:\n" << p::extract<char const *>(p::str(a)) << std::endl;
// Reshape the array into a 1D array
a = a.reshape(p::make_tuple(9));
// Print it again.
std::cout << "Reshaped array:\n" << p::extract<char const *>(p::str(a)) << std::endl;
}

View File

@@ -0,0 +1,116 @@
Ufuncs
======
Ufuncs or universal functions operate on ndarrays element by element, and support array broadcasting, type casting, and other features.
Lets try and see how we can use the binary and unary ufunc methods
After the neccessary includes ::
#include <boost/numpy.hpp>
#include <iostream>
namespace p = boost::python;
namespace np = boost::numpy;
Now we create the structs necessary to implement the ufuncs. The typedefs *must* be made as the ufunc generators take these typedefs as inputs and return an error otherwise ::
struct UnarySquare
{
typedef double argument_type;
typedef double result_type;
double operator()(double r) const { return r * r;}
};
struct BinarySquare
{
typedef double first_argument_type;
typedef double second_argument_type;
typedef double result_type;
double operator()(double a,double b) const { return (a*a + b*b) ; }
};
Initialise the Python runtime and the numpy module ::
int main(int argc, char **argv)
{
Py_Initialize();
np::initialize();
Now expose the struct UnarySquare to Python as a class, and let ud be the class object. ::
p::object ud = p::class_<UnarySquare, boost::shared_ptr<UnarySquare> >("UnarySquare")
.def("__call__", np::unary_ufunc<UnarySquare>::make());
Let inst be an instance of the class ud ::
p::object inst = ud();
Use the "__call__" method to call the overloaded () operator and print the value ::
std::cout << "Square of unary scalar 1.0 is " << p::extract <char const * > (p::str(inst.attr("__call__")(1.0))) << std::endl ;
Create an array in C++ ::
int arr[] = {1,2,3,4} ;
..and use it to create the ndarray in Python ::
np::ndarray demo_array = np::from_data(arr, np::dtype::get_builtin<int>() , p::make_tuple(4), p::make_tuple(4), p::object());
Print out the demo array ::
std::cout << "Demo array is " << p::extract <char const * > (p::str(demo_array)) << std::endl ;
Call the "__call__" method to perform the operation and assign the value to result_array ::
p::object result_array = inst.attr("__call__")(demo_array) ;
Print the resultant array ::
std::cout << "Square of demo array is " << p::extract <char const * > (p::str(result_array)) << std::endl ;
Lets try the same with a list ::
p::list li ;
li.append(3);
li.append(7);
Print out the demo list ::
std::cout << "Demo list is " << p::extract <char const * > (p::str(li)) << std::endl ;
Call the ufunc for the list ::
result_array = inst.attr("__call__")(li) ;
And print the list out ::
std::cout << "Square of demo list is " << p::extract <char const * > (p::str(result_array)) << std::endl ;
Now lets try Binary ufuncs. Again, expose the struct BinarySquare to Python as a class, and let ud be the class object ::
ud = p::class_<BinarySquare, boost::shared_ptr<BinarySquare> >("BinarySquare")
.def("__call__", np::binary_ufunc<BinarySquare>::make());
And initialise ud ::
inst = ud();
Print the two input lists ::
std::cout << "The two input list for binary ufunc are " << std::endl << p::extract <char const * > (p::str(demo_array)) << std::endl << p::extract <char const * > (p::str(demo_array)) << std::endl ;
Call the binary ufunc taking demo_array as both inputs ::
result_array = inst.attr("__call__")(demo_array,demo_array) ;
And print the output ::
std::cout << "Square of list with binary ufunc is " << p::extract <char const * > (p::str(result_array)) << std::endl ;
}

View File

@@ -0,0 +1,37 @@
# Copyright Jim Bosch 2010-2012.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
import numpy
import gaussian
mu = numpy.zeros(2, dtype=float)
sigma = numpy.identity(2, dtype=float)
sigma[0, 1] = 0.15
sigma[1, 0] = 0.15
g = gaussian.bivariate_gaussian(mu, sigma)
r = numpy.linspace(-40, 40, 1001)
x, y = numpy.meshgrid(r, r)
z = g(x, y)
s = z.sum() * (r[1] - r[0])**2
print "sum (should be ~ 1):", s
xc = (z * x).sum() / z.sum()
print "x centroid (should be ~ %f): %f" % (mu[0], xc)
yc = (z * y).sum() / z.sum()
print "y centroid (should be ~ %f): %f" % (mu[1], yc)
xx = (z * (x - xc)**2).sum() / z.sum()
print "xx moment (should be ~ %f): %f" % (sigma[0,0], xx)
yy = (z * (y - yc)**2).sum() / z.sum()
print "yy moment (should be ~ %f): %f" % (sigma[1,1], yy)
xy = 0.5 * (z * (x - xc) * (y - yc)).sum() / z.sum()
print "xy moment (should be ~ %f): %f" % (sigma[0,1], xy)

49
example/numpy/dtype.cpp Normal file
View File

@@ -0,0 +1,49 @@
// Copyright Ankit Daftery 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
/**
* @brief An example to show how to create ndarrays with built-in python data types, and extract
* the types and values of member variables
*
* @todo Add an example to show type conversion.
* Add an example to show use of user-defined types
*
*/
#include <boost/numpy.hpp>
#include <iostream>
namespace p = boost::python;
namespace np = boost::numpy;
int main(int argc, char **argv)
{
// Initialize the Python runtime.
Py_Initialize();
// Initialize NumPy
np::initialize();
// Create a 3x3 shape...
p::tuple shape = p::make_tuple(3, 3);
// ...as well as a type for C++ double
np::dtype dtype = np::dtype::get_builtin<double>();
// Construct an array with the above shape and type
np::ndarray a = np::zeros(shape, dtype);
// Print the array
std::cout << "Original array:\n" << p::extract<char const *>(p::str(a)) << std::endl;
// Print the datatype of the elements
std::cout << "Datatype is:\n" << p::extract<char const *>(p::str(a.get_dtype())) << std::endl ;
// Using user defined dtypes to create dtype and an array of the custom dtype
// First create a tuple with a variable name and its dtype, double, to create a custom dtype
p::tuple for_custom_dtype = p::make_tuple("ha",dtype) ;
// The list needs to be created, because the constructor to create the custom dtype
// takes a list of (variable,variable_type) as an argument
p::list list_for_dtype ;
list_for_dtype.append(for_custom_dtype) ;
// Create the custom dtype
np::dtype custom_dtype = np::dtype(list_for_dtype) ;
// Create an ndarray with the custom dtype
np::ndarray new_array = np::zeros(shape,custom_dtype);
}

View File

@@ -0,0 +1,48 @@
// Copyright Ankit Daftery 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
/**
* @brief An example to show how to access data using raw pointers. This shows that you can use and
* manipulate data in either Python or C++ and have the changes reflected in both.
*/
#include <boost/numpy.hpp>
#include <iostream>
namespace p = boost::python;
namespace np = boost::numpy;
int main(int argc, char **argv)
{
// Initialize the Python runtime.
Py_Initialize();
// Initialize NumPy
np::initialize();
// Create an array in C++
int arr[] = {1,2,3,4} ;
// Create the ndarray in Python
np::ndarray py_array = np::from_data(arr, np::dtype::get_builtin<int>() , p::make_tuple(4), p::make_tuple(4), p::object());
// Print the ndarray that we just created, and the source C++ array
std::cout << "C++ array :" << std::endl ;
for (int j=0;j<4;j++)
{
std::cout << arr[j] << ' ' ;
}
std::cout << std::endl << "Python ndarray :" << p::extract<char const *>(p::str(py_array)) << std::endl;
// Change an element in the python ndarray
py_array[1] = 5 ;
// And see if the C++ container is changed or not
std::cout << "Is the change reflected in the C++ array used to create the ndarray ? " << std::endl ;
for (int j = 0;j<4 ; j++)
{
std::cout << arr[j] << ' ' ;
}
// Conversely, change it in C++
arr[2] = 8 ;
// And see if the changes are reflected in the Python ndarray
std::cout << std::endl << "Is the change reflected in the Python ndarray ?" << std::endl << p::extract<char const *>(p::str(py_array)) << std::endl;
}

315
example/numpy/gaussian.cpp Normal file
View File

@@ -0,0 +1,315 @@
// Copyright Jim Bosch 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/numpy.hpp>
#include <cmath>
#include <memory>
#ifndef M_PI
#include <boost/math/constants/constants.hpp>
const double M_PI = boost::math::constants::pi<double>();
#endif
namespace bp = boost::python;
namespace bn = boost::numpy;
/**
* A 2x2 matrix class, purely for demonstration purposes.
*
* Instead of wrapping this class with Boost.Python, we'll convert it to/from numpy.ndarray.
*/
class matrix2 {
public:
double & operator()(int i, int j) {
return _data[i*2 + j];
}
double const & operator()(int i, int j) const {
return _data[i*2 + j];
}
double const * data() const { return _data; }
private:
double _data[4];
};
/**
* A 2-element vector class, purely for demonstration purposes.
*
* Instead of wrapping this class with Boost.Python, we'll convert it to/from numpy.ndarray.
*/
class vector2 {
public:
double & operator[](int i) {
return _data[i];
}
double const & operator[](int i) const {
return _data[i];
}
double const * data() const { return _data; }
vector2 operator+(vector2 const & other) const {
vector2 r;
r[0] = _data[0] + other[0];
r[1] = _data[1] + other[1];
return r;
}
vector2 operator-(vector2 const & other) const {
vector2 r;
r[0] = _data[0] - other[0];
r[1] = _data[1] - other[1];
return r;
}
private:
double _data[2];
};
/**
* Matrix-vector multiplication.
*/
vector2 operator*(matrix2 const & m, vector2 const & v) {
vector2 r;
r[0] = m(0, 0) * v[0] + m(0, 1) * v[1];
r[1] = m(1, 0) * v[0] + m(1, 1) * v[1];
return r;
}
/**
* Vector inner product.
*/
double dot(vector2 const & v1, vector2 const & v2) {
return v1[0] * v2[0] + v1[1] * v2[1];
}
/**
* This class represents a simple 2-d Gaussian (Normal) distribution, defined by a
* mean vector 'mu' and a covariance matrix 'sigma'.
*/
class bivariate_gaussian {
public:
vector2 const & get_mu() const { return _mu; }
matrix2 const & get_sigma() const { return _sigma; }
/**
* Evaluate the density of the distribution at a point defined by a two-element vector.
*/
double operator()(vector2 const & p) const {
vector2 u = _cholesky * (p - _mu);
return 0.5 * _cholesky(0, 0) * _cholesky(1, 1) * std::exp(-0.5 * dot(u, u)) / M_PI;
}
/**
* Evaluate the density of the distribution at an (x, y) point.
*/
double operator()(double x, double y) const {
vector2 p;
p[0] = x;
p[1] = y;
return operator()(p);
}
/**
* Construct from a mean vector and covariance matrix.
*/
bivariate_gaussian(vector2 const & mu, matrix2 const & sigma)
: _mu(mu), _sigma(sigma), _cholesky(compute_inverse_cholesky(sigma))
{}
private:
/**
* This evaluates the inverse of the Cholesky factorization of a 2x2 matrix;
* it's just a shortcut in evaluating the density.
*/
static matrix2 compute_inverse_cholesky(matrix2 const & m) {
matrix2 l;
// First do cholesky factorization: l l^t = m
l(0, 0) = std::sqrt(m(0, 0));
l(0, 1) = m(0, 1) / l(0, 0);
l(1, 1) = std::sqrt(m(1, 1) - l(0,1) * l(0,1));
// Now do forward-substitution (in-place) to invert:
l(0, 0) = 1.0 / l(0, 0);
l(1, 0) = l(0, 1) = -l(0, 1) / l(1, 1);
l(1, 1) = 1.0 / l(1, 1);
return l;
}
vector2 _mu;
matrix2 _sigma;
matrix2 _cholesky;
};
/*
* We have a two options for wrapping get_mu and get_sigma into NumPy-returning Python methods:
* - we could deep-copy the data, making totally new NumPy arrays;
* - we could make NumPy arrays that point into the existing memory.
* The latter is often preferable, especially if the arrays are large, but it's dangerous unless
* the reference counting is correct: the returned NumPy array needs to hold a reference that
* keeps the memory it points to from being deallocated as long as it is alive. This is what the
* "owner" argument to from_data does - the NumPy array holds a reference to the owner, keeping it
* from being destroyed.
*
* Note that this mechanism isn't completely safe for data members that can have their internal
* storage reallocated. A std::vector, for instance, can be invalidated when it is resized,
* so holding a Python reference to a C++ class that holds a std::vector may not be a guarantee
* that the memory in the std::vector will remain valid.
*/
/**
* These two functions are custom wrappers for get_mu and get_sigma, providing the shallow-copy
* conversion with reference counting described above.
*
* It's also worth noting that these return NumPy arrays that cannot be modified in Python;
* the const overloads of vector::data() and matrix::data() return const references,
* and passing a const pointer to from_data causes NumPy's 'writeable' flag to be set to false.
*/
static bn::ndarray py_get_mu(bp::object const & self) {
vector2 const & mu = bp::extract<bivariate_gaussian const &>(self)().get_mu();
return bn::from_data(
mu.data(),
bn::dtype::get_builtin<double>(),
bp::make_tuple(2),
bp::make_tuple(sizeof(double)),
self
);
}
static bn::ndarray py_get_sigma(bp::object const & self) {
matrix2 const & sigma = bp::extract<bivariate_gaussian const &>(self)().get_sigma();
return bn::from_data(
sigma.data(),
bn::dtype::get_builtin<double>(),
bp::make_tuple(2, 2),
bp::make_tuple(2 * sizeof(double), sizeof(double)),
self
);
}
/**
* To allow the constructor to work, we need to define some from-Python converters from NumPy arrays
* to the matrix/vector types. The rvalue-from-python functionality is not well-documented in Boost.Python
* itself; you can learn more from boost/python/converter/rvalue_from_python_data.hpp.
*/
/**
* We start with two functions that just copy a NumPy array into matrix/vector objects. These will be used
* in the templated converted below. The first just uses the operator[] overloads provided by
* bp::object.
*/
static void copy_ndarray_to_mv2(bn::ndarray const & array, vector2 & vec) {
vec[0] = bp::extract<double>(array[0]);
vec[1] = bp::extract<double>(array[1]);
}
/**
* Here, we'll take the alternate approach of using the strides to access the array's memory directly.
* This can be much faster for large arrays.
*/
static void copy_ndarray_to_mv2(bn::ndarray const & array, matrix2 & mat) {
// Unfortunately, get_strides() can't be inlined, so it's best to call it once up-front.
Py_intptr_t const * strides = array.get_strides();
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
mat(i, j) = *reinterpret_cast<double const *>(array.get_data() + i * strides[0] + j * strides[1]);
}
}
}
/**
* Here's the actual converter. Because we've separated the differences into the above functions,
* we can write a single template class that works for both matrix2 and vector2.
*/
template <typename T, int N>
struct mv2_from_python {
/**
* Register the converter.
*/
mv2_from_python() {
bp::converter::registry::push_back(
&convertible,
&construct,
bp::type_id< T >()
);
}
/**
* Test to see if we can convert this to the desired type; if not return zero.
* If we can convert, returned pointer can be used by construct().
*/
static void * convertible(PyObject * p) {
try {
bp::object obj(bp::handle<>(bp::borrowed(p)));
std::auto_ptr<bn::ndarray> array(
new bn::ndarray(
bn::from_object(obj, bn::dtype::get_builtin<double>(), N, N, bn::ndarray::V_CONTIGUOUS)
)
);
if (array->shape(0) != 2) return 0;
if (N == 2 && array->shape(1) != 2) return 0;
return array.release();
} catch (bp::error_already_set & err) {
bp::handle_exception();
return 0;
}
}
/**
* Finish the conversion by initializing the C++ object into memory prepared by Boost.Python.
*/
static void construct(PyObject * obj, bp::converter::rvalue_from_python_stage1_data * data) {
// Extract the array we passed out of the convertible() member function.
std::auto_ptr<bn::ndarray> array(reinterpret_cast<bn::ndarray*>(data->convertible));
// Find the memory block Boost.Python has prepared for the result.
typedef bp::converter::rvalue_from_python_storage<T> storage_t;
storage_t * storage = reinterpret_cast<storage_t*>(data);
// Use placement new to initialize the result.
T * m_or_v = new (storage->storage.bytes) T();
// Fill the result with the values from the NumPy array.
copy_ndarray_to_mv2(*array, *m_or_v);
// Finish up.
data->convertible = storage->storage.bytes;
}
};
BOOST_PYTHON_MODULE(gaussian) {
bn::initialize();
// Register the from-python converters
mv2_from_python< vector2, 1 >();
mv2_from_python< matrix2, 2 >();
typedef double (bivariate_gaussian::*call_vector)(vector2 const &) const;
bp::class_<bivariate_gaussian>("bivariate_gaussian", bp::init<bivariate_gaussian const &>())
// Declare the constructor (wouldn't work without the from-python converters).
.def(bp::init< vector2 const &, matrix2 const & >())
// Use our custom reference-counting getters
.add_property("mu", &py_get_mu)
.add_property("sigma", &py_get_sigma)
// First overload accepts a two-element array argument
.def("__call__", (call_vector)&bivariate_gaussian::operator())
// This overload works like a binary NumPy universal function: you can pass
// in scalars or arrays, and the C++ function will automatically be called
// on each element of an array argument.
.def("__call__", bn::binary_ufunc<bivariate_gaussian,double,double,double>::make())
;
}

71
example/numpy/ndarray.cpp Normal file
View File

@@ -0,0 +1,71 @@
// Copyright Ankit Daftery 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
/**
* @brief An example to show how to create ndarrays using arbitrary Python sequences.
*
* The Python sequence could be any object whose __array__ method returns an array, or any
* (nested) sequence. This example also shows how to create arrays using both unit and
* non-unit strides.
*/
#include <boost/numpy.hpp>
#include <iostream>
namespace p = boost::python;
namespace np = boost::numpy;
#if _MSC_VER
using boost::uint8_t;
#endif
int main(int argc, char **argv)
{
// Initialize the Python runtime.
Py_Initialize();
// Initialize NumPy
np::initialize();
// Create an ndarray from a simple tuple
p::object tu = p::make_tuple('a','b','c') ;
np::ndarray example_tuple = np::array (tu) ;
// and from a list
p::list l ;
np::ndarray example_list = np::array (l) ;
// Optionally, you can also specify a dtype
np::dtype dt = np::dtype::get_builtin<int>();
np::ndarray example_list1 = np::array (l,dt);
// You can also create an array by supplying data.First,create an integer array
int data[] = {1,2,3,4} ;
// Create a shape, and strides, needed by the function
p::tuple shape = p::make_tuple(4) ;
p::tuple stride = p::make_tuple(4) ;
// The function also needs an owner, to keep track of the data array passed. Passing none is dangerous
p::object own ;
// The from_data function takes the data array, datatype,shape,stride and owner as arguments
// and returns an ndarray
np::ndarray data_ex = np::from_data(data,dt,shape,stride,own);
// Print the ndarray we created
std::cout << "Single dimensional array ::" << std::endl << p::extract < char const * > (p::str(data_ex)) << std::endl ;
// Now lets make an 3x2 ndarray from a multi-dimensional array using non-unit strides
// First lets create a 3x4 array of 8-bit integers
uint8_t mul_data[][4] = {{1,2,3,4},{5,6,7,8},{1,3,5,7}};
// Now let's create an array of 3x2 elements, picking the first and third elements from each row
// For that, the shape will be 3x2
shape = p::make_tuple(3,2) ;
// The strides will be 4x2 i.e. 4 bytes to go to the next desired row, and 2 bytes to go to the next desired column
stride = p::make_tuple(4,2) ;
// Get the numpy dtype for the built-in 8-bit integer data type
np::dtype dt1 = np::dtype::get_builtin<uint8_t>();
// First lets create and print out the ndarray as is
np::ndarray mul_data_ex = np::from_data(mul_data,dt1, p::make_tuple(3,4),p::make_tuple(4,1),p::object());
std::cout << "Original multi dimensional array :: " << std::endl << p::extract < char const * > (p::str(mul_data_ex)) << std::endl ;
// Now create the new ndarray using the shape and strides
mul_data_ex = np::from_data(mul_data,dt1, shape,stride,p::object());
// Print out the array we created using non-unit strides
std::cout << "Selective multidimensional array :: "<<std::endl << p::extract < char const * > (p::str(mul_data_ex)) << std::endl ;
}

32
example/numpy/simple.cpp Normal file
View File

@@ -0,0 +1,32 @@
// Copyright 2011 Stefan Seefeld.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/numpy.hpp>
#include <iostream>
namespace p = boost::python;
namespace np = boost::numpy;
int main(int argc, char **argv)
{
// Initialize the Python runtime.
Py_Initialize();
// Initialize NumPy
np::initialize();
// Create a 3x3 shape...
p::tuple shape = p::make_tuple(3, 3);
// ...as well as a type for C++ float
np::dtype dtype = np::dtype::get_builtin<float>();
// Construct an array with the above shape and type
np::ndarray a = np::zeros(shape, dtype);
// Construct an empty array with the above shape and dtype as well
np::ndarray b = np::empty(shape,dtype);
// Print the array
std::cout << "Original array:\n" << p::extract<char const *>(p::str(a)) << std::endl;
// Reshape the array into a 1D array
a = a.reshape(p::make_tuple(9));
// Print it again.
std::cout << "Reshaped array:\n" << p::extract<char const *>(p::str(a)) << std::endl;
}

86
example/numpy/ufunc.cpp Normal file
View File

@@ -0,0 +1,86 @@
// Copyright Ankit Daftery 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
/**
* @brief An example to demonstrate use of universal functions or ufuncs
*
*
* @todo Calling the overloaded () operator is in a roundabout manner, find a simpler way
* None of the methods like np::add, np::multiply etc are supported as yet
*/
#include <boost/numpy.hpp>
#include <iostream>
namespace p = boost::python;
namespace np = boost::numpy;
// Create the structs necessary to implement the ufuncs
// The typedefs *must* be made
struct UnarySquare
{
typedef double argument_type;
typedef double result_type;
double operator()(double r) const { return r * r;}
};
struct BinarySquare
{
typedef double first_argument_type;
typedef double second_argument_type;
typedef double result_type;
double operator()(double a,double b) const { return (a*a + b*b) ; }
};
int main(int argc, char **argv)
{
// Initialize the Python runtime.
Py_Initialize();
// Initialize NumPy
np::initialize();
// Expose the struct UnarySquare to Python as a class, and let ud be the class object
p::object ud = p::class_<UnarySquare, boost::shared_ptr<UnarySquare> >("UnarySquare")
.def("__call__", np::unary_ufunc<UnarySquare>::make());
// Let inst be an instance of the class ud
p::object inst = ud();
// Use the "__call__" method to call the overloaded () operator and print the value
std::cout << "Square of unary scalar 1.0 is " << p::extract <char const * > (p::str(inst.attr("__call__")(1.0))) << std::endl ;
// Create an array in C++
int arr[] = {1,2,3,4} ;
// ..and use it to create the ndarray in Python
np::ndarray demo_array = np::from_data(arr, np::dtype::get_builtin<int>() , p::make_tuple(4), p::make_tuple(4), p::object());
// Print out the demo array
std::cout << "Demo array is " << p::extract <char const * > (p::str(demo_array)) << std::endl ;
// Call the "__call__" method to perform the operation and assign the value to result_array
p::object result_array = inst.attr("__call__")(demo_array) ;
// Print the resultant array
std::cout << "Square of demo array is " << p::extract <char const * > (p::str(result_array)) << std::endl ;
// Lets try the same with a list
p::list li ;
li.append(3);
li.append(7);
// Print out the demo list
std::cout << "Demo list is " << p::extract <char const * > (p::str(li)) << std::endl ;
// Call the ufunc for the list
result_array = inst.attr("__call__")(li) ;
// And print the list out
std::cout << "Square of demo list is " << p::extract <char const * > (p::str(result_array)) << std::endl ;
// Now lets try Binary ufuncs
// Expose the struct BinarySquare to Python as a class, and let ud be the class object
ud = p::class_<BinarySquare, boost::shared_ptr<BinarySquare> >("BinarySquare")
.def("__call__", np::binary_ufunc<BinarySquare>::make());
// Again initialise inst as an instance of the class ud
inst = ud();
// Print the two input listsPrint the two input lists
std::cout << "The two input list for binary ufunc are " << std::endl << p::extract <char const * > (p::str(demo_array)) << std::endl << p::extract <char const * > (p::str(demo_array)) << std::endl ;
// Call the binary ufunc taking demo_array as both inputs
result_array = inst.attr("__call__")(demo_array,demo_array) ;
std::cout << "Square of list with binary ufunc is " << p::extract <char const * > (p::str(result_array)) << std::endl ;
}

135
example/numpy/wrap.cpp Normal file
View File

@@ -0,0 +1,135 @@
// Copyright Jim Bosch 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
/**
* A simple example showing how to wrap a couple of C++ functions that
* operate on 2-d arrays into Python functions that take NumPy arrays
* as arguments.
*
* If you find have a lot of such functions to wrap, you may want to
* create a C++ array type (or use one of the many existing C++ array
* libraries) that maps well to NumPy arrays and create Boost.Python
* converters. There's more work up front than the approach here,
* but much less boilerplate per function. See the "Gaussian" example
* included with Boost.NumPy for an example of custom converters, or
* take a look at the "ndarray" project on GitHub for a more complete,
* high-level solution.
*
* Note that we're using embedded Python here only to make a convenient
* self-contained example; you could just as easily put the wrappers
* in a regular C++-compiled module and imported them in regular
* Python. Again, see the Gaussian demo for an example.
*/
#include <boost/numpy.hpp>
#include <boost/scoped_array.hpp>
#include <iostream>
namespace p = boost::python;
namespace np = boost::numpy;
// This is roughly the most efficient way to write a C/C++ function that operates
// on a 2-d NumPy array - operate directly on the array by incrementing a pointer
// with the strides.
void fill1(double * array, int rows, int cols, int row_stride, int col_stride) {
double * row_iter = array;
double n = 0.0; // just a counter we'll fill the array with.
for (int i = 0; i < rows; ++i, row_iter += row_stride) {
double * col_iter = row_iter;
for (int j = 0; j < cols; ++j, col_iter += col_stride) {
*col_iter = ++n;
}
}
}
// Here's a simple wrapper function for fill1. It requires that the passed
// NumPy array be exactly what we're looking for - no conversion from nested
// sequences or arrays with other data types, because we want to modify it
// in-place.
void wrap_fill1(np::ndarray const & array) {
if (array.get_dtype() != np::dtype::get_builtin<double>()) {
PyErr_SetString(PyExc_TypeError, "Incorrect array data type");
p::throw_error_already_set();
}
if (array.get_nd() != 2) {
PyErr_SetString(PyExc_TypeError, "Incorrect number of dimensions");
p::throw_error_already_set();
}
fill1(reinterpret_cast<double*>(array.get_data()),
array.shape(0), array.shape(1),
array.strides(0) / sizeof(double), array.strides(1) / sizeof(double));
}
// Another fill function that takes a double**. This is less efficient, because
// it's not the native NumPy data layout, but it's common enough in C/C++ that
// it's worth its own example. This time we don't pass the strides, and instead
// in wrap_fill2 we'll require the C_CONTIGUOUS bitflag, which guarantees that
// the column stride is 1 and the row stride is the number of columns. That
// restricts the arrays that can be passed to fill2 (it won't work on most
// subarray views or transposes, for instance).
void fill2(double ** array, int rows, int cols) {
double n = 0.0; // just a counter we'll fill the array with.
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
array[i][j] = ++n;
}
}
}
// Here's the wrapper for fill2; it's a little more complicated because we need
// to check the flags and create the array of pointers.
void wrap_fill2(np::ndarray const & array) {
if (array.get_dtype() != np::dtype::get_builtin<double>()) {
PyErr_SetString(PyExc_TypeError, "Incorrect array data type");
p::throw_error_already_set();
}
if (array.get_nd() != 2) {
PyErr_SetString(PyExc_TypeError, "Incorrect number of dimensions");
p::throw_error_already_set();
}
if (!(array.get_flags() & np::ndarray::C_CONTIGUOUS)) {
PyErr_SetString(PyExc_TypeError, "Array must be row-major contiguous");
p::throw_error_already_set();
}
double * iter = reinterpret_cast<double*>(array.get_data());
int rows = array.shape(0);
int cols = array.shape(1);
boost::scoped_array<double*> ptrs(new double*[rows]);
for (int i = 0; i < rows; ++i, iter += cols) {
ptrs[i] = iter;
}
fill2(ptrs.get(), array.shape(0), array.shape(1));
}
BOOST_PYTHON_MODULE(example) {
np::initialize(); // have to put this in any module that uses Boost.NumPy
p::def("fill1", wrap_fill1);
p::def("fill2", wrap_fill2);
}
int main(int argc, char **argv)
{
// This line makes our module available to the embedded Python intepreter.
# if PY_VERSION_HEX >= 0x03000000
PyImport_AppendInittab("example", &PyInit_example);
# else
PyImport_AppendInittab("example", &initexample);
# endif
// Initialize the Python runtime.
Py_Initialize();
PyRun_SimpleString(
"import example\n"
"import numpy\n"
"z1 = numpy.zeros((5,6), dtype=float)\n"
"z2 = numpy.zeros((4,3), dtype=float)\n"
"example.fill1(z1)\n"
"example.fill2(z2)\n"
"print z1\n"
"print z2\n"
);
Py_Finalize();
}

View File

@@ -0,0 +1,38 @@
// Copyright Jim Bosch 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_NUMPY_HPP_INCLUDED
#define BOOST_NUMPY_HPP_INCLUDED
/**
* @file boost/numpy.hpp
* @brief Main public header file for boost.numpy.
*/
#include <boost/numpy/dtype.hpp>
#include <boost/numpy/ndarray.hpp>
#include <boost/numpy/scalars.hpp>
#include <boost/numpy/matrix.hpp>
#include <boost/numpy/ufunc.hpp>
#include <boost/numpy/invoke_matching.hpp>
namespace boost {
namespace numpy {
/**
* @brief Initialize the Numpy C-API
*
* This must be called before using anything in boost.numpy;
* It should probably be the first line inside BOOST_PYTHON_MODULE.
*
* @internal This just calls the Numpy C-API functions "import_array()"
* and "import_ufunc()", and then calls
* dtype::register_scalar_converters().
*/
void initialize(bool register_scalar_converters=true);
} // namespace boost::numpy
} // namespace boost
#endif // !BOOST_NUMPY_HPP_INCLUDED

View File

@@ -0,0 +1,115 @@
// Copyright Jim Bosch 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_NUMPY_DTYPE_HPP_INCLUDED
#define BOOST_NUMPY_DTYPE_HPP_INCLUDED
/**
* @file boost/numpy/dtype.hpp
* @brief Object manager for Python's numpy.dtype class.
*/
#include <boost/python.hpp>
#include <boost/numpy/numpy_object_mgr_traits.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/type_traits/add_pointer.hpp>
namespace boost { namespace numpy {
/**
* @brief A boost.python "object manager" (subclass of object) for numpy.dtype.
*
* @todo This could have a lot more interesting accessors.
*/
class dtype : public python::object {
static python::detail::new_reference convert(python::object::object_cref arg, bool align);
public:
/// @brief Convert an arbitrary Python object to a data-type descriptor object.
template <typename T>
explicit dtype(T arg, bool align=false) : python::object(convert(arg, align)) {}
/**
* @brief Get the built-in numpy dtype associated with the given scalar template type.
*
* This is perhaps the most useful part of the numpy API: it returns the dtype object
* corresponding to a built-in C++ type. This should work for any integer or floating point
* type supported by numpy, and will also work for std::complex if
* sizeof(std::complex<T>) == 2*sizeof(T).
*
* It can also be useful for users to add explicit specializations for POD structs
* that return field-based dtypes.
*/
template <typename T> static dtype get_builtin();
/// @brief Return the size of the data type in bytes.
int get_itemsize() const;
/**
* @brief Compare two dtypes for equivalence.
*
* This is more permissive than equality tests. For instance, if long and int are the same
* size, the dtypes corresponding to each will be equivalent, but not equal.
*/
friend bool equivalent(dtype const & a, dtype const & b);
/**
* @brief Register from-Python converters for NumPy's built-in array scalar types.
*
* This is usually called automatically by initialize(), and shouldn't be called twice
* (doing so just adds unused converters to the Boost.Python registry).
*/
static void register_scalar_converters();
BOOST_PYTHON_FORWARD_OBJECT_CONSTRUCTORS(dtype, python::object);
};
bool equivalent(dtype const & a, dtype const & b);
namespace detail
{
template <int bits, bool isUnsigned> dtype get_int_dtype();
template <int bits> dtype get_float_dtype();
template <int bits> dtype get_complex_dtype();
template <typename T, bool isInt=boost::is_integral<T>::value>
struct builtin_dtype;
template <typename T>
struct builtin_dtype<T,true> {
static dtype get() { return get_int_dtype< 8*sizeof(T), boost::is_unsigned<T>::value >(); }
};
template <>
struct builtin_dtype<bool,true> {
static dtype get();
};
template <typename T>
struct builtin_dtype<T,false> {
static dtype get() { return get_float_dtype< 8*sizeof(T) >(); }
};
template <typename T>
struct builtin_dtype< std::complex<T>, false > {
static dtype get() { return get_complex_dtype< 16*sizeof(T) >(); }
};
} // namespace detail
template <typename T>
inline dtype dtype::get_builtin() { return detail::builtin_dtype<T>::get(); }
}} // namespace boost::numpy
namespace boost { namespace python { namespace converter {
NUMPY_OBJECT_MANAGER_TRAITS(numpy::dtype);
}}} // namespace boost::python::converter
#endif // !BOOST_NUMPY_DTYPE_HPP_INCLUDED

View File

@@ -0,0 +1,33 @@
// Copyright Jim Bosch 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_NUMPY_INTERNAL_HPP_INCLUDED
#define BOOST_NUMPY_INTERNAL_HPP_INCLUDED
/**
* @file boost/numpy/internal.hpp
* @brief Internal header file to include the Numpy C-API headers.
*
* This should only be included by source files in the boost.numpy library itself.
*/
#include <boost/python.hpp>
#ifdef BOOST_NUMPY_INTERNAL
#define NO_IMPORT_ARRAY
#define NO_IMPORT_UFUNC
#else
#ifndef BOOST_NUMPY_INTERNAL_MAIN
ERROR_internal_hpp_is_for_internal_use_only
#endif
#endif
#define PY_ARRAY_UNIQUE_SYMBOL BOOST_NUMPY_ARRAY_API
#define PY_UFUNC_UNIQUE_SYMBOL BOOST_UFUNC_ARRAY_API
#include <numpy/arrayobject.h>
#include <numpy/ufuncobject.h>
#include <boost/numpy.hpp>
#define NUMPY_OBJECT_MANAGER_TRAITS_IMPL(pytype,manager) \
PyTypeObject const * object_manager_traits<manager>::get_pytype() { return &pytype; }
#endif // !BOOST_NUMPY_INTERNAL_HPP_INCLUDED

View File

@@ -0,0 +1,190 @@
// Copyright Jim Bosch 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_NUMPY_INVOKE_MATCHING_HPP_INCLUDED
#define BOOST_NUMPY_INVOKE_MATCHING_HPP_INCLUDED
/**
* @file boost/numpy/invoke_matching.hpp
* @brief Template invocation based on dtype matching.
*/
#include <boost/numpy/dtype.hpp>
#include <boost/numpy/ndarray.hpp>
#include <boost/mpl/integral_c.hpp>
namespace boost
{
namespace numpy
{
namespace detail
{
struct add_pointer_meta
{
template <typename T>
struct apply
{
typedef typename boost::add_pointer<T>::type type;
};
};
struct dtype_template_match_found {};
struct nd_template_match_found {};
template <typename Function>
struct dtype_template_invoker
{
template <typename T>
void operator()(T *) const
{
if (dtype::get_builtin<T>() == m_dtype)
{
m_func.Function::template apply<T>();
throw dtype_template_match_found();
}
}
dtype_template_invoker(dtype const & dtype_, Function func)
: m_dtype(dtype_), m_func(func) {}
private:
dtype const & m_dtype;
Function m_func;
};
template <typename Function>
struct dtype_template_invoker< boost::reference_wrapper<Function> >
{
template <typename T>
void operator()(T *) const
{
if (dtype::get_builtin<T>() == m_dtype)
{
m_func.Function::template apply<T>();
throw dtype_template_match_found();
}
}
dtype_template_invoker(dtype const & dtype_, Function & func)
: m_dtype(dtype_), m_func(func) {}
private:
dtype const & m_dtype;
Function & m_func;
};
template <typename Function>
struct nd_template_invoker
{
template <int N>
void operator()(boost::mpl::integral_c<int,N> *) const
{
if (m_nd == N)
{
m_func.Function::template apply<N>();
throw nd_template_match_found();
}
}
nd_template_invoker(int nd, Function func) : m_nd(nd), m_func(func) {}
private:
int m_nd;
Function m_func;
};
template <typename Function>
struct nd_template_invoker< boost::reference_wrapper<Function> >
{
template <int N>
void operator()(boost::mpl::integral_c<int,N> *) const
{
if (m_nd == N)
{
m_func.Function::template apply<N>();
throw nd_template_match_found();
}
}
nd_template_invoker(int nd, Function & func) : m_nd(nd), m_func(func) {}
private:
int m_nd;
Function & m_func;
};
} // namespace boost::numpy::detail
template <typename Sequence, typename Function>
void invoke_matching_nd(int nd, Function f)
{
detail::nd_template_invoker<Function> invoker(nd, f);
try { boost::mpl::for_each< Sequence, detail::add_pointer_meta >(invoker);}
catch (detail::nd_template_match_found &) { return;}
PyErr_SetString(PyExc_TypeError, "number of dimensions not found in template list.");
python::throw_error_already_set();
}
template <typename Sequence, typename Function>
void invoke_matching_dtype(dtype const & dtype_, Function f)
{
detail::dtype_template_invoker<Function> invoker(dtype_, f);
try { boost::mpl::for_each< Sequence, detail::add_pointer_meta >(invoker);}
catch (detail::dtype_template_match_found &) { return;}
PyErr_SetString(PyExc_TypeError, "dtype not found in template list.");
python::throw_error_already_set();
}
namespace detail
{
template <typename T, typename Function>
struct array_template_invoker_wrapper_2
{
template <int N>
void apply() const { m_func.Function::template apply<T,N>();}
array_template_invoker_wrapper_2(Function & func) : m_func(func) {}
private:
Function & m_func;
};
template <typename DimSequence, typename Function>
struct array_template_invoker_wrapper_1
{
template <typename T>
void apply() const { invoke_matching_nd<DimSequence>(m_nd, array_template_invoker_wrapper_2<T,Function>(m_func));}
array_template_invoker_wrapper_1(int nd, Function & func) : m_nd(nd), m_func(func) {}
private:
int m_nd;
Function & m_func;
};
template <typename DimSequence, typename Function>
struct array_template_invoker_wrapper_1< DimSequence, boost::reference_wrapper<Function> >
: public array_template_invoker_wrapper_1< DimSequence, Function >
{
array_template_invoker_wrapper_1(int nd, Function & func)
: array_template_invoker_wrapper_1< DimSequence, Function >(nd, func) {}
};
} // namespace boost::numpy::detail
template <typename TypeSequence, typename DimSequence, typename Function>
void invoke_matching_array(ndarray const & array_, Function f)
{
detail::array_template_invoker_wrapper_1<DimSequence,Function> wrapper(array_.get_nd(), f);
invoke_matching_dtype<TypeSequence>(array_.get_dtype(), wrapper);
}
} // namespace boost::numpy
} // namespace boost
#endif // !BOOST_NUMPY_INVOKE_MATCHING_HPP_INCLUDED

View File

@@ -0,0 +1,85 @@
// Copyright Jim Bosch 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_NUMPY_MATRIX_HPP_INCLUDED
#define BOOST_NUMPY_MATRIX_HPP_INCLUDED
/**
* @file boost/numpy/matrix.hpp
* @brief Object manager for numpy.matrix.
*/
#include <boost/python.hpp>
#include <boost/numpy/numpy_object_mgr_traits.hpp>
#include <boost/numpy/ndarray.hpp>
namespace boost
{
namespace numpy
{
/**
* @brief A boost.python "object manager" (subclass of object) for numpy.matrix.
*
* @internal numpy.matrix is defined in Python, so object_manager_traits<matrix>::get_pytype()
* is implemented by importing numpy and getting the "matrix" attribute of the module.
* We then just hope that doesn't get destroyed while we need it, because if we put
* a dynamic python object in a static-allocated boost::python::object or handle<>,
* bad things happen when Python shuts down. I think this solution is safe, but I'd
* love to get that confirmed.
*/
class matrix : public ndarray
{
static python::object construct(object_cref obj, dtype const & dt, bool copy);
static python::object construct(object_cref obj, bool copy);
public:
BOOST_PYTHON_FORWARD_OBJECT_CONSTRUCTORS(matrix, ndarray);
/// @brief Equivalent to "numpy.matrix(obj,dt,copy)" in Python.
explicit matrix(python::object const & obj, dtype const & dt, bool copy=true)
: ndarray(python::extract<ndarray>(construct(obj, dt, copy))) {}
/// @brief Equivalent to "numpy.matrix(obj,copy=copy)" in Python.
explicit matrix(python::object const & obj, bool copy=true)
: ndarray(python::extract<ndarray>(construct(obj, copy))) {}
/// \brief Return a view of the matrix with the given dtype.
matrix view(dtype const & dt) const;
/// \brief Copy the scalar (deep for all non-object fields).
matrix copy() const;
/// \brief Transpose the matrix.
matrix transpose() const;
};
/**
* @brief CallPolicies that causes a function that returns a numpy.ndarray to
* return a numpy.matrix instead.
*/
template <typename Base = python::default_call_policies>
struct as_matrix : Base {
static PyObject * postcall(PyObject *, PyObject * result) {
python::object a = python::object(python::handle<>(result));
numpy::matrix m(a, false);
Py_INCREF(m.ptr());
return m.ptr();
}
};
} // namespace boost::numpy
namespace python
{
namespace converter
{
NUMPY_OBJECT_MANAGER_TRAITS(numpy::matrix);
} // namespace boost::python::converter
} // namespace boost::python
} // namespace boost
#endif // !BOOST_NUMPY_MATRIX_HPP_INCLUDED

View File

@@ -0,0 +1,303 @@
// Copyright Jim Bosch 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_NUMPY_NDARRAY_HPP_INCLUDED
#define BOOST_NUMPY_NDARRAY_HPP_INCLUDED
/**
* @file boost/numpy/ndarray.hpp
* @brief Object manager and various utilities for numpy.ndarray.
*/
#include <boost/python.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <boost/numpy/numpy_object_mgr_traits.hpp>
#include <boost/numpy/dtype.hpp>
#include <vector>
namespace boost
{
namespace numpy
{
/**
* @brief A boost.python "object manager" (subclass of object) for numpy.ndarray.
*
* @todo This could have a lot more functionality (like boost::python::numeric::array).
* Right now all that exists is what was needed to move raw data between C++ and Python.
*/
class ndarray : public python::object
{
/**
* @brief An internal struct that's byte-compatible with PyArrayObject.
*
* This is just a hack to allow inline access to this stuff while hiding numpy/arrayobject.h
* from the user.
*/
struct array_struct
{
PyObject_HEAD
char * data;
int nd;
Py_intptr_t * shape;
Py_intptr_t * strides;
PyObject * base;
PyObject * descr;
int flags;
PyObject * weakreflist;
};
/// @brief Return the held Python object as an array_struct.
array_struct * get_struct() const { return reinterpret_cast<array_struct*>(this->ptr()); }
public:
/**
* @brief Enum to represent (some) of Numpy's internal flags.
*
* These don't match the actual Numpy flag values; we can't get those without including
* numpy/arrayobject.h or copying them directly. That's very unfortunate.
*
* @todo I'm torn about whether this should be an enum. It's very convenient to not
* make these simple integer values for overloading purposes, but the need to
* define every possible combination and custom bitwise operators is ugly.
*/
enum bitflag
{
NONE=0x0, C_CONTIGUOUS=0x1, F_CONTIGUOUS=0x2, V_CONTIGUOUS=0x1|0x2,
ALIGNED=0x4, WRITEABLE=0x8, BEHAVED=0x4|0x8,
CARRAY_RO=0x1|0x4, CARRAY=0x1|0x4|0x8, CARRAY_MIS=0x1|0x8,
FARRAY_RO=0x2|0x4, FARRAY=0x2|0x4|0x8, FARRAY_MIS=0x2|0x8,
UPDATE_ALL=0x1|0x2|0x4, VARRAY=0x1|0x2|0x8, ALL=0x1|0x2|0x4|0x8
};
BOOST_PYTHON_FORWARD_OBJECT_CONSTRUCTORS(ndarray, object);
/// @brief Return a view of the scalar with the given dtype.
ndarray view(dtype const & dt) const;
/// @brief Copy the array, cast to a specified type.
ndarray astype(dtype const & dt) const;
/// @brief Copy the scalar (deep for all non-object fields).
ndarray copy() const;
/// @brief Return the size of the nth dimension.
Py_intptr_t shape(int n) const { return get_shape()[n]; }
/// @brief Return the stride of the nth dimension.
Py_intptr_t strides(int n) const { return get_strides()[n]; }
/**
* @brief Return the array's raw data pointer.
*
* This returns char so stride math works properly on it. It's pretty much
* expected that the user will have to reinterpret_cast it.
*/
char * get_data() const { return get_struct()->data; }
/// @brief Return the array's data-type descriptor object.
dtype get_dtype() const;
/// @brief Return the object that owns the array's data, or None if the array owns its own data.
python::object get_base() const;
/// @brief Set the object that owns the array's data. Use with care.
void set_base(object const & base);
/// @brief Return the shape of the array as an array of integers (length == get_nd()).
Py_intptr_t const * get_shape() const { return get_struct()->shape; }
/// @brief Return the stride of the array as an array of integers (length == get_nd()).
Py_intptr_t const * get_strides() const { return get_struct()->strides; }
/// @brief Return the number of array dimensions.
int get_nd() const { return get_struct()->nd; }
/// @brief Return the array flags.
bitflag get_flags() const;
/// @brief Reverse the dimensions of the array.
ndarray transpose() const;
/// @brief Eliminate any unit-sized dimensions.
ndarray squeeze() const;
/// @brief Equivalent to self.reshape(*shape) in Python.
ndarray reshape(python::tuple const & shape) const;
/**
* @brief If the array contains only a single element, return it as an array scalar; otherwise return
* the array.
*
* @internal This is simply a call to PyArray_Return();
*/
python::object scalarize() const;
};
/**
* @brief Construct a new array with the given shape and data type, with data initialized to zero.
*/
ndarray zeros(python::tuple const & shape, dtype const & dt);
ndarray zeros(int nd, Py_intptr_t const * shape, dtype const & dt);
/**
* @brief Construct a new array with the given shape and data type, with data left uninitialized.
*/
ndarray empty(python::tuple const & shape, dtype const & dt);
ndarray empty(int nd, Py_intptr_t const * shape, dtype const & dt);
/**
* @brief Construct a new array from an arbitrary Python sequence.
*
* @todo This does't seem to handle ndarray subtypes the same way that "numpy.array" does in Python.
*/
ndarray array(python::object const & obj);
ndarray array(python::object const & obj, dtype const & dt);
namespace detail
{
ndarray from_data_impl(void * data,
dtype const & dt,
std::vector<Py_intptr_t> const & shape,
std::vector<Py_intptr_t> const & strides,
python::object const & owner,
bool writeable);
template <typename Container>
ndarray from_data_impl(void * data,
dtype const & dt,
Container shape,
Container strides,
python::object const & owner,
bool writeable,
typename boost::enable_if< boost::is_integral<typename Container::value_type> >::type * enabled = NULL)
{
std::vector<Py_intptr_t> shape_(shape.begin(),shape.end());
std::vector<Py_intptr_t> strides_(strides.begin(), strides.end());
return from_data_impl(data, dt, shape_, strides_, owner, writeable);
}
ndarray from_data_impl(void * data,
dtype const & dt,
python::object const & shape,
python::object const & strides,
python::object const & owner,
bool writeable);
} // namespace boost::numpy::detail
/**
* @brief Construct a new ndarray object from a raw pointer.
*
* @param[in] data Raw pointer to the first element of the array.
* @param[in] dt Data type descriptor. Often retrieved with dtype::get_builtin().
* @param[in] shape Shape of the array as STL container of integers; must have begin() and end().
* @param[in] strides Shape of the array as STL container of integers; must have begin() and end().
* @param[in] owner An arbitray Python object that owns that data pointer. The array object will
* keep a reference to the object, and decrement it's reference count when the
* array goes out of scope. Pass None at your own peril.
*
* @todo Should probably take ranges of iterators rather than actual container objects.
*/
template <typename Container>
inline ndarray from_data(void * data,
dtype const & dt,
Container shape,
Container strides,
python::object const & owner)
{
return numpy::detail::from_data_impl(data, dt, shape, strides, owner, true);
}
/**
* @brief Construct a new ndarray object from a raw pointer.
*
* @param[in] data Raw pointer to the first element of the array.
* @param[in] dt Data type descriptor. Often retrieved with dtype::get_builtin().
* @param[in] shape Shape of the array as STL container of integers; must have begin() and end().
* @param[in] strides Shape of the array as STL container of integers; must have begin() and end().
* @param[in] owner An arbitray Python object that owns that data pointer. The array object will
* keep a reference to the object, and decrement it's reference count when the
* array goes out of scope. Pass None at your own peril.
*
* This overload takes a const void pointer and sets the "writeable" flag of the array to false.
*
* @todo Should probably take ranges of iterators rather than actual container objects.
*/
template <typename Container>
inline ndarray from_data(void const * data,
dtype const & dt,
Container shape,
Container strides,
python::object const & owner)
{
return numpy::detail::from_data_impl(const_cast<void*>(data), dt, shape, strides, owner, false);
}
/**
* @brief Transform an arbitrary object into a numpy array with the given requirements.
*
* @param[in] obj An arbitrary python object to convert. Arrays that meet the requirements
* will be passed through directly.
* @param[in] dt Data type descriptor. Often retrieved with dtype::get_builtin().
* @param[in] nd_min Minimum number of dimensions.
* @param[in] nd_max Maximum number of dimensions.
* @param[in] flags Bitwise OR of flags specifying additional requirements.
*/
ndarray from_object(python::object const & obj, dtype const & dt,
int nd_min, int nd_max, ndarray::bitflag flags=ndarray::NONE);
inline ndarray from_object(python::object const & obj, dtype const & dt,
int nd, ndarray::bitflag flags=ndarray::NONE)
{
return from_object(obj, dt, nd, nd, flags);
}
inline ndarray from_object(python::object const & obj, dtype const & dt, ndarray::bitflag flags=ndarray::NONE)
{
return from_object(obj, dt, 0, 0, flags);
}
ndarray from_object(python::object const & obj, int nd_min, int nd_max,
ndarray::bitflag flags=ndarray::NONE);
inline ndarray from_object(python::object const & obj, int nd, ndarray::bitflag flags=ndarray::NONE)
{
return from_object(obj, nd, nd, flags);
}
inline ndarray from_object(python::object const & obj, ndarray::bitflag flags=ndarray::NONE)
{
return from_object(obj, 0, 0, flags);
}
inline ndarray::bitflag operator|(ndarray::bitflag a, ndarray::bitflag b)
{
return ndarray::bitflag(int(a) | int(b));
}
inline ndarray::bitflag operator&(ndarray::bitflag a, ndarray::bitflag b)
{
return ndarray::bitflag(int(a) & int(b));
}
} // namespace boost::numpy
namespace python
{
namespace converter
{
NUMPY_OBJECT_MANAGER_TRAITS(numpy::ndarray);
} // namespace boost::python::converter
} // namespace boost::python
} // namespace boost
#endif // !BOOST_NUMPY_NDARRAY_HPP_INCLUDED

View File

@@ -0,0 +1,35 @@
// Copyright Jim Bosch 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_NUMPY_NUMPY_OBJECT_MGR_TRAITS_HPP_INCLUDED
#define BOOST_NUMPY_NUMPY_OBJECT_MGR_TRAITS_HPP_INCLUDED
/**
* @file boost/numpy/numpy_object_mgr_traits.hpp
* @brief Macro that specializes object_manager_traits by requiring a
* source-file implementation of get_pytype().
*/
#define NUMPY_OBJECT_MANAGER_TRAITS(manager) \
template <> \
struct object_manager_traits<manager> \
{ \
BOOST_STATIC_CONSTANT(bool, is_specialized = true); \
static inline python::detail::new_reference adopt(PyObject* x) \
{ \
return python::detail::new_reference(python::pytype_check((PyTypeObject*)get_pytype(), x)); \
} \
static bool check(PyObject* x) \
{ \
return ::PyObject_IsInstance(x, (PyObject*)get_pytype()); \
} \
static manager* checked_downcast(PyObject* x) \
{ \
return python::downcast<manager>((checked_downcast_impl)(x, (PyTypeObject*)get_pytype())); \
} \
static PyTypeObject const * get_pytype(); \
}
#endif // !BOOST_NUMPY_NUMPY_OBJECT_MGR_TRAITS_HPP_INCLUDED

View File

@@ -0,0 +1,64 @@
// Copyright Jim Bosch 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_NUMPY_SCALARS_HPP_INCLUDED
#define BOOST_NUMPY_SCALARS_HPP_INCLUDED
/**
* @file boost/numpy/scalars.hpp
* @brief Object managers for array scalars (currently only numpy.void is implemented).
*/
#include <boost/python.hpp>
#include <boost/numpy/numpy_object_mgr_traits.hpp>
#include <boost/numpy/dtype.hpp>
namespace boost
{
namespace numpy
{
/**
* @brief A boost.python "object manager" (subclass of object) for numpy.void.
*
* @todo This could have a lot more functionality.
*/
class void_ : public python::object
{
static python::detail::new_reference convert(object_cref arg, bool align);
public:
/**
* @brief Construct a new array scalar with the given size and void dtype.
*
* Data is initialized to zero. One can create a standalone scalar object
* with a certain dtype "dt" with:
* @code
* void_ scalar = void_(dt.get_itemsize()).view(dt);
* @endcode
*/
explicit void_(Py_ssize_t size);
BOOST_PYTHON_FORWARD_OBJECT_CONSTRUCTORS(void_, object);
/// @brief Return a view of the scalar with the given dtype.
void_ view(dtype const & dt) const;
/// @brief Copy the scalar (deep for all non-object fields).
void_ copy() const;
};
} // namespace boost::numpy
namespace python
{
namespace converter
{
NUMPY_OBJECT_MANAGER_TRAITS(numpy::void_);
} // namespace boost::python::converter
} // namespace boost::python
} // namespace boost
#endif // !BOOST_NUMPY_SCALARS_HPP_INCLUDED

View File

@@ -0,0 +1,213 @@
// Copyright Jim Bosch 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_NUMPY_UFUNC_HPP_INCLUDED
#define BOOST_NUMPY_UFUNC_HPP_INCLUDED
/**
* @file boost/numpy/ufunc.hpp
* @brief Utilities to create ufunc-like broadcasting functions out of C++ functors.
*/
#include <boost/python.hpp>
#include <boost/numpy/numpy_object_mgr_traits.hpp>
#include <boost/numpy/dtype.hpp>
#include <boost/numpy/ndarray.hpp>
namespace boost
{
namespace numpy
{
/**
* @brief A boost.python "object manager" (subclass of object) for PyArray_MultiIter.
*
* multi_iter is a Python object, but a very low-level one. It should generally only be used
* in loops of the form:
* @code
* while (iter.not_done()) {
* ...
* iter.next();
* }
* @endcode
*
* @todo I can't tell if this type is exposed in Python anywhere; if it is, we should use that name.
* It's more dangerous than most object managers, however - maybe it actually belongs in
* a detail namespace?
*/
class multi_iter : public python::object
{
public:
BOOST_PYTHON_FORWARD_OBJECT_CONSTRUCTORS(multi_iter, python::object);
/// @brief Increment the iterator.
void next();
/// @brief Check if the iterator is at its end.
bool not_done() const;
/// @brief Return a pointer to the element of the nth broadcasted array.
char * get_data(int n) const;
/// @brief Return the number of dimensions of the broadcasted array expression.
int get_nd() const;
/// @brief Return the shape of the broadcasted array expression as an array of integers.
Py_intptr_t const * get_shape() const;
/// @brief Return the shape of the broadcasted array expression in the nth dimension.
Py_intptr_t shape(int n) const;
};
/// @brief Construct a multi_iter over a single sequence or scalar object.
multi_iter make_multi_iter(python::object const & a1);
/// @brief Construct a multi_iter by broadcasting two objects.
multi_iter make_multi_iter(python::object const & a1, python::object const & a2);
/// @brief Construct a multi_iter by broadcasting three objects.
multi_iter make_multi_iter(python::object const & a1, python::object const & a2, python::object const & a3);
/**
* @brief Helps wrap a C++ functor taking a single scalar argument as a broadcasting ufunc-like
* Python object.
*
* Typical usage looks like this:
* @code
* struct TimesPI
* {
* typedef double argument_type;
* typedef double result_type;
* double operator()(double input) const { return input * M_PI; }
* };
*
* BOOST_PYTHON_MODULE(example)
* {
* class_< TimesPI >("TimesPI")
* .def("__call__", unary_ufunc<TimesPI>::make());
* }
* @endcode
*
*/
template <typename TUnaryFunctor,
typename TArgument=typename TUnaryFunctor::argument_type,
typename TResult=typename TUnaryFunctor::result_type>
struct unary_ufunc
{
/**
* @brief A C++ function with object arguments that broadcasts its arguments before
* passing them to the underlying C++ functor.
*/
static python::object call(TUnaryFunctor & self, python::object const & input, python::object const & output)
{
dtype in_dtype = dtype::get_builtin<TArgument>();
dtype out_dtype = dtype::get_builtin<TResult>();
ndarray in_array = from_object(input, in_dtype, ndarray::ALIGNED);
ndarray out_array = (output != python::object()) ?
from_object(output, out_dtype, ndarray::ALIGNED | ndarray::WRITEABLE)
: zeros(in_array.get_nd(), in_array.get_shape(), out_dtype);
multi_iter iter = make_multi_iter(in_array, out_array);
while (iter.not_done())
{
TArgument * argument = reinterpret_cast<TArgument*>(iter.get_data(0));
TResult * result = reinterpret_cast<TResult*>(iter.get_data(1));
*result = self(*argument);
iter.next();
}
return out_array.scalarize();
}
/**
* @brief Construct a boost.python function object from call() with reasonable keyword names.
*
* Users will often want to specify their own keyword names with the same signature, but this
* is a convenient shortcut.
*/
static python::object make()
{
namespace p = python;
return p::make_function(call, p::default_call_policies(), (p::arg("input"), p::arg("output")=p::object()));
}
};
/**
* @brief Helps wrap a C++ functor taking a pair of scalar arguments as a broadcasting ufunc-like
* Python object.
*
* Typical usage looks like this:
* @code
* struct CosSum
* {
* typedef double first_argument_type;
* typedef double second_argument_type;
* typedef double result_type;
* double operator()(double input1, double input2) const { return std::cos(input1 + input2); }
* };
*
* BOOST_PYTHON_MODULE(example)
* {
* class_< CosSum >("CosSum")
* .def("__call__", binary_ufunc<CosSum>::make());
* }
* @endcode
*
*/
template <typename TBinaryFunctor,
typename TArgument1=typename TBinaryFunctor::first_argument_type,
typename TArgument2=typename TBinaryFunctor::second_argument_type,
typename TResult=typename TBinaryFunctor::result_type>
struct binary_ufunc
{
static python::object
call(TBinaryFunctor & self, python::object const & input1, python::object const & input2,
python::object const & output)
{
dtype in1_dtype = dtype::get_builtin<TArgument1>();
dtype in2_dtype = dtype::get_builtin<TArgument2>();
dtype out_dtype = dtype::get_builtin<TResult>();
ndarray in1_array = from_object(input1, in1_dtype, ndarray::ALIGNED);
ndarray in2_array = from_object(input2, in2_dtype, ndarray::ALIGNED);
multi_iter iter = make_multi_iter(in1_array, in2_array);
ndarray out_array = (output != python::object())
? from_object(output, out_dtype, ndarray::ALIGNED | ndarray::WRITEABLE)
: zeros(iter.get_nd(), iter.get_shape(), out_dtype);
iter = make_multi_iter(in1_array, in2_array, out_array);
while (iter.not_done())
{
TArgument1 * argument1 = reinterpret_cast<TArgument1*>(iter.get_data(0));
TArgument2 * argument2 = reinterpret_cast<TArgument2*>(iter.get_data(1));
TResult * result = reinterpret_cast<TResult*>(iter.get_data(2));
*result = self(*argument1, *argument2);
iter.next();
}
return out_array.scalarize();
}
static python::object make()
{
namespace p = python;
return p::make_function(call, p::default_call_policies(),
(p::arg("input1"), p::arg("input2"), p::arg("output")=p::object()));
}
};
} // namespace boost::numpy
namespace python
{
namespace converter
{
NUMPY_OBJECT_MANAGER_TRAITS(numpy::multi_iter);
} // namespace boost::python::converter
} // namespace boost::python
} // namespace boost
#endif // !BOOST_NUMPY_UFUNC_HPP_INCLUDED

200
src/numpy/dtype.cpp Normal file
View File

@@ -0,0 +1,200 @@
// Copyright Jim Bosch 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifdef _MSC_VER
#include <boost/cstdint.hpp>
#endif
#define BOOST_NUMPY_INTERNAL
#include <boost/numpy/internal.hpp>
#define DTYPE_FROM_CODE(code) \
dtype(python::detail::new_reference(reinterpret_cast<PyObject*>(PyArray_DescrFromType(code))))
#define BUILTIN_INT_DTYPE(bits) \
template <> struct builtin_int_dtype< bits, false > { \
static dtype get() { return DTYPE_FROM_CODE(NPY_INT ## bits); } \
}; \
template <> struct builtin_int_dtype< bits, true > { \
static dtype get() { return DTYPE_FROM_CODE(NPY_UINT ## bits); } \
}; \
template dtype get_int_dtype< bits, false >(); \
template dtype get_int_dtype< bits, true >()
#define BUILTIN_FLOAT_DTYPE(bits) \
template <> struct builtin_float_dtype< bits > { \
static dtype get() { return DTYPE_FROM_CODE(NPY_FLOAT ## bits); } \
}; \
template dtype get_float_dtype< bits >()
#define BUILTIN_COMPLEX_DTYPE(bits) \
template <> struct builtin_complex_dtype< bits > { \
static dtype get() { return DTYPE_FROM_CODE(NPY_COMPLEX ## bits); } \
}; \
template dtype get_complex_dtype< bits >()
namespace boost { namespace python { namespace converter {
NUMPY_OBJECT_MANAGER_TRAITS_IMPL(PyArrayDescr_Type, numpy::dtype)
}}} // namespace boost::python::converter
namespace boost { namespace numpy {
namespace detail {
dtype builtin_dtype<bool,true>::get() { return DTYPE_FROM_CODE(NPY_BOOL); }
template <int bits, bool isUnsigned> struct builtin_int_dtype;
template <int bits> struct builtin_float_dtype;
template <int bits> struct builtin_complex_dtype;
template <int bits, bool isUnsigned> dtype get_int_dtype() {
return builtin_int_dtype<bits,isUnsigned>::get();
}
template <int bits> dtype get_float_dtype() { return builtin_float_dtype<bits>::get(); }
template <int bits> dtype get_complex_dtype() { return builtin_complex_dtype<bits>::get(); }
BUILTIN_INT_DTYPE(8);
BUILTIN_INT_DTYPE(16);
BUILTIN_INT_DTYPE(32);
BUILTIN_INT_DTYPE(64);
BUILTIN_FLOAT_DTYPE(16);
BUILTIN_FLOAT_DTYPE(32);
BUILTIN_FLOAT_DTYPE(64);
BUILTIN_COMPLEX_DTYPE(64);
BUILTIN_COMPLEX_DTYPE(128);
#if NPY_BITSOF_LONGDOUBLE > NPY_BITSOF_DOUBLE
template <> struct builtin_float_dtype< NPY_BITSOF_LONGDOUBLE > {
static dtype get() { return DTYPE_FROM_CODE(NPY_LONGDOUBLE); }
};
template dtype get_float_dtype< NPY_BITSOF_LONGDOUBLE >();
template <> struct builtin_complex_dtype< 2 * NPY_BITSOF_LONGDOUBLE > {
static dtype get() { return DTYPE_FROM_CODE(NPY_CLONGDOUBLE); }
};
template dtype get_complex_dtype< 2 * NPY_BITSOF_LONGDOUBLE >();
#endif
} // namespace detail
python::detail::new_reference dtype::convert(python::object const & arg, bool align) {
PyArray_Descr* obj=NULL;
if (align) {
if (PyArray_DescrAlignConverter(arg.ptr(), &obj) < 0)
python::throw_error_already_set();
} else {
if (PyArray_DescrConverter(arg.ptr(), &obj) < 0)
python::throw_error_already_set();
}
return python::detail::new_reference(reinterpret_cast<PyObject*>(obj));
}
int dtype::get_itemsize() const { return reinterpret_cast<PyArray_Descr*>(ptr())->elsize;}
bool equivalent(dtype const & a, dtype const & b) {
// On Windows x64, the behaviour described on
// http://docs.scipy.org/doc/numpy/reference/c-api.array.html for
// PyArray_EquivTypes unfortunately does not extend as expected:
// "For example, on 32-bit platforms, NPY_LONG and NPY_INT are equivalent".
// This should also hold for 64-bit platforms (and does on Linux), but not
// on Windows. Implement an alternative:
#ifdef _MSC_VER
if (sizeof(long) == sizeof(int) &&
// Manually take care of the type equivalence.
((a == dtype::get_builtin<long>() || a == dtype::get_builtin<int>()) &&
(b == dtype::get_builtin<long>() || b == dtype::get_builtin<int>()) ||
(a == dtype::get_builtin<unsigned int>() || a == dtype::get_builtin<unsigned long>()) &&
(b == dtype::get_builtin<unsigned int>() || b == dtype::get_builtin<unsigned long>()))) {
return true;
} else {
return PyArray_EquivTypes(
reinterpret_cast<PyArray_Descr*>(a.ptr()),
reinterpret_cast<PyArray_Descr*>(b.ptr())
);
}
#else
return PyArray_EquivTypes(
reinterpret_cast<PyArray_Descr*>(a.ptr()),
reinterpret_cast<PyArray_Descr*>(b.ptr())
);
#endif
}
namespace {
namespace pyconv = boost::python::converter;
template <typename T>
class array_scalar_converter {
public:
static PyTypeObject const * get_pytype() {
// This implementation depends on the fact that get_builtin returns pointers to objects
// NumPy has declared statically, and that the typeobj member also refers to a static
// object. That means we don't need to do any reference counting.
// In fact, I'm somewhat concerned that increasing the reference count of any of these
// might cause leaks, because I don't think Boost.Python ever decrements it, but it's
// probably a moot point if everything is actually static.
return reinterpret_cast<PyArray_Descr*>(dtype::get_builtin<T>().ptr())->typeobj;
}
static void * convertible(PyObject * obj) {
if (obj->ob_type == get_pytype()) {
return obj;
} else {
dtype dt(python::detail::borrowed_reference(obj->ob_type));
if (equivalent(dt, dtype::get_builtin<T>())) {
return obj;
}
}
return 0;
}
static void convert(PyObject * obj, pyconv::rvalue_from_python_stage1_data* data) {
void * storage = reinterpret_cast<pyconv::rvalue_from_python_storage<T>*>(data)->storage.bytes;
// We assume std::complex is a "standard layout" here and elsewhere; not guaranteed by
// C++03 standard, but true in every known implementation (and guaranteed by C++11).
PyArray_ScalarAsCtype(obj, reinterpret_cast<T*>(storage));
data->convertible = storage;
}
static void declare() {
pyconv::registry::push_back(
&convertible, &convert, python::type_id<T>()
#ifndef BOOST_PYTHON_NO_PY_SIGNATURES
, &get_pytype
#endif
);
}
};
} // anonymous
void dtype::register_scalar_converters() {
array_scalar_converter<bool>::declare();
array_scalar_converter<npy_uint8>::declare();
array_scalar_converter<npy_int8>::declare();
array_scalar_converter<npy_uint16>::declare();
array_scalar_converter<npy_int16>::declare();
array_scalar_converter<npy_uint32>::declare();
array_scalar_converter<npy_int32>::declare();
#ifdef _MSC_VER
// Since the npy_(u)int32 types are defined as long types and treated
// as being different from the int32 types, these converters must be declared
// explicitely.
array_scalar_converter<boost::uint32_t>::declare();
array_scalar_converter<boost::int32_t>::declare();
#endif
array_scalar_converter<npy_uint64>::declare();
array_scalar_converter<npy_int64>::declare();
array_scalar_converter<float>::declare();
array_scalar_converter<double>::declare();
array_scalar_converter< std::complex<float> >::declare();
array_scalar_converter< std::complex<double> >::declare();
#if NPY_BITSOF_LONGDOUBLE > NPY_BITSOF_DOUBLE
array_scalar_converter<long double>::declare();
array_scalar_converter< std::complex<long double> >::declare();
#endif
}
} // namespace boost::numpy
} // namespace boost

68
src/numpy/matrix.cpp Normal file
View File

@@ -0,0 +1,68 @@
// Copyright Jim Bosch 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#define BOOST_NUMPY_INTERNAL
#include <boost/numpy/internal.hpp>
#include <boost/numpy/matrix.hpp>
namespace boost
{
namespace numpy
{
namespace detail
{
inline python::object get_matrix_type()
{
python::object module = python::import("numpy");
return module.attr("matrix");
}
} // namespace boost::numpy::detail
} // namespace boost::numpy
namespace python
{
namespace converter
{
PyTypeObject const * object_manager_traits<numpy::matrix>::get_pytype()
{
return reinterpret_cast<PyTypeObject*>(numpy::detail::get_matrix_type().ptr());
}
} // namespace boost::python::converter
} // namespace boost::python
namespace numpy
{
python::object matrix::construct(python::object const & obj, dtype const & dt, bool copy)
{
return numpy::detail::get_matrix_type()(obj, dt, copy);
}
python::object matrix::construct(python::object const & obj, bool copy)
{
return numpy::detail::get_matrix_type()(obj, object(), copy);
}
matrix matrix::view(dtype const & dt) const
{
return matrix(python::detail::new_reference
(PyObject_CallMethod(this->ptr(), const_cast<char*>("view"), const_cast<char*>("O"), dt.ptr())));
}
matrix matrix::copy() const
{
return matrix(python::detail::new_reference
(PyObject_CallMethod(this->ptr(), const_cast<char*>("copy"), const_cast<char*>(""))));
}
matrix matrix::transpose() const
{
return matrix(python::extract<matrix>(ndarray::transpose()));
}
} // namespace boost::numpy
} // namespace boost

281
src/numpy/ndarray.cpp Normal file
View File

@@ -0,0 +1,281 @@
// Copyright Jim Bosch 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#define BOOST_NUMPY_INTERNAL
#include <boost/numpy/internal.hpp>
#include <boost/scoped_array.hpp>
namespace boost
{
namespace python
{
namespace converter
{
NUMPY_OBJECT_MANAGER_TRAITS_IMPL(PyArray_Type, numpy::ndarray)
} // namespace boost::python::converter
} // namespace boost::python
namespace numpy
{
namespace detail
{
ndarray::bitflag numpy_to_bitflag(int const f)
{
ndarray::bitflag r = ndarray::NONE;
if (f & NPY_C_CONTIGUOUS) r = (r | ndarray::C_CONTIGUOUS);
if (f & NPY_F_CONTIGUOUS) r = (r | ndarray::F_CONTIGUOUS);
if (f & NPY_ALIGNED) r = (r | ndarray::ALIGNED);
if (f & NPY_WRITEABLE) r = (r | ndarray::WRITEABLE);
return r;
}
int bitflag_to_numpy(ndarray::bitflag f)
{
int r = 0;
if (f & ndarray::C_CONTIGUOUS) r |= NPY_C_CONTIGUOUS;
if (f & ndarray::F_CONTIGUOUS) r |= NPY_F_CONTIGUOUS;
if (f & ndarray::ALIGNED) r |= NPY_ALIGNED;
if (f & ndarray::WRITEABLE) r |= NPY_WRITEABLE;
return r;
}
bool is_c_contiguous(std::vector<Py_intptr_t> const & shape,
std::vector<Py_intptr_t> const & strides,
int itemsize)
{
std::vector<Py_intptr_t>::const_reverse_iterator j = strides.rbegin();
int total = itemsize;
for (std::vector<Py_intptr_t>::const_reverse_iterator i = shape.rbegin(); i != shape.rend(); ++i, ++j)
{
if (total != *j) return false;
total *= (*i);
}
return true;
}
bool is_f_contiguous(std::vector<Py_intptr_t> const & shape,
std::vector<Py_intptr_t> const & strides,
int itemsize)
{
std::vector<Py_intptr_t>::const_iterator j = strides.begin();
int total = itemsize;
for (std::vector<Py_intptr_t>::const_iterator i = shape.begin(); i != shape.end(); ++i, ++j)
{
if (total != *j) return false;
total *= (*i);
}
return true;
}
bool is_aligned(std::vector<Py_intptr_t> const & strides,
int itemsize)
{
for (std::vector<Py_intptr_t>::const_iterator i = strides.begin(); i != strides.end(); ++i)
{
if (*i % itemsize) return false;
}
return true;
}
inline PyArray_Descr * incref_dtype(dtype const & dt)
{
Py_INCREF(dt.ptr());
return reinterpret_cast<PyArray_Descr*>(dt.ptr());
}
ndarray from_data_impl(void * data,
dtype const & dt,
python::object const & shape,
python::object const & strides,
python::object const & owner,
bool writeable)
{
std::vector<Py_intptr_t> shape_(len(shape));
std::vector<Py_intptr_t> strides_(len(strides));
if (shape_.size() != strides_.size())
{
PyErr_SetString(PyExc_ValueError, "Length of shape and strides arrays do not match.");
python::throw_error_already_set();
}
for (std::size_t i = 0; i < shape_.size(); ++i)
{
shape_[i] = python::extract<Py_intptr_t>(shape[i]);
strides_[i] = python::extract<Py_intptr_t>(strides[i]);
}
return from_data_impl(data, dt, shape_, strides_, owner, writeable);
}
ndarray from_data_impl(void * data,
dtype const & dt,
std::vector<Py_intptr_t> const & shape,
std::vector<Py_intptr_t> const & strides,
python::object const & owner,
bool writeable)
{
if (shape.size() != strides.size())
{
PyErr_SetString(PyExc_ValueError, "Length of shape and strides arrays do not match.");
python::throw_error_already_set();
}
int itemsize = dt.get_itemsize();
int flags = 0;
if (writeable) flags |= NPY_WRITEABLE;
if (is_c_contiguous(shape, strides, itemsize)) flags |= NPY_C_CONTIGUOUS;
if (is_f_contiguous(shape, strides, itemsize)) flags |= NPY_F_CONTIGUOUS;
if (is_aligned(strides, itemsize)) flags |= NPY_ALIGNED;
ndarray r(python::detail::new_reference
(PyArray_NewFromDescr(&PyArray_Type,
incref_dtype(dt),
shape.size(),
const_cast<Py_intptr_t*>(&shape.front()),
const_cast<Py_intptr_t*>(&strides.front()),
data,
flags,
NULL)));
r.set_base(owner);
return r;
}
} // namespace detail
ndarray ndarray::view(dtype const & dt) const
{
return ndarray(python::detail::new_reference
(PyObject_CallMethod(this->ptr(), const_cast<char*>("view"), const_cast<char*>("O"), dt.ptr())));
}
ndarray ndarray::astype(dtype const & dt) const
{
return ndarray(python::detail::new_reference
(PyObject_CallMethod(this->ptr(), const_cast<char*>("astype"), const_cast<char*>("O"), dt.ptr())));
}
ndarray ndarray::copy() const
{
return ndarray(python::detail::new_reference
(PyObject_CallMethod(this->ptr(), const_cast<char*>("copy"), const_cast<char*>(""))));
}
dtype ndarray::get_dtype() const
{
return dtype(python::detail::borrowed_reference(get_struct()->descr));
}
python::object ndarray::get_base() const
{
if (get_struct()->base == NULL) return object();
return python::object(python::detail::borrowed_reference(get_struct()->base));
}
void ndarray::set_base(object const & base)
{
Py_XDECREF(get_struct()->base);
if (base != object())
{
Py_INCREF(base.ptr());
get_struct()->base = base.ptr();
}
else
{
get_struct()->base = NULL;
}
}
ndarray::bitflag ndarray::get_flags() const
{
return numpy::detail::numpy_to_bitflag(get_struct()->flags);
}
ndarray ndarray::transpose() const
{
return ndarray(python::detail::new_reference
(PyArray_Transpose(reinterpret_cast<PyArrayObject*>(this->ptr()), NULL)));
}
ndarray ndarray::squeeze() const
{
return ndarray(python::detail::new_reference
(PyArray_Squeeze(reinterpret_cast<PyArrayObject*>(this->ptr()))));
}
ndarray ndarray::reshape(python::tuple const & shape) const
{
return ndarray(python::detail::new_reference
(PyArray_Reshape(reinterpret_cast<PyArrayObject*>(this->ptr()), shape.ptr())));
}
python::object ndarray::scalarize() const
{
Py_INCREF(ptr());
return python::object(python::detail::new_reference(PyArray_Return(reinterpret_cast<PyArrayObject*>(ptr()))));
}
ndarray zeros(python::tuple const & shape, dtype const & dt)
{
int nd = len(shape);
boost::scoped_array<Py_intptr_t> dims(new Py_intptr_t[nd]);
for (int n=0; n<nd; ++n) dims[n] = python::extract<Py_intptr_t>(shape[n]);
return ndarray(python::detail::new_reference
(PyArray_Zeros(nd, dims.get(), detail::incref_dtype(dt), 0)));
}
ndarray zeros(int nd, Py_intptr_t const * shape, dtype const & dt)
{
return ndarray(python::detail::new_reference
(PyArray_Zeros(nd, const_cast<Py_intptr_t*>(shape), detail::incref_dtype(dt), 0)));
}
ndarray empty(python::tuple const & shape, dtype const & dt)
{
int nd = len(shape);
boost::scoped_array<Py_intptr_t> dims(new Py_intptr_t[nd]);
for (int n=0; n<nd; ++n) dims[n] = python::extract<Py_intptr_t>(shape[n]);
return ndarray(python::detail::new_reference
(PyArray_Empty(nd, dims.get(), detail::incref_dtype(dt), 0)));
}
ndarray empty(int nd, Py_intptr_t const * shape, dtype const & dt)
{
return ndarray(python::detail::new_reference
(PyArray_Empty(nd, const_cast<Py_intptr_t*>(shape), detail::incref_dtype(dt), 0)));
}
ndarray array(python::object const & obj)
{
return ndarray(python::detail::new_reference
(PyArray_FromAny(obj.ptr(), NULL, 0, 0, NPY_ENSUREARRAY, NULL)));
}
ndarray array(python::object const & obj, dtype const & dt)
{
return ndarray(python::detail::new_reference
(PyArray_FromAny(obj.ptr(), detail::incref_dtype(dt), 0, 0, NPY_ENSUREARRAY, NULL)));
}
ndarray from_object(python::object const & obj, dtype const & dt, int nd_min, int nd_max, ndarray::bitflag flags)
{
int requirements = detail::bitflag_to_numpy(flags);
return ndarray(python::detail::new_reference
(PyArray_FromAny(obj.ptr(),
detail::incref_dtype(dt),
nd_min, nd_max,
requirements,
NULL)));
}
ndarray from_object(python::object const & obj, int nd_min, int nd_max, ndarray::bitflag flags)
{
int requirements = detail::bitflag_to_numpy(flags);
return ndarray(python::detail::new_reference
(PyArray_FromAny(obj.ptr(),
NULL,
nd_min, nd_max,
requirements,
NULL)));
}
}
}

34
src/numpy/numpy.cpp Normal file
View File

@@ -0,0 +1,34 @@
// Copyright Jim Bosch 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#define BOOST_NUMPY_INTERNAL_MAIN
#include <boost/numpy/internal.hpp>
#include <boost/numpy/dtype.hpp>
namespace boost
{
namespace numpy
{
#if PY_MAJOR_VERSION == 2
static void wrap_import_array() {
import_array();
}
#else
static void * wrap_import_array() {
import_array();
}
#endif
void initialize(bool register_scalar_converters)
{
wrap_import_array();
import_ufunc();
if (register_scalar_converters)
dtype::register_scalar_converters();
}
}
}

40
src/numpy/scalars.cpp Normal file
View File

@@ -0,0 +1,40 @@
// Copyright Jim Bosch 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#define BOOST_NUMPY_INTERNAL
#include <boost/numpy/internal.hpp>
namespace boost
{
namespace python
{
namespace converter
{
NUMPY_OBJECT_MANAGER_TRAITS_IMPL(PyVoidArrType_Type, numpy::void_)
} // namespace boost::python::converter
} // namespace boost::python
namespace numpy
{
void_::void_(Py_ssize_t size)
: object(python::detail::new_reference
(PyObject_CallFunction((PyObject*)&PyVoidArrType_Type, const_cast<char*>("i"), size)))
{}
void_ void_::view(dtype const & dt) const
{
return void_(python::detail::new_reference
(PyObject_CallMethod(this->ptr(), const_cast<char*>("view"), const_cast<char*>("O"), dt.ptr())));
}
void_ void_::copy() const
{
return void_(python::detail::new_reference
(PyObject_CallMethod(this->ptr(), const_cast<char*>("copy"), const_cast<char*>(""))));
}
}
}

69
src/numpy/ufunc.cpp Normal file
View File

@@ -0,0 +1,69 @@
// Copyright Jim Bosch 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#define BOOST_NUMPY_INTERNAL
#include <boost/numpy/internal.hpp>
#include <boost/numpy/ufunc.hpp>
namespace boost
{
namespace python
{
namespace converter
{
NUMPY_OBJECT_MANAGER_TRAITS_IMPL(PyArrayMultiIter_Type, numpy::multi_iter)
} // namespace boost::python::converter
} // namespace boost::python
namespace numpy
{
multi_iter make_multi_iter(python::object const & a1)
{
return multi_iter(python::detail::new_reference(PyArray_MultiIterNew(1, a1.ptr())));
}
multi_iter make_multi_iter(python::object const & a1, python::object const & a2)
{
return multi_iter(python::detail::new_reference(PyArray_MultiIterNew(2, a1.ptr(), a2.ptr())));
}
multi_iter make_multi_iter(python::object const & a1, python::object const & a2, python::object const & a3)
{
return multi_iter(python::detail::new_reference(PyArray_MultiIterNew(3, a1.ptr(), a2.ptr(), a3.ptr())));
}
void multi_iter::next()
{
PyArray_MultiIter_NEXT(ptr());
}
bool multi_iter::not_done() const
{
return PyArray_MultiIter_NOTDONE(ptr());
}
char * multi_iter::get_data(int i) const
{
return reinterpret_cast<char*>(PyArray_MultiIter_DATA(ptr(), i));
}
int multi_iter::get_nd() const
{
return reinterpret_cast<PyArrayMultiIterObject*>(ptr())->nd;
}
Py_intptr_t const * multi_iter::get_shape() const
{
return reinterpret_cast<PyArrayMultiIterObject*>(ptr())->dimensions;
}
Py_intptr_t multi_iter::shape(int n) const
{
return reinterpret_cast<PyArrayMultiIterObject*>(ptr())->dimensions[n];
}
}
}

60
test/numpy/dtype.py Normal file
View File

@@ -0,0 +1,60 @@
#!/usr/bin/env python
# Copyright Jim Bosch & Ankit Daftery 2010-2012.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
import dtype_mod
import unittest
import numpy
class DtypeTestCase(unittest.TestCase):
def assertEquivalent(self, a, b):
return self.assert_(dtype_mod.equivalent(a, b), "%r is not equivalent to %r")
def testIntegers(self):
for bits in (8, 16, 32, 64):
s = getattr(numpy, "int%d" % bits)
u = getattr(numpy, "uint%d" % bits)
fs = getattr(dtype_mod, "accept_int%d" % bits)
fu = getattr(dtype_mod, "accept_uint%d" % bits)
self.assertEquivalent(fs(s(1)), numpy.dtype(s))
self.assertEquivalent(fu(u(1)), numpy.dtype(u))
# these should just use the regular Boost.Python converters
self.assertEquivalent(fs(True), numpy.dtype(s))
self.assertEquivalent(fu(True), numpy.dtype(u))
self.assertEquivalent(fs(int(1)), numpy.dtype(s))
self.assertEquivalent(fu(int(1)), numpy.dtype(u))
self.assertEquivalent(fs(long(1)), numpy.dtype(s))
self.assertEquivalent(fu(long(1)), numpy.dtype(u))
for name in ("bool_", "byte", "ubyte", "short", "ushort", "intc", "uintc"):
t = getattr(numpy, name)
ft = getattr(dtype_mod, "accept_%s" % name)
self.assertEquivalent(ft(t(1)), numpy.dtype(t))
# these should just use the regular Boost.Python converters
self.assertEquivalent(ft(True), numpy.dtype(t))
if name != "bool_":
self.assertEquivalent(ft(int(1)), numpy.dtype(t))
self.assertEquivalent(ft(long(1)), numpy.dtype(t))
def testFloats(self):
f = numpy.float32
c = numpy.complex64
self.assertEquivalent(dtype_mod.accept_float32(f(numpy.pi)), numpy.dtype(f))
self.assertEquivalent(dtype_mod.accept_complex64(c(1+2j)), numpy.dtype(c))
f = numpy.float64
c = numpy.complex128
self.assertEquivalent(dtype_mod.accept_float64(f(numpy.pi)), numpy.dtype(f))
self.assertEquivalent(dtype_mod.accept_complex128(c(1+2j)), numpy.dtype(c))
if hasattr(numpy, "longdouble") and hasattr(dtype_mod, "accept_longdouble"):
f = numpy.longdouble
c = numpy.clongdouble
self.assertEquivalent(dtype_mod.accept_longdouble(f(numpy.pi)), numpy.dtype(f))
self.assertEquivalent(dtype_mod.accept_clongdouble(c(1+2j)), numpy.dtype(c))
if __name__=="__main__":
unittest.main()

48
test/numpy/dtype_mod.cpp Normal file
View File

@@ -0,0 +1,48 @@
// Copyright Jim Bosch & Ankit Daftery 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/numpy.hpp>
#include <boost/cstdint.hpp>
namespace p = boost::python;
namespace np = boost::numpy;
template <typename T>
np::dtype accept(T) {
return np::dtype::get_builtin<T>();
}
BOOST_PYTHON_MODULE(dtype_mod)
{
np::initialize();
// wrap dtype equivalence test, since it isn't available in Python API.
p::def("equivalent", np::equivalent);
// integers, by number of bits
p::def("accept_int8", accept<boost::int8_t>);
p::def("accept_uint8", accept<boost::uint8_t>);
p::def("accept_int16", accept<boost::int16_t>);
p::def("accept_uint16", accept<boost::uint16_t>);
p::def("accept_int32", accept<boost::int32_t>);
p::def("accept_uint32", accept<boost::uint32_t>);
p::def("accept_int64", accept<boost::int64_t>);
p::def("accept_uint64", accept<boost::uint64_t>);
// integers, by C name according to NumPy
p::def("accept_bool_", accept<bool>);
p::def("accept_byte", accept<signed char>);
p::def("accept_ubyte", accept<unsigned char>);
p::def("accept_short", accept<short>);
p::def("accept_ushort", accept<unsigned short>);
p::def("accept_intc", accept<int>);
p::def("accept_uintc", accept<unsigned int>);
// floats and complex
p::def("accept_float32", accept<float>);
p::def("accept_complex64", accept< std::complex<float> >);
p::def("accept_float64", accept<double>);
p::def("accept_complex128", accept< std::complex<double> >);
if (sizeof(long double) > sizeof(double)) {
p::def("accept_longdouble", accept<long double>);
p::def("accept_clongdouble", accept< std::complex<long double> >);
}
}

55
test/numpy/indexing.py Normal file
View File

@@ -0,0 +1,55 @@
#!/usr/bin/env python
# Copyright Jim Bosch & Ankit Daftery 2010-2012.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
import unittest
import numpy
import indexing_mod
class TestIndexing(unittest.TestCase):
def testSingle(self):
x = numpy.arange(0,10)
for i in range(0,10):
numpy.testing.assert_equal(indexing_mod.single(x,i), i)
for i in range(-10,0):
numpy.testing.assert_equal(indexing_mod.single(x,i),10+i)
def testSlice(self):
x = numpy.arange(0,10)
sl = slice(3,8)
b = [3,4,5,6,7]
numpy.testing.assert_equal(indexing_mod.slice(x,sl), b)
def testStepSlice(self):
x = numpy.arange(0,10)
sl = slice(3,8,2)
b = [3,5,7]
numpy.testing.assert_equal(indexing_mod.slice(x,sl), b)
def testIndex(self):
x = numpy.arange(0,10)
chk = numpy.array([3,4,5,6])
numpy.testing.assert_equal(indexing_mod.indexarray(x,chk),chk)
chk = numpy.array([[0,1],[2,3]])
numpy.testing.assert_equal(indexing_mod.indexarray(x,chk),chk)
x = numpy.arange(9).reshape(3,3)
y = numpy.array([0,1])
z = numpy.array([0,2])
chk = numpy.array([0,5])
numpy.testing.assert_equal(indexing_mod.indexarray(x,y,z),chk)
x = numpy.arange(0,10)
b = x>4
chk = numpy.array([5,6,7,8,9])
numpy.testing.assert_equal(indexing_mod.indexarray(x,b),chk)
x = numpy.arange(9).reshape(3,3)
b = numpy.array([0,2])
sl = slice(0,3)
chk = numpy.array([[0,1,2],[6,7,8]])
numpy.testing.assert_equal(indexing_mod.indexslice(x,b,sl),chk)
if __name__=="__main__":
unittest.main()

View File

@@ -0,0 +1,27 @@
// Copyright Jim Bosch & Ankit Daftery 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/numpy.hpp>
#include <boost/python/slice.hpp>
namespace p = boost::python;
namespace np = boost::numpy;
p::object single(np::ndarray ndarr, int i) { return ndarr[i];}
p::object slice(np::ndarray ndarr, p::slice sl) { return ndarr[sl];}
p::object indexarray(np::ndarray ndarr, np::ndarray d1) { return ndarr[d1];}
p::object indexarray_2d(np::ndarray ndarr, np::ndarray d1,np::ndarray d2) { return ndarr[p::make_tuple(d1,d2)];}
p::object indexslice(np::ndarray ndarr, np::ndarray d1, p::slice sl) { return ndarr[p::make_tuple(d1, sl)];}
BOOST_PYTHON_MODULE(indexing_mod)
{
np::initialize();
p::def("single", single);
p::def("slice", slice);
p::def("indexarray", indexarray);
p::def("indexarray", indexarray_2d);
p::def("indexslice", indexslice);
}

79
test/numpy/ndarray.py Normal file
View File

@@ -0,0 +1,79 @@
#!/usr/bin/env python
# Copyright Jim Bosch & Ankit Daftery 2010-2012.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
import ndarray_mod
import unittest
import numpy
class TestNdarray(unittest.TestCase):
def testNdzeros(self):
for dtp in (numpy.int16, numpy.int32, numpy.float32, numpy.complex128):
v = numpy.zeros(60, dtype=dtp)
dt = numpy.dtype(dtp)
for shape in ((60,),(6,10),(4,3,5),(2,2,3,5)):
a1 = ndarray_mod.zeros(shape,dt)
a2 = v.reshape(a1.shape)
self.assertEqual(shape,a1.shape)
self.assert_((a1 == a2).all())
def testNdzeros_matrix(self):
for dtp in (numpy.int16, numpy.int32, numpy.float32, numpy.complex128):
dt = numpy.dtype(dtp)
shape = (6, 10)
a1 = ndarray_mod.zeros_matrix(shape, dt)
a2 = numpy.matrix(numpy.zeros(shape, dtype=dtp))
self.assertEqual(shape,a1.shape)
self.assert_((a1 == a2).all())
self.assertEqual(type(a1), type(a2))
def testNdarray(self):
a = range(0,60)
for dtp in (numpy.int16, numpy.int32, numpy.float32, numpy.complex128):
v = numpy.array(a, dtype=dtp)
dt = numpy.dtype(dtp)
a1 = ndarray_mod.array(a)
a2 = ndarray_mod.array(a,dt)
self.assert_((a1 == v).all())
self.assert_((a2 == v).all())
for shape in ((60,),(6,10),(4,3,5),(2,2,3,5)):
a1 = a1.reshape(shape)
self.assertEqual(shape,a1.shape)
a2 = a2.reshape(shape)
self.assertEqual(shape,a2.shape)
def testNdempty(self):
for dtp in (numpy.int16, numpy.int32, numpy.float32, numpy.complex128):
dt = numpy.dtype(dtp)
for shape in ((60,),(6,10),(4,3,5),(2,2,3,5)):
a1 = ndarray_mod.empty(shape,dt)
a2 = ndarray_mod.c_empty(shape,dt)
self.assertEqual(shape,a1.shape)
self.assertEqual(shape,a2.shape)
def testTranspose(self):
for dtp in (numpy.int16, numpy.int32, numpy.float32, numpy.complex128):
dt = numpy.dtype(dtp)
for shape in ((6,10),(4,3,5),(2,2,3,5)):
a1 = numpy.empty(shape,dt)
a2 = a1.transpose()
a1 = ndarray_mod.transpose(a1)
self.assertEqual(a1.shape,a2.shape)
def testSqueeze(self):
a1 = numpy.array([[[3,4,5]]])
a2 = a1.squeeze()
a1 = ndarray_mod.squeeze(a1)
self.assertEqual(a1.shape,a2.shape)
def testReshape(self):
a1 = numpy.empty((2,2))
a2 = ndarray_mod.reshape(a1,(1,4))
self.assertEqual(a2.shape,(1,4))
if __name__=="__main__":
unittest.main()

View File

@@ -0,0 +1,45 @@
// Copyright Jim Bosch & Ankit Daftery 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/numpy.hpp>
namespace p = boost::python;
namespace np = boost::numpy;
np::ndarray zeros(p::tuple shape, np::dtype dt) { return np::zeros(shape, dt);}
np::ndarray array2(p::object obj, np::dtype dt) { return np::array(obj,dt);}
np::ndarray array1(p::object obj) { return np::array(obj);}
np::ndarray empty1(p::tuple shape, np::dtype dt) { return np::empty(shape,dt);}
np::ndarray c_empty(p::tuple shape, np::dtype dt)
{
// convert 'shape' to a C array so we can test the corresponding
// version of the constructor
unsigned len = p::len(shape);
Py_intptr_t *c_shape = new Py_intptr_t[len];
for (unsigned i = 0; i != len; ++i)
c_shape[i] = p::extract<Py_intptr_t>(shape[i]);
np::ndarray result = np::empty(len, c_shape, dt);
delete [] c_shape;
return result;
}
np::ndarray transpose(np::ndarray arr) { return arr.transpose();}
np::ndarray squeeze(np::ndarray arr) { return arr.squeeze();}
np::ndarray reshape(np::ndarray arr,p::tuple tup) { return arr.reshape(tup);}
BOOST_PYTHON_MODULE(ndarray_mod)
{
np::initialize();
p::def("zeros", zeros);
p::def("zeros_matrix", zeros, np::as_matrix<>());
p::def("array", array2);
p::def("array", array1);
p::def("empty", empty1);
p::def("c_empty", c_empty);
p::def("transpose", transpose);
p::def("squeeze", squeeze);
p::def("reshape", reshape);
}

21
test/numpy/shapes.py Normal file
View File

@@ -0,0 +1,21 @@
#!/usr/bin/env python
# Copyright Jim Bosch & Ankit Daftery 2010-2012.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
import shapes_mod
import unittest
import numpy
class TestShapes(unittest.TestCase):
def testShapes(self):
a1 = numpy.array([(0,1),(2,3)])
a1_shape = (1,4)
a1 = shapes_mod.reshape(a1,a1_shape)
self.assertEqual(a1_shape,a1.shape)
if __name__=="__main__":
unittest.main()

21
test/numpy/shapes_mod.cpp Normal file
View File

@@ -0,0 +1,21 @@
// Copyright Jim Bosch & Ankit Daftery 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/numpy.hpp>
namespace p = boost::python;
namespace np = boost::numpy;
np::ndarray reshape(np::ndarray old_array, p::tuple shape)
{
np::ndarray local_shape = old_array.reshape(shape);
return local_shape;
}
BOOST_PYTHON_MODULE(shapes_mod)
{
np::initialize();
p::def("reshape", reshape);
}

28
test/numpy/templates.py Executable file
View File

@@ -0,0 +1,28 @@
#!/usr/bin/env python
# Copyright Jim Bosch & Ankit Daftery 2010-2012.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
import templates_mod
import unittest
import numpy
class TestTemplates(unittest.TestCase):
def testTemplates(self):
for dtype in (numpy.int16, numpy.int32, numpy.float32, numpy.complex128):
v = numpy.arange(12, dtype=dtype)
for shape in ((12,), (4, 3), (2, 6)):
a1 = numpy.zeros(shape, dtype=dtype)
a2 = v.reshape(a1.shape)
templates_mod.fill(a1)
self.assert_((a1 == a2).all())
a1 = numpy.zeros((12,), dtype=numpy.float64)
self.assertRaises(TypeError, templates_mod.fill, a1)
a1 = numpy.zeros((12,2,3), dtype=numpy.float32)
self.assertRaises(TypeError, templates_mod.fill, a1)
if __name__=="__main__":
unittest.main()

View File

@@ -0,0 +1,62 @@
// Copyright Jim Bosch & Ankit Daftery 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/numpy.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/vector_c.hpp>
namespace p = boost::python;
namespace np = boost::numpy;
struct ArrayFiller
{
typedef boost::mpl::vector< short, int, float, std::complex<double> > TypeSequence;
typedef boost::mpl::vector_c< int, 1, 2 > DimSequence;
explicit ArrayFiller(np::ndarray const & arg) : argument(arg) {}
template <typename T, int N>
void apply() const
{
if (N == 1)
{
char * p = argument.get_data();
int stride = argument.strides(0);
int size = argument.shape(0);
for (int n = 0; n != size; ++n, p += stride)
*reinterpret_cast<T*>(p) = static_cast<T>(n);
}
else
{
char * row_p = argument.get_data();
int row_stride = argument.strides(0);
int col_stride = argument.strides(1);
int rows = argument.shape(0);
int cols = argument.shape(1);
int i = 0;
for (int n = 0; n != rows; ++n, row_p += row_stride)
{
char * col_p = row_p;
for (int m = 0; m != cols; ++i, ++m, col_p += col_stride)
*reinterpret_cast<T*>(col_p) = static_cast<T>(i);
}
}
}
np::ndarray argument;
};
void fill(np::ndarray const & arg)
{
ArrayFiller filler(arg);
np::invoke_matching_array<ArrayFiller::TypeSequence, ArrayFiller::DimSequence >(arg, filler);
}
BOOST_PYTHON_MODULE(templates_mod)
{
np::initialize();
p::def("fill", fill);
}

57
test/numpy/ufunc.py Executable file
View File

@@ -0,0 +1,57 @@
#!/usr/bin/env python
# Copyright Jim Bosch & Ankit Daftery 2010-2012.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
import ufunc_mod
import unittest
import numpy
from numpy.testing.utils import assert_array_almost_equal
class TestUnary(unittest.TestCase):
def testScalar(self):
f = ufunc_mod.UnaryCallable()
assert_array_almost_equal(f(1.0), 2.0)
assert_array_almost_equal(f(3.0), 6.0)
def testArray(self):
f = ufunc_mod.UnaryCallable()
a = numpy.arange(5, dtype=float)
b = f(a)
assert_array_almost_equal(b, a*2.0)
c = numpy.zeros(5, dtype=float)
d = f(a,output=c)
self.assert_(c is d)
assert_array_almost_equal(d, a*2.0)
def testList(self):
f = ufunc_mod.UnaryCallable()
a = range(5)
b = f(a)
assert_array_almost_equal(b/2.0, a)
class TestBinary(unittest.TestCase):
def testScalar(self):
f = ufunc_mod.BinaryCallable()
assert_array_almost_equal(f(1.0, 3.0), 11.0)
assert_array_almost_equal(f(3.0, 2.0), 12.0)
def testArray(self):
f = ufunc_mod.BinaryCallable()
a = numpy.random.randn(5)
b = numpy.random.randn(5)
assert_array_almost_equal(f(a,b), (a*2+b*3))
c = numpy.zeros(5, dtype=float)
d = f(a,b,output=c)
self.assert_(c is d)
assert_array_almost_equal(d, a*2 + b*3)
assert_array_almost_equal(f(a, 2.0), a*2 + 6.0)
assert_array_almost_equal(f(1.0, b), 2.0 + b*3)
if __name__=="__main__":
unittest.main()

35
test/numpy/ufunc_mod.cpp Normal file
View File

@@ -0,0 +1,35 @@
// Copyright Jim Bosch & Ankit Daftery 2010-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/numpy.hpp>
namespace p = boost::python;
namespace np = boost::numpy;
struct UnaryCallable
{
typedef double argument_type;
typedef double result_type;
double operator()(double r) const { return r * 2;}
};
struct BinaryCallable
{
typedef double first_argument_type;
typedef double second_argument_type;
typedef double result_type;
double operator()(double a, double b) const { return a * 2 + b * 3;}
};
BOOST_PYTHON_MODULE(ufunc_mod)
{
np::initialize();
p::class_<UnaryCallable>("UnaryCallable")
.def("__call__", np::unary_ufunc<UnaryCallable>::make());
p::class_< BinaryCallable>("BinaryCallable")
.def("__call__", np::binary_ufunc<BinaryCallable>::make());
}