pax_global_header00006660000000000000000000000064122627773330014526gustar00rootroot0000000000000052 comment=1a32e6934315c50f67a4452d033888a9c4a6f7d8 instant-1.3.0/000077500000000000000000000000001226277733300132075ustar00rootroot00000000000000instant-1.3.0/.bzrignore000066400000000000000000000000201226277733300152010ustar00rootroot00000000000000build tests/**/ instant-1.3.0/.gitignore000066400000000000000000000000211226277733300151700ustar00rootroot00000000000000build/ tests/**/ instant-1.3.0/AUTHORS000066400000000000000000000003521226277733300142570ustar00rootroot00000000000000Main authors: Martin Alnæs (martinal@simula.no) Kent-Andre Mardal (kent-and@simula.no) Magne Westlie (magnew@simula.no) Ilmar Wilbers (ilmarw@simula.no) Suggestions, bugfixes etc: Johan Hake Anders Logg Johannes Ring Ola Skavhauginstant-1.3.0/COPYING000066400000000000000000000033271226277733300142470ustar00rootroot00000000000000Copyright (c) 2006-2009, Magne Westlie, Kent-Andre Mardal, Martin Alnæs, and Ilmar Wilbers, Simula Research Laboratory. All rights reserved. Instant is licensed under either the GNU LGPL Version 2.1, see http://www.gnu.org or the so-called BSD license which is the following: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Simula Research Laboratory nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. instant-1.3.0/ChangeLog000066400000000000000000000042771226277733300147730ustar00rootroot000000000000001.3.0 [2014-01-07] - Add file_lock which can be used within a with statement - Introduce set_log_level and deprecate set_logging_level 1.2.0 [2013-03-24] - Allow to use CMake instead of distutils/pkg-config 1.1.0 [2013-01-07] - Converting python2 syntax to python3 (run 2to3) - Patch to make instant work with python2 - Cache dir is now created if not existing 1.0.0 [2011-12-07] - Copy all files to ~/.instant/error/module_name when Instant fails - If environmental variable INSTANT_DISPLAY_COMPILE_LOG is set the content of compile.log will be displayed - Removed copying of compile.log to ~/.instant/error/ 1.0-beta2 [2011-10-28] - Added support for flufl.lock for NFS safe file locking 1.0-beta [2011-08-11] - Error log is now copied to ~/.instant/error/module_name/compile.log and ~/.instant/error/compile.log for easier retrieval 0.9.10 [2011-05-16] - Added support for setting swig binary and swig path 0.9.9 [2011-02-23] - Optimizations - Added support for VTK and VMTK 0.9.8 [2010-02-15] - Fix cache related memory leak 0.9.7 - Use typemaps from the NumPy SWIG interface file (numpy.i) enabling the use of many new data types. - Removed support for Numeric and numarray. 0.9.6 - Minor update with some new utility functions required by FFC. 0.9.5 - Restructured and rewritten much of the code. - Improved multilevel cache functionality. - Added instant-clean and instant-showcache scripts. 0.9.4 - Various new examples with swiginac and sympy implemented. - Bug fix on 64bit. Removed director flag by default. 0.9.3 - Implemented caching 0.9.2 - Bug fix for the JIT in FFC 0.9.1 - Added test example which demonstrate use of external C code. - Added flag to turn of regeneration of the interface file (useful during debugging) 0.9 - Port to Windows with mingw by laserjungle, some updates by Martin Alnæs, and some cleanup. 0.8 - Added support for NumPy and Numarray. 0.7 - Added functionality for the use of pkg-config files. 0.6 - Created a more user-friendly interface 0.5 - Added SWIG directors for cross language inheritance 0.4 - Added md5sum to avoid unnecessary compilation 0.3 - Support for NumPy arrays 0.2 - Fixed bug in setup script 0.1 - Initial release of Instant instant-1.3.0/README000066400000000000000000000007401226277733300140700ustar00rootroot00000000000000======= 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.5 or later, SWIG, and NumPy Optional dependencies ===================== To enable NFS safe file locking flufl.lock can be installed: https://launchpad.net/flufl.lock instant-1.3.0/TODO000066400000000000000000000013561226277733300137040ustar00rootroot00000000000000TODO: - Print error when tmp directory can't be deleted (in instant-clean). Maybe add username to tmp dir name suffix? /tmp on cluster contains instant directories of many users. - Keep a most recently used list add a max cache size option to ~/.instant/intantrc clean up the oldest modules whenever we exceed this quota - Add argument to provide a cache subfolder name. Then instant-clean can take an argument to clean only the "ffc" cache subfolder etc. - Does instant handle full disk properly? (Does any software? Define properly!) - Fix arguments not used in setup.py - Use object files argument. - Improve documentation - Add tests for all variants of cache mechanisms available now - Clean up imports, don't use import * instant-1.3.0/doc/000077500000000000000000000000001226277733300137545ustar00rootroot00000000000000instant-1.3.0/doc/Instant.html000066400000000000000000000102531226277733300162630ustar00rootroot00000000000000The Instant C/C++ in Python
Local
Documentation
Download
Global
Python
NumPy
Numarray
SWIG
Simula Research Laboratory

Instant inlining of C/C++ code in Python

News

Release 0.9 (3/01/07): Port to Windows with mingw pluss some added functionality and clean up.
Release 0.8 (5/10/06): Added support for NumPy and Numarray. Release 0.7 (12/09/06): Added functionality for the use of pkg-config files.
Release 0.6 (17/07/06): Cleanup of the user interface.
Release 0.5 (10/03/06): Instant uses SWIG directors for cross language inheritance.
Release 0.4 (03/01/05): Added md5sums to avoid unnecessary compilation.
Release 0.3 (27/11/05): Instant supports Numeric arrays.

Appetizer

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.

Example of use:

from Instant import inline

add_func = inline("double add(double a, double b){ return a+b; }") 

print "The sum of 3 and 4.5 is ", add_func(3, 4.5)  

Example with NumPy arrays converted to C double arrays:
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']])

a = numpy.arange(10000000); a = numpy.sin(a)

sum1 = sum_func(a)

On my machine, the above example is about twice as fast as using the sum function implemented in NumPy. This comparison is of course not fair, since there are no safety checks in the above example. The comparison is implemented in the file test9.py that comes with the Instant package. The old package Numeric is about as slow as NumPy (test2.py), while the same example with Numarray is about as fast as with Instant (test10.py).

Requirement

Instant requires Python and SWIG. It has only been tested with Python 2.3 and 2.4 and SWIG 1.3.24 or newer. It only runs on Unix systems.

Related Projects

The weave module in SciPy
The PyInline module
The PyRex module


Magne Westlie
Kent-Andre Mardal
instant-1.3.0/doc/html_reference/000077500000000000000000000000001226277733300167365ustar00rootroot00000000000000instant-1.3.0/doc/html_reference/api-objects.txt000066400000000000000000000332111226277733300216770ustar00rootroot00000000000000instant instant-module.html instant.delete_temp_dir instant.paths-module.html#delete_temp_dir instant.get_instant_dir instant.paths-module.html#get_instant_dir instant.instant_debug instant.output-module.html#instant_debug instant.place_module_in_memory_cache instant.cache-module.html#place_module_in_memory_cache instant.modulename_from_checksum instant.cache-module.html#modulename_from_checksum instant.write_file instant.output-module.html#write_file instant.instant_assert instant.output-module.html#instant_assert instant.set_logging_level instant.output-module.html#set_logging_level instant.check_disk_cache instant.cache-module.html#check_disk_cache instant.get_default_cache_dir instant.paths-module.html#get_default_cache_dir instant.get_temp_dir instant.paths-module.html#get_temp_dir instant.strip_strings instant.build-module.html#strip_strings instant.memory_cached_module instant.cache-module.html#memory_cached_module instant.assert_is_str instant.build-module.html#assert_is_str instant.reindent instant.codegeneration-module.html#reindent instant.inline_module instant.inlining-module.html#inline_module instant.instant_error instant.output-module.html#instant_error instant.__package__ instant-module.html#__package__ instant.get_logger instant.output-module.html#get_logger instant.validate_cache_dir instant.paths-module.html#validate_cache_dir instant.check_swig_version instant.config-module.html#check_swig_version instant.recompile instant.build-module.html#recompile instant.copy_files instant.build-module.html#copy_files instant.assert_is_str_list instant.build-module.html#assert_is_str_list instant.get_swig_version instant.config-module.html#get_swig_version instant.instant_info instant.output-module.html#instant_info instant.cached_modules instant.cache-module.html#cached_modules instant.get_func_name instant.inlining-module.html#get_func_name instant.header_and_libs_from_pkgconfig instant.config-module.html#header_and_libs_from_pkgconfig instant.write_setup instant.codegeneration-module.html#write_setup instant.check_memory_cache instant.cache-module.html#check_memory_cache instant.inline_module_with_numpy instant.inlining-module.html#inline_module_with_numpy instant.is_valid_module_name instant.cache-module.html#is_valid_module_name instant.import_module_directly instant.cache-module.html#import_module_directly instant.get_lock instant.locking-module.html#get_lock instant.copy_to_cache instant.build-module.html#copy_to_cache instant.import_and_cache_module instant.cache-module.html#import_and_cache_module instant.instant_warning instant.output-module.html#instant_warning instant.assert_is_bool instant.build-module.html#assert_is_bool instant.import_module instant.cache-module.html#import_module instant.get_log_handler instant.output-module.html#get_log_handler instant.inline_with_numpy instant.inlining-module.html#inline_with_numpy instant.write_interfacefile instant.codegeneration-module.html#write_interfacefile instant.mapstrings instant.codegeneration-module.html#mapstrings instant.set_log_handler instant.output-module.html#set_log_handler instant.checksum_from_modulename instant.cache-module.html#checksum_from_modulename instant.release_lock instant.locking-module.html#release_lock instant.inline instant.inlining-module.html#inline instant.get_status_output instant.output-module.html#get_status_output instant.build_module instant.build-module.html#build_module instant.arg_strings instant.build-module.html#arg_strings instant.compute_checksum instant.signatures-module.html#compute_checksum instant.build instant.build-module.html instant.build.delete_temp_dir instant.paths-module.html#delete_temp_dir instant.build.get_instant_dir instant.paths-module.html#get_instant_dir instant.build.instant_debug instant.output-module.html#instant_debug instant.build.place_module_in_memory_cache instant.cache-module.html#place_module_in_memory_cache instant.build.write_file instant.output-module.html#write_file instant.build.instant_assert instant.output-module.html#instant_assert instant.build.set_logging_level instant.output-module.html#set_logging_level instant.build.check_disk_cache instant.cache-module.html#check_disk_cache instant.build.get_default_cache_dir instant.paths-module.html#get_default_cache_dir instant.build.get_temp_dir instant.paths-module.html#get_temp_dir instant.build.strip_strings instant.build-module.html#strip_strings instant.build.memory_cached_module instant.cache-module.html#memory_cached_module instant.build.assert_is_str instant.build-module.html#assert_is_str instant.build.reindent instant.codegeneration-module.html#reindent instant.build.__package__ instant.build-module.html#__package__ instant.build.get_logger instant.output-module.html#get_logger instant.build.copy_files instant.build-module.html#copy_files instant.build.validate_cache_dir instant.paths-module.html#validate_cache_dir instant.build.write_interfacefile instant.codegeneration-module.html#write_interfacefile instant.build.modulename_from_checksum instant.cache-module.html#modulename_from_checksum instant.build.assert_is_str_list instant.build-module.html#assert_is_str_list instant.build.instant_info instant.output-module.html#instant_info instant.build.cached_modules instant.cache-module.html#cached_modules instant.build.recompile instant.build-module.html#recompile instant.build.header_and_libs_from_pkgconfig instant.config-module.html#header_and_libs_from_pkgconfig instant.build.write_setup instant.codegeneration-module.html#write_setup instant.build.check_memory_cache instant.cache-module.html#check_memory_cache instant.build.instant_error instant.output-module.html#instant_error instant.build.is_valid_module_name instant.cache-module.html#is_valid_module_name instant.build.import_module_directly instant.cache-module.html#import_module_directly instant.build.get_lock instant.locking-module.html#get_lock instant.build.copy_to_cache instant.build-module.html#copy_to_cache instant.build.import_and_cache_module instant.cache-module.html#import_and_cache_module instant.build.instant_warning instant.output-module.html#instant_warning instant.build.assert_is_bool instant.build-module.html#assert_is_bool instant.build.import_module instant.cache-module.html#import_module instant.build.get_log_handler instant.output-module.html#get_log_handler instant.build.mapstrings instant.codegeneration-module.html#mapstrings instant.build.set_log_handler instant.output-module.html#set_log_handler instant.build.checksum_from_modulename instant.cache-module.html#checksum_from_modulename instant.build.release_lock instant.locking-module.html#release_lock instant.build.get_status_output instant.output-module.html#get_status_output instant.build.build_module instant.build-module.html#build_module instant.build.arg_strings instant.build-module.html#arg_strings instant.build.compute_checksum instant.signatures-module.html#compute_checksum instant.cache instant.cache-module.html instant.cache.instant_debug instant.output-module.html#instant_debug instant.cache.place_module_in_memory_cache instant.cache-module.html#place_module_in_memory_cache instant.cache.instant_assert instant.output-module.html#instant_assert instant.cache.check_disk_cache instant.cache-module.html#check_disk_cache instant.cache.get_default_cache_dir instant.paths-module.html#get_default_cache_dir instant.cache.validate_cache_dir instant.paths-module.html#validate_cache_dir instant.cache.memory_cached_module instant.cache-module.html#memory_cached_module instant.cache.is_valid_module_name instant.cache-module.html#is_valid_module_name instant.cache.__package__ instant.cache-module.html#__package__ instant.cache.modulename_from_checksum instant.cache-module.html#modulename_from_checksum instant.cache.cached_modules instant.cache-module.html#cached_modules instant.cache.check_memory_cache instant.cache-module.html#check_memory_cache instant.cache._modulename_prefix instant.cache-module.html#_modulename_prefix instant.cache.import_module_directly instant.cache-module.html#import_module_directly instant.cache.get_lock instant.locking-module.html#get_lock instant.cache.import_and_cache_module instant.cache-module.html#import_and_cache_module instant.cache.instant_warning instant.output-module.html#instant_warning instant.cache._memory_cache instant.cache-module.html#_memory_cache instant.cache.checksum_from_modulename instant.cache-module.html#checksum_from_modulename instant.cache.release_lock instant.locking-module.html#release_lock instant.cache.import_module instant.cache-module.html#import_module instant.cache.compute_checksum instant.signatures-module.html#compute_checksum instant.codegeneration instant.codegeneration-module.html instant.codegeneration._test_write_interfacefile instant.codegeneration-module.html#_test_write_interfacefile instant.codegeneration.instant_warning instant.output-module.html#instant_warning instant.codegeneration.instant_debug instant.output-module.html#instant_debug instant.codegeneration.write_interfacefile instant.codegeneration-module.html#write_interfacefile instant.codegeneration.mapstrings instant.codegeneration-module.html#mapstrings instant.codegeneration.__package__ instant.codegeneration-module.html#__package__ instant.codegeneration.instant_assert instant.output-module.html#instant_assert instant.codegeneration.write_file instant.output-module.html#write_file instant.codegeneration.write_setup instant.codegeneration-module.html#write_setup instant.codegeneration._test_write_setup instant.codegeneration-module.html#_test_write_setup instant.codegeneration.reindent instant.codegeneration-module.html#reindent instant.config instant.config-module.html instant.config.get_swig_version instant.config-module.html#get_swig_version instant.config.header_and_libs_from_pkgconfig instant.config-module.html#header_and_libs_from_pkgconfig instant.config.__package__ instant.config-module.html#__package__ instant.config.check_swig_version instant.config-module.html#check_swig_version instant.config.get_status_output instant.output-module.html#get_status_output instant.inlining instant.inlining-module.html instant.inlining.inline_module instant.inlining-module.html#inline_module instant.inlining.instant_warning instant.output-module.html#instant_warning instant.inlining.inline_with_numpy instant.inlining-module.html#inline_with_numpy instant.inlining.get_func_name instant.inlining-module.html#get_func_name instant.inlining.instant_error instant.output-module.html#instant_error instant.inlining.__package__ instant.inlining-module.html#__package__ instant.inlining.inline_module_with_numpy instant.inlining-module.html#inline_module_with_numpy instant.inlining.instant_assert instant.output-module.html#instant_assert instant.inlining.inline instant.inlining-module.html#inline instant.inlining.build_module instant.build-module.html#build_module instant.locking instant.locking-module.html instant.locking._lock_names instant.locking-module.html#_lock_names instant.locking._lock_files instant.locking-module.html#_lock_files instant.locking.instant_debug instant.output-module.html#instant_debug instant.locking.__package__ instant.locking-module.html#__package__ instant.locking.instant_error instant.output-module.html#instant_error instant.locking.instant_assert instant.output-module.html#instant_assert instant.locking.release_lock instant.locking-module.html#release_lock instant.locking._lock_count instant.locking-module.html#_lock_count instant.locking.get_lock instant.locking-module.html#get_lock instant.locking.release_all_locks instant.locking-module.html#release_all_locks instant.locking.validate_cache_dir instant.paths-module.html#validate_cache_dir instant.output instant.output-module.html instant.output.instant_info instant.output-module.html#instant_info instant.output.write_file instant.output-module.html#write_file instant.output.get_log_handler instant.output-module.html#get_log_handler instant.output.instant_debug instant.output-module.html#instant_debug instant.output._loghandler instant.output-module.html#_loghandler instant.output.__package__ instant.output-module.html#__package__ instant.output.get_logger instant.output-module.html#get_logger instant.output.instant_assert instant.output-module.html#instant_assert instant.output._log instant.output-module.html#_log instant.output.instant_error instant.output-module.html#instant_error instant.output.get_status_output instant.output-module.html#get_status_output instant.output.set_log_handler instant.output-module.html#set_log_handler instant.output.set_logging_level instant.output-module.html#set_logging_level instant.output.instant_warning instant.output-module.html#instant_warning instant.paths instant.paths-module.html instant.paths.delete_temp_dir instant.paths-module.html#delete_temp_dir instant.paths._tmp_dir instant.paths-module.html#_tmp_dir instant.paths.get_instant_dir instant.paths-module.html#get_instant_dir instant.paths._test instant.paths-module.html#_test instant.paths.__package__ instant.paths-module.html#__package__ instant.paths.validate_cache_dir instant.paths-module.html#validate_cache_dir instant.paths.instant_assert instant.output-module.html#instant_assert instant.paths.get_default_cache_dir instant.paths-module.html#get_default_cache_dir instant.paths.instant_debug instant.output-module.html#instant_debug instant.paths.get_temp_dir instant.paths-module.html#get_temp_dir instant.signatures instant.signatures-module.html instant.signatures.instant_debug instant.output-module.html#instant_debug instant.signatures.__package__ instant.signatures-module.html#__package__ instant.signatures.instant_error instant.output-module.html#instant_error instant.signatures.instant_assert instant.output-module.html#instant_assert instant.signatures._test instant.signatures-module.html#_test instant.signatures.compute_checksum instant.signatures-module.html#compute_checksum instant-1.3.0/doc/html_reference/class-tree.html000066400000000000000000000232111226277733300216650ustar00rootroot00000000000000 Class Hierarchy
 
[hide private]
[frames] | no frames]
[ Module Hierarchy | Class Hierarchy ]

Class Hierarchy

instant-1.3.0/doc/html_reference/crarr.png000066400000000000000000000005241226277733300205560ustar00rootroot00000000000000PNG  IHDR eE,tEXtCreation TimeTue 22 Aug 2006 00:43:10 -0500` XtIME)} pHYsnu>gAMA aEPLTEðf4sW ЊrD`@bCܖX{`,lNo@xdE螊dƴ~TwvtRNS@fMIDATxc`@0&+(;; /EXؑ? n  b;'+Y#(r<"IENDB`instant-1.3.0/doc/html_reference/epydoc.css000066400000000000000000000372271226277733300207460ustar00rootroot00000000000000 /* Epydoc CSS Stylesheet * * This stylesheet can be used to customize the appearance of epydoc's * HTML output. * */ /* Default Colors & Styles * - Set the default foreground & background color with 'body'; and * link colors with 'a:link' and 'a:visited'. * - Use bold for decision list terms. * - The heading styles defined here are used for headings *within* * docstring descriptions. All headings used by epydoc itself use * either class='epydoc' or class='toc' (CSS styles for both * defined below). */ body { background: #ffffff; color: #000000; } p { margin-top: 0.5em; margin-bottom: 0.5em; } a:link { color: #0000ff; } a:visited { color: #204080; } dt { font-weight: bold; } h1 { font-size: +140%; font-style: italic; font-weight: bold; } h2 { font-size: +125%; font-style: italic; font-weight: bold; } h3 { font-size: +110%; font-style: italic; font-weight: normal; } code { font-size: 100%; } /* N.B.: class, not pseudoclass */ a.link { font-family: monospace; } /* Page Header & Footer * - The standard page header consists of a navigation bar (with * pointers to standard pages such as 'home' and 'trees'); a * breadcrumbs list, which can be used to navigate to containing * classes or modules; options links, to show/hide private * variables and to show/hide frames; and a page title (using *

). The page title may be followed by a link to the * corresponding source code (using 'span.codelink'). * - The footer consists of a navigation bar, a timestamp, and a * pointer to epydoc's homepage. */ h1.epydoc { margin: 0; font-size: +140%; font-weight: bold; } h2.epydoc { font-size: +130%; font-weight: bold; } h3.epydoc { font-size: +115%; font-weight: bold; margin-top: 0.2em; } td h3.epydoc { font-size: +115%; font-weight: bold; margin-bottom: 0; } table.navbar { background: #a0c0ff; color: #000000; border: 2px groove #c0d0d0; } table.navbar table { color: #000000; } th.navbar-select { background: #70b0ff; color: #000000; } table.navbar a { text-decoration: none; } table.navbar a:link { color: #0000ff; } table.navbar a:visited { color: #204080; } span.breadcrumbs { font-size: 85%; font-weight: bold; } span.options { font-size: 70%; } span.codelink { font-size: 85%; } td.footer { font-size: 85%; } /* Table Headers * - Each summary table and details section begins with a 'header' * row. This row contains a section title (marked by * 'span.table-header') as well as a show/hide private link * (marked by 'span.options', defined above). * - Summary tables that contain user-defined groups mark those * groups using 'group header' rows. */ td.table-header { background: #70b0ff; color: #000000; border: 1px solid #608090; } td.table-header table { color: #000000; } td.table-header table a:link { color: #0000ff; } td.table-header table a:visited { color: #204080; } span.table-header { font-size: 120%; font-weight: bold; } th.group-header { background: #c0e0f8; color: #000000; text-align: left; font-style: italic; font-size: 115%; border: 1px solid #608090; } /* Summary Tables (functions, variables, etc) * - Each object is described by a single row of the table with * two cells. The left cell gives the object's type, and is * marked with 'code.summary-type'. The right cell gives the * object's name and a summary description. * - CSS styles for the table's header and group headers are * defined above, under 'Table Headers' */ table.summary { border-collapse: collapse; background: #e8f0f8; color: #000000; border: 1px solid #608090; margin-bottom: 0.5em; } td.summary { border: 1px solid #608090; } code.summary-type { font-size: 85%; } table.summary a:link { color: #0000ff; } table.summary a:visited { color: #204080; } /* Details Tables (functions, variables, etc) * - Each object is described in its own div. * - A single-row summary table w/ table-header is used as * a header for each details section (CSS style for table-header * is defined above, under 'Table Headers'). */ table.details { border-collapse: collapse; background: #e8f0f8; color: #000000; border: 1px solid #608090; margin: .2em 0 0 0; } table.details table { color: #000000; } table.details a:link { color: #0000ff; } table.details a:visited { color: #204080; } /* Fields */ dl.fields { margin-left: 2em; margin-top: 1em; margin-bottom: 1em; } dl.fields dd ul { margin-left: 0em; padding-left: 0em; } dl.fields dd ul li ul { margin-left: 2em; padding-left: 0em; } div.fields { margin-left: 2em; } div.fields p { margin-bottom: 0.5em; } /* Index tables (identifier index, term index, etc) * - link-index is used for indices containing lists of links * (namely, the identifier index & term index). * - index-where is used in link indices for the text indicating * the container/source for each link. * - metadata-index is used for indices containing metadata * extracted from fields (namely, the bug index & todo index). */ table.link-index { border-collapse: collapse; background: #e8f0f8; color: #000000; border: 1px solid #608090; } td.link-index { border-width: 0px; } table.link-index a:link { color: #0000ff; } table.link-index a:visited { color: #204080; } span.index-where { font-size: 70%; } table.metadata-index { border-collapse: collapse; background: #e8f0f8; color: #000000; border: 1px solid #608090; margin: .2em 0 0 0; } td.metadata-index { border-width: 1px; border-style: solid; } table.metadata-index a:link { color: #0000ff; } table.metadata-index a:visited { color: #204080; } /* Function signatures * - sig* is used for the signature in the details section. * - .summary-sig* is used for the signature in the summary * table, and when listing property accessor functions. * */ .sig-name { color: #006080; } .sig-arg { color: #008060; } .sig-default { color: #602000; } .summary-sig { font-family: monospace; } .summary-sig-name { color: #006080; font-weight: bold; } table.summary a.summary-sig-name:link { color: #006080; font-weight: bold; } table.summary a.summary-sig-name:visited { color: #006080; font-weight: bold; } .summary-sig-arg { color: #006040; } .summary-sig-default { color: #501800; } /* Subclass list */ ul.subclass-list { display: inline; } ul.subclass-list li { display: inline; } /* To render variables, classes etc. like functions */ table.summary .summary-name { color: #006080; font-weight: bold; font-family: monospace; } table.summary a.summary-name:link { color: #006080; font-weight: bold; font-family: monospace; } table.summary a.summary-name:visited { color: #006080; font-weight: bold; font-family: monospace; } /* Variable values * - In the 'variable details' sections, each varaible's value is * listed in a 'pre.variable' box. The width of this box is * restricted to 80 chars; if the value's repr is longer than * this it will be wrapped, using a backslash marked with * class 'variable-linewrap'. If the value's repr is longer * than 3 lines, the rest will be ellided; and an ellipsis * marker ('...' marked with 'variable-ellipsis') will be used. * - If the value is a string, its quote marks will be marked * with 'variable-quote'. * - If the variable is a regexp, it is syntax-highlighted using * the re* CSS classes. */ pre.variable { padding: .5em; margin: 0; background: #dce4ec; color: #000000; border: 1px solid #708890; } .variable-linewrap { color: #604000; font-weight: bold; } .variable-ellipsis { color: #604000; font-weight: bold; } .variable-quote { color: #604000; font-weight: bold; } .variable-group { color: #008000; font-weight: bold; } .variable-op { color: #604000; font-weight: bold; } .variable-string { color: #006030; } .variable-unknown { color: #a00000; font-weight: bold; } .re { color: #000000; } .re-char { color: #006030; } .re-op { color: #600000; } .re-group { color: #003060; } .re-ref { color: #404040; } /* Base tree * - Used by class pages to display the base class hierarchy. */ pre.base-tree { font-size: 80%; margin: 0; } /* Frames-based table of contents headers * - Consists of two frames: one for selecting modules; and * the other listing the contents of the selected module. * - h1.toc is used for each frame's heading * - h2.toc is used for subheadings within each frame. */ h1.toc { text-align: center; font-size: 105%; margin: 0; font-weight: bold; padding: 0; } h2.toc { font-size: 100%; font-weight: bold; margin: 0.5em 0 0 -0.3em; } /* Syntax Highlighting for Source Code * - doctest examples are displayed in a 'pre.py-doctest' block. * If the example is in a details table entry, then it will use * the colors specified by the 'table pre.py-doctest' line. * - Source code listings are displayed in a 'pre.py-src' block. * Each line is marked with 'span.py-line' (used to draw a line * down the left margin, separating the code from the line * numbers). Line numbers are displayed with 'span.py-lineno'. * The expand/collapse block toggle button is displayed with * 'a.py-toggle' (Note: the CSS style for 'a.py-toggle' should not * modify the font size of the text.) * - If a source code page is opened with an anchor, then the * corresponding code block will be highlighted. The code * block's header is highlighted with 'py-highlight-hdr'; and * the code block's body is highlighted with 'py-highlight'. * - The remaining py-* classes are used to perform syntax * highlighting (py-string for string literals, py-name for names, * etc.) */ pre.py-doctest { padding: .5em; margin: 1em; background: #e8f0f8; color: #000000; border: 1px solid #708890; } table pre.py-doctest { background: #dce4ec; color: #000000; } pre.py-src { border: 2px solid #000000; background: #f0f0f0; color: #000000; } .py-line { border-left: 2px solid #000000; margin-left: .2em; padding-left: .4em; } .py-lineno { font-style: italic; font-size: 90%; padding-left: .5em; } a.py-toggle { text-decoration: none; } div.py-highlight-hdr { border-top: 2px solid #000000; border-bottom: 2px solid #000000; background: #d8e8e8; } div.py-highlight { border-bottom: 2px solid #000000; background: #d0e0e0; } .py-prompt { color: #005050; font-weight: bold;} .py-more { color: #005050; font-weight: bold;} .py-string { color: #006030; } .py-comment { color: #003060; } .py-keyword { color: #600000; } .py-output { color: #404040; } .py-name { color: #000050; } .py-name:link { color: #000050 !important; } .py-name:visited { color: #000050 !important; } .py-number { color: #005000; } .py-defname { color: #000060; font-weight: bold; } .py-def-name { color: #000060; font-weight: bold; } .py-base-class { color: #000060; } .py-param { color: #000060; } .py-docstring { color: #006030; } .py-decorator { color: #804020; } /* Use this if you don't want links to names underlined: */ /*a.py-name { text-decoration: none; }*/ /* Graphs & Diagrams * - These CSS styles are used for graphs & diagrams generated using * Graphviz dot. 'img.graph-without-title' is used for bare * diagrams (to remove the border created by making the image * clickable). */ img.graph-without-title { border: none; } img.graph-with-title { border: 1px solid #000000; } span.graph-title { font-weight: bold; } span.graph-caption { } /* General-purpose classes * - 'p.indent-wrapped-lines' defines a paragraph whose first line * is not indented, but whose subsequent lines are. * - The 'nomargin-top' class is used to remove the top margin (e.g. * from lists). The 'nomargin' class is used to remove both the * top and bottom margin (but not the left or right margin -- * for lists, that would cause the bullets to disappear.) */ p.indent-wrapped-lines { padding: 0 0 0 7em; text-indent: -7em; margin: 0; } .nomargin-top { margin-top: 0; } .nomargin { margin-top: 0; margin-bottom: 0; } /* HTML Log */ div.log-block { padding: 0; margin: .5em 0 .5em 0; background: #e8f0f8; color: #000000; border: 1px solid #000000; } div.log-error { padding: .1em .3em .1em .3em; margin: 4px; background: #ffb0b0; color: #000000; border: 1px solid #000000; } div.log-warning { padding: .1em .3em .1em .3em; margin: 4px; background: #ffffb0; color: #000000; border: 1px solid #000000; } div.log-info { padding: .1em .3em .1em .3em; margin: 4px; background: #b0ffb0; color: #000000; border: 1px solid #000000; } h2.log-hdr { background: #70b0ff; color: #000000; margin: 0; padding: 0em 0.5em 0em 0.5em; border-bottom: 1px solid #000000; font-size: 110%; } p.log { font-weight: bold; margin: .5em 0 .5em 0; } tr.opt-changed { color: #000000; font-weight: bold; } tr.opt-default { color: #606060; } pre.log { margin: 0; padding: 0; padding-left: 1em; } instant-1.3.0/doc/html_reference/epydoc.js000066400000000000000000000245251226277733300205670ustar00rootroot00000000000000function toggle_private() { // Search for any private/public links on this page. Store // their old text in "cmd," so we will know what action to // take; and change their text to the opposite action. var cmd = "?"; var elts = document.getElementsByTagName("a"); for(var i=0; i...
"; elt.innerHTML = s; } } function toggle(id) { elt = document.getElementById(id+"-toggle"); if (elt.innerHTML == "-") collapse(id); else expand(id); return false; } function highlight(id) { var elt = document.getElementById(id+"-def"); if (elt) elt.className = "py-highlight-hdr"; var elt = document.getElementById(id+"-expanded"); if (elt) elt.className = "py-highlight"; var elt = document.getElementById(id+"-collapsed"); if (elt) elt.className = "py-highlight"; } function num_lines(s) { var n = 1; var pos = s.indexOf("\n"); while ( pos > 0) { n += 1; pos = s.indexOf("\n", pos+1); } return n; } // Collapse all blocks that mave more than `min_lines` lines. function collapse_all(min_lines) { var elts = document.getElementsByTagName("div"); for (var i=0; i 0) if (elt.id.substring(split, elt.id.length) == "-expanded") if (num_lines(elt.innerHTML) > min_lines) collapse(elt.id.substring(0, split)); } } function expandto(href) { var start = href.indexOf("#")+1; if (start != 0 && start != href.length) { if (href.substring(start, href.length) != "-") { collapse_all(4); pos = href.indexOf(".", start); while (pos != -1) { var id = href.substring(start, pos); expand(id); pos = href.indexOf(".", pos+1); } var id = href.substring(start, href.length); expand(id); highlight(id); } } } function kill_doclink(id) { var parent = document.getElementById(id); parent.removeChild(parent.childNodes.item(0)); } function auto_kill_doclink(ev) { if (!ev) var ev = window.event; if (!this.contains(ev.toElement)) { var parent = document.getElementById(this.parentID); parent.removeChild(parent.childNodes.item(0)); } } function doclink(id, name, targets_id) { var elt = document.getElementById(id); // If we already opened the box, then destroy it. // (This case should never occur, but leave it in just in case.) if (elt.childNodes.length > 1) { elt.removeChild(elt.childNodes.item(0)); } else { // The outer box: relative + inline positioning. var box1 = document.createElement("div"); box1.style.position = "relative"; box1.style.display = "inline"; box1.style.top = 0; box1.style.left = 0; // A shadow for fun var shadow = document.createElement("div"); shadow.style.position = "absolute"; shadow.style.left = "-1.3em"; shadow.style.top = "-1.3em"; shadow.style.background = "#404040"; // The inner box: absolute positioning. var box2 = document.createElement("div"); box2.style.position = "relative"; box2.style.border = "1px solid #a0a0a0"; box2.style.left = "-.2em"; box2.style.top = "-.2em"; box2.style.background = "white"; box2.style.padding = ".3em .4em .3em .4em"; box2.style.fontStyle = "normal"; box2.onmouseout=auto_kill_doclink; box2.parentID = id; // Get the targets var targets_elt = document.getElementById(targets_id); var targets = targets_elt.getAttribute("targets"); var links = ""; target_list = targets.split(","); for (var i=0; i" + target[0] + ""; } // Put it all together. elt.insertBefore(box1, elt.childNodes.item(0)); //box1.appendChild(box2); box1.appendChild(shadow); shadow.appendChild(box2); box2.innerHTML = "Which "+name+" do you want to see documentation for?" + ""; } return false; } function get_anchor() { var href = location.href; var start = href.indexOf("#")+1; if ((start != 0) && (start != href.length)) return href.substring(start, href.length); } function redirect_url(dottedName) { // Scan through each element of the "pages" list, and check // if "name" matches with any of them. for (var i=0; i-m" or "-c"; // extract the portion & compare it to dottedName. var pagename = pages[i].substring(0, pages[i].length-2); if (pagename == dottedName.substring(0,pagename.length)) { // We've found a page that matches `dottedName`; // construct its URL, using leftover `dottedName` // content to form an anchor. var pagetype = pages[i].charAt(pages[i].length-1); var url = pagename + ((pagetype=="m")?"-module.html": "-class.html"); if (dottedName.length > pagename.length) url += "#" + dottedName.substring(pagename.length+1, dottedName.length); return url; } } } instant-1.3.0/doc/html_reference/frames.html000066400000000000000000000011151226277733300210770ustar00rootroot00000000000000 API Documentation instant-1.3.0/doc/html_reference/help.html000066400000000000000000000260131226277733300205560ustar00rootroot00000000000000 Help
 
[hide private]
[frames] | no frames]

API Documentation

This document contains the API (Application Programming Interface) documentation for this project. Documentation for the Python objects defined by the project is divided into separate pages for each package, module, and class. The API documentation also includes two pages containing information about the project as a whole: a trees page, and an index page.

Object Documentation

Each Package Documentation page contains:

  • A description of the package.
  • A list of the modules and sub-packages contained by the package.
  • A summary of the classes defined by the package.
  • A summary of the functions defined by the package.
  • A summary of the variables defined by the package.
  • A detailed description of each function defined by the package.
  • A detailed description of each variable defined by the package.

Each Module Documentation page contains:

  • A description of the module.
  • A summary of the classes defined by the module.
  • A summary of the functions defined by the module.
  • A summary of the variables defined by the module.
  • A detailed description of each function defined by the module.
  • A detailed description of each variable defined by the module.

Each Class Documentation page contains:

  • A class inheritance diagram.
  • A list of known subclasses.
  • A description of the class.
  • A summary of the methods defined by the class.
  • A summary of the instance variables defined by the class.
  • A summary of the class (static) variables defined by the class.
  • A detailed description of each method defined by the class.
  • A detailed description of each instance variable defined by the class.
  • A detailed description of each class (static) variable defined by the class.

Project Documentation

The Trees page contains the module and class hierarchies:

  • The module hierarchy lists every package and module, with modules grouped into packages. At the top level, and within each package, modules and sub-packages are listed alphabetically.
  • The class hierarchy lists every class, grouped by base class. If a class has more than one base class, then it will be listed under each base class. At the top level, and under each base class, classes are listed alphabetically.

The Index page contains indices of terms and identifiers:

  • The term index lists every term indexed by any object's documentation. For each term, the index provides links to each place where the term is indexed.
  • The identifier index lists the (short) name of every package, module, class, method, function, variable, and parameter. For each identifier, the index provides a short description, and a link to its documentation.

The Table of Contents

The table of contents occupies the two frames on the left side of the window. The upper-left frame displays the project contents, and the lower-left frame displays the module contents:

Project
Contents
...
API
Documentation
Frame


Module
Contents
 
...
 

The project contents frame contains a list of all packages and modules that are defined by the project. Clicking on an entry will display its contents in the module contents frame. Clicking on a special entry, labeled "Everything," will display the contents of the entire project.

The module contents frame contains a list of every submodule, class, type, exception, function, and variable defined by a module or package. Clicking on an entry will display its documentation in the API documentation frame. Clicking on the name of the module, at the top of the frame, will display the documentation for the module itself.

The "frames" and "no frames" buttons below the top navigation bar can be used to control whether the table of contents is displayed or not.

The Navigation Bar

A navigation bar is located at the top and bottom of every page. It indicates what type of page you are currently viewing, and allows you to go to related pages. The following table describes the labels on the navigation bar. Note that not some labels (such as [Parent]) are not displayed on all pages.

Label Highlighted when... Links to...
[Parent] (never highlighted) the parent of the current package
[Package] viewing a package the package containing the current object
[Module] viewing a module the module containing the current object
[Class] viewing a class the class containing the current object
[Trees] viewing the trees page the trees page
[Index] viewing the index page the index page
[Help] viewing the help page the help page

The "show private" and "hide private" buttons below the top navigation bar can be used to control whether documentation for private objects is displayed. Private objects are usually defined as objects whose (short) names begin with a single underscore, but do not end with an underscore. For example, "_x", "__pprint", and "epydoc.epytext._tokenize" are private objects; but "re.sub", "__init__", and "type_" are not. However, if a module defines the "__all__" variable, then its contents are used to decide which objects are private.

A timestamp below the bottom navigation bar indicates when each page was last updated.

instant-1.3.0/doc/html_reference/identifier-index.html000066400000000000000000000657601226277733300230710ustar00rootroot00000000000000 Identifier Index
 
[hide private]
[frames] | no frames]

Identifier Index

[ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ ]

A

B

C

D

G

H

I

L

M

O

P

R

S

V

W

_



instant-1.3.0/doc/html_reference/index.html000066400000000000000000000011151226277733300207310ustar00rootroot00000000000000 API Documentation instant-1.3.0/doc/html_reference/instant-module.html000066400000000000000000000220521226277733300225700ustar00rootroot00000000000000 instant
Package instant
[hide private]
[frames] | no frames]

Package instant

source code

Instant allows compiled C/C++ modules to be created at runtime in your Python application, using SWIG to wrap the C/C++ code.

A simple example:

>>> from instant import inline
>>> add_func = inline("double add(double a, double b){ return a+b; }")
>>> print "The sum of 3 and 4.5 is ", add_func(3, 4.5)

The main functions are build_module, write_code, and inline* see their documentation for more details.

For more examples, see the tests/ directory in the Instant distribution.

Questions, bugs and patches should be sent to instant-dev@fenics.org.


Version: 0.9.7

Date: 2009-05-28

Author: Magne Westlie, Kent-Andre Mardal <kent-and@simula.no>, Martin Alnes <martinal@simula.no>, Ilmar M. Wilbers <ilmarw@simula.no>

Submodules [hide private]
  • instant.build: This module contains the main part of Instant, the build_module function.
  • instant.cache: This module contains helper functions for working with the module cache.
  • instant.codegeneration: This module contains helper functions for code generation.
  • instant.config: This module contains helper functions for configuration using pkg-config.
  • instant.inlining: This module contains the inline* functions, which allows easy inlining of C/C++ functions.
  • instant.locking: File locking for the cache system, to avoid problems when multiple processes work with the same module.
  • instant.output: This module contains internal logging utilities.
  • instant.paths: This module contains helper functions for working with temp and cache directories.
  • instant.signatures: This module contains helper functions for working with checksums.

Variables [hide private]
  __package__ = 'instant'
instant-1.3.0/doc/html_reference/instant-pysrc.html000066400000000000000000000245701226277733300224520ustar00rootroot00000000000000 instant
Package instant
[hide private]
[frames] | no frames]

Source Code for Package instant

 1  """ 
 2  Instant allows compiled C/C++ modules to be created 
 3  at runtime in your Python application, using SWIG to wrap the 
 4  C/C++ code. 
 5   
 6  A simple example: 
 7      >>> from instant import inline 
 8      >>> add_func = inline(\"double add(double a, double b){ return a+b; }\") 
 9      >>> print "The sum of 3 and 4.5 is ", add_func(3, 4.5) 
10   
11  The main functions are C{build_module}, C{write_code}, and 
12  C{inline*} see their documentation for more details. 
13   
14  For more examples, see the tests/ directory in the Instant distribution. 
15   
16  Questions, bugs and patches should be sent to instant-dev@fenics.org. 
17  """ 
18   
19  __authors__ = "Magne Westlie, Kent-Andre Mardal <kent-and@simula.no>, Martin Alnes <martinal@simula.no>, Ilmar M. Wilbers <ilmarw@simula.no>" 
20  __date__ = "2009-05-28" 
21  __version__ = "0.9.7" 
22   
23  # TODO: Import only the official interface 
24  from output import * 
25  from config import * 
26  from paths import * 
27  from signatures import * 
28  from cache import * 
29  from codegeneration import * 
30  from build import * 
31  from inlining import * 
32   

instant-1.3.0/doc/html_reference/instant.build-module.html000066400000000000000000000752051226277733300236760ustar00rootroot00000000000000 instant.build
Package instant :: Module build
[hide private]
[frames] | no frames]

Module build

source code

This module contains the main part of Instant, the build_module function.

Functions [hide private]
 
assert_is_str(x) source code
 
assert_is_bool(x) source code
 
assert_is_str_list(x) source code
 
strip_strings(x) source code
 
arg_strings(x) source code
 
copy_files(source, dest, files)
Copy a list of files from a source directory to a destination directory.
source code
 
recompile(modulename, module_path, setup_name, new_compilation_checksum)
Recompile module if the new checksum is different from the one in the checksum file in the module directory.
source code
 
copy_to_cache(module_path, cache_dir, modulename)
Copy module directory to cache.
source code
 
build_module(modulename=None, source_directory='.', code='', init_code='', additional_definitions='', additional_declarations='', sources=[], wrap_headers=[], local_headers=[], system_headers=[], include_dirs=['.'], library_dirs=[], libraries=[], swigargs=['-c++', '-fcompact', '-O', '-I.', '-small'], swig_include_dirs=[], cppargs=['-O2'], lddargs=[], object_files=[], arrays=[], generate_interface=True, generate_setup=True, signature=None, cache_dir=None)
Generate and compile a module from C/C++ code using SWIG.
source code
Variables [hide private]
  __package__ = 'instant'
Function Details [hide private]

copy_files(source, dest, files)

source code 

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.

build_module(modulename=None, source_directory='.', code='', init_code='', additional_definitions='', additional_declarations='', sources=[], wrap_headers=[], local_headers=[], system_headers=[], include_dirs=['.'], library_dirs=[], libraries=[], swigargs=['-c++', '-fcompact', '-O', '-I.', '-small'], swig_include_dirs=[], cppargs=['-O2'], lddargs=[], object_files=[], arrays=[], generate_interface=True, generate_setup=True, signature=None, cache_dir=None)

source code 

Generate and compile a module from C/C++ code using SWIG.

Arguments:

The keyword arguments are as follows:

  • modulename:
    • The name you want for the module. If specified, the module will not be cached. If missing, a name will be constructed based on a checksum of the other arguments, and the module will be placed in the global cache. String.
  • source_directory:
    • The directory where user supplied files reside. The files given in sources, wrap_headers, and local_headers are expected to exist in this directory. String.
  • code:
    • A string containing C or C++ code to be compiled and wrapped. String.
  • init_code:
    • Code that should be executed when the Instant module is imported. This code is inserted in the SWIG interface file, and is used for instance for calling import_array() used for the initialization of NumPy arrays. String.
  • additional_definitions:
    • Additional definitions (typically needed for inheritance) for interface file. These definitions should be given as triple-quoted strings in the case they span multiple lines, and are placed both in the initial block for C/C++ code (%{,%}-block), and the main section of the interface file. String.
  • additional_declarations:
    • Additional declarations (typically needed for inheritance) for interface file. These declarations should be given as triple-quoted strings in the case they span multiple lines, and are plaves in the main section of the interface file. String.
  • sources:
    • Source files to compile and link with the module. These files are compiled togehter with the SWIG-generated wrapper file into the final library file. Should reside in directory specified in source_directory. List of strings.
  • wrap_headers:
    • Local header files that should be wrapped by SWIG. The files specified will be included both in the initial block for C/C++ code (with a C directive) and in the main section of the interface file (with a SWIG directive). Should reside in directory specified in source_directory. List of strings.
  • local_headers:
    • Local header files required to compile the wrapped code. The files specified will be included in the initial block for C/C++ code (with a C directive). Should reside in directory specified in source_directory. List of strings.
  • system_headers:
    • System header files required to compile the wrapped code. The files specified will be included in the initial block for C/C++ code (with a C directive). List of strings.
  • include_dirs:
    • Directories to search for header files for building the extension module. Needs to be absolute path names. List of strings.
  • library_dirs:
    • Directories to search for libraries (-l) for building the extension module. Needs to be absolute paths. List of strings.
  • libraries:
    • Libraries needed by the Instant module. The libraries will be linked in from the shared object file. The initial -l is added automatically. List of strings.
  • swigargs:
    • List of arguments to swig, e.g. ["-lpointers.i"] to include the SWIG pointers.i library.
  • swig_include_dirs:
    • A list of directories to include in the 'swig' command.
  • cppargs:
    • List of arguments to the compiler, e.g. ["-Wall", "-fopenmp"].
  • lddargs:
    • List of arguments to the linker, e.g. ["-E", "-U"].
  • object_files:
    • If you want to compile the files yourself. TODO: Not yet supported.
  • arrays:
    • A nested list describing the C arrays to be made from NumPy arrays. If the NumPy array is 1D, the inner list should contain strings with the variable names for length of the array and the array itself. If the NumPy array is a matrix or a tensor, the inner list should contain strings with variable names for the number of dimensions, the length in each dimension, and the array itself, respectively.
  • generate_interface:
    • A bool to indicate if you want to generate the interface files.
  • generate_setup:
    • A bool to indicate if you want to generate the setup.py file.
  • signature:
    • A signature string to identify the form instead of the source code.
  • cache_dir:
    • A directory to look for cached modules and place new ones. If missing, a default directory is used. Note that the module will not be cached if modulename is specified. The cache directory should not be used for anything else.

instant-1.3.0/doc/html_reference/instant.build-pysrc.html000066400000000000000000004057171226277733300235560ustar00rootroot00000000000000 instant.build
Package instant :: Module build
[hide private]
[frames] | no frames]

Source Code for Module instant.build

  1  """This module contains the main part of Instant, the build_module function.""" 
  2   
  3  import os, sys, shutil, glob 
  4  from itertools import chain 
  5   
  6  # TODO: Import only the official interface 
  7  from output import * 
  8  from config import header_and_libs_from_pkgconfig 
  9  from paths import * 
 10  from signatures import * 
 11  from cache import * 
 12  from codegeneration import * 
 13  from locking import get_lock, release_lock 
 14       
15 -def assert_is_str(x):
16 instant_assert(isinstance(x, str), 17 "In instant.build_module: Expecting string.")
18
19 -def assert_is_bool(x):
20 instant_assert(isinstance(x, bool), 21 "In instant.build_module: Expecting bool.")
22
23 -def assert_is_str_list(x):
24 instant_assert(isinstance(x, (list, tuple)), 25 "In instant.build_module: Expecting sequence.") 26 instant_assert(all(isinstance(i, str) for i in x), 27 "In instant.build_module: Expecting sequence of strings.")
28
29 -def strip_strings(x):
30 assert_is_str_list(x) 31 return [s.strip() for s in x]
32
33 -def arg_strings(x):
34 if isinstance(x, str): 35 x = x.split() 36 return strip_strings(x)
37 38
39 -def copy_files(source, dest, files):
40 """Copy a list of files from a source directory to a destination directory. 41 This may seem a bit complicated, but a lot of this code is error checking.""" 42 if os.path.exists(dest): 43 overwriting = set(files) & set(glob.glob(os.path.join(dest, "*"))) 44 if overwriting: 45 instant_warning("In instant.copy_files: Path '%s' already exists, "\ 46 "overwriting existing files: %r." % (dest, list(overwriting))) 47 else: 48 os.mkdir(dest) 49 50 if source != dest: 51 instant_debug("In instant.copy_files: Copying files %r from %r to %r"\ 52 % (files, source, dest)) 53 54 for f in files: 55 a = os.path.join(source, f) 56 b = os.path.join(dest, f) 57 instant_assert(a != b, "In instant.copy_files: Seems like the "\ 58 "input files are absolute paths, should be relative to "\ 59 "source. (%r, %r)" % (a, b)) 60 instant_assert(os.path.isfile(a), "In instant.copy_files: "\ 61 "Missing source file '%s'." % a) 62 if os.path.isfile(b): 63 os.remove(b) 64 shutil.copyfile(a, b)
65 66
67 -def recompile(modulename, module_path, setup_name, new_compilation_checksum):
68 """Recompile module if the new checksum is different from 69 the one in the checksum file in the module directory.""" 70 # Check if the old checksum matches the new one 71 compilation_checksum_filename = "%s.checksum" % modulename 72 if os.path.exists(compilation_checksum_filename): 73 checksum_file = open(compilation_checksum_filename) 74 old_compilation_checksum = checksum_file.readline() 75 checksum_file.close() 76 if old_compilation_checksum == new_compilation_checksum: 77 return 78 79 # Verify that SWIG is on the system 80 (swig_stat, swig_out) = get_status_output("swig -version") 81 if swig_stat != 0: 82 instant_error("In instant.recompile: Could not find swig!"\ 83 " You can download swig from http://www.swig.org") 84 85 # Create log file for logging of compilation errors 86 compile_log_filename = os.path.join(module_path, "compile.log") 87 compile_log_file = open(compile_log_filename, "w") 88 try: 89 # Build module 90 cmd = "python %s build_ext" % setup_name 91 instant_info("--- Instant: compiling ---") 92 instant_debug("cmd = %s" % cmd) 93 ret, output = get_status_output(cmd) 94 compile_log_file.write(output) 95 compile_log_file.flush() 96 if ret != 0: 97 if os.path.exists(compilation_checksum_filename): 98 os.remove(compilation_checksum_filename) 99 instant_error("In instant.recompile: The module did not "\ 100 "compile, see '%s'" % compile_log_filename) 101 102 # 'Install' module 103 cmd = "python %s install --install-platlib=." % setup_name 104 instant_debug("cmd = %s" % cmd) 105 ret, output = get_status_output(cmd) 106 compile_log_file.write(output) 107 compile_log_file.flush() 108 if ret != 0: 109 if os.path.exists(compilation_checksum_filename): 110 os.remove(compilation_checksum_filename) 111 instant_error("In instant.recompile: Could not 'install' "\ 112 "the module, see '%s'" % compile_log_filename) 113 finally: 114 compile_log_file.close() 115 116 # Compilation succeeded, write new_compilation_checksum to checksum_file 117 write_file(compilation_checksum_filename, new_compilation_checksum)
118 119
120 -def copy_to_cache(module_path, cache_dir, modulename):
121 "Copy module directory to cache." 122 # Get lock, check if the module exists, _otherwise_ copy the 123 # finished compiled module from /tmp/foo to the cache directory, 124 # and then release lock 125 lock = get_lock(cache_dir, modulename) 126 127 # Validate the path 128 cache_module_path = os.path.join(cache_dir, modulename) 129 if os.path.exists(cache_module_path): 130 # This indicates a race condition has happened (and is being avoided!). 131 instant_warning("In instant.build_module: Path '%s' already exists,"\ 132 " but module wasn't found in cache previously. Not overwriting,"\ 133 " assuming this module is valid." % cache_module_path) 134 135 release_lock(lock) 136 return cache_module_path 137 138 # Not deleting anymore, relying on locking system 139 #shutil.rmtree(cache_module_path, ignore_errors=True) 140 141 # Error checks 142 instant_assert(os.path.isdir(module_path), "In instant.build_module:"\ 143 " Cannot copy non-existing directory %r!" % module_path) 144 instant_assert(not os.path.isdir(cache_module_path), 145 "In instant.build_module: Cache directory %r shouldn't exist "\ 146 "at this point!" % cache_module_path) 147 instant_debug("In instant.build_module: Copying built module from %r"\ 148 " to cache at %r" % (module_path, cache_module_path)) 149 150 # Do the copying 151 shutil.copytree(module_path, cache_module_path) 152 delete_temp_dir() 153 release_lock(lock) 154 return cache_module_path
155 156
157 -def build_module(modulename=None, source_directory=".", 158 code="", init_code="", 159 additional_definitions="", additional_declarations="", 160 sources=[], wrap_headers=[], 161 local_headers=[], system_headers=[], 162 include_dirs=['.'], library_dirs=[], libraries=[], 163 swigargs=['-c++', '-fcompact', '-O', '-I.', '-small'], 164 swig_include_dirs = [], 165 cppargs=['-O2'], lddargs=[], 166 object_files=[], arrays=[], 167 generate_interface=True, generate_setup=True, 168 signature=None, cache_dir=None):
169 """Generate and compile a module from C/C++ code using SWIG. 170 171 Arguments: 172 ========== 173 The keyword arguments are as follows: 174 - B{modulename}: 175 - The name you want for the module. 176 If specified, the module will not be cached. 177 If missing, a name will be constructed based on 178 a checksum of the other arguments, and the module 179 will be placed in the global cache. String. 180 - B{source_directory}: 181 - The directory where user supplied files reside. The files 182 given in B{sources}, B{wrap_headers}, and B{local_headers} 183 are expected to exist in this directory. String. 184 - B{code}: 185 - A string containing C or C++ code to be compiled and wrapped. String. 186 - B{init_code}: 187 - Code that should be executed when the Instant module is 188 imported. This code is inserted in the SWIG interface file, and is 189 used for instance for calling C{import_array()} used for the 190 initialization of NumPy arrays. String. 191 - B{additional_definitions}: 192 - Additional definitions (typically needed for inheritance) 193 for interface file. These definitions should be given as triple-quoted 194 strings in the case they span multiple lines, and are placed both in the 195 initial block for C/C++ code (C{%{,%}}-block), and the main section 196 of the interface file. String. 197 - B{additional_declarations}: 198 - Additional declarations (typically needed for inheritance) 199 for interface file. These declarations should be given as triple-quoted 200 strings in the case they span multiple lines, and are plaves in the main 201 section of the interface file. String. 202 - B{sources}: 203 - Source files to compile and link with the module. These 204 files are compiled togehter with the SWIG-generated wrapper file into 205 the final library file. Should reside in directory specified in 206 B{source_directory}. List of strings. 207 - B{wrap_headers}: 208 - Local header files that should be wrapped by SWIG. The 209 files specified will be included both in the initial block for C/C++ code 210 (with a C directive) and in the main section of the interface file (with 211 a SWIG directive). Should reside in directory specified in 212 B{source_directory}. List of strings. 213 - B{local_headers}: 214 - Local header files required to compile the wrapped 215 code. The files specified will be included in the initial block for 216 C/C++ code (with a C directive). Should reside in directory specified in 217 B{source_directory}. List of strings. 218 - B{system_headers}: 219 - System header files required to compile the wrapped 220 code. The files specified will be included in the initial block for C/C++ 221 code (with a C directive). List of strings. 222 - B{include_dirs}: 223 - Directories to search for header files for building the 224 extension module. Needs to be absolute path names. List of strings. 225 - B{library_dirs}: 226 - Directories to search for libraries (C{-l}) for building 227 the extension module. Needs to be absolute paths. List of strings. 228 - B{libraries}: 229 - Libraries needed by the Instant module. The libraries will 230 be linked in from the shared object file. The initial C{-l} is added 231 automatically. List of strings. 232 - B{swigargs}: 233 - List of arguments to swig, e.g. C{["-lpointers.i"]} 234 to include the SWIG pointers.i library. 235 - B{swig_include_dirs}: 236 - A list of directories to include in the 'swig' command. 237 - B{cppargs}: 238 - List of arguments to the compiler, e.g. C{["-Wall", "-fopenmp"]}. 239 - B{lddargs}: 240 - List of arguments to the linker, e.g. C{["-E", "-U"]}. 241 - B{object_files}: 242 - If you want to compile the files yourself. TODO: Not yet supported. 243 - B{arrays}: 244 - A nested list describing the C arrays to be made from NumPy arrays. 245 If the NumPy array is 1D, the inner list should contain strings with 246 the variable names for length of the array and the array itself. 247 If the NumPy array is a matrix or a tensor, the inner list should 248 contain strings with variable names for the number of dimensions, 249 the length in each dimension, and the array itself, respectively. 250 - B{generate_interface}: 251 - A bool to indicate if you want to generate the interface files. 252 - B{generate_setup}: 253 - A bool to indicate if you want to generate the setup.py file. 254 - B{signature}: 255 - A signature string to identify the form instead of the source code. 256 - B{cache_dir}: 257 - A directory to look for cached modules and place new ones. 258 If missing, a default directory is used. Note that the module 259 will not be cached if B{modulename} is specified. 260 The cache directory should not be used for anything else. 261 """ 262 263 # Store original directory to be able to restore later 264 original_path = os.getcwd() 265 266 # --- Validate arguments 267 268 instant_assert(modulename is None or isinstance(modulename, str), 269 "In instant.build_module: Expecting modulename to be string or None.") 270 assert_is_str(source_directory) 271 source_directory = os.path.abspath(source_directory) 272 assert_is_str(code) 273 assert_is_str(init_code) 274 assert_is_str(additional_definitions) 275 assert_is_str(additional_declarations) 276 sources = strip_strings(sources) 277 wrap_headers = strip_strings(wrap_headers) 278 local_headers = strip_strings(local_headers) 279 system_headers = strip_strings(system_headers) 280 include_dirs = strip_strings(include_dirs) 281 library_dirs = strip_strings(library_dirs) 282 libraries = strip_strings(libraries) 283 swigargs = arg_strings(swigargs) 284 swig_include_dirs = strip_strings(swig_include_dirs) 285 cppargs = arg_strings(cppargs) 286 lddargs = arg_strings(lddargs) 287 object_files = strip_strings(object_files) 288 arrays = [strip_strings(a) for a in arrays] 289 assert_is_bool(generate_interface) 290 assert_is_bool(generate_setup) 291 instant_assert( signature is None \ 292 or isinstance(signature, str) \ 293 or hasattr(signature, "signature"), 294 "In instant.build_module: Expecting modulename to be string or None.") 295 instant_assert(not (signature is not None and modulename is not None), 296 "In instant.build_module: Can't have both modulename and signature.") 297 298 # --- Replace arguments with defaults if necessary 299 300 cache_dir = validate_cache_dir(cache_dir) 301 302 # Split sources by file-suffix (.c or .cpp) 303 csrcs = [f for f in sources if f.endswith('.c') or f.endswith('.C')] 304 cppsrcs = [f for f in sources if f.endswith('.cpp') or f.endswith('.cxx')] 305 instant_assert(len(csrcs) + len(cppsrcs) == len(sources), 306 "In instant.build_module: Source files must have '.c' or '.cpp' suffix") 307 308 # --- Debugging code 309 instant_debug('In instant.build_module:') 310 instant_debug('::: Begin Arguments :::') 311 instant_debug(' modulename: %r' % modulename) 312 instant_debug(' source_directory: %r' % source_directory) 313 instant_debug(' code: %r' % code) 314 instant_debug(' init_code: %r' % init_code) 315 instant_debug(' additional_definitions: %r' % additional_definitions) 316 instant_debug(' additional_declarations: %r' % additional_declarations) 317 instant_debug(' sources: %r' % sources) 318 instant_debug(' csrcs: %r' % csrcs) 319 instant_debug(' cppsrcs: %r' % cppsrcs) 320 instant_debug(' wrap_headers: %r' % wrap_headers) 321 instant_debug(' local_headers: %r' % local_headers) 322 instant_debug(' system_headers: %r' % system_headers) 323 instant_debug(' include_dirs: %r' % include_dirs) 324 instant_debug(' library_dirs: %r' % library_dirs) 325 instant_debug(' libraries: %r' % libraries) 326 instant_debug(' swigargs: %r' % swigargs) 327 instant_debug(' swig_include_dirs: %r' % swig_include_dirs) 328 instant_debug(' cppargs: %r' % cppargs) 329 instant_debug(' lddargs: %r' % lddargs) 330 instant_debug(' object_files: %r' % object_files) 331 instant_debug(' arrays: %r' % arrays) 332 instant_debug(' generate_interface: %r' % generate_interface) 333 instant_debug(' generate_setup: %r' % generate_setup) 334 instant_debug(' signature: %r' % signature) 335 instant_debug(' cache_dir: %r' % cache_dir) 336 instant_debug('::: End Arguments :::') 337 338 # --- Setup module directory, making it and copying 339 # files to it if necessary, and compute a modulename 340 # if it isn't specified explicitly 341 342 if modulename is None: 343 # Compute a signature if we have none passed by the user: 344 if signature is None: 345 # Collect arguments used for checksum creation, 346 # including everything that affects the interface 347 # file generation and module compilation. 348 checksum_args = ( \ 349 # We don't care about the modulename, that's what we're trying to construct! 350 #modulename, 351 # We don't care where the user code resides: 352 #source_directory, 353 code, init_code, 354 additional_definitions, 355 additional_declarations, 356 # Skipping filenames, since we use the file contents: 357 #sources, wrap_headers, 358 #local_headers, 359 system_headers, 360 include_dirs, library_dirs, libraries, 361 swig_include_dirs, swigargs, cppargs, lddargs, 362 object_files, arrays, 363 generate_interface, generate_setup, 364 # The signature isn't defined, and the cache_dir doesn't affect the module: 365 #signature, cache_dir) 366 ) 367 allfiles = sources + wrap_headers + local_headers 368 allfiles = [os.path.join(source_directory, file) for file in allfiles] 369 text = "\n".join((str(a) for a in checksum_args)) 370 signature = modulename_from_checksum(compute_checksum(text, allfiles)) 371 modulename = signature 372 moduleids = [signature] 373 else: 374 module, moduleids = check_memory_cache(signature) 375 if module: return module 376 modulename = moduleids[-1] 377 378 # Look for module in disk cache 379 module = check_disk_cache(modulename, cache_dir, moduleids) 380 if module: return module 381 382 # Make a temporary module path for compilation 383 module_path = os.path.join(get_temp_dir(), modulename) 384 instant_assert(not os.path.exists(module_path), 385 "In instant.build_module: Not expecting module_path to exist: '%s'"\ 386 % module_path) 387 os.mkdir(module_path) 388 use_cache = True 389 else: 390 use_cache = False 391 moduleids = [] 392 module_path = os.path.join(original_path, modulename) 393 if not os.path.exists(module_path): 394 os.mkdir(module_path) 395 396 ## Look for module in memory cache 397 #module, moduleids = check_memory_cache(modulename) 398 #if module: return module 399 #instant_assert(modulename == moduleids[-1] and len(moduleids) == 1, "Logic breach.") 400 ## Look for module in local directory 401 #module = check_disk_cache(modulename, original_path, moduleids) 402 #if module: return module 403 404 # Wrapping rest of code in try-block to 405 # clean up at the end if something fails. 406 try: 407 # --- Copy user-supplied files to module path 408 409 module_path = os.path.abspath(module_path) 410 files_to_copy = sources + wrap_headers + local_headers + object_files 411 copy_files(source_directory, module_path, files_to_copy) 412 # At this point, all user input files should reside in module_path. 413 414 # --- Generate additional files in module directory 415 os.chdir(module_path) 416 417 # Generate __init__.py which imports compiled module contents 418 write_file("__init__.py", "from %s import *" % modulename) 419 420 # Generate SWIG interface if wanted 421 ifile_name = "%s.i" % modulename 422 if generate_interface: 423 write_interfacefile(ifile_name, modulename, code, init_code, 424 additional_definitions, additional_declarations, system_headers, 425 local_headers, wrap_headers, arrays) 426 427 # Generate setup.py if wanted 428 setup_name = "setup.py" 429 if generate_setup: 430 write_setup(setup_name, modulename, csrcs, cppsrcs, local_headers, \ 431 include_dirs, library_dirs, libraries, swig_include_dirs, \ 432 swigargs, cppargs, lddargs) 433 434 # --- Build module 435 436 # At this point we have all the files, and can make the 437 # total checksum from all file contents. This is used to 438 # decide whether the module needs recompilation or not. 439 440 # Compute new_compilation_checksum 441 # Collect arguments used for checksum creation, 442 # including everything that affects the module compilation. 443 # Since the interface file is included in allfiles, 444 # we don't need stuff that modifies it here. 445 checksum_args = ( \ 446 # We don't care about the modulename, that's what 447 # we're trying to construct! 448 #modulename, 449 # We don't care where the user code resides: 450 #source_directory, 451 #code, init_code, 452 #additional_definitions, additional_declarations, 453 # Skipping filenames, since we use the file contents: 454 #sources, wrap_headers, 455 #local_headers, 456 system_headers, 457 include_dirs, library_dirs, libraries, 458 swigargs, swig_include_dirs, cppargs, lddargs, 459 object_files, #arrays, 460 #generate_interface, generate_setup, 461 # The signature isn't defined, and the 462 # cache_dir doesn't affect the module: 463 #signature, cache_dir) 464 ) 465 text = "\n".join((str(a) for a in checksum_args)) 466 allfiles = sources + wrap_headers + local_headers + [ifile_name] 467 new_compilation_checksum = compute_checksum(text, allfiles) 468 469 # Recompile if necessary 470 recompile(modulename, module_path, setup_name, new_compilation_checksum) 471 472 # --- Load, cache, and return module 473 474 # Copy compiled module to cache 475 if use_cache: 476 module_path = copy_to_cache(module_path, cache_dir, modulename) 477 478 # Import module and place in memory cache 479 # Do not use locks if use_cache is False: 480 if use_cache: 481 lock = get_lock(cache_dir, modulename) 482 module = import_and_cache_module(module_path, modulename, moduleids) 483 if use_cache: 484 release_lock(lock) 485 if not module: 486 instant_error("Failed to import newly compiled module!") 487 488 instant_debug("In instant.build_module: Returning %s from build_module."\ 489 % module) 490 return module 491 # The end! 492 493 finally: 494 # Always get back to original directory. 495 os.chdir(original_path) 496 497 instant_error("In instant.build_module: Should never reach this point!")
498 # end build_module 499

instant-1.3.0/doc/html_reference/instant.cache-module.html000066400000000000000000000427021226277733300236360ustar00rootroot00000000000000 instant.cache
Package instant :: Module cache
[hide private]
[frames] | no frames]

Module cache

source code

This module contains helper functions for working with the module cache.

Example operations:

  • modulename = modulename_from_checksum(checksum)
  • modulename = modulename_from_checksum(compute_checksum(signature))
  • module = import_module_directly(path, modulename)
  • module = import_module(modulename)
  • module = import_module(checksum)
  • module = import_module(compute_checksum(signature))
  • modules = cached_modules()
  • modules = cached_modules(cache_dir)
Functions [hide private]
 
modulename_from_checksum(checksum)
Construct a module name from a checksum for use in cache.
source code
 
checksum_from_modulename(modulename)
Construct a module name from a checksum for use in cache.
source code
 
import_module_directly(path, modulename)
Import a module with the given module name that resides in the given path.
source code
 
memory_cached_module(moduleid)
Returns the cached module if found.
source code
 
place_module_in_memory_cache(moduleid, module)
Place a compiled module in cache with given id.
source code
 
is_valid_module_name(name) source code
 
import_and_cache_module(path, modulename, moduleids) source code
 
check_memory_cache(moduleid) source code
 
check_disk_cache(modulename, cache_dir, moduleids) source code
 
import_module(moduleid, cache_dir=None)
Import module from cache given its moduleid and an optional cache directory.
source code
 
cached_modules(cache_dir=None)
Return a list with the names of all cached modules.
source code
Variables [hide private]
  _modulename_prefix = 'instant_module_'
  _memory_cache = {}
  __package__ = 'instant'
Function Details [hide private]

import_module(moduleid, cache_dir=None)

source code 

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
  • a checksum string, which is used directly to look up in the cache
  • a hashable non-string object with a function moduleid.signature() which is used to get a signature string

The hashable object is used to look up in the memory cache before signature() is called. If the module is found on disk, it is placed in the memory cache.


instant-1.3.0/doc/html_reference/instant.cache-pysrc.html000066400000000000000000001416141226277733300235130ustar00rootroot00000000000000 instant.cache
Package instant :: Module cache
[hide private]
[frames] | no frames]

Source Code for Module instant.cache

  1  """This module contains helper functions for working with the module cache. 
  2   
  3  Example operations: 
  4    - modulename = modulename_from_checksum(checksum) 
  5    - modulename = modulename_from_checksum(compute_checksum(signature)) 
  6    - module = import_module_directly(path, modulename) 
  7    - module = import_module(modulename) 
  8    - module = import_module(checksum) 
  9    - module = import_module(compute_checksum(signature)) 
 10    - modules = cached_modules() 
 11    - modules = cached_modules(cache_dir) 
 12  """ 
 13   
 14  import os, sys, re 
 15  from output import instant_warning, instant_assert, instant_debug 
 16  from paths import get_default_cache_dir, validate_cache_dir 
 17  from signatures import compute_checksum 
 18  from locking import get_lock, release_lock 
 19   
 20  # TODO: We could make this an argument, but it's used indirectly several places so take care. 
 21  _modulename_prefix = "instant_module_" 
22 -def modulename_from_checksum(checksum):
23 "Construct a module name from a checksum for use in cache." 24 return _modulename_prefix + checksum
25 26
27 -def checksum_from_modulename(modulename):
28 "Construct a module name from a checksum for use in cache." 29 return modulename.remove(_modulename_prefix)
30 31
32 -def import_module_directly(path, modulename):
33 "Import a module with the given module name that resides in the given path." 34 sys.path.insert(0, path) 35 try: 36 module = __import__(modulename) 37 except: 38 instant_warning("In instant.import_module_directly: Failed to import module '%s' from '%s'." % (modulename, path)) 39 module = None 40 finally: 41 sys.path.pop(0) 42 return module
43 44 45 _memory_cache = {}
46 -def memory_cached_module(moduleid):
47 "Returns the cached module if found." 48 module = _memory_cache.get(moduleid, None) 49 instant_debug("Found '%s' in memory cache with key '%r'." % (module, moduleid)) 50 return module
51 52
53 -def place_module_in_memory_cache(moduleid, module):
54 "Place a compiled module in cache with given id." 55 _memory_cache[moduleid] = module 56 instant_debug("Added module '%s' to cache with key '%r'." % (module, moduleid))
57 58
59 -def is_valid_module_name(name):
60 NAMELENGTHLIMIT = 100 61 return len(name) < NAMELENGTHLIMIT and bool(re.search(r"^[a-zA-Z_][\w]*$", name))
62 63
64 -def import_and_cache_module(path, modulename, moduleids):
65 module = import_module_directly(path, modulename) 66 instant_assert(module is not None, "Failed to import module found in cache. Modulename: '%s'; Path: '%s'." % (modulename, path)) 67 for moduleid in moduleids: 68 place_module_in_memory_cache(moduleid, module) 69 return module
70 71
72 -def check_memory_cache(moduleid):
73 # Check memory cache first with the given moduleid 74 moduleids = [moduleid] 75 module = memory_cached_module(moduleid) 76 if module: return module, moduleids 77 78 # Get signature from moduleid if it isn't a string, 79 # and check memory cache again 80 if hasattr(moduleid, "signature"): 81 moduleid = moduleid.signature() 82 instant_debug("In instant.check_memory_cache: Got signature "\ 83 "'%s' from moduleid.signature()." % moduleid) 84 module = memory_cached_module(moduleid) 85 if module: 86 for moduleid in moduleids: 87 place_module_in_memory_cache(moduleid, module) 88 return module, moduleids 89 moduleids.append(moduleid) 90 91 # Construct a filename from the checksum of moduleid if it 92 # isn't already a valid name, and check memory cache again 93 if not is_valid_module_name(moduleid): 94 moduleid = modulename_from_checksum(compute_checksum(moduleid)) 95 instant_debug("In instant.check_memory_cache: Constructed module name "\ 96 "'%s' from moduleid '%s'." % (moduleid, moduleids[-1])) 97 module = memory_cached_module(moduleid) 98 if module: return module, moduleids 99 moduleids.append(moduleid) 100 101 instant_debug("In instant.check_memory_cache: Failed to find module.") 102 return None, moduleids
103 104
105 -def check_disk_cache(modulename, cache_dir, moduleids):
106 # Get file lock to avoid race conditions in cache 107 lock = get_lock(cache_dir, modulename) 108 109 # Ensure a valid cache_dir 110 cache_dir = validate_cache_dir(cache_dir) 111 112 # Check on disk, in current directory and cache directory 113 for path in (os.getcwd(), cache_dir): 114 if os.path.isdir(os.path.join(path, modulename)): 115 # Found existing directory, try to import and place in memory cache 116 module = import_and_cache_module(path, modulename, moduleids) 117 if module: 118 instant_debug("In instant.check_disk_cache: Imported module "\ 119 "'%s' from '%s'." % (modulename, path)) 120 release_lock(lock) 121 return module 122 else: 123 instant_debug("In instant.check_disk_cache: Failed to imported "\ 124 "module '%s' from '%s'." % (modulename, path)) 125 126 # All attempts failed 127 instant_debug("In instant.check_disk_cache: Can't import module with modulename "\ 128 "%r using cache directory %r." % (modulename, cache_dir)) 129 release_lock(lock) 130 return None
131 132
133 -def import_module(moduleid, cache_dir=None):
134 """Import module from cache given its moduleid and an optional cache directory. 135 136 The moduleid can be either 137 - the module name 138 - a signature string, of which a checksum is taken to look up in the cache 139 - a checksum string, which is used directly to look up in the cache 140 - a hashable non-string object with a function moduleid.signature() which is used to get a signature string 141 The hashable object is used to look up in the memory cache before signature() is called. 142 If the module is found on disk, it is placed in the memory cache. 143 """ 144 # Look for module in memory cache 145 module, moduleids = check_memory_cache(moduleid) 146 if module: return module 147 148 # Look for module in disk cache 149 modulename = moduleids[-1] 150 return check_disk_cache(modulename, cache_dir, moduleids)
151 152
153 -def cached_modules(cache_dir=None):
154 "Return a list with the names of all cached modules." 155 cache_dir = validate_cache_dir(cache_dir) 156 return os.listdir(cache_dir)
157

instant-1.3.0/doc/html_reference/instant.codegeneration-module.html000066400000000000000000000404401226277733300255560ustar00rootroot00000000000000 instant.codegeneration
Package instant :: Module codegeneration
[hide private]
[frames] | no frames]

Module codegeneration

source code

This module contains helper functions for code generation.

Functions [hide private]
 
mapstrings(format, sequence) source code
 
reindent(code)
Reindent a multiline string to allow easier to read syntax.
source code
 
write_interfacefile(filename, modulename, code, init_code, additional_definitions, additional_declarations, system_headers, local_headers, wrap_headers, arrays)
Generate a SWIG interface file.
source code
 
write_setup(filename, modulename, csrcs, cppsrcs, local_headers, include_dirs, library_dirs, libraries, swig_include_dirs, swigargs, cppargs, lddargs)
Generate a setup.py file.
source code
 
_test_write_interfacefile() source code
 
_test_write_setup() source code
Variables [hide private]
  __package__ = 'instant'
Function Details [hide private]

reindent(code)

source code 

Reindent a multiline string to allow easier to read syntax.

Each line will be indented relative to the first non-empty line. Start the first line without text like shown in this example:

   code = reindent("""
       Foo
       Bar
           Blatti
       Ping
       """)

makes all indentation relative to Foo.

write_interfacefile(filename, modulename, code, init_code, additional_definitions, additional_declarations, system_headers, local_headers, wrap_headers, arrays)

source code 

Generate a SWIG interface file. Intended for internal library use.

The input arguments are as follows:

  • modulename (Name of the module)
  • code (Code to be wrapped)
  • init_code (Code to put in the init section of the interface file)
  • additional_definitions (Definitions to be placed in initial block with C code as well as in the main section of the SWIG interface file)
  • additional_declarations (Declarations to be placed in the main section of the SWIG interface file)
  • system_headers (A list of system headers with declarations needed by the wrapped code)
  • local_headers (A list of local headers with declarations needed by the wrapped code)
  • wrap_headers (A list of local headers that will be included in the code and wrapped by SWIG)
  • arrays (A nested list, the inner lists describing the different arrays)

The result of this function is that a SWIG interface with the name modulename.i is written to the current directory.

write_setup(filename, modulename, csrcs, cppsrcs, local_headers, include_dirs, library_dirs, libraries, swig_include_dirs, swigargs, cppargs, lddargs)

source code 

Generate a setup.py file. Intended for internal library use.


instant-1.3.0/doc/html_reference/instant.codegeneration-pysrc.html000066400000000000000000002217311226277733300254350ustar00rootroot00000000000000 instant.codegeneration
Package instant :: Module codegeneration
[hide private]
[frames] | no frames]

Source Code for Module instant.codegeneration

  1  """This module contains helper functions for code generation.""" 
  2   
  3  import re, os 
  4  from output import instant_assert, instant_warning, instant_debug, write_file 
  5   
  6   
7 -def mapstrings(format, sequence):
8 return "\n".join(format % i for i in sequence)
9 10
11 -def reindent(code):
12 '''Reindent a multiline string to allow easier to read syntax. 13 14 Each line will be indented relative to the first non-empty line. 15 Start the first line without text like shown in this example:: 16 17 code = reindent(""" 18 Foo 19 Bar 20 Blatti 21 Ping 22 """) 23 24 makes all indentation relative to Foo. 25 ''' 26 lines = code.split("\n") 27 space = "" 28 # Get initial spaces from first non-empty line: 29 for l in lines: 30 if l: 31 r = re.search(r"^( [ ]*)", l) 32 if r is not None: 33 space = r.groups()[0] 34 break 35 if not space: 36 return code 37 n = len(space) 38 instant_assert(space == " "*n, "Logic breach in reindent.") 39 return "\n".join(re.sub(r"^%s" % space, "", l) for l in lines)
40 41
42 -def write_interfacefile(filename, modulename, code, init_code, 43 additional_definitions, additional_declarations, 44 system_headers, local_headers, wrap_headers, arrays):
45 """Generate a SWIG interface file. Intended for internal library use. 46 47 The input arguments are as follows: 48 - modulename (Name of the module) 49 - code (Code to be wrapped) 50 - init_code (Code to put in the init section of the interface file) 51 - additional_definitions (Definitions to be placed in initial block with 52 C code as well as in the main section of the SWIG interface file) 53 - additional_declarations (Declarations to be placed in the main section 54 of the SWIG interface file) 55 - system_headers (A list of system headers with declarations needed by the wrapped code) 56 - local_headers (A list of local headers with declarations needed by the wrapped code) 57 - wrap_headers (A list of local headers that will be included in the code and wrapped by SWIG) 58 - arrays (A nested list, the inner lists describing the different arrays) 59 60 The result of this function is that a SWIG interface with 61 the name modulename.i is written to the current directory. 62 """ 63 instant_debug("Generating SWIG interface file '%s'." % filename) 64 65 # create typemaps 66 typemaps = "" 67 valid_types = ['float', 'double', 'short', 'int', 'long', 68 'unsigned short', 'unsigned int', 'unsigned long'] 69 DATA_TYPE = 'double' 70 for a in arrays: 71 if type(a) == tuple: 72 a = list(a) 73 for vt in valid_types: 74 if vt in a: 75 DATA_TYPE = vt 76 a.remove(vt) 77 if 'in' in a: 78 # input arrays 79 a.remove('in') 80 instant_assert(len(a) > 1 and len(a) < 5, "Wrong number of elements in input array") 81 if len(a) == 2: 82 # 1-dimensional arrays, i.e. vectors 83 typemaps += reindent(""" 84 %%apply (int DIM1, %(dtype)s* IN_ARRAY1) {(int %(n1)s, %(dtype)s* %(array)s)}; 85 """ % { 'n1' : a[0], 'array' : a[1], 'dtype' : DATA_TYPE }) 86 elif len(a) == 3: 87 # 2-dimensional arrays, i.e. matrices 88 typemaps += reindent(""" 89 %%apply (int DIM1, int DIM2, %(dtype)s* IN_ARRAY2) {(int %(n1)s, int %(n2)s, %(dtype)s* %(array)s)}; 90 """ % { 'n1' : a[0], 'n2' : a[1], 'array' : a[2], 'dtype' : DATA_TYPE }) 91 else: 92 # 3-dimensional arrays, i.e. tensors 93 typemaps += reindent(""" 94 %%apply (int DIM1, int DIM2, int DIM3, %(dtype)s* IN_ARRAY3) {(int %(n1)s, int %(n2)s, int %(n3)s, %(dtype)s* %(array)s)}; 95 """ % { 'n1' : a[0], 'n2' : a[1], 'n3' : a[2], 'array' : a[3], 'dtype' : DATA_TYPE }) 96 elif 'out' in a: 97 # output arrays 98 a.remove('out') 99 instant_assert(len(a) == 2, "Output array must be 1-dimensional") 100 # 1-dimensional arrays, i.e. vectors 101 typemaps += reindent(""" 102 %%apply (int DIM1, %(dtype)s* ARGOUT_ARRAY1) {(int %(n1)s, %(dtype)s* %(array)s)}; 103 """ % { 'n1' : a[0], 'array' : a[1], 'dtype' : DATA_TYPE }) 104 else: 105 # in-place arrays 106 instant_assert(len(a) > 1 and len(a) < 5, "Wrong number of elements in output array") 107 if 'multi' in a: 108 # n-dimensional arrays, i.e. tensors > 3-dimensional 109 a.remove('multi') 110 typemaps += reindent(""" 111 %%typemap(in) (int %(n)s,int* %(ptv)s,%(dtype)s* %(array)s){ 112 if (!PyArray_Check($input)) { 113 PyErr_SetString(PyExc_TypeError, "Not a NumPy array"); 114 return NULL; ; 115 } 116 PyArrayObject* pyarray; 117 pyarray = (PyArrayObject*)$input; 118 $1 = int(pyarray->nd); 119 int* dims = new int($1); 120 for (int d=0; d<$1; d++) { 121 dims[d] = int(pyarray->dimensions[d]); 122 } 123 124 $2 = dims; 125 $3 = (%(dtype)s*)pyarray->data; 126 } 127 %%typemap(freearg) (int %(n)s,int* %(ptv)s,%(dtype)s* %(array)s){ 128 // deleting dims 129 delete $2; 130 } 131 """ % { 'n' : a[0] , 'ptv' : a[1], 'array' : a[2], 'dtype' : DATA_TYPE }) 132 elif len(a) == 2: 133 # 1-dimensional arrays, i.e. vectors 134 typemaps += reindent(""" 135 %%apply (int DIM1, %(dtype)s* INPLACE_ARRAY1) {(int %(n1)s, %(dtype)s* %(array)s)}; 136 """ % { 'n1' : a[0], 'array' : a[1], 'dtype' : DATA_TYPE }) 137 elif len(a) == 3: 138 # 2-dimensional arrays, i.e. matrices 139 typemaps += reindent(""" 140 %%apply (int DIM1, int DIM2, %(dtype)s* INPLACE_ARRAY2) {(int %(n1)s, int %(n2)s, %(dtype)s* %(array)s)}; 141 """ % { 'n1' : a[0], 'n2' : a[1], 'array' : a[2], 'dtype' : DATA_TYPE }) 142 else: 143 # 3-dimensional arrays, i.e. tensors 144 typemaps += reindent(""" 145 %%apply (int DIM1, int DIM2, int DIM3, %(dtype)s* INPLACE_ARRAY3) {(int %(n1)s, int %(n2)s, int %(n3)s, %(dtype)s* %(array)s)}; 146 """ % { 'n1' : a[0], 'n2' : a[1], 'n3' : a[2], 'array' : a[3], 'dtype' : DATA_TYPE}) 147 # end 148 # end if 149 # end for 150 151 system_headers_code = mapstrings('#include <%s>', system_headers) 152 local_headers_code = mapstrings('#include "%s"', local_headers) 153 wrap_headers_code1 = mapstrings('#include "%s"', wrap_headers) 154 wrap_headers_code2 = mapstrings('%%include "%s"', wrap_headers) 155 156 numpy_i_include = '' 157 if arrays: 158 numpy_i_include = r'%include "numpy.i"' 159 160 interface_string = reindent(""" 161 %%module %(modulename)s 162 //%%module (directors="1") %(modulename)s 163 164 //%%feature("director"); 165 166 %%{ 167 #include <iostream> 168 %(additional_definitions)s 169 %(system_headers_code)s 170 %(local_headers_code)s 171 %(wrap_headers_code1)s 172 %(code)s 173 %%} 174 175 //%%feature("autodoc", "1"); 176 %(numpy_i_include)s 177 178 %%init%%{ 179 %(init_code)s 180 %%} 181 182 %(additional_definitions)s 183 %(additional_declarations)s 184 %(wrap_headers_code2)s 185 //%(typemaps)s 186 %(code)s; 187 188 """ % locals()) 189 190 write_file(filename, interface_string) 191 instant_debug("Done generating interface file.")
192 193
194 -def write_setup(filename, modulename, csrcs, cppsrcs, local_headers, include_dirs, library_dirs, libraries, swig_include_dirs, swigargs, cppargs, lddargs):
195 """Generate a setup.py file. Intended for internal library use.""" 196 instant_debug("Generating %s." % filename) 197 198 swig_include_dirs.append(os.path.join(os.path.dirname(__file__), 'swig')) 199 200 # Handle arguments 201 swigfilename = "%s.i" % modulename 202 wrapperfilename = "%s_wrap.cxx" % modulename 203 204 # Treat C and C++ files in the same way for now 205 cppsrcs = cppsrcs + csrcs + [wrapperfilename] 206 207 swig_args = "" 208 if swigargs: 209 swig_args = " ".join(swigargs) 210 211 compile_args = "" 212 if cppargs: 213 compile_args = ", extra_compile_args=%r" % cppargs 214 215 link_args = "" 216 if lddargs: 217 link_args = ", extra_link_args=%r" % lddargs 218 219 swig_include_dirs = " ".join("-I%s"%d for d in swig_include_dirs) 220 if len(local_headers) > 0: 221 swig_include_dirs += " -I.." 222 223 # Generate code 224 code = reindent(""" 225 import os 226 from distutils.core import setup, Extension 227 name = '%s' 228 swig_cmd =r'swig -python %s %s %s' 229 os.system(swig_cmd) 230 sources = %s 231 setup(name = '%s', 232 ext_modules = [Extension('_' + '%s', 233 sources, 234 include_dirs=%s, 235 library_dirs=%s, 236 libraries=%s %s %s)]) 237 """ % (modulename, swig_include_dirs, swig_args, swigfilename, cppsrcs, 238 modulename, modulename, include_dirs, library_dirs, libraries, compile_args, link_args)) 239 240 write_file(filename, code) 241 instant_debug("Done writing setup.py file.")
242 243
245 modulename = "testmodule" 246 code = "void foo() {}" 247 init_code = "/* custom init code */" 248 additional_definitions = "/* custom definitions */" 249 additional_declarations = "/* custom declarations */" 250 system_headers = ["system_header1.h", "system_header2.h"] 251 local_headers = ["local_header1.h", "local_header2.h"] 252 wrap_headers = ["wrap_header1.h", "wrap_header2.h"] 253 arrays = [["length1", "array1"], ["dims", "lengths", "array2"]] 254 255 write_interfacefile("%s.i" % modulename, modulename, code, init_code, additional_definitions, additional_declarations, system_headers, local_headers, wrap_headers, arrays) 256 print "".join(open("%s.i" % modulename).readlines())
257 258
259 -def _test_write_setup():
260 modulename = "testmodule" 261 csrcs = ["csrc1.c", "csrc2.c"] 262 cppsrcs = ["cppsrc1.cpp", "cppsrc2.cpp"] 263 local_headers = ["local_header1.h", "local_header2.h"] 264 include_dirs = ["includedir1", "includedir2"] 265 library_dirs = ["librarydir1", "librarydir2"] 266 libraries = ["lib1", "lib2"] 267 swig_include_dirs = ["swigdir1", "swigdir2"], 268 swigargs = ["-Swigarg1", "-Swigarg2"] 269 cppargs = ["-cpparg1", "-cpparg2"] 270 lddargs = ["-Lddarg1", "-Lddarg2"] 271 272 write_setup("setup.py", modulename, csrcs, cppsrcs, local_headers, include_dirs, library_dirs, libraries, swig_include_dirs, swigargs, cppargs, lddargs) 273 print "".join(open("setup.py").readlines())
274 275 276 if __name__ == "__main__": 277 _test_write_interfacefile() 278 print "\n"*3 279 _test_write_setup() 280

instant-1.3.0/doc/html_reference/instant.config-module.html000066400000000000000000000257451226277733300240500ustar00rootroot00000000000000 instant.config
Package instant :: Module config
[hide private]
[frames] | no frames]

Module config

source code

This module contains helper functions for configuration using pkg-config.

Functions [hide private]
 
get_swig_version()
Return the current swig version in a 'str'
source code
 
check_swig_version(version, same=False)
Check the swig version
source code
 
header_and_libs_from_pkgconfig(*packages, **kwargs)
This function returns list of include files, flags, libraries and library directories obtain from a pkgconfig file.
source code
Variables [hide private]
  __package__ = 'instant'
Function Details [hide private]

check_swig_version(version, same=False)

source code 
Check the swig version

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"

header_and_libs_from_pkgconfig(*packages, **kwargs)

source code 

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)


instant-1.3.0/doc/html_reference/instant.config-pysrc.html000066400000000000000000000743601226277733300237200ustar00rootroot00000000000000 instant.config
Package instant :: Module config
[hide private]
[frames] | no frames]

Source Code for Module instant.config

  1  """This module contains helper functions for configuration using pkg-config.""" 
  2   
  3  import os 
  4  from output import get_status_output 
  5  import re 
  6   
  8      """ Return the current swig version in a 'str'""" 
  9      # Check for swig installation 
 10      result, output = get_status_output("swig -version") 
 11      if result != 0:  
 12          raise OSError("SWIG is not installed on the system.") 
 13      pattern = "SWIG Version (.*)" 
 14      r = re.search(pattern, output) 
 15      return r.groups(0)[0] 
 16   
17 -def check_swig_version(version, same=False):
18 """ Check the swig version 19 20 Returns True if the version of the installed swig is equal or greater than the 21 version passed to the function. 22 23 If same is True, the function returns True if and only if the two versions 24 are the same. 25 26 Usage: 27 if instant.check_swig_version('1.3.36'): 28 print "Swig version is greater than or equal to 1.3.36" 29 else: 30 print "Swig version is lower than 1.3.36" 31 """ 32 assert isinstance(version,str), "Provide the first version number as a 'str'" 33 assert len(version.split("."))==3, "Provide the version number as three numbers seperated by '.'" 34 35 installed_version = map(int, get_swig_version().split('.')) 36 handed_version = map(int, version.split('.')) 37 38 # If same is True then just check that all numbers are equal 39 if same: 40 return all(i == h for i, h in zip(installed_version,handed_version)) 41 42 swig_enough = True 43 for i, v in enumerate([v for v in installed_version]): 44 if handed_version[i] < v: 45 break 46 elif handed_version[i] == v: 47 continue 48 else: 49 swig_enough = False 50 break 51 52 return swig_enough
53
54 -def header_and_libs_from_pkgconfig(*packages, **kwargs):
55 """This function returns list of include files, flags, libraries and library directories obtain from a pkgconfig file. 56 57 The usage is: 58 (includes, flags, libraries, libdirs) = header_and_libs_from_pkgconfig(*list_of_packages) 59 """ 60 returnLinkFlags = kwargs.get("returnLinkFlags", False) 61 result, output = get_status_output("pkg-config --version ") 62 if result != 0: 63 raise OSError("The pkg-config package is not installed on the system.") 64 65 env = os.environ.copy() 66 try: 67 assert env["PKG_CONFIG_ALLOW_SYSTEM_CFLAGS"] == "0" 68 except: 69 env["PKG_CONFIG_ALLOW_SYSTEM_CFLAGS"] = "1" 70 71 includes = [] 72 flags = [] 73 libs = [] 74 libdirs = [] 75 linkflags = [] 76 for pack in packages: 77 result, output = get_status_output("pkg-config --exists %s " % pack, env=env) 78 if result == 0: 79 tmp = get_status_output("pkg-config --cflags-only-I %s " % pack, env=env)[1].split() 80 includes.extend(i[2:] for i in tmp) 81 82 tmp = get_status_output("pkg-config --cflags-only-other %s " % pack, env=env)[1].split() 83 flags.extend(tmp) 84 85 tmp = get_status_output("pkg-config --libs-only-l %s " % pack, env=env)[1].split() 86 libs.extend(i[2:] for i in tmp) 87 88 tmp = get_status_output("pkg-config --libs-only-L %s " % pack, env=env)[1].split() 89 libdirs.extend(i[2:] for i in tmp) 90 91 tmp = get_status_output("pkg-config --libs-only-other %s " % pack, env=env)[1].split() 92 linkflags.extend(tmp) 93 94 else: 95 raise OSError("The pkg-config file %s does not exist" % pack) 96 97 if returnLinkFlags: return (includes,flags,libs, libdirs, linkflags) 98 return (includes,flags,libs, libdirs)
99

instant-1.3.0/doc/html_reference/instant.inlining-module.html000066400000000000000000000430571226277733300244060ustar00rootroot00000000000000 instant.inlining
Package instant :: Module inlining
[hide private]
[frames] | no frames]

Module inlining

source code

This module contains the inline* functions, which allows easy inlining of C/C++ functions.

Functions [hide private]
 
get_func_name(c_code) source code
 
inline(c_code, **kwargs)
This is a short wrapper around the build_module function in instant.
source code
 
inline_module(c_code, **kwargs)
This is a short wrapper around the build_module function in instant.
source code
 
inline_with_numpy(c_code, **kwargs)
This is a short wrapper around the build_module function in instant.
source code
 
inline_module_with_numpy(c_code, **kwargs)
This is a short wrapper around the build_module function in instant.
source code
Variables [hide private]
  __package__ = 'instant'
Function Details [hide private]

inline(c_code, **kwargs)

source code 

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.

Usage:

>>> from instant import inline
>>> add_func = inline("double add(double a, double b){ return a+b; }")
>>> print "The sum of 3 and 4.5 is ", add_func(3, 4.5)

inline_module(c_code, **kwargs)

source code 

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.

Usage:

>>> from instant import inline
>>> add_func = inline("double add(double a, double b){ return a+b; }")
>>> print "The sum of 3 and 4.5 is ", add_func(3, 4.5)

inline_with_numpy(c_code, **kwargs)

source code 

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.

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]; 
        }
        return tmp; 
    }
    """
>>> sum_func = inline_with_numpy(c_code,  arrays = [['n1', 'array1']])
>>> a = numpy.arange(10000000); a = numpy.sin(a)
>>> sum_func(a)

inline_module_with_numpy(c_code, **kwargs)

source code 

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.

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]; 
        }
        return tmp; 
    }
    """
>>> sum_func = inline_with_numpy(c_code,  arrays = [['n1', 'array1']])
>>> a = numpy.arange(10000000); a = numpy.sin(a)
>>> sum_func(a)

instant-1.3.0/doc/html_reference/instant.inlining-pysrc.html000066400000000000000000001056331226277733300242600ustar00rootroot00000000000000 instant.inlining
Package instant :: Module inlining
[hide private]
[frames] | no frames]

Source Code for Module instant.inlining

  1  """This module contains the inline* functions, which allows easy inlining of C/C++ functions.""" 
  2   
  3  import sys 
  4  from output import instant_assert, instant_warning, instant_error 
  5  from build import build_module 
  6   
  7   
8 -def get_func_name(c_code):
9 # TODO: Something more robust? Regexp? 10 try: 11 func = c_code[:c_code.index('(')] 12 ret, func_name = func.split() 13 except: 14 instant_error("Failed to extract function name from c_code.") 15 return func_name
16 17
18 -def inline(c_code, **kwargs):
19 """This is a short wrapper around the build_module function in instant. 20 21 It creates a module given that 22 the input is a valid C function. It is only possible 23 to inline one C function each time. 24 25 Usage: 26 27 >>> from instant import inline 28 >>> add_func = inline("double add(double a, double b){ return a+b; }") 29 >>> print "The sum of 3 and 4.5 is ", add_func(3, 4.5) 30 """ 31 instant_assert("code" not in kwargs, "Cannot specify code twice.") 32 kwargs["code"] = c_code 33 func_name = get_func_name(c_code) 34 module = build_module(**kwargs) 35 if hasattr(module, func_name): 36 return getattr(module, func_name) 37 else: 38 instant_warning("Didn't find function '%s', returning module." % func_name) 39 return module
40
41 -def inline_module(c_code, **kwargs):
42 """This is a short wrapper around the build_module function in instant. 43 44 It creates a module given that 45 the input is a valid C function. It is only possible 46 to inline one C function each time. 47 48 Usage: 49 50 >>> from instant import inline 51 >>> add_func = inline("double add(double a, double b){ return a+b; }") 52 >>> print "The sum of 3 and 4.5 is ", add_func(3, 4.5) 53 """ 54 instant_assert("code" not in kwargs, "Cannot specify code twice.") 55 kwargs["code"] = c_code 56 module = build_module(**kwargs) 57 return module
58 59 60
61 -def inline_with_numpy(c_code, **kwargs):
62 '''This is a short wrapper around the build_module function in instant. 63 64 It creates a module given that 65 the input is a valid C function. It is only possible 66 to inline one C function each time. The difference between 67 this function and the inline function is that C-arrays can be used. 68 The following example illustrates that. 69 70 Usage: 71 72 >>> import numpy 73 >>> import time 74 >>> from instant import inline_with_numpy 75 >>> c_code = """ 76 double sum (int n1, double* array1){ 77 double tmp = 0.0; 78 for (int i=0; i<n1; i++) { 79 tmp += array1[i]; 80 } 81 return tmp; 82 } 83 """ 84 >>> sum_func = inline_with_numpy(c_code, arrays = [['n1', 'array1']]) 85 >>> a = numpy.arange(10000000); a = numpy.sin(a) 86 >>> sum_func(a) 87 ''' 88 import numpy 89 instant_assert("code" not in kwargs, "Cannot specify code twice.") 90 kwargs["code"] = c_code 91 kwargs["init_code"] = kwargs.get("init_code","") + "\nimport_array();\n" 92 kwargs["system_headers"] = kwargs.get("system_headers",[]) + ["numpy/arrayobject.h"] 93 kwargs["include_dirs"] = kwargs.get("include_dirs",[]) + ["%s" %numpy.get_include()] 94 func_name = get_func_name(c_code) 95 module = build_module(**kwargs) 96 if hasattr(module, func_name): 97 return getattr(module, func_name) 98 else: 99 instant_warning("Didn't find function '%s', returning module." % func_name) 100 return module
101
102 -def inline_module_with_numpy(c_code, **kwargs):
103 '''This is a short wrapper around the build_module function in instant. 104 105 It creates a module given that 106 the input is a valid C function. It is only possible 107 to inline one C function each time. The difference between 108 this function and the inline function is that C-arrays can be used. 109 The following example illustrates that. 110 111 Usage: 112 113 >>> import numpy 114 >>> import time 115 >>> from instant import inline_with_numpy 116 >>> c_code = """ 117 double sum (int n1, double* array1){ 118 double tmp = 0.0; 119 for (int i=0; i<n1; i++) { 120 tmp += array1[i]; 121 } 122 return tmp; 123 } 124 """ 125 >>> sum_func = inline_with_numpy(c_code, arrays = [['n1', 'array1']]) 126 >>> a = numpy.arange(10000000); a = numpy.sin(a) 127 >>> sum_func(a) 128 ''' 129 import numpy 130 instant_assert("code" not in kwargs, "Cannot specify code twice.") 131 kwargs["code"] = c_code 132 kwargs["init_code"] = kwargs.get("init_code","") + "\nimport_array();\n" 133 kwargs["system_headers"] = kwargs.get("system_headers",[]) + ["numpy/arrayobject.h"] 134 kwargs["include_dirs"] = kwargs.get("include_dirs",[]) + ["%s" % numpy.get_include()] 135 module = build_module(**kwargs) 136 return module
137

instant-1.3.0/doc/html_reference/instant.instant-class.html000066400000000000000000000441571226277733300241010ustar00rootroot00000000000000 instant.instant
Module instant :: Class instant
[hide private]
[frames] | no frames]

Class instant

source code

Instance Methods [hide private]
 
__init__(self)
instant constructor
source code
 
parse_args(self, dict)
A method for parsing arguments.
source code
 
create_extension(self, **args)
Call this function to instantly create an extension module.
source code
 
debug(self)
print out all instance variable
source code
 
clean(self)
Clean up files the current session.
source code
 
generate_Interfacefile(self)
Use this function to generate a SWIG interface file.
source code
 
check_md5sum(self)
Check if the md5sum of the generated interface file has changed since the last time the module was compiled.
source code
 
generate_setup(self)
Generates a setup.py file
source code
 
generate_Makefile(self)
Generates a project dependent Makefile, which includes and uses SWIG's own Makefile to create an extension module of the supplied C/C++ code.
source code
Method Details [hide private]

create_extension(self, **args)

source code 
Call this function to instantly create an extension module. SWIG is used to generate code that can be compiled and used as an ordinary Python module.

Arguments:

  • code:
    • A Python string containing C or C++ function, class, ....
  • module:
    • The name you want for the module (Default is 'instant_swig_module'.). String.
  • swigopts:
    • Options to swig, for instance -lpointers.i to include the SWIG pointers.i library. String.
  • init_code:
    • Code that should be executed when the instant extension is imported. String.
  • system_headers:
    • A list of system header files required by the instant code.
  • local_headers:
    • A list of local header files required by the instant code.
  • wrap_headers:
    • A list of local header files that should be wrapped by SWIG.
  • include_dirs:
    • A list of directories to search for header files.
  • sources:
    • A list of source files to compile and link with the extension.
  • cppargs:
    • Flags like -D, -U, etc. String.
  • lddargs:
    • Flags like -D, -U, etc. String.
  • libraries:
    • A list of libraries needed by the instant extension.
  • library_dirs:
    • A list of directories to search for libraries (-l).
  • object_files:
    • If you want to compile the files yourself. NOT YET SUPPORTED.
  • arrays:
    • A list of the C arrays to be made from NumPy arrays.
  • additional_definitions:
    • A list of additional definitions (typically needed for inheritance)
  • additional_declarations:
    • A list of additional declarations (typically needed for inheritance)
  • signature:
    • A signature string to identify the form instead of the source code.

generate_Interfacefile(self)

source code 

Use this function to generate a SWIG interface file.

To generate an interface file it uses the following class-variables:
  • code
  • ifile_name (The SWIG input file)
  • init_code (Code to put in the init section of the interface file)
  • system_headers (A list of system headers with declarations needed)
  • local_headers (A list of local headers with declarations needed)
  • wrap_headers (A list of local headers that will be wrapped by SWIG)

check_md5sum(self)

source code 
Check if the md5sum of the generated interface file has changed since the last time the module was compiled. If it has changed then recompilation is necessary.

instant-1.3.0/doc/html_reference/instant.locking-module.html000066400000000000000000000220701226277733300242150ustar00rootroot00000000000000 instant.locking
Package instant :: Module locking
[hide private]
[frames] | no frames]

Module locking

source code

File locking for the cache system, to avoid problems when multiple processes work with the same module. Only works on UNIX systems.

Functions [hide private]
 
release_all_locks()
Release all locks currently held by Instant.
source code
 
get_lock(cache_dir, module_name)
Get a new file lock.
source code
 
release_lock(lock)
Release a lock currently held by Instant.
source code
Variables [hide private]
  _lock_names = {}
  _lock_files = {}
  _lock_count = {}
  __package__ = 'instant'
instant-1.3.0/doc/html_reference/instant.locking-pysrc.html000066400000000000000000000664551226277733300241070ustar00rootroot00000000000000 instant.locking
Package instant :: Module locking
[hide private]
[frames] | no frames]

Source Code for Module instant.locking

 1  """File locking for the cache system, to avoid problems 
 2  when multiple processes work with the same module. 
 3  Only works on UNIX systems.""" 
 4   
 5  import os.path 
 6  from output import instant_error, instant_assert, instant_debug 
 7  from paths import validate_cache_dir 
 8   
 9  try: 
10      import fcntl 
11  except: 
12      fcntl = None 
13   
14  # Keeping an overview of locks currently held, 
15  # to avoid deadlocks within a single process. 
16  _lock_names = {} # lock.fileno() -> lockname 
17  _lock_files = {} # lockname -> lock 
18  _lock_count = {} # lockname -> number of times this lock has been aquired and not yet released 
19   
20  if fcntl: 
21 - def get_lock(cache_dir, module_name):
22 "Get a new file lock." 23 global _lock_names, _lock_files, _lock_count 24 25 lockname = module_name + ".lock" 26 count = _lock_count.get(lockname, 0) 27 28 instant_debug("Acquiring lock %s, count is %d." % (lockname, count)) 29 30 if count == 0: 31 cache_dir = validate_cache_dir(cache_dir) 32 lock = open(os.path.join(cache_dir, lockname), "w") 33 fcntl.flock(lock.fileno(), fcntl.LOCK_EX) 34 _lock_names[lock.fileno()] = lockname 35 _lock_files[lockname] = lock 36 else: 37 lock = _lock_files[lockname] 38 39 _lock_count[lockname] = count + 1 40 return lock
41
42 - def release_lock(lock):
43 "Release a lock currently held by Instant." 44 global _lock_names, _lock_files, _lock_count 45 46 lockname = _lock_names[lock.fileno()] 47 count = _lock_count[lockname] 48 49 instant_debug("Releasing lock %s, count is %d." % (lockname, count)) 50 51 instant_assert(count > 0, "Releasing lock that Instant is supposedly not holding.") 52 instant_assert(lock is _lock_files[lockname], "Lock mismatch, might be something wrong in locking logic.") 53 54 del _lock_files[lockname] 55 del _lock_names[lock.fileno()] 56 _lock_count[lockname] = count - 1 57 58 fcntl.flock(lock.fileno(), fcntl.LOCK_UN) 59 lock.close()
60
61 - def release_all_locks():
62 "Release all locks currently held by Instant." 63 locks = _lock_files.values() 64 for lock in locks: 65 release_lock(lock) 66 instant_assert(all(_lock_count[lockname] == 0 for lockname in _lock_count), "Lock counts not zero after releasing all locks.")
67 68 else: 69 # Windows systems have no fcntl, implement these otherwise if locking is needed on windows
70 - def get_lock(cache_dir, module_name):
71 return None
72
73 - def release_lock(lock):
74 pass
75

instant-1.3.0/doc/html_reference/instant.output-module.html000066400000000000000000000335221226277733300241330ustar00rootroot00000000000000 instant.output
Package instant :: Module output
[hide private]
[frames] | no frames]

Module output

source code

This module contains internal logging utilities.

Functions [hide private]
 
get_log_handler() source code
 
get_logger() source code
 
set_log_handler(handler) source code
 
set_logging_level(level) source code
 
instant_debug(*message) source code
 
instant_info(*message) source code
 
instant_warning(*message) source code
 
instant_error(*message) source code
 
instant_assert(condition, *message) source code
 
write_file(filename, text)
Write text to a file and close it.
source code
 
get_status_output(cmd, input=None, cwd=None, env=None) source code
Variables [hide private]
  _log = logging.getLogger("instant")
  _loghandler = logging.StreamHandler()
  __package__ = 'instant'
instant-1.3.0/doc/html_reference/instant.output-pysrc.html000066400000000000000000000672731226277733300240200ustar00rootroot00000000000000 instant.output
Package instant :: Module output
[hide private]
[frames] | no frames]

Source Code for Module instant.output

 1  """This module contains internal logging utilities.""" 
 2   
 3  import logging 
 4   
 5  # Logging wrappers 
 6   
 7  _log = logging.getLogger("instant") 
 8  _loghandler = logging.StreamHandler() 
 9  _log.addHandler(_loghandler) 
10  _log.setLevel(logging.WARNING) 
11  _log.setLevel(logging.INFO) 
12  #_log.setLevel(logging.DEBUG) 
13   
14 -def get_log_handler():
15 return _loghandler
16
17 -def get_logger():
18 return _log
19
20 -def set_log_handler(handler):
21 global _loghandler 22 _log.removeHandler(_loghandler) 23 _loghandler = handler 24 _log.addHandler(_loghandler)
25
26 -def set_logging_level(level):
27 if isinstance(level, str): 28 level = level.upper() 29 assert level in ("INFO", "WARNING", "ERROR", "DEBUG") 30 level = getattr(logging, level) 31 else: 32 assert isinstance(level, int) 33 _log.setLevel(level)
34 35 # Aliases for calling log consistently: 36
37 -def instant_debug(*message):
38 _log.debug(*message)
39
40 -def instant_info(*message):
41 _log.info(*message)
42
43 -def instant_warning(*message):
44 _log.warning(*message)
45
46 -def instant_error(*message):
47 _log.error(*message) 48 text = message[0] % message[1:] 49 raise RuntimeError(text)
50
51 -def instant_assert(condition, *message):
52 if not condition: 53 _log.error(*message) 54 text = message[0] % message[1:] 55 raise AssertionError(text)
56 57 # Utility functions for file handling: 58
59 -def write_file(filename, text):
60 "Write text to a file and close it." 61 try: 62 f = open(filename, "w") 63 f.write(text) 64 f.close() 65 except IOError, e: 66 instant_error("Can't open '%s': %s" % (filename, e))
67 68 69 # Taken from http://ivory.idyll.org/blog/mar-07/replacing-commands-with-subprocess 70 from subprocess import Popen, PIPE, STDOUT
71 -def get_status_output(cmd, input=None, cwd=None, env=None):
72 pipe = Popen(cmd, shell=True, cwd=cwd, env=env, stdout=PIPE, stderr=STDOUT) 73 74 (output, errout) = pipe.communicate(input=input) 75 assert not errout 76 77 status = pipe.returncode 78 79 return (status, output)
80

instant-1.3.0/doc/html_reference/instant.paths-module.html000066400000000000000000000270121226277733300237070ustar00rootroot00000000000000 instant.paths
Package instant :: Module paths
[hide private]
[frames] | no frames]

Module paths

source code

This module contains helper functions for working with temp and cache directories.

Functions [hide private]
 
get_temp_dir()
Return a temporary directory for the duration of this process.
source code
 
delete_temp_dir()
Delete the temporary directory created by get_temp_dir().
source code
 
get_instant_dir()
Return a temporary directory for the duration of this process.
source code
 
get_default_cache_dir()
Return the default cache directory.
source code
 
validate_cache_dir(cache_dir) source code
 
_test() source code
Variables [hide private]
  _tmp_dir = None
  __package__ = 'instant'
Function Details [hide private]

get_temp_dir()

source code 

Return a temporary directory for the duration of this process.

Multiple calls in the same process returns the same directory. Remember to all delete_temp_dir() before exiting.


instant-1.3.0/doc/html_reference/instant.paths-pysrc.html000066400000000000000000000606741226277733300235750ustar00rootroot00000000000000 instant.paths
Package instant :: Module paths
[hide private]
[frames] | no frames]

Source Code for Module instant.paths

 1  """This module contains helper functions for working with temp and cache directories.""" 
 2   
 3  # Utilities for directory handling: 
 4   
 5  import os 
 6  import shutil 
 7  import tempfile 
 8  import time 
 9  from output import instant_debug, instant_assert 
10   
11  _tmp_dir = None 
12 -def get_temp_dir():
13 """Return a temporary directory for the duration of this process. 14 15 Multiple calls in the same process returns the same directory. 16 Remember to all delete_temp_dir() before exiting.""" 17 global _tmp_dir 18 if _tmp_dir is None: 19 datestring = "%d-%d-%d-%02d-%02d" % time.localtime()[:5] 20 suffix = datestring + "_instant" 21 _tmp_dir = tempfile.mkdtemp(suffix) 22 instant_debug("Created temp directory '%s'." % _tmp_dir) 23 return _tmp_dir
24
25 -def delete_temp_dir():
26 """Delete the temporary directory created by get_temp_dir().""" 27 global _tmp_dir 28 if _tmp_dir and os.path.isdir(_tmp_dir): 29 shutil.rmtree(_tmp_dir, ignore_errors=True) 30 _tmp_dir = None
31
32 -def get_instant_dir():
33 "Return a temporary directory for the duration of this process." 34 # os.path.expanduser works for Windows, Linux, and Mac 35 # In Windows, $HOME is os.environ['HOMEDRIVE'] + os.environ['HOMEPATH'] 36 instant_dir = os.path.join(os.path.expanduser("~"), ".instant") 37 if not os.path.isdir(instant_dir): 38 instant_debug("Creating instant directory '%s'." % instant_dir) 39 os.mkdir(instant_dir) 40 return instant_dir
41
43 "Return the default cache directory." 44 cache_dir = os.path.join(get_instant_dir(), "cache") 45 if not os.path.isdir(cache_dir): 46 instant_debug("Creating cache directory '%s'." % cache_dir) 47 os.mkdir(cache_dir) 48 return cache_dir
49
50 -def validate_cache_dir(cache_dir):
51 if cache_dir is None: 52 return get_default_cache_dir() 53 instant_assert(isinstance(cache_dir, str), "Expecting cache_dir to be a string.") 54 cache_dir = os.path.abspath(cache_dir) 55 if not os.path.isdir(cache_dir): 56 os.mkdir(cache_dir) 57 return cache_dir
58
59 -def _test():
60 print "Temp dir:", get_temp_dir() 61 print "Instant dir:", get_instant_dir() 62 print "Default cache dir:", get_default_cache_dir() 63 delete_temp_dir()
64 65 if __name__ == "__main__": 66 _test() 67

instant-1.3.0/doc/html_reference/instant.signatures-module.html000066400000000000000000000170551226277733300247620ustar00rootroot00000000000000 instant.signatures
Package instant :: Module signatures
[hide private]
[frames] | no frames]

Module signatures

source code

This module contains helper functions for working with checksums.

Functions [hide private]
 
compute_checksum(text='', filenames=[])
Get the checksum value of filename modified based on Python24\Tools\Scripts\md5.py
source code
 
_test() source code
Variables [hide private]
  __package__ = 'instant'
instant-1.3.0/doc/html_reference/instant.signatures-pysrc.html000066400000000000000000000427521226277733300246370ustar00rootroot00000000000000 instant.signatures
Package instant :: Module signatures
[hide private]
[frames] | no frames]

Source Code for Module instant.signatures

 1  """This module contains helper functions for working with checksums.""" 
 2   
 3  import hashlib 
 4  from output import instant_assert, instant_debug, instant_error 
 5   
6 -def compute_checksum(text="", filenames=[]):
7 """ 8 Get the checksum value of filename 9 modified based on Python24\Tools\Scripts\md5.py 10 """ 11 instant_assert(isinstance(text, str), "Expecting string.") 12 instant_assert(isinstance(filenames, (list,tuple)), "Expecting sequence.") 13 14 m = hashlib.new('sha1') 15 if text: 16 m.update(text) 17 18 for filename in sorted(filenames): 19 instant_debug("Adding file '%s' to checksum." % filename) 20 try: 21 fp = open(filename, 'rb') 22 except IOError, e: 23 instant_error("Can't open file '%s': %s" % (filename, e)) 24 25 try: 26 while 1: 27 data = fp.read() 28 if not data: 29 break 30 m.update(data) 31 except IOError, e: 32 instant_error("I/O error reading '%s': %s" % (filename, e)) 33 34 fp.close() 35 36 return m.hexdigest().lower()
37 38
39 -def _test():
40 signature = "(Test signature)" 41 files = ["signatures.py", "__init__.py"] 42 print 43 print "Signature:", repr(signature) 44 print "Checksum:", compute_checksum(signature, []) 45 print 46 print "Files:", files 47 print "Checksum:", compute_checksum("", files) 48 print
49 50 if __name__ == "__main__": 51 _test() 52

instant-1.3.0/doc/html_reference/module-tree.html000066400000000000000000000137501226277733300220540ustar00rootroot00000000000000 Module Hierarchy
 
[hide private]
[frames] | no frames]

Module Hierarchy

  • instant: Instant allows compiled C/C++ modules to be created at runtime in your Python application, using SWIG to wrap the C/C++ code.
    • instant.build: This module contains the main part of Instant, the build_module function.
    • instant.cache: This module contains helper functions for working with the module cache.
    • instant.codegeneration: This module contains helper functions for code generation.
    • instant.config: This module contains helper functions for configuration using pkg-config.
    • instant.inlining: This module contains the inline* functions, which allows easy inlining of C/C++ functions.
    • instant.locking: File locking for the cache system, to avoid problems when multiple processes work with the same module.
    • instant.output: This module contains internal logging utilities.
    • instant.paths: This module contains helper functions for working with temp and cache directories.
    • instant.signatures: This module contains helper functions for working with checksums.
instant-1.3.0/doc/html_reference/redirect.html000066400000000000000000000022471226277733300214320ustar00rootroot00000000000000Epydoc Redirect Page

Epydoc Auto-redirect page

When javascript is enabled, this page will redirect URLs of the form redirect.html#dotted.name to the documentation for the object with the given fully-qualified dotted name.

 

instant-1.3.0/doc/html_reference/toc-everything.html000066400000000000000000000243201226277733300225740ustar00rootroot00000000000000 Everything

Everything


All Functions

instant.build.arg_strings
instant.build.assert_is_bool
instant.build.assert_is_str
instant.build.assert_is_str_list
instant.build.build_module
instant.build.copy_files
instant.build.copy_to_cache
instant.build.recompile
instant.build.strip_strings
instant.cache.cached_modules
instant.cache.check_disk_cache
instant.cache.check_memory_cache
instant.cache.checksum_from_modulename
instant.cache.import_and_cache_module
instant.cache.import_module
instant.cache.import_module_directly
instant.cache.is_valid_module_name
instant.cache.memory_cached_module
instant.cache.modulename_from_checksum
instant.cache.place_module_in_memory_cache
instant.codegeneration.mapstrings
instant.codegeneration.reindent
instant.codegeneration.write_interfacefile
instant.codegeneration.write_setup
instant.config.check_swig_version
instant.config.get_swig_version
instant.config.header_and_libs_from_pkgconfig
instant.inlining.get_func_name
instant.inlining.inline
instant.inlining.inline_module
instant.inlining.inline_module_with_numpy
instant.inlining.inline_with_numpy
instant.locking.get_lock
instant.locking.release_all_locks
instant.locking.release_lock
instant.output.get_log_handler
instant.output.get_logger
instant.output.get_status_output
instant.output.instant_assert
instant.output.instant_debug
instant.output.instant_error
instant.output.instant_info
instant.output.instant_warning
instant.output.set_log_handler
instant.output.set_logging_level
instant.output.write_file
instant.paths.delete_temp_dir
instant.paths.get_default_cache_dir
instant.paths.get_instant_dir
instant.paths.get_temp_dir
instant.paths.validate_cache_dir
instant.signatures.compute_checksum

All Variables

instant.__package__
instant.build.__package__
instant.cache.__package__
instant.codegeneration.__package__
instant.config.__package__
instant.inlining.__package__
instant.locking.__package__
instant.output.__package__
instant.paths.__package__
instant.signatures.__package__

[hide private] instant-1.3.0/doc/html_reference/toc-instant-module.html000066400000000000000000000021041226277733300233470ustar00rootroot00000000000000 instant

Module instant


Variables

__package__

[hide private] instant-1.3.0/doc/html_reference/toc-instant.build-module.html000066400000000000000000000037651226277733300244630ustar00rootroot00000000000000 build

Module build


Functions

arg_strings
assert_is_bool
assert_is_str
assert_is_str_list
build_module
copy_files
copy_to_cache
recompile
strip_strings

Variables

__package__

[hide private] instant-1.3.0/doc/html_reference/toc-instant.cache-module.html000066400000000000000000000051771226277733300244260ustar00rootroot00000000000000 cache

Module cache


Functions

cached_modules
check_disk_cache
check_memory_cache
checksum_from_modulename
import_and_cache_module
import_module
import_module_directly
is_valid_module_name
memory_cached_module
modulename_from_checksum
place_module_in_memory_cache

Variables

__package__

[hide private] instant-1.3.0/doc/html_reference/toc-instant.codegeneration-module.html000066400000000000000000000035661226277733300263510ustar00rootroot00000000000000 codegeneration

Module codegeneration


Functions

mapstrings
reindent
write_interfacefile
write_setup

Variables

__package__

[hide private] instant-1.3.0/doc/html_reference/toc-instant.config-module.html000066400000000000000000000027211226277733300246200ustar00rootroot00000000000000 config

Module config


Functions

check_swig_version
get_swig_version
header_and_libs_from_pkgconfig

Variables

__package__

[hide private] instant-1.3.0/doc/html_reference/toc-instant.inlining-module.html000066400000000000000000000032151226277733300251610ustar00rootroot00000000000000 inlining

Module inlining


Functions

get_func_name
inline
inline_module
inline_module_with_numpy
inline_with_numpy

Variables

__package__

[hide private] instant-1.3.0/doc/html_reference/toc-instant.locking-module.html000066400000000000000000000034601226277733300250020ustar00rootroot00000000000000 locking

Module locking


Functions

get_lock
release_all_locks
release_lock

Variables

__package__

[hide private] instant-1.3.0/doc/html_reference/toc-instant.output-module.html000066400000000000000000000047411226277733300247170ustar00rootroot00000000000000 output

Module output


Functions

get_log_handler
get_logger
get_status_output
instant_assert
instant_debug
instant_error
instant_info
instant_warning
set_log_handler
set_logging_level
write_file

Variables

__package__

[hide private] instant-1.3.0/doc/html_reference/toc-instant.paths-module.html000066400000000000000000000035711226277733300244760ustar00rootroot00000000000000 paths

Module paths


Functions

delete_temp_dir
get_default_cache_dir
get_instant_dir
get_temp_dir
validate_cache_dir

Variables

__package__

[hide private] instant-1.3.0/doc/html_reference/toc-instant.signatures-module.html000066400000000000000000000025431226277733300255410ustar00rootroot00000000000000 signatures

Module signatures


Functions

compute_checksum

Variables

__package__

[hide private] instant-1.3.0/doc/html_reference/toc.html000066400000000000000000000056061226277733300204200ustar00rootroot00000000000000 Table of Contents

Table of Contents


Everything

Modules

instant
instant.build
instant.cache
instant.codegeneration
instant.config
instant.inlining
instant.locking
instant.output
instant.paths
instant.signatures

[hide private] instant-1.3.0/doc/makedoc.sh000077500000000000000000000001641226277733300157170ustar00rootroot00000000000000#!/bin/sh -x epydoc -c white -o html_reference \ -v -u http://www.fenics.org/instant \ --html ../src/instant/*.py instant-1.3.0/doc/man/000077500000000000000000000000001226277733300145275ustar00rootroot00000000000000instant-1.3.0/doc/man/man1/000077500000000000000000000000001226277733300153635ustar00rootroot00000000000000instant-1.3.0/doc/man/man1/instant-clean.1.gz000066400000000000000000000005611226277733300206260ustar00rootroot00000000000000\Hinstant-clean.1]_k0)y,2NA^VRInOh$?s TUVV:j2{̅5ymI3XpB4D&H.7OPB;g*ϑf&}%tFfՏ8Kqz̓8#>8?Ns±5܊ۗ$_ainstant-1.3.0/doc/man/man1/instant-showcache.1.gz000066400000000000000000000006421226277733300215100ustar00rootroot00000000000000HQk0)eaM q_7"V}Ue T~g(\kܸ,qJzƱF<]HhB69Ut^c8g?щ ‰}VmHSHVb=52(-U?_^LћR0ģ滣Wx0D,-<ΓF!:8j|nj-x|H0Z X^;XnVp>'8>={^sɮۏ#MVHI]uN렻Hnw^^=om׸oEs@Oinstant-1.3.0/instant/000077500000000000000000000000001226277733300146675ustar00rootroot00000000000000instant-1.3.0/instant/__init__.py000066400000000000000000000017541226277733300170070ustar00rootroot00000000000000""" Instant allows compiled C/C++ modules to be created at runtime in your Python application, using SWIG to wrap the C/C++ code. A simple example: >>> from instant import inline >>> add_func = inline(\"double add(double a, double b){ return a+b; }\") >>> print "The sum of 3 and 4.5 is ", add_func(3, 4.5) The main functions are C{build_module}, C{write_code}, and C{inline*} see their documentation for more details. For more examples, see the tests/ directory in the Instant distribution. Questions, bugs and patches should be sent to fenics@fenicsproject.org. """ __authors__ = "Magne Westlie, Kent-Andre Mardal , Martin Alnes , Ilmar M. Wilbers " __date__ = "2014-01-07" __version__ = "1.3.0" # TODO: Import only the official interface from .output import * from .config import * from .paths import * from .signatures import * from .cache import * from .codegeneration import * from .build import * from .inlining import * instant-1.3.0/instant/build.py000066400000000000000000000661061226277733300163510ustar00rootroot00000000000000"""This module contains the main part of Instant, the build_module function.""" import os, sys, shutil, glob, errno from itertools import chain # TODO: Import only the official interface from output import * from config import header_and_libs_from_pkgconfig, get_swig_version from paths import * from signatures import * 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.") def assert_is_bool(x): 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.") 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. """ try: os.makedirs(path) except os.error, e: 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.""" if os.path.exists(dest): overwriting = set(files) & set(glob.glob(os.path.join(dest, "*"))) if overwriting: instant_warning("In instant.copy_files: Path '%s' already exists, "\ "overwriting existing files: %r." % (dest, list(overwriting))) else: makedirs(dest) if source != dest: instant_debug("In instant.copy_files: Copying files %r from %r to %r"\ % (files, source, dest)) for f in files: a = os.path.join(source, f) b = os.path.join(dest, f) instant_assert(a != b, "In instant.copy_files: Seems like the "\ "input files are absolute paths, should be relative to "\ "source. (%r, %r)" % (a, b)) instant_assert(os.path.isfile(a), "In instant.copy_files: "\ "Missing source file '%s'." % a) if os.path.isfile(b): os.remove(b) shutil.copyfile(a, b) def recompile(modulename, module_path, new_compilation_checksum, build_system="distutils"): """Recompile module if the new checksum is different from the one in the checksum file in the module directory.""" assert(build_system in ["distutils", "cmake"]) # Check if the old checksum matches the new one compilation_checksum_filename = "%s.checksum" % modulename if os.path.exists(compilation_checksum_filename): checksum_file = open(compilation_checksum_filename) old_compilation_checksum = checksum_file.readline() checksum_file.close() if old_compilation_checksum == new_compilation_checksum: return # Verify that SWIG is on the system try: get_swig_version() except OSError: instant_error("In instant.recompile: Could not find swig!"\ " You can download swig from http://www.swig.org") # Create log file for logging of compilation errors compile_log_filename = os.path.join(module_path, "compile.log") compile_log_filename_dest = os.path.join(get_default_error_dir(), \ modulename, "compile.log") compile_log_file = open(compile_log_filename, "w") ret = 1 try: compile_log_contents = None instant_info("--- Instant: compiling ---") # 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=." instant_debug("cmd = %s" % cmd) ret, output = get_status_output(cmd) compile_log_file.write(output) compile_log_file.flush() if ret != 0: compile_log_contents = output if os.path.exists(compilation_checksum_filename): 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 ."; #cmd = "cmake ."; instant_debug("cmd = %s" % cmd) ret, output = get_status_output(cmd) compile_log_file.write(output) compile_log_file.flush() if ret != 0: compile_log_contents = output if os.path.exists(compilation_checksum_filename): 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)) # Build extension module with cmake generated makefile cmd = "make VERBOSE=1" instant_debug("cmd = %s" % cmd) ret, output = get_status_output(cmd) compile_log_file.write(output) compile_log_file.flush() if ret != 0: compile_log_contents = output if os.path.exists(compilation_checksum_filename): 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)) finally: compile_log_file.close() if ret != 0: if "INSTANT_DISPLAY_COMPILE_LOG" in os.environ.keys(): instant_warning("") instant_warning("Content of instant compile.log") instant_warning("==============================") instant_warning(compile_log_contents) instant_warning("") # Copy module to error dir module_path = copy_to_cache(module_path, get_default_error_dir(), modulename, check_for_existing_path=False) # 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, \ check_for_existing_path=True): "Copy module directory to cache." # Get lock, check if the module exists, _otherwise_ copy the # finished compiled module from /tmp/foo to the cache directory, # and then release lock with file_lock(cache_dir, modulename) as lock: # Validate the path cache_module_path = os.path.join(cache_dir, modulename) if check_for_existing_path and os.path.exists(cache_module_path): # 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) return cache_module_path # Not deleting anymore, relying on locking system #shutil.rmtree(cache_module_path, ignore_errors=True) # Error checks instant_assert(os.path.isdir(module_path), "In instant.build_module:"\ " Cannot copy non-existing directory %r!" % module_path) if check_for_existing_path and os.path.isdir(cache_module_path): instant_error("In instant.build_module: Cache directory %r shouldn't"\ " exist at this point!" % cache_module_path) instant_debug("In instant.build_module: Copying built module from %r"\ " to cache at %r" % (module_path, cache_module_path)) # Do the copying try: shutil.copytree(module_path, cache_module_path) except OSError, e: if e.errno != errno.EEXIST: raise finally: delete_temp_dir() return cache_module_path def build_module(modulename=None, source_directory=".", code="", init_code="", additional_definitions="", additional_declarations="", sources=[], wrap_headers=[], local_headers=[], system_headers=[], include_dirs=['.'], library_dirs=[], libraries=[], swigargs=['-c++', '-fcompact', '-O', '-I.', '-small'], swig_include_dirs = [], cppargs=['-O2'], lddargs=[], object_files=[], arrays=[], generate_interface=True, generate_setup=True, cmake_packages=[], signature=None, cache_dir=None): """Generate and compile a module from C/C++ code using SWIG. Arguments: ========== The keyword arguments are as follows: - B{modulename}: - The name you want for the module. If specified, the module will not be cached. If missing, a name will be constructed based on a checksum of the other arguments, and the module will be placed in the global cache. String. - B{source_directory}: - The directory where user supplied files reside. The files given in B{sources}, B{wrap_headers}, and B{local_headers} are expected to exist in this directory. String. - B{code}: - A string containing C or C++ code to be compiled and wrapped. String. - B{init_code}: - Code that should be executed when the Instant module is imported. This code is inserted in the SWIG interface file, and is used for instance for calling C{import_array()} used for the initialization of NumPy arrays. String. - B{additional_definitions}: - Additional definitions (typically needed for inheritance) for interface file. These definitions should be given as triple-quoted strings in the case they span multiple lines, and are placed both in the initial block for C/C++ code (C{%{,%}}-block), and the main section of the interface file. String. - B{additional_declarations}: - Additional declarations (typically needed for inheritance) for interface file. These declarations should be given as triple-quoted strings in the case they span multiple lines, and are plaves in the main section of the interface file. String. - B{sources}: - Source files to compile and link with the module. These files are compiled togehter with the SWIG-generated wrapper file into the final library file. Should reside in directory specified in B{source_directory}. List of strings. - B{wrap_headers}: - Local header files that should be wrapped by SWIG. The files specified will be included both in the initial block for C/C++ code (with a C directive) and in the main section of the interface file (with a SWIG directive). Should reside in directory specified in B{source_directory}. List of strings. - B{local_headers}: - Local header files required to compile the wrapped code. The files specified will be included in the initial block for C/C++ code (with a C directive). Should reside in directory specified in B{source_directory}. List of strings. - B{system_headers}: - System header files required to compile the wrapped code. The files specified will be included in the initial block for C/C++ code (with a C directive). List of strings. - B{include_dirs}: - Directories to search for header files for building the extension module. Needs to be absolute path names. List of strings. - B{library_dirs}: - Directories to search for libraries (C{-l}) for building the extension module. Needs to be absolute paths. List of strings. - B{libraries}: - Libraries needed by the Instant module. The libraries will be linked in from the shared object file. The initial C{-l} is added automatically. List of strings. - B{swigargs}: - List of arguments to swig, e.g. C{["-lpointers.i"]} to include the SWIG pointers.i library. - B{swig_include_dirs}: - A list of directories to include in the 'swig' command. - B{cppargs}: - List of arguments to the compiler, e.g. C{["-Wall", "-fopenmp"]}. - B{lddargs}: - List of arguments to the linker, e.g. C{["-E", "-U"]}. - B{object_files}: - If you want to compile the files yourself. TODO: Not yet supported. - B{arrays}: - A nested list describing the C arrays to be made from NumPy arrays. The SWIG interface for fil NumPy is used. For 1D arrays, the inner list should contain strings with the variable names for the length of the arrays and the array itself. 2D matrices should contain the names of the dimensions in the two directions as well as the name of the array, and 3D tensors should contain the names of the dimensions in the three directions in addition to the name of the array. If the NumPy array har more than four dimensions, the inner list should contain strings with variable names for the number of dimensions, the length in each dimension as a pointer, and the array itself, respectively. - B{generate_interface}: - A bool to indicate if you want to generate the interface files. - B{generate_setup}: - A bool to indicate if you want to generate the setup.py file. - B{cmake_packages}: - A list with CMake configured packages which are used to configure and build the extension module. If used it will override the default behaviour of using distutils. - B{signature}: - A signature string to identify the form instead of the source code. - B{cache_dir}: - A directory to look for cached modules and place new ones. If missing, a default directory is used. Note that the module will not be cached if B{modulename} is specified. The cache directory should not be used for anything else. """ # Store original directory to be able to restore later original_path = os.getcwd() # --- Validate arguments instant_assert(modulename is None or isinstance(modulename, str), "In instant.build_module: Expecting modulename to be string or None.") assert_is_str(source_directory) source_directory = os.path.abspath(source_directory) assert_is_str(code) assert_is_str(init_code) assert_is_str(additional_definitions) assert_is_str(additional_declarations) sources = strip_strings(sources) wrap_headers = strip_strings(wrap_headers) local_headers = strip_strings(local_headers) system_headers = strip_strings(system_headers) include_dirs = strip_strings(include_dirs) library_dirs = strip_strings(library_dirs) libraries = strip_strings(libraries) swigargs = arg_strings(swigargs) swig_include_dirs = strip_strings(swig_include_dirs) cppargs = arg_strings(cppargs) lddargs = arg_strings(lddargs) object_files = strip_strings(object_files) arrays = [strip_strings(a) for a in arrays] assert_is_bool(generate_interface) assert_is_bool(generate_setup) cmake_packages = strip_strings(cmake_packages) 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.") # --- Replace arguments with defaults if necessary cache_dir = validate_cache_dir(cache_dir) # 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") # --- Debugging code instant_debug('In instant.build_module:') instant_debug('::: Begin Arguments :::') instant_debug(' modulename: %r' % modulename) instant_debug(' source_directory: %r' % source_directory) instant_debug(' code: %r' % code) instant_debug(' init_code: %r' % init_code) instant_debug(' additional_definitions: %r' % additional_definitions) instant_debug(' additional_declarations: %r' % additional_declarations) instant_debug(' sources: %r' % sources) instant_debug(' csrcs: %r' % csrcs) instant_debug(' cppsrcs: %r' % cppsrcs) instant_debug(' wrap_headers: %r' % wrap_headers) instant_debug(' local_headers: %r' % local_headers) instant_debug(' system_headers: %r' % system_headers) instant_debug(' include_dirs: %r' % include_dirs) instant_debug(' library_dirs: %r' % library_dirs) instant_debug(' libraries: %r' % libraries) instant_debug(' swigargs: %r' % swigargs) instant_debug(' swig_include_dirs: %r' % swig_include_dirs) instant_debug(' cppargs: %r' % cppargs) instant_debug(' lddargs: %r' % lddargs) instant_debug(' object_files: %r' % object_files) instant_debug(' arrays: %r' % arrays) instant_debug(' generate_interface: %r' % generate_interface) instant_debug(' generate_setup: %r' % generate_setup) instant_debug(' cmake_packages: %r' % cmake_packages) instant_debug(' signature: %r' % signature) instant_debug(' cache_dir: %r' % cache_dir) instant_debug('::: End Arguments :::') # --- Setup module directory, making it and copying # files to it if necessary, and compute a modulename # if it isn't specified explicitly if modulename is None: # Compute a signature if we have none passed by the user: if signature is None: # Collect arguments used for checksum creation, # 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! #modulename, # We don't care where the user code resides: #source_directory, code, init_code, additional_definitions, additional_declarations, # Skipping filenames, since we use the file contents: #sources, wrap_headers, #local_headers, system_headers, include_dirs, library_dirs, libraries, 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: #signature, cache_dir) ) 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)) signature = modulename_from_checksum(compute_checksum(text, allfiles)) modulename = signature moduleids = [signature] else: module, moduleids = check_memory_cache(signature) if module: return module modulename = moduleids[-1] # Look for module in disk cache module = check_disk_cache(modulename, cache_dir, moduleids) if module: return module # 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'"\ % module_path) makedirs(module_path) use_cache = True else: use_cache = False moduleids = [] module_path = os.path.join(original_path, modulename) makedirs(module_path) ## Look for module in memory cache #module, moduleids = check_memory_cache(modulename) #if module: return module #instant_assert(modulename == moduleids[-1] and len(moduleids) == 1, "Logic breach.") ## Look for module in local directory #module = check_disk_cache(modulename, original_path, moduleids) #if module: return module # Wrapping rest of code in try-block to # clean up at the end if something fails. try: # --- Copy user-supplied files to module path 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. # --- Generate additional files in module directory os.chdir(module_path) # Generate __init__.py which imports compiled module contents write_file("__init__.py", "from %s import *" % modulename) # Generate SWIG interface if wanted 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) # 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) build_system = "distutils" else: 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. # Compute new_compilation_checksum # Collect arguments used for checksum creation, # including everything that affects the module compilation. # Since the interface file is included in allfiles, # we don't need stuff that modifies it here. checksum_args = ( \ # 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, #code, init_code, #additional_definitions, additional_declarations, # Skipping filenames, since we use the file contents: #sources, wrap_headers, #local_headers, system_headers, include_dirs, library_dirs, libraries, swigargs, swig_include_dirs, cppargs, lddargs, object_files, #arrays, #generate_interface, generate_setup, # The signature isn't defined, and the # cache_dir doesn't affect the module: #signature, cache_dir) ) text = "\n".join((str(a) for a in checksum_args)) allfiles = sources + wrap_headers + local_headers + [ifile_name] new_compilation_checksum = compute_checksum(text, allfiles) # Recompile if necessary recompile(modulename, module_path, new_compilation_checksum, build_system) # --- Load, cache, and return module # Copy compiled module to cache if use_cache: module_path = copy_to_cache(module_path, cache_dir, modulename) with file_lock(cache_dir, modulename) as lock: # Import module and place in memory cache module = import_and_cache_module(module_path, modulename, moduleids) else: # Import module and place in memory cache module = import_and_cache_module(module_path, modulename, moduleids) if not module: instant_error("Failed to import newly compiled module!") instant_debug("In instant.build_module: Returning %s from build_module."\ % module) return module # The end! finally: # Always get back to original directory. os.chdir(original_path) instant_error("In instant.build_module: Should never reach this point!") # end build_module def build_module_vtk(c_code, cache_dir=None): original_path = os.getcwd() cache_dir = validate_cache_dir(cache_dir) signature = modulename_from_checksum(compute_checksum(c_code)) modulename = signature moduleids = [signature] module_path = os.path.join(get_temp_dir(), modulename) makedirs(module_path) os.chdir(module_path) write_cmakefile(modulename) s = generate_interface_file_vtk(signature, c_code) write_vtk_interface_file(signature, c_code) ret, output = get_status_output("cmake -DDEBUG=TRUE . > cmake.log ") ret, output = get_status_output("make > compile.log ") module_path = copy_to_cache(module_path, cache_dir, modulename) os.chdir(original_path) lock = get_lock(cache_dir, modulename) module = import_and_cache_module(module_path, modulename, moduleids) release_lock(lock) return module def build_module_vmtk(c_code, cache_dir=None): original_path = os.getcwd() cache_dir = validate_cache_dir(cache_dir) signature = modulename_from_checksum(compute_checksum(c_code)) modulename = signature moduleids = [signature] module_path = os.path.join(get_temp_dir(), modulename) makedirs(module_path) os.chdir(module_path) write_vmtk_cmakefile(modulename) s = generate_interface_file_vtk(signature, c_code) write_vtk_interface_file(signature, c_code) ret, output = get_status_output("cmake -DDEBUG=TRUE . > cmake.log ") ret, output = get_status_output("make > compile.log ") module_path = copy_to_cache(module_path, cache_dir, modulename) os.chdir(original_path) lock = get_lock(cache_dir, modulename) module = import_and_cache_module(module_path, modulename, moduleids) release_lock(lock) return module instant-1.3.0/instant/cache.py000066400000000000000000000147021226277733300163100ustar00rootroot00000000000000"""This module contains helper functions for working with the module cache. Example operations: - modulename = modulename_from_checksum(checksum) - modulename = modulename_from_checksum(compute_checksum(signature)) - module = import_module_directly(path, modulename) - module = import_module(modulename) - module = import_module(checksum) - module = import_module(compute_checksum(signature)) - modules = cached_modules() - modules = cached_modules(cache_dir) """ import os, sys, re from .output import instant_warning, instant_assert, instant_debug from .paths import get_default_cache_dir, validate_cache_dir from .signatures import compute_checksum from .locking import get_lock, release_lock # 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." return _modulename_prefix + checksum def checksum_from_modulename(modulename): "Construct a module name from a checksum for use in cache." return modulename.remove(_modulename_prefix) def import_module_directly(path, modulename): "Import a module with the given module name that resides in the given path." sys.path.insert(0, path) e = None try: module = __import__(modulename) except Exception as e: instant_warning("In instant.import_module_directly: Failed to import module '%s' from '%s';\n%s:%s;" % (modulename, path, type(e).__name__, e)) module = None finally: sys.path.pop(0) return module, e _memory_cache = {} 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)) 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)) def is_valid_module_name(name): NAMELENGTHLIMIT = 200 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)) for moduleid in moduleids: place_module_in_memory_cache(moduleid, module) return module def check_memory_cache(moduleid): # Check memory cache first with the given 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"): moduleid = moduleid.signature() instant_debug("In instant.check_memory_cache: Got signature "\ "'%s' from moduleid.signature()." % moduleid) module = memory_cached_module(moduleid) if module: # 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 # 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): moduleid = modulename_from_checksum(compute_checksum(moduleid)) instant_debug("In instant.check_memory_cache: Constructed module name "\ "'%s' from moduleid '%s'." % (moduleid, moduleids[-1])) 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 def check_disk_cache(modulename, cache_dir, moduleids): # Get file lock to avoid race conditions in cache lock = get_lock(cache_dir, modulename) # 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.isdir(os.path.join(path, modulename)): # Found existing directory, try to import and place in memory cache module = import_and_cache_module(path, modulename, moduleids) if module: instant_debug("In instant.check_disk_cache: Imported module "\ "'%s' from '%s'." % (modulename, path)) release_lock(lock) return module 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)) release_lock(lock) return None 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 - a checksum string, which is used directly to look up in the cache - a hashable non-string object with a function moduleid.signature() which is used to get a signature string The hashable object is used to look up in the memory cache before signature() is called. If the module is found on disk, it is placed in the memory cache. """ # 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) 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) instant-1.3.0/instant/codegeneration.py000066400000000000000000000473071226277733300202420ustar00rootroot00000000000000"""This module contains helper functions for code generation.""" import re, os from output import instant_assert, instant_warning, instant_debug, write_file from config import get_swig_binary def mapstrings(format, sequence): return "\n".join(format % i for i in sequence) def reindent(code): '''Reindent a multiline string to allow easier to read syntax. Each line will be indented relative to the first non-empty line. Start the first line without text like shown in this example:: code = reindent(""" Foo Bar Blatti Ping """) makes all indentation relative to Foo. ''' lines = code.split("\n") space = "" # Get initial spaces from first non-empty line: for l in lines: if l: r = re.search(r"^( [ ]*)", l) if r is not None: space = r.groups()[0] break if not space: return code n = len(space) instant_assert(space == " "*n, "Logic breach in reindent.") return "\n".join(re.sub(r"^%s" % space, "", l) for l in lines) def write_interfacefile(filename, modulename, code, init_code, additional_definitions, additional_declarations, system_headers, local_headers, wrap_headers, arrays): """Generate a SWIG interface file. Intended for internal library use. The input arguments are as follows: - modulename (Name of the module) - code (Code to be wrapped) - init_code (Code to put in the init section of the interface file) - additional_definitions (Definitions to be placed in initial block with C code as well as in the main section of the SWIG interface file) - additional_declarations (Declarations to be placed in the main section of the SWIG interface file) - system_headers (A list of system headers with declarations needed by the wrapped code) - local_headers (A list of local headers with declarations needed by the wrapped code) - wrap_headers (A list of local headers that will be included in the code and wrapped by SWIG) - arrays (A nested list, the inner lists describing the different arrays) The result of this function is that a SWIG interface with the name modulename.i is written to the current directory. """ instant_debug("Generating SWIG interface file '%s'." % filename) # create typemaps typemaps = "" valid_types = ['float', 'double', 'short', 'int', 'long', 'long long', 'unsigned short', 'unsigned int', 'unsigned long', 'unsigned long long'] for a in arrays: if type(a) == tuple: a = list(a) DATA_TYPE = 'double' for vt in valid_types: if vt in a: DATA_TYPE = vt a.remove(vt) 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") if len(a) == 2: # 1-dimensional arrays, i.e. vectors typemaps += reindent(""" %%apply (int DIM1, %(dtype)s* IN_ARRAY1) {(int %(n1)s, %(dtype)s* %(array)s)}; """ % { 'n1' : a[0], 'array' : a[1], 'dtype' : DATA_TYPE }) elif len(a) == 3: # 2-dimensional arrays, i.e. matrices typemaps += reindent(""" %%apply (int DIM1, int DIM2, %(dtype)s* IN_ARRAY2) {(int %(n1)s, int %(n2)s, %(dtype)s* %(array)s)}; """ % { 'n1' : a[0], 'n2' : a[1], 'array' : a[2], 'dtype' : DATA_TYPE }) else: # 3-dimensional arrays, i.e. tensors typemaps += reindent(""" %%apply (int DIM1, int DIM2, int DIM3, %(dtype)s* IN_ARRAY3) {(int %(n1)s, int %(n2)s, int %(n3)s, %(dtype)s* %(array)s)}; """ % { 'n1' : a[0], 'n2' : a[1], 'n3' : a[2], 'array' : a[3], 'dtype' : DATA_TYPE }) elif 'out' in a: # output arrays a.remove('out') instant_assert(len(a) == 2, "Output array must be 1-dimensional") # 1-dimensional arrays, i.e. vectors typemaps += reindent(""" %%apply (int DIM1, %(dtype)s* ARGOUT_ARRAY1) {(int %(n1)s, %(dtype)s* %(array)s)}; """ % { '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") if 'multi' in a: # n-dimensional arrays, i.e. tensors > 3-dimensional a.remove('multi') typemaps += reindent(""" %%typemap(in) (int %(n)s,int* %(ptv)s,%(dtype)s* %(array)s){ if (!PyArray_Check($input)) { PyErr_SetString(PyExc_TypeError, "Not a NumPy array"); return NULL; ; } PyArrayObject* pyarray; pyarray = (PyArrayObject*)$input; $1 = int(pyarray->nd); int* dims = new int[$1]; for (int d=0; d<$1; d++) { dims[d] = int(pyarray->dimensions[d]); } $2 = dims; $3 = (%(dtype)s*)pyarray->data; } %%typemap(freearg) (int %(n)s,int* %(ptv)s,%(dtype)s* %(array)s){ // deleting dims delete $2; } """ % { 'n' : a[0] , 'ptv' : a[1], 'array' : a[2], 'dtype' : DATA_TYPE }) elif len(a) == 2: # 1-dimensional arrays, i.e. vectors typemaps += reindent(""" %%apply (int DIM1, %(dtype)s* INPLACE_ARRAY1) {(int %(n1)s, %(dtype)s* %(array)s)}; """ % { 'n1' : a[0], 'array' : a[1], 'dtype' : DATA_TYPE }) elif len(a) == 3: # 2-dimensional arrays, i.e. matrices typemaps += reindent(""" %%apply (int DIM1, int DIM2, %(dtype)s* INPLACE_ARRAY2) {(int %(n1)s, int %(n2)s, %(dtype)s* %(array)s)}; """ % { 'n1' : a[0], 'n2' : a[1], 'array' : a[2], 'dtype' : DATA_TYPE }) else: # 3-dimensional arrays, i.e. tensors typemaps += reindent(""" %%apply (int DIM1, int DIM2, int DIM3, %(dtype)s* INPLACE_ARRAY3) {(int %(n1)s, int %(n2)s, int %(n3)s, %(dtype)s* %(array)s)}; """ % { 'n1' : a[0], 'n2' : a[1], 'n3' : a[2], 'array' : a[3], 'dtype' : DATA_TYPE}) # end # end if # end for system_headers_code = mapstrings('#include <%s>', system_headers) local_headers_code = mapstrings('#include "%s"', local_headers) wrap_headers_code1 = mapstrings('#include "%s"', wrap_headers) wrap_headers_code2 = mapstrings('%%include "%s"', wrap_headers) numpy_i_include = '' if arrays: numpy_i_include = r'%include "numpy.i"' # Do not reindent as SWIG interface code can also include Python code. interface_string = """%%module %(modulename)s //%%module (directors="1") %(modulename)s //%%feature("director"); %%{ #include %(additional_definitions)s %(system_headers_code)s %(local_headers_code)s %(wrap_headers_code1)s %(code)s %%} //%%feature("autodoc", "1"); %(numpy_i_include)s %%init%%{ %(init_code)s %%} %(additional_definitions)s %(additional_declarations)s %(wrap_headers_code2)s //%(typemaps)s %(code)s; """ % locals() write_file(filename, interface_string) instant_debug("Done generating interface file.") def write_setup(filename, modulename, csrcs, cppsrcs, local_headers, include_dirs, library_dirs, libraries, swig_include_dirs, swigargs, cppargs, lddargs): """Generate a setup.py file. Intended for internal library use.""" instant_debug("Generating %s." % filename) swig_include_dirs.append(os.path.join(os.path.dirname(__file__), 'swig')) # Handle arguments swigfilename = "%s.i" % modulename wrapperfilename = "%s_wrap.cxx" % modulename # Treat C and C++ files in the same way for now cppsrcs = cppsrcs + csrcs + [wrapperfilename] swig_args = "" if swigargs: swig_args = " ".join(swigargs) compile_args = "" if cppargs: compile_args = ", extra_compile_args=%r" % cppargs link_args = "" if lddargs: link_args = ", extra_link_args=%r" % lddargs swig_include_dirs = " ".join("-I%s"%d for d in swig_include_dirs) if len(local_headers) > 0: swig_include_dirs += " -I.." # Generate code code = reindent(""" import os from distutils.core import setup, Extension name = '%s' swig_cmd =r'%s -python %s %s %s' os.system(swig_cmd) sources = %s setup(name = '%s', ext_modules = [Extension('_' + '%s', sources, include_dirs=%s, library_dirs=%s, libraries=%s %s %s)]) """ % (modulename, get_swig_binary(), swig_include_dirs, swig_args, \ swigfilename, cppsrcs, modulename, modulename, include_dirs, \ library_dirs, libraries, compile_args, link_args)) write_file(filename, code) instant_debug("Done writing setup.py file.") def _test_write_interfacefile(): modulename = "testmodule" code = "void foo() {}" init_code = "/* custom init code */" additional_definitions = "/* custom definitions */" additional_declarations = "/* custom declarations */" system_headers = ["system_header1.h", "system_header2.h"] local_headers = ["local_header1.h", "local_header2.h"] wrap_headers = ["wrap_header1.h", "wrap_header2.h"] arrays = [["length1", "array1"], ["dims", "lengths", "array2"]] write_interfacefile("%s.i" % modulename, modulename, code, init_code, \ additional_definitions, additional_declarations, \ system_headers, local_headers, wrap_headers, arrays) print "".join(open("%s.i" % modulename).readlines()) def _test_write_setup(): modulename = "testmodule" csrcs = ["csrc1.c", "csrc2.c"] cppsrcs = ["cppsrc1.cpp", "cppsrc2.cpp"] local_headers = ["local_header1.h", "local_header2.h"] include_dirs = ["includedir1", "includedir2"] library_dirs = ["librarydir1", "librarydir2"] libraries = ["lib1", "lib2"] swig_include_dirs = ["swigdir1", "swigdir2"], swigargs = ["-Swigarg1", "-Swigarg2"] cppargs = ["-cpparg1", "-cpparg2"] lddargs = ["-Lddarg1", "-Lddarg2"] write_setup("setup.py", modulename, csrcs, cppsrcs, local_headers, \ include_dirs, library_dirs, libraries, swig_include_dirs, \ swigargs, cppargs, lddargs) print "".join(open("setup.py").readlines()) def unique(list): set = {} map(set.__setitem__, list, []) return set.keys() def find_vtk_classes(str): pattern = "vtk\w*" l = unique(re.findall(pattern, str)) return l def create_typemaps(classes): s = "" typemap_template = """ %%typemap(in) %(class_name)s * { vtkObjectBase* obj = vtkPythonGetPointerFromObject($input, "%(class_name)s"); %(class_name)s * oobj = NULL; if (obj->IsA("%(class_name)s")) { oobj = %(class_name)s::SafeDownCast(obj); $1 = oobj; } } %%typemap(out) %(class_name)s * { $result = vtkPythonGetObjectFromPointer($1); } """ for cl in classes: s += typemap_template % { "class_name" : cl } return s def generate_vtk_includes(classes): s = """ #include "vtkPythonUtil.h" """ for cl in classes: s += """ #include \"%s.h\" """ % cl return s def generate_interface_file_vtk(signature, code): interface_template = """ %%module test %%{ %(includes)s %(code)s %%} %(typemaps)s %(code)s """ class_list = find_vtk_classes(code) includes = generate_vtk_includes(class_list) typemaps = create_typemaps(class_list) s = interface_template % { "typemaps" : typemaps, "code" : code, "includes" : includes } return s def write_cmakefile(module_name, cmake_packages, csrcs, cppsrcs, local_headers, include_dirs, library_dirs, libraries, swig_include_dirs, swigargs, cppargs, lddargs): find_package_template = """ # Configuration for package %(package)s FIND_PACKAGE(%(package)s REQUIRED) IF(%(package)s_FOUND) INCLUDE(${%(PACKAGE)s_USE_FILE}) ENDIF(%(package)s_FOUND) """ cmake_form = dict(module_name=module_name) cmake_form["extra_libraries"] = ";".join(libraries) cmake_form["extra_include_dirs"] = ";".join(include_dirs) cmake_form["extra_swig_include_dirs"] = " -I".join([" "] + swig_include_dirs) cmake_form["extra_swigargs"] = " ".join(swigargs) cmake_form["find_packages"] = "\n\n".join(find_package_template % \ dict(package=package, PACKAGE=package.upper())\ for package in cmake_packages) cmake_form["packages_definitions"] = "\n".join( "${%s_CXX_DEFINITIONS}" % package.upper() for package in cmake_packages) cmake_form["packages_definitions"] += "\n"+"\n".join( "${%s_PYTHON_DEFINITIONS}" % package.upper() for package in cmake_packages) cmake_form["package_include_dirs"] = "\n".join(\ "include_directories(${%s_PYTHON_INCLUDE_DIRS} ${${NAME}_SOURCE_DIR})" % package.upper() for package in cmake_packages) cmake_form["package_flags"] = "\n".join(\ """set(CMAKE_EXE_LINKER_FLAGS \"${CMAKE_EXE_LINKER_FLAGS} ${%(package)s_LINK_FLAGS}\") set(CMAKE_SHARED_LINKER_FLAGS \"${CMAKE_SHARED_LINKER_FLAGS} ${%(package)s_LINK_FLAGS}\") """ % dict(package=package.upper()) for package in cmake_packages) cmake_form["package_swig_link_libraries"] = "\n".join(\ """if (DEFINED %(package)s_LIBRARIES OR DEFINED %(package)s_3RD_PARTY_LIBRARIES OR DEFINED %(package)s_PYTHON_LIBRARIES) swig_link_libraries(${SWIG_MODULE_NAME} ${%(package)s_LIBRARIES} ${%(package)s_3RD_PARTY_LIBRARIES} ${%(package)s_PYTHON_LIBRARIES} ${EXTRA_SOURCE_LIB}) endif()""" % dict(package=package.upper()) for package in cmake_packages) cmake_form["package_python_definitions"] = "\n".join(\ """if (DEFINED %(package)s_PYTHON_DEFINITIONS) add_definitions(${%(package)s_PYTHON_DEFINITIONS}) endif()""" % dict(package=package.upper()) for package in cmake_packages) cppsrcs.extend(csrcs) if len(cppsrcs) > 0: cmake_form["extra_sources_files"] = "set(SOURCE_FILES %s) " % " ".join(cppsrcs) else: cmake_form["extra_sources_files"] = "set(SOURCE_FILES)" if cppargs: cmake_form["cppargs"] = "set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} %s\")" % \ (" ".join(cppargs)) else: cmake_form["cppargs"] = "" if lddargs: cmake_form["lddargs"] = "set(CMAKE_EXE_LINKER_FLAGS \""\ "${CMAKE_EXE_LINKER_FLAGS} %s\")" % (" ".join(lddargs)) else: cmake_form["lddargs"] = "" cmake_template = """ cmake_minimum_required(VERSION 2.6.0) set (NAME %(module_name)s) %(find_packages)s PROJECT(${NAME}) %(cppargs)s %(lddargs)s find_package(SWIG REQUIRED) include(${SWIG_USE_FILE}) set(SWIG_MODULE_NAME ${NAME}) set(CMAKE_SWIG_FLAGS -module ${SWIG_MODULE_NAME} -shadow -modern -modernargs -fastdispatch -fvirtual -nosafecstrings -noproxydel -fastproxy -fastinit -fastunpack -fastquery -nobuildnone %(packages_definitions)s %(extra_swigargs)s %(extra_swig_include_dirs)s ) set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) set(SWIG_SOURCES ${NAME}.i) set_source_files_properties(${SWIG_SOURCES} PROPERTIES CPLUSPLUS ON) set(EXTRA_INCLUDE_DIRS \"%(extra_include_dirs)s\") if(EXTRA_INCLUDE_DIRS) include_directories(${EXTRA_INCLUDE_DIRS}) endif() %(package_include_dirs)s %(package_flags)s %(extra_sources_files)s %(package_python_definitions)s swig_add_module(${SWIG_MODULE_NAME} python ${SWIG_SOURCES}) set(EXTRA_LIBRARIES %(extra_libraries)s) if(SOURCE_FILES) set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -fpic\") add_library(source_file_lib STATIC ${SOURCE_FILES}) set(EXTRA_LIBRARIES \"source_file_lib ${EXTRA_LIBRARIES}\") endif() if(EXTRA_LIBRARIES) string(STRIP \"${EXTRA_LIBRARIES}\" EXTRA_LIBRARIES) swig_link_libraries(${SWIG_MODULE_NAME} ${EXTRA_LIBRARIES}) endif() %(package_swig_link_libraries)s """ % cmake_form filename = "CMakeLists.txt" write_file(filename, cmake_template) def write_itk_cmakefile(name): file_template = """ cmake_minimum_required(VERSION 2.6.0) # This project is designed to be built outside the Insight source tree. PROJECT(%(name)%s) # Find ITK. FIND_PACKAGE(ITK REQUIRED) IF(ITK_FOUND) INCLUDE(${ITK_USE_FILE}) ENDIF(ITK_FOUND) # Find VTK. FIND_PACKAGE(VTK REQUIRED) IF(VTK_FOUND) INCLUDE(${VTK_USE_FILE}) ENDIF(VTK_FOUND) find_package(SWIG REQUIRED) include(${SWIG_USE_FILE}) set(SWIG_MODULE_NAME %(name)s) set(CMAKE_SWIG_FLAGS -module ${SWIG_MODULE_NAME} -shadow -modern -modernargs -fastdispatch -fvirtual -nosafecstrings -noproxydel -fastproxy -fastinit -fastunpack -fastquery -nobuildnone -Iinclude/swig ) set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) set(SWIG_SOURCES %(name)s.i) set_source_files_properties(${SWIG_SOURCES} PROPERTIES CPLUSPLUS ON) include_directories(${PYTHON_INCLUDE_PATH} ${%(name)s_SOURCE_DIR}) set(VTK_LIBS ITKCommon vtkCommon vtkImaging vtkIO vtkFiltering vtkRendering vtkGraphics vtkCommonPythonD vtkFilteringPythonD) swig_add_module(${SWIG_MODULE_NAME} python ${SWIG_SOURCES}) swig_link_libraries(${SWIG_MODULE_NAME} ${PYTHON_LIBRARIES} ${VTK_LIBS}) """ % { "name" : name } f = open("CMakeLists.txt", 'w') f.write(file_template) def write_vmtk_cmakefile(name): file_template = """ cmake_minimum_required(VERSION 2.6.0) # This project is designed to be built outside the Insight source tree. PROJECT(%(name)%s) # Find ITK. FIND_PACKAGE(ITK REQUIRED) IF(ITK_FOUND) INCLUDE(${ITK_USE_FILE}) ENDIF(ITK_FOUND) # Find VTK. FIND_PACKAGE(VTK REQUIRED) IF(VTK_FOUND) INCLUDE(${VTK_USE_FILE}) ENDIF(VTK_FOUND) # Find VMTK. #FIND_PACKAGE(VMTK REQUIRED) #IF(VMTK_FOUND) # INCLUDE(${VMTK_USE_FILE}) #ENDIF(ITK_FOUND) find_package(SWIG REQUIRED) include(${SWIG_USE_FILE}) set(SWIG_MODULE_NAME %(name)s) set(CMAKE_SWIG_FLAGS -module ${SWIG_MODULE_NAME} -shadow -modern -modernargs -fastdispatch -fvirtual -nosafecstrings -noproxydel -fastproxy -fastinit -fastunpack -fastquery -nobuildnone -Iinclude/swig ) set(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_BINARY_DIR}) set(SWIG_SOURCES %(name)s.i) set_source_files_properties(${SWIG_SOURCES} PROPERTIES CPLUSPLUS ON) include_directories(${PYTHON_INCLUDE_PATH} ${%(name)s_SOURCE_DIR} /usr/local/include/vmtk) link_directories(/usr/local/lib/vmtk .) set(VTK_LIBS ITKCommon vtkCommon vtkImaging vtkIO vtkFiltering vtkRendering vtkGraphics vtkCommonPythonD vtkFilteringPythonD) set(VMTK_LIBS vtkvmtkCommonPythonD vtkvmtkITKPythonD vtkvmtkCommon vtkvmtkITK vtkvmtkComputationalGeometryPythonD vtkvmtkMiscPythonD vtkvmtkComputationalGeometry vtkvmtkMisc vtkvmtkDifferentialGeometryPythonD vtkvmtkSegmentationPythonD vtkvmtkDifferentialGeometry vtkvmtkSegmentation vtkvmtkIOPythonD) swig_add_module(${SWIG_MODULE_NAME} python ${SWIG_SOURCES}) swig_link_libraries(${SWIG_MODULE_NAME} ${PYTHON_LIBRARIES} ${VTK_LIBS} ${VMTK_LIBS}) """ % { "name" : name } f = open("CMakeLists.txt", 'w') f.write(file_template) def write_vtk_interface_file(signature, code): filename = signature ifile = filename + ".i" iff = open(ifile, 'w') ifile_code = generate_interface_file_vtk(signature, code) iff.write(ifile_code) if __name__ == "__main__": _test_write_interfacefile() print "\n"*3 _test_write_setup() instant-1.3.0/instant/config.py000066400000000000000000000132301226277733300165050ustar00rootroot00000000000000"""This module contains helper functions for configuration using pkg-config.""" import os from .output import get_status_output import re # Global cache variables _swig_binary_cache = None _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): raise TypeError("expected a 'str' as first argument") if not isinstance(path, str): 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: return False # Set binary cache _swig_binary_cache = swig_binary # Reset SWIG version cache 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: 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 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 '.'" 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: break elif handed_version[i] == v: continue 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: (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.") env = os.environ.copy() try: assert env["PKG_CONFIG_ALLOW_SYSTEM_CFLAGS"] == "0" except: env["PKG_CONFIG_ALLOW_SYSTEM_CFLAGS"] = "1" includes = [] flags = [] libs = [] libdirs = [] linkflags = [] for pack in packages: if not pack in _header_and_library_cache: result, output = get_status_output(\ "pkg-config --exists %s " % pack, env=env) 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] _flags = get_status_output(\ "pkg-config --cflags-only-other %s " % pack, env=env)[1].split() tmp = get_status_output(\ "pkg-config --libs-only-l %s " % pack, env=env)[1].split() _libs = [i[2:] for i in tmp] tmp = get_status_output(\ "pkg-config --libs-only-L %s " % pack, env=env)[1].split() _libdirs = [i[2:] for i in tmp] _linkflags = get_status_output(\ "pkg-config --libs-only-other %s " % pack, env=env)[1].split() _header_and_library_cache[pack] = (_includes, _flags, _libs, \ _libdirs, _linkflags) else: _header_and_library_cache[pack] = None result = _header_and_library_cache[pack] if not result: raise OSError("The pkg-config file %s does not exist" % pack) _includes, _flags, _libs, _libdirs, _linkflags = result includes.extend(_includes) flags.extend(_flags) libs.extend(_libs) libdirs.extend(_libdirs) linkflags.extend(_linkflags) if returnLinkFlags: return (includes, flags, libs, libdirs, linkflags) return (includes, flags, libs, libdirs) instant-1.3.0/instant/inlining.py000066400000000000000000000124251226277733300170540ustar00rootroot00000000000000"""This module contains the inline* functions, which allows easy inlining of C/C++ functions.""" from .output import instant_assert, instant_warning, instant_error from .build import build_module, build_module_vtk, build_module_vmtk def get_func_name(c_code): # TODO: Something more robust? Regexp? try: func = c_code[:c_code.index('(')] ret, func_name = func.split() except: instant_error("Failed to extract function name from c_code.") return func_name def inline(c_code, **kwargs): """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. Usage: >>> from instant import inline >>> add_func = inline("double add(double a, double b){ return a+b; }") >>> print "The sum of 3 and 4.5 is ", add_func(3, 4.5) """ instant_assert("code" not in kwargs, "Cannot specify code twice.") kwargs["code"] = c_code func_name = get_func_name(c_code) module = build_module(**kwargs) if hasattr(module, func_name): return getattr(module, func_name) else: 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. It creates a module given that the input is a valid C function. It is only possible to inline one C function each time. Usage: >>> from instant import inline >>> add_func = inline("double add(double a, double b){ return a+b; }") >>> print "The sum of 3 and 4.5 is ", add_func(3, 4.5) """ instant_assert("code" not in kwargs, "Cannot specify code twice.") kwargs["code"] = c_code module = build_module(**kwargs) return module def inline_with_numpy(c_code, **kwargs): '''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. 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>> 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["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()] func_name = get_func_name(c_code) module = build_module(**kwargs) if hasattr(module, func_name): return getattr(module, func_name) else: instant_warning("Didn't find function '%s', returning module." % func_name) return module def inline_module_with_numpy(c_code, **kwargs): '''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. 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>> 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["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()] module = build_module(**kwargs) return module def inline_vtk(c_code, cache_dir=None): module = build_module_vtk(c_code) func_name = get_func_name(c_code) if hasattr(module, func_name): return getattr(module, func_name) else: instant_warning("Didn't find function '%s', returning module." % func_name) return module def inline_vmtk(c_code, cache_dir=None): module = build_module_vmtk(c_code) func_name = get_func_name(c_code) if hasattr(module, func_name): return getattr(module, func_name) else: instant_warning("Didn't find function '%s', returning module." % func_name) return module instant-1.3.0/instant/locking.py000066400000000000000000000107551226277733300166770ustar00rootroot00000000000000"""File locking for the cache system, to avoid problems when multiple processes work with the same module. Only works on UNIX systems. Two python libraries can be used: flufl.lock : A nfs safe which can be downloaded from: https://launchpad.net/flufl.lock fcntl : A builtin Python module which only works on posix machines and it is does unfortunately not work on nfs """ __all__ = ["get_lock", "release_lock", "release_all_lock", "file_lock"] import os.path from .output import instant_error, instant_assert, instant_debug from .paths import validate_cache_dir try: import flufl.lock fcntl = None except: flufl = None try: import fcntl except: fcntl = None # 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 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: hostname, pid, lockname = lock.details instant_debug("Releasing lock %s." % (lockname)) lock.unlock() def release_all_locks(): pass 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") fcntl.flock(lock.fileno(), fcntl.LOCK_EX) _lock_names[lock.fileno()] = lockname _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] import inspect frame = inspect.currentframe().f_back instant_debug("Releasing lock %s, count is %d. Called from: %s line: %d" % \ (lockname, count, inspect.getfile(frame), frame.f_lineno)) 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()) for lock in locks: release_lock(lock) 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 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 """ 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 def __exit__(self, type, value, tb): release_lock(self.lock) instant-1.3.0/instant/output.py000066400000000000000000000072521226277733300166070ustar00rootroot00000000000000"""This module contains internal logging utilities.""" import logging # Logging wrappers _log = logging.getLogger("instant") _loghandler = logging.StreamHandler() _log.addHandler(_loghandler) _log.setLevel(logging.WARNING) _log.setLevel(logging.INFO) #_log.setLevel(logging.DEBUG) 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 instant_warning("set_logging_level is deprecated but was called "\ "from %s, at line %d. Use set_log_level instead." % \ (inspect.getfile(frame), frame.f_lineno)) set_log_level(level) def set_log_level(level): if isinstance(level, str): level = level.upper() assert level in ("INFO", "WARNING", "ERROR", "DEBUG") level = getattr(logging, level) else: 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: f = open(filename, "w") f.write(text) f.close() except IOError as e: instant_error("Can't open '%s': %s" % (filename, e)) from subprocess import Popen, PIPE, STDOUT 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): cmd = cmd.strip().split() instant_debug("Running: " + str(cmd)) pipe = Popen(cmd, shell=False, cwd=cwd, env=env, stdout=PIPE, stderr=STDOUT) (output, errout) = pipe.communicate(input=input) assert not errout status = pipe.returncode return (status, output) def get_output(cmd): "Replacement for commands.getoutput which does not work on Windows." if isinstance(cmd, str): cmd = cmd.strip().split() pipe = Popen(cmd, shell=False, stdout=PIPE, stderr=STDOUT, bufsize=-1) r = pipe.wait() output, error = pipe.communicate() return output # Some HPC platforms does not work with the subprocess module and needs commands #import platform #if platform.system() == "Windows": # # Taken from http://ivory.idyll.org/blog/mar-07/replacing-commands-with-subprocess # from subprocess import Popen, PIPE, STDOUT # def get_status_output(cmd, input=None, cwd=None, env=None): # "Replacement for commands.getstatusoutput which does not work on Windows." # pipe = Popen(cmd, shell=True, cwd=cwd, env=env, stdout=PIPE, stderr=STDOUT) # # (output, errout) = pipe.communicate(input=input) # assert not errout # # status = pipe.returncode # # return (status, output) # # def get_output(cmd): # "Replacement for commands.getoutput which does not work on Windows." # pipe = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT, bufsize=-1) # r = pipe.wait() # output, error = pipe.communicate() # return output # #else: # import commands # get_status_output = commands.getstatusoutput # get_output = commands.getoutput instant-1.3.0/instant/paths.py000066400000000000000000000056511226277733300163670ustar00rootroot00000000000000"""This module contains helper functions for working with temp and cache directories.""" # Utilities for directory handling: import os import errno import shutil import tempfile import time 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 if _tmp_dir is None: datestring = "%d-%d-%d-%02d-%02d" % time.localtime()[:5] suffix = datestring + "_instant_" + compute_checksum(get_default_cache_dir()) _tmp_dir = tempfile.mkdtemp(suffix) 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 if _tmp_dir and os.path.isdir(_tmp_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") makedirs(instant_dir) return instant_dir def get_default_cache_dir(): "Return the default cache directory." cache_dir = os.environ.get("INSTANT_CACHE_DIR") # Catches the cases where INSTANT_CACHE_DIR is not set or '' if not cache_dir: cache_dir = os.path.join(get_instant_dir(), "cache") makedirs(cache_dir) return cache_dir def get_default_error_dir(): "Return the default error directory." error_dir = os.environ.get("INSTANT_ERROR_DIR") # Catches the cases where INSTANT_ERROR_DIR is not set or '' if not error_dir: error_dir = os.path.join(get_instant_dir(), "error") 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.") 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. """ try: os.makedirs(path) instant_debug("In instant.makedirs: Creating directory %r" % path) except os.error as e: if e.errno != errno.EEXIST: raise def _test(): from .output import set_logging_level set_logging_level("DEBUG") print("Temp dir:", get_temp_dir()) print("Instant dir:", get_instant_dir()) print("Default cache dir:", get_default_cache_dir()) print("Default error dir:", get_default_error_dir()) delete_temp_dir() if __name__ == "__main__": _test() instant-1.3.0/instant/signatures.py000066400000000000000000000026601226277733300174310ustar00rootroot00000000000000"""This module contains helper functions for working with checksums.""" import hashlib from .output import instant_assert, instant_debug, instant_error 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(filenames, (list,tuple)), "Expecting sequence.") m = hashlib.new('sha1') if text: m.update(text) for filename in sorted(filenames): instant_debug("Adding file '%s' to checksum." % filename) try: fp = open(filename, 'rb') except IOError as e: instant_error("Can't open file '%s': %s" % (filename, e)) try: while 1: data = fp.read() if not data: break m.update(data) except IOError as e: instant_error("I/O error reading '%s': %s" % (filename, e)) fp.close() return m.hexdigest().lower() def _test(): signature = "(Test signature)" files = ["signatures.py", "__init__.py"] print() print("Signature:", repr(signature)) print("Checksum:", compute_checksum(signature, [])) print() print("Files:", files) print("Checksum:", compute_checksum("", files)) print() if __name__ == "__main__": _test() instant-1.3.0/instant/swig/000077500000000000000000000000001226277733300156405ustar00rootroot00000000000000instant-1.3.0/instant/swig/numpy.i000066400000000000000000001636361226277733300172010ustar00rootroot00000000000000/* -*- C -*- (not really, but good for syntax highlighting) */ #ifdef SWIGPYTHON %{ #ifndef SWIG_FILE_WITH_INIT # define NO_IMPORT_ARRAY #endif #include "stdio.h" #include %} /**********************************************************************/ %fragment("NumPy_Backward_Compatibility", "header") { /* Support older NumPy data type names */ %#if NDARRAY_VERSION < 0x01000000 %#define NPY_BOOL PyArray_BOOL %#define NPY_BYTE PyArray_BYTE %#define NPY_UBYTE PyArray_UBYTE %#define NPY_SHORT PyArray_SHORT %#define NPY_USHORT PyArray_USHORT %#define NPY_INT PyArray_INT %#define NPY_UINT PyArray_UINT %#define NPY_LONG PyArray_LONG %#define NPY_ULONG PyArray_ULONG %#define NPY_LONGLONG PyArray_LONGLONG %#define NPY_ULONGLONG PyArray_ULONGLONG %#define NPY_FLOAT PyArray_FLOAT %#define NPY_DOUBLE PyArray_DOUBLE %#define NPY_LONGDOUBLE PyArray_LONGDOUBLE %#define NPY_CFLOAT PyArray_CFLOAT %#define NPY_CDOUBLE PyArray_CDOUBLE %#define NPY_CLONGDOUBLE PyArray_CLONGDOUBLE %#define NPY_OBJECT PyArray_OBJECT %#define NPY_STRING PyArray_STRING %#define NPY_UNICODE PyArray_UNICODE %#define NPY_VOID PyArray_VOID %#define NPY_NTYPES PyArray_NTYPES %#define NPY_NOTYPE PyArray_NOTYPE %#define NPY_CHAR PyArray_CHAR %#define NPY_USERDEF PyArray_USERDEF %#define npy_intp intp %#define NPY_MAX_BYTE MAX_BYTE %#define NPY_MIN_BYTE MIN_BYTE %#define NPY_MAX_UBYTE MAX_UBYTE %#define NPY_MAX_SHORT MAX_SHORT %#define NPY_MIN_SHORT MIN_SHORT %#define NPY_MAX_USHORT MAX_USHORT %#define NPY_MAX_INT MAX_INT %#define NPY_MIN_INT MIN_INT %#define NPY_MAX_UINT MAX_UINT %#define NPY_MAX_LONG MAX_LONG %#define NPY_MIN_LONG MIN_LONG %#define NPY_MAX_ULONG MAX_ULONG %#define NPY_MAX_LONGLONG MAX_LONGLONG %#define NPY_MIN_LONGLONG MIN_LONGLONG %#define NPY_MAX_ULONGLONG MAX_ULONGLONG %#define NPY_MAX_INTP MAX_INTP %#define NPY_MIN_INTP MIN_INTP %#define NPY_FARRAY FARRAY %#define NPY_F_CONTIGUOUS F_CONTIGUOUS %#endif } /**********************************************************************/ /* The following code originally appeared in * enthought/kiva/agg/src/numeric.i written by Eric Jones. It was * translated from C++ to C by John Hunter. Bill Spotz has modified * it to fix some minor bugs, upgrade from Numeric to numpy (all * versions), add some comments and functionality, and convert from * direct code insertion to SWIG fragments. */ %fragment("NumPy_Macros", "header") { /* Macros to extract array attributes. */ %#define is_array(a) ((a) && PyArray_Check((PyArrayObject *)a)) %#define array_type(a) (int)(PyArray_TYPE(a)) %#define array_numdims(a) (((PyArrayObject *)a)->nd) %#define array_dimensions(a) (((PyArrayObject *)a)->dimensions) %#define array_size(a,i) (((PyArrayObject *)a)->dimensions[i]) %#define array_data(a) (((PyArrayObject *)a)->data) %#define array_is_contiguous(a) (PyArray_ISCONTIGUOUS(a)) %#define array_is_native(a) (PyArray_ISNOTSWAPPED(a)) %#define array_is_fortran(a) (PyArray_ISFORTRAN(a)) } /**********************************************************************/ %fragment("NumPy_Utilities", "header") { /* Given a PyObject, return a string describing its type. */ const char* pytype_string(PyObject* py_obj) { if (py_obj == NULL ) return "C NULL value"; if (py_obj == Py_None ) return "Python None" ; if (PyCallable_Check(py_obj)) return "callable" ; if (PyString_Check( py_obj)) return "string" ; if (PyInt_Check( py_obj)) return "int" ; if (PyFloat_Check( py_obj)) return "float" ; if (PyDict_Check( py_obj)) return "dict" ; if (PyList_Check( py_obj)) return "list" ; if (PyTuple_Check( py_obj)) return "tuple" ; if (PyFile_Check( py_obj)) return "file" ; if (PyModule_Check( py_obj)) return "module" ; if (PyInstance_Check(py_obj)) return "instance" ; return "unkown type"; } /* Given a NumPy typecode, return a string describing the type. */ const char* typecode_string(int typecode) { static const char* type_names[25] = {"bool", "byte", "unsigned byte", "short", "unsigned short", "int", "unsigned int", "long", "unsigned long", "long long", "unsigned long long", "float", "double", "long double", "complex float", "complex double", "complex long double", "object", "string", "unicode", "void", "ntypes", "notype", "char", "unknown"}; return typecode < 24 ? type_names[typecode] : type_names[24]; } /* Make sure input has correct numpy type. Allow character and byte * to match. Also allow int and long to match. This is deprecated. * You should use PyArray_EquivTypenums() instead. */ int type_match(int actual_type, int desired_type) { return PyArray_EquivTypenums(actual_type, desired_type); } } /**********************************************************************/ %fragment("NumPy_Object_to_Array", "header", fragment="NumPy_Backward_Compatibility", fragment="NumPy_Macros", fragment="NumPy_Utilities") { /* Given a PyObject pointer, cast it to a PyArrayObject pointer if * legal. If not, set the python error string appropriately and * return NULL. */ PyArrayObject* obj_to_array_no_conversion(PyObject* input, int typecode) { PyArrayObject* ary = NULL; if (is_array(input) && (typecode == NPY_NOTYPE || PyArray_EquivTypenums(array_type(input), typecode))) { ary = (PyArrayObject*) input; } else if is_array(input) { const char* desired_type = typecode_string(typecode); const char* actual_type = typecode_string(array_type(input)); PyErr_Format(PyExc_TypeError, "Array of type '%s' required. Array of type '%s' given", desired_type, actual_type); ary = NULL; } else { const char * desired_type = typecode_string(typecode); const char * actual_type = pytype_string(input); PyErr_Format(PyExc_TypeError, "Array of type '%s' required. A '%s' was given", desired_type, actual_type); ary = NULL; } return ary; } /* Convert the given PyObject to a NumPy array with the given * typecode. On success, return a valid PyArrayObject* with the * correct type. On failure, the python error string will be set and * the routine returns NULL. */ PyArrayObject* obj_to_array_allow_conversion(PyObject* input, int typecode, int* is_new_object) { PyArrayObject* ary = NULL; PyObject* py_obj; if (is_array(input) && (typecode == NPY_NOTYPE || PyArray_EquivTypenums(array_type(input),typecode))) { ary = (PyArrayObject*) input; *is_new_object = 0; } else { py_obj = PyArray_FROMANY(input, typecode, 0, 0, NPY_DEFAULT); /* If NULL, PyArray_FromObject will have set python error value.*/ ary = (PyArrayObject*) py_obj; *is_new_object = 1; } return ary; } /* Given a PyArrayObject, check to see if it is contiguous. If so, * return the input pointer and flag it as not a new object. If it is * not contiguous, create a new PyArrayObject using the original data, * flag it as a new object and return the pointer. */ PyArrayObject* make_contiguous(PyArrayObject* ary, int* is_new_object, int min_dims, int max_dims) { PyArrayObject* result; if (array_is_contiguous(ary)) { result = ary; *is_new_object = 0; } else { result = (PyArrayObject*) PyArray_ContiguousFromObject((PyObject*)ary, array_type(ary), min_dims, max_dims); *is_new_object = 1; } return result; } /* Given a PyArrayObject, check to see if it is Fortran-contiguous. * If so, return the input pointer, but do not flag it as not a new * object. If it is not Fortran-contiguous, create a new * PyArrayObject using the original data, flag it as a new object * and return the pointer. */ PyArrayObject* make_fortran(PyArrayObject* ary, int* is_new_object, int min_dims, int max_dims) { PyArrayObject* result; if (array_is_fortran(ary)) { result = ary; *is_new_object = 0; } else { Py_INCREF(ary->descr); result = (PyArrayObject*) PyArray_FromArray(ary, ary->descr, NPY_FORTRAN); *is_new_object = 1; } return result; } /* Convert a given PyObject to a contiguous PyArrayObject of the * specified type. If the input object is not a contiguous * PyArrayObject, a new one will be created and the new object flag * will be set. */ PyArrayObject* obj_to_array_contiguous_allow_conversion(PyObject* input, int typecode, int* is_new_object) { int is_new1 = 0; int is_new2 = 0; PyArrayObject* ary2; PyArrayObject* ary1 = obj_to_array_allow_conversion(input, typecode, &is_new1); if (ary1) { ary2 = make_contiguous(ary1, &is_new2, 0, 0); if ( is_new1 && is_new2) { Py_DECREF(ary1); } ary1 = ary2; } *is_new_object = is_new1 || is_new2; return ary1; } /* Convert a given PyObject to a Fortran-ordered PyArrayObject of the * specified type. If the input object is not a Fortran-ordered * PyArrayObject, a new one will be created and the new object flag * will be set. */ PyArrayObject* obj_to_array_fortran_allow_conversion(PyObject* input, int typecode, int* is_new_object) { int is_new1 = 0; int is_new2 = 0; PyArrayObject* ary2; PyArrayObject* ary1 = obj_to_array_allow_conversion(input, typecode, &is_new1); if (ary1) { ary2 = make_fortran(ary1, &is_new2, 0, 0); if (is_new1 && is_new2) { Py_DECREF(ary1); } ary1 = ary2; } *is_new_object = is_new1 || is_new2; return ary1; } /* The following code was added by Ilmar M. Wilbers for forcing a copy of the * object even when it is a NumPy array. This is meant for use with the * IN_ARRAY typemaps, and allows the user to perform changes on an array * without these chenges being reflected in the calling code. */ /* Convert the given PyObject to a NumPy array with the given * typecode as a copy. On success, return a valid PyArrayObject* with the * correct type. On failure, the python error string will be set and * the routine returns NULL. */ PyArrayObject* obj_to_array_force_conversion(PyObject* input, int typecode, int* is_new_object) { PyArrayObject* ary = NULL; PyObject* py_obj; if (is_array(input) && (typecode == NPY_NOTYPE || PyArray_EquivTypenums(array_type(input),typecode))) { py_obj = PyArray_Copy((PyArrayObject*) input); ary = (PyArrayObject*) py_obj; *is_new_object = 1; } else { py_obj = PyArray_FROMANY(input, typecode, 0, 0, NPY_DEFAULT); /* If NULL, PyArray_FromObject will have set python error value.*/ ary = (PyArrayObject*) py_obj; *is_new_object = 1; } return ary; } /* Convert a given PyObject to a contiguous PyArrayObject of the * specified type. If the input object is not a contiguous * PyArrayObject, a new one will be created and the new object flag * will be set. */ PyArrayObject* obj_to_array_contiguous_force_conversion(PyObject* input, int typecode, int* is_new_object) { int is_new1 = 0; int is_new2 = 0; PyArrayObject* ary2; PyArrayObject* ary1 = obj_to_array_force_conversion(input, typecode, &is_new1); if (ary1) { ary2 = make_contiguous(ary1, &is_new2, 0, 0); if ( is_new1 && is_new2) { Py_DECREF(ary1); } ary1 = ary2; } *is_new_object = is_new1 || is_new2; return ary1; } /* Convert a given PyObject to a Fortran-ordered PyArrayObject of the * specified type. If the input object is not a Fortran-ordered * PyArrayObject, a new one will be created and the new object flag * will be set. */ PyArrayObject* obj_to_array_fortran_force_conversion(PyObject* input, int typecode, int* is_new_object) { int is_new1 = 0; int is_new2 = 0; PyArrayObject* ary2; PyArrayObject* ary1 = obj_to_array_force_conversion(input, typecode, &is_new1); if (ary1) { ary2 = make_fortran(ary1, &is_new2, 0, 0); if (is_new1 && is_new2) { Py_DECREF(ary1); } ary1 = ary2; } *is_new_object = is_new1 || is_new2; return ary1; } /* End modifications by Ilmar M. Wilbers */ } /* end fragment */ /**********************************************************************/ %fragment("NumPy_Array_Requirements", "header", fragment="NumPy_Backward_Compatibility", fragment="NumPy_Macros") { /* Test whether a python object is contiguous. If array is * contiguous, return 1. Otherwise, set the python error string and * return 0. */ int require_contiguous(PyArrayObject* ary) { int contiguous = 1; if (!array_is_contiguous(ary)) { PyErr_SetString(PyExc_TypeError, "Array must be contiguous. A non-contiguous array was given"); contiguous = 0; } return contiguous; } /* Require that a numpy array is not byte-swapped. If the array is * not byte-swapped, return 1. Otherwise, set the python error string * and return 0. */ int require_native(PyArrayObject* ary) { int native = 1; if (!array_is_native(ary)) { PyErr_SetString(PyExc_TypeError, "Array must have native byteorder. " "A byte-swapped array was given"); native = 0; } return native; } /* Require the given PyArrayObject to have a specified number of * dimensions. If the array has the specified number of dimensions, * return 1. Otherwise, set the python error string and return 0. */ int require_dimensions(PyArrayObject* ary, int exact_dimensions) { int success = 1; if (array_numdims(ary) != exact_dimensions) { PyErr_Format(PyExc_TypeError, "Array must have %d dimensions. Given array has %d dimensions", exact_dimensions, array_numdims(ary)); success = 0; } return success; } /* Require the given PyArrayObject to have one of a list of specified * number of dimensions. If the array has one of the specified number * of dimensions, return 1. Otherwise, set the python error string * and return 0. */ int require_dimensions_n(PyArrayObject* ary, int* exact_dimensions, int n) { int success = 0; int i; char dims_str[255] = ""; char s[255]; for (i = 0; i < n && !success; i++) { if (array_numdims(ary) == exact_dimensions[i]) { success = 1; } } if (!success) { for (i = 0; i < n-1; i++) { sprintf(s, "%d, ", exact_dimensions[i]); strcat(dims_str,s); } sprintf(s, " or %d", exact_dimensions[n-1]); strcat(dims_str,s); PyErr_Format(PyExc_TypeError, "Array must have %s dimensions. Given array has %d dimensions", dims_str, array_numdims(ary)); } return success; } /* Require the given PyArrayObject to have a specified shape. If the * array has the specified shape, return 1. Otherwise, set the python * error string and return 0. */ int require_size(PyArrayObject* ary, npy_intp* size, int n) { int i; int success = 1; int len; char desired_dims[255] = "["; char s[255]; char actual_dims[255] = "["; for(i=0; i < n;i++) { if (size[i] != -1 && size[i] != array_size(ary,i)) { success = 0; } } if (!success) { for (i = 0; i < n; i++) { if (size[i] == -1) { sprintf(s, "*,"); } else { sprintf(s, "%ld,", (long int)size[i]); } strcat(desired_dims,s); } len = strlen(desired_dims); desired_dims[len-1] = ']'; for (i = 0; i < n; i++) { sprintf(s, "%ld,", (long int)array_size(ary,i)); strcat(actual_dims,s); } len = strlen(actual_dims); actual_dims[len-1] = ']'; PyErr_Format(PyExc_TypeError, "Array must have shape of %s. Given array has shape of %s", desired_dims, actual_dims); } return success; } /* Require the given PyArrayObject to to be FORTRAN ordered. If the * the PyArrayObject is already FORTRAN ordered, do nothing. Else, * set the FORTRAN ordering flag and recompute the strides. */ int require_fortran(PyArrayObject* ary) { int success = 1; int nd = array_numdims(ary); int i; if (array_is_fortran(ary)) return success; /* Set the FORTRAN ordered flag */ ary->flags = NPY_FARRAY; /* Recompute the strides */ ary->strides[0] = ary->strides[nd-1]; for (i=1; i < nd; ++i) ary->strides[i] = ary->strides[i-1] * array_size(ary,i-1); return success; } } /* Combine all NumPy fragments into one for convenience */ %fragment("NumPy_Fragments", "header", fragment="NumPy_Backward_Compatibility", fragment="NumPy_Macros", fragment="NumPy_Utilities", fragment="NumPy_Object_to_Array", fragment="NumPy_Array_Requirements") { } /* End John Hunter translation (with modifications by Bill Spotz) */ /* %numpy_typemaps() macro * * This macro defines a family of 41 typemaps that allow C arguments * of the form * * (DATA_TYPE IN_ARRAY1[ANY]) * (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) * (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) * * (DATA_TYPE IN_ARRAY2[ANY][ANY]) * (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) * (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) * (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) * (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) * * (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) * (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) * (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_ARRAY3) * (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) * (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_FARRAY3) * * (DATA_TYPE INPLACE_ARRAY1[ANY]) * (DATA_TYPE* INPLACE_ARRAY1, DIM_TYPE DIM1) * (DIM_TYPE DIM1, DATA_TYPE* INPLACE_ARRAY1) * * (DATA_TYPE INPLACE_ARRAY2[ANY][ANY]) * (DATA_TYPE* INPLACE_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) * (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_ARRAY2) * (DATA_TYPE* INPLACE_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) * (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_FARRAY2) * * (DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) * (DATA_TYPE* INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) * (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_ARRAY3) * (DATA_TYPE* INPLACE_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) * (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_FARRAY3) * * (DATA_TYPE ARGOUT_ARRAY1[ANY]) * (DATA_TYPE* ARGOUT_ARRAY1, DIM_TYPE DIM1) * (DIM_TYPE DIM1, DATA_TYPE* ARGOUT_ARRAY1) * * (DATA_TYPE ARGOUT_ARRAY2[ANY][ANY]) * * (DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) * * (DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1) * (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEW_ARRAY1) * * (DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) * (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_ARRAY2) * (DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) * (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_FARRAY2) * * (DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) * (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_ARRAY3) * (DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) * (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_FARRAY3) * * where "DATA_TYPE" is any type supported by the NumPy module, and * "DIM_TYPE" is any int-like type suitable for specifying dimensions. * The difference between "ARRAY" typemaps and "FARRAY" typemaps is * that the "FARRAY" typemaps expect FORTRAN ordering of * multidimensional arrays. In python, the dimensions will not need * to be specified (except for the "DATA_TYPE* ARGOUT_ARRAY1" * typemaps). The IN_ARRAYs can be a numpy array or any sequence that * can be converted to a numpy array of the specified type. The * INPLACE_ARRAYs must be numpy arrays of the appropriate type. The * ARGOUT_ARRAYs will be returned as new numpy arrays of the * appropriate type. * * These typemaps can be applied to existing functions using the * %apply directive. For example: * * %apply (double* IN_ARRAY1, int DIM1) {(double* series, int length)}; * double prod(double* series, int length); * * %apply (int DIM1, int DIM2, double* INPLACE_ARRAY2) * {(int rows, int cols, double* matrix )}; * void floor(int rows, int cols, double* matrix, double f); * * %apply (double IN_ARRAY3[ANY][ANY][ANY]) * {(double tensor[2][2][2] )}; * %apply (double ARGOUT_ARRAY3[ANY][ANY][ANY]) * {(double low[2][2][2] )}; * %apply (double ARGOUT_ARRAY3[ANY][ANY][ANY]) * {(double upp[2][2][2] )}; * void luSplit(double tensor[2][2][2], * double low[2][2][2], * double upp[2][2][2] ); * * or directly with * * double prod(double* IN_ARRAY1, int DIM1); * * void floor(int DIM1, int DIM2, double* INPLACE_ARRAY2, double f); * * void luSplit(double IN_ARRAY3[ANY][ANY][ANY], * double ARGOUT_ARRAY3[ANY][ANY][ANY], * double ARGOUT_ARRAY3[ANY][ANY][ANY]); */ %define %numpy_typemaps(DATA_TYPE, DATA_TYPECODE, DIM_TYPE) /************************/ /* Input Array Typemaps */ /************************/ /* Typemap suite for (DATA_TYPE IN_ARRAY1[ANY]) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE IN_ARRAY1[ANY]) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE IN_ARRAY1[ANY]) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[1] = { $1_dim0 }; array = obj_to_array_contiguous_force_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 1) || !require_size(array, size, 1)) SWIG_fail; $1 = ($1_ltype) array_data(array); } %typemap(freearg) (DATA_TYPE IN_ARRAY1[ANY]) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[1] = { -1 }; array = obj_to_array_contiguous_force_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 1) || !require_size(array, size, 1)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); } %typemap(freearg) (DATA_TYPE* IN_ARRAY1, DIM_TYPE DIM1) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[1] = {-1}; array = obj_to_array_contiguous_force_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 1) || !require_size(array, size, 1)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DATA_TYPE*) array_data(array); } %typemap(freearg) (DIM_TYPE DIM1, DATA_TYPE* IN_ARRAY1) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE IN_ARRAY2[ANY][ANY]) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE IN_ARRAY2[ANY][ANY]) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE IN_ARRAY2[ANY][ANY]) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[2] = { $1_dim0, $1_dim1 }; array = obj_to_array_contiguous_force_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 2) || !require_size(array, size, 2)) SWIG_fail; $1 = ($1_ltype) array_data(array); } %typemap(freearg) (DATA_TYPE IN_ARRAY2[ANY][ANY]) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[2] = { -1, -1 }; array = obj_to_array_contiguous_force_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 2) || !require_size(array, size, 2)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); } %typemap(freearg) (DATA_TYPE* IN_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[2] = { -1, -1 }; array = obj_to_array_contiguous_force_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 2) || !require_size(array, size, 2)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DATA_TYPE*) array_data(array); } %typemap(freearg) (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_ARRAY2) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[2] = { -1, -1 }; array = obj_to_array_fortran_force_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 2) || !require_size(array, size, 2) || !require_fortran(array)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); } %typemap(freearg) (DATA_TYPE* IN_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[2] = { -1, -1 }; array = obj_to_array_contiguous_force_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 2) || !require_size(array, size, 2) || !require_fortran(array)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DATA_TYPE*) array_data(array); } %typemap(freearg) (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* IN_FARRAY2) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[3] = { $1_dim0, $1_dim1, $1_dim2 }; array = obj_to_array_contiguous_force_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 3) || !require_size(array, size, 3)) SWIG_fail; $1 = ($1_ltype) array_data(array); } %typemap(freearg) (DATA_TYPE IN_ARRAY3[ANY][ANY][ANY]) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, * DIM_TYPE DIM3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[3] = { -1, -1, -1 }; array = obj_to_array_contiguous_force_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 3) || !require_size(array, size, 3)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); $4 = (DIM_TYPE) array_size(array,2); } %typemap(freearg) (DATA_TYPE* IN_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, * DATA_TYPE* IN_ARRAY3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_ARRAY3) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_ARRAY3) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[3] = { -1, -1, -1 }; array = obj_to_array_contiguous_force_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 3) || !require_size(array, size, 3)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DIM_TYPE) array_size(array,2); $4 = (DATA_TYPE*) array_data(array); } %typemap(freearg) (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_ARRAY3) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, * DIM_TYPE DIM3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[3] = { -1, -1, -1 }; array = obj_to_array_fortran_force_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 3) || !require_size(array, size, 3) | !require_fortran(array)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); $4 = (DIM_TYPE) array_size(array,2); } %typemap(freearg) (DATA_TYPE* IN_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, * DATA_TYPE* IN_FARRAY3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_FARRAY3) { $1 = is_array($input) || PySequence_Check($input); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_FARRAY3) (PyArrayObject* array=NULL, int is_new_object=0) { npy_intp size[3] = { -1, -1, -1 }; array = obj_to_array_contiguous_force_conversion($input, DATA_TYPECODE, &is_new_object); if (!array || !require_dimensions(array, 3) || !require_size(array, size, 3) || !require_fortran(array)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DIM_TYPE) array_size(array,2); $4 = (DATA_TYPE*) array_data(array); } %typemap(freearg) (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* IN_FARRAY3) { if (is_new_object$argnum && array$argnum) { Py_DECREF(array$argnum); } } /***************************/ /* In-Place Array Typemaps */ /***************************/ /* Typemap suite for (DATA_TYPE INPLACE_ARRAY1[ANY]) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE INPLACE_ARRAY1[ANY]) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE INPLACE_ARRAY1[ANY]) (PyArrayObject* array=NULL) { npy_intp size[1] = { $1_dim0 }; array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,1) || !require_size(array, size, 1) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = ($1_ltype) array_data(array); } /* Typemap suite for (DATA_TYPE* INPLACE_ARRAY1, DIM_TYPE DIM1) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* INPLACE_ARRAY1, DIM_TYPE DIM1) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* INPLACE_ARRAY1, DIM_TYPE DIM1) (PyArrayObject* array=NULL, int i=1) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,1) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = 1; for (i=0; i < array_numdims(array); ++i) $2 *= array_size(array,i); } /* Typemap suite for (DIM_TYPE DIM1, DATA_TYPE* INPLACE_ARRAY1) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DATA_TYPE* INPLACE_ARRAY1) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DATA_TYPE* INPLACE_ARRAY1) (PyArrayObject* array=NULL, int i=0) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,1) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = 1; for (i=0; i < array_numdims(array); ++i) $1 *= array_size(array,i); $2 = (DATA_TYPE*) array_data(array); } /* Typemap suite for (DATA_TYPE INPLACE_ARRAY2[ANY][ANY]) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE INPLACE_ARRAY2[ANY][ANY]) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE INPLACE_ARRAY2[ANY][ANY]) (PyArrayObject* array=NULL) { npy_intp size[2] = { $1_dim0, $1_dim1 }; array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,2) || !require_size(array, size, 2) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = ($1_ltype) array_data(array); } /* Typemap suite for (DATA_TYPE* INPLACE_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* INPLACE_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* INPLACE_ARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,2) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_ARRAY2) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_ARRAY2) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_ARRAY2) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,2) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DATA_TYPE*) array_data(array); } /* Typemap suite for (DATA_TYPE* INPLACE_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* INPLACE_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* INPLACE_FARRAY2, DIM_TYPE DIM1, DIM_TYPE DIM2) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,2) || !require_contiguous(array) || !require_native(array) || !require_fortran(array)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_FARRAY2) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_FARRAY2) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DATA_TYPE* INPLACE_FARRAY2) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,2) || !require_contiguous(array) || !require_native(array) || !require_fortran(array)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DATA_TYPE*) array_data(array); } /* Typemap suite for (DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE INPLACE_ARRAY3[ANY][ANY][ANY]) (PyArrayObject* array=NULL) { npy_intp size[3] = { $1_dim0, $1_dim1, $1_dim2 }; array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,3) || !require_size(array, size, 3) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = ($1_ltype) array_data(array); } /* Typemap suite for (DATA_TYPE* INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, * DIM_TYPE DIM3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* INPLACE_ARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,3) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); $4 = (DIM_TYPE) array_size(array,2); } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, * DATA_TYPE* INPLACE_ARRAY3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_ARRAY3) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_ARRAY3) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,3) || !require_contiguous(array) || !require_native(array)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DIM_TYPE) array_size(array,2); $4 = (DATA_TYPE*) array_data(array); } /* Typemap suite for (DATA_TYPE* INPLACE_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, * DIM_TYPE DIM3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DATA_TYPE* INPLACE_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DATA_TYPE* INPLACE_FARRAY3, DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,3) || !require_contiguous(array) || !require_native(array) || !require_fortran(array)) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); $2 = (DIM_TYPE) array_size(array,0); $3 = (DIM_TYPE) array_size(array,1); $4 = (DIM_TYPE) array_size(array,2); } /* Typemap suite for (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, * DATA_TYPE* INPLACE_FARRAY3) */ %typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="NumPy_Macros") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_FARRAY3) { $1 = is_array($input) && PyArray_EquivTypenums(array_type($input), DATA_TYPECODE); } %typemap(in, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DIM_TYPE DIM2, DIM_TYPE DIM3, DATA_TYPE* INPLACE_FARRAY3) (PyArrayObject* array=NULL) { array = obj_to_array_no_conversion($input, DATA_TYPECODE); if (!array || !require_dimensions(array,3) || !require_contiguous(array) || !require_native(array) || !require_fortran(array)) SWIG_fail; $1 = (DIM_TYPE) array_size(array,0); $2 = (DIM_TYPE) array_size(array,1); $3 = (DIM_TYPE) array_size(array,2); $4 = (DATA_TYPE*) array_data(array); } /*************************/ /* Argout Array Typemaps */ /*************************/ /* Typemap suite for (DATA_TYPE ARGOUT_ARRAY1[ANY]) */ %typemap(in,numinputs=0, fragment="NumPy_Backward_Compatibility,NumPy_Macros") (DATA_TYPE ARGOUT_ARRAY1[ANY]) (PyObject * array = NULL) { npy_intp dims[1] = { $1_dim0 }; array = PyArray_SimpleNew(1, dims, DATA_TYPECODE); if (!array) SWIG_fail; $1 = ($1_ltype) array_data(array); } %typemap(argout) (DATA_TYPE ARGOUT_ARRAY1[ANY]) { $result = SWIG_Python_AppendOutput($result,array$argnum); } /* Typemap suite for (DATA_TYPE* ARGOUT_ARRAY1, DIM_TYPE DIM1) */ %typemap(in,numinputs=1, fragment="NumPy_Fragments") (DATA_TYPE* ARGOUT_ARRAY1, DIM_TYPE DIM1) (PyObject * array = NULL) { npy_intp dims[1]; if (!PyInt_Check($input)) { const char* typestring = pytype_string($input); PyErr_Format(PyExc_TypeError, "Int dimension expected. '%s' given.", typestring); SWIG_fail; } $2 = (DIM_TYPE) PyInt_AsLong($input); dims[0] = (npy_intp) $2; array = PyArray_SimpleNew(1, dims, DATA_TYPECODE); if (!array) SWIG_fail; $1 = (DATA_TYPE*) array_data(array); } %typemap(argout) (DATA_TYPE* ARGOUT_ARRAY1, DIM_TYPE DIM1) { $result = SWIG_Python_AppendOutput($result,array$argnum); } /* Typemap suite for (DIM_TYPE DIM1, DATA_TYPE* ARGOUT_ARRAY1) */ %typemap(in,numinputs=1, fragment="NumPy_Fragments") (DIM_TYPE DIM1, DATA_TYPE* ARGOUT_ARRAY1) (PyObject * array = NULL) { npy_intp dims[1]; if (!PyInt_Check($input)) { const char* typestring = pytype_string($input); PyErr_Format(PyExc_TypeError, "Int dimension expected. '%s' given.", typestring); SWIG_fail; } $1 = (DIM_TYPE) PyInt_AsLong($input); dims[0] = (npy_intp) $1; array = PyArray_SimpleNew(1, dims, DATA_TYPECODE); if (!array) SWIG_fail; $2 = (DATA_TYPE*) array_data(array); } %typemap(argout) (DIM_TYPE DIM1, DATA_TYPE* ARGOUT_ARRAY1) { $result = SWIG_Python_AppendOutput($result,array$argnum); } /* Typemap suite for (DATA_TYPE ARGOUT_ARRAY2[ANY][ANY]) */ %typemap(in,numinputs=0, fragment="NumPy_Backward_Compatibility,NumPy_Macros") (DATA_TYPE ARGOUT_ARRAY2[ANY][ANY]) (PyObject * array = NULL) { npy_intp dims[2] = { $1_dim0, $1_dim1 }; array = PyArray_SimpleNew(2, dims, DATA_TYPECODE); if (!array) SWIG_fail; $1 = ($1_ltype) array_data(array); } %typemap(argout) (DATA_TYPE ARGOUT_ARRAY2[ANY][ANY]) { $result = SWIG_Python_AppendOutput($result,array$argnum); } /* Typemap suite for (DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) */ %typemap(in,numinputs=0, fragment="NumPy_Backward_Compatibility,NumPy_Macros") (DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) (PyObject * array = NULL) { npy_intp dims[3] = { $1_dim0, $1_dim1, $1_dim2 }; array = PyArray_SimpleNew(3, dims, DATA_TYPECODE); if (!array) SWIG_fail; $1 = ($1_ltype) array_data(array); } %typemap(argout) (DATA_TYPE ARGOUT_ARRAY3[ANY][ANY][ANY]) { $result = SWIG_Python_AppendOutput($result,array$argnum); } /*****************************/ /* Argoutview Array Typemaps */ /*****************************/ /* Typemap suite for (DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1 ) (DATA_TYPE* data_temp , DIM_TYPE dim_temp) { $1 = &data_temp; $2 = &dim_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DATA_TYPE** ARGOUTVIEW_ARRAY1, DIM_TYPE* DIM1) { npy_intp dims[1] = { *$2 }; PyObject * array = PyArray_SimpleNewFromData(1, dims, DATA_TYPECODE, (void*)(*$1)); if (!array) SWIG_fail; $result = SWIG_Python_AppendOutput($result,array); } /* Typemap suite for (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEW_ARRAY1) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DATA_TYPE** ARGOUTVIEW_ARRAY1) (DIM_TYPE dim_temp, DATA_TYPE* data_temp ) { $1 = &dim_temp; $2 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DIM_TYPE* DIM1, DATA_TYPE** ARGOUTVIEW_ARRAY1) { npy_intp dims[1] = { *$1 }; PyObject * array = PyArray_SimpleNewFromData(1, dims, DATA_TYPECODE, (void*)(*$2)); if (!array) SWIG_fail; $result = SWIG_Python_AppendOutput($result,array); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 ) (DATA_TYPE* data_temp , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DATA_TYPE** ARGOUTVIEW_ARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) { npy_intp dims[2] = { *$2, *$3 }; PyObject * array = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$1)); if (!array) SWIG_fail; $result = SWIG_Python_AppendOutput($result,array); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_ARRAY2) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DATA_TYPE** ARGOUTVIEW_ARRAY2) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DATA_TYPE* data_temp ) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_ARRAY2) { npy_intp dims[2] = { *$1, *$2 }; PyObject * array = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$3)); if (!array) SWIG_fail; $result = SWIG_Python_AppendOutput($result,array); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1 , DIM_TYPE* DIM2 ) (DATA_TYPE* data_temp , DIM_TYPE dim1_temp, DIM_TYPE dim2_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DATA_TYPE** ARGOUTVIEW_FARRAY2, DIM_TYPE* DIM1, DIM_TYPE* DIM2) { npy_intp dims[2] = { *$2, *$3 }; PyObject * obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject * array = (PyArrayObject*) obj; if (!array || !require_fortran(array)) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_FARRAY2) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1 , DIM_TYPE* DIM2 , DATA_TYPE** ARGOUTVIEW_FARRAY2) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DATA_TYPE* data_temp ) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DATA_TYPE** ARGOUTVIEW_FARRAY2) { npy_intp dims[2] = { *$1, *$2 }; PyObject * obj = PyArray_SimpleNewFromData(2, dims, DATA_TYPECODE, (void*)(*$3)); PyArrayObject * array = (PyArrayObject*) obj; if (!array || !require_fortran(array)) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) (DATA_TYPE* data_temp, DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; $4 = &dim3_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DATA_TYPE** ARGOUTVIEW_ARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) { npy_intp dims[3] = { *$2, *$3, *$4 }; PyObject * array = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$1)); if (!array) SWIG_fail; $result = SWIG_Python_AppendOutput($result,array); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_ARRAY3) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_ARRAY3) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DATA_TYPE* data_temp) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &dim3_temp; $4 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_ARRAY3) { npy_intp dims[3] = { *$1, *$2, *$3 }; PyObject * array = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$3)); if (!array) SWIG_fail; $result = SWIG_Python_AppendOutput($result,array); } /* Typemap suite for (DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) */ %typemap(in,numinputs=0) (DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) (DATA_TYPE* data_temp, DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp) { $1 = &data_temp; $2 = &dim1_temp; $3 = &dim2_temp; $4 = &dim3_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DATA_TYPE** ARGOUTVIEW_FARRAY3, DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3) { npy_intp dims[3] = { *$2, *$3, *$4 }; PyObject * obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$1)); PyArrayObject * array = (PyArrayObject*) obj; if (!array || require_fortran(array)) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } /* Typemap suite for (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_FARRAY3) */ %typemap(in,numinputs=0) (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_FARRAY3) (DIM_TYPE dim1_temp, DIM_TYPE dim2_temp, DIM_TYPE dim3_temp, DATA_TYPE* data_temp) { $1 = &dim1_temp; $2 = &dim2_temp; $3 = &dim3_temp; $4 = &data_temp; } %typemap(argout, fragment="NumPy_Backward_Compatibility,NumPy_Array_Requirements") (DIM_TYPE* DIM1, DIM_TYPE* DIM2, DIM_TYPE* DIM3, DATA_TYPE** ARGOUTVIEW_FARRAY3) { npy_intp dims[3] = { *$1, *$2, *$3 }; PyObject * obj = PyArray_SimpleNewFromData(3, dims, DATA_TYPECODE, (void*)(*$3)); PyArrayObject * array = (PyArrayObject*) obj; if (!array || require_fortran(array)) SWIG_fail; $result = SWIG_Python_AppendOutput($result,obj); } %enddef /* %numpy_typemaps() macro */ /* *************************************************************** */ /* Concrete instances of the %numpy_typemaps() macro: Each invocation * below applies all of the typemaps above to the specified data type. */ %numpy_typemaps(signed char , NPY_BYTE , int) %numpy_typemaps(unsigned char , NPY_UBYTE , int) %numpy_typemaps(short , NPY_SHORT , int) %numpy_typemaps(unsigned short , NPY_USHORT , int) %numpy_typemaps(int , NPY_INT , int) %numpy_typemaps(unsigned int , NPY_UINT , int) %numpy_typemaps(long , NPY_LONG , int) %numpy_typemaps(unsigned long , NPY_ULONG , int) %numpy_typemaps(long long , NPY_LONGLONG , int) %numpy_typemaps(unsigned long long, NPY_ULONGLONG, int) %numpy_typemaps(float , NPY_FLOAT , int) %numpy_typemaps(double , NPY_DOUBLE , int) /* *************************************************************** * The follow macro expansion does not work, because C++ bool is 4 * bytes and NPY_BOOL is 1 byte * * %numpy_typemaps(bool, NPY_BOOL, int) */ /* *************************************************************** * On my Mac, I get the following warning for this macro expansion: * 'swig/python detected a memory leak of type 'long double *', no destructor found.' * * %numpy_typemaps(long double, NPY_LONGDOUBLE, int) */ /* *************************************************************** * Swig complains about a syntax error for the following macro * expansions: * * %numpy_typemaps(complex float, NPY_CFLOAT , int) * * %numpy_typemaps(complex double, NPY_CDOUBLE, int) * * %numpy_typemaps(complex long double, NPY_CLONGDOUBLE, int) */ #endif /* SWIGPYTHON */ instant-1.3.0/release.conf000066400000000000000000000001721226277733300154760ustar00rootroot00000000000000# Configuration file for fenics-release PACKAGE="instant" BRANCH="master" FILES="ChangeLog setup.py instant/__init__.py" instant-1.3.0/scripts/000077500000000000000000000000001226277733300146765ustar00rootroot00000000000000instant-1.3.0/scripts/instant-clean000077500000000000000000000050221226277733300173630ustar00rootroot00000000000000#!/usr/bin/env python # # This script cleans the Instant cache __author__ = "Ilmar Wilbers (ilmarw@simula.no)" __date__ = "2008-08-08 -- 2013-05-02" __copyright__ = "Copyright (C) 2008 Ilmar Wilbers" __license__ = "GNU GPL version 3 or any later version" # Modified by Martin Alnes import os, sys, shutil, glob, re try: import instant except: print "Instant not installed, exiting..." sys.exit(1) instant_tmp_dir_suffix = instant.compute_checksum(instant.get_instant_dir()) # Check if any temp directories exists tmp = instant.get_temp_dir() tmp_dir_prefix = os.path.split(tmp)[0] # FIXME: Is it safe to assume that the prefix to tempdirs is constant on a platform? s = re.search(r"(.*)%s[^%s]*instant_%s" % (os.path.pathsep, os.path.pathsep, \ instant_tmp_dir_suffix), tmp) instant.delete_temp_dir() tmp_dirs = glob.glob(os.path.join(tmp_dir_prefix, '*instant_' + instant_tmp_dir_suffix)) for d in tmp_dirs: if os.path.isdir(d): print "Deleting temp directory", d shutil.rmtree(d, ignore_errors=True) # Get default cache dir (won't and can't touch userdefined cache dirs in this script) cache_dir = instant.get_default_cache_dir() error_dir = instant.get_default_error_dir() # Check if directory exists (it always should after calling get_default_cache_dir) assert os.path.isdir(cache_dir) assert os.path.isdir(error_dir) # Get list of cached forms modules = os.listdir(cache_dir) error_logs = os.listdir(error_dir) if len(modules+error_logs) == 0: print "Instant cache is empty" sys.exit(0) # Remove cached forms lockfiles = [m for m in modules if m.endswith(".lock")] modules = [m for m in modules if not m.endswith(".lock")] error_lockfiles = [f for f in error_logs if f.endswith(".lock")] error_logs = [f for f in error_logs if not f.endswith(".lock")] print "Removing %d modules from Instant cache..." % len(modules) for module in modules: directory = os.path.join(cache_dir, module) shutil.rmtree(directory, ignore_errors=True) print "Removing %d error logs from Instant cache..." % len(error_logs) for error_log in error_logs: if os.path.isdir(os.path.join(error_dir, error_log)): shutil.rmtree(os.path.join(error_dir, error_log)) else: os.remove(os.path.join(error_dir, error_log)) print "Removing %d lock files from Instant cache..." % len(lockfiles+error_lockfiles) for lf in lockfiles: f = os.path.join(cache_dir, lf) os.remove(f) for lf in error_lockfiles: f = os.path.join(error_dir, lf) os.remove(f) instant-1.3.0/scripts/instant-showcache000077500000000000000000000024731226277733300202540ustar00rootroot00000000000000#!/usr/bin/env python # # This script prints all modules found in the instant cache __author__ = "Martin Alnes (martinal@simula.no)" __date__ = "2008-09-02 -- 2008-10-16" __copyright__ = "Copyright (C) 2008 Martin Alnes" __license__ = "GNU GPL version 3 or any later version" import os, sys, shutil, tempfile, glob try: import instant except: print "Instant not installed, exiting..." sys.exit(1) files = sys.argv[1:] if files: print "Showing contents of files: ", files modules = instant.cached_modules() lockfiles = [m for m in modules if m.endswith(".lock")] modules = [m for m in modules if not m.endswith(".lock")] print "Found %d modules in Instant cache:" % len(modules) for module in modules: print module if files: for f in files: filepath = os.path.join(instant.get_default_cache_dir(), module, f) filenames = glob.glob(filepath) for filename in filenames: print "Contents of file '%s':" % filename try: lines = open(filename).readlines() print "".join(lines) except: print "Failed to open." print print print "Found %d lock files in Instant cache:" % len(lockfiles) for lockfile in lockfiles: print lockfile instant-1.3.0/scripts/maketarball.sh000077500000000000000000000005601226277733300175150ustar00rootroot00000000000000#!/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 instant-1.3.0/setup.py000066400000000000000000000025641226277733300147300ustar00rootroot00000000000000#!/usr/bin/env python import sys, platform from os.path import join, split, pardir from distutils.core import setup scripts = [join("scripts", "instant-clean"), join("scripts", "instant-showcache")] if platform.system() == "Windows" or "bdist_wininst" in sys.argv: # In the Windows command prompt we can't execute Python scripts # without a .py extension. A solution is to create batch files # that runs the different scripts. batch_files = [] for script in scripts: batch_file = script + ".bat" f = open(batch_file, "w") f.write('python "%%~dp0\%s" %%*\n' % split(script)[1]) f.close() batch_files.append(batch_file) scripts.extend(batch_files) setup(name = "instant", version = "1.3.0", description = "Instant Inlining of C/C++ in Python", author = "Magne Westlie, Kent-Andre Mardal, Martin Sandve Alnes and Ilmar M. Wilbers", author_email = "kent-and@simula.no, martinal@simula.no, ilmarw@simula.no", url = "http://www.fenicsproject.org", packages = ['instant'], package_dir = {'instant': 'instant'}, package_data = {'': [join('swig', 'numpy.i')]}, scripts = scripts, data_files = [(join("share", "man", "man1"), [join("doc", "man", "man1", "instant-clean.1.gz"), join("doc", "man", "man1", "instant-showcache.1.gz")])] ) instant-1.3.0/test/000077500000000000000000000000001226277733300141665ustar00rootroot00000000000000instant-1.3.0/test/Probe/000077500000000000000000000000001226277733300152355ustar00rootroot00000000000000instant-1.3.0/test/Probe/Probe.cpp000066400000000000000000000114461226277733300170160ustar00rootroot00000000000000// Copyright (C) 2013 Kent-Andre Mardal, Mikael Mortensen, Johan Hake // // This file is part of DOLFIN. // // DOLFIN 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. // // DOLFIN 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 DOLFIN. If not, see . // // First added: 2013-04-02 #include #include #include #include #include #include #include "Probe.h" using namespace dolfin; //---------------------------------------------------------------------------- Probe::Probe(const Array& x, const FunctionSpace& V) : _element(V.element()) { const Mesh& mesh = *V.mesh(); const std::size_t gdim = mesh.geometry().dim(); // Store position of probe for (std::size_t i = 0; i < 3; i++) _x[i] = (i < gdim ? x[i] : 0.0); // Compute in tensor (one for scalar function, . . .) value_size_loc = 1; for (uint i = 0; i < _element->value_rank(); i++) value_size_loc *= _element->value_dimension(i); _probes.resize(value_size_loc); // Find the cell that contains probe const Point point(gdim, x.data()); boost::shared_ptr tree = mesh.bounding_box_tree(); const unsigned int id = tree->compute_first_entity_collision(point); // If the cell is on this process, then create an instance // of the Probe class. Otherwise raise a dolfin_error. if (id != std::numeric_limits::max()) { // Create cell that contains point dolfin_cell.reset(new Cell(mesh, id)); dolfin_cell->get_cell_data(ufc_cell); dolfin_cell->get_vertex_coordinates(_vertex_coordinates); // Create work vector for basis std::vector basis(value_size_loc); _coefficients.resize(_element->space_dimension()); // Create work vector for basis _basis_matrix.resize(value_size_loc); for (std::size_t i = 0; i < value_size_loc; ++i) _basis_matrix[i].resize(_element->space_dimension()); for (std::size_t i = 0; i < _element->space_dimension(); ++i) { _element->evaluate_basis(i, basis.data(), x.data(), _vertex_coordinates.data(), dolfin_cell->orientation()); for (std::size_t j = 0; j < value_size_loc; ++j) _basis_matrix[j][i] = basis[j]; } } else dolfin_error("Probe.cpp","set probe","Probe is not found on processor"); } //---------------------------------------------------------------------------- std::size_t Probe::value_size() const { return value_size_loc; } //---------------------------------------------------------------------------- std::size_t Probe::number_of_evaluations() const { return _probes[0].size(); } //---------------------------------------------------------------------------- void Probe::eval(const Function& u) { // Restrict function to cell u.restrict(&_coefficients[0], *_element, *dolfin_cell, _vertex_coordinates.data(), ufc_cell); // Make room for one more evaluation for (std::size_t j = 0; j < value_size_loc; j++) _probes[j].push_back(0.0); const std::size_t n = _probes[0].size() - 1; // Compute linear combination for (std::size_t i = 0; i < _element->space_dimension(); i++) { for (std::size_t j = 0; j < value_size_loc; j++) _probes[j][n] += _coefficients[i]*_basis_matrix[j][i]; } } //---------------------------------------------------------------------------- void Probe::erase(std::size_t i) { for (std::size_t j = 0; j < value_size_loc; j++) _probes[j].erase(_probes[j].begin()+i); } //---------------------------------------------------------------------------- void Probe::clear() { for (std::size_t j = 0; j < value_size_loc; j++) _probes[j].clear(); } //---------------------------------------------------------------------------- std::vector Probe::get_probe(std::size_t i) const { return _probes[i]; } //---------------------------------------------------------------------------- std::vector Probe::coordinates() const { std::vector x(3); x.assign(_x, _x + 3); return x; } //---------------------------------------------------------------------------- instant-1.3.0/test/Probe/Probe.h000066400000000000000000000040061226277733300164550ustar00rootroot00000000000000// Copyright (C) 2013 Kent-Andre Mardal, Mikael Mortensen, Johan Hake // // This file is part of DOLFIN. // // DOLFIN 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. // // DOLFIN 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 DOLFIN. If not, see . // // First added: 2013-04-02 #ifndef __PROBE_H #define __PROBE_H #include #include #include namespace dolfin { class Cell; class FiniteElement; class Function; class FunctionSpace; template class Array; class Probe { public: /// Constructor Probe(const Array& x, const FunctionSpace& V); void eval(const Function& u); /// Return probe values for chosen value_size std::vector get_probe(std::size_t i) const; std::size_t value_size() const; std::size_t number_of_evaluations() const; /// Return coordinates of probe std::vector coordinates() const; /// Remove one instance of the probe void erase(std::size_t i); /// Reset probe by removing all values void clear(); private: std::vector > _basis_matrix; std::vector _coefficients; double _x[3]; boost::shared_ptr _element; boost::scoped_ptr dolfin_cell; ufc::cell ufc_cell; std::vector _vertex_coordinates; std::size_t value_size_loc; std::vector > _probes; }; } #endif instant-1.3.0/test/_test_ode_omp.py000077500000000000000000000034531226277733300173700ustar00rootroot00000000000000 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): p[i] = p[i-1] + dt*(B*Q[i] - A*p[i-1]) c_code = r''' 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; } if ( n != N ) { printf("n and N should be equal"); return; } #pragma omp parallel { int id; id = omp_get_thread_num(); printf("Thread %d\n", id); p[0] = p0; #pragma omp for for (int i=1; iGetNumberOfElements(); i++) { a->SetElement(i,i); } } """ func = inline_vmtk(code, cache_dir="test_vmtk") v = vtkvmtk.vtkvmtkDoubleVector() v.Allocate(12,1) print("norm of v ", v.ComputeNorm()) func(v) print("norm of v after test ", v.ComputeNorm()) instant-1.3.0/test/_test_vtk.py000066400000000000000000000026121226277733300165430ustar00rootroot00000000000000 from instant import inline_vtk import vtk c_code1 = """ vtkObject* test1(char* filename){ std::cout <<" Reading grid file "<SetFileName(filename); reader1->Update(); vtkUnstructuredGrid* grid; grid= reader1->GetOutput(); std::cout << "Number of cells "<GetNumberOfCells () <GetNumberOfCells () <GetNumberOfCells (); i++) { cell = grid->GetCell (i); std::cout <<"cell no. "<GetCellType () <GetPoints (); std::cout <<"points->GetNumberOfPoints() "<< points->GetNumberOfPoints() <GetNumberOfPoints(); d++){ points->GetPoint(d, x); std::cout <<" x " <GetPointIds(); for (int d=0; dGetNumberOfIds(); d++){ std::cout <<" ids " <GetId(d) < double some_func(double a) { return cos(a) + sin(a); } instant-1.3.0/test/test1.py000077500000000000000000000003111226277733300155760ustar00rootroot00000000000000#!/usr/bin/env python 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)) instant-1.3.0/test/test10.py000077500000000000000000000071071226277733300156700ustar00rootroot00000000000000#!/usr/bin/env python import numpy import time from instant import inline_with_numpy # 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; for (int i=0; i t2 assert t1 > t3 instant-1.3.0/test/test18.py000077500000000000000000000026621226277733300157010ustar00rootroot00000000000000#!/usr/bin/python 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 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 sig = Sig("((test18.py signature))") cache_dir = "test_cache" # 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 t2 = toc("second build") tic() module = build_module(code=c_code, signature=sig, cache_dir=cache_dir) assert module is not None t3 = toc("third build") # Time importing tic() module = import_module(sig, cache_dir) assert module is not None t4 = toc("first import") 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 instant-1.3.0/test/test19.py000077500000000000000000000070761226277733300157060ustar00rootroot00000000000000#!/usr/bin/python import shutil import time import os 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 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 instant-1.3.0/test/test2.py000077500000000000000000000012711226277733300156050ustar00rootroot00000000000000#!/usr/bin/env python 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 tmp) { tmp = array1[i]; } } return tmp; } """ c_module = inline_module_with_numpy(c_code, arrays = [['n1', 'array1']], cache_dir="test_cache") a = numpy.arange(10000000); a = numpy.sin(a) sum_func = c_module.sum max_func = c_module.max sum = sum_func(a) max = max_func(a) print("sum ", sum) print("max ", max) instant-1.3.0/test/test21.py000077500000000000000000000015751226277733300156750ustar00rootroot00000000000000#!/usr/bin/env python import sys, os, threading from instant import inline def compile_stuff(i): c_code = """ double sum(int a, int b) { return a + b; } // Code number %d """ % (i % 2) func = inline(c_code, cache_dir="test_locking_cache") s = func(i, 3) assert s == (i+3) print("In run %d, result is %d as expected." % (i, s)) if __name__ == "__main__": cmd = sys.argv[0] args = sys.argv[1:] if args: print("Compiling with args =", args) i, = args compile_stuff(int(i)) else: print("Starting new processes to compile.") def run(i): os.system("python %s %d" % (cmd, i)) threads = [] for i in range(10): threads.append( threading.Thread(target=run, args=(i,)) ) for t in threads: t.start() for t in threads: t.join() instant-1.3.0/test/test3.py000077500000000000000000000005431226277733300156070ustar00rootroot00000000000000#!/usr/bin/env python 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)) instant-1.3.0/test/test4.py000077500000000000000000000025051226277733300156100ustar00rootroot00000000000000#!/usr/bin/env python 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)) instant-1.3.0/test/test5.py000077500000000000000000000025141226277733300156110ustar00rootroot00000000000000#!/usr/bin/python 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& x, const FunctionSpace& V); void eval(const Function& u); std::vector get_probe(std::size_t i) const; std::size_t value_size() const; std::size_t number_of_evaluations() const; std::vector coordinates() const; void erase(std::size_t i); void clear(); private: std::vector > _basis_matrix; std::vector _coefficients; double _x[3]; boost::shared_ptr _element; boost::scoped_ptr dolfin_cell; ufc::cell ufc_cell; std::vector _vertex_coordinates; std::size_t value_size_loc; std::vector > _probes; }; } """ additional_declarations= """ %init%{ import_array(); %} // Include global SWIG interface files: // Typemaps, shared_ptr declarations, exceptions, version %include // Global typemaps and forward declarations %include "dolfin/swig/typemaps/includes.i" %include "dolfin/swig/forwarddeclarations.i" // Global exceptions %include // Local shared_ptr declarations %shared_ptr(dolfin::Function) %shared_ptr(dolfin::FunctionSpace) // %import types from submodule function of SWIG module function %import(module="dolfin.cpp.function") "dolfin/function/Function.h" %import(module="dolfin.cpp.function") "dolfin/function/FunctionSpace.h" %feature("autodoc", "1"); """ system_headers = ['numpy/arrayobject.h', 'dolfin/function/Function.h', 'dolfin/function/FunctionSpace.h'] swigargs = ['-c++', '-fcompact', '-O', '-I.', '-small'] cmake_packages = ['DOLFIN'] sources=["Probe.cpp"] source_dir="Probe" include_dirs=[".", os.path.abspath("Probe")] compiled_module = instant.build_module(code=code, source_directory=source_dir, \ additional_declarations=additional_declarations, \ system_headers=system_headers, \ include_dirs=include_dirs, \ swigargs=swigargs, \ sources=sources, \ cmake_packages=cmake_packages) mesh = UnitCubeMesh(10, 10, 10) V = FunctionSpace(mesh, 'CG', 1) x = numpy.array((0.5, 0.5, 0.5)) probe = compiled_module.Probe(x, V) # Just create some random data to be used for probing u0 = interpolate(Expression('x[0]'), V) probe.eval(u0) print "The number of probes is ", probe.value_size() print "The value at ", x, " is ", probe.get_probe(0) instant-1.3.0/test/test_ode.py000077500000000000000000000027051226277733300163550ustar00rootroot00000000000000#!/usr/bin/python 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): 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, double dt, int N, double p0) { if ( n != m ) { printf("n and m should be equal"); return; } if ( n != N ) { printf("n and N should be equal"); return; } p[0] = p0; for (int i=1; i 13.839100 12.873900 0.000000 13.623200 12.606700 0.000000 13.874600 12.666100 0.000000 13.742100 12.401000 0.000000 13.910000 12.458200 0.000000 10.547900 14.172600 0.000000 10.355600 14.565700 0.000000 10.326900 14.164100 0.000000 10.621100 14.520300 0.000000 10.694300 14.868000 0.000000 10.384300 14.967300 0.000000 10.767400 15.215800 0.000000 10.413000 15.368900 0.000000 9.963150 11.221800 0.000000 10.115600 11.587700 0.000000 9.878450 11.540300 0.000000 10.226700 11.350200 0.000000 10.262900 11.017800 0.000000 10.047900 10.903300 0.000000 10.132600 10.584800 0.000000 10.469000 10.395900 0.000000 10.217300 10.266300 0.000000 10.480900 10.629600 0.000000 10.497700 10.960200 0.000000 10.514500 11.290900 0.000000 10.330500 11.612300 0.000000 10.531300 11.621500 0.000000 10.750000 10.436100 0.000000 11.415600 10.974000 0.000000 11.156800 11.211600 0.000000 11.134500 10.911800 0.000000 11.275500 10.648000 0.000000 11.180300 11.728000 0.000000 11.085100 11.490700 0.000000 11.282100 11.568300 0.000000 10.955000 11.666500 0.000000 10.782000 11.450500 0.000000 10.847800 11.195000 0.000000 10.913600 10.939500 0.000000 10.979300 10.684000 0.000000 11.045100 10.428500 0.000000 11.328500 10.447100 0.000000 11.574800 10.564800 0.000000 11.782600 10.783000 0.000000 11.615800 11.044800 0.000000 11.449000 11.306500 0.000000 11.986700 10.994400 0.000000 11.840200 11.314000 0.000000 11.693700 11.633600 0.000000 11.386000 11.822300 0.000000 11.547200 11.953200 0.000000 11.834300 11.777400 0.000000 11.639200 12.124300 0.000000 12.029400 11.430500 0.000000 12.224500 11.083700 0.000000 12.093300 11.830400 0.000000 12.345200 11.586500 0.000000 12.510600 11.064700 0.000000 12.663100 11.421500 0.000000 12.799100 11.165100 0.000000 12.962000 11.398200 0.000000 12.955400 11.676800 0.000000 12.666100 11.823000 0.000000 12.331100 11.992500 0.000000 11.996000 12.161900 0.000000 11.661000 12.331300 0.000000 13.010000 11.908700 0.000000 12.908600 13.287500 0.000000 12.747700 12.847900 0.000000 13.109900 12.946300 0.000000 12.584700 13.154500 0.000000 12.385600 12.749500 0.000000 12.260800 13.021400 0.000000 12.023400 12.651000 0.000000 11.936900 12.888300 0.000000 11.661200 12.775000 0.000000 11.661300 12.552600 0.000000 13.371400 12.646600 0.000000 13.122400 12.661600 0.000000 13.360800 12.414000 0.000000 13.134900 12.377000 0.000000 13.352900 12.238100 0.000000 13.147400 12.092300 0.000000 13.611900 12.356600 0.000000 11.364700 15.866000 0.000000 11.426000 16.340900 0.000000 11.153700 16.262600 0.000000 11.078200 15.945400 0.000000 15.226600 14.859800 0.000000 15.662200 14.943400 0.000000 15.451000 15.128600 0.000000 15.416800 14.669800 0.000000 15.002100 14.590900 0.000000 15.171300 14.396200 0.000000 14.839700 15.075400 0.000000 14.713100 14.713900 0.000000 15.215500 15.288800 0.000000 14.966300 15.437000 0.000000 14.540000 15.166100 0.000000 14.710800 15.581400 0.000000 14.369200 14.750700 0.000000 14.050300 15.141200 0.000000 14.004500 14.759900 0.000000 14.450300 15.721000 0.000000 14.219900 15.627500 0.000000 13.989500 15.534000 0.000000 13.549000 15.355300 0.000000 13.108500 15.176500 0.000000 13.347500 14.928300 0.000000 13.652600 14.799600 0.000000 13.094400 16.273900 0.000000 13.191200 15.913800 0.000000 13.370800 16.189700 0.000000 12.727400 15.990300 0.000000 12.816500 16.340700 0.000000 12.892200 15.454500 0.000000 12.638200 15.639900 0.000000 12.283400 16.035800 0.000000 12.308000 15.657700 0.000000 12.537800 16.388000 0.000000 12.258800 16.413800 0.000000 11.850500 16.018400 0.000000 11.702200 16.392200 0.000000 11.616400 15.648800 0.000000 11.946000 15.611800 0.000000 11.980000 16.415900 0.000000 10.888800 16.160000 0.000000 10.731000 15.808900 0.000000 10.633900 16.036100 0.000000 10.389400 15.895000 0.000000 10.407800 15.590600 0.000000 10.155200 15.740700 0.000000 9.321390 11.895300 0.000000 9.582190 11.700700 0.000000 9.546900 11.939100 0.000000 9.459500 12.115700 0.000000 9.252960 12.134600 0.000000 9.180660 12.000400 0.000000 9.039940 12.105400 0.000000 11.120200 14.864200 0.000000 11.170800 15.216100 0.000000 11.083700 14.609500 0.000000 11.047100 14.354900 0.000000 10.778100 14.130700 0.000000 12.075900 15.059600 0.000000 11.981200 14.453900 0.000000 12.292000 14.802000 0.000000 11.694200 14.590600 0.000000 11.792200 15.267300 0.000000 11.407200 14.727400 0.000000 11.491600 15.306500 0.000000 12.298700 13.760000 0.000000 12.765900 13.617300 0.000000 12.657200 13.934600 0.000000 12.387200 13.480800 0.000000 11.940100 13.585400 0.000000 12.008400 13.344300 0.000000 11.581500 13.410700 0.000000 11.629700 13.207800 0.000000 11.653500 12.994600 0.000000 14.436600 13.173000 0.000000 14.183700 12.817100 0.000000 14.509300 12.915400 0.000000 14.105800 13.098200 0.000000 14.232600 12.553300 0.000000 14.565100 12.652400 0.000000 14.892900 12.765900 0.000000 14.832800 12.999500 0.000000 14.772600 13.233100 0.000000 15.201600 12.904300 0.000000 15.127900 13.156900 0.000000 15.054300 13.409500 0.000000 15.234800 13.709300 0.000000 15.337500 13.297000 0.000000 15.470700 13.498200 0.000000 15.476600 13.077500 0.000000 15.706500 13.287200 0.000000 15.882600 13.526000 0.000000 15.630200 13.743100 0.000000 15.996300 13.786300 0.000000 15.657800 14.062100 0.000000 16.039100 14.060700 0.000000 15.276400 14.063500 0.000000 16.004700 14.340500 0.000000 15.612500 14.381400 0.000000 15.901700 14.610000 0.000000 11.788700 13.777800 0.000000 11.498400 13.604100 0.000000 12.079000 13.951600 0.000000 12.558300 14.238500 0.000000 11.819500 14.272700 0.000000 12.444700 14.528000 0.000000 11.502900 13.918100 0.000000 11.206700 13.924700 0.000000 11.375500 13.775300 0.000000 11.002600 14.045600 0.000000 9.714110 15.397900 0.000000 10.099000 15.334000 0.000000 9.930380 15.574800 0.000000 9.713240 14.997700 0.000000 10.073600 14.973800 0.000000 9.505400 15.210600 0.000000 9.303300 15.013600 0.000000 9.578800 14.708300 0.000000 10.054300 14.613100 0.000000 9.854300 14.403100 0.000000 10.129800 14.097800 0.000000 9.706900 14.123800 0.000000 9.970830 13.967600 0.000000 9.442970 14.280100 0.000000 9.179030 14.436300 0.000000 9.106850 14.807300 0.000000 8.915100 14.592600 0.000000 9.697300 13.870800 0.000000 9.851230 13.791600 0.000000 9.471900 13.986800 0.000000 9.246500 14.102700 0.000000 8.986800 14.236300 0.000000 8.727110 14.369900 0.000000 9.759630 13.610000 0.000000 8.363620 13.902900 0.000000 8.796040 13.895900 0.000000 8.542120 14.139900 0.000000 8.599120 13.521400 0.000000 8.198950 13.658800 0.000000 8.321450 13.265400 0.000000 8.055620 13.407500 0.000000 8.587270 13.123200 0.000000 8.984230 13.355000 0.000000 8.853100 12.981100 0.000000 9.115370 13.728800 0.000000 8.145440 12.587300 0.000000 7.862930 12.883100 0.000000 7.828560 12.609900 0.000000 8.139680 12.943300 0.000000 8.444440 12.867100 0.000000 8.462310 12.564800 0.000000 8.748160 12.776200 0.000000 8.779180 12.542200 0.000000 9.055730 12.872700 0.000000 9.096060 12.519700 0.000000 9.258360 12.764400 0.000000 7.941110 13.149000 0.000000 7.885870 12.046600 0.000000 8.056330 12.342600 0.000000 7.840170 12.330000 0.000000 8.159570 12.112200 0.000000 8.344530 12.367400 0.000000 8.433270 12.177800 0.000000 8.706970 12.243500 0.000000 8.980670 12.309100 0.000000 8.762100 12.021400 0.000000 8.949530 12.161400 0.000000 8.559720 11.870300 0.000000 8.369810 11.966800 0.000000 8.141540 11.837400 0.000000 7.953890 11.763300 0.000000 8.043210 11.484700 0.000000 8.357340 11.719200 0.000000 9.628670 10.620000 0.000000 9.694410 11.035400 0.000000 9.385690 10.860200 0.000000 9.157050 10.605800 0.000000 9.400030 10.365600 0.000000 9.871640 10.379800 0.000000 9.676280 11.546100 0.000000 9.420820 11.287700 0.000000 9.165360 11.029200 0.000000 8.909890 10.770800 0.000000 8.880950 10.328800 0.000000 8.654430 10.512400 0.000000 9.140420 10.179100 0.000000 9.422630 10.078500 0.000000 9.706910 10.051100 0.000000 9.972540 10.120500 0.000000 8.293950 10.960500 0.000000 8.376100 11.387200 0.000000 8.155880 11.215500 0.000000 8.722100 10.994000 0.000000 8.741750 11.360000 0.000000 8.459450 10.724600 0.000000 9.108280 11.349400 0.000000 9.373230 11.585900 0.000000 9.070180 11.625700 0.000000 8.713760 11.672400 0.000000 10.700400 10.953800 0.000000 10.765600 10.678900 0.000000 10.734800 11.633800 0.000000 12.138500 12.398600 0.000000 12.517000 12.370500 0.000000 12.855800 12.206600 0.000000 13.457300 15.787200 0.000000 13.645200 16.090200 0.000000 13.743400 15.852600 0.000000 13.723400 15.660600 0.000000 13.976200 15.745800 0.000000 14.185600 15.853800 0.000000 13.917000 15.977500 0.000000 11.542500 14.382500 0.000000 11.294800 14.209800 0.000000 11.661200 14.095400 0.000000 9.512360 13.757500 0.000000 9.292440 13.830600 0.000000 9.338380 13.558600 0.000000 9.527760 13.535700 0.000000 9.384330 13.286500 0.000000 9.430270 13.014400 0.000000 9.574700 13.241300 0.000000 9.676580 13.433400 0.000000 9.161640 13.117900 0.000000 8.920990 11.985600 0.000000 9.079880 11.949800 0.000000 0 1 2 1 2 3 2 3 4 5 6 7 5 6 8 6 8 9 6 9 10 9 10 11 10 11 12 13 14 15 13 14 16 13 16 17 13 17 18 17 18 19 19 20 21 19 20 22 17 19 22 17 22 23 17 23 24 16 17 24 24 25 26 16 24 25 14 16 25 20 22 27 28 29 30 28 30 31 32 33 34 32 33 35 33 35 36 33 36 37 29 33 37 29 37 38 29 30 38 30 38 39 30 31 39 31 39 40 31 40 41 31 41 42 28 31 42 28 42 43 28 43 44 28 44 45 28 29 45 29 34 45 29 33 34 43 44 46 44 46 47 44 45 47 45 47 48 34 45 48 34 48 49 48 49 50 50 51 52 48 50 51 48 51 53 47 48 53 46 47 53 46 53 54 51 53 55 53 55 56 53 54 56 54 56 57 56 57 58 57 58 59 58 59 60 58 60 61 58 61 62 56 58 62 56 62 63 55 56 63 55 63 64 52 64 65 51 52 64 51 55 64 61 62 66 67 68 69 67 68 70 68 70 71 70 71 72 71 72 73 72 73 74 73 74 75 73 75 76 69 77 78 77 78 79 78 79 80 79 80 81 80 81 82 79 81 83 1 3 83 1 79 83 1 77 79 84 85 86 84 86 87 88 89 90 88 89 91 88 91 92 91 92 93 88 92 94 92 94 95 88 90 96 88 94 96 94 96 97 97 98 99 94 97 98 94 95 98 95 98 100 100 101 102 98 100 101 98 99 103 98 103 104 98 101 104 101 104 105 101 105 106 106 107 108 106 108 109 101 106 109 101 102 109 110 111 112 110 113 114 110 111 113 111 113 115 113 115 116 113 116 117 116 117 118 113 114 119 113 117 119 117 119 120 85 121 122 84 85 121 84 121 123 121 123 124 117 118 124 117 121 124 117 120 125 117 121 125 121 122 125 86 87 126 126 127 128 87 126 127 127 128 129 127 129 130 129 130 131 132 133 134 132 134 135 132 135 136 132 136 137 136 137 138 11 139 140 9 11 139 9 139 141 8 9 141 8 141 142 8 142 143 5 8 143 144 145 146 144 145 147 144 147 148 147 148 149 148 149 150 140 149 150 139 140 149 151 152 153 151 152 154 151 154 155 154 155 156 155 156 157 156 157 158 67 70 152 70 152 154 70 72 154 72 154 156 72 74 156 74 156 158 74 158 159 160 161 162 160 161 163 0 161 163 0 2 161 2 4 164 2 161 164 161 164 165 161 162 165 162 165 166 162 166 167 162 167 168 160 162 168 166 167 169 167 169 170 167 168 170 168 170 171 172 173 174 171 172 173 170 171 173 169 170 175 170 173 175 173 175 176 173 174 176 174 176 177 174 177 178 177 178 179 179 180 181 178 179 180 178 180 182 172 178 182 172 174 178 180 181 183 180 183 184 183 184 185 89 91 185 91 184 185 91 93 184 93 182 184 180 182 184 155 157 186 157 186 187 155 186 188 151 155 188 151 153 189 151 188 189 145 188 189 145 188 190 145 189 191 145 146 191 192 193 194 142 143 195 196 197 198 196 197 199 197 199 200 196 199 201 199 201 202 199 202 203 199 203 204 199 200 204 203 204 205 204 205 206 7 204 206 6 7 204 6 10 204 10 200 204 10 197 200 10 12 197 12 130 197 130 131 197 131 197 198 205 206 207 206 207 208 205 207 209 203 205 209 203 209 210 202 203 211 203 210 211 210 211 212 207 208 213 208 213 214 207 213 215 207 209 215 209 215 216 209 210 216 210 216 217 210 212 217 212 217 218 213 214 219 220 221 222 220 221 223 220 223 224 224 225 226 223 224 225 223 225 227 227 228 229 223 227 228 223 228 230 221 223 230 216 221 230 216 217 221 217 218 222 217 221 222 231 232 233 231 232 234 231 234 235 231 235 236 235 236 237 236 237 238 238 239 240 239 240 241 237 238 239 229 237 239 227 229 237 227 235 237 225 227 235 225 234 235 225 226 242 225 234 242 232 234 242 243 244 245 243 244 246 244 246 247 246 247 248 247 248 249 238 240 250 238 249 250 236 238 249 236 247 249 231 236 247 231 244 247 231 233 244 233 244 245 248 249 251 249 250 252 249 251 252 248 251 253 248 253 254 246 248 254 246 254 255 243 246 255 243 255 256 255 256 257 255 257 258 254 255 258 253 254 258 259 260 261 259 261 262 259 262 263 259 263 264 13 15 265 13 260 265 260 265 266 260 261 266 261 266 267 261 262 267 262 267 268 268 269 270 262 268 269 262 269 271 262 263 271 263 271 272 263 272 273 263 264 273 264 273 274 21 264 274 19 21 264 19 259 264 18 19 259 18 259 260 13 18 260 275 276 277 275 276 278 276 278 279 275 278 280 268 270 280 268 278 280 267 268 278 267 278 281 278 279 281 266 267 281 265 266 282 266 281 282 281 282 283 279 281 283 279 283 284 276 279 284 258 276 284 257 258 276 257 276 277 22 23 285 22 285 286 22 27 286 27 39 40 27 39 286 38 39 286 38 285 286 37 38 285 24 36 37 26 36 287 24 26 36 24 37 285 23 24 285 35 36 287 32 34 49 63 64 288 63 288 289 63 289 290 62 63 290 62 66 290 66 82 290 80 82 290 78 80 290 68 78 290 68 69 78 68 289 290 68 71 289 71 288 289 71 73 288 65 73 76 65 73 288 64 65 288 74 75 159 111 112 291 112 291 292 291 292 293 291 293 294 293 294 295 105 294 295 104 105 295 103 104 296 104 295 296 295 296 297 293 295 297 292 293 297 106 107 115 111 115 291 106 115 291 106 291 294 105 106 294 147 149 298 141 149 298 139 141 149 141 298 299 141 142 299 142 195 299 193 195 299 192 193 299 192 299 300 298 299 300 190 298 300 145 147 190 147 190 298 186 187 192 187 192 194 186 192 300 186 188 300 188 190 300 213 215 301 215 216 302 215 301 302 301 302 303 301 303 304 303 304 305 305 306 307 304 305 307 304 307 308 219 304 308 219 301 304 213 219 301 239 241 309 241 306 309 305 306 309 228 303 305 230 302 303 216 230 302 228 230 303 228 305 309 228 229 309 229 239 309 283 310 311 283 284 310 251 284 310 251 253 284 253 258 284 251 252 310 138 252 310 138 310 311 137 138 311 132 137 311 133 265 282 132 133 282 132 282 283 132 283 311 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 63 66 69 72 75 78 81 84 87 90 93 96 99 102 105 108 111 114 117 120 123 126 129 132 135 138 141 144 147 150 153 156 159 162 165 168 171 174 177 180 183 186 189 192 195 198 201 204 207 210 213 216 219 222 225 228 231 234 237 240 243 246 249 252 255 258 261 264 267 270 273 276 279 282 285 288 291 294 297 300 303 306 309 312 315 318 321 324 327 330 333 336 339 342 345 348 351 354 357 360 363 366 369 372 375 378 381 384 387 390 393 396 399 402 405 408 411 414 417 420 423 426 429 432 435 438 441 444 447 450 453 456 459 462 465 468 471 474 477 480 483 486 489 492 495 498 501 504 507 510 513 516 519 522 525 528 531 534 537 540 543 546 549 552 555 558 561 564 567 570 573 576 579 582 585 588 591 594 597 600 603 606 609 612 615 618 621 624 627 630 633 636 639 642 645 648 651 654 657 660 663 666 669 672 675 678 681 684 687 690 693 696 699 702 705 708 711 714 717 720 723 726 729 732 735 738 741 744 747 750 753 756 759 762 765 768 771 774 777 780 783 786 789 792 795 798 801 804 807 810 813 816 819 822 825 828 831 834 837 840 843 846 849 852 855 858 861 864 867 870 873 876 879 882 885 888 891 894 897 900 903 906 909 912 915 918 921 924 927 930 933 936 939 942 945 948 951 954 957 960 963 966 969 972 975 978 981 984 987 990 993 996 999 1002 1005 1008 1011 1014 1017 1020 1023 1026 1029 1032 1035 1038 1041 1044 1047 1050 1053 1056 1059 1062 1065 1068 1071 1074 1077 1080 1083 1086 1089 1092 1095 1098 1101 1104 1107 1110 1113 1116 1119 1122 1125 1128 1131 1134 1137 1140 1143 1146 1149 1152 1155 1158 1161 1164 1167 1170 1173 1176 1179 1182 1185 1188 1191 1194 1197 1200 1203 1206 1209 1212 1215 1218 1221 1224 1227 1230 1233 1236 1239 1242 1245 1248 1251 1254 1257 1260 1263 1266 1269 1272 1275 1278 1281 1284 1287 1290 1293 1296 1299 1302 1305 1308 1311 1314 1317 1320 1323 1326 1329 1332 1335 1338 1341 1344 1347 1350 1353 1356 1359 1362 1365 1368 1371 1374 1377 1380 1383 1386 1389 1392 1395 1398 1401 1404 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 1.426730e+00 1.374390e+00 1.418458e+00 1.384971e+00 1.414920e+00 1.849535e+00 2.034070e+00 1.853364e+00 1.927511e+00 1.918304e+00 1.981738e+00 1.907446e+00 1.953255e+00 3.827848e-01 4.719162e-01 3.755406e-01 4.808449e-01 4.632717e-01 3.920855e-01 3.913151e-01 4.529437e-01 3.625016e-01 4.907213e-01 5.218821e-01 5.517520e-01 5.339134e-01 5.764968e-01 5.526561e-01 7.511818e-01 6.983820e-01 6.762518e-01 6.948893e-01 7.248998e-01 6.907134e-01 7.548820e-01 6.560157e-01 6.171855e-01 6.222235e-01 6.238414e-01 6.257282e-01 6.378878e-01 6.995318e-01 7.503244e-01 8.197499e-01 8.089605e-01 7.867080e-01 9.149888e-01 9.043851e-01 9.047515e-01 8.217952e-01 9.198666e-01 9.746110e-01 1.011255e+00 9.754204e-01 1.012503e+00 1.053489e+00 1.074722e+00 1.081233e+00 1.118978e+00 1.121136e+00 1.143241e+00 1.170624e+00 1.158676e+00 1.132203e+00 1.102542e+00 1.088778e+00 1.215815e+00 1.396933e+00 1.328120e+00 1.339906e+00 1.380629e+00 1.289094e+00 1.343167e+00 1.231812e+00 1.286913e+00 1.225025e+00 1.156542e+00 1.329536e+00 1.319004e+00 1.321630e+00 1.292160e+00 1.311773e+00 1.266043e+00 1.360820e+00 1.803160e+00 1.797502e+00 1.812828e+00 1.827300e+00 1.661053e+00 1.651653e+00 1.658974e+00 1.651466e+00 1.663744e+00 1.648127e+00 1.678517e+00 1.682506e+00 1.667356e+00 1.677261e+00 1.690835e+00 1.687474e+00 1.698503e+00 1.707990e+00 1.710203e+00 1.697164e+00 1.703861e+00 1.710704e+00 1.721403e+00 1.728308e+00 1.722797e+00 1.717858e+00 1.739873e+00 1.735256e+00 1.731663e+00 1.750118e+00 1.748326e+00 1.737898e+00 1.750604e+00 1.766000e+00 1.766554e+00 1.756886e+00 1.765786e+00 1.782280e+00 1.785295e+00 1.789636e+00 1.780063e+00 1.775074e+00 1.833173e+00 1.876666e+00 1.864950e+00 1.897795e+00 1.932199e+00 1.930100e+00 1.018333e-01 1.901935e-01 1.370078e-01 1.148508e-01 7.679714e-02 4.332885e-02 -4.689006e-02 1.828111e+00 1.825396e+00 1.817515e+00 1.790165e+00 1.805169e+00 1.732487e+00 1.675558e+00 1.697901e+00 1.721164e+00 1.763329e+00 1.771962e+00 1.788127e+00 1.517553e+00 1.471663e+00 1.546011e+00 1.451654e+00 1.486586e+00 1.419212e+00 1.438433e+00 1.366569e+00 1.295728e+00 1.492598e+00 1.458610e+00 1.493502e+00 1.460642e+00 1.456579e+00 1.492974e+00 1.529371e+00 1.529664e+00 1.530722e+00 1.563159e+00 1.565013e+00 1.570135e+00 1.603352e+00 1.586983e+00 1.602954e+00 1.588710e+00 1.606575e+00 1.619019e+00 1.618431e+00 1.626772e+00 1.630269e+00 1.632507e+00 1.627950e+00 1.637952e+00 1.640677e+00 1.642863e+00 1.547722e+00 1.511132e+00 1.570044e+00 1.609958e+00 1.656042e+00 1.660906e+00 1.614478e+00 1.667647e+00 1.587308e+00 1.741102e+00 1.970625e+00 1.971209e+00 1.954892e+00 2.004828e+00 2.027037e+00 1.976867e+00 1.946839e+00 2.057755e+00 2.216105e+00 2.495600e+00 1.795388e+00 3.874548e+00 1.343937e+01 2.265145e+00 1.826013e+00 1.868243e+00 1.704072e+00 1.540359e+01 1.403871e+01 2.572474e+00 1.792538e+00 1.524851e+00 1.419526e+00 1.198732e+01 7.367881e-01 9.953851e-01 1.066362e+00 4.675903e-01 4.762042e-01 2.502890e-01 2.885633e-01 4.164100e-02 -2.196188e-02 -4.374769e-01 8.547196e-01 4.474812e-02 1.096382e-01 6.831169e-02 1.222949e-01 1.219348e-03 -7.202822e-02 -3.278376e-01 -3.396092e-01 -1.086061e+00 -8.824770e-01 -1.847974e+00 1.769271e-01 3.591502e-02 3.499963e-02 4.423750e-02 2.107380e-02 -2.191036e-02 -3.412441e-02 -1.518005e-01 -4.034278e-01 -7.488103e-02 -1.865134e-01 -2.456185e-03 3.779400e-03 3.308297e-02 4.031983e-02 5.730886e-02 3.281579e-02 2.751729e-01 2.970351e-01 2.257219e-01 1.976670e-01 2.345695e-01 3.099983e-01 2.678472e-01 2.074246e-01 1.742941e-01 1.599302e-01 1.776912e-01 1.515901e-01 2.061848e-01 2.343206e-01 2.642638e-01 3.017444e-01 1.009769e-01 6.931094e-02 7.728610e-02 1.243480e-01 8.438257e-02 1.255954e-01 1.296628e-01 1.594904e-01 7.508150e-02 2.972408e-02 5.732027e-01 5.708342e-01 6.115545e-01 1.183636e+00 1.226554e+00 1.240142e+00 1.726964e+00 1.723461e+00 1.719283e+00 1.718734e+00 1.711996e+00 1.706451e+00 1.715162e+00 1.707776e+00 1.716561e+00 1.636974e+00 -1.590347e-01 1.233107e+00 3.092582e-01 1.336676e+01 -2.228967e+00 -3.768477e+00 1.116396e+01 1.227489e+01 -1.422023e+00 -6.062756e-02 9.749067e-03 instant-1.3.0/test/zombie_model.py000066400000000000000000000035621226277733300172130ustar00rootroot00000000000000# Zombie model as described by # WHEN ZOMBIES ATTACK !: MATHEMATICAL MODELLING OF AN OUTBREAK OF ZOMBIE INFECTION # by Philip Munz, Ioan Hudea, Joe Imad, Robert J. Smith. # In: Infectious Disease Modelling Research Progress, # Editors: J.M. Tchuenche and C. Chiyaka, pp. 133-150 2009 Nova Science Publishers, Inc. from instant import inline_with_numpy from numpy import * c_code = """ void time_loop(int nS, double* S, int nI, double* I, int nZ, double* Z, int nR, double* R, double PI, double alpha, double beta, double delta, double rho, double zeta, double dt, int N, double S0, double I0, double Z0, double R0) { if ( nS != nI || nS != nZ || nS != nR || nS != N ) { printf("Arrays must be of same size!"); return; } S[0] = S0; I[0] = I0; Z[0] = Z0; R[0] = R0; for (int i=0; i