[instant] 03/05: New upstream version 2016.2.0
Johannes Ring
johannr-guest at moszumanska.debian.org
Thu Dec 1 13:06:31 UTC 2016
This is an automated email from the git hooks/post-receive script.
johannr-guest pushed a commit to branch master
in repository instant.
commit 2726e1535ac3a3d132e36806792f7e99fb8ddc5c
Author: Johannes Ring <johannr at simula.no>
Date: Thu Dec 1 13:53:07 2016 +0100
New upstream version 2016.2.0
---
.bzrignore | 2 -
.gitignore | 2 -
ChangeLog | 5 +
README | 53 ------
README.rst | 64 ++++++++
doc/sphinx/README | 9 +-
doc/sphinx/generate-apidoc | 29 ----
doc/sphinx/source/api-doc/instant.rst | 86 ----------
doc/sphinx/source/api-doc/modules.rst | 7 -
doc/sphinx/source/conf.py | 19 +++
doc/sphinx/source/index.rst | 21 ++-
doc/sphinx/source/installation.rst | 93 +++++++++++
doc/sphinx/source/manual.rst | 8 +
doc/sphinx/source/releases.rst | 5 +
doc/sphinx/source/releases/next.rst | 21 ++-
doc/sphinx/source/releases/v1.6.0.rst | 5 +-
doc/sphinx/source/releases/v2016.1.0.rst | 7 +
instant/__init__.py | 4 +-
instant/build.py | 109 +++++++------
instant/cache.py | 34 ++--
instant/codegeneration.py | 14 +-
instant/config.py | 56 ++++---
instant/inlining.py | 64 ++++----
instant/locking.py | 44 ++---
instant/output.py | 53 ++++--
instant/paths.py | 44 ++++-
instant/signatures.py | 3 +-
release.conf | 5 -
scripts/maketarball.sh | 22 ---
setup.py | 55 +++++--
test/dolfin_test.py | 38 -----
test/pytest.ini | 9 ++
test/rerun_tests.py | 17 +-
test/run_tests.py | 19 +--
test/test01.py | 8 +
test/test02.py | 34 ++++
test/test03.py | 20 +++
test/test04.py | 63 ++++++++
test/test05.py | 51 ++++++
test/test06.py | 55 +++++++
test/test07.py | 57 +++++++
test/test08.py | 42 +++++
test/test1.py | 11 --
test/test10.py | 155 +++++++++---------
test/test11.py | 43 ++---
test/test12.py | 56 +++----
test/test13.py | 11 --
test/test14.py | 9 --
test/test15.py | 41 ++---
test/test16.py | 92 +++++------
test/test17.py | 49 +++---
test/test18.py | 114 ++++++-------
test/test19.py | 267 ++++++++++++++++---------------
test/test2.py | 37 -----
test/test20.py | 23 ++-
test/test21.py | 3 -
test/test3.py | 21 ---
test/test4.py | 66 --------
test/test5.py | 56 -------
test/test6.py | 59 -------
test/test7.py | 76 ---------
test/test8.py | 42 -----
test/test_instant_system_calls.py | 19 +--
test/test_ode.py | 43 +++--
64 files changed, 1340 insertions(+), 1309 deletions(-)
diff --git a/.bzrignore b/.bzrignore
deleted file mode 100644
index 54f4cb8..0000000
--- a/.bzrignore
+++ /dev/null
@@ -1,2 +0,0 @@
-build
-tests/**/
diff --git a/.gitignore b/.gitignore
deleted file mode 100644
index 3a1f657..0000000
--- a/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-build/
-tests/**/
diff --git a/ChangeLog b/ChangeLog
index 6be39ce..0f6c46b 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,8 @@
+2016.2.0 [2016-11-30]
+ - Add Python version string to hash signature input
+ - Add pipelines testing, with py2 and py3 coverage
+ - Remove commands module (removed from Py3)
+ - Switch unit tests to pytest
2016.1.0 [2016-06-23]
- Minor fixes
1.6.0 [2015-07-28]
diff --git a/README b/README
deleted file mode 100644
index df81922..0000000
--- a/README
+++ /dev/null
@@ -1,53 +0,0 @@
-=======
-Instant
-=======
-
-Instant is a Python module that allows for instant inlining of C and
-C++ code in Python. It is a small Python module built on top of SWIG
-and Distutils. For more information, visit:
-
-https://bitbucket.org/fenics-project/instant
-
-
-Dependencies
-============
-
-Instant depends on Python 2.7 or later, SWIG, and NumPy
-
-
-Optional dependencies
-=====================
-
-To enable NFS safe file locking flufl.lock can be installed:
-
-https://gitlab.com/warsaw/flufl.lock
-
-
-Environment
-===========
-
-Instant's behaviour depened on following environment variables:
-
- - INSTANT_CACHE_DIR
- - INSTANT_ERROR_DIR
-
- These options can override placement of default cache and error
- directories in ~/.instant/cache and ~/.instant/error.
-
- - INSTANT_SYSTEM_CALL_METHOD
-
- Choose method for calling external programs (pkgconfig,
- swig, cmake, make). Available values:
-
- - 'SUBPROCESS'
-
- Uses pipes. Probably not OFED-fork safe. Default.
-
- - 'OS_SYSTEM'
-
- Uses temporary files. Probably OFED-fork safe.
-
- - 'COMMANDS'
-
- Uses pipes. Possibly OFED-fork safe on some machines.
- Does not work on Windows.
diff --git a/README.rst b/README.rst
new file mode 100644
index 0000000..8db5741
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,64 @@
+=======
+Instant
+=======
+
+Instant is a Python module that allows for instant inlining of C and
+C++ code in Python. It is a small Python module built on top of SWIG
+and Distutils.
+
+Instant is part of the FEniCS Project.
+
+For more information, visit http://www.fenicsproject.org.
+
+
+Documentation
+=============
+
+Documentation can be viewed at http://fenics-instant.readthedocs.org/.
+
+.. image:: https://readthedocs.org/projects/fenics-instant/badge/?version=latest
+ :target: http://fenics.readthedocs.io/projects/instant/en/latest/?badge=latest
+ :alt: Documentation Status
+
+
+Automated Testing
+=================
+
+We use Bitbucket Pipelines and Atlassian Bamboo to perform automated
+testing.
+
+.. image:: https://bitbucket-badges.useast.atlassian.io/badge/fenics-project/instant.svg
+ :target: https://bitbucket.org/fenics-project/instant/addon/pipelines/home
+ :alt: Pipelines Build Status
+
+.. image:: http://fenics-bamboo.simula.no:8085/plugins/servlet/wittified/build-status/IN-ID
+ :target: http://fenics-bamboo.simula.no:8085/browse/IN-ID/latest
+ :alt: Bamboo Build Status
+
+
+Code Coverage
+=============
+
+Code coverage reports can be viewed at
+https://coveralls.io/repos/bitbucket/fenics-project/instant.
+
+.. image:: https://coveralls.io/repos/bitbucket/fenics-project/instant/badge.svg?branch=master
+ :target: https://coveralls.io/bitbucket/fenics-project/instant?branch=master
+ :alt: Coverage Status
+
+
+License
+=======
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
diff --git a/doc/sphinx/README b/doc/sphinx/README
index 0859d21..0398b18 100644
--- a/doc/sphinx/README
+++ b/doc/sphinx/README
@@ -2,10 +2,11 @@
Sphinx documentation
====================
-Instant is documented using Sphinx and reStructured text. The
-documnentation is hosted at
-http://fenics-instant.readthedocs.org/. The online documentation is
-automatically updated upon pushes to the Instant master branch.
+Instant is documented using Sphinx and reStructured text.
+The documentation is hosted at http://fenics-instant.readthedocs.org/.
+
+The online documentation is automatically updated upon pushes to the
+Instant master branch.
Updating the API documentation
diff --git a/doc/sphinx/generate-apidoc b/doc/sphinx/generate-apidoc
deleted file mode 100755
index a2c12ee..0000000
--- a/doc/sphinx/generate-apidoc
+++ /dev/null
@@ -1,29 +0,0 @@
-# Copyright (C) 2015 Garth N. Wells
-#
-# This file is part of UFL.
-#
-# UFL is free software: you can redistribute it and/or modify
-# it under the terms of the GNU Lesser General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# UFL is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public License
-# along with UFL. If not, see <http://www.gnu.org/licenses/>.
-
-# This script calls sphinx-apidoc to generate files ready for autodoc
-
-echo ""
-echo "--- Generating Instant autodoc RST files"
-echo ""
-
-# Get location of Sphinx files
-SPHINX_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
-SPHINX_SOURCE_DIR=$SPHINX_DIR/source
-
-# Generate .rst files ready for autodoc
-sphinx-apidoc -f -d 1 -o $SPHINX_SOURCE_DIR/api-doc $SPHINX_DIR/../../instant
diff --git a/doc/sphinx/source/api-doc/instant.rst b/doc/sphinx/source/api-doc/instant.rst
deleted file mode 100644
index 4fcb5b9..0000000
--- a/doc/sphinx/source/api-doc/instant.rst
+++ /dev/null
@@ -1,86 +0,0 @@
-instant package
-===============
-
-Submodules
-----------
-
-instant.build module
---------------------
-
-.. automodule:: instant.build
- :members:
- :undoc-members:
- :show-inheritance:
-
-instant.cache module
---------------------
-
-.. automodule:: instant.cache
- :members:
- :undoc-members:
- :show-inheritance:
-
-instant.codegeneration module
------------------------------
-
-.. automodule:: instant.codegeneration
- :members:
- :undoc-members:
- :show-inheritance:
-
-instant.config module
----------------------
-
-.. automodule:: instant.config
- :members:
- :undoc-members:
- :show-inheritance:
-
-instant.inlining module
------------------------
-
-.. automodule:: instant.inlining
- :members:
- :undoc-members:
- :show-inheritance:
-
-instant.locking module
-----------------------
-
-.. automodule:: instant.locking
- :members:
- :undoc-members:
- :show-inheritance:
-
-instant.output module
----------------------
-
-.. automodule:: instant.output
- :members:
- :undoc-members:
- :show-inheritance:
-
-instant.paths module
---------------------
-
-.. automodule:: instant.paths
- :members:
- :undoc-members:
- :show-inheritance:
-
-instant.signatures module
--------------------------
-
-.. automodule:: instant.signatures
- :members:
- :undoc-members:
- :show-inheritance:
-
-
-Module contents
----------------
-
-.. automodule:: instant
- :members:
- :undoc-members:
- :show-inheritance:
diff --git a/doc/sphinx/source/api-doc/modules.rst b/doc/sphinx/source/api-doc/modules.rst
deleted file mode 100644
index 9bb1943..0000000
--- a/doc/sphinx/source/api-doc/modules.rst
+++ /dev/null
@@ -1,7 +0,0 @@
-instant
-=======
-
-.. toctree::
- :maxdepth: 1
-
- instant
diff --git a/doc/sphinx/source/conf.py b/doc/sphinx/source/conf.py
index 3f0488d..c5bb1d4 100644
--- a/doc/sphinx/source/conf.py
+++ b/doc/sphinx/source/conf.py
@@ -269,3 +269,22 @@ texinfo_documents = [
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}
+
+
+def run_apidoc(_):
+ modules = ['instant']
+
+ # Get location of Sphinx files
+ sphinx_source_dir = os.path.abspath(os.path.dirname(__file__))
+ repo_dir = os.path.abspath(os.path.join(sphinx_source_dir, os.path.pardir,
+ os.path.pardir, os.path.pardir))
+ apidoc_dir = os.path.join(sphinx_source_dir, "api-doc")
+
+ from sphinx.apidoc import main
+ for module in modules:
+ # Generate .rst files ready for autodoc
+ module_dir = os.path.join(repo_dir, module)
+ main(["-f", "-d", "1", "-o", apidoc_dir, module_dir])
+
+def setup(app):
+ app.connect('builder-inited', run_apidoc)
diff --git a/doc/sphinx/source/index.rst b/doc/sphinx/source/index.rst
index 26a705d..e936ea6 100644
--- a/doc/sphinx/source/index.rst
+++ b/doc/sphinx/source/index.rst
@@ -1,25 +1,32 @@
+.. title:: Instant
+
+=======
Instant
=======
Instant is a Python module that allows for instant inlining of C and
C++ code in Python. It is a small Python module built on top of SWIG
-and distutils. It is part of the FEniCS Project
-(http://fenicsproject.org).
+and Distutils.
-Instant development takes place on Bitbucket at
-https://bitbucket.org/fenics-project/instant.
+Instant is part of the FEniCS Project.
+
+For more information, visit http://www.fenicsproject.org.
Documentation
--------------
+=============
.. toctree::
:titlesonly:
+ :maxdepth: 1
- api-doc/instant
+ installation
+ manual
+ API reference <api-doc/instant>
releases
+[FIXME: These links don't belong here, should go under API reference somehow.]
+
* :ref:`genindex`
* :ref:`modindex`
-* :ref:`search`
diff --git a/doc/sphinx/source/installation.rst b/doc/sphinx/source/installation.rst
new file mode 100644
index 0000000..e29aa20
--- /dev/null
+++ b/doc/sphinx/source/installation.rst
@@ -0,0 +1,93 @@
+.. title:: Installation
+
+
+============
+Installation
+============
+
+Instant is normally installed as part of an installation of FEniCS.
+If you are using Instant as part of the FEniCS software suite, it
+is recommended that you follow the
+`installation instructions for FEniCS
+<https://fenics.readthedocs.io/en/latest/>`__.
+
+To install Instant itself, read on below for a list of requirements
+and installation instructions.
+
+
+Requirements and dependencies
+=============================
+
+Instant requires Python version 2.7 or later and depends on the
+following Python packages:
+
+* NumPy
+* SWIG
+
+These packages will be automatically installed as part of the
+installation of Instant, if not already present on your system.
+
+If running on a cluster with Infiniband with python 2,
+you also need to install a backport of the subprocess
+module from python 3 to get safe fork behaviour:
+
+* subprocess32
+
+In addition, Instant optionally depends on flufl.lock for NFS safe
+file locking flufl.lock can be installed
+
+* flufl.lock (https://gitlab.com/warsaw/flufl.lock)
+
+
+Installation instructions
+=========================
+
+To install Instant, download the source code from the
+`Instant Bitbucket repository
+<https://bitbucket.org/fenics-project/instant>`__,
+and run the following command:
+
+.. code-block:: console
+
+ pip install .
+
+To install to a specific location, add the ``--prefix`` flag
+to the installation command:
+
+.. code-block:: console
+
+ pip install --prefix=<some directory> .
+
+
+Environment
+===========
+
+Instant's behaviour depened on following environment variables:
+
+ - ``INSTANT_CACHE_DIR``
+ - ``INSTANT_ERROR_DIR``
+
+ These options can override placement of default cache and error
+ directories. The default directories are placed below the prefix
+ of the currently active virtualenv or conda environment, in
+ ``.cache/instant/cache`` and ``.cache/instant/error``.
+ If no such environment is active, the default directories are
+ ``~/.cache/instant/pythonM.N/cache`` and ``.cache/instant/pythonM.N/error``.
+
+ - ``INSTANT_SYSTEM_CALL_METHOD``
+
+ Choose method for calling external programs (pkgconfig,
+ swig, cmake, make). Available values:
+
+ - ``SUBPROCESS``
+
+ Uses pipes. Not OFED-fork safe on Python 2 unless
+ subprocess32 has been installed. Default.
+
+ - ``OS_SYSTEM``
+
+ Uses temporary files. Probably OFED-fork safe.
+
+.. warning:: OFED-fork safe system call method might be required to
+ avoid crashes on OFED-based (InfiniBand) clusters!
+ If using python 2, installing subprocess32 is recommended.
diff --git a/doc/sphinx/source/manual.rst b/doc/sphinx/source/manual.rst
new file mode 100644
index 0000000..95f7078
--- /dev/null
+++ b/doc/sphinx/source/manual.rst
@@ -0,0 +1,8 @@
+.. title:: User manual
+
+
+===========
+User manual
+===========
+
+.. note:: This page is work in progress.
diff --git a/doc/sphinx/source/releases.rst b/doc/sphinx/source/releases.rst
index 57717e7..796ed29 100644
--- a/doc/sphinx/source/releases.rst
+++ b/doc/sphinx/source/releases.rst
@@ -1,3 +1,7 @@
+.. title:: Release notes
+
+
+=============
Release notes
=============
@@ -5,4 +9,5 @@ Release notes
:maxdepth: 2
releases/next
+ releases/v2016.1.0
releases/v1.6.0
diff --git a/doc/sphinx/source/releases/next.rst b/doc/sphinx/source/releases/next.rst
index 7287586..1bfdf0e 100644
--- a/doc/sphinx/source/releases/next.rst
+++ b/doc/sphinx/source/releases/next.rst
@@ -1,2 +1,19 @@
-Changes in the next release of Instant
-======================================
+===========================
+Changes in the next release
+===========================
+
+
+Summary of changes
+==================
+
+.. note:: Developers should use this page to track and list changes
+ during development. At the time of release, this page should
+ be published (and renamed) to list the most important
+ changes in the new release.
+
+
+Detailed changes
+================
+
+.. note:: At the time of release, make a verbatim copy of the
+ ChangeLog here (and remove this note).
diff --git a/doc/sphinx/source/releases/v1.6.0.rst b/doc/sphinx/source/releases/v1.6.0.rst
index 13aab14..d3603b0 100644
--- a/doc/sphinx/source/releases/v1.6.0.rst
+++ b/doc/sphinx/source/releases/v1.6.0.rst
@@ -1,6 +1,7 @@
-Changes in Instant 1.6.0
+========================
+Changes in version 1.6.0
========================
-Instant 1.6.0 was released on 2015-07-28
+Instant 1.6.0 was released on 2015-07-28.
- Minor bug fixes
diff --git a/doc/sphinx/source/releases/v2016.1.0.rst b/doc/sphinx/source/releases/v2016.1.0.rst
new file mode 100644
index 0000000..208e09a
--- /dev/null
+++ b/doc/sphinx/source/releases/v2016.1.0.rst
@@ -0,0 +1,7 @@
+===========================
+Changes in version 2016.1.0
+===========================
+
+Instant 2016.1.0 was released on 2016-06-23.
+
+- Minor fixes
diff --git a/instant/__init__.py b/instant/__init__.py
index 8872161..1a5ca2f 100644
--- a/instant/__init__.py
+++ b/instant/__init__.py
@@ -17,8 +17,8 @@ Questions, bugs and patches should be sent to fenics-dev at googlegroups.com.
"""
__authors__ = "Magne Westlie, Kent-Andre Mardal <kent-and at simula.no>, Martin Alnes <martinal at simula.no>, Ilmar M. Wilbers <ilmarw at simula.no>"
-__date__ = "2016-06-23"
-__version__ = "2016.1.0"
+__date__ = "2016-11-30"
+__version__ = "2016.2.0"
# TODO: Import only the official interface
from .output import *
diff --git a/instant/build.py b/instant/build.py
index 5e5478f..3bfdc9d 100644
--- a/instant/build.py
+++ b/instant/build.py
@@ -33,29 +33,31 @@ from .cache import *
from .codegeneration import *
from .locking import file_lock
+
def assert_is_str(x):
- instant_assert(isinstance(x, str),
- "In instant.build_module: Expecting string.")
+ instant_assert(isinstance(x, str), "In instant.build_module: Expecting string.")
+
def assert_is_bool(x):
- instant_assert(isinstance(x, bool),
- "In instant.build_module: Expecting bool.")
+ instant_assert(isinstance(x, bool), "In instant.build_module: Expecting bool.")
+
def assert_is_str_list(x):
- instant_assert(isinstance(x, (list, tuple)),
- "In instant.build_module: Expecting sequence.")
- instant_assert(all(isinstance(i, str) for i in x),
- "In instant.build_module: Expecting sequence of strings.")
+ instant_assert(isinstance(x, (list, tuple)), "In instant.build_module: Expecting sequence.")
+ instant_assert(all(isinstance(i, str) for i in x), "In instant.build_module: Expecting sequence of strings.")
+
def strip_strings(x):
assert_is_str_list(x)
return [s.strip() for s in x]
+
def arg_strings(x):
if isinstance(x, str):
x = x.split()
return strip_strings(x)
+
def makedirs(path):
"""
Creates a directory (tree). If directory already excists it does nothing.
@@ -66,9 +68,13 @@ def makedirs(path):
if e.errno != errno.EEXIST:
raise
+
def copy_files(source, dest, files):
- """Copy a list of files from a source directory to a destination directory.
- This may seem a bit complicated, but a lot of this code is error checking."""
+ """Copy a list of files from a source directory to a destination
+ directory. This may seem a bit complicated, but a lot of this
+ code is error checking.
+
+ """
if os.path.exists(dest):
overwriting = set(files) & set(glob.glob(os.path.join(dest, "*")))
if overwriting:
@@ -120,11 +126,12 @@ def recompile(modulename, module_path, new_compilation_checksum,
compile_log_contents = None
instant_info("--- Instant: compiling ---")
- # TODO: The three blocks below can be made a function and three calls
-
+ # TODO: The three blocks below can be made a function and
+ # three calls
if build_system == "distutils":
# Build extension module with distutils
- cmd = "python setup.py build_ext install --install-platlib=."
+ python_interp = sys.executable
+ cmd = python_interp + " setup.py build_ext install --install-platlib=."
instant_debug("cmd = %s" % cmd)
ret, output = get_status_output(cmd)
compile_log_file.write(output)
@@ -135,7 +142,6 @@ def recompile(modulename, module_path, new_compilation_checksum,
os.remove(compilation_checksum_filename)
msg = "In instant.recompile: The module did not compile with command '%s', see '%s'"
instant_error(msg % (cmd, compile_log_filename_dest))
-
else:
# Build makefile for extension module with cmake
cmd = "cmake -DDEBUG=TRUE .";
@@ -176,13 +182,15 @@ def recompile(modulename, module_path, new_compilation_checksum,
# Copy module to error dir
module_path = copy_to_cache(module_path, get_default_error_dir(),
- modulename, check_for_existing_path=False)
+ modulename,
+ check_for_existing_path=False)
- # Compilation succeeded, write new_compilation_checksum to checksum_file
+ # Compilation succeeded, write new_compilation_checksum to
+ # checksum_file
write_file(compilation_checksum_filename, new_compilation_checksum)
-def copy_to_cache(module_path, cache_dir, modulename, \
+def copy_to_cache(module_path, cache_dir, modulename,
check_for_existing_path=True):
"Copy module directory to cache."
# Get lock, check if the module exists, _otherwise_ copy the
@@ -194,7 +202,8 @@ def copy_to_cache(module_path, cache_dir, modulename, \
cache_module_path = os.path.join(cache_dir, modulename)
if check_for_existing_path and os.path.exists(os.path.join(\
cache_module_path, "finished_copying")):
- # This indicates a race condition has happened (and is being avoided!).
+ # This indicates a race condition has happened (and is
+ # being avoided!).
instant_warning("In instant.build_module: Path '%s' already exists,"\
" but module wasn't found in cache previously. Not overwriting,"\
" assuming this module is valid." % cache_module_path)
@@ -213,11 +222,12 @@ def copy_to_cache(module_path, cache_dir, modulename, \
instant_debug("In instant.build_module: Copying built module from %r"\
" to cache at %r" % (module_path, cache_module_path))
- # Do the copying and mark that we are finished by creating an empty file
- # finished_copying
+ # Do the copying and mark that we are finished by creating an
+ # empty file finished_copying
try:
shutil.copytree(module_path, cache_module_path)
- open(os.path.join(cache_module_path, "finished_copying"), "w").close()
+ open(os.path.join(cache_module_path,
+ "finished_copying"), "w").close()
except OSError as e:
if e.errno != errno.EEXIST:
raise
@@ -226,6 +236,7 @@ def copy_to_cache(module_path, cache_dir, modulename, \
return cache_module_path
+
def build_module(modulename=None, source_directory=".",
code="", init_code="",
additional_definitions="", additional_declarations="",
@@ -373,12 +384,12 @@ def build_module(modulename=None, source_directory=".",
assert_is_bool(generate_interface)
assert_is_bool(generate_setup)
cmake_packages = strip_strings(cmake_packages)
- instant_assert( signature is None \
+
+ instant_assert(signature is None \
or isinstance(signature, str) \
- or hasattr(signature, "signature"),
- "In instant.build_module: Expecting modulename to be string or None.")
- instant_assert(not (signature is not None and modulename is not None),
- "In instant.build_module: Can't have both modulename and signature.")
+ or hasattr(signature, "signature"), "In instant.build_module: Expecting modulename to be string or None.")
+
+ instant_assert(not (signature is not None and modulename is not None), "In instant.build_module: Can't have both modulename and signature.")
# --- Replace arguments with defaults if necessary
@@ -387,8 +398,7 @@ def build_module(modulename=None, source_directory=".",
# Split sources by file-suffix (.c or .cpp)
csrcs = [f for f in sources if f.endswith('.c') or f.endswith('.C')]
cppsrcs = [f for f in sources if f.endswith('.cpp') or f.endswith('.cxx')]
- instant_assert(len(csrcs) + len(cppsrcs) == len(sources),
- "In instant.build_module: Source files must have '.c' or '.cpp' suffix")
+ instant_assert(len(csrcs) + len(cppsrcs) == len(sources), "In instant.build_module: Source files must have '.c' or '.cpp' suffix")
# --- Debugging code
instant_debug('In instant.build_module:')
@@ -432,7 +442,8 @@ def build_module(modulename=None, source_directory=".",
# including everything that affects the interface
# file generation and module compilation.
checksum_args = ( \
- # We don't care about the modulename, that's what we're trying to construct!
+ # We don't care about the modulename, that's what
+ # we're trying to construct!
#modulename,
# We don't care where the user code resides:
#source_directory,
@@ -447,9 +458,11 @@ def build_module(modulename=None, source_directory=".",
swig_include_dirs, swigargs, cppargs, lddargs,
object_files, arrays,
generate_interface, generate_setup, cmake_packages,
- # The signature isn't defined, and the cache_dir doesn't affect the module:
+ # The signature isn't defined, and the cache_dir
+ # doesn't affect the module:
#signature, cache_dir)
- )
+ sys.version
+ )
allfiles = sources + wrap_headers + local_headers
allfiles = [os.path.join(source_directory, f) for f in allfiles]
text = "\n".join((str(a) for a in checksum_args))
@@ -467,8 +480,7 @@ def build_module(modulename=None, source_directory=".",
# Make a temporary module path for compilation
module_path = os.path.join(get_temp_dir(), modulename)
- instant_assert(not os.path.exists(module_path),
- "In instant.build_module: Not expecting module_path to exist: '%s'"\
+ instant_assert(not os.path.exists(module_path), "In instant.build_module: Not expecting module_path to exist: '%s'"\
% module_path)
makedirs(module_path)
use_cache = True
@@ -494,7 +506,7 @@ def build_module(modulename=None, source_directory=".",
module_path = os.path.abspath(module_path)
files_to_copy = sources + wrap_headers + local_headers + object_files
copy_files(source_directory, module_path, files_to_copy)
- # At this point, all user input files should reside in module_path.
+ # At this point, all user input files should reside in module_path
# --- Generate additional files in module directory
os.chdir(module_path)
@@ -507,28 +519,30 @@ def build_module(modulename=None, source_directory=".",
ifile_name = "%s.i" % modulename
if generate_interface:
write_interfacefile(ifile_name, modulename, code, init_code,
- additional_definitions, additional_declarations, system_headers,
- local_headers, wrap_headers, arrays)
+ additional_definitions,
+ additional_declarations, system_headers,
+ local_headers, wrap_headers, arrays)
# Generate setup.py if wanted
if generate_setup and not cmake_packages:
setup_name = "setup.py"
- write_setup(setup_name, modulename, csrcs, cppsrcs, local_headers, \
- include_dirs, library_dirs, libraries, swig_include_dirs, \
- swigargs, cppargs, lddargs)
+ write_setup(setup_name, modulename, csrcs, cppsrcs, local_headers,
+ include_dirs, library_dirs, libraries,
+ swig_include_dirs, swigargs, cppargs, lddargs)
build_system = "distutils"
else:
- write_cmakefile(modulename, cmake_packages, csrcs, cppsrcs, local_headers, \
- include_dirs, library_dirs, libraries, swig_include_dirs, \
- swigargs, cppargs, lddargs)
+ write_cmakefile(modulename, cmake_packages, csrcs, cppsrcs,
+ local_headers, include_dirs, library_dirs,
+ libraries, swig_include_dirs, swigargs, cppargs,
+ lddargs)
build_system = "cmake"
# --- Build module
- # At this point we have all the files, and can make the
- # total checksum from all file contents. This is used to
- # decide whether the module needs recompilation or not.
+ # At this point we have all the files, and can make the total
+ # checksum from all file contents. This is used to decide
+ # whether the module needs recompilation or not.
# Compute new_compilation_checksum
# Collect arguments used for checksum creation,
@@ -560,7 +574,8 @@ def build_module(modulename=None, source_directory=".",
new_compilation_checksum = compute_checksum(text, allfiles)
# Recompile if necessary
- recompile(modulename, module_path, new_compilation_checksum, build_system)
+ recompile(modulename, module_path, new_compilation_checksum,
+ build_system)
# --- Load, cache, and return module
@@ -596,7 +611,6 @@ def build_module_vtk(c_code, cache_dir=None):
moduleids = [signature]
module_path = os.path.join(get_temp_dir(), modulename)
-
makedirs(module_path)
os.chdir(module_path)
@@ -615,6 +629,7 @@ def build_module_vtk(c_code, cache_dir=None):
return module
+
def build_module_vmtk(c_code, cache_dir=None):
original_path = os.getcwd()
cache_dir = validate_cache_dir(cache_dir)
diff --git a/instant/cache.py b/instant/cache.py
index 1b75a9c..424345d 100644
--- a/instant/cache.py
+++ b/instant/cache.py
@@ -35,7 +35,8 @@ from .output import instant_warning, instant_assert, instant_debug
from .paths import get_default_cache_dir, validate_cache_dir
from .signatures import compute_checksum
-# TODO: We could make this an argument, but it's used indirectly several places so take care.
+# TODO: We could make this an argument, but it's used indirectly
+# several places so take care.
_modulename_prefix = "instant_module_"
def modulename_from_checksum(checksum):
"Construct a module name from a checksum for use in cache."
@@ -67,24 +68,28 @@ def memory_cached_module(moduleid):
"Returns the cached module if found."
import sys
module = _memory_cache.get(moduleid, None)
- instant_debug("Found '%s' in memory cache with key '%r'." % (module, moduleid))
+ instant_debug("Found '%s' in memory cache with key '%r'." % (module,
+ moduleid))
return module
def place_module_in_memory_cache(moduleid, module):
"Place a compiled module in cache with given id."
_memory_cache[moduleid] = module
- instant_debug("Added module '%s' to cache with key '%r'." % (module, moduleid))
+ instant_debug("Added module '%s' to cache with key '%r'." % (module,
+ moduleid))
def is_valid_module_name(name):
NAMELENGTHLIMIT = 200
- return len(name) < NAMELENGTHLIMIT and bool(re.search(r"^[a-zA-Z_][\w]*$", name))
+ return len(name) < NAMELENGTHLIMIT and bool(re.search(r"^[a-zA-Z_][\w]*$",
+ name))
def import_and_cache_module(path, modulename, moduleids):
module, e = import_module_directly(path, modulename)
- instant_assert(module is not None, "Failed to import module found in cache. Modulename: '%s';\nPath: '%s';\n%s:%s;" % (modulename, path, type(e).__name__, e))
+ instant_assert(module is not None, "Failed to import module found in cache. Modulename: '%s';\nPath: '%s';\n%s:%s;" % (modulename, path, type(e).__name__,
+ e))
for moduleid in moduleids:
place_module_in_memory_cache(moduleid, module)
return module
@@ -95,7 +100,7 @@ def check_memory_cache(moduleid):
moduleids = [moduleid]
module = memory_cached_module(moduleid)
if module: return module, moduleids
-
+
# Get signature from moduleid if it isn't a string,
# and check memory cache again
if hasattr(moduleid, "signature"):
@@ -104,15 +109,15 @@ def check_memory_cache(moduleid):
"'%s' from moduleid.signature()." % moduleid)
module = memory_cached_module(moduleid)
if module:
- # FIXME (GNW): I haved commented this out since it can continually
+ # FIXME (GNW): I haved commented this out since it can continually
# insert indentical objects into the cache. This
- # function checks the cache, so why should it also
+ # function checks the cache, so why should it also
# insert?
#for moduleid in moduleids:
# place_module_in_memory_cache(moduleid, module)
return module, moduleids
moduleids.append(moduleid)
-
+
# Construct a filename from the checksum of moduleid if it
# isn't already a valid name, and check memory cache again
if not is_valid_module_name(moduleid):
@@ -122,7 +127,7 @@ def check_memory_cache(moduleid):
module = memory_cached_module(moduleid)
if module: return module, moduleids
moduleids.append(moduleid)
-
+
instant_debug("In instant.check_memory_cache: Failed to find module: %s." % moduleid)
return None, moduleids
@@ -130,7 +135,7 @@ def check_memory_cache(moduleid):
def check_disk_cache(modulename, cache_dir, moduleids):
# Ensure a valid cache_dir
cache_dir = validate_cache_dir(cache_dir)
-
+
# Check on disk, in current directory and cache directory
for path in (os.getcwd(), cache_dir):
if os.path.exists(os.path.join(path, modulename, "finished_copying")):
@@ -144,7 +149,7 @@ def check_disk_cache(modulename, cache_dir, moduleids):
else:
instant_debug("In instant.check_disk_cache: Failed to import "\
"module '%s' from '%s'." % (modulename, path))
-
+
# All attempts failed
instant_debug("In instant.check_disk_cache: Can't import module with modulename "\
"%r using cache directory %r." % (modulename, cache_dir))
@@ -153,7 +158,7 @@ def check_disk_cache(modulename, cache_dir, moduleids):
def import_module(moduleid, cache_dir=None):
"""Import module from cache given its moduleid and an optional cache directory.
-
+
The moduleid can be either
- the module name
- a signature string, of which a checksum is taken to look up in the cache
@@ -165,7 +170,7 @@ def import_module(moduleid, cache_dir=None):
# Look for module in memory cache
module, moduleids = check_memory_cache(moduleid)
if module: return module
-
+
# Look for module in disk cache
modulename = moduleids[-1]
return check_disk_cache(modulename, cache_dir, moduleids)
@@ -175,4 +180,3 @@ def cached_modules(cache_dir=None):
"Return a list with the names of all cached modules."
cache_dir = validate_cache_dir(cache_dir)
return os.listdir(cache_dir)
-
diff --git a/instant/codegeneration.py b/instant/codegeneration.py
index da8ca26..d780d7c 100644
--- a/instant/codegeneration.py
+++ b/instant/codegeneration.py
@@ -99,7 +99,8 @@ def write_interfacefile(filename, modulename, code, init_code,
if 'in' in a:
# input arrays
a.remove('in')
- instant_assert(len(a) > 1 and len(a) < 5, "Wrong number of elements in input array")
+ instant_assert(len(a) > 1 and len(a) < 5,
+ "Wrong number of elements in input array")
if len(a) == 2:
# 1-dimensional arrays, i.e. vectors
typemaps += reindent("""
@@ -125,7 +126,8 @@ def write_interfacefile(filename, modulename, code, init_code,
""" % { 'n1' : a[0], 'array' : a[1], 'dtype' : DATA_TYPE })
else:
# in-place arrays
- instant_assert(len(a) > 1 and len(a) < 5, "Wrong number of elements in output array")
+ instant_assert(len(a) > 1 and len(a) < 5,
+ "Wrong number of elements in output array")
if 'multi' in a:
# n-dimensional arrays, i.e. tensors > 3-dimensional
a.remove('multi')
@@ -380,6 +382,7 @@ ENDIF(%(package)s_FOUND)
cmake_form["extra_libraries"] = ";".join(libraries)
cmake_form["extra_include_dirs"] = ";".join(include_dirs)
+ cmake_form["extra_library_dirs"] = ";".join(library_dirs)
cmake_form["extra_swig_include_dirs"] = " -I".join([" "] + swig_include_dirs)
cmake_form["extra_swigargs"] = " ".join(swigargs)
@@ -494,6 +497,11 @@ endif()
%(package_flags)s
+set(EXTRA_LIBRARY_DIRS \"%(extra_library_dirs)s\")
+if(EXTRA_LIBRARY_DIRS)
+ link_directories(${EXTRA_LIBRARY_DIRS})
+endif()
+
%(extra_sources_files)s
%(package_python_definitions)s
@@ -513,7 +521,7 @@ if(SOURCE_FILES)
add_library(source_file_lib
STATIC
${SOURCE_FILES})
- set(EXTRA_LIBRARIES \"source_file_lib ${EXTRA_LIBRARIES}\")
+ set(EXTRA_LIBRARIES \"source_file_lib;${EXTRA_LIBRARIES}\")
endif()
if(EXTRA_LIBRARIES)
diff --git a/instant/config.py b/instant/config.py
index 9b91eb4..e4ce625 100644
--- a/instant/config.py
+++ b/instant/config.py
@@ -20,8 +20,10 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Instant. If not, see <http://www.gnu.org/licenses/>.
#
-# Alternatively, Instant may be distributed under the terms of the BSD license.
+# Alternatively, Instant may be distributed under the terms of the BSD
+# license.
+from six import string_types
import os
from .output import get_status_output
import re
@@ -32,21 +34,22 @@ _swig_version_cache = None
_pkg_config_installed = None
_header_and_library_cache = {}
+
def check_and_set_swig_binary(binary="swig", path=""):
""" Check if a particular swig binary is available"""
global _swig_binary_cache
- if not isinstance(binary, str):
+ if not isinstance(binary, string_types):
raise TypeError("expected a 'str' as first argument")
- if not isinstance(path, str):
+ if not isinstance(path, string_types):
raise TypeError("expected a 'str' as second argument")
swig_binary = os.path.join(path, binary)
if swig_binary == _swig_binary_cache:
return True
-
+
result, output = get_status_output("%s -version"%swig_binary)
- if result != 0:
+ if result != 0:
return False
-
+
# Set binary cache
_swig_binary_cache = swig_binary
@@ -54,51 +57,55 @@ def check_and_set_swig_binary(binary="swig", path=""):
pattern = "SWIG Version (.*)"
r = re.search(pattern, output)
_swig_version_cache = r.groups(0)[0]
-
+
return True
+
def get_swig_binary():
"Return any cached swig binary"
return _swig_binary_cache if _swig_binary_cache else "swig"
+
def get_swig_version():
""" Return the current swig version in a 'str'"""
global _swig_version_cache
if _swig_version_cache is None:
# Check for swig installation
result, output = get_status_output("%s -version"%get_swig_binary())
- if result != 0:
+ if result != 0:
raise OSError("SWIG is not installed on the system.")
pattern = "SWIG Version (.*)"
r = re.search(pattern, output)
_swig_version_cache = r.groups(0)[0]
return _swig_version_cache
+
def check_swig_version(version, same=False):
- """ Check the swig version
+ """Check the swig version
- Returns True if the version of the installed swig is equal or greater than the
- version passed to the function.
+ Returns True if the version of the installed swig is equal or
+ greater than the version passed to the function.
If same is True, the function returns True if and only if the two versions
are the same.
-
+
Usage:
if instant.check_swig_version('1.3.36'):
print "Swig version is greater than or equal to 1.3.36"
else:
print "Swig version is lower than 1.3.36"
+
"""
- assert isinstance(version, str), "Provide the first version number as a 'str'"
- assert len(version.split("."))==3, "Provide the version number as three numbers seperated by '.'"
+ assert isinstance(version, string_types), "Provide the first version number as a 'str'"
+ assert len(version.split(".")) == 3, "Provide the version number as three numbers seperated by '.'"
installed_version = list(map(int, get_swig_version().split('.')))
handed_version = list(map(int, version.split('.')))
-
+
# If same is True then just check that all numbers are equal
if same:
return all(i == h for i, h in zip(installed_version, handed_version))
-
+
swig_enough = True
for i, v in enumerate([v for v in installed_version]):
if handed_version[i] < v:
@@ -108,26 +115,30 @@ def check_swig_version(version, same=False):
else:
swig_enough = False
break
-
+
return swig_enough
+
def header_and_libs_from_pkgconfig(*packages, **kwargs):
- """This function returns list of include files, flags,
- libraries and library directories obtain from a pkgconfig file.
-
- The usage is:
+ """This function returns list of include files, flags, libraries and
+ library directories obtain from a pkgconfig file.
+
+ The usage is:
(includes, flags, libraries, libdirs) = \
header_and_libs_from_pkgconfig(*list_of_packages)
or:
(includes, flags, libraries, libdirs, linkflags) = \
header_and_libs_from_pkgconfig(*list_of_packages, \
returnLinkFlags=True)
+
"""
+
global _pkg_config_installed, _header_and_library_cache
returnLinkFlags = kwargs.get("returnLinkFlags", False)
if _pkg_config_installed is None:
result, output = get_status_output("pkg-config --version ")
_pkg_config_installed = (result == 0)
+
if not _pkg_config_installed:
raise OSError("The pkg-config package is not installed on the system.")
@@ -146,7 +157,7 @@ def header_and_libs_from_pkgconfig(*packages, **kwargs):
if not pack in _header_and_library_cache:
result, output = get_status_output(\
"pkg-config --exists %s " % pack, env=env)
- if result == 0:
+ if result == 0:
tmp = get_status_output(\
"pkg-config --cflags-only-I %s " % pack, env=env)[1].split()
_includes = [i[2:] for i in tmp]
@@ -183,4 +194,5 @@ def header_and_libs_from_pkgconfig(*packages, **kwargs):
if returnLinkFlags:
return (includes, flags, libs, libdirs, linkflags)
+
return (includes, flags, libs, libdirs)
diff --git a/instant/inlining.py b/instant/inlining.py
index 6c0456c..053e040 100644
--- a/instant/inlining.py
+++ b/instant/inlining.py
@@ -34,15 +34,14 @@ def get_func_name(c_code):
return func_name
-
def inline(c_code, **kwargs):
- """This is a short wrapper around the build_module function in instant.
-
+ """This is a short wrapper around the build_module function in instant.
+
It creates a module given that
the input is a valid C function. It is only possible
- to inline one C function each time.
+ to inline one C function each time.
- Usage:
+ Usage:
>>> from instant import inline
>>> add_func = inline("double add(double a, double b){ return a+b; }")
@@ -58,14 +57,15 @@ def inline(c_code, **kwargs):
instant_warning("Didn't find function '%s', returning module." % func_name)
return module
+
def inline_module(c_code, **kwargs):
- """This is a short wrapper around the build_module function in instant.
-
+ """This is a short wrapper around the build_module function in instant.
+
It creates a module given that
the input is a valid C function. It is only possible
- to inline one C function each time.
+ to inline one C function each time.
- Usage:
+ Usage:
>>> from instant import inline
>>> add_func = inline("double add(double a, double b){ return a+b; }")
@@ -79,35 +79,36 @@ def inline_module(c_code, **kwargs):
def inline_with_numpy(c_code, **kwargs):
- '''This is a short wrapper around the build_module function in instant.
-
+ '''This is a short wrapper around the build_module function in instant.
+
It creates a module given that
the input is a valid C function. It is only possible
to inline one C function each time. The difference between
- this function and the inline function is that C-arrays can be used.
- The following example illustrates that.
+ this function and the inline function is that C-arrays can be used.
+ The following example illustrates that.
- Usage:
+ Usage:
>>> import numpy
>>> import time
>>> from instant import inline_with_numpy
>>> c_code = """
double sum (int n1, double* array1){
- double tmp = 0.0;
- for (int i=0; i<n1; i++) {
- tmp += array1[i];
+ double tmp = 0.0;
+ for (int i=0; i<n1; i++) {
+ tmp += array1[i];
}
- return tmp;
+ return tmp;
}
"""
>>> sum_func = inline_with_numpy(c_code, arrays = [['n1', 'array1']])
>>> a = numpy.arange(10000000); a = numpy.sin(a)
>>> sum_func(a)
'''
+
import numpy
instant_assert("code" not in kwargs, "Cannot specify code twice.")
- kwargs["code"] = c_code
+ kwargs["code"] = c_code
kwargs["init_code"] = kwargs.get("init_code", "") + "\nimport_array();\n"
kwargs["system_headers"] = kwargs.get("system_headers", []) + ["numpy/arrayobject.h"]
kwargs["include_dirs"] = kwargs.get("include_dirs", []) + ["%s" %numpy.get_include()]
@@ -120,26 +121,26 @@ def inline_with_numpy(c_code, **kwargs):
return module
def inline_module_with_numpy(c_code, **kwargs):
- '''This is a short wrapper around the build_module function in instant.
-
+ '''This is a short wrapper around the build_module function in instant.
+
It creates a module given that
the input is a valid C function. It is only possible
to inline one C function each time. The difference between
- this function and the inline function is that C-arrays can be used.
- The following example illustrates that.
+ this function and the inline function is that C-arrays can be used.
+ The following example illustrates that.
- Usage:
+ Usage:
>>> import numpy
>>> import time
>>> from instant import inline_with_numpy
>>> c_code = """
double sum (int n1, double* array1){
- double tmp = 0.0;
- for (int i=0; i<n1; i++) {
- tmp += array1[i];
+ double tmp = 0.0;
+ for (int i=0; i<n1; i++) {
+ tmp += array1[i];
}
- return tmp;
+ return tmp;
}
"""
>>> sum_func = inline_with_numpy(c_code, arrays = [['n1', 'array1']])
@@ -148,7 +149,7 @@ def inline_module_with_numpy(c_code, **kwargs):
'''
import numpy
instant_assert("code" not in kwargs, "Cannot specify code twice.")
- kwargs["code"] = c_code
+ kwargs["code"] = c_code
kwargs["init_code"] = kwargs.get("init_code", "") + "\nimport_array();\n"
kwargs["system_headers"] = kwargs.get("system_headers", []) + ["numpy/arrayobject.h"]
kwargs["include_dirs"] = kwargs.get("include_dirs", []) + ["%s" % numpy.get_include()]
@@ -156,7 +157,7 @@ def inline_module_with_numpy(c_code, **kwargs):
return module
-def inline_vtk(c_code, cache_dir=None):
+def inline_vtk(c_code, cache_dir=None):
module = build_module_vtk(c_code)
func_name = get_func_name(c_code)
@@ -166,7 +167,7 @@ def inline_vtk(c_code, cache_dir=None):
instant_warning("Didn't find function '%s', returning module." % func_name)
return module
-def inline_vmtk(c_code, cache_dir=None):
+def inline_vmtk(c_code, cache_dir=None):
module = build_module_vmtk(c_code)
func_name = get_func_name(c_code)
@@ -175,4 +176,3 @@ def inline_vmtk(c_code, cache_dir=None):
else:
instant_warning("Didn't find function '%s', returning module." % func_name)
return module
-
diff --git a/instant/locking.py b/instant/locking.py
index d65eb6c..00485ef 100644
--- a/instant/locking.py
+++ b/instant/locking.py
@@ -2,7 +2,7 @@
when multiple processes work with the same module.
Only works on UNIX systems.
-Two python libraries can be used:
+Two Python libraries can be used:
flufl.lock : A nfs safe which can be downloaded from:
@@ -49,8 +49,8 @@ except:
except:
fcntl = None
-# Keeping an overview of locks currently held,
-# to avoid deadlocks within a single process.
+# Keeping an overview of locks currently held, to avoid deadlocks
+# within a single process
_lock_names = {} # lock.fileno() -> lockname
_lock_files = {} # lockname -> lock
_lock_count = {} # lockname -> number of times this lock has been aquired and not yet released
@@ -58,22 +58,22 @@ _lock_count = {} # lockname -> number of times this lock has been aquired and no
if flufl:
def get_lock(cache_dir, module_name):
"Get a new file lock."
-
+
from flufl.lock import Lock
from datetime import timedelta
-
+
lockname = module_name + ".lock"
count = _lock_count.get(lockname, 0)
-
+
instant_debug("Acquiring lock %s, count is %d." % (lockname, count))
-
+
cache_dir = validate_cache_dir(cache_dir)
lockname = os.path.join(cache_dir, lockname)
lock = Lock(lockname)
lock.lock()
-
+
return lock
-
+
def release_lock(lock):
"Release a lock currently held by Instant."
if lock.is_locked:
@@ -88,14 +88,14 @@ elif fcntl:
def get_lock(cache_dir, module_name):
"Get a new file lock."
global _lock_names, _lock_files, _lock_count
-
+
lockname = module_name + ".lock"
count = _lock_count.get(lockname, 0)
import inspect
frame = inspect.currentframe().f_back
instant_debug("Acquiring lock %s, count is %d. Called from: %s line: %d" % \
(lockname, count, inspect.getfile(frame), frame.f_lineno))
-
+
if count == 0:
cache_dir = validate_cache_dir(cache_dir)
lock = open(os.path.join(cache_dir, lockname), "w")
@@ -104,14 +104,14 @@ elif fcntl:
_lock_files[lockname] = lock
else:
lock = _lock_files[lockname]
-
+
_lock_count[lockname] = count + 1
return lock
-
+
def release_lock(lock):
"Release a lock currently held by Instant."
global _lock_names, _lock_files, _lock_count
-
+
lockname = _lock_names[lock.fileno()]
count = _lock_count[lockname]
@@ -123,14 +123,14 @@ elif fcntl:
instant_assert(count > 0, "Releasing lock that Instant is supposedly not holding.")
instant_assert(lock is _lock_files[lockname], "Lock mismatch, might be something wrong in locking logic.")
-
+
del _lock_files[lockname]
del _lock_names[lock.fileno()]
_lock_count[lockname] = count - 1
-
+
fcntl.flock(lock.fileno(), fcntl.LOCK_UN)
lock.close()
-
+
def release_all_locks():
"Release all locks currently held by Instant."
locks = list(_lock_files.values())
@@ -139,16 +139,18 @@ elif fcntl:
instant_assert(all(_lock_count[lockname] == 0 for lockname in _lock_count), "Lock counts not zero after releasing all locks.")
else:
- # Windows systems have no fcntl, implement these otherwise if locking is needed on windows
+ # Windows systems have no fcntl, implement these otherwise if
+ # locking is needed on windows
def get_lock(cache_dir, module_name):
return None
-
+
def release_lock(lock):
pass
def release_all_locks():
pass
-
+
+
class file_lock(object):
"""
File lock using with statement
@@ -156,7 +158,7 @@ class file_lock(object):
def __init__(self, cache_dir, module_name):
self.cache_dir = cache_dir
self.module_name = module_name
-
+
def __enter__(self):
self.lock = get_lock(self.cache_dir, self.module_name)
return self.lock
diff --git a/instant/output.py b/instant/output.py
index 58b9f8b..a983896 100644
--- a/instant/output.py
+++ b/instant/output.py
@@ -20,6 +20,7 @@
#
# Alternatively, Instant may be distributed under the terms of the BSD license.
+from six import string_types
import logging, os, platform, sys
# Logging wrappers
@@ -31,26 +32,30 @@ _log.setLevel(logging.INFO)
#_log.setLevel(logging.DEBUG)
# Choose method for calling external programs. use subprocess by
-# deafult, and os.system on Windows
+# default, and os.system on Windows
_default_call_method = 'SUBPROCESS'
if 'Windows' in platform.system() or 'CYGWIN' in platform.system():
_default_call_method = 'OS_SYSTEM'
-_call_method = os.environ.get("INSTANT_SYSTEM_CALL_METHOD", \
+_call_method = os.environ.get("INSTANT_SYSTEM_CALL_METHOD",
_default_call_method)
_log.debug('Using call method: %s'%_call_method)
+
def get_log_handler():
return _loghandler
+
def get_logger():
return _log
+
def set_log_handler(handler):
global _loghandler
_log.removeHandler(_loghandler)
_loghandler = handler
_log.addHandler(_loghandler)
+
def set_logging_level(level):
import inspect
frame = inspect.currentframe().f_back
@@ -59,8 +64,9 @@ def set_logging_level(level):
(inspect.getfile(frame), frame.f_lineno))
set_log_level(level)
+
def set_log_level(level):
- if isinstance(level, str):
+ if isinstance(level, string_types):
level = level.upper()
assert level in ("INFO", "WARNING", "ERROR", "DEBUG")
level = getattr(logging, level)
@@ -68,30 +74,38 @@ def set_log_level(level):
assert isinstance(level, int)
_log.setLevel(level)
+
# Aliases for calling log consistently:
+
def instant_debug(*message):
_log.debug(*message)
+
def instant_info(*message):
_log.info(*message)
+
def instant_warning(*message):
_log.warning(*message)
+
def instant_error(*message):
_log.error(*message)
text = message[0] % message[1:]
raise RuntimeError(text)
+
def instant_assert(condition, *message):
if not condition:
_log.error(*message)
text = message[0] % message[1:]
raise AssertionError(text)
+
# Utility functions for file handling:
+
def write_file(filename, text):
"Write text to a file and close it."
try:
@@ -101,12 +115,27 @@ def write_file(filename, text):
except IOError as e:
instant_error("Can't open '%s': %s" % (filename, e))
+
if _call_method == 'SUBPROCESS':
- from subprocess import Popen, PIPE, STDOUT
+
+ # NOTE: subprocess in Python 2 is not OFED-fork-safe! Check subprocess.py,
+ # http://bugs.python.org/issue1336#msg146685
+ # OFED-fork-safety means that parent should not
+ # touch anything between fork() and exec(),
+ # which is not met in subprocess module. See
+ # https://www.open-mpi.org/faq/?category=openfabrics#ofa-fork
+ # http://www.openfabrics.org/downloads/OFED/release_notes/OFED_3.12_rc1_release_notes#3.03
+ # However, subprocess32 backports the fix from Python 3 to 2.7.
+ if os.name == "posix" and sys.version_info[0] < 3:
+ try:
+ import subprocess32 as subprocess
+ except:
+ import subprocess
+ else:
+ import subprocess
def get_status_output(cmd, input=None, cwd=None, env=None):
- "Replacement for commands.getstatusoutput which does not work on Windows."
- if isinstance(cmd, str):
+ if isinstance(cmd, string_types):
cmd = cmd.strip().split()
instant_debug("Running: " + str(cmd))
@@ -117,7 +146,8 @@ if _call_method == 'SUBPROCESS':
# which is not met in subprocess module. See
# https://www.open-mpi.org/faq/?category=openfabrics#ofa-fork
# http://www.openfabrics.org/downloads/OFED/release_notes/OFED_3.12_rc1_release_notes#3.03
- pipe = Popen(cmd, shell=False, cwd=cwd, env=env, stdout=PIPE, stderr=STDOUT)
+ pipe = subprocess.Popen(cmd, shell=False, cwd=cwd, env=env, stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT)
(output, errout) = pipe.communicate(input=input)
assert not errout
@@ -134,7 +164,7 @@ elif _call_method == 'OS_SYSTEM':
def get_status_output(cmd, input=None, cwd=None, env=None):
# We don't need function with such a generality.
# We only need output and return code.
- if not isinstance(cmd, str) or input is not None or \
+ if not isinstance(cmd, string_types) or input is not None or \
cwd is not None or env is not None:
raise NotImplementedError(
'This implementation (%s) of get_status_output does'
@@ -155,13 +185,6 @@ elif _call_method == 'OS_SYSTEM':
output = output.decode('utf-8') if sys.version_info[0] > 2 else output
return (status, output)
-
-elif _call_method == 'COMMANDS':
- import commands
- def get_status_output(*args, **kwargs):
- status, output = commands.getstatusoutput(*args, **kwargs)
- output = output.decode('utf-8') if sys.version_info[0] > 2 else output
- return status, output
else:
instant_error('Incomprehensible environment variable'
' INSTANT_SYSTEM_CALL_METHOD=%s'%_call_method)
diff --git a/instant/paths.py b/instant/paths.py
index 736d354..fca9e0e 100644
--- a/instant/paths.py
+++ b/instant/paths.py
@@ -22,7 +22,9 @@
# Utilities for directory handling:
+from six import string_types
import os
+import sys
import errno
import shutil
import tempfile
@@ -31,9 +33,11 @@ from .signatures import compute_checksum
from .output import instant_debug, instant_assert
_tmp_dir = None
+
+
def get_temp_dir():
"""Return a temporary directory for the duration of this process.
-
+
Multiple calls in the same process returns the same directory.
Remember to call delete_temp_dir() before exiting."""
global _tmp_dir
@@ -44,6 +48,7 @@ def get_temp_dir():
instant_debug("Created temp directory '%s'." % _tmp_dir)
return _tmp_dir
+
def delete_temp_dir():
"""Delete the temporary directory created by get_temp_dir()."""
global _tmp_dir
@@ -51,14 +56,35 @@ def delete_temp_dir():
shutil.rmtree(_tmp_dir, ignore_errors=True)
_tmp_dir = None
+
def get_instant_dir():
"Return the default instant directory, creating it if necessary."
- # os.path.expanduser works for Windows, Linux, and Mac
- # In Windows, $HOME is os.environ['HOMEDRIVE'] + os.environ['HOMEPATH']
- instant_dir = os.path.join(os.path.expanduser("~"), ".instant")
+ # Place default cache dir in virtualenv or conda prefix
+ # if one of them are active, or under user's home directory
+ home = os.path.expanduser("~")
+ venv = os.environ.get("VIRTUAL_ENV")
+ cenv = os.environ.get("CONDA_PREFIX")
+ if venv == sys.prefix:
+ env = venv
+ elif cenv == sys.prefix:
+ env = cenv
+ else:
+ env = home
+
+ instant_dir = os.path.join(env, ".cache", "instant")
+
+ # If placed in home directory, add python version for safety,
+ # since C extensions are not compatible across versions.
+ # (for python 3, it's possible to use the stable C API,
+ # however we don't know if the instant user has done that)
+ if env == home:
+ ver = "python%d.%d" % sys.version_info[:2]
+ instant_dir = os.path.join(instant_dir, ver)
+
makedirs(instant_dir)
return instant_dir
+
def get_default_cache_dir():
"Return the default cache directory."
cache_dir = os.environ.get("INSTANT_CACHE_DIR")
@@ -68,6 +94,7 @@ def get_default_cache_dir():
makedirs(cache_dir)
return cache_dir
+
def get_default_error_dir():
"Return the default error directory."
error_dir = os.environ.get("INSTANT_ERROR_DIR")
@@ -77,14 +104,16 @@ def get_default_error_dir():
makedirs(error_dir)
return error_dir
+
def validate_cache_dir(cache_dir):
if cache_dir is None:
return get_default_cache_dir()
- instant_assert(isinstance(cache_dir, str), "Expecting cache_dir to be a string.")
+ instant_assert(isinstance(cache_dir, string_types), "Expecting cache_dir to be a string.")
cache_dir = os.path.abspath(cache_dir)
makedirs(cache_dir)
return cache_dir
+
def makedirs(path):
"""
Creates a directory (tree). If directory already excists it does nothing.
@@ -96,6 +125,7 @@ def makedirs(path):
if e.errno != errno.EEXIST:
raise
+
def _test():
from .output import set_logging_level
set_logging_level("DEBUG")
@@ -104,7 +134,7 @@ def _test():
print("Default cache dir:", get_default_cache_dir())
print("Default error dir:", get_default_error_dir())
delete_temp_dir()
-
+
+
if __name__ == "__main__":
_test()
-
diff --git a/instant/signatures.py b/instant/signatures.py
index 6f2528b..9598d7e 100644
--- a/instant/signatures.py
+++ b/instant/signatures.py
@@ -19,6 +19,7 @@
#
# Alternatively, Instant may be distributed under the terms of the BSD license.
+from six import string_types
import hashlib
from .output import instant_assert, instant_debug, instant_error
@@ -27,7 +28,7 @@ def compute_checksum(text="", filenames=[]):
Get the checksum value of filename
modified based on Python24\Tools\Scripts\md5.py
"""
- instant_assert(isinstance(text, str), "Expecting string.")
+ instant_assert(isinstance(text, string_types), "Expecting string.")
instant_assert(isinstance(filenames, (list, tuple)), "Expecting sequence.")
m = hashlib.new('sha1')
diff --git a/release.conf b/release.conf
deleted file mode 100644
index 9a2bc6f..0000000
--- a/release.conf
+++ /dev/null
@@ -1,5 +0,0 @@
-# Configuration file for fenics-release
-
-PACKAGE="instant"
-BRANCH="master"
-FILES="ChangeLog setup.py instant/__init__.py"
diff --git a/scripts/maketarball.sh b/scripts/maketarball.sh
deleted file mode 100755
index 3573e93..0000000
--- a/scripts/maketarball.sh
+++ /dev/null
@@ -1,22 +0,0 @@
-#!/bin/sh
-
-
-rm -rf ../build
-rm instant-0.9.6.tar.gz
-
-cd ../tests
-sh clean.sh
-
-cd ../..
-cp -r instant instant-0.9.6
-cd instant-0.9.6/etc
-
-files=`find ../../instant-0.9.6 -type f| grep -v hg`
-#echo $files
-tar -cf instant-0.9.6.tar $files
-gzip instant-0.9.6.tar
-ls -s instant-0.9.6.tar.gz
-cp instant-0.9.6.tar.gz ../../instant/etc/.
-rm -rf ../../instant-0.9.6
-
-
diff --git a/setup.py b/setup.py
index 2e46942..cb58118 100755
--- a/setup.py
+++ b/setup.py
@@ -36,19 +36,44 @@ tarball = None
if not 'dev' in version:
tarball = url + "downloads/instant-%s.tar.gz" % version
-setup(name = "instant",
- version = version,
- description = "Instant Inlining of C/C++ in Python",
- author = "Magne Westlie, Kent-Andre Mardal, Martin Sandve Alnes and Ilmar M. Wilbers",
- author_email = "fenics-dev at googlegroups.com",
- url = url,
- download_url = tarball,
- packages = ['instant'],
- package_dir = {'instant': 'instant'},
- package_data = {'': [join('swig', 'numpy.i')]},
- scripts = scripts,
- install_requires = ["numpy"],
- data_files = [(join("share", "man", "man1"),
- [join("doc", "man", "man1", "instant-clean.1.gz"),
- join("doc", "man", "man1", "instant-showcache.1.gz")])]
+CLASSIFIERS = """\
+Development Status :: 5 - Production/Stable
+Intended Audience :: Developers
+Intended Audience :: Science/Research
+License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)
+Operating System :: POSIX
+Operating System :: POSIX :: Linux
+Operating System :: MacOS :: MacOS X
+Operating System :: Microsoft :: Windows
+Programming Language :: Python
+Programming Language :: Python :: 2
+Programming Language :: Python :: 2.7
+Programming Language :: Python :: 3
+Programming Language :: Python :: 3.4
+Programming Language :: Python :: 3.5
+Programming Language :: Python :: 3.6
+Topic :: Scientific/Engineering :: Mathematics
+Topic :: Software Development :: Libraries :: Python Modules
+"""
+
+requires = ["numpy", "six"]
+if sys.version_info[0] == 2:
+ requires.append("subprocess32")
+
+setup(name="instant",
+ version=version,
+ description="Instant Inlining of C/C++ in Python",
+ author="Magne Westlie, Kent-Andre Mardal, Martin Sandve Alnes and Ilmar M. Wilbers",
+ author_email="fenics-dev at googlegroups.com",
+ classifiers=[_f for _f in CLASSIFIERS.split('\n') if _f],
+ url=url,
+ download_url=tarball,
+ packages=['instant'],
+ package_dir={'instant': 'instant'},
+ package_data={'': [join('swig', 'numpy.i')]},
+ scripts=scripts,
+ install_requires=requires,
+ data_files=[(join("share", "man", "man1"),
+ [join("doc", "man", "man1", "instant-clean.1.gz"),
+ join("doc", "man", "man1", "instant-showcache.1.gz")])]
)
diff --git a/test/dolfin_test.py b/test/dolfin_test.py
deleted file mode 100644
index 518d3a4..0000000
--- a/test/dolfin_test.py
+++ /dev/null
@@ -1,38 +0,0 @@
-from __future__ import print_function
-
-try:
- from dolfin import *
-except:
- print("dolfin not installed...")
- exit()
-
-import instant
-
-cpp_code = """
-void dabla(dolfin::Vector& a, dolfin::Vector& b, double c, double d) {
- for (unsigned int i=0; i < a.size(); i++) {
- b.setitem(i, d*a[i] + c);
- }
-}
-"""
-
-
-a = Vector(12)
-a[:] = 3.4
-b = Vector(12)
-
-c = 1.3
-d = 2.4
-
-
-include_dirs, flags, libs, libdirs = instant.header_and_libs_from_pkgconfig("dolfin")
-
-headers= ["dolfin.h"]
-
-func = instant.inline(cpp_code, system_headers=headers, include_dirs=include_dirs, libraries = libs, library_dirs = libdirs)
-
-func(a, b, c, d)
-
-print(b.array())
-
-
diff --git a/test/pytest.ini b/test/pytest.ini
new file mode 100644
index 0000000..8349e72
--- /dev/null
+++ b/test/pytest.ini
@@ -0,0 +1,9 @@
+[pytest]
+# We use fixture features requiring pytest 2.4
+minversion = 2.4
+
+# Make pytest ignore temp folders
+norecursedirs = .* __pycache__ test_*_tempdir
+
+# Make pytest ignore the book files and other utility .py files
+python_files = test*.py
diff --git a/test/rerun_tests.py b/test/rerun_tests.py
index 1e054c2..c47a2c2 100644
--- a/test/rerun_tests.py
+++ b/test/rerun_tests.py
@@ -1,18 +1,7 @@
#!/usr/bin/env python
+
from __future__ import print_function
-import os, sys, glob
+import pytest
print("Not cleaning local test cache before tests.")
-
-failed_tests = []
-for f in glob.glob("test*.py"):
- print("Running test", f, sep=" ")
- failure = os.system("python " + f)
- if failure:
- failed_tests.append(f)
-
-if failed_tests:
- print("\nThe following tests failed:")
- for f in failed_tests:
- print(f)
- sys.exit(len(failed_tests))
+pytest.main()
diff --git a/test/run_tests.py b/test/run_tests.py
index 960badd..5743636 100644
--- a/test/run_tests.py
+++ b/test/run_tests.py
@@ -1,20 +1,11 @@
-#!/usr/bin/env python
+#!/usr/bin/env python
from __future__ import print_function
-import os, sys, glob, shutil
+import os
+import pytest
print("Cleaning local test cache before tests.")
os.system("python clean.py")
-failed_tests = []
-for f in glob.glob("test*.py"):
- print("Running test %s" % f)
- failure = os.system("python " + f)
- if failure:
- failed_tests.append(f)
-
-if failed_tests:
- print("\nThe following tests failed:")
- for f in failed_tests:
- print(f)
- sys.exit(len(failed_tests))
+# Run tests
+pytest.main()
diff --git a/test/test01.py b/test/test01.py
new file mode 100644
index 0000000..7ec6237
--- /dev/null
+++ b/test/test01.py
@@ -0,0 +1,8 @@
+from __future__ import print_function
+import pytest
+from instant import inline
+
+def test_inline():
+ add_func = inline("double add(double a, double b){ return a+b; }",
+ cache_dir="test_cache")
+ assert add_func(3, 4.5) == 7.5
diff --git a/test/test02.py b/test/test02.py
new file mode 100644
index 0000000..d7266d3
--- /dev/null
+++ b/test/test02.py
@@ -0,0 +1,34 @@
+from __future__ import print_function
+import pytest
+import numpy
+import time
+from instant import inline_with_numpy
+
+c_code = """
+double sum (int n1, double* array1){
+ double tmp = 0.0;
+ for (int i=0; i<n1; i++) {
+ tmp += array1[i];
+ }
+ return tmp;
+}
+"""
+
+def test_compare_numpy():
+
+ sum_func = inline_with_numpy(c_code, arrays = [['n1', 'array1']], cache_dir="test_cache")
+
+ a = numpy.arange(10000000); a = numpy.sin(a)
+
+ t1 = time.time()
+ sum1 = sum_func(a)
+ t2 = time.time()
+ print('With instant:', t2 - t1, 'seconds')
+
+ t1 = time.time()
+ sum2 = numpy.sum(a)
+ t2 = time.time()
+ print('With numpy: ', t2-t1, 'seconds')
+
+ difference = abs(sum1 - sum2)
+ assert difference < 1.0e-12
diff --git a/test/test03.py b/test/test03.py
new file mode 100644
index 0000000..c35281d
--- /dev/null
+++ b/test/test03.py
@@ -0,0 +1,20 @@
+from __future__ import print_function
+import pytest
+import instant
+from instant import build_module
+
+c_code = """
+double sum(double a, double b){
+ return a+b;
+}
+"""
+
+def test_build_module():
+ build_module(code=c_code, modulename='test3_ext',
+ cppargs=['-pg', '-O3', '-g'], lddargs=['-pg'])
+
+ from test3_ext import sum
+ a = 3.7
+ b = 4.8
+ c = sum(a, b)
+ assert c == 8.5
diff --git a/test/test04.py b/test/test04.py
new file mode 100644
index 0000000..5e7ab37
--- /dev/null
+++ b/test/test04.py
@@ -0,0 +1,63 @@
+from __future__ import print_function
+import pytest
+from instant import build_module
+import numpy, sys
+from functools import reduce
+
+a = numpy.arange(10000000)
+a = numpy.sin(a)
+b = numpy.arange(10000000)
+b = numpy.cos(b)
+
+s = """
+PyObject* add(PyObject* a_, PyObject* b_){
+ /*
+ various checks
+ */
+ PyArrayObject* a=(PyArrayObject*) a_;
+ PyArrayObject* b=(PyArrayObject*) b_;
+
+ int n = a->dimensions[0];
+
+ npy_intp dims[1];
+ dims[0] = n;
+ PyArrayObject* ret;
+ ret = (PyArrayObject*) PyArray_SimpleNew(1, dims, PyArray_DOUBLE);
+
+ int i;
+ double aj;
+ double bj;
+ double *retj;
+ for (i=0; i < n; i++) {
+ retj = (double*)(ret->data+ret->strides[0]*i);
+ aj = *(double *)(a->data+ a->strides[0]*i);
+ bj = *(double *)(b->data+ b->strides[0]*i);
+ *retj = aj + bj;
+ }
+return PyArray_Return(ret);
+}
+"""
+
+def test_build_module():
+
+ test4_ext = build_module(code=s, system_headers=["numpy/arrayobject.h"],
+ include_dirs=[numpy.get_include()],
+ init_code='import_array();', modulename="test4_ext")
+
+ import time
+
+ t1 = time.time()
+ d = test4_ext.add(a, b)
+ t2 = time.time()
+
+ print('With instant:', t2 - t1, 'seconds')
+
+ t1 = time.time()
+ c = a + b
+ t2 = time.time()
+
+ print('With numpy: ', t2 - t1, 'seconds')
+
+ difference = abs(c - d)
+ sum = reduce( lambda a, b: a + b, difference)
+ assert sum < 1.0e-12
diff --git a/test/test05.py b/test/test05.py
new file mode 100644
index 0000000..b4cf4cc
--- /dev/null
+++ b/test/test05.py
@@ -0,0 +1,51 @@
+from __future__ import print_function
+import pytest
+from instant import build_module
+import numpy
+import sys
+import time
+from functools import reduce
+
+
+c_code = """
+/* add function for vectors with all safety checks removed ..*/
+void add(int n1, double* array1, int n2, double* array2, int n3, double* array3){
+ if ( n1 == n2 && n1 == n3 ) {
+ for (int i=0; i<n1; i++) {
+ array3[i] = array1[i] + array2[i];
+ }
+ }
+ else {
+ printf("The arrays should have the same size.");
+ }
+
+}
+"""
+
+def test_buil_module():
+ test5_ext = build_module(code=c_code, system_headers=["numpy/arrayobject.h"],
+ cppargs=['-pg'], lddargs=['-pg'],
+ include_dirs=[numpy.get_include()],
+ init_code='import_array();', modulename='test5_ext',
+ arrays = [['n1', 'array1'], ['n2', 'array2'], ['n3', 'array3']])
+
+ from test5_ext import add
+ add = test5_ext.add
+ a = numpy.arange(10000000); a = numpy.sin(a)
+ b = numpy.arange(10000000); b = numpy.cos(b)
+ c = numpy.arange(10000000); c = numpy.cos(c)
+ d = numpy.arange(10000000); d = numpy.cos(d)
+
+ t1 = time.time()
+ add(a, b, c)
+ t2 = time.time()
+ print('With instant:', t2-t1, 'seconds')
+
+ t1 = time.time()
+ numpy.add(a, b, d)
+ t2 = time.time()
+ print('With numpy: ', t2-t1, 'seconds')
+
+ difference = abs(d - c)
+ sum = reduce( lambda a, b: a+b, difference)
+ assert abs(sum) < 1.0e-12
diff --git a/test/test06.py b/test/test06.py
new file mode 100644
index 0000000..7f74411
--- /dev/null
+++ b/test/test06.py
@@ -0,0 +1,55 @@
+from __future__ import print_function
+import pytest
+from instant import build_module
+import numpy as N
+import sys
+import time
+
+
+c_code = """
+/* add function for matrices with all safety checks removed ..*/
+void add(int x1, int y1, double* array1,
+ int x2, int y2, double* array2,
+ int x3, int y3, double* array3){
+
+ for (int i=0; i<x1; i++) {
+ for (int j=0; j<y1; j++) {
+ *array3 = *array1 + *array2;
+ array3++;
+ array2++;
+ array1++;
+ }
+ }
+}
+"""
+
+def test_build_module():
+
+ # Guess arrayobject is either in sys.prefix or /usr/local
+
+ test6_ext = build_module(code=c_code, system_headers=["numpy/arrayobject.h"], cppargs=['-g'],
+ include_dirs=[N.get_include()],
+ init_code='import_array();', modulename='test6_ext',
+ arrays = [['x1', 'y1', 'array1'],
+ ['x2', 'y2', 'array2'],
+ ['x3', 'y3', 'array3']])
+
+ from test6_ext import add
+ a = N.arange(4000000); a = N.sin(a); a.shape=(2000, 2000)
+ b = N.arange(4000000); b = N.cos(b); b.shape=(2000, 2000)
+ c = N.arange(4000000); c = N.cos(c); c.shape=(2000, 2000)
+ d = N.arange(4000000); d = N.cos(d); d.shape=(2000, 2000)
+
+ t1 = time.time()
+ add(a, b, c)
+ t2 = time.time()
+
+ t3 = time.time()
+ N.add(a, b, d)
+ t4 = time.time()
+
+ e = abs(d-c)
+ e.shape=(4000000,)
+
+ max_difference = max(e)
+ assert abs(max_difference) < 1.0e-12
diff --git a/test/test07.py b/test/test07.py
new file mode 100644
index 0000000..93c6d0e
--- /dev/null
+++ b/test/test07.py
@@ -0,0 +1,57 @@
+from __future__ import print_function
+import pytest
+import numpy as N
+import time
+from instant import build_module
+import sys
+from functools import reduce
+
+
+c_code = """
+void func(int n1, double* array1, int n2, double* array2){
+ double a;
+ if ( n1 == n2 ) {
+ for (int i=0; i<n1; i++) {
+ a = array1[i];
+ array2[i] = sin(a) + cos(a) + tan(a);
+ }
+ } else {
+ printf("The arrays should have the same size.");
+ }
+}
+"""
+
+
+def test_module():
+ # Guess arrayobject is either in sys.prefix or /usr/local
+
+ test7_ext = build_module(code=c_code, system_headers=["numpy/arrayobject.h"], cppargs='-g',
+ include_dirs=[N.get_include()],
+ init_code='import_array();', modulename='test7_ext',
+ arrays = [['n1', 'array1'], ['n2', 'array2']])
+
+ seed = 10000000.0
+
+ a = N.arange(seed)
+ t1 = time.time()
+ b = N.sin(a) + N.cos(a) + N.tan(a)
+ t2 = time.time()
+ print("With NumPy: ", t2-t1, "seconds")
+
+ from test7_ext import func
+ c = N.arange(seed)
+ t1 = time.time()
+ func(a, c)
+ t2 = time.time()
+ print("With instant: ", t2-t1, "seconds")
+
+ t1 = time.time()
+ d = N.sin(a)
+ d += N.cos(a)
+ d += N.tan(a)
+ t2 = time.time()
+ print("With NumPy inplace aritmetic: ", t2-t1, "seconds")
+
+ difference = abs(b - c)
+ sum = reduce( lambda a, b: a+b, difference)
+ assert abs(sum) < 1.0e-12
diff --git a/test/test08.py b/test/test08.py
new file mode 100644
index 0000000..21528c6
--- /dev/null
+++ b/test/test08.py
@@ -0,0 +1,42 @@
+from __future__ import print_function
+import pytest
+from instant import build_module
+
+c_code = """
+class Sum {
+public:
+ virtual double sum(double a, double b){
+ return a+b;
+ }
+};
+
+
+double use_Sum(Sum& sum, double a, double b) {
+ return sum.sum(a,b);
+}
+"""
+
+def test_build_module():
+ test8_ext = build_module(code=c_code, modulename='test8_ext')
+
+ from test8_ext import Sum, use_Sum
+ sum = Sum()
+ a = 3.7
+ b = 4.8
+ c = use_Sum(sum, a, b)
+ assert c == 8.5
+
+
+ class Sub(Sum):
+ def __init__(self):
+ Sum.__init__(self)
+
+ def sum(self, a, b):
+ print("sub")
+ return a-b;
+
+ sub = Sub()
+ a = 3.7
+ b = 4.8
+ c = use_Sum(sub, a, b)
+ assert c == 8.5
diff --git a/test/test1.py b/test/test1.py
deleted file mode 100755
index ff6a4e9..0000000
--- a/test/test1.py
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/usr/bin/env python
-
-from __future__ import print_function
-from instant import inline
-
-add_func = inline("double add(double a, double b){ return a+b; }", cache_dir="test_cache")
-
-print("The sum of 3 and 4.5 is ", add_func(3, 4.5))
-
-
-
diff --git a/test/test10.py b/test/test10.py
old mode 100755
new mode 100644
index 17d6753..e19aef4
--- a/test/test10.py
+++ b/test/test10.py
@@ -1,93 +1,102 @@
-#!/usr/bin/env python
-
from __future__ import print_function
-import numpy
+import pytest
+import numpy
import time
from instant import inline_with_numpy
-# Example 1: two arrays, one in, one inout
-c_code = """
+def test_inline_numpy1():
+
+ # Example 1: two arrays, one in, one inout
+ c_code = """
double sum (int x1, int y1, int z1, double* array1, int x2, double* array2){
- double tmp = 0.0;
+ double tmp = 0.0;
for (int i=0; i<x1; i++)
for (int j=0; j<y1; j++)
for (int k=0; k<z1; k++){
tmp += array1[i*y1*z1 + j*z1 + k];
array2[1] = 2;
}
- return tmp;
+ return tmp;
}
-"""
+ """
+
+ sum_func = inline_with_numpy(c_code, arrays = [['x1', 'y1', 'z1', 'array1'],
+ ['x2', 'array2', 'in']],
+ cache_dir="test_ex1_cache")
+
+ a = numpy.arange(27000); a = numpy.sin(a)
+ c = a.copy()
+ a.shape = (30, 30, 30)
-sum_func = inline_with_numpy(c_code, arrays = [['x1', 'y1', 'z1', 'array1'],
- ['x2', 'array2', 'in']],
- cache_dir="test_ex1_cache")
+ #print('b = (1,1)')
+ b = (1., 1.)
+ sum1 = sum_func(a, b)
+ #print(b, 'b not changed when list')
-a = numpy.arange(27000); a = numpy.sin(a)
-c = a.copy()
-a.shape = (30, 30, 30)
+ b = numpy.ones(2)
+ sum1 = sum_func(a, b)
+ #print(b, 'b not changed when numpy array')
+ #print(sum1)
-print('b = (1,1)')
-b = (1., 1.)
-sum1 = sum_func(a, b)
-print(b, 'b not changed when list')
-b = numpy.ones(2)
-sum1 = sum_func(a, b)
-print(b, 'b not changed when numpy array')
+def test_inline_numpy2():
-# Example 2: two array, both inout and of same size
-# Cannot avoid specifying all dimensions for both arrays
-c_code = """
+ # Example 2: two array, both inout and of same size
+ # Cannot avoid specifying all dimensions for both arrays
+ c_code = """
double sum (int x1, int y1, double* array1, int x2, int y2, double* array2){
- double tmp = 0.0;
+ double tmp = 0.0;
for (int i=0; i<x1; i++)
for (int j=0; j<y1; j++){
tmp = array1[i*y1 + j];
array1[i*y1 + j] = array2[i*y1 + j];
array2[i*y1 + j] = tmp;
}
- return tmp;
+ return tmp;
}
-"""
+ """
-sum_func = inline_with_numpy(c_code, arrays = [['x1', 'y1', 'array1'],
- ['x2', 'y2', 'array2']],
- cache_dir="test_ex2_cache")
+ sum_func = inline_with_numpy(c_code, arrays = [['x1', 'y1', 'array1'],
+ ['x2', 'y2', 'array2']],
+ cache_dir="test_ex2_cache")
-a = numpy.ones(4)
-a.shape = (2, 2)
-b = a.copy()
-a *= 2
+ a = numpy.ones(4)
+ a.shape = (2, 2)
+ b = a.copy()
+ a *= 2
-sum1 = sum_func(a, b)
-print('a and b changed')
-print(a)
-print(b)
+ sum1 = sum_func(a, b)
+ #print('a and b changed')
+ #print(a)
+ #print(b)
-# Example 3: two arrays, one in, one out
-c_code = """
+
+def test_inline_numpy3():
+ # Example 3: two arrays, one in, one out
+ c_code = """
void sum (int x1, int y1, double* array1, int xy2, double* array2){
for (int i=0; i<x1; i++)
for (int j=0; j<y1; j++)
array2[i*y1 + j] = array1[i*y1 + j]*2;
}
-"""
+ """
+
+ sum_func = inline_with_numpy(c_code, arrays = [['x1', 'y1', 'array1', 'in'],
+ ['xy2', 'array2', 'out']],
+ cache_dir="test_ex3_cache")
-sum_func = inline_with_numpy(c_code, arrays = [['x1', 'y1', 'array1', 'in'],
- ['xy2', 'array2', 'out']],
- cache_dir="test_ex3_cache")
+ a = numpy.ones(4)
+ a.shape = (2, 2)
+ a *= 2
-a = numpy.ones(4)
-a.shape = (2, 2)
-a *= 2
+ c = sum_func(a, a.size)
+ c.shape = a.shape
+ #print(c.shape)
-c = sum_func(a, a.size)
-c.shape = a.shape
-print(c)
-# Example 4: three arrays, one in, one inout, and one out
-c_code = """
+def test_inline_numpy4():
+ # Example 4: three arrays, one in, one inout, and one out
+ c_code = """
void sum (int x1, int y1, long* array1, int x2, int* array2, int x3, double* array3){
for (int i=0; i<x1; i++){
array3[i] = 0;
@@ -95,23 +104,25 @@ void sum (int x1, int y1, long* array1, int x2, int* array2, int x3, double* arr
array3[i] += array1[i*y1 + j]*array2[j];
}
}
-"""
+ """
-sum_func = inline_with_numpy(c_code, arrays = [['x1', 'y1', 'array1', 'in', 'long'],
+ sum_func = inline_with_numpy(c_code, arrays = [['x1', 'y1', 'array1', 'in', 'long'],
['x2', 'array2', 'int'],
['x3', 'array3', 'out', 'double']],
- cache_dir="test_ex4_cache")
+ cache_dir="test_ex4_cache")
+
+ a = numpy.arange(9)#, dtype='int32')
+ a.shape = (3, 3)
+ b = numpy.arange(3, dtype='int32')
-a = numpy.arange(9)#, dtype='int32')
-a.shape = (3, 3)
-b = numpy.arange(3, dtype='int32')
+ c = sum_func(a, b, b.size)
+ #print(c)
+ #print(numpy.dot(a, b))
-c = sum_func(a, b, b.size)
-print(c)
-print(numpy.dot(a, b))
-# Example 5: arrays with more than 3 dimensions, uses old typemaps, only doubles
-c_code = """
+def test_inline_numpy5():
+ # Example 5: arrays with more than 3 dimensions, uses old typemaps, only doubles
+ c_code = """
void sum (int m, int* mp, double* array1, int n, int* np, double* array2){
int w = mp[0], x = mp[1], y = mp[2], z = mp[3];
for (int i=0; i<w; i++)
@@ -123,15 +134,15 @@ void sum (int m, int* mp, double* array1, int n, int* np, double* array2){
array2++;
}
}
-"""
+ """
-sum_func = inline_with_numpy(c_code, arrays = [['m', 'mp', 'array1', 'multi'],
- ['n', 'np', 'array2', 'multi'],],
- cache_dir="test_ex5_cache")
+ sum_func = inline_with_numpy(c_code, arrays = [['m', 'mp', 'array1', 'multi'],
+ ['n', 'np', 'array2', 'multi'],],
+ cache_dir="test_ex5_cache")
-a = numpy.arange(16, dtype='float64')
-a.shape = (2, 2, 2, 2)
-b = a.copy()*0
+ a = numpy.arange(16, dtype='float64')
+ a.shape = (2, 2, 2, 2)
+ b = a.copy()*0
-sum_func(a, b)
-print(numpy.array(a*2 == b).all())
+ sum_func(a, b)
+ assert numpy.array(a*2 == b).all()
diff --git a/test/test11.py b/test/test11.py
old mode 100755
new mode 100644
index 39207c5..2b27e6a
--- a/test/test11.py
+++ b/test/test11.py
@@ -1,35 +1,36 @@
-#!/usr/bin/env python
-
from __future__ import print_function
-import numpy
+import pytest
+import numpy
import time
import instant
from instant import inline_with_numpy
+def test_numpy_inline():
-c_code = """
+ c_code = """
double sum_of_some_func(int n1, double* array1){
- double tmp = 0.0;
- for (int i=0; i<n1; i++) {
- tmp += some_func(array1[i]);
+ double tmp = 0.0;
+ for (int i=0; i<n1; i++) {
+ tmp += some_func(array1[i]);
}
- return tmp;
+ return tmp;
}
-"""
-
+ """
-some_func = inline_with_numpy(c_code, arrays = [['n1', 'array1']], local_headers = ["./some_func.h"], libraries = ["m"])
+ some_func = inline_with_numpy(c_code, arrays=[['n1', 'array1']],
+ local_headers=["./some_func.h"],
+ libraries = ["m"])
-a = numpy.arange(10000000); a = numpy.sin(a)
+ a = numpy.arange(10000000); a = numpy.sin(a)
-t1 = time.time()
-b = some_func(a)
-t2 = time.time()
-print('With instant:', t2-t1, 'seconds')
+ t1 = time.time()
+ b = some_func(a)
+ t2 = time.time()
+ print('With instant:', t2-t1, 'seconds')
-t1 = time.time()
-c = sum(numpy.sin(a) + numpy.cos(a))
-t2 = time.time()
-print('With numpy :', t2-t1, 'seconds')
+ t1 = time.time()
+ c = sum(numpy.sin(a) + numpy.cos(a))
+ t2 = time.time()
+ print('With numpy :', t2-t1, 'seconds')
-print('Difference: ', c - b)
+ assert abs(c - b) < 1.0e-12
diff --git a/test/test12.py b/test/test12.py
old mode 100755
new mode 100644
index 21a3c8d..6a46d4f
--- a/test/test12.py
+++ b/test/test12.py
@@ -1,48 +1,50 @@
-#!/usr/bin/env python
-
from __future__ import print_function
+import pytest
import numpy as N
import time
from instant import inline_with_numpy
-func_str = "sin"
-c_code = """
+
+def test_grid_loop():
+
+ func_str = "sin"
+ c_code = """
void gridloop(int x1, int y1, double* a,
int n, double* x,
int m, double* y) {
- for (int i=0; i<n; i++) {
- for (int j=0; j<m; j++) {
+ for (int i=0; i<n; i++) {
+ for (int j=0; j<m; j++) {
a[i*n +j] = %s(x[i] + y[j]);
}
}
}
-""" % func_str
+ """ % func_str
-n = 5000
+ n = 5000
-a = N.zeros([n, n])
-x = N.arange(0.0, n, 1.0)
-y = N.arange(0.0, n, 1.0)
+ a = N.zeros([n, n])
+ x = N.arange(0.0, n, 1.0)
+ y = N.arange(0.0, n, 1.0)
-arrays = [['x1', 'y1', 'a'], ['n', 'x'], ['m', 'y']]
-grid_func = inline_with_numpy(c_code, arrays=arrays )
+ arrays = [['x1', 'y1', 'a'], ['n', 'x'], ['m', 'y']]
+ grid_func = inline_with_numpy(c_code, arrays=arrays )
-t1 = time.time()
-grid_func(a, x, y)
-t2 = time.time()
-print('With instant:', t2-t1, 'seconds')
+ t1 = time.time()
+ grid_func(a, x, y)
+ t2 = time.time()
+ print('With instant:', t2-t1, 'seconds')
-xv = x[:, N.newaxis]
-yv = y[N.newaxis,:]
-a2 = N.zeros([n, n])
-t1 = time.time()
-a2[:,:] = N.sin(xv + yv)
-t2 = time.time()
-print('With numpy:', t2-t1, 'seconds')
+ xv = x[:, N.newaxis]
+ yv = y[N.newaxis,:]
+ a2 = N.zeros([n, n])
+ t1 = time.time()
+ a2[:,:] = N.sin(xv + yv)
+ t2 = time.time()
+ print('With numpy:', t2-t1, 'seconds')
-d = a-a2
-d.shape = (n*n,)
+ d = a-a2
+ d.shape = (n*n,)
-print('The difference is ', max(d))
+ assert abs(max(d)) < 1.0e-12
diff --git a/test/test13.py b/test/test13.py
deleted file mode 100755
index 1aff1cd..0000000
--- a/test/test13.py
+++ /dev/null
@@ -1,11 +0,0 @@
-#!/usr/bin/env python
-
-from __future__ import print_function
-import instant
-
-add_func = instant.inline("double add(double a, double b){ return a+b; }", cache_dir="test_cache")
-
-print("The sum of 3 and 4.5 is ", add_func(3, 4.5))
-
-
-
diff --git a/test/test14.py b/test/test14.py
deleted file mode 100755
index 0c5d25c..0000000
--- a/test/test14.py
+++ /dev/null
@@ -1,9 +0,0 @@
-#!/usr/bin/env python
-
-from __future__ import print_function
-from instant import inline
-
-add_func = inline("double add(double a, double b){ return a+b; }", signature = "add", cache_dir="test_cache")
-
-print("The sum of 3 and 4.5 is ", add_func(3, 4.5))
-
diff --git a/test/test15.py b/test/test15.py
old mode 100755
new mode 100644
index 64eef2c..654eb64
--- a/test/test15.py
+++ b/test/test15.py
@@ -1,11 +1,18 @@
-#!/usr/bin/python
-
from __future__ import print_function
-def test2():
+import pytest
+import time
+#from math import exp, sin, cos
+
+def test_2():
+
+ try:
+ from sympy import Symbol, exp, sin, cos
+ except:
+ print("You need sympy for this test")
+ return
x = Symbol('x')
pi = 3.14
-
f = -3*x**7 - 2*x**3 + 2*exp(x**2) + x**12*(2*exp(2*x) - pi*sin(x)**((-1) + pi)*cos(x)) + 4*(pi**5 + x**5 + 5*pi*x**4 + 5*x*pi**4 + 10*pi**2*x**3 + 10*pi**3*x**2)*exp(123 + x - x**5 + 2*x**4)
a = []
@@ -20,7 +27,12 @@ def test2():
print("Elapsed time with sympy", t1-t0)
-def test3():
+def test_3():
+ try:
+ from sympy import Symbol, exp, sin, cos
+ except:
+ print("You need sympy for this test")
+ return
x = Symbol('x')
pi = 3.14
@@ -38,22 +50,3 @@ def test3():
t1 = time.time()
print("Elapsed time with lambda and math", t1-t0)
-
-
-if __name__ == '__main__':
- import time
- try:
- from sympy import *
- test2()
- except:
- print("You need sympy for this test")
- try:
- from math import *
- test3()
- except:
- print("You need math for this test")
- try:
- from sympycore import *
- test2()
- except:
- print("You need sympycore for this test")
diff --git a/test/test16.py b/test/test16.py
old mode 100755
new mode 100644
index 31f8736..c203c77
--- a/test/test16.py
+++ b/test/test16.py
@@ -1,55 +1,51 @@
-#!/usr/bin/python
-
from __future__ import print_function
+import pytest
import instant
-
from instant import build_module, import_module
-sig = "((instant unittest test16.py))"
-
-# Trying to import module
-module = import_module(sig, cache_dir="test_cache")
-if module is None:
- print("Defining code")
- c_code = """
- class Sum {
- public:
- virtual double sum(double a, double b){
- return a+b;
- }
- };
-
-
- double use_Sum(Sum& sum, double a, double b) {
- return sum.sum(a,b);
- }
- """
- print("Compiling code")
- module = build_module(code=c_code, signature=sig, cache_dir="test_cache")
+def test_sum():
-# Testing module
-Sum = module.Sum
-use_Sum = module.use_Sum
+ sig = "((instant unittest test16.py))"
-sum = Sum()
-a = 3.7
-b = 4.8
-c = use_Sum(sum, a, b)
-print("The sum of %g and %g is %g"% (a, b, c))
+ # Trying to import module
+ module = import_module(sig, cache_dir="test_cache")
+ if module is None:
+ print("Defining code")
+ c_code = """
+ class Sum {
+ public:
+ virtual double sum(double a, double b){
+ return a+b;
+ }
+ };
-
-class Sub(Sum):
- def __init__(self):
- Sum.__init__(self)
-
- def sum(self, a, b):
- print("sub")
- return a-b;
-
-
-
-sub = Sub()
-a = 3.7
-b = 4.8
-c = use_Sum(sub, a, b)
-print("The sub of %g and %g is %g"% (a, b, c))
+ double use_Sum(Sum& sum, double a, double b) {
+ return sum.sum(a,b);
+ }
+ """
+ print("Compiling code")
+ module = build_module(code=c_code, signature=sig, cache_dir="test_cache")
+
+ # Testing module
+ Sum = module.Sum
+ use_Sum = module.use_Sum
+
+ sum = Sum()
+ a = 3.7
+ b = 4.8
+ c = use_Sum(sum, a, b)
+ print("The sum of %g and %g is %g"% (a, b, c))
+
+ class Sub(Sum):
+ def __init__(self):
+ Sum.__init__(self)
+
+ def sum(self, a, b):
+ print("sub")
+ return a-b;
+
+ sub = Sub()
+ a = 3.7
+ b = 4.8
+ c = use_Sum(sub, a, b)
+ print("The sub of %g and %g is %g"% (a, b, c))
diff --git a/test/test17.py b/test/test17.py
old mode 100755
new mode 100644
index f014f39..3d48759
--- a/test/test17.py
+++ b/test/test17.py
@@ -1,39 +1,38 @@
-#!/usr/bin/python
-
from __future__ import print_function
+import pytest
from time import time
from instant import build_module, import_module
-_t = None
-def tic():
- global _t
- _t = -time()
+def test_repeated_build():
+ #_t = None
+ def tic():
+ global _t
+ _t = -time()
-def toc(msg=""):
- t = time() + _t
- print("t = %f (%s)" % (t, msg))
- return t
+ def toc(msg=""):
+ t = time() + _t
+ print("t = %f (%s)" % (t, msg))
+ return t
-c_code = """
+ c_code = """
double sum(double a, double b)
{
return a+b;
}
-"""
-
-# Time a few builds
-tic()
-module = build_module(code=c_code)
-t1 = toc("first build")
+ """
-tic()
-module = build_module(code=c_code)
-t2 = toc("second build")
+ # Time a few builds
+ tic()
+ module = build_module(code=c_code)
+ t1 = toc("first build")
-tic()
-module = build_module(code=c_code)
-t3 = toc("third build")
+ tic()
+ module = build_module(code=c_code)
+ t2 = toc("second build")
-assert t1 > t2
-assert t1 > t3
+ tic()
+ module = build_module(code=c_code)
+ t3 = toc("third build")
+ assert t1 > t2
+ assert t1 > t3
diff --git a/test/test18.py b/test/test18.py
old mode 100755
new mode 100644
index a9f82c9..0249ea8
--- a/test/test18.py
+++ b/test/test18.py
@@ -1,76 +1,76 @@
-#!/usr/bin/python
-
from __future__ import print_function
+import pytest
import time
from instant import build_module, import_module
-_t = None
-def tic():
- global _t
- _t = -time.time()
-def toc(msg=""):
- t = time.time() + _t
- print("t = %f (%s)" % (t, msg))
- return t
+def test_timing():
+ #_t = None
+ def tic():
+ global _t
+ _t = -time.time()
+
+ def toc(msg=""):
+ t = time.time() + _t
+ print("t = %f (%s)" % (t, msg))
+ return t
-c_code = """
+ c_code = """
double sum(double a, double b)
{
return a+b;
}
-"""
+ """
+
+ class Sig:
+ def __init__(self, sig):
+ self.sig = sig
+
+ def signature(self):
+ time.sleep(1.0)
+ return self.sig
-class Sig:
- def __init__(self, sig):
- self.sig = sig
-
- def signature(self):
- time.sleep(1.0)
- return self.sig
-
- def __hash__(self):
- time.sleep(0.5)
- return hash(self.sig)
-
- def __cmp__(self, other):
- if isinstance(other, Sig):
- return cmp(self.sig, other.sig)
- return -1
+ def __hash__(self):
+ time.sleep(0.5)
+ return hash(self.sig)
-sig = Sig("((test18.py signature))")
-cache_dir = "test_cache"
+ def __cmp__(self, other):
+ if isinstance(other, Sig):
+ return cmp(self.sig, other.sig)
+ return -1
-# Time a few builds
-tic()
-module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
-assert module is not None
-t1 = toc("first build")
+ sig = Sig("((test18.py signature))")
+ cache_dir = "test_cache"
-tic()
-module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
-assert module is not None
-t2 = toc("second build")
+ # Time a few builds
+ tic()
+ module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
+ assert module is not None
+ t1 = toc("first build")
-tic()
-module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
-assert module is not None
-t3 = toc("third build")
+ tic()
+ module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
+ assert module is not None
+ t2 = toc("second build")
-# Time importing
-tic()
-module = import_module(sig, cache_dir)
-assert module is not None
-t4 = toc("first import")
+ tic()
+ module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
+ assert module is not None
+ t3 = toc("third build")
-tic()
-module = import_module(sig, cache_dir)
-assert module is not None
-t5 = toc("second import")
+ # Time importing
+ tic()
+ module = import_module(sig, cache_dir)
+ assert module is not None
+ t4 = toc("first import")
-assert t1 > 1
-assert t2 < 1 and t2 > 0.4
-assert t3 < 1 and t3 > 0.4
-assert t4 < 1 and t4 > 0.4
-assert t5 < 1 and t5 > 0.4
+ tic()
+ module = import_module(sig, cache_dir)
+ assert module is not None
+ t5 = toc("second import")
+ assert t1 > 1
+ assert t2 < 1 and t2 > 0.4
+ assert t3 < 1 and t3 > 0.4
+ assert t4 < 1 and t4 > 0.4
+ assert t5 < 1 and t5 > 0.4
diff --git a/test/test19.py b/test/test19.py
old mode 100755
new mode 100644
index c18a9e2..1fe4052
--- a/test/test19.py
+++ b/test/test19.py
@@ -1,139 +1,150 @@
-#!/usr/bin/python
-
from __future__ import print_function
+import pytest
import shutil
import time
-import os
+import os, sys
from instant import build_module, import_module
-_t = None
-def tic():
- global _t
- _t = -time.time()
+def test_build():
+
+ #_t = None
+ def tic():
+ global _t
+ _t = -time.time()
-def toc(msg=""):
- t = time.time() + _t
- print("t = %f (%s)" % (t, msg))
- return t
+ def toc(msg=""):
+ t = time.time() + _t
+ print("t = %f (%s)" % (t, msg))
+ return t
-c_code = """
+ c_code = """
double sum(double a, double b)
{
return a+b;
}
-"""
-
-class Sig:
- def __init__(self, sig):
- self.sig = sig
-
- def signature(self):
- time.sleep(1.0)
- return self.sig
-
- def __hash__(self):
- time.sleep(0.5)
- return hash(self.sig)
-
- def __cmp__(self, other):
- if isinstance(other, Sig):
- return cmp(self.sig, other.sig)
- return -1
-
-modulename = "test19_ext"
-cache_dir = "test19_cache"
-shutil.rmtree(cache_dir, ignore_errors=True)
-shutil.rmtree(modulename, ignore_errors=True)
-
-# Build and rebuild with explicit modulename
-tic()
-module = build_module(code=c_code, modulename=modulename, cache_dir=cache_dir)
-assert module is not None
-t1 = toc("(1) With modulename")
-tic()
-module = build_module(code=c_code, modulename=modulename, cache_dir=cache_dir)
-assert module is not None
-t2 = toc("(2) With modulename")
-assert t1 > t2
-
-# Try importing module in a separate python process
-cmd = 'python -c "import %s"' % modulename
-print(cmd)
-stat = os.system(cmd)
-assert stat == 0 # a
-
-# Build and rebuild with a valid filename as signature
-sig = "test19_signature_module"
-tic()
-module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
-assert module is not None
-t1 = toc("(1) With signature")
-tic()
-module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
-assert module is not None
-t2 = toc("(2) With signature")
-assert t1 > t2
-tic()
-module = import_module(sig, cache_dir)
-assert module is not None
-t3 = toc("(3) import_module")
-assert t1 > t3
-
-# Try importing module in a separate python process
-cmd = 'python -c "import instant; assert instant.import_module(\'%s\', \'%s\') is not None"' % (sig, cache_dir)
-print(cmd)
-stat = os.system(cmd)
-assert stat == 0 # b
-
-# Build and rebuild with generic signature string
-sig = "((test19_signature_module))"
-tic()
-module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
-assert module is not None
-t1 = toc("(1) With signature")
-tic()
-module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
-assert module is not None
-t2 = toc("(2) With signature")
-assert t1 > t2
-tic()
-module = import_module(sig, cache_dir)
-assert module is not None
-t3 = toc("(3) import_module")
-assert t1 > t3
-
-# Try importing module in a separate python process
-cmd = 'python -c "import instant; assert instant.import_module(\'%s\', \'%s\') is not None"' % (sig, cache_dir)
-print(cmd)
-stat = os.system(cmd)
-assert stat == 0 # c
-
-print("Skipping unit test, see https://bugs.launchpad.net/instant/+bug/518389")
-# Build and rebuild with generic signature object
-#sig = Sig("((test19_signature_module))")
-#tic()
-#module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
-#assert module is not None
-#t1 = toc("(1) With signature")
-#tic()
-#module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
-#assert module is not None
-#t2 = toc("(2) With signature")
-#assert t1 > t2
-#tic()
-#module = import_module(sig, cache_dir)
-#assert module is not None
-#t3 = toc("(3) import_module")
-#assert t1 > t3
-
-# Build and rebuild without modulename or signature
-tic()
-module = build_module(code=c_code, cache_dir=cache_dir)
-assert module is not None
-t1 = toc("(1) Without modulename or signature")
-tic()
-module = build_module(code=c_code, cache_dir=cache_dir)
-assert module is not None
-t2 = toc("(2) Without modulename or signature")
-assert t1 > t2
-
+ """
+
+ class Sig:
+ def __init__(self, sig):
+ self.sig = sig
+
+ def signature(self):
+ time.sleep(1.0)
+ return self.sig
+
+ def __hash__(self):
+ time.sleep(0.5)
+ return hash(self.sig)
+
+ def __cmp__(self, other):
+ if isinstance(other, Sig):
+ return cmp(self.sig, other.sig)
+ return -1
+
+ modulename = "test19_ext"
+ cache_dir = "test19_cache"
+ shutil.rmtree(cache_dir, ignore_errors=True)
+ shutil.rmtree(modulename, ignore_errors=True)
+
+ # Build and rebuild with explicit modulename
+ tic()
+ module = build_module(code=c_code, modulename=modulename,
+ cache_dir=cache_dir)
+ assert module is not None
+ t1 = toc("(1) With modulename")
+
+ tic()
+ module = build_module(code=c_code, modulename=modulename,
+ cache_dir=cache_dir)
+ assert module is not None
+ t2 = toc("(2) With modulename")
+ assert t1 > t2
+
+ # Try importing module in a separate python process
+ python_interp = sys.executable
+ cmd = python_interp + ' -c "import %s"' % modulename
+ print(cmd)
+ stat = os.system(cmd)
+ assert stat == 0 # a
+
+ # Build and rebuild with a valid filename as signature
+ sig = "test19_signature_module"
+ tic()
+ module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
+ assert module is not None
+ t1 = toc("(1) With signature")
+
+ tic()
+ module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
+ assert module is not None
+ t2 = toc("(2) With signature")
+ assert t1 > t2
+
+ tic()
+ module = import_module(sig, cache_dir)
+ assert module is not None
+ t3 = toc("(3) import_module")
+ assert t1 > t3
+
+ # Try importing module in a separate python process
+ python_interp = sys.executable
+ cmd = python_interp + ' -c "import instant; assert instant.import_module(\'%s\', \'%s\') is not None"' % (sig, cache_dir)
+ print(cmd)
+ stat = os.system(cmd)
+ assert stat == 0 # b
+
+ # Build and rebuild with generic signature string
+ sig = "((test19_signature_module))"
+ tic()
+ module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
+ assert module is not None
+ t1 = toc("(1) With signature")
+
+ tic()
+ module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
+ assert module is not None
+ t2 = toc("(2) With signature")
+ assert t1 > t2
+
+ tic()
+ module = import_module(sig, cache_dir)
+ assert module is not None
+ t3 = toc("(3) import_module")
+ assert t1 > t3
+
+ # Try importing module in a separate python process
+ python_interp = sys.executable
+ cmd = python_interp + ' -c "import instant; assert instant.import_module(\'%s\', \'%s\') is not None"' % (sig, cache_dir)
+ print(cmd)
+ stat = os.system(cmd)
+ assert stat == 0 # c
+
+ print("Skipping unit test, see https://bugs.launchpad.net/instant/+bug/518389")
+ # Build and rebuild with generic signature object
+ #sig = Sig("((test19_signature_module))")
+ #tic()
+ #module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
+ #assert module is not None
+ #t1 = toc("(1) With signature")
+ #tic()
+ #module = build_module(code=c_code, signature=sig, cache_dir=cache_dir)
+ #assert module is not None
+ #t2 = toc("(2) With signature")
+ #assert t1 > t2
+ #tic()
+ #module = import_module(sig, cache_dir)
+ #assert module is not None
+ #t3 = toc("(3) import_module")
+ #assert t1 > t3
+
+ # Build and rebuild without modulename or signature
+ tic()
+ module = build_module(code=c_code, cache_dir=cache_dir)
+ assert module is not None
+ t1 = toc("(1) Without modulename or signature")
+
+ tic()
+ module = build_module(code=c_code, cache_dir=cache_dir)
+ assert module is not None
+ t2 = toc("(2) Without modulename or signature")
+ assert t1 > t2
diff --git a/test/test2.py b/test/test2.py
deleted file mode 100755
index 519018f..0000000
--- a/test/test2.py
+++ /dev/null
@@ -1,37 +0,0 @@
-#!/usr/bin/env python
-
-from __future__ import print_function
-import numpy
-import time
-from instant import inline_with_numpy
-
-c_code = """
-double sum (int n1, double* array1){
- double tmp = 0.0;
- for (int i=0; i<n1; i++) {
- tmp += array1[i];
- }
- return tmp;
-}
-"""
-
-
-sum_func = inline_with_numpy(c_code, arrays = [['n1', 'array1']], cache_dir="test_cache")
-
-a = numpy.arange(10000000); a = numpy.sin(a)
-
-t1 = time.time()
-sum1 = sum_func(a)
-t2 = time.time()
-print('With instant:', t2-t1, 'seconds')
-
-t1 = time.time()
-sum2 = numpy.sum(a)
-t2 = time.time()
-print('With numpy: ', t2-t1, 'seconds')
-
-difference = abs(sum1 - sum2)
-print("The difference between the sums computed by numpy and instant is " + str(difference))
-
-
-
diff --git a/test/test20.py b/test/test20.py
old mode 100755
new mode 100644
index e2ef1bc..ece6830
--- a/test/test20.py
+++ b/test/test20.py
@@ -1,26 +1,24 @@
-#!/usr/bin/env python
-
from __future__ import print_function
-import numpy
+import numpy
import time
from instant import inline_module_with_numpy
c_code = """
double sum (int n1, double* array1){
- double tmp = 0.0;
- for (int i=0; i<n1; i++) {
- tmp += array1[i];
+ double tmp = 0.0;
+ for (int i=0; i<n1; i++) {
+ tmp += array1[i];
}
- return tmp;
+ return tmp;
}
double max(int n1, double* array1){
- double tmp = 0.0;
- for (int i=0; i<n1; i++) {
- if (array1[i] > tmp) {
- tmp = array1[i];
+ double tmp = 0.0;
+ for (int i=0; i<n1; i++) {
+ if (array1[i] > tmp) {
+ tmp = array1[i];
}
}
- return tmp;
+ return tmp;
}
"""
@@ -40,4 +38,3 @@ max = max_func(a)
print("sum ", sum)
print("max ", max)
-
diff --git a/test/test21.py b/test/test21.py
old mode 100755
new mode 100644
index a75fe02..f01d544
--- a/test/test21.py
+++ b/test/test21.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python
-
from __future__ import print_function
import sys, os, threading
from instant import inline
@@ -35,4 +33,3 @@ if __name__ == "__main__":
t.start()
for t in threads:
t.join()
-
diff --git a/test/test3.py b/test/test3.py
deleted file mode 100755
index 6fe60df..0000000
--- a/test/test3.py
+++ /dev/null
@@ -1,21 +0,0 @@
-#!/usr/bin/env python
-
-from __future__ import print_function
-import instant
-from instant import build_module
-
-c_code = """
-double sum(double a, double b){
- return a+b;
-}
-"""
-
-build_module(code=c_code, modulename='test3_ext',
- cppargs=['-pg', '-O3', '-g'], lddargs=['-pg'])
-
-from test3_ext import sum
-a = 3.7
-b = 4.8
-c = sum(a, b)
-print("The sum of %g and %g is %g" % (a, b, c))
-
diff --git a/test/test4.py b/test/test4.py
deleted file mode 100755
index e1adbda..0000000
--- a/test/test4.py
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/env python
-
-from __future__ import print_function
-from instant import build_module
-import numpy, sys
-from functools import reduce
-
-a = numpy.arange(10000000)
-a = numpy.sin(a)
-b = numpy.arange(10000000)
-b = numpy.cos(b)
-
-
-
-s = """
-PyObject* add(PyObject* a_, PyObject* b_){
- /*
- various checks
- */
- PyArrayObject* a=(PyArrayObject*) a_;
- PyArrayObject* b=(PyArrayObject*) b_;
-
- int n = a->dimensions[0];
-
- npy_intp dims[1];
- dims[0] = n;
- PyArrayObject* ret;
- ret = (PyArrayObject*) PyArray_SimpleNew(1, dims, PyArray_DOUBLE);
-
- int i;
- double aj;
- double bj;
- double *retj;
- for (i=0; i < n; i++) {
- retj = (double*)(ret->data+ret->strides[0]*i);
- aj = *(double *)(a->data+ a->strides[0]*i);
- bj = *(double *)(b->data+ b->strides[0]*i);
- *retj = aj + bj;
- }
-return PyArray_Return(ret);
-}
-"""
-
-test4_ext = build_module(code=s, system_headers=["numpy/arrayobject.h"],
- include_dirs=[numpy.get_include()],
- init_code='import_array();', modulename="test4_ext")
-
-import time
-
-t1 = time.time()
-d = test4_ext.add(a, b)
-t2 = time.time()
-
-print('With instant:', t2-t1, 'seconds')
-
-t1 = time.time()
-c = a+b
-t2 = time.time()
-
-print('With numpy: ', t2-t1, 'seconds')
-
-difference = abs(c - d)
-
-sum = reduce( lambda a, b: a+b, difference)
-print("The difference between the arrays computed by numpy and instant is " + str(sum))
-
diff --git a/test/test5.py b/test/test5.py
deleted file mode 100755
index e804533..0000000
--- a/test/test5.py
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/python
-
-from __future__ import print_function
-from instant import build_module
-import numpy
-import sys
-import time
-from functools import reduce
-
-
-c_code = """
-/* add function for vectors with all safety checks removed ..*/
-void add(int n1, double* array1, int n2, double* array2, int n3, double* array3){
- if ( n1 == n2 && n1 == n3 ) {
- for (int i=0; i<n1; i++) {
- array3[i] = array1[i] + array2[i];
- }
- }
- else {
- printf("The arrays should have the same size.");
- }
-
-}
-"""
-
-
-test5_ext = build_module(code=c_code, system_headers=["numpy/arrayobject.h"],
- cppargs=['-pg'], lddargs=['-pg'],
- include_dirs=[numpy.get_include()],
- init_code='import_array();', modulename='test5_ext',
- arrays = [['n1', 'array1'], ['n2', 'array2'], ['n3', 'array3']])
-
-from test5_ext import add
-add = test5_ext.add
-a = numpy.arange(10000000); a = numpy.sin(a)
-b = numpy.arange(10000000); b = numpy.cos(b)
-c = numpy.arange(10000000); c = numpy.cos(c)
-d = numpy.arange(10000000); d = numpy.cos(d)
-
-
-
-t1 = time.time()
-add(a, b, c)
-t2 = time.time()
-print('With instant:', t2-t1, 'seconds')
-
-t1 = time.time()
-numpy.add(a, b, d)
-t2 = time.time()
-print('With numpy: ', t2-t1, 'seconds')
-
-difference = abs(d - c)
-sum = reduce( lambda a, b: a+b, difference)
-print("The difference between the arrays computed by numpy and instant is " + str(sum))
-
-
diff --git a/test/test6.py b/test/test6.py
deleted file mode 100755
index f80e477..0000000
--- a/test/test6.py
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-
-from __future__ import print_function
-from instant import build_module
-import numpy as N
-import sys
-import time
-
-
-
-c_code = """
-/* add function for matrices with all safety checks removed ..*/
-void add(int x1, int y1, double* array1,
- int x2, int y2, double* array2,
- int x3, int y3, double* array3){
-
- for (int i=0; i<x1; i++) {
- for (int j=0; j<y1; j++) {
- *array3 = *array1 + *array2;
- array3++;
- array2++;
- array1++;
- }
- }
-}
-"""
-
-# Guess arrayobject is either in sys.prefix or /usr/local
-
-test6_ext = build_module(code=c_code, system_headers=["numpy/arrayobject.h"], cppargs=['-g'],
- include_dirs=[N.get_include()],
- init_code='import_array();', modulename='test6_ext',
- arrays = [['x1', 'y1', 'array1'],
- ['x2', 'y2', 'array2'],
- ['x3', 'y3', 'array3']])
-
-from test6_ext import add
-a = N.arange(4000000); a = N.sin(a); a.shape=(2000, 2000)
-b = N.arange(4000000); b = N.cos(b); b.shape=(2000, 2000)
-c = N.arange(4000000); c = N.cos(c); c.shape=(2000, 2000)
-d = N.arange(4000000); d = N.cos(d); d.shape=(2000, 2000)
-
-t1 = time.time()
-add(a, b, c)
-t2 = time.time()
-
-t3 = time.time()
-N.add(a, b, d)
-t4 = time.time()
-
-e = abs(d-c)
-e.shape=(4000000,)
-
-max_difference = max(e)
-print("The difference between the arrays computed by numpy and instant is ", max_difference)
-
-print('With instant:', t2-t1, 'seconds')
-print('With numpy: ', t4-t3, 'seconds')
-
diff --git a/test/test7.py b/test/test7.py
deleted file mode 100755
index 8ddfad7..0000000
--- a/test/test7.py
+++ /dev/null
@@ -1,76 +0,0 @@
-#!/usr/bin/python
-
-from __future__ import print_function
-import numpy as N
-import time
-from instant import build_module
-import sys
-from functools import reduce
-
-
-c_code = """
-void func(int n1, double* array1, int n2, double* array2){
- double a;
- if ( n1 == n2 ) {
- for (int i=0; i<n1; i++) {
- a = array1[i];
- array2[i] = sin(a) + cos(a) + tan(a);
- }
- } else {
- printf("The arrays should have the same size.");
- }
-}
-"""
-
-# Guess arrayobject is either in sys.prefix or /usr/local
-
-test7_ext = build_module(code=c_code, system_headers=["numpy/arrayobject.h"], cppargs='-g',
- include_dirs=[N.get_include()],
- init_code='import_array();', modulename='test7_ext',
- arrays = [['n1', 'array1'], ['n2', 'array2']])
-
-
-
-seed = 10000000.0
-
-
-a = N.arange(seed)
-t1 = time.time()
-b = N.sin(a) + N.cos(a) + N.tan(a)
-t2 = time.time()
-print("With NumPy: ", t2-t1, "seconds")
-
-
-from test7_ext import func
-
-c = N.arange(seed)
-t1 = time.time()
-func(a, c)
-t2 = time.time()
-print("With instant: ", t2-t1, "seconds")
-
-
-t1 = time.time()
-d = N.sin(a)
-d += N.cos(a)
-d += N.tan(a)
-t2 = time.time()
-print("With NumPy inplace aritmetic: ", t2-t1, "seconds")
-
-
-
-difference = abs(b - c)
-sum = reduce( lambda a, b: a+b, difference)
-print("The difference between the arrays computed by numpy and instant is " + str(sum))
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/test/test8.py b/test/test8.py
deleted file mode 100755
index 4f07119..0000000
--- a/test/test8.py
+++ /dev/null
@@ -1,42 +0,0 @@
-#!/usr/bin/python
-
-from __future__ import print_function
-from instant import build_module
-
-c_code = """
-class Sum {
-public:
- virtual double sum(double a, double b){
- return a+b;
- }
-};
-
-
-double use_Sum(Sum& sum, double a, double b) {
- return sum.sum(a,b);
-}
-"""
-
-test8_ext = build_module(code=c_code, modulename='test8_ext')
-
-from test8_ext import *
-sum = Sum()
-a = 3.7
-b = 4.8
-c = use_Sum(sum, a, b)
-print("The sum of %g and %g is %g"% (a, b, c))
-
-class Sub(Sum):
- def __init__(self):
- Sum.__init__(self)
-
- def sum(self, a, b):
- print("sub")
- return a-b;
-
-sub = Sub()
-a = 3.7
-b = 4.8
-c = use_Sum(sub, a, b)
-print("The sub of %g and %g is %g"% (a, b, c))
-
diff --git a/test/test_instant_system_calls.py b/test/test_instant_system_calls.py
index 1f15f73..59718e6 100644
--- a/test/test_instant_system_calls.py
+++ b/test/test_instant_system_calls.py
@@ -1,17 +1,14 @@
-#!/usr/bin/env python
-
from __future__ import print_function
import os
from instant import inline
-os.environ["INSTANT_SYSTEM_CALL_METHOD"] = "SUBPROCESS"
-add_func = inline("double add(double a, double b){ return a+b; }", cache_dir="test_cache")
-print("The sum of 3 and 4.5 is ", add_func(3, 4.5))
+def test_system_call_subprocess():
+ os.environ["INSTANT_SYSTEM_CALL_METHOD"] = "SUBPROCESS"
+ add_func = inline("double add(double a, double b){ return a+b; }", cache_dir="test_cache")
+ print("The sum of 3 and 4.5 is ", add_func(3, 4.5))
-os.environ["INSTANT_SYSTEM_CALL_METHOD"] = "OS_SYSTEM"
-add_func = inline("double add(double c, double d){ return c+d; }", cache_dir="test_cache")
-print("The sum of 3 and 4.5 is ", add_func(3, 4.5))
-os.environ["INSTANT_SYSTEM_CALL_METHOD"] = "COMMANDS"
-add_func = inline("double add(double e, double f){ return e+f; }", cache_dir="test_cache")
-print("The sum of 3 and 4.5 is ", add_func(3, 4.5))
+def test_system_call_os_system():
+ os.environ["INSTANT_SYSTEM_CALL_METHOD"] = "OS_SYSTEM"
+ add_func = inline("double add(double c, double d){ return c+d; }", cache_dir="test_cache")
+ print("The sum of 3 and 4.5 is ", add_func(3, 4.5))
diff --git a/test/test_ode.py b/test/test_ode.py
old mode 100755
new mode 100644
index f23ded2..400cb69
--- a/test/test_ode.py
+++ b/test/test_ode.py
@@ -1,43 +1,41 @@
-#!/usr/bin/python
-
from __future__ import print_function
from instant import inline_with_numpy
from numpy import *
import time
-def time_loop2(p, Q, A, B, dt, N, p0):
- p[0] = p0
- for i in range(1, N):
+def time_loop2(p, Q, A, B, dt, N, p0):
+ p[0] = p0
+ for i in range(1, N):
p[i] = p[i-1] + dt*(B*Q[i] - A*p[i-1])
c_code = """
-void time_loop(int n, double* p,
- int m, double* Q,
- double A, double B,
+void time_loop(int n, double* p,
+ int m, double* Q,
+ double A, double B,
double dt, int N, double p0)
{
if ( n != m ) {
- printf("n and m should be equal");
- return;
+ printf("n and m should be equal");
+ return;
}
if ( n != N ) {
- printf("n and N should be equal");
- return;
+ printf("n and N should be equal");
+ return;
}
- p[0] = p0;
- for (int i=1; i<n; i++) {
+ p[0] = p0;
+ for (int i=1; i<n; i++) {
p[i] = p[i-1] + dt*(B*Q[i] - A*p[i-1]);
}
}
"""
-N = 100000
+N = 100000
time_loop = inline_with_numpy(c_code, arrays = [['n', 'p'], ['m', 'Q']], cppargs='-g', cache_dir="test_cache")
p = zeros(N)
T = 20.0
-Q = sin(arange(0, T, T/N))+1
+Q = sin(arange(0, T, T/N))+1
t1 = time.time()
time_loop(p, Q, 1.0, 1.0, 1.0/N, N, 1.0)
@@ -50,13 +48,13 @@ time_loop2(p2, Q, 1.0, 1.0, 1.0/N, N, 1.0)
t2 = time.time()
print('With Python :', t2-t1, 'seconds')
-print('The max difference between p and p2 is ', max(abs(p - p2)))
+print('The max difference between p and p2 is ', max(abs(p - p2)))
-tt = arange(0, 1, 1.0/N)
+tt = arange(0, 1, 1.0/N)
a = """
-try:
+try:
import pylab
pylab.plot(tt, p)
pylab.plot(tt, Q)
@@ -65,11 +63,6 @@ try:
pylab.title('Pressure ')
#pylab.savefig('pressure_plot')
pylab.show()
-except:
+except:
print "To get a plot of the solution install pylab"
"""
-
-
-
-
-
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-science/packages/fenics/instant.git
More information about the debian-science-commits
mailing list