python-arrayfire-3.3.20160624/000077500000000000000000000000001276671162200155775ustar00rootroot00000000000000python-arrayfire-3.3.20160624/.gitignore000066400000000000000000000012761276671162200175750ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover # Translations *.mo *.pot # Django stuff: *.log # Sphinx documentation docs/_build/ # PyBuilder target/ python-arrayfire-3.3.20160624/CHANGELOG.md000066400000000000000000000112051276671162200174070ustar00rootroot00000000000000### v3.3.20160624 - Adding 16 bit integer support - Adding support for sphinx documentation ### v3.3.20160516 - Bugfix: Increase arrayfire's priority over numpy for mixed operations - Added new library functions - `get_backend` returns backend name ### v3.3.20160510 - Bugfix to `af.histogram` - Added missing functions / methods - `gaussian_kernel` - Added new array properties - `Array.T` now returns transpose - `Array.H` now returns hermitian transpose - `Array.shape` now allows easier access individual dimensions ### v3.3.20160427 - Fixes to numpy interop on Windows - Fixes issues with occasional double free - Fixes to graphics examples ### v3.3.20160328 - Fixes to make arrayfire-python to work on 32 bit systems ### v3.3.20160320 - Feature parity with Arrayfire 3.3 libs - Functions to interact with arryafire's internal data structures. - `Array.offset` - `Array.strides` - `Array.is_owner` - `Array.is_linear` - `Array.raw_ptr` - Array constructor now takes `offset` and `strides` as optional parameters. - New visualization functions: `scatter` and `scatter3` - OpenCL backend specific functions: - `get_device_type` - `get_platform` - `add_device_context` - `delete_device_context` - `set_device_context` - Functions to allocate and free memory on host and device - `alloc_host` and `free_host` - `alloc_pinned` and `free_pinned` - `alloc_device` and `free_device` - Function to query which device and backend an array was created on - `get_device_id` - `get_backend_id` - Miscellaneous functions - `is_lapack_available` - `is_image_io_available` - Interopability - Transfer PyCUDA GPUArrays using `af.pycuda_to_af_array` - Transfer PyOpenCL Arrays using `af.pyopencl_to_af_array` - New helper function `af.to_array` added to convert a different `array` to arrayfire Array. - This function can be used in place of `af.xyz_to_af_array` functions mentioned above. - Deprecated functions list - `lock_device_ptr` is deprecated. Use `lock_array` instead. - `unlock_device_ptr` is deprecated. Use `unlock_array` instead. - Bug Fixes: - [Boolean indexing giving faulty results](https://github.com/arrayfire/arrayfire-python/issues/68) for multi dimensional arrays. - [Enum types comparision failures](https://github.com/arrayfire/arrayfire-python/issues/65) in Python 2.x - [Support loading SO versioned libraries](https://github.com/arrayfire/arrayfire-python/issues/64) in Linux and OSX. - Fixed typo that prevented changing backend - Fixed image processing functions that accepted floating point scalar paramters. - Affected functions include: `translate`, `scale`, `skew`, `histogram`, `bilateral`, `mean_shift`. ### v3.2.20151224 - Bug fixes: - A default `AF_PATH` is set if none is found as an environment variable. - Examples: - Heston model example uses a smaller data set to help run on low end GPUs. ### v3.2.20151214 - Bug fixes: - `get_version()` now returns ints instead of `c_int` - Fixed bug in `tests/simple/device.py` - The module now looks at additional paths when loading ArrayFire libraries. - Link to the wiki is provided when `ctypes.cdll.LoadLibrary` fails. - New function: - `info_str()` returns information similar to `info()` as a string. - Updated README.md with latest instructions ### v3.2.20151211 - Feature parity with ArrayFire 3.2 libs - New computer vision functions: `sift`, `gloh`, `homography` - New graphics functions: `plot3`, `surface` - Functions to load and save native images: `load_image_native`, `save_image_native` - Use `unified` backend when possible - Added missing functions - `eval`, `init`, `convolve2_separable`, `as_type` method - `cuda` backend specific functions - `opencl` backend specific functions - `timeit` function to benchmark arrayfire functions - Added new examples - getting_started: `intro`, `convolve` - benchmarks: `bench_blas`, `bench_fft` - financial: `monte_carlo_options`, `black_scholes`, `heston_model` - graphics: `fractal`, `histogram`, `plot3d`, `conway`, `surface` - Bug fixes - Fixed bug when array types were being reported incorrectly - Fixed various bugs in graphics functions ### v3.1.20151111 - Feature parity with ArrayFire 3.1 libs - Ability to interop with other python libs - Ability to extract raw device pointers - Load and Save arrays from disk - Improved `__repr__` support ### v3.0.20150914 - Feature parity with ArrayFire 3.0 libs - Ability to switch all backends - Supports both python2 and python3 python-arrayfire-3.3.20160624/LICENSE000066400000000000000000000027141276671162200166100ustar00rootroot00000000000000Copyright (c) 2015, ArrayFire All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of arrayfire_python nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. python-arrayfire-3.3.20160624/README.md000066400000000000000000000071601276671162200170620ustar00rootroot00000000000000# ArrayFire Python Bindings [ArrayFire](https://github.com/arrayfire/arrayfire) is a high performance library for parallel computing with an easy-to-use API. It enables users to write scientific computing code that is portable across CUDA, OpenCL and CPU devices. This project provides Python bindings for the ArrayFire library. ## Status | OS | Tests | |:-------:|:-------:| | Linux | [![Build Status](http://ci.arrayfire.org/buildStatus/icon?job=arrayfire-wrappers/python-linux)](http://ci.arrayfire.org/view/All/job/arrayfire-wrappers/job/python-linux/) | | Windows | [![Build Status](http://ci.arrayfire.org/buildStatus/icon?job=arrayfire-wrappers/python-windows)](http://ci.arrayfire.org/view/All/job/arrayfire-wrappers/job/python-windows/) | | OSX | [![Build Status](http://ci.arrayfire.org/buildStatus/icon?job=arrayfire-wrappers/python-osx)](http://ci.arrayfire.org/view/All/job/arrayfire-wrappers/job/python-osx/) | ## Documentation Documentation for this project can be found [over here](http://arrayfire.org/arrayfire-python/). ## Example ```python # Monte Carlo estimation of pi def calc_pi_device(samples): # Simple, array based API # Generate uniformly distributed random numers x = af.randu(samples) y = af.randu(samples) # Supports Just In Time Compilation # The following line generates a single kernel within_unit_circle = (x * x + y * y) < 1 # Intuitive function names return 4 * af.count(within_unit_circle) / samples ``` Choosing a particular backend can be done using `af.backend.set( backend_name )` where backend_name can be one of: "_cuda_", "_opencl_", or "_cpu_". The default device is chosen in the same order of preference. ## Requirements Currently, this project is tested only on Linux and OSX. You also need to have the ArrayFire C/C++ library installed on your machine. You can get it from the following sources. - [Download and install binaries](https://arrayfire.com/download) - [Build and install from source](https://github.com/arrayfire/arrayfire) Please check the following links for dependencies. - [Linux dependencies](http://www.arrayfire.com/docs/using_on_linux.htm) - [OSX dependencies](http://www.arrayfire.com/docs/using_on_osx.htm) ## Getting started **Install the last stable version:** ``` pip install arrayfire ``` **Install the development version:** ``` pip install git+git://github.com/arrayfire/arrayfire.git@devel ``` **Installing offline** ``` cd path/to/arrayfire-python python setup.py install ``` **Post Installation** Please follow [these instructions](https://github.com/arrayfire/arrayfire-python/wiki) to ensure the arrayfire-python can find the arrayfire libraries. ## Acknowledgements The ArrayFire library is written by developers at [ArrayFire](http://arrayfire.com) LLC with [contributions from several individuals](https://github.com/arrayfire/arrayfire_python/graphs/contributors). The developers at ArrayFire LLC have received partial financial support from several grants and institutions. Those that wish to receive public acknowledgement are listed below: ### Grants This material is based upon work supported by the DARPA SBIR Program Office under Contract Numbers W31P4Q-14-C-0012 and W31P4Q-15-C-0008. Any opinions, findings and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the DARPA SBIR Program Office. python-arrayfire-3.3.20160624/__af_version__.py000066400000000000000000000006431276671162200211030ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## version = "3.3" release = "20160624" full_version = version + "." + release python-arrayfire-3.3.20160624/arrayfire/000077500000000000000000000000001276671162200175635ustar00rootroot00000000000000python-arrayfire-3.3.20160624/arrayfire/__init__.py000066400000000000000000000042231276671162200216750ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ ArrayFire is a high performance scientific computing library with an easy to use API. >>> # Monte Carlo estimation of pi >>> def calc_pi_device(samples): # Simple, array based API # Generate uniformly distributed random numers x = af.randu(samples) y = af.randu(samples) # Supports Just In Time Compilation # The following line generates a single kernel within_unit_circle = (x * x + y * y) < 1 # Intuitive function names return 4 * af.count(within_unit_circle) / samples Programs written using ArrayFire are portable across CUDA, OpenCL and CPU devices. The default backend is chosen in the following order of preference based on the available libraries: 1. CUDA 2. OpenCL 3. CPU The backend can be chosen at the beginning of the program by using the following function >>> af.backend.set(name) where name is one of 'cuda', 'opencl' or 'cpu'. The functionality provided by ArrayFire spans the following domains: 1. Vector Algorithms 2. Image Processing 3. Signal Processing 4. Computer Vision 5. Linear Algebra 6. Statistics """ try: import pycuda.autoinit except: pass from .library import * from .array import * from .data import * from .util import * from .algorithm import * from .device import * from .blas import * from .arith import * from .statistics import * from .lapack import * from .signal import * from .image import * from .features import * from .vision import * from .graphics import * from .bcast import * from .index import * from .interop import * from .timer import * # do not export default modules as part of arrayfire del ct del inspect del numbers del os if (AF_NUMPY_FOUND): del np python-arrayfire-3.3.20160624/arrayfire/algorithm.py000066400000000000000000000350551276671162200221330ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Vector algorithms (sum, min, sort, etc). """ from .library import * from .array import * def _parallel_dim(a, dim, c_func): out = Array() safe_call(c_func(ct.pointer(out.arr), a.arr, ct.c_int(dim))) return out def _reduce_all(a, c_func): real = ct.c_double(0) imag = ct.c_double(0) safe_call(c_func(ct.pointer(real), ct.pointer(imag), a.arr)) real = real.value imag = imag.value return real if imag == 0 else real + imag * 1j def _nan_parallel_dim(a, dim, c_func, nan_val): out = Array() safe_call(c_func(ct.pointer(out.arr), a.arr, ct.c_int(dim), ct.c_double(nan_val))) return out def _nan_reduce_all(a, c_func, nan_val): real = ct.c_double(0) imag = ct.c_double(0) safe_call(c_func(ct.pointer(real), ct.pointer(imag), a.arr, ct.c_double(nan_val))) real = real.value imag = imag.value return real if imag == 0 else real + imag * 1j def sum(a, dim=None, nan_val=None): """ Calculate the sum of all the elements along a specified dimension. Parameters ---------- a : af.Array Multi dimensional arrayfire array. dim: optional: int. default: None Dimension along which the sum is required. nan_val: optional: scalar. default: None The value that replaces NaN in the array Returns ------- out: af.Array or scalar number The sum of all elements in `a` along dimension `dim`. If `dim` is `None`, sum of the entire Array is returned. """ if (nan_val is not None): if dim is not None: return _nan_parallel_dim(a, dim, backend.get().af_sum_nan, nan_val) else: return _nan_reduce_all(a, backend.get().af_sum_nan_all, nan_val) else: if dim is not None: return _parallel_dim(a, dim, backend.get().af_sum) else: return _reduce_all(a, backend.get().af_sum_all) def product(a, dim=None, nan_val=None): """ Calculate the product of all the elements along a specified dimension. Parameters ---------- a : af.Array Multi dimensional arrayfire array. dim: optional: int. default: None Dimension along which the product is required. nan_val: optional: scalar. default: None The value that replaces NaN in the array Returns ------- out: af.Array or scalar number The product of all elements in `a` along dimension `dim`. If `dim` is `None`, product of the entire Array is returned. """ if (nan_val is not None): if dim is not None: return _nan_parallel_dim(a, dim, backend.get().af_product_nan, nan_val) else: return _nan_reduce_all(a, backend.get().af_product_nan_all, nan_val) else: if dim is not None: return _parallel_dim(a, dim, backend.get().af_product) else: return _reduce_all(a, backend.get().af_product_all) def min(a, dim=None): """ Find the minimum value of all the elements along a specified dimension. Parameters ---------- a : af.Array Multi dimensional arrayfire array. dim: optional: int. default: None Dimension along which the minimum value is required. Returns ------- out: af.Array or scalar number The minimum value of all elements in `a` along dimension `dim`. If `dim` is `None`, minimum value of the entire Array is returned. """ if dim is not None: return _parallel_dim(a, dim, backend.get().af_min) else: return _reduce_all(a, backend.get().af_min_all) def max(a, dim=None): """ Find the maximum value of all the elements along a specified dimension. Parameters ---------- a : af.Array Multi dimensional arrayfire array. dim: optional: int. default: None Dimension along which the maximum value is required. Returns ------- out: af.Array or scalar number The maximum value of all elements in `a` along dimension `dim`. If `dim` is `None`, maximum value of the entire Array is returned. """ if dim is not None: return _parallel_dim(a, dim, backend.get().af_max) else: return _reduce_all(a, backend.get().af_max_all) def all_true(a, dim=None): """ Check if all the elements along a specified dimension are true. Parameters ---------- a : af.Array Multi dimensional arrayfire array. dim: optional: int. default: None Dimension along which the product is required. Returns ------- out: af.Array or scalar number Af.array containing True if all elements in `a` along the dimension are True. If `dim` is `None`, output is True if `a` does not have any zeros, else False. """ if dim is not None: return _parallel_dim(a, dim, backend.get().af_all_true) else: return _reduce_all(a, backend.get().af_all_true_all) def any_true(a, dim=None): """ Check if any the elements along a specified dimension are true. Parameters ---------- a : af.Array Multi dimensional arrayfire array. dim: optional: int. default: None Dimension along which the product is required. Returns ------- out: af.Array or scalar number Af.array containing True if any elements in `a` along the dimension are True. If `dim` is `None`, output is True if `a` does not have any zeros, else False. """ if dim is not None: return _parallel_dim(a, dim, backend.get().af_any_true) else: return _reduce_all(a, backend.get().af_any_true_all) def count(a, dim=None): """ Count the number of non zero elements in an array along a specified dimension. Parameters ---------- a : af.Array Multi dimensional arrayfire array. dim: optional: int. default: None Dimension along which the the non zero elements are to be counted. Returns ------- out: af.Array or scalar number The count of non zero elements in `a` along `dim`. If `dim` is `None`, the total number of non zero elements in `a`. """ if dim is not None: return _parallel_dim(a, dim, backend.get().af_count) else: return _reduce_all(a, backend.get().af_count_all) def imin(a, dim=None): """ Find the value and location of the minimum value along a specified dimension Parameters ---------- a : af.Array Multi dimensional arrayfire array. dim: optional: int. default: None Dimension along which the minimum value is required. Returns ------- (val, idx): tuple of af.Array or scalars `val` contains the minimum value of `a` along `dim`. `idx` contains the location of where `val` occurs in `a` along `dim`. If `dim` is `None`, `val` and `idx` value and location of global minimum. """ if dim is not None: out = Array() idx = Array() safe_call(backend.get().af_imin(ct.pointer(out.arr), ct.pointer(idx.arr), a.arr, ct.c_int(dim))) return out,idx else: real = ct.c_double(0) imag = ct.c_double(0) idx = ct.c_uint(0) safe_call(backend.get().af_imin_all(ct.pointer(real), ct.pointer(imag), ct.pointer(idx), a.arr)) real = real.value imag = imag.value val = real if imag == 0 else real + imag * 1j return val,idx.value def imax(a, dim=None): """ Find the value and location of the maximum value along a specified dimension Parameters ---------- a : af.Array Multi dimensional arrayfire array. dim: optional: int. default: None Dimension along which the maximum value is required. Returns ------- (val, idx): tuple of af.Array or scalars `val` contains the maximum value of `a` along `dim`. `idx` contains the location of where `val` occurs in `a` along `dim`. If `dim` is `None`, `val` and `idx` value and location of global maximum. """ if dim is not None: out = Array() idx = Array() safe_call(backend.get().af_imax(ct.pointer(out.arr), ct.pointer(idx.arr), a.arr, ct.c_int(dim))) return out,idx else: real = ct.c_double(0) imag = ct.c_double(0) idx = ct.c_uint(0) safe_call(backend.get().af_imax_all(ct.pointer(real), ct.pointer(imag), ct.pointer(idx), a.arr)) real = real.value imag = imag.value val = real if imag == 0 else real + imag * 1j return val,idx.value def accum(a, dim=0): """ Cumulative sum of an array along a specified dimension Parameters ---------- a : af.Array Multi dimensional arrayfire array. dim: optional: int. default: 0 Dimension along which the cumulative sum is required. Returns ------- out: af.Array array of same size as `a` containing the cumulative sum along `dim`. """ return _parallel_dim(a, dim, backend.get().af_accum) def where(a): """ Find the indices of non zero elements Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns ------- idx: af.Array Linear indices for non zero elements. """ out = Array() safe_call(backend.get().af_where(ct.pointer(out.arr), a.arr)) return out def diff1(a, dim=0): """ Find the first order differences along specified dimensions Parameters ---------- a : af.Array Multi dimensional arrayfire array. dim: optional: int. default: 0 Dimension along which the differences are required. Returns ------- out: af.Array Array whose length along `dim` is 1 less than that of `a`. """ return _parallel_dim(a, dim, backend.get().af_diff1) def diff2(a, dim=0): """ Find the second order differences along specified dimensions Parameters ---------- a : af.Array Multi dimensional arrayfire array. dim: optional: int. default: 0 Dimension along which the differences are required. Returns ------- out: af.Array Array whose length along `dim` is 2 less than that of `a`. """ return _parallel_dim(a, dim, backend.get().af_diff2) def sort(a, dim=0, is_ascending=True): """ Sort the array along a specified dimension Parameters ---------- a : af.Array Multi dimensional arrayfire array. dim: optional: int. default: 0 Dimension along which sort is to be performed. is_ascending: optional: bool. default: True Specifies the direction of the sort Returns ------- out: af.Array array containing the sorted values Note ------- Currently `dim` is only supported for 0. """ out = Array() safe_call(backend.get().af_sort(ct.pointer(out.arr), a.arr, ct.c_uint(dim), ct.c_bool(is_ascending))) return out def sort_index(a, dim=0, is_ascending=True): """ Sort the array along a specified dimension and get the indices. Parameters ---------- a : af.Array Multi dimensional arrayfire array. dim: optional: int. default: 0 Dimension along which sort is to be performed. is_ascending: optional: bool. default: True Specifies the direction of the sort Returns ------- (val, idx): tuple of af.Array `val` is an af.Array containing the sorted values. `idx` is an af.Array containing the original indices of `val` in `a`. Note ------- Currently `dim` is only supported for 0. """ out = Array() idx = Array() safe_call(backend.get().af_sort_index(ct.pointer(out.arr), ct.pointer(idx.arr), a.arr, ct.c_uint(dim), ct.c_bool(is_ascending))) return out,idx def sort_by_key(iv, ik, dim=0, is_ascending=True): """ Sort an array based on specified keys Parameters ---------- iv : af.Array An Array containing the values ik : af.Array An Array containing the keys dim: optional: int. default: 0 Dimension along which sort is to be performed. is_ascending: optional: bool. default: True Specifies the direction of the sort Returns ------- (ov, ok): tuple of af.Array `ov` contains the values from `iv` after sorting them based on `ik` `ok` contains the values from `ik` in sorted order Note ------- Currently `dim` is only supported for 0. """ ov = Array() ok = Array() safe_call(backend.get().af_sort_by_key(ct.pointer(ov.arr), ct.pointer(ok.arr), iv.arr, ik.arr, ct.c_uint(dim), ct.c_bool(is_ascending))) return ov,ok def set_unique(a, is_sorted=False): """ Find the unique elements of an array. Parameters ---------- a : af.Array A 1D arrayfire array. is_sorted: optional: bool. default: False Specifies if the input is pre-sorted. Returns ------- out: af.Array an array containing the unique values from `a` """ out = Array() safe_call(backend.get().af_set_unique(ct.pointer(out.arr), a.arr, ct.c_bool(is_sorted))) return out def set_union(a, b, is_unique=False): """ Find the union of two arrays. Parameters ---------- a : af.Array A 1D arrayfire array. b : af.Array A 1D arrayfire array. is_unique: optional: bool. default: False Specifies if the both inputs contain unique elements. Returns ------- out: af.Array an array values after performing the union of `a` and `b`. """ out = Array() safe_call(backend.get().af_set_union(ct.pointer(out.arr), a.arr, b.arr, ct.c_bool(is_unique))) return out def set_intersect(a, b, is_unique=False): """ Find the intersect of two arrays. Parameters ---------- a : af.Array A 1D arrayfire array. b : af.Array A 1D arrayfire array. is_unique: optional: bool. default: False Specifies if the both inputs contain unique elements. Returns ------- out: af.Array an array values after performing the intersect of `a` and `b`. """ out = Array() safe_call(backend.get().af_set_intersect(ct.pointer(out.arr), a.arr, b.arr, ct.c_bool(is_unique))) return out python-arrayfire-3.3.20160624/arrayfire/arith.py000066400000000000000000000551031276671162200212500ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Math functions (sin, sqrt, exp, etc). """ from .library import * from .array import * from .bcast import _bcast_var from .util import _is_number def _arith_binary_func(lhs, rhs, c_func): out = Array() is_left_array = isinstance(lhs, Array) is_right_array = isinstance(rhs, Array) if not (is_left_array or is_right_array): raise TypeError("Atleast one input needs to be of type arrayfire.array") elif (is_left_array and is_right_array): safe_call(c_func(ct.pointer(out.arr), lhs.arr, rhs.arr, _bcast_var.get())) elif (_is_number(rhs)): ldims = dim4_to_tuple(lhs.dims()) rty = implicit_dtype(rhs, lhs.type()) other = Array() other.arr = constant_array(rhs, ldims[0], ldims[1], ldims[2], ldims[3], rty) safe_call(c_func(ct.pointer(out.arr), lhs.arr, other.arr, _bcast_var.get())) else: rdims = dim4_to_tuple(rhs.dims()) lty = implicit_dtype(lhs, rhs.type()) other = Array() other.arr = constant_array(lhs, rdims[0], rdims[1], rdims[2], rdims[3], lty) safe_call(c_func(ct.pointer(out.arr), other.arr, rhs.arr, _bcast_var.get())) return out def _arith_unary_func(a, c_func): out = Array() safe_call(c_func(ct.pointer(out.arr), a.arr)) return out def cast(a, dtype): """ Cast an array to a specified type Parameters ---------- a : af.Array Multi dimensional arrayfire array. dtype: af.Dtype Must be one of the following: - Dtype.f32 for float - Dtype.f64 for double - Dtype.b8 for bool - Dtype.u8 for unsigned char - Dtype.s32 for signed 32 bit integer - Dtype.u32 for unsigned 32 bit integer - Dtype.s64 for signed 64 bit integer - Dtype.u64 for unsigned 64 bit integer - Dtype.c32 for 32 bit complex number - Dtype.c64 for 64 bit complex number Returns -------- out : af.Array array containing the values from `a` after converting to `dtype`. """ out=Array() safe_call(backend.get().af_cast(ct.pointer(out.arr), a.arr, dtype.value)) return out def minof(lhs, rhs): """ Find the minimum value of two inputs at each location. Parameters ---------- lhs : af.Array or scalar Multi dimensional arrayfire array or a scalar number. rhs : af.Array or scalar Multi dimensional arrayfire array or a scalar number. Returns -------- out : af.Array array containing the minimum value at each location of the inputs. Note ------- - Atleast one of `lhs` and `rhs` needs to be af.Array. - If `lhs` and `rhs` are both af.Array, they must be of same size. """ return _arith_binary_func(lhs, rhs, backend.get().af_minof) def maxof(lhs, rhs): """ Find the maximum value of two inputs at each location. Parameters ---------- lhs : af.Array or scalar Multi dimensional arrayfire array or a scalar number. rhs : af.Array or scalar Multi dimensional arrayfire array or a scalar number. Returns -------- out : af.Array array containing the maximum value at each location of the inputs. Note ------- - Atleast one of `lhs` and `rhs` needs to be af.Array. - If `lhs` and `rhs` are both af.Array, they must be of same size. """ return _arith_binary_func(lhs, rhs, backend.get().af_maxof) def rem(lhs, rhs): """ Find the remainder. Parameters ---------- lhs : af.Array or scalar Multi dimensional arrayfire array or a scalar number. rhs : af.Array or scalar Multi dimensional arrayfire array or a scalar number. Returns -------- out : af.Array Contains the remainders after dividing each value of lhs` with those in `rhs`. Note ------- - Atleast one of `lhs` and `rhs` needs to be af.Array. - If `lhs` and `rhs` are both af.Array, they must be of same size. """ return _arith_binary_func(lhs, rhs, backend.get().af_rem) def abs(a): """ Find the absolute values. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array Contains the absolute values of the inputs. """ return _arith_unary_func(a, backend.get().af_abs) def arg(a): """ Find the theta value of the inputs in polar co-ordinates. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array Contains the theta values. """ return _arith_unary_func(a, backend.get().af_arg) def sign(a): """ Find the sign of the inputs. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing -1 for negative values, 1 otherwise. """ return _arith_unary_func(a, backend.get().af_sign) def round(a): """ Round the values to nearest integer. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the values rounded to nearest integer. """ return _arith_unary_func(a, backend.get().af_round) def trunc(a): """ Round the values towards zero. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the truncated values. """ return _arith_unary_func(a, backend.get().af_trunc) def floor(a): """ Round the values towards a smaller integer. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the floored values. """ return _arith_unary_func(a, backend.get().af_floor) def ceil(a): """ Round the values towards a bigger integer. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the ceiled values. """ return _arith_unary_func(a, backend.get().af_ceil) def hypot(lhs, rhs): """ Find the value of the hypotunese. Parameters ---------- lhs : af.Array or scalar Multi dimensional arrayfire array or a scalar number. rhs : af.Array or scalar Multi dimensional arrayfire array or a scalar number. Returns -------- out : af.Array Contains the value of `sqrt(lhs**2, rhs**2)`. Note ------- - Atleast one of `lhs` and `rhs` needs to be af.Array. - If `lhs` and `rhs` are both af.Array, they must be of same size. """ return _arith_binary_func(lhs, rhs, backend.get().af_hypot) def sin(a): """ Sine of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the sine of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_sin) def cos(a): """ Cosine of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the cosine of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_cos) def tan(a): """ Tangent of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the tangent of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_tan) def asin(a): """ Arc Sine of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the arc sine of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_asin) def acos(a): """ Arc Cosine of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the arc cosine of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_acos) def atan(a): """ Arc Tangent of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the arc tangent of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_atan) def atan2(lhs, rhs): """ Find the arc tan using two values. Parameters ---------- lhs : af.Array or scalar Multi dimensional arrayfire array or a scalar number. rhs : af.Array or scalar Multi dimensional arrayfire array or a scalar number. Returns -------- out : af.Array Contains the value arc tan values where: - `lhs` contains the sine values. - `rhs` contains the cosine values. Note ------- - Atleast one of `lhs` and `rhs` needs to be af.Array. - If `lhs` and `rhs` are both af.Array, they must be of same size. """ return _arith_binary_func(lhs, rhs, backend.get().af_atan2) def cplx(lhs, rhs=None): """ Create a complex array from real inputs. Parameters ---------- lhs : af.Array or scalar Multi dimensional arrayfire array or a scalar number. rhs : optional: af.Array or scalar. default: None. Multi dimensional arrayfire array or a scalar number. Returns -------- out : af.Array Contains complex values whose - real values contain values from `lhs` - imaginary values contain values from `rhs` (0 if `rhs` is None) Note ------- - Atleast one of `lhs` and `rhs` needs to be af.Array. - If `lhs` and `rhs` are both af.Array, they must be of same size. """ if rhs is None: return _arith_unary_func(lhs, backend.get().af_cplx) else: return _arith_binary_func(lhs, rhs, backend.get().af_cplx2) def real(a): """ Find the real values of the input. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the real values from `a`. """ return _arith_unary_func(a, backend.get().af_real) def imag(a): """ Find the imaginary values of the input. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the imaginary values from `a`. """ return _arith_unary_func(a, backend.get().af_imag) def conjg(a): """ Find the complex conjugate values of the input. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing copmplex conjugate values from `a`. """ return _arith_unary_func(a, backend.get().af_conjg) def sinh(a): """ Hyperbolic Sine of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the hyperbolic sine of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_sinh) def cosh(a): """ Hyperbolic Cosine of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the hyperbolic cosine of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_cosh) def tanh(a): """ Hyperbolic Tangent of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the hyperbolic tangent of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_tanh) def asinh(a): """ Arc Hyperbolic Sine of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the arc hyperbolic sine of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_asinh) def acosh(a): """ Arc Hyperbolic Cosine of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the arc hyperbolic cosine of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_acosh) def atanh(a): """ Arc Hyperbolic Tangent of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the arc hyperbolic tangent of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_atanh) def root(lhs, rhs): """ Find the root values of two inputs at each location. Parameters ---------- lhs : af.Array or scalar Multi dimensional arrayfire array or a scalar number. rhs : af.Array or scalar Multi dimensional arrayfire array or a scalar number. Returns -------- out : af.Array array containing the value of `lhs ** (1/rhs)` Note ------- - Atleast one of `lhs` and `rhs` needs to be af.Array. - If `lhs` and `rhs` are both af.Array, they must be of same size. """ return _arith_binary_func(lhs, rhs, backend.get().af_root) def pow(lhs, rhs): """ Find the power of two inputs at each location. Parameters ---------- lhs : af.Array or scalar Multi dimensional arrayfire array or a scalar number. rhs : af.Array or scalar Multi dimensional arrayfire array or a scalar number. Returns -------- out : af.Array array containing the value of `lhs ** (rhs)` Note ------- - Atleast one of `lhs` and `rhs` needs to be af.Array. - If `lhs` and `rhs` are both af.Array, they must be of same size. """ return _arith_binary_func(lhs, rhs, backend.get().af_pow) def pow2(a): """ Raise 2 to the power of each element in input. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array where each element is 2 raised to power of the corresponding value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_pow2) def sigmoid(a): """ Raise 2 to the power of each element in input. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array where each element is outout of a sigmoid function for the corresponding value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_sigmoid) def exp(a): """ Exponential of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the exponential of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_exp) def expm1(a): """ Exponential of each element in the array minus 1. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the exponential of each value from `a`. Note ------- - `a` must not be complex. - This function provides a more stable result for small values of `a`. """ return _arith_unary_func(a, backend.get().af_expm1) def erf(a): """ Error function of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the error function of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_erf) def erfc(a): """ Complementary error function of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the complementary error function of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_erfc) def log(a): """ Natural logarithm of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the natural logarithm of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_log) def log1p(a): """ Logarithm of each element in the array plus 1. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the the values of `log(a) + 1` Note ------- - `a` must not be complex. - This function provides a more stable result for small values of `a`. """ return _arith_unary_func(a, backend.get().af_log1p) def log10(a): """ Logarithm base 10 of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the logarithm base 10 of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_log10) def log2(a): """ Logarithm base 2 of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the logarithm base 2 of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_log2) def sqrt(a): """ Square root of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the square root of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_sqrt) def cbrt(a): """ Cube root of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the cube root of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_cbrt) def factorial(a): """ factorial of each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the factorial of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_factorial) def tgamma(a): """ Performs the gamma function for each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the output of gamma function of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_tgamma) def lgamma(a): """ Performs the logarithm of gamma function for each element in the array. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the output of logarithm of gamma function of each value from `a`. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_lgamma) def iszero(a): """ Check if each element of the input is zero. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the output after checking if each value of `a` is 0. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_iszero) def isinf(a): """ Check if each element of the input is infinity. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the output after checking if each value of `a` is inifnite. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_isinf) def isnan(a): """ Check if each element of the input is NaN. Parameters ---------- a : af.Array Multi dimensional arrayfire array. Returns -------- out : af.Array array containing the output after checking if each value of `a` is NaN. Note ------- `a` must not be complex. """ return _arith_unary_func(a, backend.get().af_isnan) python-arrayfire-3.3.20160624/arrayfire/array.py000066400000000000000000001117521276671162200212620ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Array class and helper functions. """ import inspect from .library import * from .util import * from .util import _is_number from .bcast import _bcast_var from .base import * from .index import * from .index import _Index4 def _create_array(buf, numdims, idims, dtype, is_device): out_arr = ct.c_void_p(0) c_dims = dim4(idims[0], idims[1], idims[2], idims[3]) if (not is_device): safe_call(backend.get().af_create_array(ct.pointer(out_arr), ct.c_void_p(buf), numdims, ct.pointer(c_dims), dtype.value)) else: safe_call(backend.get().af_device_array(ct.pointer(out_arr), ct.c_void_p(buf), numdims, ct.pointer(c_dims), dtype.value)) return out_arr def _create_strided_array(buf, numdims, idims, dtype, is_device, offset, strides): out_arr = ct.c_void_p(0) c_dims = dim4(idims[0], idims[1], idims[2], idims[3]) if offset is None: offset = 0 offset = c_dim_t(offset) if strides is None: strides = (1, idims[0], idims[0]*idims[1], idims[0]*idims[1]*idims[2]) while len(strides) < 4: strides = strides + (strides[-1],) strides = dim4(strides[0], strides[1], strides[2], strides[3]) if is_device: location = Source.device else: location = Source.host safe_call(backend.get().af_create_strided_array(ct.pointer(out_arr), ct.c_void_p(buf), offset, numdims, ct.pointer(c_dims), ct.pointer(strides), dtype.value, location.value)) return out_arr def _create_empty_array(numdims, idims, dtype): out_arr = ct.c_void_p(0) c_dims = dim4(idims[0], idims[1], idims[2], idims[3]) safe_call(backend.get().af_create_handle(ct.pointer(out_arr), numdims, ct.pointer(c_dims), dtype.value)) return out_arr def constant_array(val, d0, d1=None, d2=None, d3=None, dtype=Dtype.f32): """ Internal function to create a C array. Should not be used externall. """ if not isinstance(dtype, ct.c_int): if isinstance(dtype, int): dtype = ct.c_int(dtype) elif isinstance(dtype, Dtype): dtype = ct.c_int(dtype.value) else: raise TypeError("Invalid dtype") out = ct.c_void_p(0) dims = dim4(d0, d1, d2, d3) if isinstance(val, complex): c_real = ct.c_double(val.real) c_imag = ct.c_double(val.imag) if (dtype.value != Dtype.c32.value and dtype.value != Dtype.c64.value): dtype = Dtype.c32.value safe_call(backend.get().af_constant_complex(ct.pointer(out), c_real, c_imag, 4, ct.pointer(dims), dtype)) elif dtype.value == Dtype.s64.value: c_val = ct.c_longlong(val.real) safe_call(backend.get().af_constant_long(ct.pointer(out), c_val, 4, ct.pointer(dims))) elif dtype.value == Dtype.u64.value: c_val = ct.c_ulonglong(val.real) safe_call(backend.get().af_constant_ulong(ct.pointer(out), c_val, 4, ct.pointer(dims))) else: c_val = ct.c_double(val) safe_call(backend.get().af_constant(ct.pointer(out), c_val, 4, ct.pointer(dims), dtype)) return out def _binary_func(lhs, rhs, c_func): out = Array() other = rhs if (_is_number(rhs)): ldims = dim4_to_tuple(lhs.dims()) rty = implicit_dtype(rhs, lhs.type()) other = Array() other.arr = constant_array(rhs, ldims[0], ldims[1], ldims[2], ldims[3], rty.value) elif not isinstance(rhs, Array): raise TypeError("Invalid parameter to binary function") safe_call(c_func(ct.pointer(out.arr), lhs.arr, other.arr, _bcast_var.get())) return out def _binary_funcr(lhs, rhs, c_func): out = Array() other = lhs if (_is_number(lhs)): rdims = dim4_to_tuple(rhs.dims()) lty = implicit_dtype(lhs, rhs.type()) other = Array() other.arr = constant_array(lhs, rdims[0], rdims[1], rdims[2], rdims[3], lty.value) elif not isinstance(lhs, Array): raise TypeError("Invalid parameter to binary function") c_func(ct.pointer(out.arr), other.arr, rhs.arr, _bcast_var.get()) return out def _ctype_to_lists(ctype_arr, dim, shape, offset=0): if (dim == 0): return list(ctype_arr[offset : offset + shape[0]]) else: dim_len = shape[dim] res = [[]] * dim_len for n in range(dim_len): res[n] = _ctype_to_lists(ctype_arr, dim - 1, shape, offset) offset += shape[0] return res def _slice_to_length(key, dim): tkey = [key.start, key.stop, key.step] if tkey[0] is None: tkey[0] = 0 elif tkey[0] < 0: tkey[0] = dim - tkey[0] if tkey[1] is None: tkey[1] = dim elif tkey[1] < 0: tkey[1] = dim - tkey[1] if tkey[2] is None: tkey[2] = 1 return int(((tkey[1] - tkey[0] - 1) / tkey[2]) + 1) def _get_info(dims, buf_len): elements = 1 numdims = len(dims) idims = [1]*4 for i in range(numdims): elements *= dims[i] idims[i] = dims[i] if (elements == 0): if (buf_len != 0): idims = [buf_len, 1, 1, 1] numdims = 1 else: raise RuntimeError("Invalid size") return numdims, idims def _get_indices(key): S = Index(slice(None)) inds = _Index4(S, S, S, S) if isinstance(key, tuple): n_idx = len(key) for n in range(n_idx): inds[n] = Index(key[n]) else: inds[0] = Index(key) return inds def _get_assign_dims(key, idims): dims = [1]*4 for n in range(len(idims)): dims[n] = idims[n] if _is_number(key): dims[0] = 1 return dims elif isinstance(key, slice): dims[0] = _slice_to_length(key, idims[0]) return dims elif isinstance(key, ParallelRange): dims[0] = _slice_to_length(key.S, idims[0]) return dims elif isinstance(key, BaseArray): # If the array is boolean take only the number of nonzeros if(key.dtype() is Dtype.b8): dims[0] = int(sum(key)) else: dims[0] = key.elements() return dims elif isinstance(key, tuple): n_inds = len(key) for n in range(n_inds): if (_is_number(key[n])): dims[n] = 1 elif (isinstance(key[n], BaseArray)): # If the array is boolean take only the number of nonzeros if(key[n].dtype() is Dtype.b8): dims[n] = int(sum(key[n])) else: dims[n] = key[n].elements() elif (isinstance(key[n], slice)): dims[n] = _slice_to_length(key[n], idims[n]) elif (isinstance(key[n], ParallelRange)): dims[n] = _slice_to_length(key[n].S, idims[n]) else: raise IndexError("Invalid type while assigning to arrayfire.array") return dims else: raise IndexError("Invalid type while assigning to arrayfire.array") def transpose(a, conj=False): """ Perform the transpose on an input. Parameters ----------- a : af.Array Multi dimensional arrayfire array. conj : optional: bool. default: False. Flag to specify if a complex conjugate needs to applied for complex inputs. Returns -------- out : af.Array Containing the tranpose of `a` for all batches. """ out = Array() safe_call(backend.get().af_transpose(ct.pointer(out.arr), a.arr, conj)) return out def transpose_inplace(a, conj=False): """ Perform inplace transpose on an input. Parameters ----------- a : af.Array - Multi dimensional arrayfire array. - Contains transposed values on exit. conj : optional: bool. default: False. Flag to specify if a complex conjugate needs to applied for complex inputs. Note ------- Input `a` needs to be a square matrix or a batch of square matrices. """ safe_call(backend.get().af_transpose_inplace(a.arr, conj)) class Array(BaseArray): """ A multi dimensional array container. Parameters ---------- src : optional: array.array, list or C buffer. default: None. - When `src` is `array.array` or `list`, the data is copied to create the Array() - When `src` is None, an empty buffer is created. dims : optional: tuple of ints. default: (0,) - When using the default values of `dims`, the dims are caclulated as `len(src)` dtype: optional: str or arrayfire.Dtype. default: None. - if str, must be one of the following: - 'f' for float - 'd' for double - 'b' for bool - 'B' for unsigned char - 'h' for signed 16 bit integer - 'H' for unsigned 16 bit integer - 'i' for signed 32 bit integer - 'I' for unsigned 32 bit integer - 'l' for signed 64 bit integer - 'L' for unsigned 64 bit integer - 'F' for 32 bit complex number - 'D' for 64 bit complex number - if arrayfire.Dtype, must be one of the following: - Dtype.f32 for float - Dtype.f64 for double - Dtype.b8 for bool - Dtype.u8 for unsigned char - Dtype.s16 for signed 16 bit integer - Dtype.u16 for unsigned 16 bit integer - Dtype.s32 for signed 32 bit integer - Dtype.u32 for unsigned 32 bit integer - Dtype.s64 for signed 64 bit integer - Dtype.u64 for unsigned 64 bit integer - Dtype.c32 for 32 bit complex number - Dtype.c64 for 64 bit complex number - if None, Dtype.f32 is assumed Attributes ----------- arr: ctypes.c_void_p ctypes variable containing af_array from arrayfire library. Examples -------- Creating an af.Array() from array.array() >>> import arrayfire as af >>> import array >>> a = array.array('f', (1, 2, 3, 4)) >>> b = af.Array(a, (2,2)) >>> af.display(b) [2 2 1 1] 1.0000 3.0000 2.0000 4.0000 Creating an af.Array() from a list >>> import arrayfire as af >>> import array >>> a = [1, 2, 3, 4] >>> b = af.Array(a) >>> af.display(b) [4 1 1 1] 1.0000 2.0000 3.0000 4.0000 Creating an af.Array() from numpy.array() >>> import numpy as np >>> import arrayfire as af >>> a = np.random.random((2,2)) >>> a array([[ 0.33042524, 0.36135449], [ 0.86748649, 0.42199135]]) >>> b = af.Array(a.ctypes.data, a.shape, a.dtype.char) >>> af.display(b) [2 2 1 1] 0.3304 0.8675 0.3614 0.4220 Note ----- - The class is currently limited to 4 dimensions. - arrayfire.Array() uses column major format. - numpy uses row major format by default which can cause issues during conversion """ # Numpy checks this attribute to know which class handles binary builtin operations, such as __add__. # Setting to such a high value should make sure that arrayfire has priority over # other classes, ensuring that e.g. numpy.float32(1)*arrayfire.randu(3) is handled by # arrayfire's __radd__() instead of numpy's __add__() __array_priority__ = 30 def __init__(self, src=None, dims=(0,), dtype=None, is_device=False, offset=None, strides=None): super(Array, self).__init__() buf=None buf_len=0 if dtype is not None: if isinstance(dtype, str): type_char = dtype else: type_char = to_typecode[dtype.value] else: type_char = None _type_char='f' if src is not None: if (isinstance(src, Array)): safe_call(backend.get().af_retain_array(ct.pointer(self.arr), src.arr)) return host = __import__("array") if isinstance(src, host.array): buf,buf_len = src.buffer_info() _type_char = src.typecode numdims, idims = _get_info(dims, buf_len) elif isinstance(src, list): tmp = host.array('f', src) buf,buf_len = tmp.buffer_info() _type_char = tmp.typecode numdims, idims = _get_info(dims, buf_len) elif isinstance(src, int) or isinstance(src, ct.c_void_p): buf = src if not isinstance(src, ct.c_void_p) else src.value numdims, idims = _get_info(dims, buf_len) elements = 1 for dim in idims: elements *= dim if (elements == 0): raise RuntimeError("Expected dims when src is data pointer") if (type_char is None): raise TypeError("Expected type_char when src is data pointer") _type_char = type_char else: raise TypeError("src is an object of unsupported class") if (type_char is not None and type_char != _type_char): raise TypeError("Can not create array of requested type from input data type") if(offset is None and strides is None): self.arr = _create_array(buf, numdims, idims, to_dtype[_type_char], is_device) else: self.arr = _create_strided_array(buf, numdims, idims, to_dtype[_type_char], is_device, offset, strides) else: if type_char is None: type_char = 'f' numdims = len(dims) idims = [1] * 4 for n in range(numdims): idims[n] = dims[n] self.arr = _create_empty_array(numdims, idims, to_dtype[type_char]) def as_type(self, ty): """ Cast current array to a specified data type Parameters ---------- ty : Return data type """ return cast(self, ty) def copy(self): """ Performs a deep copy of the array. Returns ------- out: af.Array() An identical copy of self. """ out = Array() safe_call(backend.get().af_copy_array(ct.pointer(out.arr), self.arr)) return out def __del__(self): """ Release the C array when going out of scope """ if self.arr.value: backend.get().af_release_array(self.arr) self.arr.value = 0 def device_ptr(self): """ Return the device pointer exclusively held by the array. Returns -------- ptr : int Contains location of the device pointer Note ---- - This can be used to integrate with custom C code and / or PyCUDA or PyOpenCL. - No other arrays will share the same device pointer. - A copy of the memory is done if multiple arrays share the same memory or the array is not the owner of the memory. - In case of a copy the return value points to the newly allocated memory which is now exclusively owned by the array. """ ptr = ct.c_void_p(0) backend.get().af_get_device_ptr(ct.pointer(ptr), self.arr) return ptr.value def raw_ptr(self): """ Return the device pointer held by the array. Returns -------- ptr : int Contains location of the device pointer Note ---- - This can be used to integrate with custom C code and / or PyCUDA or PyOpenCL. - No mem copy is peformed, this function returns the raw device pointer. - This pointer may be shared with other arrays. Use this function with caution. - In particular the JIT compiler will not be aware of the shared arrays. - This results in JITed operations not being immediately visible through the other array. """ ptr = ct.c_void_p(0) backend.get().af_get_raw_ptr(ct.pointer(ptr), self.arr) return ptr.value def offset(self): """ Return the offset, of the first element relative to the raw pointer. Returns -------- offset : int The offset in number of elements """ offset = c_dim_t(0) safe_call(backend.get().af_get_offset(ct.pointer(offset), self.arr)) return offset.value def strides(self): """ Return the distance in bytes between consecutive elements for each dimension. Returns -------- strides : tuple The strides for each dimension """ s0 = c_dim_t(0) s1 = c_dim_t(0) s2 = c_dim_t(0) s3 = c_dim_t(0) safe_call(backend.get().af_get_strides(ct.pointer(s0), ct.pointer(s1), ct.pointer(s2), ct.pointer(s3), self.arr)) strides = (s0.value,s1.value,s2.value,s3.value) return strides[:self.numdims()] def elements(self): """ Return the number of elements in the array. """ num = c_dim_t(0) safe_call(backend.get().af_get_elements(ct.pointer(num), self.arr)) return num.value def dtype(self): """ Return the data type as a arrayfire.Dtype enum value. """ dty = ct.c_int(Dtype.f32.value) safe_call(backend.get().af_get_type(ct.pointer(dty), self.arr)) return to_dtype[to_typecode[dty.value]] def type(self): """ Return the data type as an int. """ return self.dtype().value @property def T(self): """ Return the transpose of the array """ return transpose(self, False) @property def H(self): """ Return the hermitian transpose of the array """ return transpose(self, False) def dims(self): """ Return the shape of the array as a tuple. """ d0 = c_dim_t(0) d1 = c_dim_t(0) d2 = c_dim_t(0) d3 = c_dim_t(0) safe_call(backend.get().af_get_dims(ct.pointer(d0), ct.pointer(d1), ct.pointer(d2), ct.pointer(d3), self.arr)) dims = (d0.value,d1.value,d2.value,d3.value) return dims[:self.numdims()] @property def shape(self): """ The shape of the array """ return self.dims() def numdims(self): """ Return the number of dimensions of the array. """ nd = ct.c_uint(0) safe_call(backend.get().af_get_numdims(ct.pointer(nd), self.arr)) return nd.value def is_empty(self): """ Check if the array is empty i.e. it has no elements. """ res = ct.c_bool(False) safe_call(backend.get().af_is_empty(ct.pointer(res), self.arr)) return res.value def is_scalar(self): """ Check if the array is scalar i.e. it has only one element. """ res = ct.c_bool(False) safe_call(backend.get().af_is_scalar(ct.pointer(res), self.arr)) return res.value def is_row(self): """ Check if the array is a row i.e. it has a shape of (1, cols). """ res = ct.c_bool(False) safe_call(backend.get().af_is_row(ct.pointer(res), self.arr)) return res.value def is_column(self): """ Check if the array is a column i.e. it has a shape of (rows, 1). """ res = ct.c_bool(False) safe_call(backend.get().af_is_column(ct.pointer(res), self.arr)) return res.value def is_vector(self): """ Check if the array is a vector i.e. it has a shape of one of the following: - (rows, 1) - (1, cols) - (1, 1, vols) - (1, 1, 1, batch) """ res = ct.c_bool(False) safe_call(backend.get().af_is_vector(ct.pointer(res), self.arr)) return res.value def is_complex(self): """ Check if the array is of complex type. """ res = ct.c_bool(False) safe_call(backend.get().af_is_complex(ct.pointer(res), self.arr)) return res.value def is_real(self): """ Check if the array is not of complex type. """ res = ct.c_bool(False) safe_call(backend.get().af_is_real(ct.pointer(res), self.arr)) return res.value def is_double(self): """ Check if the array is of double precision floating point type. """ res = ct.c_bool(False) safe_call(backend.get().af_is_double(ct.pointer(res), self.arr)) return res.value def is_single(self): """ Check if the array is of single precision floating point type. """ res = ct.c_bool(False) safe_call(backend.get().af_is_single(ct.pointer(res), self.arr)) return res.value def is_real_floating(self): """ Check if the array is real and of floating point type. """ res = ct.c_bool(False) safe_call(backend.get().af_is_realfloating(ct.pointer(res), self.arr)) return res.value def is_floating(self): """ Check if the array is of floating point type. """ res = ct.c_bool(False) safe_call(backend.get().af_is_floating(ct.pointer(res), self.arr)) return res.value def is_integer(self): """ Check if the array is of integer type. """ res = ct.c_bool(False) safe_call(backend.get().af_is_integer(ct.pointer(res), self.arr)) return res.value def is_bool(self): """ Check if the array is of type b8. """ res = ct.c_bool(False) safe_call(backend.get().af_is_bool(ct.pointer(res), self.arr)) return res.value def is_linear(self): """ Check if all elements of the array are contiguous. """ res = ct.c_bool(False) safe_call(backend.get().af_is_linear(ct.pointer(res), self.arr)) return res.value def is_owner(self): """ Check if the array owns the raw pointer or is a derived array. """ res = ct.c_bool(False) safe_call(backend.get().af_is_owner(ct.pointer(res), self.arr)) return res.value def __add__(self, other): """ Return self + other. """ return _binary_func(self, other, backend.get().af_add) def __iadd__(self, other): """ Perform self += other. """ self = _binary_func(self, other, backend.get().af_add) return self def __radd__(self, other): """ Return other + self. """ return _binary_funcr(other, self, backend.get().af_add) def __sub__(self, other): """ Return self - other. """ return _binary_func(self, other, backend.get().af_sub) def __isub__(self, other): """ Perform self -= other. """ self = _binary_func(self, other, backend.get().af_sub) return self def __rsub__(self, other): """ Return other - self. """ return _binary_funcr(other, self, backend.get().af_sub) def __mul__(self, other): """ Return self * other. """ return _binary_func(self, other, backend.get().af_mul) def __imul__(self, other): """ Perform self *= other. """ self = _binary_func(self, other, backend.get().af_mul) return self def __rmul__(self, other): """ Return other * self. """ return _binary_funcr(other, self, backend.get().af_mul) def __truediv__(self, other): """ Return self / other. """ return _binary_func(self, other, backend.get().af_div) def __itruediv__(self, other): """ Perform self /= other. """ self = _binary_func(self, other, backend.get().af_div) return self def __rtruediv__(self, other): """ Return other / self. """ return _binary_funcr(other, self, backend.get().af_div) def __div__(self, other): """ Return self / other. """ return _binary_func(self, other, backend.get().af_div) def __idiv__(self, other): """ Perform other / self. """ self = _binary_func(self, other, backend.get().af_div) return self def __rdiv__(self, other): """ Return other / self. """ return _binary_funcr(other, self, backend.get().af_div) def __mod__(self, other): """ Return self % other. """ return _binary_func(self, other, backend.get().af_mod) def __imod__(self, other): """ Perform self %= other. """ self = _binary_func(self, other, backend.get().af_mod) return self def __rmod__(self, other): """ Return other % self. """ return _binary_funcr(other, self, backend.get().af_mod) def __pow__(self, other): """ Return self ** other. """ return _binary_func(self, other, backend.get().af_pow) def __ipow__(self, other): """ Perform self **= other. """ self = _binary_func(self, other, backend.get().af_pow) return self def __rpow__(self, other): """ Return other ** self. """ return _binary_funcr(other, self, backend.get().af_pow) def __lt__(self, other): """ Return self < other. """ return _binary_func(self, other, backend.get().af_lt) def __gt__(self, other): """ Return self > other. """ return _binary_func(self, other, backend.get().af_gt) def __le__(self, other): """ Return self <= other. """ return _binary_func(self, other, backend.get().af_le) def __ge__(self, other): """ Return self >= other. """ return _binary_func(self, other, backend.get().af_ge) def __eq__(self, other): """ Return self == other. """ return _binary_func(self, other, backend.get().af_eq) def __ne__(self, other): """ Return self != other. """ return _binary_func(self, other, backend.get().af_neq) def __and__(self, other): """ Return self & other. """ return _binary_func(self, other, backend.get().af_bitand) def __iand__(self, other): """ Perform self &= other. """ self = _binary_func(self, other, backend.get().af_bitand) return self def __or__(self, other): """ Return self | other. """ return _binary_func(self, other, backend.get().af_bitor) def __ior__(self, other): """ Perform self |= other. """ self = _binary_func(self, other, backend.get().af_bitor) return self def __xor__(self, other): """ Return self ^ other. """ return _binary_func(self, other, backend.get().af_bitxor) def __ixor__(self, other): """ Perform self ^= other. """ self = _binary_func(self, other, backend.get().af_bitxor) return self def __lshift__(self, other): """ Return self << other. """ return _binary_func(self, other, backend.get().af_bitshiftl) def __ilshift__(self, other): """ Perform self <<= other. """ self = _binary_func(self, other, backend.get().af_bitshiftl) return self def __rshift__(self, other): """ Return self >> other. """ return _binary_func(self, other, backend.get().af_bitshiftr) def __irshift__(self, other): """ Perform self >>= other. """ self = _binary_func(self, other, backend.get().af_bitshiftr) return self def __neg__(self): """ Return -self """ return 0 - self def __pos__(self): """ Return +self """ return self def __invert__(self): """ Return ~self """ return self == 0 def __nonzero__(self): return self != 0 # TODO: # def __abs__(self): # return self def __getitem__(self, key): """ Return self[key] Note ---- Ellipsis not supported as key """ try: out = Array() n_dims = self.numdims() if (isinstance(key, Array) and key.type() == Dtype.b8.value): n_dims = 1 if (count(key) == 0): return out inds = _get_indices(key) safe_call(backend.get().af_index_gen(ct.pointer(out.arr), self.arr, c_dim_t(n_dims), inds.pointer)) return out except RuntimeError as e: raise IndexError(str(e)) def __setitem__(self, key, val): """ Perform self[key] = val Note ---- Ellipsis not supported as key """ try: n_dims = self.numdims() is_boolean_idx = isinstance(key, Array) and key.type() == Dtype.b8.value if (is_boolean_idx): n_dims = 1 num = count(key) if (num == 0): return if (_is_number(val)): tdims = _get_assign_dims(key, self.dims()) if (is_boolean_idx): n_dims = 1 other_arr = constant_array(val, int(num), dtype=self.type()) else: other_arr = constant_array(val, tdims[0] , tdims[1], tdims[2], tdims[3], self.type()) del_other = True else: other_arr = val.arr del_other = False out_arr = ct.c_void_p(0) inds = _get_indices(key) safe_call(backend.get().af_assign_gen(ct.pointer(out_arr), self.arr, c_dim_t(n_dims), inds.pointer, other_arr)) safe_call(backend.get().af_release_array(self.arr)) if del_other: safe_call(backend.get().af_release_array(other_arr)) self.arr = out_arr except RuntimeError as e: raise IndexError(str(e)) def to_ctype(self, row_major=False, return_shape=False): """ Return the data as a ctype C array after copying to host memory Parameters ----------- row_major: optional: bool. default: False. Specifies if a transpose needs to occur before copying to host memory. return_shape: optional: bool. default: False. Specifies if the shape of the array needs to be returned. Returns ------- If return_shape is False: res: The ctypes array of the appropriate type and length. else : (res, dims): tuple of the ctypes array and the shape of the array """ if (self.arr.value == 0): raise RuntimeError("Can not call to_ctype on empty array") tmp = transpose(self) if row_major else self ctype_type = to_c_type[self.type()] * self.elements() res = ctype_type() safe_call(backend.get().af_get_data_ptr(ct.pointer(res), self.arr)) if (return_shape): return res, self.dims() else: return res def to_array(self, row_major=False, return_shape=False): """ Return the data as array.array Parameters ----------- row_major: optional: bool. default: False. Specifies if a transpose needs to occur before copying to host memory. return_shape: optional: bool. default: False. Specifies if the shape of the array needs to be returned. Returns ------- If return_shape is False: res: array.array of the appropriate type and length. else : (res, dims): array.array and the shape of the array """ if (self.arr.value == 0): raise RuntimeError("Can not call to_array on empty array") res = self.to_ctype(row_major, return_shape) host = __import__("array") h_type = to_typecode[self.type()] if (return_shape): return host.array(h_type, res[0]), res[1] else: return host.array(h_type, res) def to_list(self, row_major=False): """ Return the data as list Parameters ----------- row_major: optional: bool. default: False. Specifies if a transpose needs to occur before copying to host memory. return_shape: optional: bool. default: False. Specifies if the shape of the array needs to be returned. Returns ------- If return_shape is False: res: list of the appropriate type and length. else : (res, dims): list and the shape of the array """ ct_array, shape = self.to_ctype(row_major, True) return _ctype_to_lists(ct_array, len(shape) - 1, shape) def __repr__(self): """ Displays the meta data and contents of the arrayfire array. Note ---- You can also use af.display(a, pres) to display the contents of the array with better precision. """ arr_str = ct.c_char_p(0) safe_call(backend.get().af_array_to_string(ct.pointer(arr_str), "", self.arr, 4, True)) return 'arrayfire.Array()\nType: %s' % \ (to_typename[self.type()]) + to_str(arr_str) def __array__(self): """ Constructs a numpy.array from arrayfire.Array """ import numpy as np res = np.empty(self.dims(), dtype=np.dtype(to_typecode[self.type()]), order='F') safe_call(backend.get().af_get_data_ptr(ct.c_void_p(res.ctypes.data), self.arr)) return res def display(a, precision=4): """ Displays the contents of an array. Parameters ---------- a : af.Array Multi dimensional arrayfire array precision: int. optional. Specifies the number of precision bits to display """ expr = inspect.stack()[1][-2] name = "" try: if (expr is not None): st = expr[0].find('(') + 1 en = expr[0].rfind(')') name = expr[0][st:en] except: pass safe_call(backend.get().af_print_array_gen(name.encode('utf-8'), a.arr, ct.c_int(precision))) def save_array(key, a, filename, append=False): """ Save an array to disk. Parameters ---------- key : str A name / key associated with the array a : af.Array The array to be stored to disk filename : str Location of the data file. append : Boolean. optional. default: False. If the file already exists, specifies if the data should be appended or overwritten. Returns --------- index : int The index of the array stored in the file. """ index = ct.c_int(-1) safe_call(backend.get().af_save_array(ct.pointer(index), key.encode('utf-8'), a.arr, filename.encode('utf-8'), append)) return index.value def read_array(filename, index=None, key=None): """ Read an array from disk. Parameters ---------- filename : str Location of the data file. index : int. Optional. Default: None. - The index of the array stored in the file. - If None, key is used. key : str. Optional. Default: None. - A name / key associated with the array - If None, index is used. Returns --------- """ assert((index is not None) or (key is not None)) out = Array() if (index is not None): safe_call(backend.get().af_read_array_index(ct.pointer(out.arr), filename.encode('utf-8'), index)) elif (key is not None): safe_call(backend.get().af_read_array_key(ct.pointer(out.arr), filename.encode('utf-8'), key.encode('utf-8'))) return out from .algorithm import (sum, count) from .arith import cast python-arrayfire-3.3.20160624/arrayfire/base.py000066400000000000000000000010721276671162200210470ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Implementation of BaseArray class. """ from .library import * from .util import * class BaseArray(object): """ Base array class for arrayfire. For internal use only. """ def __init__(self): self.arr = ct.c_void_p(0) python-arrayfire-3.3.20160624/arrayfire/bcast.py000066400000000000000000000043721276671162200212370ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Function to perform broadcasting operations. """ class _bcast(object): _flag = False def get(self): return _bcast._flag def set(self, flag): _bcast._flag = flag def toggle(self): _bcast._flag ^= True _bcast_var = _bcast() def broadcast(func, *args): """ Function to perform broadcast operations. This function can be used directly or as an annotation in the following manner. Example ------- Using broadcast as an annotation >>> import arrayfire as af >>> @af.broadcast ... def add(a, b): ... return a + b ... >>> a = af.randu(2,3) >>> b = af.randu(2,1) # b is a different size >>> # Trying to add arrays of different sizes raises an exceptions >>> c = add(a, b) # This call does not raise an exception because of the annotation >>> af.display(a) [2 3 1 1] 0.4107 0.9518 0.4198 0.8224 0.1794 0.0081 >>> af.display(b) [2 1 1 1] 0.7269 0.7104 >>> af.display(c) [2 3 1 1] 1.1377 1.6787 1.1467 1.5328 0.8898 0.7185 Using broadcast as function >>> import arrayfire as af >>> add = lambda a,b: a + b >>> a = af.randu(2,3) >>> b = af.randu(2,1) # b is a different size >>> # Trying to add arrays of different sizes raises an exceptions >>> c = af.broadcast(add, a, b) # This call does not raise an exception >>> af.display(a) [2 3 1 1] 0.4107 0.9518 0.4198 0.8224 0.1794 0.0081 >>> af.display(b) [2 1 1 1] 0.7269 0.7104 >>> af.display(c) [2 3 1 1] 1.1377 1.6787 1.1467 1.5328 0.8898 0.7185 """ def wrapper(*func_args): _bcast_var.toggle() res = func(*func_args) _bcast_var.toggle() return res if len(args) == 0: return wrapper else: return wrapper(*args) python-arrayfire-3.3.20160624/arrayfire/blas.py000066400000000000000000000120411276671162200210540ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ BLAS functions (matmul, dot, etc) """ from .library import * from .array import * def matmul(lhs, rhs, lhs_opts=MATPROP.NONE, rhs_opts=MATPROP.NONE): """ Generalized matrix multiplication for two matrices. Parameters ---------- lhs : af.Array A 2 dimensional, real or complex arrayfire array. rhs : af.Array A 2 dimensional, real or complex arrayfire array. lhs_opts: optional: af.MATPROP. default: af.MATPROP.NONE. Can be one of - af.MATPROP.NONE - If no op should be done on `lhs`. - af.MATPROP.TRANS - If `lhs` has to be transposed before multiplying. - af.MATPROP.CTRANS - If `lhs` has to be hermitian transposed before multiplying. rhs_opts: optional: af.MATPROP. default: af.MATPROP.NONE. Can be one of - af.MATPROP.NONE - If no op should be done on `rhs`. - af.MATPROP.TRANS - If `rhs` has to be transposed before multiplying. - af.MATPROP.CTRANS - If `rhs` has to be hermitian transposed before multiplying. Returns ------- out : af.Array Output of the matrix multiplication on `lhs` and `rhs`. Note ----- - The data types of `lhs` and `rhs` should be the same. - Batches are not supported. """ out = Array() safe_call(backend.get().af_matmul(ct.pointer(out.arr), lhs.arr, rhs.arr, lhs_opts.value, rhs_opts.value)) return out def matmulTN(lhs, rhs): """ Matrix multiplication after transposing the first matrix. Parameters ---------- lhs : af.Array A 2 dimensional, real or complex arrayfire array. rhs : af.Array A 2 dimensional, real or complex arrayfire array. Returns ------- out : af.Array Output of the matrix multiplication on `transpose(lhs)` and `rhs`. Note ----- - The data types of `lhs` and `rhs` should be the same. - Batches are not supported. """ out = Array() safe_call(backend.get().af_matmul(ct.pointer(out.arr), lhs.arr, rhs.arr, MATPROP.TRANS.value, MATPROP.NONE.value)) return out def matmulNT(lhs, rhs): """ Matrix multiplication after transposing the second matrix. Parameters ---------- lhs : af.Array A 2 dimensional, real or complex arrayfire array. rhs : af.Array A 2 dimensional, real or complex arrayfire array. Returns ------- out : af.Array Output of the matrix multiplication on `lhs` and `transpose(rhs)`. Note ----- - The data types of `lhs` and `rhs` should be the same. - Batches are not supported. """ out = Array() safe_call(backend.get().af_matmul(ct.pointer(out.arr), lhs.arr, rhs.arr, MATPROP.NONE.value, MATPROP.TRANS.value)) return out def matmulTT(lhs, rhs): """ Matrix multiplication after transposing both inputs. Parameters ---------- lhs : af.Array A 2 dimensional, real or complex arrayfire array. rhs : af.Array A 2 dimensional, real or complex arrayfire array. Returns ------- out : af.Array Output of the matrix multiplication on `transpose(lhs)` and `transpose(rhs)`. Note ----- - The data types of `lhs` and `rhs` should be the same. - Batches are not supported. """ out = Array() safe_call(backend.get().af_matmul(ct.pointer(out.arr), lhs.arr, rhs.arr, MATPROP.TRANS.value, MATPROP.TRANS.value)) return out def dot(lhs, rhs, lhs_opts=MATPROP.NONE, rhs_opts=MATPROP.NONE): """ Dot product of two input vectors. Parameters ---------- lhs : af.Array A 1 dimensional, real or complex arrayfire array. rhs : af.Array A 1 dimensional, real or complex arrayfire array. lhs_opts: optional: af.MATPROP. default: af.MATPROP.NONE. Can be one of - af.MATPROP.NONE - If no op should be done on `lhs`. - No other options are currently supported. rhs_opts: optional: af.MATPROP. default: af.MATPROP.NONE. Can be one of - af.MATPROP.NONE - If no op should be done on `rhs`. - No other options are currently supported. Returns ------- out : af.Array Output of dot product of `lhs` and `rhs`. Note ----- - The data types of `lhs` and `rhs` should be the same. - Batches are not supported. """ out = Array() safe_call(backend.get().af_dot(ct.pointer(out.arr), lhs.arr, rhs.arr, lhs_opts.value, rhs_opts.value)) return out python-arrayfire-3.3.20160624/arrayfire/cuda.py000066400000000000000000000040321276671162200210500ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Functions specific to CUDA backend. This module provides interoperability with other CUDA libraries. """ def get_stream(idx): """ Get the CUDA stream used for the device `idx` by ArrayFire. Parameters ---------- idx : int. Specifies the index of the device. Returns ----------- stream : integer denoting the stream id. """ import ctypes as ct from .util import safe_call as safe_call from .library import backend as backend if (backend.name() != "cuda"): raise RuntimeError("Invalid backend loaded") stream = ct.c_void_p(0) safe_call(backend.get().afcu_get_stream(ct.pointer(stream), idx)) return stream.value def get_native_id(idx): """ Get native (unsorted) CUDA device ID Parameters ---------- idx : int. Specifies the (sorted) index of the device. Returns ----------- native_idx : integer denoting the native cuda id. """ import ctypes as ct from .util import safe_call as safe_call from .library import backend as backend if (backend.name() != "cuda"): raise RuntimeError("Invalid backend loaded") native = ct.c_int(0) safe_call(backend.get().afcu_get_native_id(ct.pointer(native), idx)) return native.value def set_native_id(idx): """ Set native (unsorted) CUDA device ID Parameters ---------- idx : int. Specifies the (unsorted) native index of the device. """ import ctypes as ct from .util import safe_call as safe_call from .library import backend as backend if (backend.name() != "cuda"): raise RuntimeError("Invalid backend loaded") safe_call(backend.get().afcu_set_native_id(idx)) return python-arrayfire-3.3.20160624/arrayfire/data.py000066400000000000000000000604531276671162200210560ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Functions to create and manipulate arrays. """ from sys import version_info from .library import * from .array import * from .util import * from .util import _is_number def constant(val, d0, d1=None, d2=None, d3=None, dtype=Dtype.f32): """ Create a multi dimensional array whose elements contain the same value. Parameters ---------- val : scalar. Value of each element of the constant array. d0 : int. Length of first dimension. d1 : optional: int. default: None. Length of second dimension. d2 : optional: int. default: None. Length of third dimension. d3 : optional: int. default: None. Length of fourth dimension. dtype : optional: af.Dtype. default: af.Dtype.f32. Data type of the array. Returns ------- out : af.Array Multi dimensional array whose elements are of value `val`. - If d1 is None, `out` is 1D of size (d0,). - If d1 is not None and d2 is None, `out` is 2D of size (d0, d1). - If d1 and d2 are not None and d3 is None, `out` is 3D of size (d0, d1, d2). - If d1, d2, d3 are all not None, `out` is 4D of size (d0, d1, d2, d3). """ out = Array() out.arr = constant_array(val, d0, d1, d2, d3, dtype.value) return out # Store builtin range function to be used later _brange = range def range(d0, d1=None, d2=None, d3=None, dim=0, dtype=Dtype.f32): """ Create a multi dimensional array using length of a dimension as range. Parameters ---------- val : scalar. Value of each element of the constant array. d0 : int. Length of first dimension. d1 : optional: int. default: None. Length of second dimension. d2 : optional: int. default: None. Length of third dimension. d3 : optional: int. default: None. Length of fourth dimension. dim : optional: int. default: 0. The dimension along which the range is calculated. dtype : optional: af.Dtype. default: af.Dtype.f32. Data type of the array. Returns ------- out : af.Array Multi dimensional array whose elements are along `dim` fall between [0 - self.dims[dim]-1] - If d1 is None, `out` is 1D of size (d0,). - If d1 is not None and d2 is None, `out` is 2D of size (d0, d1). - If d1 and d2 are not None and d3 is None, `out` is 3D of size (d0, d1, d2). - If d1, d2, d3 are all not None, `out` is 4D of size (d0, d1, d2, d3). Examples -------- >>> import arrayfire as af >>> a = af.range(3, 2) # dim is not specified, range is along first dimension. >>> af.display(a) # The data ranges from [0 - 2] (3 elements along first dimension) [3 2 1 1] 0.0000 0.0000 1.0000 1.0000 2.0000 2.0000 >>> a = af.range(3, 2, dim=1) # dim is 1, range is along second dimension. >>> af.display(a) # The data ranges from [0 - 1] (2 elements along second dimension) [3 2 1 1] 0.0000 1.0000 0.0000 1.0000 0.0000 1.0000 """ out = Array() dims = dim4(d0, d1, d2, d3) safe_call(backend.get().af_range(ct.pointer(out.arr), 4, ct.pointer(dims), dim, dtype.value)) return out def iota(d0, d1=None, d2=None, d3=None, dim=-1, tile_dims=None, dtype=Dtype.f32): """ Create a multi dimensional array using the number of elements in the array as the range. Parameters ---------- val : scalar. Value of each element of the constant array. d0 : int. Length of first dimension. d1 : optional: int. default: None. Length of second dimension. d2 : optional: int. default: None. Length of third dimension. d3 : optional: int. default: None. Length of fourth dimension. tile_dims : optional: tuple of ints. default: None. The number of times the data is tiled. dtype : optional: af.Dtype. default: af.Dtype.f32. Data type of the array. Returns ------- out : af.Array Multi dimensional array whose elements are along `dim` fall between [0 - self.elements() - 1]. Examples -------- >>> import arrayfire as af >>> import arrayfire as af >>> a = af.iota(3,3) # tile_dim is not specified, data is not tiled >>> af.display(a) # the elements range from [0 - 8] (9 elements) [3 3 1 1] 0.0000 3.0000 6.0000 1.0000 4.0000 7.0000 2.0000 5.0000 8.0000 >>> b = af.iota(3,3,tile_dims(1,2)) # Asking to tile along second dimension. >>> af.display(b) [3 6 1 1] 0.0000 3.0000 6.0000 0.0000 3.0000 6.0000 1.0000 4.0000 7.0000 1.0000 4.0000 7.0000 2.0000 5.0000 8.0000 2.0000 5.0000 8.0000 """ out = Array() dims = dim4(d0, d1, d2, d3) td=[1]*4 if tile_dims is not None: for i in _brange(len(tile_dims)): td[i] = tile_dims[i] tdims = dim4(td[0], td[1], td[2], td[3]) safe_call(backend.get().af_iota(ct.pointer(out.arr), 4, ct.pointer(dims), 4, ct.pointer(tdims), dtype.value)) return out def randu(d0, d1=None, d2=None, d3=None, dtype=Dtype.f32): """ Create a multi dimensional array containing values from a uniform distribution. Parameters ---------- d0 : int. Length of first dimension. d1 : optional: int. default: None. Length of second dimension. d2 : optional: int. default: None. Length of third dimension. d3 : optional: int. default: None. Length of fourth dimension. dtype : optional: af.Dtype. default: af.Dtype.f32. Data type of the array. Returns ------- out : af.Array Multi dimensional array whose elements are sampled uniformly between [0, 1]. - If d1 is None, `out` is 1D of size (d0,). - If d1 is not None and d2 is None, `out` is 2D of size (d0, d1). - If d1 and d2 are not None and d3 is None, `out` is 3D of size (d0, d1, d2). - If d1, d2, d3 are all not None, `out` is 4D of size (d0, d1, d2, d3). """ out = Array() dims = dim4(d0, d1, d2, d3) safe_call(backend.get().af_randu(ct.pointer(out.arr), 4, ct.pointer(dims), dtype.value)) return out def randn(d0, d1=None, d2=None, d3=None, dtype=Dtype.f32): """ Create a multi dimensional array containing values from a normal distribution. Parameters ---------- d0 : int. Length of first dimension. d1 : optional: int. default: None. Length of second dimension. d2 : optional: int. default: None. Length of third dimension. d3 : optional: int. default: None. Length of fourth dimension. dtype : optional: af.Dtype. default: af.Dtype.f32. Data type of the array. Returns ------- out : af.Array Multi dimensional array whose elements are sampled from a normal distribution with mean 0 and sigma of 1. - If d1 is None, `out` is 1D of size (d0,). - If d1 is not None and d2 is None, `out` is 2D of size (d0, d1). - If d1 and d2 are not None and d3 is None, `out` is 3D of size (d0, d1, d2). - If d1, d2, d3 are all not None, `out` is 4D of size (d0, d1, d2, d3). """ out = Array() dims = dim4(d0, d1, d2, d3) safe_call(backend.get().af_randn(ct.pointer(out.arr), 4, ct.pointer(dims), dtype.value)) return out def set_seed(seed=0): """ Set the seed for the random number generator. Parameters ---------- seed: int. Seed for the random number generator """ safe_call(backend.get().af_set_seed(ct.c_ulonglong(seed))) def get_seed(): """ Get the seed for the random number generator. Returns ---------- seed: int. Seed for the random number generator """ seed = ct.c_ulonglong(0) safe_call(backend.get().af_get_seed(ct.pointer(seed))) return seed.value def identity(d0, d1, d2=None, d3=None, dtype=Dtype.f32): """ Create an identity matrix or batch of identity matrices. Parameters ---------- d0 : int. Length of first dimension. d1 : int. Length of second dimension. d2 : optional: int. default: None. Length of third dimension. d3 : optional: int. default: None. Length of fourth dimension. dtype : optional: af.Dtype. default: af.Dtype.f32. Data type of the array. Returns ------- out : af.Array Multi dimensional array whose first two dimensions form a identity matrix. - If d2 is None, `out` is 2D of size (d0, d1). - If d2 is not None and d3 is None, `out` is 3D of size (d0, d1, d2). - If d2, d3 are not None, `out` is 4D of size (d0, d1, d2, d3). """ out = Array() dims = dim4(d0, d1, d2, d3) safe_call(backend.get().af_identity(ct.pointer(out.arr), 4, ct.pointer(dims), dtype.value)) return out def diag(a, num=0, extract=True): """ Create a diagonal matrix or Extract the diagonal from a matrix. Parameters ---------- a : af.Array. 1 dimensional or 2 dimensional arrayfire array. num : optional: int. default: 0. The index of the diagonal. - num == 0 signifies the diagonal. - num > 0 signifies super diagonals. - num < 0 signifies sub diagonals. extract : optional: bool. default: True. - If True , diagonal is extracted. `a` has to be 2D. - If False, diagonal matrix is created. `a` has to be 1D. Returns ------- out : af.Array - if extract is True, `out` contains the num'th diagonal from `a`. - if extract is False, `out` contains `a` as the num'th diagonal. """ out = Array() if extract: safe_call(backend.get().af_diag_extract(ct.pointer(out.arr), a.arr, ct.c_int(num))) else: safe_call(backend.get().af_diag_create(ct.pointer(out.arr), a.arr, ct.c_int(num))) return out def join(dim, first, second, third=None, fourth=None): """ Join two or more arrayfire arrays along a specified dimension. Parameters ---------- dim: int. Dimension along which the join occurs. first : af.Array. Multi dimensional arrayfire array. second : af.Array. Multi dimensional arrayfire array. third : optional: af.Array. default: None. Multi dimensional arrayfire array. fourth : optional: af.Array. default: None. Multi dimensional arrayfire array. Returns ------- out : af.Array An array containing the input arrays joined along the specified dimension. Examples --------- >>> import arrayfire as af >>> a = af.randu(2, 3) >>> b = af.randu(2, 3) >>> c = af.join(0, a, b) >>> d = af.join(1, a, b) >>> af.display(a) [2 3 1 1] 0.9508 0.2591 0.7928 0.5367 0.8359 0.8719 >>> af.display(b) [2 3 1 1] 0.3266 0.6009 0.2442 0.6275 0.0495 0.6591 >>> af.display(c) [4 3 1 1] 0.9508 0.2591 0.7928 0.5367 0.8359 0.8719 0.3266 0.6009 0.2442 0.6275 0.0495 0.6591 >>> af.display(d) [2 6 1 1] 0.9508 0.2591 0.7928 0.3266 0.6009 0.2442 0.5367 0.8359 0.8719 0.6275 0.0495 0.6591 """ out = Array() if (third is None and fourth is None): safe_call(backend.get().af_join(ct.pointer(out.arr), dim, first.arr, second.arr)) else: c_void_p_4 = ct.c_void_p * 4 c_array_vec = c_void_p_4(first.arr, second.arr, 0, 0) num = 2 if third is not None: c_array_vec[num] = third.arr num+=1 if fourth is not None: c_array_vec[num] = fourth.arr num+=1 safe_call(backend.get().af_join_many(ct.pointer(out.arr), dim, num, ct.pointer(c_array_vec))) return out def tile(a, d0, d1=1, d2=1, d3=1): """ Tile an array along specified dimensions. Parameters ---------- a : af.Array. Multi dimensional array. d0: int. The number of times `a` has to be tiled along first dimension. d1: optional: int. default: 1. The number of times `a` has to be tiled along second dimension. d2: optional: int. default: 1. The number of times `a` has to be tiled along third dimension. d3: optional: int. default: 1. The number of times `a` has to be tiled along fourth dimension. Returns ------- out : af.Array An array containing the input after tiling the the specified number of times. Examples --------- >>> import arrayfire as af >>> a = af.randu(2, 3) >>> b = af.tile(a, 2) >>> c = af.tile(a, 1, 2) >>> d = af.tile(a, 2, 2) >>> af.display(a) [2 3 1 1] 0.9508 0.2591 0.7928 0.5367 0.8359 0.8719 >>> af.display(b) [4 3 1 1] 0.4107 0.9518 0.4198 0.8224 0.1794 0.0081 0.4107 0.9518 0.4198 0.8224 0.1794 0.0081 >>> af.display(c) [2 6 1 1] 0.4107 0.9518 0.4198 0.4107 0.9518 0.4198 0.8224 0.1794 0.0081 0.8224 0.1794 0.0081 >>> af.display(d) [4 6 1 1] 0.4107 0.9518 0.4198 0.4107 0.9518 0.4198 0.8224 0.1794 0.0081 0.8224 0.1794 0.0081 0.4107 0.9518 0.4198 0.4107 0.9518 0.4198 0.8224 0.1794 0.0081 0.8224 0.1794 0.0081 """ out = Array() safe_call(backend.get().af_tile(ct.pointer(out.arr), a.arr, d0, d1, d2, d3)) return out def reorder(a, d0=1, d1=0, d2=2, d3=3): """ Reorder the dimensions of the input. Parameters ---------- a : af.Array. Multi dimensional array. d0: optional: int. default: 1. The location of the first dimension in the output. d1: optional: int. default: 0. The location of the second dimension in the output. d2: optional: int. default: 2. The location of the third dimension in the output. d3: optional: int. default: 3. The location of the fourth dimension in the output. Returns ------- out : af.Array - An array containing the input aftern reordering its dimensions. Note ------ - `af.reorder(a, 1, 0)` is the same as `transpose(a)` Examples -------- >>> import arrayfire as af >>> a = af.randu(5, 5, 3) >>> af.display(a) [5 5 3 1] 0.4107 0.0081 0.6600 0.1046 0.8395 0.8224 0.3775 0.0764 0.8827 0.1933 0.9518 0.3027 0.0901 0.1647 0.7270 0.1794 0.6456 0.5933 0.8060 0.0322 0.4198 0.5591 0.1098 0.5938 0.0012 0.8703 0.9250 0.4387 0.6530 0.4224 0.5259 0.3063 0.3784 0.5476 0.5293 0.1443 0.9313 0.4002 0.8577 0.0212 0.3253 0.8684 0.4390 0.8370 0.1103 0.5081 0.6592 0.4718 0.0618 0.4420 0.8355 0.6767 0.1033 0.9426 0.9276 0.4878 0.6742 0.2119 0.4817 0.8662 0.2055 0.4523 0.5955 0.9097 0.3578 0.1794 0.1236 0.3745 0.6821 0.6263 0.5606 0.7924 0.9165 0.6056 0.9747 >>> b = af.reorder(a, 2, 0, 1) >>> af.display(b) [3 5 5 1] 0.4107 0.8224 0.9518 0.1794 0.4198 0.8703 0.5259 0.1443 0.3253 0.5081 0.8355 0.4878 0.2055 0.1794 0.5606 0.0081 0.3775 0.3027 0.6456 0.5591 0.9250 0.3063 0.9313 0.8684 0.6592 0.6767 0.6742 0.4523 0.1236 0.7924 0.6600 0.0764 0.0901 0.5933 0.1098 0.4387 0.3784 0.4002 0.4390 0.4718 0.1033 0.2119 0.5955 0.3745 0.9165 0.1046 0.8827 0.1647 0.8060 0.5938 0.6530 0.5476 0.8577 0.8370 0.0618 0.9426 0.4817 0.9097 0.6821 0.6056 0.8395 0.1933 0.7270 0.0322 0.0012 0.4224 0.5293 0.0212 0.1103 0.4420 0.9276 0.8662 0.3578 0.6263 0.9747 """ out = Array() safe_call(backend.get().af_reorder(ct.pointer(out.arr), a.arr, d0, d1, d2, d3)) return out def shift(a, d0, d1=0, d2=0, d3=0): """ Shift the input along each dimension. Parameters ---------- a : af.Array. Multi dimensional array. d0: int. The amount of shift along first dimension. d1: optional: int. default: 0. The amount of shift along second dimension. d2: optional: int. default: 0. The amount of shift along third dimension. d3: optional: int. default: 0. The amount of shift along fourth dimension. Returns ------- out : af.Array - An array the same shape as `a` after shifting it by the specified amounts. Examples -------- >>> import arrayfire as af >>> a = af.randu(3, 3) >>> b = af.shift(a, 2) >>> c = af.shift(a, 1, -1) >>> af.display(a) [3 3 1 1] 0.7269 0.3569 0.3341 0.7104 0.1437 0.0899 0.5201 0.4563 0.5363 >>> af.display(b) [3 3 1 1] 0.7104 0.1437 0.0899 0.5201 0.4563 0.5363 0.7269 0.3569 0.3341 >>> af.display(c) [3 3 1 1] 0.4563 0.5363 0.5201 0.3569 0.3341 0.7269 0.1437 0.0899 0.7104 """ out = Array() safe_call(backend.get().af_shift(ct.pointer(out.arr), a.arr, d0, d1, d2, d3)) return out def moddims(a, d0, d1=1, d2=1, d3=1): """ Modify the shape of the array without changing the data layout. Parameters ---------- a : af.Array. Multi dimensional array. d0: int. The first dimension of output. d1: optional: int. default: 1. The second dimension of output. d2: optional: int. default: 1. The third dimension of output. d3: optional: int. default: 1. The fourth dimension of output. Returns ------- out : af.Array - An containing the same data as `a` with the specified shape. - The number of elements in `a` must match `d0 x d1 x d2 x d3`. """ out = Array() dims = dim4(d0, d1, d2, d3) safe_call(backend.get().af_moddims(ct.pointer(out.arr), a.arr, 4, ct.pointer(dims))) return out def flat(a): """ Flatten the input array. Parameters ---------- a : af.Array. Multi dimensional array. Returns ------- out : af.Array - 1 dimensional array containing all the elements from `a`. """ out = Array() safe_call(backend.get().af_flat(ct.pointer(out.arr), a.arr)) return out def flip(a, dim=0): """ Flip an array along a dimension. Parameters ---------- a : af.Array. Multi dimensional array. dim : optional: int. default: 0. The dimension along which the flip is performed. Returns ------- out : af.Array The output after flipping `a` along `dim`. Examples --------- >>> import arrayfire as af >>> a = af.randu(3, 3) >>> af.display(a) [3 3 1 1] 0.7269 0.3569 0.3341 0.7104 0.1437 0.0899 0.5201 0.4563 0.5363 >>> af.display(b) [3 3 1 1] 0.5201 0.4563 0.5363 0.7104 0.1437 0.0899 0.7269 0.3569 0.3341 >>> af.display(c) [3 3 1 1] 0.3341 0.3569 0.7269 0.0899 0.1437 0.7104 0.5363 0.4563 0.5201 """ out = Array() safe_call(backend.get().af_flip(ct.pointer(out.arr), a.arr, ct.c_int(dim))) return out def lower(a, is_unit_diag=False): """ Extract the lower triangular matrix from the input. Parameters ---------- a : af.Array. Multi dimensional array. is_unit_diag: optional: bool. default: False. Flag specifying if the diagonal elements are 1. Returns ------- out : af.Array An array containing the lower triangular elements from `a`. """ out = Array() safe_call(backend.get().af_lower(ct.pointer(out.arr), a.arr, is_unit_diag)) return out def upper(a, is_unit_diag=False): """ Extract the upper triangular matrix from the input. Parameters ---------- a : af.Array. Multi dimensional array. is_unit_diag: optional: bool. default: False. Flag specifying if the diagonal elements are 1. Returns ------- out : af.Array An array containing the upper triangular elements from `a`. """ out = Array() safe_call(backend.get().af_upper(ct.pointer(out.arr), a.arr, is_unit_diag)) return out def select(cond, lhs, rhs): """ Select elements from one of two arrays based on condition. Parameters ---------- cond : af.Array Conditional array lhs : af.Array or scalar numerical array whose elements are picked when conditional element is True rhs : af.Array or scalar numerical array whose elements are picked when conditional element is False Returns -------- out: af.Array An array containing elements from `lhs` when `cond` is True and `rhs` when False. Examples --------- >>> import arrayfire as af >>> a = af.randu(3,3) >>> b = af.randu(3,3) >>> cond = a > b >>> res = af.select(cond, a, b) >>> af.display(a) [3 3 1 1] 0.4107 0.1794 0.3775 0.8224 0.4198 0.3027 0.9518 0.0081 0.6456 >>> af.display(b) [3 3 1 1] 0.7269 0.3569 0.3341 0.7104 0.1437 0.0899 0.5201 0.4563 0.5363 >>> af.display(res) [3 3 1 1] 0.7269 0.3569 0.3775 0.8224 0.4198 0.3027 0.9518 0.4563 0.6456 """ out = Array() is_left_array = isinstance(lhs, Array) is_right_array = isinstance(rhs, Array) if not (is_left_array or is_right_array): raise TypeError("Atleast one input needs to be of type arrayfire.array") elif (is_left_array and is_right_array): safe_call(backend.get().af_select(ct.pointer(out.arr), cond.arr, lhs.arr, rhs.arr)) elif (_is_number(rhs)): safe_call(backend.get().af_select_scalar_r(ct.pointer(out.arr), cond.arr, lhs.arr, ct.c_double(rhs))) else: safe_call(backend.get().af_select_scalar_l(ct.pointer(out.arr), cond.arr, ct.c_double(lhs), rhs.arr)) return out def replace(lhs, cond, rhs): """ Select elements from one of two arrays based on condition. Parameters ---------- lhs : af.Array or scalar numerical array whose elements are replaced with `rhs` when conditional element is False cond : af.Array Conditional array rhs : af.Array or scalar numerical array whose elements are picked when conditional element is False Examples --------- >>> import arrayfire as af >>> a = af.randu(3,3) >>> af.display(a) [3 3 1 1] 0.4107 0.1794 0.3775 0.8224 0.4198 0.3027 0.9518 0.0081 0.6456 >>> cond = (a >= 0.25) & (a <= 0.75) >>> af.display(cond) [3 3 1 1] 1 0 1 0 1 1 0 0 1 >>> af.replace(a, cond, 0.3333) >>> af.display(a) [3 3 1 1] 0.3333 0.1794 0.3333 0.8224 0.3333 0.3333 0.9518 0.0081 0.3333 """ is_right_array = isinstance(rhs, Array) if (is_right_array): safe_call(backend.get().af_replace(lhs.arr, cond.arr, rhs.arr)) else: safe_call(backend.get().af_replace_scalar(lhs.arr, cond.arr, ct.c_double(rhs))) python-arrayfire-3.3.20160624/arrayfire/device.py000066400000000000000000000223441276671162200214010ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Functions to handle the available devices in the backend. """ from .library import * from .util import (safe_call, to_str, get_version) def init(): """ Note ----- This function may need to be called when interoperating with other libraries """ safe_call(backend.get().af_init()) def info(): """ Displays the information about the following: - ArrayFire build and version number. - The number of devices available. - The names of the devices. - The current device being used. """ safe_call(backend.get().af_info()) def device_info(): """ Returns a map with the following fields: - 'device': Name of the current device. - 'backend': The current backend being used. - 'toolkit': The toolkit version for the backend. - 'compute': The compute version of the device. """ c_char_256 = ct.c_char * 256 device_name = c_char_256() backend_name = c_char_256() toolkit = c_char_256() compute = c_char_256() safe_call(backend.get().af_device_info(ct.pointer(device_name), ct.pointer(backend_name), ct.pointer(toolkit), ct.pointer(compute))) dev_info = {} dev_info['device'] = to_str(device_name) dev_info['backend'] = to_str(backend_name) dev_info['toolkit'] = to_str(toolkit) dev_info['compute'] = to_str(compute) return dev_info def get_device_count(): """ Returns the number of devices available. """ c_num = ct.c_int(0) safe_call(backend.get().af_get_device_count(ct.pointer(c_num))) return c_num.value def get_device(): """ Returns the id of the current device. """ c_dev = ct.c_int(0) safe_call(backend.get().af_get_device(ct.pointer(c_dev))) return c_dev.value def set_device(num): """ Change the active device to the specified id. Parameters ----------- num: int. id of the desired device. """ safe_call(backend.get().af_set_device(num)) def info_str(verbose = False): """ Returns information about the following as a string: - ArrayFire version number. - The number of devices available. - The names of the devices. - The current device being used. """ import platform res_str = 'ArrayFire' major, minor, patch = get_version() dev_info = device_info() backend_str = dev_info['backend'] res_str += ' v' + str(major) + '.' + str(minor) + '.' + str(patch) res_str += ' (' + backend_str + ' ' + platform.architecture()[0] + ')\n' num_devices = get_device_count() curr_device_id = get_device() for n in range(num_devices): # To suppress warnings on CPU if (n != curr_device_id): set_device(n) if (n == curr_device_id): res_str += '[%d] ' % n else: res_str += '-%d- ' % n dev_info = device_info() if (backend_str.lower() == 'opencl'): res_str += dev_info['toolkit'] res_str += ': ' + dev_info['device'] if (backend_str.lower() != 'cpu'): res_str += ' (Compute ' + dev_info['compute'] + ')' res_str += '\n' # To suppress warnings on CPU if (curr_device_id != get_device()): set_device(curr_device_id) return res_str def is_dbl_supported(device=None): """ Check if double precision is supported on specified device. Parameters ----------- device: optional: int. default: None. id of the desired device. Returns -------- - True if double precision supported. - False if double precision not supported. """ dev = device if device is not None else get_device() res = ct.c_bool(False) safe_call(backend.get().af_get_dbl_support(ct.pointer(res), dev)) return res.value def sync(device=None): """ Block until all the functions on the device have completed execution. Parameters ----------- device: optional: int. default: None. id of the desired device. """ dev = device if device is not None else get_device() safe_call(backend.get().af_sync(dev)) def __eval(*args): for A in args: if isinstance(A, tuple): __eval(*A) if isinstance(A, list): __eval(*A) if isinstance(A, Array): safe_call(backend.get().af_eval(A.arr)) def eval(*args): """ Evaluate the input Parameters ----------- args : arguments to be evaluated """ __eval(args) def device_mem_info(): """ Returns a map with the following fields: - 'alloc': Contains the map of the following - 'buffers' : Total number of buffers allocated by memory manager. - 'bytes' : Total number of bytes allocated by memory manager. - 'lock': Contains the map of the following - 'buffers' : Total number of buffers currently in scope. - 'bytes' : Total number of bytes currently in scope. Note ----- ArrayFire does not free memory when array goes out of scope. The memory is marked for reuse. - The difference between alloc buffers and lock buffers equals the number of free buffers. - The difference between alloc bytes and lock bytes equals the number of free bytes. """ alloc_bytes = ct.c_size_t(0) alloc_buffers = ct.c_size_t(0) lock_bytes = ct.c_size_t(0) lock_buffers = ct.c_size_t(0) safe_call(backend.get().af_device_mem_info(ct.pointer(alloc_bytes), ct.pointer(alloc_buffers), ct.pointer(lock_bytes), ct.pointer(lock_buffers))) mem_info = {} mem_info['alloc'] = {'buffers' : alloc_buffers.value, 'bytes' : alloc_bytes.value} mem_info['lock'] = {'buffers' : lock_buffers.value, 'bytes' : lock_bytes.value} return mem_info def device_gc(): """ Ask the garbage collector to free all unlocked memory """ safe_call(backend.get().af_device_gc()) def get_device_ptr(a): """ Get the raw device pointer of an array Parameters ---------- a: af.Array - A multi dimensional arrayfire array. Returns ------- - internal device pointer held by a Note ----- - The device pointer of `a` is not freed by memory manager until `unlock_device_ptr()` is called. - This function enables the user to interoperate arrayfire with other CUDA/OpenCL/C libraries. """ ptr = ct.c_void_p(0) safe_call(backend.get().af_get_device_ptr(ct.pointer(ptr), a.arr)) return ptr def lock_device_ptr(a): """ This functions is deprecated. Please use lock_array instead. """ import warnings warnings.warn("This function is deprecated. Use lock_array instead.", DeprecationWarning) lock_array(a) def lock_array(a): """ Ask arrayfire to not perform garbage collection on raw data held by an array. Parameters ---------- a: af.Array - A multi dimensional arrayfire array. Note ----- - The device pointer of `a` is not freed by memory manager until `unlock_device_ptr()` is called. """ safe_call(backend.get().af_lock_array(a.arr)) def unlock_device_ptr(a): """ This functions is deprecated. Please use unlock_array instead. """ import warnings warnings.warn("This function is deprecated. Use unlock_array instead.", DeprecationWarning) unlock_array(a) def unlock_array(a): """ Tell arrayfire to resume garbage collection on raw data held by an array. Parameters ---------- a: af.Array - A multi dimensional arrayfire array. """ safe_call(backend.get().af_unlock_array(a.arr)) def alloc_device(num_bytes): """ Allocate a buffer on the device with specified number of bytes. """ ptr = ct.c_void_p(0) c_num_bytes = c_dim_t(num_bytes) safe_call(backend.get().af_alloc_device(ct.pointer(ptr), c_num_bytes)) return ptr.value def alloc_host(num_bytes): """ Allocate a buffer on the host with specified number of bytes. """ ptr = ct.c_void_p(0) c_num_bytes = c_dim_t(num_bytes) safe_call(backend.get().af_alloc_host(ct.pointer(ptr), c_num_bytes)) return ptr.value def alloc_pinned(num_bytes): """ Allocate a buffer on the host using pinned memory with specified number of bytes. """ ptr = ct.c_void_p(0) c_num_bytes = c_dim_t(num_bytes) safe_call(backend.get().af_alloc_pinned(ct.pointer(ptr), c_num_bytes)) return ptr.value def free_device(ptr): """ Free the device memory allocated by alloc_device """ cptr = ct.c_void_p(ptr) safe_call(backend.get().af_free_device(cptr)) def free_host(ptr): """ Free the host memory allocated by alloc_host """ cptr = ct.c_void_p(ptr) safe_call(backend.get().af_free_host(cptr)) def free_pinned(ptr): """ Free the pinned memory allocated by alloc_pinned """ cptr = ct.c_void_p(ptr) safe_call(backend.get().af_free_pinned(cptr)) from .array import Array python-arrayfire-3.3.20160624/arrayfire/features.py000066400000000000000000000043371276671162200217620ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Features class used for Computer Vision algorithms. """ from .library import * from .array import * import numbers class Features(object): """ A container class used for various feature detectors. Parameters ---------- num: optional: int. default: 0. Specifies the number of features. """ def __init__(self, num=0): self.feat = ct.c_void_p(0) if num is not None: assert(isinstance(num, numbers.Number)) safe_call(backend.get().af_create_features(ct.pointer(self.feat), c_dim_t(num))) def num_features(): """ Returns the number of features detected. """ num = c_dim_t(0) safe_call(backend.get().af_get_features_num(ct.pointer(num), self.feat)) return num def get_xpos(): """ Returns the x-positions of the features detected. """ out = Array() safe_call(backend.get().af_get_features_xpos(ct.pointer(out.arr), self.feat)) return out def get_ypos(): """ Returns the y-positions of the features detected. """ out = Array() safe_call(backend.get().af_get_features_ypos(ct.pointer(out.arr), self.feat)) return out def get_score(): """ Returns the scores of the features detected. """ out = Array() safe_call(backend.get().af_get_features_score(ct.pointer(out.arr), self.feat)) return out def get_orientation(): """ Returns the orientations of the features detected. """ out = Array() safe_call(backend.get().af_get_features_orientation(ct.pointer(out.arr), self.feat)) return out def get_size(): """ Returns the sizes of the features detected. """ out = Array() safe_call(backend.get().af_get_features_size(ct.pointer(out.arr), self.feat)) return out python-arrayfire-3.3.20160624/arrayfire/graphics.py000066400000000000000000000217611276671162200217440ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Graphics functions (plot, image, etc). """ from .library import * from .array import * from .util import _is_number class _Cell(ct.Structure): _fields_ = [("row", ct.c_int), ("col", ct.c_int), ("title", ct.c_char_p), ("cmap", ct.c_int)] def __init__(self, r, c, title, cmap): self.row = r self.col = c self.title = title if title is not None else ct.c_char_p() self.cmap = cmap.value class Window(object): """ Class to create the Window object. Parameters ---------- width: optional: int. default: 1280. - Specifies the width of the window in pixels. height: optional: int. default: 720. - Specifies the height of the window in pixels. title: optional: str. default: "ArrayFire". - Specifies the title used for the window. """ def __init__(self, width=1280, height=720, title="ArrayFire"): self._r = -1 self._c = -1 self._wnd = ct.c_void_p(0) self._cmap = COLORMAP.DEFAULT _width = 1280 if width is None else width _height = 720 if height is None else height _title = "ArrayFire" if title is None else title _title = _title.encode("ascii") safe_call(backend.get().af_create_window(ct.pointer(self._wnd), ct.c_int(_width), ct.c_int(_height), ct.c_char_p(_title))) def __del__(self): """ Destroys the window when going out of scope. """ safe_call(backend.get().af_destroy_window(self._wnd)) def set_pos(self, x, y): """ Set the position of window on the screen. Parameters ---------- x : int. Pixel offset from left. y : int. Pixel offset from top """ safe_call(backend.get().af_set_position(self._wnd, ct.c_int(x), ct.c_int(y))) def set_title(self, title): """ Set the title of the window Parameters ---------- title : str. Title used for the current window. """ safe_call(backend.get().af_set_title(self._wnd, title)) def set_colormap(self, cmap): """ Set the colormap for the window. Parameters ---------- cmap : af.COLORMAP. Set the colormap for the window. """ self._cmap = cmap def set_size(self, w, h): """ Set the windo height and width. Parameters ----------- w : int Width if window. h : int Height of window. """ safe_call(backend.get().af_set_size(self._wnd, w, h)) def image(self, img, title=None): """ Display an arrayfire array as an image. Paramters --------- img: af.Array. A 2 dimensional array for single channel image. A 3 dimensional array for 3 channel image. title: str. Title used for the image. """ _cell = _Cell(self._r, self._c, title, self._cmap) safe_call(backend.get().af_draw_image(self._wnd, img.arr, ct.pointer(_cell))) def scatter(self, X, Y, marker=MARKER.POINT, title=None): """ Renders input arrays as 2D scatter plot. Paramters --------- X: af.Array. A 1 dimensional array containing X co-ordinates. Y: af.Array. A 1 dimensional array containing Y co-ordinates. marker: af.MARKER Specifies how the points look title: str. Title used for the plot. """ _cell = _Cell(self._r, self._c, title, self._cmap) safe_call(backend.get().af_draw_scatter(self._wnd, X.arr, Y.arr, marker.value, ct.pointer(_cell))) def scatter3(self, P, marker=MARKER.POINT, title=None): """ Renders the input array as a 3D Scatter plot. Paramters --------- P: af.Array. A 2 dimensional array containing (X,Y,Z) co-ordinates. title: str. Title used for the plot. """ _cell = _Cell(self._r, self._c, title, self._cmap) safe_call(backend.get().af_draw_scatter3(self._wnd, P.arr, marker.value, ct.pointer(_cell))) def plot(self, X, Y, title=None): """ Display a 2D Plot. Paramters --------- X: af.Array. A 1 dimensional array containing X co-ordinates. Y: af.Array. A 1 dimensional array containing Y co-ordinates. title: str. Title used for the plot. """ _cell = _Cell(self._r, self._c, title, self._cmap) safe_call(backend.get().af_draw_plot(self._wnd, X.arr, Y.arr, ct.pointer(_cell))) def plot3(self, line, title=None): """ Renders the input array as a 3D line plot. Paramters --------- line: af.Array. A 2 dimensional array containing (X,Y,Z) co-ordinates. title: str. Title used for the plot. """ _cell = _Cell(self._r, self._c, title, self._cmap) safe_call(backend.get().af_draw_plot3(self._wnd, line.arr, ct.pointer(_cell))) def surface(self, x_vals, y_vals, z_vals, title=None): """ Renders the input array as a 3D surface plot. Paramters --------- x_vals: af.Array. A 1 dimensional array containing X co-ordinates. y_vals: af.Array. A 1 dimensional array containing Y co-ordinates. z_vals: af.Array. A 1 dimensional array containing Z co-ordinates. title: str. Title used for the plot. """ _cell = _Cell(self._r, self._c, title, self._cmap) safe_call(backend.get().af_draw_surface(self._wnd, x_vals.arr, y_vals.arr, z_vals.arr, ct.pointer(_cell))) def hist(self, X, min_val, max_val, title=None): """ Display a histogram Plot. Paramters --------- X: af.Array. A 1 dimensional array containing the histogram. min_val: scalar. A scalar value specifying the lower bound of the histogram. max_val: scalar. A scalar value specifying the upper bound of the histogram. title: str. Title used for the histogram. """ _cell = _Cell(self._r, self._c, title, self._cmap) safe_call(backend.get().af_draw_hist(self._wnd, X.arr, ct.c_double(max_val), ct.c_double(min_val), ct.pointer(_cell))) def grid(self, rows, cols): """ Create a grid for sub plotting within the window. Parameters ---------- rows: int. Number of rows in the grid. cols: int. Number of columns in the grid. """ safe_call(backend.get().af_grid(self._wnd, ct.c_int(rows), ct.c_int(cols))) def show(self): """ Force the window to display the contents. Note: This is only needed when using the window as a grid. """ safe_call(backend.get().af_show(self._wnd)) def close(self): """ Close the window. """ tmp = ct.c_bool(True) safe_call(backend.get().af_is_window_closed(ct.pointer(tmp), self._wnd)) return tmp def set_visibility(is_visible): """ A flag that shows or hides the window as requested. Parameters ---------- is_visible: Flag specifying the visibility of the flag. """ safe_call(backend.get().af_set_visibility(self._wnd, is_visible)) def __getitem__(self, keys): """ Get access to a specific grid location within the window. Examples -------- >>> a = af.randu(5,5) >>> b = af.randu(5,5) >>> w = af.Window() >>> w.grid(1,2) >>> w[0, 0].image(a) >>> w[0, 1].image(b) >>> w.show() """ if not isinstance(keys, tuple): raise IndexError("Window expects indexing along two dimensions") if len(keys) != 2: raise IndexError("Window expects indexing along two dimensions only") if not (_is_number(keys[0]) and _is_number(keys[1])): raise IndexError("Window expects the indices to be numbers") self._r = keys[0] self._c = keys[1] return self python-arrayfire-3.3.20160624/arrayfire/image.py000066400000000000000000001035031276671162200212210ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Image processing functions. """ from .library import * from .array import * from .data import constant import os def gradient(image): """ Find the horizontal and vertical gradients. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. Returns --------- (dx, dy) : Tuple of af.Array. - `dx` containing the horizontal gradients of `image`. - `dy` containing the vertical gradients of `image`. """ dx = Array() dy = Array() safe_call(backend.get().af_gradient(ct.pointer(dx.arr), ct.pointer(dy.arr), image.arr)) return dx, dy def load_image(file_name, is_color=False): """ Load an image on the disk as an array. Parameters ---------- file_name: str - Full path of the file name on disk. is_color : optional: bool. default: False. - Specifies if the image is loaded as 1 channel (if False) or 3 channel image (if True). Returns ------- image - af.Array A 2 dimensional (1 channel) or 3 dimensional (3 channel) array containing the image. """ assert(os.path.isfile(file_name)) image = Array() safe_call(backend.get().af_load_image(ct.pointer(image.arr), ct.c_char_p(file_name.encode('ascii')), is_color)) return image def save_image(image, file_name): """ Save an array as an image on the disk. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image. file_name: str - Full path of the file name on the disk. """ assert(isinstance(file_name, str)) safe_call(backend.get().af_save_image(ct.c_char_p(file_name.encode('ascii')), image.arr)) return image def load_image_native(file_name): """ Load an image on the disk as an array in native format. Parameters ---------- file_name: str - Full path of the file name on disk. Returns ------- image - af.Array A 2 dimensional (1 channel) or 3 dimensional (3 or 4 channel) array containing the image. """ assert(os.path.isfile(file_name)) image = Array() safe_call(backend.get().af_load_image_native(ct.pointer(image.arr), ct.c_char_p(file_name.encode('ascii')))) return image def save_image_native(image, file_name): """ Save an array as an image on the disk in native format. Parameters ---------- image : af.Array - A 2 or 3 dimensional arrayfire array representing an image. file_name: str - Full path of the file name on the disk. """ assert(isinstance(file_name, str)) safe_call(backend.get().af_save_image_native(ct.c_char_p(file_name.encode('ascii')), image.arr)) return image def resize(image, scale=None, odim0=None, odim1=None, method=INTERP.NEAREST): """ Resize an image. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. scale : optional: scalar. default: None. - Scale factor for the image resizing. odim0 : optional: int. default: None. - Size of the first dimension of the output. odim1 : optional: int. default: None. - Size of the second dimension of the output. method : optional: af.INTERP. default: af.INTERP.NEAREST. - Interpolation method used for resizing. Returns --------- out : af.Array - Output image after resizing. Note ----- - If `scale` is None, `odim0` and `odim1` need to be specified. - If `scale` is not None, `odim0` and `odim1` are ignored. """ if (scale is None): assert(odim0 is not None) assert(odim1 is not None) else: idims = image.dims() odim0 = int(scale * idims[0]) odim1 = int(scale * idims[1]) output = Array() safe_call(backend.get().af_resize(ct.pointer(output.arr), image.arr, c_dim_t(odim0), c_dim_t(odim1), method.value)) return output def transform(image, trans_mat, odim0 = 0, odim1 = 0, method=INTERP.NEAREST, is_inverse=True): """ Transform an image using a transformation matrix. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. trans_mat : af.Array - A 2 D floating point arrayfire array of size [3, 2]. odim0 : optional: int. default: 0. - Size of the first dimension of the output. odim1 : optional: int. default: 0. - Size of the second dimension of the output. method : optional: af.INTERP. default: af.INTERP.NEAREST. - Interpolation method used for transformation. is_inverse : optional: bool. default: True. - Specifies if the inverse transform is applied. Returns --------- out : af.Array - Output image after transformation. Note ----- - If `odim0` and `odim` are 0, the output dimensions are automatically calculated by the function. """ output = Array() safe_call(backend.get().af_transform(ct.pointer(output.arr), image.arr, trans_mat.arr, c_dim_t(odim0), c_dim_t(odim1), method.value, is_inverse)) return output def rotate(image, theta, is_crop = True, method = INTERP.NEAREST): """ Rotate an image. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. theta : scalar - The angle to rotate in radians. is_crop : optional: bool. default: True. - Specifies if the output should be cropped to the input size. method : optional: af.INTERP. default: af.INTERP.NEAREST. - Interpolation method used for rotating. Returns --------- out : af.Array - Output image after rotating. """ output = Array() safe_call(backend.get().af_rotate(ct.pointer(output.arr), image.arr, ct.c_float(theta), is_crop, method.value)) return output def translate(image, trans0, trans1, odim0 = 0, odim1 = 0, method = INTERP.NEAREST): """ Translate an image. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. trans0: int. - Translation along first dimension in pixels. trans1: int. - Translation along second dimension in pixels. odim0 : optional: int. default: 0. - Size of the first dimension of the output. odim1 : optional: int. default: 0. - Size of the second dimension of the output. method : optional: af.INTERP. default: af.INTERP.NEAREST. - Interpolation method used for translation. Returns --------- out : af.Array - Output image after translation. Note ----- - If `odim0` and `odim` are 0, the output dimensions are automatically calculated by the function. """ output = Array() safe_call(backend.get().af_translate(ct.pointer(output.arr), image.arr, trans0, trans1, c_dim_t(odim0), c_dim_t(odim1), method.value)) return output def scale(image, scale0, scale1, odim0 = 0, odim1 = 0, method = INTERP.NEAREST): """ Scale an image. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. scale0 : scalar. - Scale factor for the first dimension. scale1 : scalar. - Scale factor for the second dimension. odim0 : optional: int. default: None. - Size of the first dimension of the output. odim1 : optional: int. default: None. - Size of the second dimension of the output. method : optional: af.INTERP. default: af.INTERP.NEAREST. - Interpolation method used for resizing. Returns --------- out : af.Array - Output image after scaling. Note ----- - If `odim0` and `odim` are 0, the output dimensions are automatically calculated by the function. """ output = Array() safe_call(backend.get().af_scale(ct.pointer(output.arr), image.arr, ct.c_float(scale0), ct.c_float(scale1), c_dim_t(odim0), c_dim_t(odim1), method.value)) return output def skew(image, skew0, skew1, odim0 = 0, odim1 = 0, method = INTERP.NEAREST, is_inverse=True): """ Skew an image. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. skew0 : scalar. - Skew factor for the first dimension. skew1 : scalar. - Skew factor for the second dimension. odim0 : optional: int. default: None. - Size of the first dimension of the output. odim1 : optional: int. default: None. - Size of the second dimension of the output. method : optional: af.INTERP. default: af.INTERP.NEAREST. - Interpolation method used for resizing. is_inverse : optional: bool. default: True. - Specifies if the inverse skew is applied. Returns --------- out : af.Array - Output image after skewing. Note ----- - If `odim0` and `odim` are 0, the output dimensions are automatically calculated by the function. """ output = Array() safe_call(backend.get().af_skew(ct.pointer(output.arr), image.arr, ct.c_float(skew0), ct.c_float(skew1), c_dim_t(odim0), c_dim_t(odim1), method.value, is_inverse)) return output def histogram(image, nbins, min_val = None, max_val = None): """ Find the histogram of an image. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. nbins : int. - Number of bins in the histogram. min_val : optional: scalar. default: None. - The lower bound for the bin values. - If None, `af.min(image)` is used. max_val : optional: scalar. default: None. - The upper bound for the bin values. - If None, `af.max(image)` is used. Returns --------- hist : af.Array - Containing the histogram of the image. """ from .algorithm import min as af_min from .algorithm import max as af_max if min_val is None: min_val = af_min(image) if max_val is None: max_val = af_max(image) output = Array() safe_call(backend.get().af_histogram(ct.pointer(output.arr), image.arr, ct.c_uint(nbins), ct.c_double(min_val), ct.c_double(max_val))) return output def hist_equal(image, hist): """ Equalize an image based on a histogram. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. hist : af.Array - Containing the histogram of an image. Returns --------- output : af.Array - The equalized image. """ output = Array() safe_call(backend.get().af_hist_equal(ct.pointer(output.arr), image.arr, hist.arr)) return output def dilate(image, mask = None): """ Run image dilate on the image. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. mask : optional: af.Array. default: None. - Specifies the neighborhood of a pixel. - When None, a [3, 3] array of all ones is used. Returns --------- output : af.Array - The dilated image. """ if mask is None: mask = constant(1, 3, 3, dtype=Dtype.f32) output = Array() safe_call(backend.get().af_dilate(ct.pointer(output.arr), image.arr, mask.arr)) return output def dilate3(volume, mask = None): """ Run volume dilate on a volume. Parameters ---------- volume : af.Array - A 3 D arrayfire array representing a volume, or - A multi dimensional array representing batch of volumes. mask : optional: af.Array. default: None. - Specifies the neighborhood of a pixel. - When None, a [3, 3, 3] array of all ones is used. Returns --------- output : af.Array - The dilated volume. """ if mask is None: mask = constant(1, 3, 3, 3, dtype=Dtype.f32) output = Array() safe_call(backend.get().af_dilate3(ct.pointer(output.arr), volume.arr, mask.arr)) return output def erode(image, mask = None): """ Run image erode on the image. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. mask : optional: af.Array. default: None. - Specifies the neighborhood of a pixel. - When None, a [3, 3] array of all ones is used. Returns --------- output : af.Array - The eroded image. """ if mask is None: mask = constant(1, 3, 3, dtype=Dtype.f32) output = Array() safe_call(backend.get().af_erode(ct.pointer(output.arr), image.arr, mask.arr)) return output def erode3(volume, mask = None): """ Run volume erode on the volume. Parameters ---------- volume : af.Array - A 3 D arrayfire array representing an volume, or - A multi dimensional array representing batch of volumes. mask : optional: af.Array. default: None. - Specifies the neighborhood of a pixel. - When None, a [3, 3, 3] array of all ones is used. Returns --------- output : af.Array - The eroded volume. """ if mask is None: mask = constant(1, 3, 3, 3, dtype=Dtype.f32) output = Array() safe_call(backend.get().af_erode3(ct.pointer(output.arr), volume.arr, mask.arr)) return output def bilateral(image, s_sigma, c_sigma, is_color = False): """ Apply bilateral filter to the image. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. s_sigma : scalar. - Sigma value for the co-ordinate space. c_sigma : scalar. - Sigma value for the color space. is_color : optional: bool. default: False. - Specifies if the third dimension is 3rd channel (if True) or a batch (if False). Returns --------- output : af.Array - The image after the application of the bilateral filter. """ output = Array() safe_call(backend.get().af_bilateral(ct.pointer(output.arr), image.arr, ct.c_float(s_sigma), ct.c_float(c_sigma), is_color)) return output def mean_shift(image, s_sigma, c_sigma, n_iter, is_color = False): """ Apply mean shift to the image. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. s_sigma : scalar. - Sigma value for the co-ordinate space. c_sigma : scalar. - Sigma value for the color space. n_iter : int. - Number of mean shift iterations. is_color : optional: bool. default: False. - Specifies if the third dimension is 3rd channel (if True) or a batch (if False). Returns --------- output : af.Array - The image after the application of the meanshift. """ output = Array() safe_call(backend.get().af_mean_shift(ct.pointer(output.arr), image.arr, ct.c_float(s_sigma), ct.c_float(c_sigma), ct.c_uint(n_iter), is_color)) return output def medfilt(image, w0 = 3, w1 = 3, edge_pad = PAD.ZERO): """ Apply median filter for the image. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. w0 : optional: int. default: 3. - The length of the filter along the first dimension. w1 : optional: int. default: 3. - The length of the filter along the second dimension. edge_pad : optional: af.PAD. default: af.PAD.ZERO - Flag specifying how the median at the edge should be treated. Returns --------- output : af.Array - The image after median filter is applied. """ output = Array() safe_call(backend.get().af_medfilt(ct.pointer(output.arr), image.arr, c_dim_t(w0), c_dim_t(w1), edge_pad.value)) return output def minfilt(image, w_len = 3, w_wid = 3, edge_pad = PAD.ZERO): """ Apply min filter for the image. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. w0 : optional: int. default: 3. - The length of the filter along the first dimension. w1 : optional: int. default: 3. - The length of the filter along the second dimension. edge_pad : optional: af.PAD. default: af.PAD.ZERO - Flag specifying how the min at the edge should be treated. Returns --------- output : af.Array - The image after min filter is applied. """ output = Array() safe_call(backend.get().af_minfilt(ct.pointer(output.arr), image.arr, c_dim_t(w_len), c_dim_t(w_wid), edge_pad.value)) return output def maxfilt(image, w_len = 3, w_wid = 3, edge_pad = PAD.ZERO): """ Apply max filter for the image. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. w0 : optional: int. default: 3. - The length of the filter along the first dimension. w1 : optional: int. default: 3. - The length of the filter along the second dimension. edge_pad : optional: af.PAD. default: af.PAD.ZERO - Flag specifying how the max at the edge should be treated. Returns --------- output : af.Array - The image after max filter is applied. """ output = Array() safe_call(backend.get().af_maxfilt(ct.pointer(output.arr), image.arr, c_dim_t(w_len), c_dim_t(w_wid), edge_pad.value)) return output def regions(image, conn = CONNECTIVITY.FOUR, out_type = Dtype.f32): """ Find the connected components in the image. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image. conn : optional: af.CONNECTIVITY. default: af.CONNECTIVITY.FOUR. - Specifies the connectivity of the pixels. out_type : optional: af.Dtype. default: af.Dtype.f32. - Specifies the type for the output. Returns --------- output : af.Array - An array where each pixel is labeled with its component number. """ output = Array() safe_call(backend.get().af_regions(ct.pointer(output.arr), image.arr, conn.value, out_type.value)) return output def sobel_derivatives(image, w_len=3): """ Find the sobel derivatives of the image. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. w_len : optional: int. default: 3. - The size of the sobel operator. Returns --------- (dx, dy) : tuple of af.Arrays. - `dx` is the sobel derivative along the horizontal direction. - `dy` is the sobel derivative along the vertical direction. """ dx = Array() dy = Array() safe_call(backend.get().af_sobel_operator(ct.pointer(dx.arr), ct.pointer(dy.arr), image.arr, ct.c_uint(w_len))) return dx,dy def gaussian_kernel(rows, cols, sigma_r = None, sigma_c = None): """ Create a gaussian kernel with the given parameters. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. rows : int - The number of rows in the gaussian kernel. cols : int - The number of columns in the gaussian kernel. sigma_r : optional: number. default: None. - The sigma value along rows - If None, calculated as (0.25 * rows + 0.75) sigma_c : optional: number. default: None. - The sigma value along columns - If None, calculated as (0.25 * cols + 0.75) Returns ------- out : af.Array - A gaussian kernel of size (rows, cols) """ out = Array() if (sigma_r is None): sigma_r = 0.25 * rows + 0.75 if (sigma_c is None): sigma_c = 0.25 * cols + 0.75 safe_call(backend.get().af_gaussian_kernel(ct.pointer(out.arr), ct.c_int(rows), ct.c_int(cols), ct.c_double(sigma_r), ct.c_double(sigma_c))) return out def sobel_filter(image, w_len = 3, is_fast = False): """ Apply sobel filter to the image. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. w_len : optional: int. default: 3. - The size of the sobel operator. is_fast : optional: bool. default: False. - Specifies if the magnitude is generated using SAD (if True) or SSD (if False). Returns --------- output : af.Array - Image containing the magnitude of the sobel derivatives. """ from .arith import abs as af_abs from .arith import hypot as af_hypot dx,dy = sobel_derivatives(image, w_len) if (is_fast): return af_abs(dx) + af_abs(dy) else: return af_hypot(dx, dy) def rgb2gray(image, r_factor = 0.2126, g_factor = 0.7152, b_factor = 0.0722): """ Convert RGB image to Grayscale. Parameters ---------- image : af.Array - A 3 D arrayfire array representing an 3 channel image, or - A multi dimensional array representing batch of images. r_factor : optional: scalar. default: 0.2126. - Weight for the red channel. g_factor : optional: scalar. default: 0.7152. - Weight for the green channel. b_factor : optional: scalar. default: 0.0722. - Weight for the blue channel. Returns -------- output : af.Array - A grayscale image. """ output=Array() safe_call(backend.get().af_rgb2gray(ct.pointer(output.arr), image.arr, ct.c_float(r_factor), ct.c_float(g_factor), ct.c_float(b_factor))) return output def gray2rgb(image, r_factor = 1.0, g_factor = 1.0, b_factor = 1.0): """ Convert Grayscale image to an RGB image. Parameters ---------- image : af.Array - A 2 D arrayfire array representing an image, or - A multi dimensional array representing batch of images. r_factor : optional: scalar. default: 1.0. - Scale factor for the red channel. g_factor : optional: scalar. default: 1.0. - Scale factor for the green channel. b_factor : optional: scalar. default: 1.0 - Scale factor for the blue channel. Returns -------- output : af.Array - An RGB image. - The channels are not coalesced, i.e. they appear along the third dimension. """ output=Array() safe_call(backend.get().af_gray2rgb(ct.pointer(output.arr), image.arr, ct.c_float(r_factor), ct.c_float(g_factor), ct.c_float(b_factor))) return output def hsv2rgb(image): """ Convert HSV image to RGB. Parameters ---------- image : af.Array - A 3 D arrayfire array representing an 3 channel image, or - A multi dimensional array representing batch of images. Returns -------- output : af.Array - A HSV image. """ output = Array() safe_call(backend.get().af_hsv2rgb(ct.pointer(output.arr), image.arr)) return output def rgb2hsv(image): """ Convert RGB image to HSV. Parameters ---------- image : af.Array - A 3 D arrayfire array representing an 3 channel image, or - A multi dimensional array representing batch of images. Returns -------- output : af.Array - A RGB image. """ output = Array() safe_call(backend.get().af_rgb2hsv(ct.pointer(output.arr), image.arr)) return output def color_space(image, to_type, from_type): """ Convert an image from one color space to another. Parameters ---------- image : af.Array - A multi dimensional array representing batch of images in `from_type` color space. to_type : af.CSPACE - An enum for the destination color space. from_type : af.CSPACE - An enum for the source color space. Returns -------- output : af.Array - An image in the `to_type` color space. """ output = Array() safe_call(backend.get().af_color_space(ct.pointer(output.arr), image.arr, to_type.value, from_type.value)) return output def unwrap(image, wx, wy, sx, sy, px=0, py=0, is_column=True): """ Unrwap an image into an array. Parameters ---------- image : af.Array A multi dimensional array specifying an image or batch of images. wx : Integer. Block window size along the first dimension. wy : Integer. Block window size along the second dimension. sx : Integer. Stride along the first dimension. sy : Integer. Stride along the second dimension. px : Integer. Optional. Default: 0 Padding along the first dimension. py : Integer. Optional. Default: 0 Padding along the second dimension. is_column : Boolean. Optional. Default: True. Specifies if the patch should be laid along row or columns. Returns ------- out : af.Array A multi dimensional array contianing the image patches along specified dimension. Examples -------- >>> import arrayfire as af >>> a = af.randu(6, 6) >>> af.display(a) [6 6 1 1] 0.4107 0.3775 0.0901 0.8060 0.0012 0.9250 0.8224 0.3027 0.5933 0.5938 0.8703 0.3063 0.9518 0.6456 0.1098 0.8395 0.5259 0.9313 0.1794 0.5591 0.1046 0.1933 0.1443 0.8684 0.4198 0.6600 0.8827 0.7270 0.3253 0.6592 0.0081 0.0764 0.1647 0.0322 0.5081 0.4387 >>> b = af.unwrap(a, 2, 2, 2, 2) >>> af.display(b) [4 9 1 1] 0.4107 0.9518 0.4198 0.0901 0.1098 0.8827 0.0012 0.5259 0.3253 0.8224 0.1794 0.0081 0.5933 0.1046 0.1647 0.8703 0.1443 0.5081 0.3775 0.6456 0.6600 0.8060 0.8395 0.7270 0.9250 0.9313 0.6592 0.3027 0.5591 0.0764 0.5938 0.1933 0.0322 0.3063 0.8684 0.4387 """ out = Array() safe_call(backend.get().af_unwrap(ct.pointer(out.arr), image.arr, c_dim_t(wx), c_dim_t(wy), c_dim_t(sx), c_dim_t(sy), c_dim_t(px), c_dim_t(py), is_column)) return out def wrap(a, ox, oy, wx, wy, sx, sy, px=0, py=0, is_column=True): """ Wrap an array into an image. Parameters ---------- a : af.Array A multi dimensional array containing patches of images. wx : Integer. Block window size along the first dimension. wy : Integer. Block window size along the second dimension. sx : Integer. Stride along the first dimension. sy : Integer. Stride along the second dimension. px : Integer. Optional. Default: 0 Padding along the first dimension. py : Integer. Optional. Default: 0 Padding along the second dimension. is_column : Boolean. Optional. Default: True. Specifies if the patch should be laid along row or columns. Returns ------- out : af.Array A multi dimensional array contianing the images. Examples -------- >>> import arrayfire as af >>> a = af.randu(6, 6) >>> af.display(a) [6 6 1 1] 0.4107 0.3775 0.0901 0.8060 0.0012 0.9250 0.8224 0.3027 0.5933 0.5938 0.8703 0.3063 0.9518 0.6456 0.1098 0.8395 0.5259 0.9313 0.1794 0.5591 0.1046 0.1933 0.1443 0.8684 0.4198 0.6600 0.8827 0.7270 0.3253 0.6592 0.0081 0.0764 0.1647 0.0322 0.5081 0.4387 >>> b = af.unwrap(a, 2, 2, 2, 2) >>> af.display(b) [4 9 1 1] 0.4107 0.9518 0.4198 0.0901 0.1098 0.8827 0.0012 0.5259 0.3253 0.8224 0.1794 0.0081 0.5933 0.1046 0.1647 0.8703 0.1443 0.5081 0.3775 0.6456 0.6600 0.8060 0.8395 0.7270 0.9250 0.9313 0.6592 0.3027 0.5591 0.0764 0.5938 0.1933 0.0322 0.3063 0.8684 0.4387 >>> af.display(c) [6 6 1 1] 0.4107 0.3775 0.0901 0.8060 0.0012 0.9250 0.8224 0.3027 0.5933 0.5938 0.8703 0.3063 0.9518 0.6456 0.1098 0.8395 0.5259 0.9313 0.1794 0.5591 0.1046 0.1933 0.1443 0.8684 0.4198 0.6600 0.8827 0.7270 0.3253 0.6592 0.0081 0.0764 0.1647 0.0322 0.5081 0.4387 """ out = Array() safe_call(backend.get().af_wrap(ct.pointer(out.arr), a.arr, c_dim_t(ox), c_dim_t(oy), c_dim_t(wx), c_dim_t(wy), c_dim_t(sx), c_dim_t(sy), c_dim_t(px), c_dim_t(py), is_column)) return out def sat(image): """ Summed Area Tables Parameters ---------- image : af.Array A multi dimensional array specifying image or batch of images Returns ------- out : af.Array A multi dimensional array containing the summed area table of input image """ out = Array() safe_call(backend.get().af_sat(ct.pointer(out.arr), image.arr)) return out def ycbcr2rgb(image, standard=YCC_STD.BT_601): """ YCbCr to RGB colorspace conversion. Parameters ---------- image : af.Array A multi dimensional array containing an image or batch of images in YCbCr format. standard: YCC_STD. optional. default: YCC_STD.BT_601 - Specifies the YCbCr format. - Can be one of YCC_STD.BT_601, YCC_STD.BT_709, and YCC_STD.BT_2020. Returns -------- out : af.Array A multi dimensional array containing an image or batch of images in RGB format """ out = Array() safe_call(backend.get().af_ycbcr2rgb(ct.pointer(out.arr), image.arr, standard.value)) return out def rgb2ycbcr(image, standard=YCC_STD.BT_601): """ RGB to YCbCr colorspace conversion. Parameters ---------- image : af.Array A multi dimensional array containing an image or batch of images in RGB format. standard: YCC_STD. optional. default: YCC_STD.BT_601 - Specifies the YCbCr format. - Can be one of YCC_STD.BT_601, YCC_STD.BT_709, and YCC_STD.BT_2020. Returns -------- out : af.Array A multi dimensional array containing an image or batch of images in YCbCr format """ out = Array() safe_call(backend.get().af_rgb2ycbcr(ct.pointer(out.arr), image.arr, standard.value)) return out def is_image_io_available(): """ Function to check if the arrayfire library was built with Image IO support. """ res = ct.c_bool(False) safe_call(backend.get().af_is_image_io_available(ct.pointer(res))) return res.value python-arrayfire-3.3.20160624/arrayfire/index.py000066400000000000000000000131431276671162200212460ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Index and Seq classes used in indexing operations. """ from .library import * from .util import * from .util import _is_number from .base import * from .bcast import _bcast_var import math class Seq(ct.Structure): """ arrayfire equivalent of slice Attributes ---------- begin: number Start of the sequence. end : number End of sequence. step : number Step size. Parameters ---------- S: slice or number. """ _fields_ = [("begin", ct.c_double), ("end" , ct.c_double), ("step" , ct.c_double)] def __init__ (self, S): self.begin = ct.c_double( 0) self.end = ct.c_double(-1) self.step = ct.c_double( 1) if _is_number(S): self.begin = ct.c_double(S) self.end = ct.c_double(S) elif isinstance(S, slice): if (S.step is not None): self.step = ct.c_double(S.step) if(S.step < 0): self.begin, self.end = self.end, self.begin if (S.start is not None): self.begin = ct.c_double(S.start) if (S.stop is not None): self.end = ct.c_double(S.stop - math.copysign(1, self.step)) else: raise IndexError("Invalid type while indexing arrayfire.array") class ParallelRange(Seq): """ Class used to parallelize for loop. Inherits from Seq. Attributes ---------- S: slice Parameters ---------- start: number Beginning of parallel range. stop : number End of parallel range. step : number Step size for parallel range. Examples -------- >>> import arrayfire as af >>> a = af.randu(3, 3) >>> b = af.randu(3, 1) >>> c = af.constant(0, 3, 3) >>> for ii in af.ParallelRange(3): ... c[:, ii] = a[:, ii] + b ... >>> af.display(a) [3 3 1 1] 0.4107 0.1794 0.3775 0.8224 0.4198 0.3027 0.9518 0.0081 0.6456 >>> af.display(b) [3 1 1 1] 0.7269 0.7104 0.5201 >>> af.display(c) [3 3 1 1] 1.1377 0.9063 1.1045 1.5328 1.1302 1.0131 1.4719 0.5282 1.1657 """ def __init__(self, start, stop=None, step=None): if (stop is None): stop = start start = 0 self.S = slice(start, stop, step) super(ParallelRange, self).__init__(self.S) def __iter__(self): return self def next(self): """ Function called by the iterator in Python 2 """ if _bcast_var.get() is True: _bcast_var.toggle() raise StopIteration else: _bcast_var.toggle() return self def __next__(self): """ Function called by the iterator in Python 3 """ return self.next() class _uidx(ct.Union): _fields_ = [("arr", ct.c_void_p), ("seq", Seq)] class Index(ct.Structure): _fields_ = [("idx", _uidx), ("isSeq", ct.c_bool), ("isBatch", ct.c_bool)] """ Container for the index class in arrayfire C library Attributes ---------- idx.arr: ctypes.c_void_p - Default 0 idx.seq: af.Seq - Default af.Seq(0, -1, 1) isSeq : bool - Default True isBatch : bool - Default False Parameters ----------- idx: key - If of type af.Array, self.idx.arr = idx, self.isSeq = False - If of type af.ParallelRange, self.idx.seq = idx, self.isBatch = True - Default:, self.idx.seq = af.Seq(idx) Note ---- Implemented for internal use only. Use with extreme caution. """ def __init__ (self, idx): self.idx = _uidx() self.isBatch = False self.isSeq = True if isinstance(idx, BaseArray): arr = ct.c_void_p(0) if (idx.type() == Dtype.b8.value): safe_call(backend.get().af_where(ct.pointer(arr), idx.arr)) else: safe_call(backend.get().af_retain_array(ct.pointer(arr), idx.arr)) self.idx.arr = arr self.isSeq = False elif isinstance(idx, ParallelRange): self.idx.seq = idx self.isBatch = True else: self.idx.seq = Seq(idx) def __del__(self): if not self.isSeq: # ctypes field variables are automatically # converted to basic C types so we have to # build the void_p from the value again. arr = ct.c_void_p(self.idx.arr) backend.get().af_release_array(arr) class _Index4(object): def __init__(self, idx0, idx1, idx2, idx3): index_vec = Index * 4 self.array = index_vec(idx0, idx1, idx2, idx3) # Do not lose those idx as self.array keeps # no reference to them. Otherwise the destructor # is prematurely called self.idxs = [idx0,idx1,idx2,idx3] @property def pointer(self): return ct.pointer(self.array) def __getitem__(self, idx): return self.array[idx] def __setitem__(self, idx, value): self.array[idx] = value self.idxs[idx] = value python-arrayfire-3.3.20160624/arrayfire/interop.py000066400000000000000000000160761276671162200216270ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Interop with other python packages. This module provides interoperability with the following python packages. 1. numpy 2. pycuda 3. pyopencl """ from .array import * from .device import * try: import numpy as np from numpy import ndarray as NumpyArray from .data import reorder AF_NUMPY_FOUND=True def np_to_af_array(np_arr): """ Convert numpy.ndarray to arrayfire.Array. Parameters ---------- np_arr : numpy.ndarray() Returns --------- af_arr : arrayfire.Array() """ in_shape = np_arr.shape in_ptr = np_arr.ctypes.data_as(ct.c_void_p) in_dtype = np_arr.dtype.char if (np_arr.flags['F_CONTIGUOUS']): return Array(in_ptr, in_shape, in_dtype) elif (np_arr.flags['C_CONTIGUOUS']): if np_arr.ndim == 1: return Array(in_ptr, in_shape, in_dtype) elif np_arr.ndim == 2: shape = (in_shape[1], in_shape[0]) res = Array(in_ptr, shape, in_dtype) return reorder(res, 1, 0) elif np_arr.ndim == 3: shape = (in_shape[2], in_shape[1], in_shape[0]) res = Array(in_ptr, shape, in_dtype) return reorder(res, 2, 1, 0) elif np_arr.ndim == 4: shape = (in_shape[3], in_shape[2], in_shape[1], in_shape[0]) res = Array(in_ptr, shape, in_dtype) return reorder(res, 3, 2, 1, 0) else: raise RuntimeError("Unsupported ndim") else: return np_to_af_array(np.asfortranarray(np_arr)) from_ndarray = np_to_af_array except: AF_NUMPY_FOUND=False try: import pycuda.gpuarray from pycuda.gpuarray import GPUArray as CudaArray AF_PYCUDA_FOUND=True def pycuda_to_af_array(pycu_arr): """ Convert pycuda.gpuarray to arrayfire.Array Parameters ----------- pycu_arr : pycuda.GPUArray() Returns ---------- af_arr : arrayfire.Array() Note ---------- The input array is copied to af.Array """ in_ptr = pycu_arr.ptr in_shape = pycu_arr.shape in_dtype = pycu_arr.dtype.char if (pycu_arr.flags.f_contiguous): res = Array(in_ptr, in_shape, in_dtype, is_device=True) lock_array(res) res = res.copy() return res elif (pycu_arr.flags.c_contiguous): if pycu_arr.ndim == 1: return Array(in_ptr, in_shape, in_dtype, is_device=True) elif pycu_arr.ndim == 2: shape = (in_shape[1], in_shape[0]) res = Array(in_ptr, shape, in_dtype, is_device=True) lock_array(res) return reorder(res, 1, 0) elif pycu_arr.ndim == 3: shape = (in_shape[2], in_shape[1], in_shape[0]) res = Array(in_ptr, shape, in_dtype, is_device=True) lock_array(res) return reorder(res, 2, 1, 0) elif pycu_arr.ndim == 4: shape = (in_shape[3], in_shape[2], in_shape[1], in_shape[0]) res = Array(in_ptr, shape, in_dtype, is_device=True) lock_array(res) return reorder(res, 3, 2, 1, 0) else: raise RuntimeError("Unsupported ndim") else: return pycuda_to_af_array(pycu_arr.copy()) except: AF_PYCUDA_FOUND=False try: from pyopencl.array import Array as OpenclArray from .opencl import add_device_context as _add_device_context from .opencl import set_device_context as _set_device_context from .opencl import get_device_id as _get_device_id from .opencl import get_context as _get_context AF_PYOPENCL_FOUND=True def pyopencl_to_af_array(pycl_arr): """ Convert pyopencl.gpuarray to arrayfire.Array Parameters ----------- pycl_arr : pyopencl.Array() Returns ---------- af_arr : arrayfire.Array() Note ---------- The input array is copied to af.Array """ ctx = pycl_arr.context.int_ptr que = pycl_arr.queue.int_ptr dev = pycl_arr.queue.device.int_ptr dev_idx = None ctx_idx = None for n in range(get_device_count()): set_device(n) dev_idx = _get_device_id() ctx_idx = _get_context() if (dev_idx == dev and ctx_idx == ctx): break if (dev_idx == None or ctx_idx == None or dev_idx != dev or ctx_idx != ctx): _add_device_context(dev, ctx, que) _set_device_context(dev, ctx) in_ptr = pycl_arr.base_data.int_ptr in_shape = pycl_arr.shape in_dtype = pycl_arr.dtype.char if (pycl_arr.flags.f_contiguous): res = Array(in_ptr, in_shape, in_dtype, is_device=True) lock_array(res) return res elif (pycl_arr.flags.c_contiguous): if pycl_arr.ndim == 1: return Array(in_ptr, in_shape, in_dtype, is_device=True) elif pycl_arr.ndim == 2: shape = (in_shape[1], in_shape[0]) res = Array(in_ptr, shape, in_dtype, is_device=True) lock_array(res) return reorder(res, 1, 0) elif pycl_arr.ndim == 3: shape = (in_shape[2], in_shape[1], in_shape[0]) res = Array(in_ptr, shape, in_dtype, is_device=True) lock_array(res) return reorder(res, 2, 1, 0) elif pycl_arr.ndim == 4: shape = (in_shape[3], in_shape[2], in_shape[1], in_shape[0]) res = Array(in_ptr, shape, in_dtype, is_device=True) lock_array(res) return reorder(res, 3, 2, 1, 0) else: raise RuntimeError("Unsupported ndim") else: return pyopencl_to_af_array(pycl_arr.copy()) except: AF_PYOPENCL_FOUND=False def to_array(in_array): """ Helper function to convert input from a different module to af.Array Parameters ------------- in_array : array like object Can be one of numpy.ndarray, pycuda.GPUArray, pyopencl.Array, array.array, list Returns -------------- af.Array of same dimensions as input after copying the data from the input """ if AF_NUMPY_FOUND and isinstance(in_array, NumpyArray): return np_to_af_array(in_array) if AF_PYCUDA_FOUND and isinstance(in_array, CudaArray): return pycuda_to_af_array(in_array) if AF_PYOPENCL_FOUND and isinstance(in_array, OpenclArray): return pyopencl_to_af_array(in_array) return Array(src=in_array) python-arrayfire-3.3.20160624/arrayfire/lapack.py000066400000000000000000000236541276671162200214020ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Dense Linear Algebra functions (solve, inverse, etc). """ from .library import * from .array import * def lu(A): """ LU decomposition. Parameters ---------- A: af.Array A 2 dimensional arrayfire array. Returns ------- (L,U,P): tuple of af.Arrays - L - Lower triangular matrix. - U - Upper triangular matrix. - P - Permutation array. Note ---- The original matrix `A` can be reconstructed using the outputs in the following manner. >>> A[P, :] = af.matmul(L, U) """ L = Array() U = Array() P = Array() safe_call(backend.get().af_lu(ct.pointer(L.arr), ct.pointer(U.arr), ct.pointer(P.arr), A.arr)) return L,U,P def lu_inplace(A, pivot="lapack"): """ In place LU decomposition. Parameters ---------- A: af.Array - a 2 dimensional arrayfire array on entry. - Contains L in the lower triangle on exit. - Contains U in the upper triangle on exit. Returns ------- P: af.Array - Permutation array. Note ---- This function is primarily used with `af.solve_lu` to reduce computations. """ P = Array() is_pivot_lapack = False if (pivot == "full") else True safe_call(backend.get().af_lu_inplace(ct.pointer(P.arr), A.arr, is_pivot_lapack)) return P def qr(A): """ QR decomposition. Parameters ---------- A: af.Array A 2 dimensional arrayfire array. Returns ------- (Q,R,T): tuple of af.Arrays - Q - Orthogonal matrix. - R - Upper triangular matrix. - T - Vector containing additional information to solve a least squares problem. Note ---- The outputs of this funciton have the following properties. >>> A = af.matmul(Q, R) >>> I = af.matmulNT(Q, Q) # Identity matrix """ Q = Array() R = Array() T = Array() safe_call(backend.get().af_lu(ct.pointer(Q.arr), ct.pointer(R.arr), ct.pointer(T.arr), A.arr)) return Q,R,T def qr_inplace(A): """ In place QR decomposition. Parameters ---------- A: af.Array - a 2 dimensional arrayfire array on entry. - Packed Q and R matrices on exit. Returns ------- T: af.Array - Vector containing additional information to solve a least squares problem. Note ---- This function is used to save space only when `R` is required. """ T = Array() safe_call(backend.get().af_qr_inplace(ct.pointer(T.arr), A.arr)) return T def cholesky(A, is_upper=True): """ Cholesky decomposition Parameters ---------- A: af.Array A 2 dimensional, symmetric, positive definite matrix. is_upper: optional: bool. default: True Specifies if output `R` is upper triangular (if True) or lower triangular (if False). Returns ------- (R,info): tuple of af.Array, int. - R - triangular matrix. - info - 0 if decomposition sucessful. Note ---- The original matrix `A` can be reconstructed using the outputs in the following manner. >>> A = af.matmulNT(R, R) #if R is upper triangular """ R = Array() info = ct.c_int(0) safe_call(backend.get().af_cholesky(ct.pointer(R.arr), ct.pointer(info), A.arr, is_upper)) return R, info.value def cholesky_inplace(A, is_upper=True): """ In place Cholesky decomposition. Parameters ---------- A: af.Array - a 2 dimensional, symmetric, positive definite matrix. - Trinangular matrix on exit. is_upper: optional: bool. default: True. Specifies if output `R` is upper triangular (if True) or lower triangular (if False). Returns ------- info : int. 0 if decomposition sucessful. """ info = ct.c_int(0) safe_call(backend.get().af_cholesky_inplace(ct.pointer(info), A.arr, is_upper)) return info.value def solve(A, B, options=MATPROP.NONE): """ Solve a system of linear equations. Parameters ---------- A: af.Array A 2 dimensional arrayfire array representing the coefficients of the system. B: af.Array A 1 or 2 dimensional arrayfire array representing the constants of the system. options: optional: af.MATPROP. default: af.MATPROP.NONE. - Additional options to speed up computations. - Currently needs to be one of `af.MATPROP.NONE`, `af.MATPROP.LOWER`, `af.MATPROP.UPPER`. Returns ------- X: af.Array A 1 or 2 dimensional arrayfire array representing the unknowns in the system. """ X = Array() safe_call(backend.get().af_solve(ct.pointer(X.arr), A.arr, B.arr, options.value)) return X def solve_lu(A, P, B, options=MATPROP.NONE): """ Solve a system of linear equations, using LU decomposition. Parameters ---------- A: af.Array - A 2 dimensional arrayfire array representing the coefficients of the system. - This matrix should be decomposed previously using `lu_inplace(A)`. P: af.Array - Permutation array. - This array is the output of an earlier call to `lu_inplace(A)` B: af.Array A 1 or 2 dimensional arrayfire array representing the constants of the system. Returns ------- X: af.Array A 1 or 2 dimensional arrayfire array representing the unknowns in the system. """ X = Array() safe_call(backend.get().af_solve_lu(ct.pointer(X.arr), A.arr, P.arr, B.arr, options.value)) return X def inverse(A, options=MATPROP.NONE): """ Invert a matrix. Parameters ---------- A: af.Array - A 2 dimensional arrayfire array options: optional: af.MATPROP. default: af.MATPROP.NONE. - Additional options to speed up computations. - Currently needs to be one of `af.MATPROP.NONE`. Returns ------- AI: af.Array - A 2 dimensional array that is the inverse of `A` Note ---- `A` needs to be a square matrix. """ AI = Array() safe_call(backend.get().af_inverse(ct.pointer(AI.arr), A.arr, options.value)) return AI def rank(A, tol=1E-5): """ Rank of a matrix. Parameters ---------- A: af.Array - A 2 dimensional arrayfire array tol: optional: scalar. default: 1E-5. - Tolerance for calculating rank Returns ------- r: int - Rank of `A` within the given tolerance """ r = ct.c_uint(0) safe_call(backend.get().af_rank(ct.pointer(r), A.arr, ct.c_double(tol))) return r.value def det(A): """ Determinant of a matrix. Parameters ---------- A: af.Array - A 2 dimensional arrayfire array Returns ------- res: scalar - Determinant of the matrix. """ re = ct.c_double(0) im = ct.c_double(0) safe_call(backend.get().af_det(ct.pointer(re), ct.pointer(im), A.arr)) re = re.value im = im.value return re if (im == 0) else re + im * 1j def norm(A, norm_type=NORM.EUCLID, p=1.0, q=1.0): """ Norm of an array or a matrix. Parameters ---------- A: af.Array - A 1 or 2 dimensional arrayfire array norm_type: optional: af.NORM. default: af.NORM.EUCLID. - Type of norm to be calculated. p: scalar. default 1.0. - Used only if `norm_type` is one of `af.NORM.VECTOR_P`, `af.NORM_MATRIX_L_PQ` q: scalar. default 1.0. - Used only if `norm_type` is `af.NORM_MATRIX_L_PQ` Returns ------- res: scalar - norm of the input """ res = ct.c_double(0) safe_call(backend.get().af_norm(ct.pointer(res), A.arr, norm_type.value, ct.c_double(p), ct.c_double(q))) return res.value def svd(A): """ Singular Value Decomposition Parameters ---------- A: af.Array A 2 dimensional arrayfire array. Returns ------- (U,S,Vt): tuple of af.Arrays - U - A unitary matrix - S - An array containing the elements of diagonal matrix - Vt - A unitary matrix Note ---- - The original matrix `A` is preserved and additional storage space is required for decomposition. - If the original matrix `A` need not be preserved, use `svd_inplace` instead. - The original matrix `A` can be reconstructed using the outputs in the following manner. >>> Smat = af.diag(S, 0, False) >>> A_recon = af.matmul(af.matmul(U, Smat), Vt) """ U = Array() S = Array() Vt = Array() safe_call(backend.get().af_svd(ct.pointer(U.arr), ct.pointer(S.arr), ct.pointer(Vt.arr), A.arr)) return U, S, Vt def svd_inplace(A): """ Singular Value Decomposition Parameters ---------- A: af.Array A 2 dimensional arrayfire array. Returns ------- (U,S,Vt): tuple of af.Arrays - U - A unitary matrix - S - An array containing the elements of diagonal matrix - Vt - A unitary matrix Note ---- - The original matrix `A` is not preserved. - If the original matrix `A` needs to be preserved, use `svd` instead. - The original matrix `A` can be reconstructed using the outputs in the following manner. >>> Smat = af.diag(S, 0, False) >>> A_recon = af.matmul(af.matmul(U, Smat), Vt) """ U = Array() S = Array() Vt = Array() safe_call(backend.get().af_svd_inplace(ct.pointer(U.arr), ct.pointer(S.arr), ct.pointer(Vt.arr), A.arr)) return U, S, Vt def is_lapack_available(): """ Function to check if the arrayfire library was built with lapack support. """ res = ct.c_bool(False) safe_call(backend.get().af_is_lapack_available(ct.pointer(res))) return res.value python-arrayfire-3.3.20160624/arrayfire/library.py000066400000000000000000000342741276671162200216130ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Module containing enums and other constants. """ import platform import ctypes as ct # Work around for unexpected architectures if 'c_dim_t_forced' in globals(): global c_dim_t_forced c_dim_t = c_dim_t_forced else: # dim_t is long long by default c_dim_t = ct.c_longlong # Change to int for 32 bit x86 and amr architectures if (platform.architecture()[0][0:2] == '32' and (platform.machine()[-2:] == '86' or platform.machine()[0:3] == 'arm')): c_dim_t = ct.c_int try: from enum import Enum as _Enum def _Enum_Type(v): return v except: class _MetaEnum(type): def __init__(cls, name, bases, attrs): for attrname, attrvalue in attrs.iteritems(): if name != '_Enum' and isinstance(attrvalue, _Enum_Type): attrvalue.__class__ = cls attrs[attrname] = attrvalue class _Enum(object): __metaclass__ = _MetaEnum class _Enum_Type(object): def __init__(self, v): self.value = v class ERR(_Enum): """ Error values. For internal use only. """ NONE = _Enum_Type(0) #100-199 Errors in environment NO_MEM = _Enum_Type(101) DRIVER = _Enum_Type(102) RUNTIME = _Enum_Type(103) # 200-299 Errors in input parameters INVALID_ARRAY = _Enum_Type(201) ARG = _Enum_Type(202) SIZE = _Enum_Type(203) TYPE = _Enum_Type(204) DIFF_TYPE = _Enum_Type(205) BATCH = _Enum_Type(207) DEVICE = _Enum_Type(208) # 300-399 Errors for missing software features NOT_SUPPORTED = _Enum_Type(301) NOT_CONFIGURED = _Enum_Type(302) NONFREE = _Enum_Type(303) # 400-499 Errors for missing hardware features NO_DBL = _Enum_Type(401) NO_GFX = _Enum_Type(402) # 500-599 Errors specific to the heterogeneous API LOAD_LIB = _Enum_Type(501) LOAD_SYM = _Enum_Type(502) ARR_BKND_MISMATCH = _Enum_Type(503) # 900-999 Errors from upstream libraries and runtimes INTERNAL = _Enum_Type(998) UNKNOWN = _Enum_Type(999) class Dtype(_Enum): """ Error values. For internal use only. """ f32 = _Enum_Type(0) c32 = _Enum_Type(1) f64 = _Enum_Type(2) c64 = _Enum_Type(3) b8 = _Enum_Type(4) s32 = _Enum_Type(5) u32 = _Enum_Type(6) u8 = _Enum_Type(7) s64 = _Enum_Type(8) u64 = _Enum_Type(9) s16 = _Enum_Type(10) u16 = _Enum_Type(11) class Source(_Enum): """ Source of the pointer """ device = _Enum_Type(0) host = _Enum_Type(1) class INTERP(_Enum): """ Interpolation method """ NEAREST = _Enum_Type(0) LINEAR = _Enum_Type(1) BILINEAR = _Enum_Type(2) CUBIC = _Enum_Type(3) LOWER = _Enum_Type(4) class PAD(_Enum): """ Edge padding types """ ZERO = _Enum_Type(0) SYM = _Enum_Type(1) class CONNECTIVITY(_Enum): """ Neighborhood connectivity """ FOUR = _Enum_Type(4) EIGHT = _Enum_Type(8) class CONV_MODE(_Enum): """ Convolution mode """ DEFAULT = _Enum_Type(0) EXPAND = _Enum_Type(1) class CONV_DOMAIN(_Enum): """ Convolution domain """ AUTO = _Enum_Type(0) SPATIAL = _Enum_Type(1) FREQ = _Enum_Type(2) class MATCH(_Enum): """ Match type """ """ Sum of absolute differences """ SAD = _Enum_Type(0) """ Zero mean SAD """ ZSAD = _Enum_Type(1) """ Locally scaled SAD """ LSAD = _Enum_Type(2) """ Sum of squared differences """ SSD = _Enum_Type(3) """ Zero mean SSD """ ZSSD = _Enum_Type(4) """ Locally scaled SSD """ LSSD = _Enum_Type(5) """ Normalized cross correlation """ NCC = _Enum_Type(6) """ Zero mean NCC """ ZNCC = _Enum_Type(7) """ Sum of hamming distances """ SHD = _Enum_Type(8) class YCC_STD(_Enum): """ YCC Standard formats """ BT_601 = _Enum_Type(601) BT_709 = _Enum_Type(709) BT_2020 = _Enum_Type(2020) class CSPACE(_Enum): """ Colorspace formats """ GRAY = _Enum_Type(0) RGB = _Enum_Type(1) HSV = _Enum_Type(2) YCbCr= _Enum_Type(3) class MATPROP(_Enum): """ Matrix properties """ """ None, general. """ NONE = _Enum_Type(0) """ Transposed. """ TRANS = _Enum_Type(1) """ Conjugate transposed. """ CTRANS = _Enum_Type(2) """ Upper triangular matrix. """ UPPER = _Enum_Type(32) """ Lower triangular matrix. """ LOWER = _Enum_Type(64) """ Treat diagonal as units. """ DIAG_UNIT = _Enum_Type(128) """ Symmetric matrix. """ SYM = _Enum_Type(512) """ Positive definite matrix. """ POSDEF = _Enum_Type(1024) """ Orthogonal matrix. """ ORTHOG = _Enum_Type(2048) """ Tri diagonal matrix. """ TRI_DIAG = _Enum_Type(4096) """ Block diagonal matrix. """ BLOCK_DIAG = _Enum_Type(8192) class NORM(_Enum): """ Norm types """ VECTOR_1 = _Enum_Type(0) VECTOR_INF = _Enum_Type(1) VECTOR_2 = _Enum_Type(2) VECTOR_P = _Enum_Type(3) MATRIX_1 = _Enum_Type(4) MATRIX_INF = _Enum_Type(5) MATRIX_2 = _Enum_Type(6) MATRIX_L_PQ = _Enum_Type(7) EUCLID = VECTOR_2 class COLORMAP(_Enum): """ Colormaps """ DEFAULT = _Enum_Type(0) SPECTRUM = _Enum_Type(1) COLORS = _Enum_Type(2) RED = _Enum_Type(3) MOOD = _Enum_Type(4) HEAT = _Enum_Type(5) BLUE = _Enum_Type(6) class IMAGE_FORMAT(_Enum): """ Image Formats """ BMP = _Enum_Type(0) ICO = _Enum_Type(1) JPEG = _Enum_Type(2) JNG = _Enum_Type(3) PNG = _Enum_Type(13) PPM = _Enum_Type(14) PPMRAW = _Enum_Type(15) TIFF = _Enum_Type(18) PSD = _Enum_Type(20) HDR = _Enum_Type(26) EXR = _Enum_Type(29) JP2 = _Enum_Type(31) RAW = _Enum_Type(34) class HOMOGRAPHY(_Enum): """ Homography Types """ RANSAC = _Enum_Type(0) LMEDS = _Enum_Type(1) class BACKEND(_Enum): """ Backend libraries """ DEFAULT = _Enum_Type(0) CPU = _Enum_Type(1) CUDA = _Enum_Type(2) OPENCL = _Enum_Type(4) class MARKER(_Enum): """ Markers used for different points in graphics plots """ NONE = _Enum_Type(0) POINT = _Enum_Type(1) CIRCLE = _Enum_Type(2) SQUARE = _Enum_Type(3) TRIANGE = _Enum_Type(4) CROSS = _Enum_Type(5) PLUS = _Enum_Type(6) STAR = _Enum_Type(7) def _setup(): import platform import os platform_name = platform.system() try: AF_PATH = os.environ['AF_PATH'] except: AF_PATH = None pass AF_SEARCH_PATH = AF_PATH try: CUDA_PATH = os.environ['CUDA_PATH'] except: CUDA_PATH= None pass CUDA_FOUND = False assert(len(platform_name) >= 3) if platform_name == 'Windows' or platform_name[:3] == 'CYG': ## Windows specific setup pre = '' post = '.dll' if platform_name == "Windows": ''' Supressing crashes caused by missing dlls http://stackoverflow.com/questions/8347266/missing-dll-print-message-instead-of-launching-a-popup https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx ''' ct.windll.kernel32.SetErrorMode(0x0001 | 0x0002) if AF_SEARCH_PATH is None: AF_SEARCH_PATH="C:/Program Files/ArrayFire/v3/" if CUDA_PATH is not None: CUDA_FOUND = os.path.isdir(CUDA_PATH + '/bin') and os.path.isdir(CUDA_PATH + '/nvvm/bin/') elif platform_name == 'Darwin': ## OSX specific setup pre = 'lib' post = '.3.dylib' if AF_SEARCH_PATH is None: AF_SEARCH_PATH='/usr/local/' if CUDA_PATH is None: CUDA_PATH='/usr/local/cuda/' CUDA_FOUND = os.path.isdir(CUDA_PATH + '/lib') and os.path.isdir(CUDA_PATH + '/nvvm/lib') elif platform_name == 'Linux': pre = 'lib' post = '.so.3' if AF_SEARCH_PATH is None: AF_SEARCH_PATH='/opt/arrayfire-3/' if CUDA_PATH is None: CUDA_PATH='/usr/local/cuda/' if platform.architecture()[0][:2] == '64': CUDA_FOUND = os.path.isdir(CUDA_PATH + '/lib64') and os.path.isdir(CUDA_PATH + '/nvvm/lib64') else: CUDA_FOUND = os.path.isdir(CUDA_PATH + '/lib') and os.path.isdir(CUDA_PATH + '/nvvm/lib') else: raise OSError(platform_name + ' not supported') if AF_PATH is None: os.environ['AF_PATH'] = AF_SEARCH_PATH return pre, post, AF_SEARCH_PATH, CUDA_FOUND class _clibrary(object): def __libname(self, name, head='af'): libname = self.__pre + head + name + self.__post libname_full = self.AF_PATH + '/lib/' + libname return (libname, libname_full) def set_unsafe(self, name): lib = self.__clibs[name] if (lib is None): raise RuntimeError("Backend not found") self.__name = name def __init__(self): more_info_str = "Please look at https://github.com/arrayfire/arrayfire-python/wiki for more information." pre, post, AF_PATH, CUDA_FOUND = _setup() self.__pre = pre self.__post = post self.AF_PATH = AF_PATH self.CUDA_FOUND = CUDA_FOUND self.__name = None self.__clibs = {'cuda' : None, 'opencl' : None, 'cpu' : None, 'unified' : None} self.__backend_map = {0 : 'unified', 1 : 'cpu' , 2 : 'cuda' , 4 : 'opencl' } self.__backend_name_map = {'default' : 0, 'unified' : 0, 'cpu' : 1, 'cuda' : 2, 'opencl' : 4} # Try to pre-load forge library if it exists libnames = self.__libname('forge', '') for libname in libnames: try: ct.cdll.LoadLibrary(libname) except: pass # Iterate in reverse order of preference for name in ('cpu', 'opencl', 'cuda', ''): libnames = self.__libname(name) for libname in libnames: try: ct.cdll.LoadLibrary(libname) __name = 'unified' if name == '' else name self.__clibs[__name] = ct.CDLL(libname) self.__name = __name break; except: pass if (self.__name is None): raise RuntimeError("Could not load any ArrayFire libraries.\n" + more_info_str) def get_id(self, name): return self.__backend_name_map[name] def get_name(self, bk_id): return self.__backend_map[bk_id] def get(self): return self.__clibs[self.__name] def name(self): return self.__name def is_unified(self): return self.__name == 'unified' def parse(self, res): lst = [] for key,value in self.__backend_name_map.items(): if (value & res): lst.append(key) return tuple(lst) backend = _clibrary() def set_backend(name, unsafe=False): """ Set a specific backend by name Parameters ---------- name : str. unsafe : optional: bool. Default: False. If False, does not switch backend if current backend is not unified backend. """ if (backend.is_unified() == False and unsafe == False): raise RuntimeError("Can not change backend to %s after loading %s" % (name, backend.name())) if (backend.is_unified()): safe_call(backend.get().af_set_backend(backend.get_id(name))) else: backend.set_unsafe(name) return def get_backend(): """ Return the name of the backend """ return backend.name() def get_backend_id(A): """ Get backend name of an array Parameters ---------- A : af.Array Returns ---------- name : str. Backend name """ backend_id = ct.c_int(BACKEND.CPU.value) safe_call(backend.get().af_get_backend_id(ct.pointer(backend_id), A.arr)) return backend.get_name(backend_id.value) def get_backend_count(): """ Get number of available backends Returns ---------- count : int Number of available backends """ count = ct.c_int(0) safe_call(backend.get().af_get_backend_count(ct.pointer(count))) return count.value def get_available_backends(): """ Get names of available backends Returns ---------- names : tuple of strings Names of available backends """ available = ct.c_int(0) safe_call(backend.get().af_get_available_backends(ct.pointer(available))) return backend.parse(int(available.value)) def get_active_backend(): """ Get the current active backend name : str. Backend name """ backend_id = ct.c_int(BACKEND.CPU.value) safe_call(backend.get().af_get_active_backend(ct.pointer(backend_id))) return backend.get_name(backend_id.value) def get_device_id(A): """ Get the device id of the array Parameters ---------- A : af.Array Returns ---------- dev : Integer id of the device array was created on """ device_id = ct.c_int(0) safe_call(backend.get().af_get_device_id(ct.pointer(device_id), A.arr)) return device_id from .util import safe_call python-arrayfire-3.3.20160624/arrayfire/opencl.py000066400000000000000000000124041276671162200214160ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Functions specific to OpenCL backend. This module provides interoperability with other OpenCL libraries. """ from .util import * from .library import (_Enum, _Enum_Type) class DEVICE_TYPE(_Enum): """ ArrayFire wrapper for CL_DEVICE_TYPE """ CPU = _Enum_Type(1<<1) GPU = _Enum_Type(1<<2) ACC = _Enum_Type(1<<3) UNKNOWN = _Enum_Type(-1) class PLATFORM(_Enum): """ ArrayFire enum for common platforms """ AMD = _Enum_Type(0) APPLE = _Enum_Type(1) INTEL = _Enum_Type(2) NVIDIA = _Enum_Type(3) BEIGNET = _Enum_Type(4) POCL = _Enum_Type(5) UNKNOWN = _Enum_Type(-1) def get_context(retain=False): """ Get the current OpenCL context being used by ArrayFire. Parameters ---------- retain : bool. optional. Default: False. Specifies if the context needs to be retained by arrayfire before returning. Returns ----------- context : integer denoting the context id. """ import ctypes as ct from .util import safe_call as safe_call from .library import backend as backend if (backend.name() != "opencl"): raise RuntimeError("Invalid backend loaded") context = ct.c_void_p(0) safe_call(backend.get().afcl_get_context(ct.pointer(context), retain)) return context.value def get_queue(retain): """ Get the current OpenCL command queue being used by ArrayFire. Parameters ---------- retain : bool. optional. Default: False. Specifies if the context needs to be retained by arrayfire before returning. Returns ----------- queue : integer denoting the queue id. """ import ctypes as ct from .util import safe_call as safe_call from .library import backend as backend if (backend.name() != "opencl"): raise RuntimeError("Invalid backend loaded") queue = ct.c_int(0) safe_call(backend.get().afcl_get_queue(ct.pointer(queue), retain)) return queue.value def get_device_id(): """ Get native (unsorted) OpenCL device ID Returns -------- idx : int. Specifies the `cl_device_id` of the device. """ import ctypes as ct from .util import safe_call as safe_call from .library import backend as backend if (backend.name() != "opencl"): raise RuntimeError("Invalid backend loaded") idx = ct.c_int(0) safe_call(backend.get().afcl_get_device_id(ct.pointer(idx))) return idx.value def set_device_id(idx): """ Set native (unsorted) OpenCL device ID Parameters ---------- idx : int. Specifies the `cl_device_id` of the device. """ import ctypes as ct from .util import safe_call as safe_call from .library import backend as backend if (backend.name() != "opencl"): raise RuntimeError("Invalid backend loaded") safe_call(backend.get().afcl_set_device_id(idx)) return def add_device_context(dev, ctx, que): """ Add a new device to arrayfire opencl device manager Parameters ---------- dev : cl_device_id ctx : cl_context que : cl_command_queue """ if (backend.name() != "opencl"): raise RuntimeError("Invalid backend loaded") safe_call(backend.get().afcl_add_device_context(dev, ctx, que)) def set_device_context(dev, ctx): """ Set a device as current active device Parameters ---------- dev : cl_device_id ctx : cl_context """ if (backend.name() != "opencl"): raise RuntimeError("Invalid backend loaded") safe_call(backend.get().afcl_set_device_context(dev, ctx)) def delete_device_context(dev, ctx): """ Delete a device Parameters ---------- dev : cl_device_id ctx : cl_context """ if (backend.name() != "opencl"): raise RuntimeError("Invalid backend loaded") safe_call(backend.get().afcl_delete_device_context(dev, ctx)) _to_device_type = {DEVICE_TYPE.CPU.value : DEVICE_TYPE.CPU, DEVICE_TYPE.GPU.value : DEVICE_TYPE.GPU, DEVICE_TYPE.ACC.value : DEVICE_TYPE.ACC, DEVICE_TYPE.UNKNOWN.value : DEVICE_TYPE.UNKNOWN} _to_platform = {PLATFORM.AMD.value : PLATFORM.AMD, PLATFORM.APPLE.value : PLATFORM.APPLE, PLATFORM.INTEL.value : PLATFORM.INTEL, PLATFORM.NVIDIA.value : PLATFORM.NVIDIA, PLATFORM.BEIGNET.value : PLATFORM.BEIGNET, PLATFORM.POCL.value : PLATFORM.POCL, PLATFORM.UNKNOWN.value : PLATFORM.UNKNOWN} def get_device_type(): """ Get opencl device type """ res = ct.c_int(DEVICE_TYPE.UNKNOWN.value) safe_call(backend.get().afcl_get_device_type(ct.pointer(res))) return _to_device_type[res.value] def get_platform(): """ Get opencl platform """ res = ct.c_int(PLATFORM.UNKNOWN.value) safe_call(backend.get().afcl_get_platform(ct.pointer(res))) return _to_platform[res.value] python-arrayfire-3.3.20160624/arrayfire/signal.py000066400000000000000000001033321276671162200214140ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Signal processing functions (fft, convolve, etc). """ from .library import * from .array import * def approx1(signal, pos0, method=INTERP.LINEAR, off_grid=0.0): """ Interpolate along a single dimension. Parameters ---------- signal: af.Array A 1 dimensional signal or batch of 1 dimensional signals. pos0 : af.Array Locations of the interpolation points. method: optional: af.INTERP. default: af.INTERP.LINEAR. Interpolation method. off_grid: optional: scalar. default: 0.0. The value used for positions outside the range. Returns ------- output: af.Array Values calculated at interpolation points. Note ----- The initial measurements are assumed to have taken place at equal steps between [0, N - 1], where N is the length of the first dimension of `signal`. """ output = Array() safe_call(backend.get().af_approx1(ct.pointer(output.arr), signal.arr, pos0.arr, method.value, ct.c_double(off_grid))) return output def approx2(signal, pos0, pos1, method=INTERP.LINEAR, off_grid=0.0): """ Interpolate along a two dimension. Parameters ---------- signal: af.Array A 2 dimensional signal or batch of 2 dimensional signals. pos0 : af.Array Locations of the interpolation points along the first dimension. pos1 : af.Array Locations of the interpolation points along the second dimension. method: optional: af.INTERP. default: af.INTERP.LINEAR. Interpolation method. off_grid: optional: scalar. default: 0.0. The value used for positions outside the range. Returns ------- output: af.Array Values calculated at interpolation points. Note ----- The initial measurements are assumed to have taken place at equal steps between [(0,0) - [M - 1, N - 1]] where M is the length of the first dimension of `signal`, and N is the length of the second dimension of `signal`. """ output = Array() safe_call(backend.get().af_approx2(ct.pointer(output.arr), signal.arr, pos0.arr, pos1.arr, method.value, ct.c_double(off_grid))) return output def fft(signal, dim0 = None , scale = None): """ Fast Fourier Transform: 1D Parameters ---------- signal: af.Array A 1 dimensional signal or a batch of 1 dimensional signals. dim0: optional: int. default: None. - Specifies the size of the output. - If None, dim0 is calculated to be the first dimension of `signal`. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1. Returns ------- output: af.Array A complex af.Array containing the full output of the fft. """ if dim0 is None: dim0 = 0 if scale is None: scale = 1.0 output = Array() safe_call(backend.get().af_fft(ct.pointer(output.arr), signal.arr, ct.c_double(scale), c_dim_t(dim0))) return output def fft2(signal, dim0 = None, dim1 = None , scale = None): """ Fast Fourier Transform: 2D Parameters ---------- signal: af.Array A 2 dimensional signal or a batch of 2 dimensional signals. dim0: optional: int. default: None. - Specifies the size of the output. - If None, dim0 is calculated to be the first dimension of `signal`. dim1: optional: int. default: None. - Specifies the size of the output. - If None, dim1 is calculated to be the second dimension of `signal`. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1. Returns ------- output: af.Array A complex af.Array containing the full output of the fft. """ if dim0 is None: dim0 = 0 if dim1 is None: dim1 = 0 if scale is None: scale = 1.0 output = Array() safe_call(backend.get().af_fft2(ct.pointer(output.arr), signal.arr, ct.c_double(scale), c_dim_t(dim0), c_dim_t(dim1))) return output def fft3(signal, dim0 = None, dim1 = None , dim2 = None, scale = None): """ Fast Fourier Transform: 3D Parameters ---------- signal: af.Array A 3 dimensional signal or a batch of 3 dimensional signals. dim0: optional: int. default: None. - Specifies the size of the output. - If None, dim0 is calculated to be the first dimension of `signal`. dim1: optional: int. default: None. - Specifies the size of the output. - If None, dim1 is calculated to be the second dimension of `signal`. dim2: optional: int. default: None. - Specifies the size of the output. - If None, dim2 is calculated to be the third dimension of `signal`. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1. Returns ------- output: af.Array A complex af.Array containing the full output of the fft. """ if dim0 is None: dim0 = 0 if dim1 is None: dim1 = 0 if dim2 is None: dim2 = 0 if scale is None: scale = 1.0 output = Array() safe_call(backend.get().af_fft3(ct.pointer(output.arr), signal.arr, ct.c_double(scale), c_dim_t(dim0), c_dim_t(dim1), c_dim_t(dim2))) return output def ifft(signal, dim0 = None , scale = None): """ Inverse Fast Fourier Transform: 1D Parameters ---------- signal: af.Array A 1 dimensional signal or a batch of 1 dimensional signals. dim0: optional: int. default: None. - Specifies the size of the output. - If None, dim0 is calculated to be the first dimension of `signal`. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1.0 / (dim0) Returns ------- output: af.Array A complex af.Array containing the full output of the inverse fft. Note ---- The output is always complex. """ if dim0 is None: dim0 = signal.dims()[0] if scale is None: scale = 1.0/float(dim0) output = Array() safe_call(backend.get().af_ifft(ct.pointer(output.arr), signal.arr, ct.c_double(scale), c_dim_t(dim0))) return output def ifft2(signal, dim0 = None, dim1 = None , scale = None): """ Inverse Fast Fourier Transform: 2D Parameters ---------- signal: af.Array A 2 dimensional signal or a batch of 2 dimensional signals. dim0: optional: int. default: None. - Specifies the size of the output. - If None, dim0 is calculated to be the first dimension of `signal`. dim1: optional: int. default: None. - Specifies the size of the output. - If None, dim1 is calculated to be the second dimension of `signal`. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1.0 / (dim0 * dim1) Returns ------- output: af.Array A complex af.Array containing the full output of the inverse fft. Note ---- The output is always complex. """ dims = signal.dims() if dim0 is None: dim0 = dims[0] if dim1 is None: dim1 = dims[1] if scale is None: scale = 1.0/float(dim0 * dim1) output = Array() safe_call(backend.get().af_ifft2(ct.pointer(output.arr), signal.arr, ct.c_double(scale), c_dim_t(dim0), c_dim_t(dim1))) return output def ifft3(signal, dim0 = None, dim1 = None , dim2 = None, scale = None): """ Inverse Fast Fourier Transform: 3D Parameters ---------- signal: af.Array A 3 dimensional signal or a batch of 3 dimensional signals. dim0: optional: int. default: None. - Specifies the size of the output. - If None, dim0 is calculated to be the first dimension of `signal`. dim1: optional: int. default: None. - Specifies the size of the output. - If None, dim1 is calculated to be the second dimension of `signal`. dim2: optional: int. default: None. - Specifies the size of the output. - If None, dim2 is calculated to be the third dimension of `signal`. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1.0 / (dim0 * dim1 * dim2). Returns ------- output: af.Array A complex af.Array containing the full output of the inverse fft. Note ---- The output is always complex. """ dims = signal.dims() if dim0 is None: dim0 = dims[0] if dim1 is None: dim1 = dims[1] if dim2 is None: dim2 = dims[2] if scale is None: scale = 1.0 / float(dim0 * dim1 * dim2) output = Array() safe_call(backend.get().af_ifft3(ct.pointer(output.arr), signal.arr, ct.c_double(scale), c_dim_t(dim0), c_dim_t(dim1), c_dim_t(dim2))) return output def fft_inplace(signal, scale = None): """ In-place Fast Fourier Transform: 1D Parameters ---------- signal: af.Array A 1 dimensional signal or a batch of 1 dimensional signals. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1. """ if scale is None: scale = 1.0 safe_call(backend.get().af_fft_inplace(signal.arr, ct.c_double(scale))) def fft2_inplace(signal, scale = None): """ In-place Fast Fourier Transform: 2D Parameters ---------- signal: af.Array A 2 dimensional signal or a batch of 2 dimensional signals. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1. """ if scale is None: scale = 1.0 safe_call(backend.get().af_fft2_inplace(signal.arr, ct.c_double(scale))) def fft3_inplace(signal, scale = None): """ In-place Fast Fourier Transform: 3D Parameters ---------- signal: af.Array A 3 dimensional signal or a batch of 3 dimensional signals. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1. """ if scale is None: scale = 1.0 output = Array() safe_call(backend.get().af_fft3_inplace(signal.arr, ct.c_double(scale))) def ifft_inplace(signal, scale = None): """ Inverse In-place Fast Fourier Transform: 1D Parameters ---------- signal: af.Array A 1 dimensional signal or a batch of 1 dimensional signals. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1.0 / (signal.dims()[0]) """ if scale is None: dim0 = signal.dims()[0] scale = 1.0/float(dim0) safe_call(backend.get().af_ifft_inplace(signal.arr, ct.c_double(scale))) def ifft2_inplace(signal, scale = None): """ Inverse In-place Fast Fourier Transform: 2D Parameters ---------- signal: af.Array A 2 dimensional signal or a batch of 2 dimensional signals. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1.0 / (signal.dims()[0] * signal.dims()[1]) """ dims = signal.dims() if scale is None: dim0 = dims[0] dim1 = dims[1] scale = 1.0/float(dim0 * dim1) safe_call(backend.get().af_ifft2_inplace(signal.arr, ct.c_double(scale))) def ifft3_inplace(signal, scale = None): """ Inverse In-place Fast Fourier Transform: 3D Parameters ---------- signal: af.Array A 3 dimensional signal or a batch of 3 dimensional signals. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1.0 / (signal.dims()[0] * signal.dims()[1] * signal.dims()[2]). """ dims = signal.dims() if scale is None: dim0 = dims[0] dim1 = dims[1] dim2 = dims[2] scale = 1.0 / float(dim0 * dim1 * dim2) safe_call(backend.get().af_ifft3_inplace(signal.arr, ct.c_double(scale))) def fft_r2c(signal, dim0 = None , scale = None): """ Real to Complex Fast Fourier Transform: 1D Parameters ---------- signal: af.Array A 1 dimensional signal or a batch of 1 dimensional signals. dim0: optional: int. default: None. - Specifies the size of the output. - If None, dim0 is calculated to be the first dimension of `signal`. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1. Returns ------- output: af.Array A complex af.Array containing the non-redundant parts of the full FFT. """ if dim0 is None: dim0 = 0 if scale is None: scale = 1.0 output = Array() safe_call(backend.get().af_fft_r2c(ct.pointer(output.arr), signal.arr, ct.c_double(scale), c_dim_t(dim0))) return output def fft2_r2c(signal, dim0 = None, dim1 = None , scale = None): """ Real to Complex Fast Fourier Transform: 2D Parameters ---------- signal: af.Array A 2 dimensional signal or a batch of 2 dimensional signals. dim0: optional: int. default: None. - Specifies the size of the output. - If None, dim0 is calculated to be the first dimension of `signal`. dim1: optional: int. default: None. - Specifies the size of the output. - If None, dim1 is calculated to be the second dimension of `signal`. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1. Returns ------- output: af.Array A complex af.Array containing the non-redundant parts of the full FFT. """ if dim0 is None: dim0 = 0 if dim1 is None: dim1 = 0 if scale is None: scale = 1.0 output = Array() safe_call(backend.get().af_fft2_r2c(ct.pointer(output.arr), signal.arr, ct.c_double(scale), c_dim_t(dim0), c_dim_t(dim1))) return output def fft3_r2c(signal, dim0 = None, dim1 = None , dim2 = None, scale = None): """ Real to Complex Fast Fourier Transform: 3D Parameters ---------- signal: af.Array A 3 dimensional signal or a batch of 3 dimensional signals. dim0: optional: int. default: None. - Specifies the size of the output. - If None, dim0 is calculated to be the first dimension of `signal`. dim1: optional: int. default: None. - Specifies the size of the output. - If None, dim1 is calculated to be the second dimension of `signal`. dim2: optional: int. default: None. - Specifies the size of the output. - If None, dim2 is calculated to be the third dimension of `signal`. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1. Returns ------- output: af.Array A complex af.Array containing the non-redundant parts of the full FFT. """ if dim0 is None: dim0 = 0 if dim1 is None: dim1 = 0 if dim2 is None: dim2 = 0 if scale is None: scale = 1.0 output = Array() safe_call(backend.get().af_fft3_r2c(ct.pointer(output.arr), signal.arr, ct.c_double(scale), c_dim_t(dim0), c_dim_t(dim1), c_dim_t(dim2))) return output def _get_c2r_dim(dim, is_odd): return 2 *(dim - 1) + int(is_odd) def fft_c2r(signal, is_odd = False, scale = None): """ Real to Complex Fast Fourier Transform: 1D Parameters ---------- signal: af.Array A 1 dimensional signal or a batch of 1 dimensional signals. is_odd: optional: Boolean. default: False. - Specifies if the first dimension of output should be even or odd. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1 / (signal.dims()[0]). Returns ------- output: af.Array A real af.Array containing the full output of the fft. """ if scale is None: dim0 = _get_c2r_dim(signal.dims()[0], is_odd) scale = 1.0/float(dim0) output = Array() safe_call(backend.get().af_fft_c2r(ct.pointer(output.arr), signal.arr, ct.c_double(scale), is_odd)) return output def fft2_c2r(signal, is_odd = False, scale = None): """ Real to Complex Fast Fourier Transform: 2D Parameters ---------- signal: af.Array A 2 dimensional signal or a batch of 2 dimensional signals. is_odd: optional: Boolean. default: False. - Specifies if the first dimension of output should be even or odd. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1 / (signal.dims()[0] * signal.dims()[1]). Returns ------- output: af.Array A real af.Array containing the full output of the fft. """ dims = signal.dims() if scale is None: dim0 = _get_c2r_dim(dims[0], is_odd) dim1 = dims[1] scale = 1.0/float(dim0 * dim1) output = Array() safe_call(backend.get().af_fft2_c2r(ct.pointer(output.arr), signal.arr, ct.c_double(scale), is_odd)) return output def fft3_c2r(signal, is_odd = False, scale = None): """ Real to Complex Fast Fourier Transform: 3D Parameters ---------- signal: af.Array A 3 dimensional signal or a batch of 3 dimensional signals. is_odd: optional: Boolean. default: False. - Specifies if the first dimension of output should be even or odd. scale: optional: scalar. default: None. - Specifies the scaling factor. - If None, scale is set to 1 / (signal.dims()[0] * signal.dims()[1] * signal.dims()[2]). Returns ------- output: af.Array A real af.Array containing the full output of the fft. """ dims = signal.dims() if scale is None: dim0 = _get_c2r_dim(dims[0], is_odd) dim1 = dims[1] dim2 = dims[2] scale = 1.0/float(dim0 * dim1 * dim2) output = Array() safe_call(backend.get().af_fft3_c2r(ct.pointer(output.arr), signal.arr, ct.c_double(scale), is_odd)) return output def dft(signal, odims=(None, None, None, None), scale = None): """ Non batched Fourier transform. This function performs n-dimensional fourier transform depending on the input dimensions. Parameters ---------- signal: af.Array - A multi dimensional arrayfire array. odims: optional: tuple of ints. default: (None, None, None, None). - If None, calculated to be `signal.dims()` scale: optional: scalar. default: None. - Scale factor for the fourier transform. - If none, calculated to be 1.0. Returns ------- output: af.Array - A complex array that is the ouput of n-dimensional fourier transform. """ odims4 = dim4_to_tuple(odims, default=None) dims = signal.dims() ndims = len(dims) if (ndims == 1): return fft(signal, dims[0], scale) elif (ndims == 2): return fft2(signal, dims[0], dims[1], scale) else: return fft3(signal, dims[0], dims[1], dims[2], scale) def idft(signal, scale = None, odims=(None, None, None, None)): """ Non batched Inverse Fourier transform. This function performs n-dimensional inverse fourier transform depending on the input dimensions. Parameters ---------- signal: af.Array - A multi dimensional arrayfire array. odims: optional: tuple of ints. default: (None, None, None, None). - If None, calculated to be `signal.dims()` scale: optional: scalar. default: None. - Scale factor for the fourier transform. - If none, calculated to be 1.0 / signal.elements() Returns ------- output: af.Array - A complex array that is the ouput of n-dimensional inverse fourier transform. Note ---- the output is always complex. """ odims4 = dim4_to_tuple(odims, default=None) dims = signal.dims() ndims = len(dims) if (ndims == 1): return ifft(signal, scale, dims[0]) elif (ndims == 2): return ifft2(signal, scale, dims[0], dims[1]) else: return ifft3(signal, scale, dims[0], dims[1], dims[2]) def convolve1(signal, kernel, conv_mode = CONV_MODE.DEFAULT, conv_domain = CONV_DOMAIN.AUTO): """ Convolution: 1D Parameters ----------- signal: af.Array - A 1 dimensional signal or batch of 1 dimensional signals. kernel: af.Array - A 1 dimensional kernel or batch of 1 dimensional kernels. conv_mode: optional: af.CONV_MODE. default: af.CONV_MODE.DEFAULT. - Specifies if the output does full convolution (af.CONV_MODE.EXPAND) or maintains the same size as input (af.CONV_MODE.DEFAULT). conv_domain: optional: af.CONV_DOMAIN. default: af.CONV_DOMAIN.AUTO. - Specifies the domain in which convolution is performed. - af.CONV_DOMAIN.SPATIAL: Performs convolution in spatial domain. - af.CONV_DOMAIN.FREQ: Performs convolution in frequency domain. - af.CONV_DOMAIN.AUTO: Switches between spatial and frequency based on input size. Returns -------- output: af.Array - Output of 1D convolution. Note ----- Supported batch combinations: | Signal | Kernel | output | |:---------:|:---------:|:---------:| | [m 1 1 1] | [m 1 1 1] | [m 1 1 1] | | [m n 1 1] | [m n 1 1] | [m n 1 1] | | [m n p 1] | [m n 1 1] | [m n p 1] | | [m n p 1] | [m n p 1] | [m n p 1] | | [m n p 1] | [m n 1 q] | [m n p q] | | [m n 1 p] | [m n q 1] | [m n q p] | """ output = Array() safe_call(backend.get().af_convolve1(ct.pointer(output.arr), signal.arr, kernel.arr, conv_mode.value, conv_domain.value)) return output def convolve2(signal, kernel, conv_mode = CONV_MODE.DEFAULT, conv_domain = CONV_DOMAIN.AUTO): """ Convolution: 2D Parameters ----------- signal: af.Array - A 2 dimensional signal or batch of 2 dimensional signals. kernel: af.Array - A 2 dimensional kernel or batch of 2 dimensional kernels. conv_mode: optional: af.CONV_MODE. default: af.CONV_MODE.DEFAULT. - Specifies if the output does full convolution (af.CONV_MODE.EXPAND) or maintains the same size as input (af.CONV_MODE.DEFAULT). conv_domain: optional: af.CONV_DOMAIN. default: af.CONV_DOMAIN.AUTO. - Specifies the domain in which convolution is performed. - af.CONV_DOMAIN.SPATIAL: Performs convolution in spatial domain. - af.CONV_DOMAIN.FREQ: Performs convolution in frequency domain. - af.CONV_DOMAIN.AUTO: Switches between spatial and frequency based on input size. Returns -------- output: af.Array - Output of 2D convolution. Note ----- Supported batch combinations: | Signal | Kernel | output | |:---------:|:---------:|:---------:| | [m n 1 1] | [m n 1 1] | [m n 1 1] | | [m n p 1] | [m n 1 1] | [m n p 1] | | [m n p 1] | [m n p 1] | [m n p 1] | | [m n p 1] | [m n 1 q] | [m n p q] | | [m n 1 p] | [m n q 1] | [m n q p] | """ output = Array() safe_call(backend.get().af_convolve2(ct.pointer(output.arr), signal.arr, kernel.arr, conv_mode.value, conv_domain.value)) return output def convolve2_separable(col_kernel, row_kernel, signal, conv_mode = CONV_MODE.DEFAULT): """ Convolution: 2D separable convolution Parameters ----------- col_kernel: af.Array - A column vector to be applied along each column of `signal` row_kernel: af.Array - A row vector to be applied along each row of `signal` signal: af.Array - A 2 dimensional signal or batch of 2 dimensional signals. conv_mode: optional: af.CONV_MODE. default: af.CONV_MODE.DEFAULT. - Specifies if the output does full convolution (af.CONV_MODE.EXPAND) or maintains the same size as input (af.CONV_MODE.DEFAULT). Returns -------- output: af.Array - Output of 2D sepearable convolution. """ output = Array() safe_call(backend.get().af_convolve2_sep(ct.pointer(output.arr), col_kernel.arr, row_kernel.arr,signal.arr, conv_mode.value)) return output def convolve3(signal, kernel, conv_mode = CONV_MODE.DEFAULT, conv_domain = CONV_DOMAIN.AUTO): """ Convolution: 3D Parameters ----------- signal: af.Array - A 3 dimensional signal or batch of 3 dimensional signals. kernel: af.Array - A 3 dimensional kernel or batch of 3 dimensional kernels. conv_mode: optional: af.CONV_MODE. default: af.CONV_MODE.DEFAULT. - Specifies if the output does full convolution (af.CONV_MODE.EXPAND) or maintains the same size as input (af.CONV_MODE.DEFAULT). conv_domain: optional: af.CONV_DOMAIN. default: af.CONV_DOMAIN.AUTO. - Specifies the domain in which convolution is performed. - af.CONV_DOMAIN.SPATIAL: Performs convolution in spatial domain. - af.CONV_DOMAIN.FREQ: Performs convolution in frequency domain. - af.CONV_DOMAIN.AUTO: Switches between spatial and frequency based on input size. Returns -------- output: af.Array - Output of 3D convolution. Note ----- Supported batch combinations: | Signal | Kernel | output | |:---------:|:---------:|:---------:| | [m n p 1] | [m n p 1] | [m n p 1] | | [m n p 1] | [m n p q] | [m n p q] | | [m n q p] | [m n q p] | [m n q p] | """ output = Array() safe_call(backend.get().af_convolve3(ct.pointer(output.arr), signal.arr, kernel.arr, conv_mode.value, conv_domain.value)) return output def convolve(signal, kernel, conv_mode = CONV_MODE.DEFAULT, conv_domain = CONV_DOMAIN.AUTO): """ Non batched Convolution. This function performs n-dimensional convolution based on input dimensionality. Parameters ----------- signal: af.Array - An n-dimensional array. kernel: af.Array - A n-dimensional kernel. conv_mode: optional: af.CONV_MODE. default: af.CONV_MODE.DEFAULT. - Specifies if the output does full convolution (af.CONV_MODE.EXPAND) or maintains the same size as input (af.CONV_MODE.DEFAULT). conv_domain: optional: af.CONV_DOMAIN. default: af.CONV_DOMAIN.AUTO. - Specifies the domain in which convolution is performed. - af.CONV_DOMAIN.SPATIAL: Performs convolution in spatial domain. - af.CONV_DOMAIN.FREQ: Performs convolution in frequency domain. - af.CONV_DOMAIN.AUTO: Switches between spatial and frequency based on input size. Returns -------- output: af.Array - Output of n-dimensional convolution. """ dims = signal.dims() ndims = len(dims) if (ndims == 1): return convolve1(signal, kernel, conv_mode, conv_domain) elif (ndims == 2): return convolve2(signal, kernel, conv_mode, conv_domain) else: return convolve3(signal, kernel, conv_mode, conv_domain) def fft_convolve1(signal, kernel, conv_mode = CONV_MODE.DEFAULT): """ FFT based Convolution: 1D Parameters ----------- signal: af.Array - A 1 dimensional signal or batch of 1 dimensional signals. kernel: af.Array - A 1 dimensional kernel or batch of 1 dimensional kernels. conv_mode: optional: af.CONV_MODE. default: af.CONV_MODE.DEFAULT. - Specifies if the output does full convolution (af.CONV_MODE.EXPAND) or maintains the same size as input (af.CONV_MODE.DEFAULT). Returns -------- output: af.Array - Output of 1D convolution. Note ----- This is same as convolve1(..., conv_mode=af.CONV_MODE.FREQ) Supported batch combinations: | Signal | Kernel | output | |:---------:|:---------:|:---------:| | [m 1 1 1] | [m 1 1 1] | [m 1 1 1] | | [m n 1 1] | [m n 1 1] | [m n 1 1] | | [m n p 1] | [m n 1 1] | [m n p 1] | | [m n p 1] | [m n p 1] | [m n p 1] | | [m n p 1] | [m n 1 q] | [m n p q] | | [m n 1 p] | [m n q 1] | [m n q p] | """ output = Array() safe_call(backend.get().af_fft_convolve1(ct.pointer(output.arr), signal.arr, kernel.arr, conv_mode.value)) return output def fft_convolve2(signal, kernel, conv_mode = CONV_MODE.DEFAULT): """ FFT based Convolution: 2D Parameters ----------- signal: af.Array - A 2 dimensional signal or batch of 2 dimensional signals. kernel: af.Array - A 2 dimensional kernel or batch of 2 dimensional kernels. conv_mode: optional: af.CONV_MODE. default: af.CONV_MODE.DEFAULT. - Specifies if the output does full convolution (af.CONV_MODE.EXPAND) or maintains the same size as input (af.CONV_MODE.DEFAULT). Returns -------- output: af.Array - Output of 2D convolution. Note ----- This is same as convolve2(..., conv_mode=af.CONV_MODE.FREQ) Supported batch combinations: | Signal | Kernel | output | |:---------:|:---------:|:---------:| | [m n 1 1] | [m n 1 1] | [m n 1 1] | | [m n p 1] | [m n 1 1] | [m n p 1] | | [m n p 1] | [m n p 1] | [m n p 1] | | [m n p 1] | [m n 1 q] | [m n p q] | | [m n 1 p] | [m n q 1] | [m n q p] | """ output = Array() safe_call(backend.get().af_fft_convolve2(ct.pointer(output.arr), signal.arr, kernel.arr, conv_mode.value)) return output def fft_convolve3(signal, kernel, conv_mode = CONV_MODE.DEFAULT): """ FFT based Convolution: 3D Parameters ----------- signal: af.Array - A 3 dimensional signal or batch of 3 dimensional signals. kernel: af.Array - A 3 dimensional kernel or batch of 3 dimensional kernels. conv_mode: optional: af.CONV_MODE. default: af.CONV_MODE.DEFAULT. - Specifies if the output does full convolution (af.CONV_MODE.EXPAND) or maintains the same size as input (af.CONV_MODE.DEFAULT). Returns -------- output: af.Array - Output of 3D convolution. Note ----- This is same as convolve3(..., conv_mode=af.CONV_MODE.FREQ) Supported batch combinations: | Signal | Kernel | output | |:---------:|:---------:|:---------:| | [m n p 1] | [m n p 1] | [m n p 1] | | [m n p 1] | [m n p q] | [m n p q] | | [m n q p] | [m n q p] | [m n q p] | """ output = Array() safe_call(backend.get().af_fft_convolve3(ct.pointer(output.arr), signal.arr, kernel.arr, conv_mode.value)) return output def fft_convolve(signal, kernel, conv_mode = CONV_MODE.DEFAULT): """ Non batched FFT Convolution. This function performs n-dimensional convolution based on input dimensionality. Parameters ----------- signal: af.Array - An n-dimensional array. kernel: af.Array - A n-dimensional kernel. conv_mode: optional: af.CONV_MODE. default: af.CONV_MODE.DEFAULT. - Specifies if the output does full convolution (af.CONV_MODE.EXPAND) or maintains the same size as input (af.CONV_MODE.DEFAULT). Returns -------- output: af.Array - Output of n-dimensional convolution. Note ----- This is same as convolve(..., conv_mode=af.CONV_MODE.FREQ) """ dims = signal.dims() ndims = len(dims) if (ndims == 1): return fft_convolve1(signal, kernel, conv_mode) elif (ndims == 2): return fft_convolve2(signal, kernel, conv_mode) else: return fft_convolve3(signal, kernel, conv_mode) def fir(B, X): """ Finite impulse response filter. Parameters ---------- B : af.Array A 1 dimensional array containing the coefficients of the filter. X : af.Array A 1 dimensional array containing the signal. Returns ------- Y : af.Array The output of the filter. """ Y = Array() safe_call(backend.get().af_fir(ct.pointer(Y.arr), B.arr, X.arr)) return Y def iir(B, A, X): """ Infinite impulse response filter. Parameters ---------- B : af.Array A 1 dimensional array containing the feed forward coefficients of the filter. A : af.Array A 1 dimensional array containing the feed back coefficients of the filter. X : af.Array A 1 dimensional array containing the signal. Returns ------- Y : af.Array The output of the filter. """ Y = Array() safe_call(backend.get().af_iir(ct.pointer(Y.arr), B.arr, A.arr, X.arr)) return Y python-arrayfire-3.3.20160624/arrayfire/statistics.py000066400000000000000000000070411276671162200223310ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Statistical algorithms (mean, var, stdev, etc). """ from .library import * from .array import * def mean(a, weights=None, dim=None): if dim is not None: out = Array() if weights is None: safe_call(backend.get().af_mean(ct.pointer(out.arr), a.arr, ct.c_int(dim))) else: safe_call(backend.get().af_mean_weighted(ct.pointer(out.arr), a.arr, weights.arr, ct.c_int(dim))) return out else: real = ct.c_double(0) imag = ct.c_double(0) if weights is None: safe_call(backend.get().af_mean_all(ct.pointer(real), ct.pointer(imag), a.arr)) else: safe_call(backend.get().af_mean_all_weighted(ct.pointer(real), ct.pointer(imag), a.arr, weights.arr)) real = real.value imag = imag.value return real if imag == 0 else real + imag * 1j def var(a, isbiased=False, weights=None, dim=None): if dim is not None: out = Array() if weights is None: safe_call(backend.get().af_var(ct.pointer(out.arr), a.arr, isbiased, ct.c_int(dim))) else: safe_call(backend.get().af_var_weighted(ct.pointer(out.arr), a.arr, weights.arr, ct.c_int(dim))) return out else: real = ct.c_double(0) imag = ct.c_double(0) if weights is None: safe_call(backend.get().af_var_all(ct.pointer(real), ct.pointer(imag), a.arr, isbiased)) else: safe_call(backend.get().af_var_all_weighted(ct.pointer(real), ct.pointer(imag), a.arr, weights.arr)) real = real.value imag = imag.value return real if imag == 0 else real + imag * 1j def stdev(a, dim=None): if dim is not None: out = Array() safe_call(backend.get().af_stdev(ct.pointer(out.arr), a.arr, ct.c_int(dim))) return out else: real = ct.c_double(0) imag = ct.c_double(0) safe_call(backend.get().af_stdev_all(ct.pointer(real), ct.pointer(imag), a.arr)) real = real.value imag = imag.value return real if imag == 0 else real + imag * 1j def cov(a, isbiased=False, dim=None): if dim is not None: out = Array() safe_call(backend.get().af_cov(ct.pointer(out.arr), a.arr, isbiased, ct.c_int(dim))) return out else: real = ct.c_double(0) imag = ct.c_double(0) safe_call(backend.get().af_cov_all(ct.pointer(real), ct.pointer(imag), a.arr, isbiased)) real = real.value imag = imag.value return real if imag == 0 else real + imag * 1j def median(a, dim=None): if dim is not None: out = Array() safe_call(backend.get().af_median(ct.pointer(out.arr), a.arr, ct.c_int(dim))) return out else: real = ct.c_double(0) imag = ct.c_double(0) safe_call(backend.get().af_median_all(ct.pointer(real), ct.pointer(imag), a.arr)) real = real.value imag = imag.value return real if imag == 0 else real + imag * 1j def corrcoef(x, y): real = ct.c_double(0) imag = ct.c_double(0) safe_call(backend.get().af_corrcoef(ct.pointer(real), ct.pointer(imag), x.arr, y.arr)) real = real.value imag = imag.value return real if imag == 0 else real + imag * 1j python-arrayfire-3.3.20160624/arrayfire/timer.py000066400000000000000000000023041276671162200212540ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Functions to time arrayfire. """ from .library import * from .device import (sync, eval) from time import time import math def timeit(af_func, *args): """ Function to time arrayfire functions. Parameters ---------- af_func : arrayfire function *args : arguments to `af_func` Returns -------- t : Time in seconds """ sample_trials = 3 sample_time = 1E20 for i in range(sample_trials): start = time() res = af_func(*args) eval(res) sync() sample_time = min(sample_time, time() - start) if (sample_time >= 0.5): return sample_time num_iters = max(math.ceil(1.0 / sample_time), 3.0) start = time() for i in range(int(num_iters)): res = af_func(*args) eval(res) sync() sample_time = (time() - start) / num_iters return sample_time python-arrayfire-3.3.20160624/arrayfire/util.py000066400000000000000000000102651276671162200211160ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Utility functions to help with Array metadata. """ from .library import * import numbers def dim4(d0=1, d1=1, d2=1, d3=1): c_dim4 = c_dim_t * 4 out = c_dim4(1, 1, 1, 1) for i, dim in enumerate((d0, d1, d2, d3)): if (dim is not None): out[i] = c_dim_t(dim) return out def _is_number(a): return isinstance(a, numbers.Number) def number_dtype(a): if isinstance(a, bool): return Dtype.b8 if isinstance(a, int): return Dtype.s64 elif isinstance(a, float): return Dtype.f64 elif isinstance(a, complex): return Dtype.c64 else: return to_dtype[a.dtype.char] def implicit_dtype(number, a_dtype): n_dtype = number_dtype(number) n_value = n_dtype.value f64v = Dtype.f64.value f32v = Dtype.f32.value c32v = Dtype.c32.value c64v = Dtype.c64.value if n_value == f64v and (a_dtype == f32v or a_dtype == c32v): return Dtype.f32 if n_value == c64v and (a_dtype == f32v or a_dtype == c32v): return Dtype.c32 return n_dtype def dim4_to_tuple(dims, default=1): assert(isinstance(dims, tuple)) if (default is not None): assert(_is_number(default)) out = [default]*4 for i, dim in enumerate(dims): out[i] = dim return tuple(out) def to_str(c_str): return str(c_str.value.decode('utf-8')) def safe_call(af_error): if (af_error != ERR.NONE.value): err_str = ct.c_char_p(0) err_len = c_dim_t(0) backend.get().af_get_last_error(ct.pointer(err_str), ct.pointer(err_len)) raise RuntimeError(to_str(err_str)) def get_version(): """ Function to get the version of arrayfire. """ major=ct.c_int(0) minor=ct.c_int(0) patch=ct.c_int(0) safe_call(backend.get().af_get_version(ct.pointer(major), ct.pointer(minor), ct.pointer(patch))) return major.value,minor.value,patch.value def get_reversion(): """ Function to get the revision hash of the library. """ return to_str(backend.get().af_get_revision()) to_dtype = {'f' : Dtype.f32, 'd' : Dtype.f64, 'b' : Dtype.b8, 'B' : Dtype.u8, 'h' : Dtype.s16, 'H' : Dtype.u16, 'i' : Dtype.s32, 'I' : Dtype.u32, 'l' : Dtype.s64, 'L' : Dtype.u64, 'F' : Dtype.c32, 'D' : Dtype.c64} to_typecode = {Dtype.f32.value : 'f', Dtype.f64.value : 'd', Dtype.b8.value : 'b', Dtype.u8.value : 'B', Dtype.s16.value : 'h', Dtype.u16.value : 'H', Dtype.s32.value : 'i', Dtype.u32.value : 'I', Dtype.s64.value : 'l', Dtype.u64.value : 'L', Dtype.c32.value : 'F', Dtype.c64.value : 'D'} to_c_type = {Dtype.f32.value : ct.c_float, Dtype.f64.value : ct.c_double, Dtype.b8.value : ct.c_char, Dtype.u8.value : ct.c_ubyte, Dtype.s16.value : ct.c_short, Dtype.u16.value : ct.c_ushort, Dtype.s32.value : ct.c_int, Dtype.u32.value : ct.c_uint, Dtype.s64.value : ct.c_longlong, Dtype.u64.value : ct.c_ulonglong, Dtype.c32.value : ct.c_float * 2, Dtype.c64.value : ct.c_double * 2} to_typename = {Dtype.f32.value : 'float', Dtype.f64.value : 'double', Dtype.b8.value : 'bool', Dtype.u8.value : 'unsigned char', Dtype.s16.value : 'short int', Dtype.u16.value : 'unsigned short int', Dtype.s32.value : 'int', Dtype.u32.value : 'unsigned int', Dtype.s64.value : 'long int', Dtype.u64.value : 'unsigned long int', Dtype.c32.value : 'float complex', Dtype.c64.value : 'double complex'} python-arrayfire-3.3.20160624/arrayfire/vision.py000066400000000000000000000356751276671162200214640ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## """ Computer vision functions (FAST, ORB, etc) """ from .library import * from .array import * from .features import * def fast(image, threshold=20.0, arc_length=9, non_max=True, feature_ratio=0.05, edge=3): """ FAST feature detector. Parameters ---------- image : af.Array A 2D array representing an image. threshold : scalar. optional. default: 20.0. FAST threshold for which a pixel of the circle around a central pixel is consdered. arc_length : scalar. optional. default: 9 The minimum length of arc length to be considered. Max length should be 16. non_max : Boolean. optional. default: True A boolean flag specifying if non max suppression has to be performed. feature_ratio : scalar. optional. default: 0.05 (5%) Specifies the maximum ratio of features to pixels in the image. edge : scalar. optional. default: 3. Specifies the number of edge rows and columns to be ignored. Returns --------- features : af.Features() Contains the location and score. Orientation and size are not computed. """ out = Features() safe_call(backend.get().af_fast(ct.pointer(out.feat), image.arr, ct.c_float(threshold), ct.c_uint(arc_length), non_max, ct.c_float(feature_ratio), ct.c_uint(edge))) return out def harris(image, max_corners=500, min_response=1E5, sigma=1.0, block_size=0, k_thr=0.04): """ Harris corner detector. Parameters ---------- image : af.Array A 2D array specifying an image. max_corners : scalar. optional. default: 500. Specifies the maximum number of corners to be calculated. min_response : scalar. optional. default: 1E5 Specifies the cutoff score for a corner to be considered sigma : scalar. optional. default: 1.0 - Specifies the standard deviation of a circular window. - Only used when block_size == 0. Must be >= 0.5 and <= 5.0. block_size : scalar. optional. default: 0 Specifies the window size. k_thr : scalar. optional. default: 0.04 Harris constant. must be >= 0.01 Returns --------- features : af.Features() Contains the location and score. Orientation and size are not computed. Note ------ The covariation matrix will be square when `block_size` is used and circular when `sigma` is used. """ out = Features() safe_call(backend.get().af_harris(ct.pointer(out.feat), image.arr, ct.c_uint(max_corners), ct.c_float(min_response), ct.c_float(sigma), ct.c_uint(block_size), ct.c_float(k_thr))) return out def orb(image, threshold=20.0, max_features=400, scale = 1.5, num_levels = 4, blur_image = False): """ ORB Feature descriptor. Parameters ---------- image : af.Array A 2D array representing an image. threshold : scalar. optional. default: 20.0. FAST threshold for which a pixel of the circle around a central pixel is consdered. max_features : scalar. optional. default: 400. Specifies the maximum number of features to be considered. scale : scalar. optional. default: 1.5. Specifies the factor by which images are down scaled at each level. num_levles : scalar. optional. default: 4. Specifies the number of levels used in the image pyramid. blur_image : Boolean. optional. default: False. Flag specifying if the input has to be blurred before computing descriptors. A gaussian filter with sigma = 2 is applied if True. Returns --------- (features, descriptor) : tuple of (af.Features(), af.Array) - descriptor is an af.Array of size N x 8 """ feat = Features() desc = Array() safe_call(backend.get().af_orb(ct.pointer(feat.feat), ct.pointer(desc.arr), ct.c_float(threshold), ct.c_uint(max_features), ct.c_float(scale), ct.c_uint(num_levels), blur_image)) return feat, desc def hamming_matcher(query, database, dim = 0, num_nearest = 1): """ Hamming distance matcher. Parameters ----------- query : af.Array A query feature descriptor database : af.Array A multi dimensional array containing the feature descriptor database. dim : scalar. optional. default: 0. Specifies the dimension along which feature descriptor lies. num_nearest: scalar. optional. default: 1. Specifies the number of nearest neighbors to find. Returns --------- (location, distance): tuple of af.Array location and distances of closest matches. """ index = Array() dist = Array() safe_call(backend.get().af_hamming_matcher(ct.pointer(idx.arr), ct.pointer(dist.arr), query.arr, database.arr, c_dim_t(dim), c_dim_t(num_nearest))) return index, dist def nearest_neighbour(query, database, dim = 0, num_nearest = 1, match_type=MATCH.SSD): """ Nearest Neighbour matcher. Parameters ----------- query : af.Array A query feature descriptor database : af.Array A multi dimensional array containing the feature descriptor database. dim : scalar. optional. default: 0. Specifies the dimension along which feature descriptor lies. num_nearest: scalar. optional. default: 1. Specifies the number of nearest neighbors to find. match_type: optional: af.MATCH. default: af.MATCH.SSD Specifies the match function metric. Returns --------- (location, distance): tuple of af.Array location and distances of closest matches. """ index = Array() dist = Array() safe_call(backend.get().af_nearest_neighbour(ct.pointer(idx.arr), ct.pointer(dist.arr), query.arr, database.arr, c_dim_t(dim), c_dim_t(num_nearest), match_type.value)) return index, dist def match_template(image, template, match_type = MATCH.SAD): """ Find the closest match of a template in an image. Parameters ---------- image : af.Array A multi dimensional array specifying an image or batch of images. template : af.Array A multi dimensional array specifying a template or batch of templates. match_type: optional: af.MATCH. default: af.MATCH.SAD Specifies the match function metric. Returns -------- out : af.Array An array containing the score of the match at each pixel. """ out = Array() safe_call(backend.get().af_match_template(ct.pointer(out.arr), image.arr, template.arr, match_type.value)) return out def susan(image, radius=3, diff_thr=32, geom_thr=10, feature_ratio=0.05, edge=3): """ SUSAN corner detector. Parameters ---------- image : af.Array A 2D array specifying an image. radius : scalar. optional. default: 500. Specifies the radius of each pixel neighborhood. diff_thr : scalar. optional. default: 1E5 Specifies the intensity difference threshold. geom_thr : scalar. optional. default: 1.0 Specifies the geometric threshold. feature_ratio : scalar. optional. default: 0.05 (5%) Specifies the ratio of corners found to number of pixels. edge : scalar. optional. default: 3 Specifies the number of edge rows and columns that are ignored. Returns --------- features : af.Features() Contains the location and score. Orientation and size are not computed. """ out = Features() safe_call(backend.get().af_susan(ct.pointer(out.feat), image.arr, ct.c_uint(radius), ct.c_float(diff_thr), ct.c_float(geom_thr), ct.c_float(feature_ratio), ct.c_uint(edge))) return out def dog(image, radius1, radius2): """ Difference of gaussians. Parameters ---------- image : af.Array A 2D array specifying an image. radius1 : scalar. The radius of first gaussian kernel. radius2 : scalar. The radius of second gaussian kernel. Returns -------- out : af.Array A multi dimensional array containing the difference of gaussians. Note ------ The sigma values are calculated to be 0.25 * radius. """ out = Array() safe_call(backend.get().af_dog(ct.pointer(out.arr), image.arr, radius1, radius2)) return out def sift(image, num_layers=3, contrast_threshold=0.04, edge_threshold=10.0, initial_sigma = 1.6, double_input = True, intensity_scale = 0.00390625, feature_ratio = 0.05): """ SIFT feature detector and descriptor. Parameters ---------- image : af.Array A 2D array representing an image num_layers : optional: integer. Default: 3 Number of layers per octave. The number of octaves is calculated internally. contrast_threshold : optional: float. Default: 0.04 Threshold used to filter out features that have low contrast. edge_threshold : optional: float. Default: 10.0 Threshold used to filter out features that are too edge-like. initial_sigma : optional: float. Default: 1.6 The sigma value used to filter the input image at the first octave. double_input : optional: bool. Default: True If True, the input image will be scaled to double the size for the first octave. intensity_scale : optional: float. Default: 1.0/255 The inverse of the difference between maximum and minimum intensity values. feature_ratio : optional: float. Default: 0.05 Specifies the maximum number of features to detect as a ratio of image pixels. Returns -------- (features, descriptor) : tuple of (af.Features(), af.Array) - descriptor is an af.Array of size N x 128 """ feat = Features() desc = Array() safe_call(af_sift(ct.pointer(feat), ct.pointer(desc), image.arr, num_layers, contrast_threshold, edge_threshold, initial_sigma, double_input, intensity_scale, feature_ratio)) return (feat, desc) def gloh(image, num_layers=3, contrast_threshold=0.04, edge_threshold=10.0, initial_sigma = 1.6, double_input = True, intensity_scale = 0.00390625, feature_ratio = 0.05): """ GLOH feature detector and descriptor. Parameters ---------- image : af.Array A 2D array representing an image num_layers : optional: integer. Default: 3 Number of layers per octave. The number of octaves is calculated internally. contrast_threshold : optional: float. Default: 0.04 Threshold used to filter out features that have low contrast. edge_threshold : optional: float. Default: 10.0 Threshold used to filter out features that are too edge-like. initial_sigma : optional: float. Default: 1.6 The sigma value used to filter the input image at the first octave. double_input : optional: bool. Default: True If True, the input image will be scaled to double the size for the first octave. intensity_scale : optional: float. Default: 1.0/255 The inverse of the difference between maximum and minimum intensity values. feature_ratio : optional: float. Default: 0.05 Specifies the maximum number of features to detect as a ratio of image pixels. Returns -------- (features, descriptor) : tuple of (af.Features(), af.Array) - descriptor is an af.Array of size N x 272 """ feat = Features() desc = Array() safe_call(af_gloh(ct.pointer(feat), ct.pointer(desc), image.arr, num_layers, contrast_threshold, edge_threshold, initial_sigma, double_input, intensity_scale, feature_ratio)) return (feat, desc) def homography(x_src, y_src, x_dst, y_dst, htype = HOMOGRAPHY.RANSAC, ransac_threshold = 3.0, iters = 1000, out_type = Dtype.f32): """ Homography estimation Parameters ---------- x_src : af.Array A list of x co-ordinates of the source points. y_src : af.Array A list of y co-ordinates of the source points. x_dst : af.Array A list of x co-ordinates of the destination points. y_dst : af.Array A list of y co-ordinates of the destination points. htype : optional: af.HOMOGRAPHY. Default: HOMOGRAPHY.RANSAC htype can be one of - HOMOGRAPHY.RANSAC: RANdom SAmple Consensus will be used to evaluate quality. - HOMOGRAPHY.LMEDS : Least MEDian of Squares is used to evaluate quality. ransac_threshold : optional: scalar. Default: 3.0 If `htype` is HOMOGRAPHY.RANSAC, it specifies the L2-distance threshold for inliers. out_type : optional. af.Dtype. Default: Dtype.f32. Specifies the output data type. Returns ------- (H, inliers) : A tuple of (af.Array, integer) """ H = Array() inliers = ct.c_int(0) safe_call(backend.get().af_homography(ct.pointer(H), ct.pointer(inliers), x_src.arr, y_src.arr, x_dst.arr, y_dst.arr, htype.value, ransac_threshold, iters, out_type.value)) return (H, inliers) python-arrayfire-3.3.20160624/docs/000077500000000000000000000000001276671162200165275ustar00rootroot00000000000000python-arrayfire-3.3.20160624/docs/Makefile000066400000000000000000000167021276671162200201750ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " applehelp to make an Apple Help Book" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " epub3 to make an epub3" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" @echo " dummy to check syntax errors of document sources" .PHONY: clean clean: rm -rf $(BUILDDIR)/* .PHONY: html html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." .PHONY: dirhtml dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." .PHONY: singlehtml singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." .PHONY: pickle pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." .PHONY: json json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." .PHONY: htmlhelp htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." .PHONY: qthelp qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/ArrayFire.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/ArrayFire.qhc" .PHONY: applehelp applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." .PHONY: devhelp devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/ArrayFire" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/ArrayFire" @echo "# devhelp" .PHONY: epub epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." .PHONY: epub3 epub3: $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 @echo @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." .PHONY: latex latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." .PHONY: latexpdf latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." .PHONY: latexpdfja latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." .PHONY: text text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." .PHONY: man man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." .PHONY: texinfo texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." .PHONY: info info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." .PHONY: gettext gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." .PHONY: changes changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." .PHONY: linkcheck linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." .PHONY: doctest doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." .PHONY: coverage coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." .PHONY: xml xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." .PHONY: pseudoxml pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." .PHONY: dummy dummy: $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy @echo @echo "Build finished. Dummy builder generates no files." python-arrayfire-3.3.20160624/docs/arrayfire.algorithm.rst000066400000000000000000000002241276671162200232300ustar00rootroot00000000000000arrayfire.algorithm module ========================== .. automodule:: arrayfire.algorithm :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.arith.rst000066400000000000000000000002101276671162200223440ustar00rootroot00000000000000arrayfire.arith module ====================== .. automodule:: arrayfire.arith :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.array.rst000066400000000000000000000002101276671162200223530ustar00rootroot00000000000000arrayfire.array module ====================== .. automodule:: arrayfire.array :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.base.rst000066400000000000000000000002051276671162200221530ustar00rootroot00000000000000arrayfire.base module ===================== .. automodule:: arrayfire.base :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.bcast.rst000066400000000000000000000002101276671162200223310ustar00rootroot00000000000000arrayfire.bcast module ====================== .. automodule:: arrayfire.bcast :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.blas.rst000066400000000000000000000002051276671162200221620ustar00rootroot00000000000000arrayfire.blas module ===================== .. automodule:: arrayfire.blas :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.cuda.rst000066400000000000000000000002051276671162200221550ustar00rootroot00000000000000arrayfire.cuda module ===================== .. automodule:: arrayfire.cuda :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.data.rst000066400000000000000000000002051276671162200221520ustar00rootroot00000000000000arrayfire.data module ===================== .. automodule:: arrayfire.data :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.device.rst000066400000000000000000000002131276671162200224770ustar00rootroot00000000000000arrayfire.device module ======================= .. automodule:: arrayfire.device :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.features.rst000066400000000000000000000002211276671162200230550ustar00rootroot00000000000000arrayfire.features module ========================= .. automodule:: arrayfire.features :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.graphics.rst000066400000000000000000000002211276671162200230370ustar00rootroot00000000000000arrayfire.graphics module ========================= .. automodule:: arrayfire.graphics :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.image.rst000066400000000000000000000002101276671162200223170ustar00rootroot00000000000000arrayfire.image module ====================== .. automodule:: arrayfire.image :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.index.rst000066400000000000000000000002101276671162200223440ustar00rootroot00000000000000arrayfire.index module ====================== .. automodule:: arrayfire.index :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.interop.rst000066400000000000000000000002161276671162200227230ustar00rootroot00000000000000arrayfire.interop module ======================== .. automodule:: arrayfire.interop :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.lapack.rst000066400000000000000000000002131276671162200224730ustar00rootroot00000000000000arrayfire.lapack module ======================= .. automodule:: arrayfire.lapack :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.library.rst000066400000000000000000000002161276671162200227070ustar00rootroot00000000000000arrayfire.library module ======================== .. automodule:: arrayfire.library :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.opencl.rst000066400000000000000000000002131276671162200225200ustar00rootroot00000000000000arrayfire.opencl module ======================= .. automodule:: arrayfire.opencl :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.rst000066400000000000000000000011201276671162200212370ustar00rootroot00000000000000ArrayFire Python Wrapper ======================== Introduction --------------- .. automodule:: arrayfire Submodules ---------- .. autosummary:: arrayfire.algorithm arrayfire.arith arrayfire.array arrayfire.base arrayfire.bcast arrayfire.blas arrayfire.cuda arrayfire.data arrayfire.device arrayfire.features arrayfire.graphics arrayfire.image arrayfire.index arrayfire.interop arrayfire.lapack arrayfire.library arrayfire.opencl arrayfire.signal arrayfire.statistics arrayfire.timer arrayfire.util arrayfire.vision python-arrayfire-3.3.20160624/docs/arrayfire.signal.rst000066400000000000000000000002131276671162200225150ustar00rootroot00000000000000arrayfire.signal module ======================= .. automodule:: arrayfire.signal :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.statistics.rst000066400000000000000000000002271276671162200234370ustar00rootroot00000000000000arrayfire.statistics module =========================== .. automodule:: arrayfire.statistics :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.timer.rst000066400000000000000000000002101276671162200223550ustar00rootroot00000000000000arrayfire.timer module ====================== .. automodule:: arrayfire.timer :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.util.rst000066400000000000000000000002051276671162200222160ustar00rootroot00000000000000arrayfire.util module ===================== .. automodule:: arrayfire.util :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire.vision.rst000066400000000000000000000002131276671162200225470ustar00rootroot00000000000000arrayfire.vision module ======================= .. automodule:: arrayfire.vision :members: :undoc-members: :show-inheritance: python-arrayfire-3.3.20160624/docs/arrayfire_logo_symbol.png000066400000000000000000001055501276671162200236340ustar00rootroot00000000000000‰PNG  IHDRîîñ“Ê pHYs.#.#x¥?v OiCCPPhotoshop ICC profilexÚSgTSé=÷ÞôBKˆ€”KoR RB‹€‘&*! Jˆ!¡ÙQÁEEÈ ˆŽŽ€ŒQ, Š Øä!¢Žƒ£ˆŠÊûá{£kÖ¼÷æÍþµ×>ç¬ó³ÏÀ –H3Q5€ ©BàƒÇÄÆáä.@ $p³d!sý#ø~<<+"À¾xÓ ÀM›À0‡ÿêB™\€„Àt‘8K€@zŽB¦@F€˜&S `ËcbãP-`'æÓ€ø™{[”! ‘ eˆDh;¬ÏVŠEX0fKÄ9Ø-0IWfH°·ÀÎ ² 0Qˆ…){`È##x„™FòW<ñ+®ç*x™²<¹$9E[-qWW.(ÎI+6aaš@.Ây™24àóÌ ‘àƒóýxήÎÎ6޶_-ê¿ÿ"bbãþåÏ«p@át~Ñþ,/³€;€mþ¢%îh^  u÷‹f²@µ éÚWópø~<ß5°j>{‘-¨]cöK'XtÀâ÷ò»oÁÔ(€hƒáÏwÿï?ýG %€fI’q^D$.Tʳ?ÇD *°AôÁ,ÀÁÜÁ ü`6„B$ÄÂBB d€r`)¬‚B(†Í°*`/Ô@4ÀQh†“p.ÂU¸=púažÁ(¼ AÈa!ÚˆbŠX#Ž™…ø!ÁH‹$ ɈQ"K‘5H1RŠT UHò=r9‡\Fº‘;È2‚ü†¼G1”²Q=Ô µC¹¨7„F¢ Ðdt1š ›Ðr´=Œ6¡çЫhÚ>CÇ0Àè3Äl0.ÆÃB±8, “c˱"¬ «Æ°V¬»‰õcϱwEÀ 6wB aAHXLXNØH¨ $4Ú 7 „QÂ'"“¨K´&ºùÄb21‡XH,#Ö/{ˆCÄ7$‰C2'¹I±¤TÒÒFÒnR#é,©›4H#“ÉÚdk²9”, +È…ääÃä3ää!ò[ b@q¤øSâ(RÊjJåå4åe˜2AU£šRݨ¡T5ZB­¡¶R¯Q‡¨4uš9̓IK¥­¢•Óhh÷i¯ètºÝ•N—ÐWÒËéGè—èôw †ƒÇˆg(›gw¯˜L¦Ó‹ÇT071ë˜ç™™oUX*¶*|‘Ê •J•&•*/T©ª¦ªÞª UóUËT©^S}®FU3Sã© Ô–«UªPëSSg©;¨‡ªg¨oT?¤~Yý‰YÃLÃOC¤Q ±_ã¼Æ c³x,!k «†u5Ä&±ÍÙ|v*»˜ý»‹=ª©¡9C3J3W³Ró”f?ã˜qøœtN ç(§—ó~ŠÞï)â)¦4L¹1e\kª–—–X«H«Q«Gë½6®í§¦½E»YûAÇJ'\'GgÎçSÙSݧ §M=:õ®.ªk¥¡»Dw¿n§î˜ž¾^€žLo§Þy½çú}/ýTýmú§õG X³ $Û Î<Å5qo</ÇÛñQC]Ã@C¥a•a—á„‘¹Ñ<£ÕFFŒiÆ\ã$ãmÆmÆ£&&!&KMêMîšRM¹¦)¦;L;LÇÍÌÍ¢ÍÖ™5›=1×2ç›ç›×›ß·`ZxZ,¶¨¶¸eI²äZ¦Yî¶¼n…Z9Y¥XUZ]³F­­%Ö»­»§§¹N“N«žÖgðñ¶É¶©·°åØÛ®¶m¶}agbg·Å®Ã“}º}ý= ‡Ù«Z~s´r:V:ޚΜî?}Åô–é/gXÏÏØ3ã¶Ë)ÄiS›ÓGgg¹sƒóˆ‹‰K‚Ë.—>.›ÆÝȽäJtõq]ázÒõ›³›Âí¨Û¯î6îiî‡ÜŸÌ4Ÿ)žY3sÐÃÈCàQåÑ? Ÿ•0k߬~OCOgµç#/c/‘W­×°·¥wª÷aï>ö>rŸã>ã<7Þ2ÞY_Ì7À·È·ËOÃož_…ßC#ÿdÿzÿѧ€%g‰A[ûøz|!¿Ž?:Ûeö²ÙíAŒ ¹AA‚­‚åÁ­!hÈì­!÷ç˜Î‘Îi…P~èÖÐaæa‹Ã~ '…‡…W†?ŽpˆXÑ1—5wÑÜCsßDúD–DÞ›g1O9¯-J5*>ª.j<Ú7º4º?Æ.fYÌÕXXIlK9.*®6nl¾ßüíó‡ââ ã{˜/È]py¡ÎÂô…§©.,:–@LˆN8”ðA*¨Œ%òw%Ž yÂÂg"/Ñ6шØC\*NòH*Mz’쑼5y$Å3¥,幄'©¼L LÝ›:žšv m2=:½1ƒ’‘qBª!M“¶gêgæfvˬe…²þÅn‹·/•Ék³¬Y- ¶B¦èTZ(×*²geWf¿Í‰Ê9–«ž+Íí̳ÊÛ7œïŸÿíÂá’¶¥†KW-X潬j9²‰Š®Û—Ø(Üxå‡oÊ¿™Ü”´©«Ä¹dÏfÒféæÞ-ž[–ª—æ—n ÙÚ´ ßV´íõöEÛ/—Í(Û»ƒ¶C¹£¿<¸¼e§ÉÎÍ;?T¤TôTúT6îÒݵa×ønÑî{¼ö4ìÕÛ[¼÷ý>ɾÛUUMÕfÕeûIû³÷?®‰ªéø–ûm]­NmqíÇÒý#¶×¹ÔÕÒ=TRÖ+ëGǾþïw- 6 UœÆâ#pDyäé÷ ß÷ :ÚvŒ{¬áÓvg/jBšòšF›Sšû[b[ºOÌ>ÑÖêÞzüGÛœ499â?rýéü§CÏdÏ&žþ¢þË®/~øÕë×Îјѡ—ò—“¿m|¥ýêÀë¯ÛÆÂƾÉx31^ôVûíÁwÜwï£ßOä| (ÿhù±õSЧû“““ÿ˜óüc3-Û cHRMz%€ƒùÿ€éu0ê`:˜o’_ÅF€“IDATxÚìÝKs#Y~ßýÿ!‹U¬Q„Èyæµù"Ûűl˲<.´îǪ̀©WÐìÝH#U³«F]§X#ÉÚ¸[ì^i7ìW v„ýìž*¼ÑΨµf½tƒrÄŒ»ŠÀy™ ‘ÀÉsË“‰Lä÷¨nHdžL¿<øç9Jk-Úm‹&îîÁÁÁ ¸ ¸ ¸ww€à€à€àÜÜÜ‚;‚;‚;@p@pîîîÁÁÁ ¸ ¸www€à€à€àÜÜÜ‚;‚;@p@p@pîîîÁÁ ¸ ¸ ¸www€à€à€àÜÜ‚;‚;‚;@p@p@pîîÁÁÁ ¸ ¸ ¸www€à€àÜÜÜ‚;‚;‚;@p@pîîîÁÁÁ ¸ ¸ ¸ww€à€à€àÜÜÜ‚;‚;@p@p@pîîîÁÁÁ ¸ ¸www€à€à€àÜÜ‚;‚;‚;@p@p@pîîîÁÁ ¸ ¸ ¸www€à€àÜÜÜ‚;‚;‚;°îlú*¥ØËòøÉÓGùî‹ÈáÂ]‡ùß \µáÇ~ð{jûì6ø’#™,Î/ü÷e~¹üøÃ^±—ºAkMp}0?ÌÃ÷`)Œ›B9u94üm`ùþZ÷óà?‘ÉÇ~ð‚&Á] èDä ¿ þ€.˜B~ìçA~$YoýHDFøÁÍ‚;ÚÒæ`‡ 7úf?ÿ>\õ— ~H˜ÁMõG LZ«ƒüv´ð]:ñCÉ®¡"ȃàŽ$AýAþa3XüÐÑóÛÉR¿ ^w„†õ‡"rœõZ€f‚üã'O'"r‘‡øOiÜa ëò°~LX`möçßÇ„xܱØßÉ? ´­ñç"rƸòwô+¬ïIVWw"ŒŸ@WBü‰då4C9¥žàŽÍìDä4?{Ý4‘a>ÔäéÇ~ð MBp´×ˆœ?~òô”OpG÷;%1ô+ÀSB³¹¶h‚ íoK6KÛ)¡€Þøáã'Oÿ>ÿµw´<°ï=~òôï$>ꀠw"2züäé3š‚àŽö†ö·EäR˜á€¾Û‘ÓÇOžþ¯|bEÜÑ¢Ðþ7’õ²ïÓ w(YùÌ;4Áëì{Ÿ<ý_’]€ °l_²‹WHSܱ¾ÐþP²Ò˜CZ8ç¥3{4Á͆öG"2Jc€¿CÉJg¨{'¸£¡Ðþ¡Þ îhh?§%@û„w‚;ê íoÚ@âðÎdMw$í í †ð~Á«w¤ 턚vPCÉæ‚ÁCûž0±¨× ŸÌwTp&ŒÓêw’_O‡–ºC´Wþæ9¦%1\øï‘ˆL–‰ 6/DD•Ü÷há¿%ûú`é†tÎ?yzøñ‡¼¢)îðí„‹Qëç—ùm˜‡ó—4 ´>Ô›þ{9Üæ·a¾’ý<¼ESÜáïL¨k¯b’‡óù€Ž^û«Ddò•¿ýÇ+Z= ÷‹¡þAàòù> 3xüäé;øÁ'4E»PãÞBy‰Ì-ìRn¯ ø²ˆü¶ˆ|DhGOŠÈåøÛ_}6þöWæ }óJD>É¿¾œ§žÓ,AÎ"’àwhßËÃ'üLòãCù)yŸ ˆÈí²§"2û«?Ì{á>úTDÞÍß'ÂuK>æŸ ¸ÃâD¨Íóq)Ù…»ù‡1aX—È,†“cÉzàÿ†xôØ•d¿ÄþÔü=A“Ø3 ³ªÜQ"ïm?¡%¼ûOIö3(õ»@¹aIç%4@öB€w;¥ î0;. )3ÉÇ<°ˆ î"·?Æßþê;4ðrH@-uL¯;ÁKò7Å1-at.YIÌG4dä¸ÿ@DÎÇßþêß¿ýÕ‡4zìJDžç~Ds¬à¤†àŽå3Zš`ÅD²a¼ÞJb€`_ùÛ|)«“‰™ $ë}§þ}÷2?œÓÅŒB¯;Á9jÛ†’õ¾ )€JF=‘¬þ)ÏÑgW’uÓ§4Áù™¬PÛ¾èL²ÛèeÒœ‡Ø‘‹ñ·¿úwô¾£çæµïšBDDŽ×àŽÌ MP8‰yŸf’Å~I ½ïÀ¼t†ðžÔÑ ÷^{üäéCaÜöÅÐΈ1@;‚ûü‹šÞwÞ ïs'4Á7í@M¾ò·ÿø*ÁbŽ$»xõ- Â{¯r‘*Á½ïŽhB;P³a‚eˆÈpüí¯>£9Ñãð~B3[î=õøÉÓ·…‹RÏí@íF —ušûNé úè“ü{«ÏŽ9 öÓP¸hÂ$ñò’]¸Jé úè}Ió+VWQ.Cp'¸÷4Hq$§¶/YéÌ{4/zèXú]ïÎ÷7Á½_òÑdö{þ¦gœv —5.ûlüí¯þÒôÌ+é÷„D‚;g«ýq.̈ 4&ÑÈ26Ç"2û§ ï蓤¿%3Gì~‚;g«ý0®ÊÖ@]Š(©ñv("—ãoÿôCÚ=rÚ× üä)׸Ü î=p"”ÈëpÙÀkì‹Èpü;?ýÍžx!Ù¯ÈäÜ9KÝÈàÀÐÀ:¨Ænû"rNxGœöt»ÙõwÎRùpPaïw>þŸþš=ðJúÙë>`×Ü9KÝ\—Bo;Ðbµt¿ŸŒçŸý¶Eô1¸ï3ž;ÁྐྵNÙí@sÆßþªŒ¿ýÕ€`^›cÂ;zà…¤¡˜<‚{<~òtODz¶Ù¡·hI€_‹ãñïü³¿ÿÎ?c¸Hl²3‚;îä›àœÝôÞ‘ˆ ïØ`dÜ9È7Á»hÖWþöÛúù7ÿî?'¼c]õ0¼°Û î›n¿gÛ;’ìŠ{ë¤T[n„wl²¾÷Cv9Á}Ó z¶½çìr†/û3š÷îcd‚û¦ÛçC äxü»ÿœÑf°i®¤ù9Öí€ÝNpßd‡=ÚÖK¡LX›–Ö¹Þ±éî ¸£“.h mTËnr<þÝÎ « ¸ÜApo—ÇOž>âà Àšû æ‰–ªœHœŒ÷_¼Ã>†xѳíÝg—ÜApÐ/ç„wðý×I‡ìn‚û¦:èѶŽ$»H@W¿\+UÀD9ç_»›à>´¤sØd·y&:ôÞ± .ûõù‚;îúúÅz(LЄn{A€àΗ'Á@_>{ŽÇßù—ï±ëÐaš÷nÛïѶra*ÐƒŽ®÷Ùø;ÿò»5¢ @pG i Æßù™"ê }/yר_Œ¿ó3Ô»-öøÉSÞ£w@ƒî®úÍŪìFtаGÛzÈî&¸ƒ+Õ³ïQ7;Ú‹'ãïüÌ3v&‚;`“ :x²aºŽïg¨wG—LhÜÑ—4°~ãßû™·e墸öw¯[œï_QK‹®Ñ ¸ƒàÀ“:J;©R-ër;‘sö+‚;`cä=ÓG¸iGãßûWo³‡Üpes玠dÁHä’&Öîxƒ·m_(™@p’xEë3þ½ýPD ‚êÇUÍ·ô±R2ƒ¶Ñ ¸씜Ô;¸KÔ:U¼OÎÇ¿ÿ¯)™A[]Ñ ¸JåAöxÃOLæ·}9e¯ ¸ºè¤oÛ;þýÍÄLî€îÿþ¿Ù[ ·`gì}w@—œˆ¨ývO¸ä#8ìŽÿß¼Ãî@p´ž¹·½WÎò6‚; ÕNds'\ò±/\¨ €àh³ñ㇫½í¡C,6z“º†§<ÿþ¿yÀ€àh«Qj?|£uI1!Téæœr8 ¸ZÇØÛÞ ¥aÿxüø!ÃC ¸ZçLú]ÛnrJ ¸ZcüøáÙôYRã èu@p´Éùíª ¿;åð@p¬ÝøñáÛ"jÐ퉖BýÁøñ!½î;k< ¯­ó¿÷µw8–ܵŸüÛg¢äpc >g©’ÕWpÌ€à¨#´?fÿLôã“ËÐî€äÎS'× ¨•©ê„à ÁÌøäß>‘ÃÍ›h©î§cŽ.w@¢Ðþ³³Iƒ‘>èïO~ömÚ ÁÂ9MP«#šÁPÉøägó™ÔògÕ²ÛzJ|ŽÇ'?ËLªî€èÐî1ŠLlH–vVÞÜd÷ØÐíˆ#ÁbÕ¹WÇBèøww@¸ñûÿ®¦”ü£ñûÿŽrw@Ph$­›h©uã¯×ሣÁàÚ÷$É(2m›ø¨õ1ÜÜANEä zøÝtµ}ÊeÜnã÷ÿý#uÒß0¾Î c@[ ¸l¡}OD.ͪ]½Õì8tÅšÖâ\Dö½òe¥pÚU:n3tð 8t=îаñ“ÿŽˆ…õ6oìÈ.–“Žˆm o–ƒñûÿþ!G%‚;`)´ÿ‡"rÊQ=è—>t@û ¸–‹¨}By«Âým  ¨q€†ŒŸü‡gÒŠšê¶œ,è¶ìšG'€. Çš í%é쨛0«i{¶aüä?<â(@pB{ÀÐ ×æ1ù‹ 8Rܧr3;j¢ I‡{¢!¸èjÜ Fã'?÷¶ˆœåL¤k'í½ ‚;€Ö£Çê íOnO²‰–Š9±ÖÞp¦Nmïñ“Ÿc#˜w.ØhmF© ¤ íy]{›JWzPËžÆA¾ÿ •èq€´N¥Ö’ Uéîv3¬¼sT˜ä³¯ŠÈ cmD;$2~úÆ~4WÃM-Þ¤_צ:;ê—Ú§zÃr$h+zÜ‘Ú%M€ž†öÕ¡)Ôý'T ú¶;Œôšà€à‚;Ð#"²ß­p¾®Ó-ÛäB¨?àP@p€ 5~úóï­o ð.vÙWYg]÷j 8¢´5îP%´÷犒³zRd_'\Zo»Œ¿ûó8²‘È%M‚;´#´{ÔµÇPÔð­h?ÜAp€Ír*Ö‹[̾ݷ1ÚÚˆwˆ0þîÏ/ ýØpúTÉÔ¥«ê¨g¯¯Ü}Ÿ#Á}0¡ °ù¡ý?U(‘‰ ±}­g÷½[§ ÷‡åîèƒM€¸Ø^YE(o4ä»Â½9ØОîÐqãïþ§÷ÄgÈ@E8ïD¸WÆOpG*—4RââTðíE–†~\¹®Qe·VŽÃÕ©¾m3þƒ_`HHÜÑ:ô¸€Ohÿƒ_ØÑçÅ ·î ¹)b·¥ÖXDäG>‚;6Ù%M€ u*¢{È«®†nËJF¯È>‡<€¶¡TwÀaü¿°0ôcªÀYCÙH›ªWZ³.Ñ >äÈÐ6ô¸€=´Gý˜¨ç¼±øº_H7³j:Õ‚5?RÒ ¸@s.ÄZ6‘ —¼[ ë§«¿Œwo¢, îX¯Kš›bü¿ðL C?F†ÏèÌÊ’qí¡ãQ|Ú>í €àŽMÇ( ØÐþŸŠÈi½9›`¾ž€¯ÙhÊ%M‚;ÔÚ÷$+‘I”¹I„Ý ö7¡~@;!:³@pGkMhlˆ3™ÏžÙù€ÞÅ“M{Á5Ñèºñþç·E丽áN­å©ÍæôÚ†‘Öa"\3DÇnCûYú±ŽAÎmÉÚsPóuŒÍ¾ÎÍ.Ý–ú6|ü‡_À» ŒhÜÑF—4ºM‹¨ýzÓn¢PÞû]•*Ü[ÐÐÚ„RÜÿá×—†~L‘,Ãïj.õ¶^ïfj׃(Ãß ¸@ÛB{øÐ­è]ïz]]ïËëMi_ÜApÊht0´»‡~t%½Zò¡±ZÛhšÁ°˜Ðè 31Ö2×ÒI‡ë ÷”Á 1Cš©pq*Rº¤ Ð%ã?üz>ôcÉE‹I. íèÕ¥ªâ­³X0à] MèqGJ̇…öÿ²:ôc¥ÀÙ‚´ªÚ¸.UèÂ?Zq`ш&Ám3¡ Ð)JÎ%zRÕôºö4Pª€æÖT¿ ­®h¤B© RÑèŠñ÷þKÀÐ Ô(QªüF/°_#ÚÚ&Äz]Ò ¸£M&4:Ú-C?ÖÒmáœT¹æ`Oë€à‚;V 6xÛFì^´?´?Zú±†^ÐמUn- õß‘hjÜAoúäTD¤Ë{ë v›(C·‹¢vtÆd÷oŸ]Ü zÜApG/Œ¿÷èm9©ÒëíüX‹ }Ú 0Úðí;d7ƒ÷†<~òôÁX[hß“å¡]yPêækȸm¦×±ÑôØ£1š)ÐãŽTÃmv!¶Ÿr—ëÒ“¥Ü{‚k)_cýúZJâé©Gc^løö ØÅ͠ǃ:…!»m5þÞ£÷VÞµ”¹¨5/ªí³êúéðEêìKàÖ¥ˆlè¶í³{ î›æ`ƒ·mÂîE+Cû ŠÖgéK_TË Hú·ö{ U2 ¸§tÈîm¥2Ô)ŒØ½hahÏêÚ+—¾T(¥ð.óà"Ë´ߣinð]™Ôã'O²‹ îw>Œ€X§áï»Ä!¤ØýPð]IÎ!¸÷KF”!¸£UÆ4x$^C?ÖÒÛÎUGo­i«!ï&$t¹áÛ7`×wæQm íK³£.‡³ˆ<wg³/£›zqŠÕÑŒ,ƒÊèqoÆÑoÛÝ‹–9—Â=¹A=éu%憇U¬cÓ[¶öàF£ Þ¶êÜ î÷øÉÓB};Јñ½õžˆ:ªtÝwÔœj+áM“d» ôhË ß¾»˜àÞuGô„ö’]Ú¢ äVÇõrzð™Ø1»˜àÎȦàãBL“€4Ô=`-9¶K€®q½ƒysç%o+$6Üðí;Ì+ @pïž”Ɉˆ¼dOcÝÆôÖ³›÷ZíA½Bz-á¶ojh“²ÅL_sá=R{уmßP—a¶ñ”ÝLpïš>|€úŒÿøß–¨_µRö¦74}ƒ¸t³ê&ô þ œð.ßÑz0k<Á}S<~òô=9Øð͉È{k íK%2!‰06¨7mÁ\(·îŽ:‚= Z¼’ÍÏ]DäŒ]MpïBhß“~üD4doc.¤´­® Þp8G}ÁÞ¯¡/iDðZÉ!µî÷.8‘ͯm'¸cmÆü‹ïÉÊì|m êe}]á\µü¶®¦( ôwðZÝiÞ¡ ‚{ûäã¶Ÿò¡ÔÚÊÍϯa½± ¾Ž€¾)£¼´h{–=PŸ‹žlç0®;Á½ÅÎ{Ú©oÇ:ÂÝy|XO<®»)¤7d{,ÔÝ>CÂ;jt%ý™íôñ“§Ùå÷VÉ/HÐSÔcüÇ¿ô7âœÕîRõ”¹¹ÅÁ¼óøsÒ¾K[äœÝMpoShïS‰Œe2h:´ÿÉ/=%'Íôª×Ñ›¾®r‰o½jrO5>|£TpÉ;÷d?yúŒ]NpoÓ›o¿'Ûz)"/Ùåh0´;†~¬!¨'…M„òØÀÝ´Ø€&6aa¡Ó7¯x÷¡f/{v‚HÉ Á}ý?yzûó==@Îde^„*©ÍÛÒ+…òMW!܇›ð¶ß©õl/£ÌÜ×Úß‘þ]-}ΞGSÆòK ³£Æ&±T5ê ÃrY8§&»žpo öf#Ú|§Öâ@è$¸¯)´/ K×—B™  í¿¼W:ŠLPXOÔSäH[Ï9ÖìͳÒNh+4¤oå2""ƒ¼Z÷ÆBûÉ.ÐÜïÙ¦s–Œ¦·€÷XÕ^õŠAÚ«½Aµ·5·“R#Þ~໵V'̪Jpo*´ïI¿.F]tÆ€&Œÿä—=‡W­R«^!,®=¤oʤK­Ý¾ ?„€ïÖÚÞ îM„ö¡ôëbÔ¹‘ˆ0ÊšíÅ:¼jª°›#›5Öê\¯má#J˜Ð WҟɘVNZi†àNh§GÝv.+¿hņõÈ g êM„óƒxÛÔºþÑ ºäm¾c±/"CÂ;ÁОÖD¨oGÆòËÏnßg)Âz[‚z…Z[ïhW{²E[žÌîhÞ…ô÷¢hÂ;ÁÐ^ÃÊGj íú+EÔi#a½¶ ™$k ¡mîz¯q«µåˆw#ÖàJú=Ü2áàNhO蔣5‡öì¢ïFÂzA½®@Ù÷É—BÂ~åöŸðŽÄšœõ|û÷EdÄ«÷ØÐþP²‹EúÚ/„‹RÑÌÉáAÒ°^Ú«ž24¦ èóúý×S†´=Öä•0É¡£ÍÜ#Bû#ÉzÚh .JE½Æú+Ä:qdX¯¾*„ôç]‹½Ê6\Þüyúš7(Öщ,¼ÿf ¸û„öw¤Ÿ“+™ EäÍ€Cûž{˜bÂzÕàÔÓ$ú–…nÏ’“u®C}íuYü;ШWÂ`sÇŸ<ýû¼l÷•À¾—ŸÝÓœù£Ñcì MX¯تõ¦Bg@àmb@˜Ú_c-DnÇšÐ7’Õ½sÑ*Á½ÚHÖ»|LkÜ ½í¨ÑøO5/‘i2¬{¾¨ ÞT8—ÍŸ45*³'kˆK™¾¹¢¾kF­{Ñd#ÎP÷NpyüäéÛÂE¨œñ£éО—ÈøŽ’*¬ÇdðºRqd8GÐyN`C^Ò h‰Sa„£Eû’×½÷½t¦·Á}¡4æB¨g_v."/iÔ|bxàÎÙ1iÕЂƒúúZRn'cªêw W¬Å+ap“céyéL/ƒ{>jÌH(1™½í¨ÑøOõ¡˜®Ÿ¨4L@¯zÜ*$źój×Gz‰9¡¨í%/y‡¢Ež ¿™äáýY7þNÏû^¦åN„YRQ¯óBx*þG`òн;e¹KM‹N¿° âj»àÑí²5ÍŒ68–ìš3¬:}üä鑈üὩèMûB/;¡½ÜPD>¡P—ñŸþê{"r_ S¥g=õ¸î*ag0íéƒ}D{Nß¼,^W¬Ý ¡dÆæPòÞ÷¾Ô¾o|{>bÌ™ˆq|[M„Ò!ÔÚÿì׈èÓä½ëµõ¬×ћ޲0¨šZ?íõ§5lðâÊŒVNxG+¼/Ù°ˆ‡4E©SÉÆ}?‘O7yC[Ýã®”ªt{ïéwŸåÆ„v·cÉ.†êr&¢öÃB–Ǧ¥w$¦ÒâîA_ì)ö½5¶~¦_+|oMœï(Q#Þ¢hùwô„f°:‘‹÷ž~÷ïÞ{úÝUòc›md{^s.e£VÀ¨6û ë5þ³_{äwÓ³ž°W]%ZN¹²‰×i%å±éºðO$‚;ÚìeÞ/h §#9züä驈œ}üáuÝÞFÕ¸?~òôáã'Oÿ^²ZmB»Ÿ¡d?Ãu:w‡³Øžõ˜ XR£³Œ”aº¬Çœšw¿ýQ­Ç~TاÓ74+ÚæSá:½§"r¹i7mD{^Ç~*Ôh‡ eD¨ÙøÏ~í™ùDº©Þõ½ê‰C³ªa™°ï»•æ^꥟¾a¦htÁG’Õº“wüìK6qÓ©ˆœ|üá¯.ètp'°W2‘ìb†~D¡}OVzˆTÂz±Â[лp¢ ›oìŸQêöÿ{_ùÁÿàóux7ÿ—ìãï@D.?y:‘Ó?ü ³'ê,•yüäéƒ|ÖÓK\B;ZíLDöKËJ’–ÂX., zn…À¶\êR{XÞ„É—b¶'¹a ‹?ÿ?ä#5†÷sš!Ø@D†Ÿ<ýûüzH‚;½õFùû’¦@ÆöëDÔ±µvÝÿŽšÃz‚^KPß„0¾Ž€ó¹¸4âMÇãïã=> Pcx?¡*ø·»´â(•yüäéÃüà$¬§ íô´£ §Æ¼å÷GGh‹yzÅ0VkÙK!¼kù^×¹ÑÚöÙ˜ºÝòÏÆßÿÆä+?øLn‡:|$Ygæ¹dõÜðƒÇOž^JVBÓú÷i«ƒ{þ3ÆiÞ°¨æBD~›f@Æöëoß¼o“Õ®«fÃz-A]µrQÍ¥{nUt²íœÈôõËÚä`á¿ÏÇßÿ†ÞQ“O…¡"S¼_籞‹Èó¶®hÛKeÂLa)Ê4r–¦v½dèFßç„fº¤e/ J8‚«ATä­) ×/Ýæ ëÙTuP’Rä|üìùh@ æu MV:hó ¶:¸üáÏóà~αTÙ¡d?óÅZÿü×ßµüÁ×°ž<¨×ÎûZó¸ÝaM4Zy@š1Ü +”cÃñ³oòŒ”æßí‡4E%ÉS8øøÃÞ%¸W ï¯òF< ÀW¶/YïÒ;4j í{Rèù‰ ìu‡õ½ê‘¡¹r8OE·äÖD°w>t¸ú€Šïƒgß|`ù ¾?ûæŸHàü;}Ÿ¦ˆv)Ù5”øÁûøÁ«¶¯pgÆqÏóݼþèT¸PµJxŸŸQo‰ÔNäføGßÀš—bJNRô¦§~Jê ÞEºþýàºPµž‰—÷ Eäk|\ bh?§*öN\Œº¬sã¸ÓŸÌ¹ˆ<¢ÊøÏcODø…«š{×WêÕcúçk:;z«öž7Õs½¼Ê:òVgÐOÕYéŠq÷Tþ•C:ž{8~öMÆx¡}=ýøã?ø©.†öNwC€H]m¾ ¡æ霈ó'ÛÀS/^¥& X×ÒóèÐß*è5½~p­å4Ó×± °ïq Ÿ}“1Þê!¡½Ÿ}îN×÷D>mí[ùБg¡_.CÉ~½`lwDËzÛË& -‡‰¨Y¦<,æõ«†âTÊ£tHûë’àn[FtCÜËÒ""gãgß}åùÁ§yüäé3ñúé’ýJñ7"ò>MPã?ÿR¸X<¤‡=pØÄ¤'ú>,ä5CÃhÊ ÞE5^œZÖcÛKoî°˜¾‘*;e|ú[{"ú`euµµóäB¸XîzH3xJVój7nkS÷Z~†u Ô‚ù:.VEü±#q=ì>,¦n½J¯z•uÛkUé=_ÃÅ©­ úÛá¶—~X_Gˆáø±V‡ãgßú>JPâa$=—"rôñ‡¼µ©¡}£ƒ{Þ¯ò X…rç’ýxÿùoc¿É’BGi -…ñX¾ò ë)‚º©t£J0­+èoJÕsk®„&æÂT[¢Žêy?ô:.Wÿ|2~ö­·ùTÁ’’õ¶ÃîLD?þðƒO7}C·ú°7?þðƒ—øÁ["r$Ô¿ÛÓ&#̉(ÙoGïzHž÷íU÷ ”Á=é)«O— []B×Ã?ðWh«éìE=s\éÃà3ÇÛ?O©wGÁ¹Pòks)"ƒ|ò¤^ ²±Õ³üiÞB8µ1JfàaüýßÜU6’L@`¯£w=ºW=2¨ìø`îÊS„ÿ6\”êð#_c˜äDÓlà¿.+Çä¾dõÈÛb¡¹³<ÓõjT¦Þ÷ÇOžÎÿóJDž å3®7às’·_9°ͲêÙ»Ö«õÈdŒá<&”7<ªK´ta?<Ô‹”†ãé›…C&<¼ŸkOŒ³¦…øÃñéo=ãã¥÷öø..5ÉOhÞÏ3<~òt1çÜ»ØKvæKy+Þ‡’] ØÇvØ}ó|аÔcBºo8osoCØ÷ õZDôÐïD0x†Û{8J¯}v:>ý-~ù¤cä€fX1ÌÛåEYæ#¸w<´{øHè}79.TE‰ñ÷óÛ/•ÐÀÖcJa"úWzHPöëE÷¨u†Þ6ÝRo㊉LÕ˨“N·Aq‘¡'çÙÐ’è¡"¶2Ä^ç’·Ä1aä¦÷¾ßÙÄŠØa¯òƒá=á§©¹ýüƒã9MCÊõûR {]Þí3 Œå>¯Ò“àX!saMT•eE<^¥x­M =ÚHy>MôôÎUá9*â85=ZéÖ>Ï×åQ ÷ß–Ó%3}±gü|íohˆ£ž=67v¹|¦“=î ž9=~²:F˜Á­“• ÜÃîs—Oïºi9¶žõÐ^õ²Ò—ø TË{\ų×Ü/µßHOw_m?}#õí'2ÿ%JIÄñá¸ßZ¿º.Ÿýà7ð‰Ev耉0ÑÁ½%^I¿fT°Ë{@ÉQÚÀ^\|Æ]÷Au…õ$AÝÒK¾ä³ëû/ Á5ñ{°Cã·{­ósÃq]i,üÏþò—÷DôIºcÇr¿Ò¾½ð§|`uΞd¥§}r*L²DpoÙÙû" ›ï¨<°KD`—Ò¿‡—ÃÈj`¯=¬W ꮾ>G"ú`v½û²lž´A¼)—ê\¸kÛW†”YºÅIöè±®^=ý!Þü~8¦×½«Ÿ¯½q) lApo™¾õº±Ë7xÏtØËë×=‚WïºG ë~ÔÝ›î ¨#ÉzÚ-=SzxUËn•ƒ~©Ñìúþ«ÒåLgÁëóÙ_þò)‚Óâ%Mˆ/ï…?å3«S=Û^ŽO‚{+ñ¡ƒM0>ý­·eefà’2—ÈÀîûxcè ­y7d(Ÿ°è(ÃzÓ­†·¡ÝT·îü衘fmöʺ]·Ê¿4ÐGv¤”¿ Rú,¿ T*]”â-÷Wõø³¿øuÆuç;´.…Y× î-õRú3ÂÌ¡d5zØLG^ÝkˆÆT½Bïz’žußÒ—èÑdÎg×»oÍ®w¯J.TÍ^KÉ Z o›ß¼Üóà퟾YXnqÁŸÿÕ/=‘£¥I$l´"íñ¡ÇæJÍ ]ð@ú5 ä)»œàÞfçô`3ömh`×iûJ9Œø…üda½¼ü¥ZP7÷ëéýw-ª.>þp³FIðÕJ°¿ÐÓûWö!#=ºóóñù_ýâÞí‰@ñîò /áÇ÷1[zß ½î|w¶Ì¥ÐÛNpo¹O$ ¢ÙÝ›g|ú[Eô9T4Ø£z×S†õAÝ#`«,´»j•/}Ý‘[²`a]æÔtªµçTnzHË×9>Ä[N<ÃÞû"ú˜O1‚{‹œ±» î]pÁ‡ºki¨Aï O‹£ÄÔØ-!ÇYcž"¬‡ä’|x{;××»ïú._Ýùñž¬üÄÞÅò˜*'¡ŸÁÕÚãó¿úÅ·ÅZ‚’"ħ(¥¹qÂgXëöd;'Ò¯*‚;g˜w¬s¿†^x:JÌR0©Ø×ÖC‚úJ€ÌC{P=¬=”/¯sÔMÆZ«Oã·_ã¶Ü;â¥du]}ðݽiôQµ Oc»øvkp•°ÎB‚zÁ¹¾*™ û ÝiÇQþñ¯{îlO¥VO,¦oŠ_Ž?©öDäB”aŸ¨_`ª„xÓqf}œð9ÖZ‡=ÚÖ3v7Á½kgš}0`WoŽñóo>НcOØ}zCC”oX÷ _:6¨/…vòóè)ÆðVÂ;{òì'zzÿSÛPŸzº]làÒ+‚õùÍ/Ö_âOøüC|ðûbðÙ_ü*2ñ¹N#É:1Ap'¸Ó{€f¾TÖØ%"°ÛC’½ Æ?dÃtøh2#Y®A6qX:zÊ¡{üïÈ Üú‹O½‚ý…e¤{OþÂc¶~âõee’9Ë(6A'’öïl—½Onî;áãŒïÌ5:gWÜ»æ…ôct™võ¦÷БbêìÕÊaâz×=Âz¥e²Qõt÷ÊÐ+é¯+P¯}½ÎݯgOî[_úâ‡ÙÈ,û7Iˆ/xÿ^xÓfhÅè2÷µº`WÜ»hØ ‡Í¡æ€à3RLÊÀ€´¸‡ LÖƒ‚ú¢ÛÐLõ|D™}¿¼1ÇcÈv^êëû/¬K»Þ±!~éÿþPDŽÃ‚wªÛ _>4ägù+\¤Ú>=ØÆ‘ˆ¼bWÜ îíŪ`üüLÀlÃ:zv2±“yýü† LÖ½ÃòD”g¡=6¨ŠG”i2·µ\feÝÏݯižzuk÷Ÿö¶~âÇÿ«Úc÷wÊ_ ðJ‰–ÑóÉÖ*z²çìj‚;ÁÔï0]`÷F2¸&Eïzª°nq[s=¥úz÷¥_`¶ÚOij™`Wg„mævûÚ‰ƒþ¹»M _‚»W%ë!< »¸7uˆ÷{À2š£ÏþòW˜IµuŸ±dÜÛê¥ô£Îý]½åe1¦`°€ ì z׃ºgˆ,|'úúþËè@Z\æ¡+œûñ¶ð ú¡~¨§»¯l[Oï­„æ­Ý«gyh?ܯlj+Ä×Ñ ¯EDñÑF'Wƒ.…Ñdîœyv!ð¡ûôa\/»ö ÷ó¿EöørY ìU&À)Õ&'úz÷¯î5œ£>p…óÀý½æ[Š€¿X&ãhÏ…ã`kwòhkwò¿EôiÐz%ë7„x =¶m½ðÇ|¶ÑÉEæ!¸ÃߨÛ¸Ïnî¶Ï~ð›{JÍ{ƒê¸ð4´†=¦ÆÖ»ž"¬•QœëëݼCº_x=ð çmI&ʼnƒµ]&JùŒ`¡dëÞäÑÖ½ÉßçáâÀo½ª#7)EÁ½>[ü¿<¨äaõh±cÁt|i²NÚï±Îï:Ð w-‡xÛsÍ>¯s'¸¯WF”¹†$¸o€«ü`> '-vX,”;p7Øc{×=¼3C:ÃîDDŽÊ‡}¬–ë8H˜³uÝÛeÝ9g[w~,ùgì}Ù«ËY>ö´Ö¯íÑŸ,ćô¯üýèó¿ú¥½/ÿéÿw%à;²>Cv3Á}“ÎB7=¸$›-Ýt` ;!½ì] ìªbï|ñq'zzÿeµ4«ÁRmÿß•–[÷H2©–¯cöƒT{ä…xíéõøˆ|ÊG][:G6ÒˆÝ\?.Nå,”ÞH6cªÏŧ– O½B’ë¢Sq¿žóbSÇ}Î Ã'_RJÎõt>‚ŒïÅŸ~C9æ=°o“ãVòší¹…n‡Ï6…„ùò癇]¬8Þ¿’ Ç ÏŬÆçñ9׆βª¡Ç½—ô& ­>ûÁ¯?( kè6„`ïÀ^¡‡½rﺫ&¬®}i;F³ëÝw}Ÿkn‡r³ëû²½ýã¥qôxŒ +?÷,•q/H•î7¿ÞxÇc¼KiBzáÏðiGp¯×¹5€w‚{*ûìæŽ¡„L¢dgÜúܨvël¬®e-¬§²=ϯç´d¼ô‰d@Z–­=Æ[7÷Ï®wç'¶Çõc¤Ƕ{õÐÇ´[Lo|ø²ÊßWÇyé˜ð…ç|þW¿È°÷ºŒØÅwèn9d7w”’Cs-»oYŒ}&÷¤N©»®€¼ÂúâcŽg×»¯\%/1áqv}ñ9éÂy‹KeRoST˜y!ÞàCKÁœþˆ<‚;9‡à7®äG‹é}sh7… q?ÎXÇž*°[BK¥Þõ °>ÿÃÙìz÷SûsBƒábh ¶]™x)vÝS,·Î âmÇ´Dž„–øŸwkч_:.ÙÍwÎF»ç»¹“Ö Xc¾ð4U`—òÀlÌëìÖßϧ~=êþsv½+³ëÝ•^{¿€Û€ ‹F› ÷–äS…x ?^ÓøC>îÖâ Û8d7Ü7Í„&@»ù\|ê.‹ñ ÷õöðÞõˆ v|;^{•šéÛçèé}[¯ý~åp~Nuü­´$¥Ê-EøOæ­A¾Ú¨2izá+øƒÏÿë[Ô¹7o¿ÛxÉn&¸ošQ¶ñÝÜÉÀ>ðïe7ÿ²˜¥ YK`·‡)wïº3Œêé½—q5Ñær=½ïzΡ;”û†î6ž0züFÂ|l÷ñq¥4eïƒ÷‚–´3ð‚ïÆ̘Jpß8zÐ Ñe1!uì#*°Wí]_¹¨§»Ïýâ)`oz>rŒO¸, è}U¦r O0ªL’/+!ÞÿX.9&üßOw¤6¢ î ¸£Ÿýů>(vï^öªuì¡= ÈN,ÊëÄý–(™ˆ’ãø ¾³Ðî“ô Q¦R ¯0ªLtˆ÷í…¯%ÀøäkܦŸ,MØÅÍa¦æ ùpB Ü„ö¤})Pø>¶ÆláÉ~_ùè.â|®yÝEDäTß ýXBù¿ž¾¾°n!!´k<'_Š ôË €Iù?vñ Ó¦Ç¸&hZèÉ>ÁSÉrçÁ_—>‡Ïéæí“o =î@Ÿô²×±{]xj [¡=ì¶r˜ˆ‹WzQµˆè¡¾¾÷‘ñ¤¤´GÝÚ=Êc¼/ìÃ$L‰¶9¸W>²7Þ¸ïâ{á}ÿÕãÇøœýÏÿë#.P:Šw¤t@tyŸ¥îe·”’Pòø¥€ã÷Ëýömç2~í˜6 ¯«.>|#” õ*rû=ì^½ñ!ÞØ ïsAêí}‘þϺÆôaFq:&ÄÅ©H/„n9¸ýr íÁÃ;†ŽÃî3þzÙßmÉzy¡§»/œË7¦ÌâEæÐî¡eù¤Q®í¨{(Æ*' éÖo±}²[ŠÉ—ÄG/ÏpA«×q¾zŸ{(ÉÂß÷ù躉w ÷Á}¹G»©²˜”=ìUÊaŒ÷ODäÄ;ðYÂ[6ìcdHV:t½7Œm•3Ì//+¬g> 7~q?iÿa÷W,£ñ짃©\Òw £à^vßpo žöçû[ã ½gzzïU|¨ž‡vÏšvurÑ@8®ƒªy½•w˜·“n{=]JãSF“"À£!ûw¤D© xjìæî°‡vCÉIY L’²Û,§â^·*ÓÆ/†.¥/EÉ™ñ¹^åÙcKkÚM³|ÖÈÛX.S÷zÅ• );ƒª¸÷³s9ŽûJÇ„wŸÐ”ÿù_ýŸ€8¤ =îÍ÷M¶÷Îi¢—=´,¦ÁöÕ²ŸS}}ïª|[ÜË/ÌŠÌuâÇÙ¶½%‡\ЃTÅTÎYÿÞxÇ9Ki|zÒÅPFãwAêmïûü>zß‚;€ í!³ž6Ø+”˜˜õPOï}R¹tE¥Þ]¥<&Ÿ¨ª«¢+n´;È/ÿòS¬¯0¢Œµ”&°Œ&:À÷áú4dD4‹R _ò‘¡]ù†ö²‘bBKb¦Ž_]×òÉ–Üíc=ÙXí®ç'*SQ–›õu›,©ðúÎmKÕÆîçGö ¡(ô8ô;ƽKhŒ#Ð øÌCš€à`-¡}1,yÖ²Ç»Ž½ÞÀn IÖ‹eõPOïÅ ÿ˜?¦ÚSHÕ^+–ضùXWÐ ô釅 ñ:űYK€G#8ABR”Ê µCš £]$¼—ÝçqAe115ìÁå0eÏ=q.¯ä5•™]‡ÎŠZvaÀþjÃ1Óx½´¥LFù<DÑwÑ—ÎpTw/ûúû|]Ou`X¿ ×Y]»rŽtfµ§=Q2V’~™ÑP%Z]a…A>ª7Þüÿ^ø¦ï¬|9Kë¿0ümï¸.÷j¡]-]-1Ý FžÛ`)¶_ßcJ{äXß×YxÜÒqã>†Ë_çö˜Ö5¿t=î@¯y SÓËž´‡ÝL&"r^¾æeKZ"‡Wô*Y]IÚqžWvñltT5nOÀjá9Ú÷u|zâ]½ð1uð=ðåå3C>ÿ‚;€.Åöé½W·£•ø”Æ4YË4¬£g Õ""zzï**„GŽ@cV>AT‹&aŠ åu &¿\íüU¥e‡-g©^ÇÍœj>™U–_¶ s€·_Äj ð:åÉ‚;€u˜ˆè}w0®ÒËž¶Ž=lütK™Œg¹žîF Á¨Ë ]Þr»n,˜×Í5•9؇nlD_<>S…xU6ñ”ÿh2«£ÐxÖ³ÏaMxºŠw ×´ˆèQã¡=²Ž= †Ýüw%#=½÷ò¶þØ]¿¬§÷$¸ÆÙÚ#k³õôÞËÅçÎÛbñ–ø¸HpKìWo jÝCž·Xïµ\û£ëà‹íSÿ¾ÿ½xÁçÐÍ¢ÇÀdñ‹>®4¦®²˜$=ì‹áè̯ç<Ñí ¯ŸÕµÇ.ó¦F5$äº.F¬w(HÓIÜj*XOåñ7;ÖµL:öà:øboz¥ht =îFQ¡]†vk/{Hh×âÚ =šz""Þ½¡b³Ý³—VG.1‡vÿã…õ‘{Ý»<êLõmXý"f9#É8{áµx÷¢õÀÇŽ@ã:Ž´=î@ïe#Ë„—ÆT1&&°‹`_½ïBOï^ù¯‡ë>×öåK¸¾žUÙ½*À/îÒš X¯5ä³è&Je€SJDOクýâ¯;´ëÀÐîY& –×oå9ùL©Žòë¤<:èÅÒšv¥Wo¾õf_ùÚæ. m×z…• ™Ëj|_C"'×2l%4þåbÊü¾|þ×_çè zÜÞÓ’×ïÛC{ †–ÅØ.<µ–¼\ØÇf/Þ§¯ïY¶Ã½^…YQ•ŽÜ'¥FR¸@µbÈUk8Ü*=P%xQUäož¡C'[²=n!¼k¿ñÚ÷­ôÀû•ÏzßG|îÝD;ÐûÐ~«‡vcrL/»GøZÒ±ô¤Däf¦TÓº.…îé½À -í B‡tý %›ñÒ÷"Y[Ó*¯SŠÞù°Þø ‹U}{ჟ¿Ôïý[>ROï¾èïµHl@Ü4oh ¡¡Ýçq¥c²‡–Åxw}™îœª…½,øïÖ8÷•G>ahúîk óîç™C|Åc¥j€/ÆyÒ{™~ÜM¡T€Èòh%¥å'uŒzáið(0¾š‡ô "zz?â¹ö×SËMù\XØ•ÞT×z*ëÿÚ1SêÊó”yHL)*ð"ñ%4+#Ð8ËgF|ÜÝE;Ðk7=ƒ£bщC»­—=Eh·ôPªÅÑd|žçÓk[ì¥ÍÊBgE]^†Ïl¨Zò!-G¦etoÜö°6*/Mžù´ã¹Ç÷ÂKy€î—Þ÷!e2Á@—ãÑìÞ+™ÔWSWYŒ-°k¥'Y=¯;ŒeÃ?ú…õåp=sΊêéef7ãÀ/®›åbÛµ„é–­CpyM) ña'})|YùŒññ#{°@pÐ^óÀ¡Ê&÷1ôH{]€Z¡—}exGñö—s€÷ë…¯à%*À‡ ) 8 h‚;€¦C{ö•>t ã˜ÔUGŒ1ô²[ƒ£—½xßÐ'p'[ò ë¦píÛ›î\g‹CJ.=_Oï¾Yž8Ë'D·Uëìä“„x) ñi|èóJËg†›WNÜôÆrȵì€Ò˜°c–ÂT|YŒéž [X2•8øîy¸Þwo|x-–Ç”=^.³©õí®PŸ(È' ñî^øj>YùŒý=€à #ñè¦<6´ß_Ÿpï?+«ÄvÑ£üBNK`™]ß ëæPV-¨/öÞÏ®wWzíKœ'ÛùªÁ[­>öùu„ø|tùÌÍv]Ã@wíó‡îÐ^>âLc½ìJ|z ‡ËË„CÃúí‰ÎndP7N=½_Ô‹¥<Ùöë™­\ÆÊõÒ$Q Þ ¯:اË=$Ä·-À[ßG“¬ÄJ¯oò-lª‡4Á@c½¤\¦tTñ íŽ×ªÒËî÷œ‹Åusbÿ! oG ‰™u5X¯ŽÿnxÎJБÅ^÷²`ÞêršÀ`ßH ññ£È$ ðþï‹°ÀÛ>M@p°Ãò@RÏîxnT/{X¯žÞ}áq¨Ïh)óåîÆEC³¾ÿ½°¼ss@ß´ËåPæ†ø€myí°/ï ËI9‚;€Ž$¥EÏî¾¥'îÐZϾzbzÙƒÂÒ°<°Ïø=%ŽÀÔWO´ïøï%Û¯§w_õ3YÂ|í!Þ°oƒ¼ù8÷ ð®òëk]ÐËÜt™2~áíAÁ·ž=¤4&¶—½4܌‚TI[ gÎÞqkP_zµkWyŒv¬ãÍcΓàFo5†ù¨ ¯Ó'A¾J åø0÷¾_Ü^¨M™ ’;  îa åö€]GiŒ˜C{Ph)¬ß0z¿•žÔyïø=±OìãN½ÊcŒëaXÖôî'"2‰ æë<îši1È×âë ð¾Ç»ù„·ð— ÿ_€àNpÐÎØ¾rq¦ˆÜLZ´úE\Ïn- íew÷@.¬ßÈö8=½+öRß8LÖS6êKP˜Ý´1Ýëô1½ñ‘ã¸' ðÅ÷[tïûDD.ìu ¸èXPš‡ù»¯Vƒ¯O={hiŒ˜C»cý]Dä2ßwøò ázºkxLèˆ2KË* èQNžõç8Mæ{ãCC|Àã’ø¨Þ÷ =ËËd¬Ã¨ ¸èHZ çËÁØã9K¡= 4&º—Ý8Ìã¨ô¹*ÿ•! Ç<~èG1ŸD†Îâz,MДé>ª7 ·¥–=¼ÝÓ†øˆ‰˜j ðÞ'ç¦÷Ûþ÷þ?€à ëA>ÂQõì±¥1–`^¶ËP#kLÐØÙ¾q„8åFÒ/0;fS=«¶ìÅ›$ºÝ.³¹Ÿ`6Uïšø¦¼¬xÏÞ÷ËlFdÊdP«M@p°¾Ð.2ËÊe‚C»Ïã a:¼—Ý>6»ˆ,ö</îôïå\ Û¾A½8‘yØGÿðj ë‹.DdRÊí!»n>!¿ž@_a6Uï [ëð1å3ZDô™ßÉ0‚;€ÎvS9ŒR‹?±§í#Ì”Žo|ÎÈ|¡©ä¥J@÷ }KA½°„ëûñ´töZÃm¶s¥”¾XG(¯7ܧôUB|SÞùŽ‹WÏãÖÁ@+C»e¤˜ ÿÐXÏ.â÷ØÒu,M=›_˜6#êÊ#¬4IiP/†ö]¿´üW–ë6Ï6ñ(5ŸŒ$¼H5ä‚`¯^øª>¬|¦¤÷ý\fw¯êÁÀ¢Û€º\&r÷•ˆZI’zv{o· « – ãq‘©5”i¯°>l鬨րîXªãdBO«\¤Ú­I—ÒùØŸ"À/¾Ÿ|Ÿïì}?5üíÆçýu>‘Ê>M@pÐkoù¹1`8C{IXõyìÂßUxÁ$8@©ÕõË&[ZÙþ¡·0+jTH¯4ìäY\(oê8«gÒù¦|Õò™•vÊlçÕrÛÐûŽšÒ͹C}íÖ¿_HvÁã~1°†vï×.âQ<ǯyU6dã=¯u{ŠÔÛßö8çs.ò˜ýÍ9à õ—!­uÄòBž3ïʲ‹´cY ÷«åU°=wå¾SÓßçm2»¾K€:ŠwKà¶ç/›¸E_¤ í:0´L:£äÒôœB‰I`yÊêzØŸ[>ìc½Ü IéÙΕ§¸ß„ã2¾íÊ{ã#ÞΟ¢¾,§;ßÃlÈò÷I×.Z@pàJ/’…vók—_€ê|nË .­¥:ʾ¼Õò°r•bh¯:êíPŽ…^M·Ugý9É òÕB|S>¶|FŸ]w€à ‹ág1´/ ¡8»ûRÔâl¤Ž0 BB{̨¦Zû›¿_®¦´Ðà>ù’R1³¢úµ¾üœâ–æZq=Û©8“j—fN­äÍ!>ò½S)À{£îð¾ÐÛ4»*‚;€ÎÄ÷Ù½¥Ð¾âÌp—SPÈøì¡ –ö²ßždLo/È»™üheìvsàºuÆÔ–ÃõìÚ5+ª;¤—™Æ _gñ¼®0ÝdÀz{á]Þ³|Æ>tä©ÿ°’„w€à {æAÅ2JŒžî|""wh÷ #1¡}yW–ylR• ˜Ãzhht‡ts ùŽo<Ûù$»Hu]=à©~¯áàã{áë ðÖÞ÷¡ží¼¸y/—xçü@œ‡4Á@S¡ÝšWÄYxh7‡ó¤OaÛÐ˾àÒÜãïBÅ0ãÖMáÚ·7Ý/œÎ‡”\9‘ºëPσ‡:nÉC}ó!>® Êà]ËpÜWlßcãý‘Û Ú§ îjô3úyµÐn«g÷Xåjüƒ›)”ùîy¸Þwo|xè,–Ç”=ß«‡ú,(”×y‚èÿÚ“ð0Ÿ"Äûx‘t>YïûùíŒÁK÷—î[Â;@pÐÝÓ‹kç:›Ðå<>´'/Y~Îhyeõí‹!lv}/(¬—‡¹*¡ò¶÷~v½»Òk½Og;¯DÉ…taè¿Û˜ßÎý×;E÷{~\MŠò™Òû&"râ|/5q‚€à ‘Øn í Në íA¥1ËÏ™˜Ã½6öÅ àn‡~ æ^r=½_ÔWê’³1ö}wîY‡Ä‘žî¼ÒÓ—zºó®ˆ DÉ$ü—T!^¼B|Ø ·®üüS=ݹ²?F/œÈj<@pÐÝÀ^& ãžç½îÃj¡Ýsä¿^v¯ÿ÷ ÄþC@ÞŽ@ãÖ,ARe¡ÝùœÂXôæåÜÞn«gw^ˆi˜ÌÒ×jâf9É(¬ûÎ 9å¡-ƒ‚|•Ö Ÿ&Àõ¾ôôîG~ïÅðw]` æJŸú†vóE¨Ü¿—}ѤÊï\êzÅYXw‚º-\ç¡ý:tü÷åå-†ùÒ“¢³õ³îµ.–§gw®Dd ¶Úwï Ÿ"Ä7àíÏ=)ŸXŒpÜl¨yç]g L>ÁËÐ'´»ÃýÒß½KcŒám´¢lAÆ>,^ÙÄRU‚ºa¢$ßñßKœ}t™‚sñºès­Î󾺷á=à„¦®ïàýóvŸD—ÌŽ›ÿ"áxœö-w-¦$bT -rSëž8´;ÃŽ.ߎB~ðdER:‹ìBtöŽ[ƒúÒ«]»Êc´cýC§ží\ÉJovë\Ø·áÎK}¶ƒB|º¿: M•×_y^Êâõ&K'ি/>'Àwd«·ô¼g½ ãC»¶„öÀ`S¨ù^¬©­A/ zóÞqÃ̪A½Ú=ÊcŒëaX–ÿ˜î§->/õìΧ^5ð7õúe?ÎÓ ïà«ö¾jß³“1Ûõ)RáµÜ´/¶¯\œiÛK5ã§ñ¡]C{YÓ%!ɲnF×0…:[€[©¥N0)q\óОuw½žÝÉ.,n§sŸíÉ98õkÏÈë ðÎû‹%2¶_gߊžv€à`S"üB˜¿[Ú ²ðp6±RÂÐn !Åmð,m±•µLw ÓKË* èac¿†±³–€g¾Û¬gw>‘ÒQr"ÚÇ»>]€·óÖû/í'.¦Ô·C‡NvD&4Á@#ÝU.£mÃ9žÈgh¯tj…n•ÿÊÐc?ô£˜O"/Š,®ÇÒMžcºgå(ŽÐ«ßÜJ/JMwâkðzßÅV"ãýkƒ–ýïýHé%M@p°† ¿Ü#hÎq¶óJ©ååÚ-ë¨Y_dAÉ÷1î@hF²l™º<¬Çž¤)9«´Ã¸ÃýyD ǹD÷ðyì3k{Äü2"¥Þõ˜…ûOó_¹_׻ޠë Á~A½°„ëû]Çnœ\§$àÎv ½´w~¶Ý¦¡!ÏLa´xó¬)E€÷è… ÿÁ¾`""GeÏ÷ïµY_TtH€à ihwÏnêîE׳ç²R;*´KÐsn.Ä œuåÖ š¤4¨Cû®øÖo!Á2ÌéÍrU÷Ûí¸”Ùö'^ç/†@¯gÛŸJ-¿4àË·uiYGY]{ùóK{ßg”ÉwC©Å€º\&r·$Ä/ò›ÿ?NÚõìáe3^™*mŸÒ#¬Ï[:+ª5 ;–ê8™ðžIu¶ýJ”¾¨¥¦ÝyÐÝìßóªÇ®(¹¨¯>¿îoï}Ïs*³;/|Ÿoê}/ë‘ÿü¯¿Î R¹¤ îã[onÊq!ègÎ]$ íÑ£fÄLà$+:›li9dû´á|²¦ûåA=hŸ¤ͦ¤ÔälÝ${ý˜a0 .Ì'] ðÆð~!Ù/YAÇüíHC;«£÷w‚;8¸ÑõÐîówÓPŽÆ°"óòkhב¡=æäÃ6»¤a¢¢é=íœ=ó~õï:౞a~ºýÂë3)ýðÙIÃtû*¾=n ½Ö»©|Ü–.{$"Ç¢|_ßïø¿)32þš€à޾÷Gìê.y}Dôì®ø÷ kѳW"ùpƒÖÐ.‰CûMé„1°JLËSÌ¡Òò¨Òac'Zò°RõBO«ÇóNñ ?Ueö…¶›m_‰è‘÷:ÕàÓô¾ODäXÏëÚUȲÊ.Âa‰Ò ¸¨1´[ºgÏ/T……v¿1©M÷-„ýÒÇ;{Àó—•ò°r•bh¯:êíPŽÉÃõÜõö'ÒüÐr½}•æxÕ"J†Þ¿p$í… ðÎåéÙ—Ë'Ñ¢|—ñëê²ß“í±« î›jB }a½ì‚Ó¼÷nv×ÚK&;}Ú=N&JBû‚ÃÒ¾Â'_R*fVÔò±ÖË'ZÒK½©æÒ’ ^÷ækÝO/ov’æ ׉|X€>ί1?Þ#¼ßgWÈ6wôfJàvuÇâûìÞRh÷ Ñ%=ÛYp|Y h¡¡Ý]Ïkú©_OwVœ¹l ¤¶Ý3¬/‡ëÙµkVTwH/3+Œ_5|Y.RU5ßæ¡ýzëUâ’¡ay8׎_s$a/|åÞ÷S=»ó‰sù+Ë3xû¾P³M‚;îHkÖË/8-bkh/8‘˸Ðn/ÖúÜÒ¡$cB¢9¬‡dwH7÷œÏ|Ç7žŒíˆW@¾Þº%ç g–ÚöЋod¹^:ñ_)¼Gõ¾Ÿë›™Q=/B5ý3ßç–p7¢ î›ì’&@ëB»10ûiÊù´ôGÍ„v-"úÀÌÜA¨f|º)\ûö¦û…ÓÙâ’+'Rw=O¼6p´É›­ˆÚvöR2òÝ7'vkðæå^èÙwcÞ ÎÞ|•äØ@¼AO¶s®&¸Üù°B#tõ¿«òpŸ]d· Uå‹PËžw¬VÇ·Öž{®wÅÝ^R,){~`µ­Œåzë•ØJNÒ|±Ÿ¥»Àve›GÆíô ð*æ"ÓŠï¯ÛeŽdeØÇ°“Îùòng ^º¿Ò…²¨`\‚;g¦]±Ïnî`„·]Ô¦J.xTîùÛQfª…ö˜ç•Õ·/†ìÙõ½ °^Ø|¯uÿ :»Þ•ÙõîJ¯}ô>íH@Oôi5î§ríèm¯èGÎeú„øZ¼õW‚Öw®ngå;νN¶k›a%{´­¯ØÝ÷M6â -ŒíÖÐn3¾Ã=j%Ç¢ô¤æÐ~hJÚØÃwHX¿=ÑÙ êæ^r=½_ÔWê’=¬½Ùz!¢/íõæQ·Ky³õ‘ÿ äÎÍ­4Я†àK“øÂ÷À /'[~¯„ÈâEÙö¡ o&^"Àó=˜Î„]Mpç ß ØÕ] ì®™E=ïu í""¦’™´¡]Dd¿lä¿@ì?äí413£®†A=½ï~Na˜CKý´*>VÏî¬_-µîÇA'7…uß±èùíÍÖ˰Þõ>þýVÚûï»ùzÿ¾G*=ÙλšàÎANoÖÍÌB{!0Ïv>‘ w¸Ð–Ðn[w~ü`1Ðø_êª#^œ…u7$Û§Ñס㿦rm‹ç6¿Ù*NÈT}øÇ‹¬'?v¸N< Azγø¸^ë<´o_y(ú —Z:f=áœïÀF\²« î›n‡ÚgÞÃy×Ì]Ó©/†vÃãŽÅ6D¤säq…惛\å˜*Þ>,^ÉÄR¡õì˽àË%ùŽÿ®ÊJ$î¦?ÔÂE¤Õ–3%'AGaIH÷ ï¦ÏÖT½ð¥CŒø<´Êc\'Ѫ¬½v<§ÞCHh@pÁ}3ôe¦»º”xü,¯ƒ@ih± Y9´‹ˆÈAüdE%³È.3gï¸5¨/½Úµ«<Æ·çÜ'Ϥš¢ƒáL^o%»h- ïÖíV ç^>º|¦$´û£Úóä ¼÷½xñ9¾fz´­#v7ÁàŽÆ„‡ò,€ï„‡ö¹¬Þý¤†Ðž÷å!«…õÛÞqÃ̪A½Ú=ÊcŒëaXVê1Ý_o]I¡¤)ò3îõÖóø`î{ì.ÜB{וÇcl'»þå3yhŸ—Ç„¼ ¡\-žŒÙ®O‘ ¯¾ÿ¼]²» îè›ã!»ºå±}åâL{h·OèÚç›ÝùHd>[g²Ð.¢äÐ>|âÒ襡«$ð®ÔqÇŒ&#öe–”Õ…XÃs<ËMæëTuhÈãê'”†Ò"ë/zâëð ¡]ôöÕêœÇÉÂýÅv°ü:³Øû®èi'¸×â%»›àÞ£žl绺3~!Ìßõ å³âtÞ¡ýÖI>ÂFªÐ.’Ï!PÜÏÒ[YËt×ð˜Ð0½´¬Ò€ÓãœØ[¯nO¬‚Ê[/ë:NýN@ =ñU¼õ¾òqÚEoÊc”Š<¾ÞÃÅõзC‡Újõ‘Ê^‚ûˆÝMp'¸ÜÑx`w•Ë,‡òÕç‡v%"úΕRr¤”©ž:*´Kñ ÓÜc®§÷‚zÌã‡~ó @dà.®ÇÒMžcº{Ð’µgLpÊë­ç¡“ýýP¾Þ#ë~©àÃzßÏe¶õ5™™'ªÔûn+‘ñ=®”–ýïý|ïUuÉî&¸Ü7Ë¡0ž{ç‚üràjh/†ˆ¨Ð~Ø^­~ÑE‡öìïüøµ &(0ù>Æ52ˆkɲeêò°{’æ7Œ£Èë­âºà³hb -^CG&è~½ueçe4U¼ès™m½ës<÷¾ç¿r¹Cÿò/h”ÉÜÉ2wTñJú3,ä»»ƒ¡=ïÁµ†ö•¿é€Ð¾0cèìÎ ‘yMtµÐž;0‡,×Ôð«Û°¶Ã'U6죉LXX7~ø‡†tߎò [Ã̶óuó/²ôÐOVNlíS¹Dfʼn̶ßuWæ}ë8®–¶Ùý<ׯi¨Á^Ͼó†ìr‚{ŸôåLõ˜]ÝþÀn*‡ñ íÙtëîž?Ûè(zvç}^=´kÑ󅦶Y&}‡_ô ê…%\ß—è:vãä:%w¶S襽ó³mÿCã‹­OÅïçðùÂ4ÑRày‚2Ý‚®¶o/|Y@÷»ïX¦ÛùT¹¼ÿóý{íÝë€ÊŽz¶½#v9Á½Oúr¦z(”Ë´:´¯†;Ÿ^ºb 7öáÚç׳;ï–¿/|CûÍ1'¡3¢®<Â:A“”õbhßßšcã-`}£OÚ”ã&úÔQÂs.¯ÕGÎå¬Ìðêa ô:ä¤Þ?%‡2Ýú$,<—oëʾ^yiKè_|e2 ;éYh¿b—Ü9SÝL§ìîvRj1 .—‰Ü- ñË<¤<ÆbŽVßA¡=îº$ˆûöœ{„\G0+ÕÐKuœLxϤ:Ûöë[D^o}"¦”ì6”×[ïF芣›(s¹Î¤Ú2 Þöüâçø@®GÑ©8<¨,õ¢—–ùõ¾—õÈþ×_ç0­GÒ¯ÃGìr‚{ß {´­G’Õþ¡•I3šMü“7mtV2±ÐQšc/Y¯ðhå#6À»{߇¢d Ó­—öZzŸ6( ï¦÷”ãù·# í¬þÞ÷:“a@pßlW=:cÝ—~ý„رÐîówÃÌ¢•zÚËÇU×Ù¸×=‰ís‡îÀ®“ÒdÃEºB¶#pôÌû…jðXÏ@<õ,5ÉÚýLŠÔDdPÉ%`øÇòׯ2®}L@÷E¬æûÏåzë-¹^¸W…¾ÇüÞ~'~¨Þ”MCî ¸sàoš¡×½#A^߆èÙÝ 0~Óëî íe1¿ˆTo¿”Åž÷ð šŲŸ{†ÀÛ6öç–û˜8šÂgéõîçY‡‡ÌF‹9» ­óлLU¥í—käuضV ð™c¹VïF-#àDzõ½äàM%Se5ñHä´gÛ{)Ùèx ¸Ü7ؾÐëÞÐn èža\[Þ·ô~/÷|ë;/EäD¢fU]ª5uö€ç%.+5äaå*ÅÐ^u6ÔÛ¡Ó†à×x*9%gòzëݨac_×ÕV‹¥NJ.“Ì’j>æ.EÉ¡\«OœZEl.œßY9‰廬á!‘ÀCé_oû»àNpï‡a„™†õ² Nçã¬ßµ„vóì¤á¡½díôö'«_Š^ác°zÂárÂ'_R*fVÔò±ÖË'ZÒK½©æÒ’ ^w__l½’/¶Þoù}éÎÃüPDåzˆ#zßµq]²<ÓEØw#ƒ="‘]@p﫞¹î÷ôC®ýñ}vϺËB»)„ë’ðÚOûwàØßº÷ŠÒ%e%µíža}9\Ï®]³¢ºCz™YaøªáËR®£j¾Í]oIm%C¡áÜ/ÀŸÊ›­·äëW†ê½ï–‰¥¤¼÷ÝtâísœÞx§ÐIП²ë î}Ö·3×#y›ÝÞ"ó°né)Ï&Yò í!ÆÿñYx×ÇaÛ´<4[LH4‡õЀìéæžó™ï8ðÆ“±¿€|½U­Ü&Iˆ½øvAá"W“ÿõ›ˆÈ‘¼Þz~¼”“–Ô;ža»¼÷ýfŸ[½s~øÚ“~vD]°ë î}×Ç7Á¹p¡j»B»10ûiáÖÞCÞ Xìyw†v‘›ž0w*†Ÿ°n ×¾½é~át¶8¤äʉÔ]Ï“†–yó•ãÑ^¥5ÿ%¥\îqÚG"r(¯·"{ëéõ^ñÒÕ›¯:tltó»{ŸÌ‚{ÿ¼’þMd°Ï›¿-tõ¿«òpo $*æ§û, ‹v„÷bP9r«Õñ­µgàž‡ë]q÷Ƈ—…ËcÊžØCm+c¹nè« ¶QfnL̶ìZ £Sy³õ5y³õªòÅ¿¾½ïÎ_"÷ÝŒe¸¿Ò…²(ñžô³D†àNpGÛ<‘¿a×·(ÂÛ.jS%<*w|áyUBûÍÿ–„÷Õ Õ¹[»Èìú^PX/¼¤Wº]ïÊìzw¥×>zŸÎvüƒqÝ5ƒþõÖKã2Ë‚pñþ‰dÃ\>/]·èð^Þû®u>‚Œu’/Ÿ ˜ï­£A$›!õ¬Ç¡ýŠC€àŽ~w‘l”™wØý­ˆíÖÐnZ¾#ÇhÇ÷¡½,¼«’×¼Ï}5°/†ï°~{¢³Ôͽäzz¿4¨¯Ô%{X+z³%öZó ·€=ݹ¹•zçI›+x¯ø Qr oÔ ÓФéüò‰Õ²ãÖÿ o3ûcæ%awÅ9+,lJ¿{œÏ9îÈômt™åÂûZ»kfÑÅ ±ÚEDJëÝ#BûüyzëQrl íypÏ@ì?äí413£®†A=½ï~Na,zW÷ícÝ#•4Q÷ð:…uß±èùíÍVä2z""'òZý¶¼VÅYPUè…¦aï7m{Oô¾›¯wÐñï{”y Ù`û=ÝþKa4‚;8“%¼·”-˜„öB`ö"r¡wÜ8f[Ke3+çÈïâPWñâ,¬»ñÕÐ{¬¯CÇ_^Þb˜wM¾ãxÜrÏxŠá½í¾ûÀuâaÒþ#È EÉ¡¼Q9Û7àBS¯ø~3ã«ãDQùÔ·kË{’pž0´_ô8´÷=£Üaô©Ì'!¼£qóλÎ`îšN}1´—?Î^6£B.¦» ïæ^Ê­/}ö¶)ÈØ‡Åó$$¨&Jòÿ]••HÜM(¤ª…ŽXFYH÷ ïaëp*¯·Þ’×[¯¼ÖÕVê¸Æò×I´*[ÖŽÇã´ÿkÁä¡ÌGê7‚;Á¼1ŒÛÏ«MRâñ³¼ –Ðî1ÁŒŠc¦>%™*²¸}"Gáµçæëì·õ¥W»v•Çøöœû„Åõ_¯Ó}Åd·Ê/"ùñqX:6»3ÀW+Ÿ±–Ç8{ßýOÀM/^|N€÷ôHú]³øÝüŠÃàŽUg+Á£NDäï…qÞʳ ¼#q=íeá½BhŸß?Ýz!²ÞWÆs 뷽㆙U‚z1´{”Ç×ð¬Ôcº§ ÛË)sßcwáæîùžˆ’¼Ùz1ÓêÉn`ùÌmyLÈûÑÊÕâɘíú©ðZlÈGBûmpÁW¼An‚ÖeÞÛ:cûÊÅ™öÐnžÐ#´ÏÿVï BûÍIÁÖKQ2U˜á`ëKŸ?,„ðù襡«$ð®ÔqÇŒ&#öe–”Õ…XÃs‚ÊMR ÿXù„ÒPZdýåÀà'’ õøÒ; W ð…UÛ6Ìxœ,Ü_l˯3‹½ïŠžvO{"òwÒß!— EäÍ@pG9>,2ûùÆ…Þ÷&"üB˜¿ëÊgÅ!è¼C»áÿ“„öyOä?ñ2?ù-Üwì Ͷ²–é®á1¡aziY¥=¦Ç9±/¶Öû|khõ<)–Ǭ†öÐo½ÏrléíâŸUäñð.¾ ¾:Ô:,+$»ÎêR¬“·õÎ)M@p‡Ý+Â{ÁqþAúŒ¦¨+°»Êe–Cùês‚C»}Ç1Ûhxh¿9§øÑ—¯f?ÚÿšˆœßÖ¹K>ôâ½ óø¡Å|¸‹ë±4A“ç˜îÞ#´Té1½Üó}ñ©;\çå1êeÜp‘!÷­Œx”ÝL¯Òûn+‘ñ=®”–ýïý·IV¢y.”Æ, ½íwxŸáNh†ûy›üoaä™Úƒüràjh/†ˆ¨Ðn lÕB»ºóã›ÇÌ~´ÿn~ìlýÄäáíãýÇl¯Ô×Ñ>ŒdÙ2uyX=Ió-qIUëîUV“ x~°ÚEòZ½,Ýþ:¼è¥À^¾mÁ½ïù¯\îпü e2%Hö«îP¬×ÂôÖ M@p‡Ÿ+¡×Ýä ïù\²ø4IM¡=ïÁµ†ö•¿é€Ð^6MµÐn R³í?—¬ÇýÈý®1ÛÃ'U6죉LXX7~øCëÚcÂþl^ÿí_6dí¡ÏÚ< íoÔKkûT.‘1oë¸2ï[Çqµ´Íîç¹~MëµG’Õ±_Ja,8‘—4ÁþžK¿Çu·Ù—¬õ2ÿð}›&©ØMå0¾¡=›nÝÝógåvD‘ª¡ÝÈ´Ì~´÷éìG{ÏËg™ô~Ñ/¨–p}_¢ëØ“ë”ÜÙN! —ö΃e‰Zõuí¦uWá×C»5œ{øû¦Û^ï5w€÷¾¯½{6ÜÉFŠùß’õ°ñÙo}Ð ít‡&hµãüåŽòÛ$o«‹ü_Æœõüw—º¸{ÑõlGÔÖ›¨Ð>ÿ»žÝµu]1´»ÖÛ?äØ'h¯‹ün‡}”ŠËÒá,à¤-Ű¯·ü/zÔ ;Ñó$ÂôKžm‹Úššn¾UÙ6G_H—„tÛ}×[ùʳTé¶j­‹/jœuX­´ÏêóGORÒC%+9&P q*Ù/ÿ ¸#Ћ<ˆÒ3à¶/…rå·aþ/?ù•…„é=QÛ_¬$=½›ÿÝ CÊcb‚ašÐ~{q§O€V‘!wáD¤0ÁRXà·L¬î“å}öÚ½ Ù¶Èöµß‹¾Þ¹;+o–ОöàbK˜W†e¿Ùzéõú®¯-Ï_¾ïÚTÓ®Òå}ÿ{À§|°¡ˆ|D3ÜïX²’}š"Èa~;^øÛ(oË‘d=ô£…¤ó¨M÷í·½îñ¡}µ×=&´‹lÝý'™½þIm4Ÿ|d“-…„lSyL• ®?¶bO½ªóثᅔǦ»¼Oïû<´›Â|P€/ ïÓëcL÷ݬötgõoz#zßçó{ä·Ã…QÍD¨ù'¸£²+Éz‘‡4E²0äøàþ>‘÷73´ûüÝ7ŒGÖzùDKz©7Õ*ήŠ>…öÍ@pG=®ò7Ø„¦@Òø>»çÝe¡ÝÂuIø í‹'ÛQ¡}ëÞÿÉ&?2– zø£Î˜g0UJdvíšÕÒËÌ ãÀW _–ñÐUÍ·¹›aµÔ"Sø7[ÙÍÙ¶!Ë/›ÏÀ±ü•å™N¼}ŽÂ;n.FeèG‚;ïèŒyX·ô”/ŽPaí!ÆÿñYx×ÛT~2t}BvyPw…tsÏùÌwxãÉØŽ_@¾ÞjfŸ‰b&ªšn[–c8) ]¿ ² øÞ÷ÛÐî Ûå½ï7ûÜîó O¡} •LpG#^Þ‘4´³ï0‘æ>$äËrÏ{Hhw¡b˜ñ ë¦píÛ›îNgeãÀ‹éW„²å·Ì›˜¯ö*­ù/)åRžÇOt-¿c=½Þ+ˆ¹zóU‡Ž ÚApïAx?jÞQ‰®þwUîDÅütŸÏðª·C»=X§™÷ë·ázWܽñáe!Åò˜²çöPÛÊX®ú*Hv­gwxÛ Æ›­êÿúö¾;‰pÜ—e¼¿Ò…²Ø@#B;Áëó*i TŽð¶‹ÚTÉÊÝ#_x^•Ð~ó¿Ûž¡]guîÖÀ.2»¾Ö /éÕ£îDg×»2»Þ]éµÞ§³ÿðYw»ëä E ½àM¯aêe¯àí'ÙèI £âD¼?¼N¶SŒBB;î¨ìJDÞóÄ@@¸(íæ å;rÌÂ}UC{YxW%¯¹¤MAXE–ÜýÔͽäzz¿4¨¯Ô%{X+z³%öZó ·€=ݹ¹•zçI›+x—ø7Ê84iº¿|buÇrÜzžÈò «åCAf'çšßOg"ò5áBT‚;Zã}ÉfÐ –`®JzÏCB»ˆHi½{DhŸ?Oo•omçî@ì?äí4Ú³}íezzßýœÂXô®:ïÛǺG*i¢î9àu ë¾cÐ7{+r™|]^«ìVx\è…¦aï7m{Oô¾›¯wÐñï{lšIž Þ§)îhŸO%›ú‚¦@%¶`Ú ÙwˆÈ…Þqgà˜my…vw˜vÕ/κP ½Çú:tüwY ˜Êµ-žÛüf˹¾ÁÃ?{Û}÷ëÄäCF™÷²»Ú7àBS¯ø~3J’ãDQùÔ·kË{’pÞsy&`FT‚;ZìJD~;?þ¤9à%òλÎ`nÝÚËg/›Q!ÓÝ„ws/åÖ—>3û°x¾£‘„uÃDI¾ã¿«²‰»é…TµÐË( é^á=tg€õ úiÊgŒå1®“hU¶¬Çiÿצ¸Ì3Ào ¥1wtƧ’:s*”ÏÀH‚êj]AÀÚ=&˜Q1#`Ì”£ö9´öÜb½ãÖ ¾ôj×®òßžsŸ°¸³žãëuº¯˜,ðVùeÂc½œ¾ZùŒµ<ÆÙûînú{ñâsü;Í¿ûée'¸£ƒ®Dä¹d?•Òpbw(Ï‚òŽÄõ´—…÷ ¡}~ÿt+8HùMÖ3ï7̬Ô‹¡Ý£<Ƹ†e¥Ó=UØ\N1˜‡î;í_ãîSo»?²|Æo1Òµx2f»>E*¼:è<ÿ®.ô²ܱ1~_èG!ôÝ íöá =Bûüo…ðž ´ßœ˜CÙÖ—>/†ðù襡«$ð®ÔqÇŒ&#öe–”Õ…XÃs‚ÊMR ÿXù„ÒPZdýåÀ#À;‡‹Là «¶m˜3 ð8Y¸¿Ø–_g{ß=íØß•lˆhܱþ@DN„xpÙ(+ÁzV‚Î;´þ?IhŸ÷D~ñ%AÊšme-Ó]ÃcBÃôÒ²JzLsb_l­÷ùÖÐêyâ[ãà­÷YŽ­¥¡K•Š<¾ÞÃÅÔ·C‡Z‡eE‡L$ë„#°ÜÑ£ÿ‘ˆü”d°œÓ$}ì®r™åP¾úœàЮDDßqÌ6ÚoÎ)~ôe™ýhõ>•ÿÊÐc?ô£˜O"wq=–&hòÓÝ{„–*=毷‚{Þ£/>õ ×7ã³KÄp‘!÷F<š™¿b+õ¾ÛJd|+¥eÿ{ÿÀÇ_÷ EäXD¾,Y'àŽú4?cßÏ?F4I¿ƒür R–À<Û‰ íÖÀV-´«;?¾yÌMx‘­Ÿ˜,<ÞÌö*A½x°ëÕþ¶[µÙT—JI\%.©jݽÊjôÏOVþ®Ê·¿Ž/z)°—o[pï{þ+—;ô/ÿ‚F™L‡]J6yÒd“-~B“ôÛš¹«üáy YOü‘dÓ#£o¡}vWdë {h_ù›Ç̨† ¢gwDm]' í¦ 5ûѾl}iâyb°<¹ÍnàIÅüu—–SA&pYÔuÅç´ï²˜™ÙöMÕÚo%ŠÇLIÛkU2F»^mmÙþÐûfÛ–×T¥ûFkmoô¥“\÷óÊÞ¯L™Ú‘°~!Ù¯á/iÜáòJ²RšDdo!Àò³~lX`_ wÚ;´ë鎨í×Q¡½ÄÞ$íÚpŸ–Ùöòu e2.¨¯†öÈÞNïÉ®$ûõ£t?,Ë­©¿7«/´{`”z‡yhW¶fÓîo{þò}ÓmÏcØà•÷ó•’¼}|C9=ï-5ʃú°‚;ªXì‰y¸â’•ؠáÝ]êâ.}ѳCðö í7áÌÖ‹ÚrûMâu‘ßí°RqYº¦Ð•hØÀ×[þ=ê…8ÛözŠ)ÐëÙ¶¨²S™OÝþz+0<«Òm]éE7Î:¬JBÿâóîZO°ö >\¸1„#î¨ÅËüöQþÿò˜ß4Qw¨übMµý…¬–‰ÜÍÿî о5í¥45†öÛ‹;}´Š ¹ '"Æò©4ªÇí¾*»ÿ®¯ûöµß‹¾Þ¹;+o–Оö I±a^–ýfËïõ]>¤DæÚTÓ®MÕVZB†n, í·½îñ¡}µ×=&´‹lÝý'™½þIm4Ÿ|d“-…„lKM{TP׉[±§^ÕyìÕðBÊcÓ]Þ§÷}Úõî!¾$¼Ow¬1Ýw³ÚÓÕ¿izß0ÉÃùâÒÜÑjó^ùÅ0¿·âù¿‡4׺C»Ïß}ÃxÄã–‘ÖÛ¢Ô4:´{߯ʆl¼Pº¶ìø@­Ÿãñ˜é¶È¶G­»-ã™FrñݤévÀzWš*6À;Êg® “9iÿ`îò Ëtüd¼¯ø÷ù¦Ì®ï µî•]æ·Ñ¿#¡'wlˆ+y‘ßD²1h—CýbäÿÄ®'È+=»+jë ï0~ÓëÚo.xÕÛ¢Ôu²Ð^¨W.Uñ{^ù°5¥Â›;¢¶^?Ïj±\fño‰3vXÛç5ò[×~/š"ÀÏï»VqËè}¿™uå„Àà•á"ls¯<¬F’õžÏúdáoô ƒàB}þߟ‚ýÜC¹-¹9\øïÅÀ/KÁ‘¡Ýëo¦<Ûµý&0´jÒõ,¼G…v÷òMË‹þñæù÷+õ’¡UMÁøz[äŽç3ó×M1+êõvºãU-ÿ·£é«xµ8Ĥ%@[¼;¼ëÂ$KªdyÚÞM÷õºLf¸Mÿ?ä’t&5B«)­ù¹ h;fNîîÁÁÁ ¸ ¸ ¸ww€à€à€àÜÜÜ‚;‚;‚;@p@pîîîÁÁÁ ¸ ¸www€à€à€àÜÜÜ‚;‚;@p@p@pîîîÁÁ ¸ ¸ ¸www€à€à€àÜÜ‚;‚;‚;@p@p@pîîÁÁÁ ¸ ¸ ¸www€à€àÜÜÜ‚;‚;‚;@p@pîîîÁÁÁ ¸ ¸ ¸ww€à€à€àÜÜÜ‚;‚;@p@p@pîîîÁÁÁ ¸ ¸www€à€à€àÜÜ‚;‚;‚;@p@p@pîîîÁÁ ¸ ¸ ¸www€à€àÜÜÜ‚;‚;‚;°þÿ÷§eŠ5hIEND®B`‚python-arrayfire-3.3.20160624/docs/conf.py000066400000000000000000000232661276671162200200370ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # ArrayFire documentation build configuration file, created by # sphinx-quickstart on Fri Jun 24 20:20:43 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath('..')) from __af_version__ import full_version # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode', 'numpydoc', 'sphinx.ext.autosummary', 'sphinx.ext.doctest', 'sphinx.ext.inheritance_diagram'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. # # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'ArrayFire' copyright = '2016, Pavan Yalamanchili' author = 'Pavan Yalamanchili' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = full_version # The full version, including alpha/beta/rc tags. release = full_version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # # today = '' # # Else, today_fmt is used as the format for a strftime call. # # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The reST default role (used for this markup: `text`) to use for all # documents. # # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. # " v documentation" by default. # html_title = 'ArrayFire Python documentation' # A shorter title for the navigation bar. Default is the same as html_title. # # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = "arrayfire_logo_symbol.png" # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # # html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. # # html_last_updated_fmt = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # # html_additional_pages = {} # If false, no module index is generated. # # html_domain_indices = True # If false, no index is generated. # # html_use_index = True # If true, the index is split into individual pages for each letter. # # html_split_index = False # If true, links to the reST sources are added to the pages. # # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh' # # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # 'ja' uses this config value. # 'zh' user can custom change `jieba` dictionary path. # # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'ArrayFiredoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'ArrayFire.tex', 'ArrayFire Documentation', 'Pavan Yalamanchili', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # # latex_use_parts = False # If true, show page references after internal links. # # latex_show_pagerefs = False # If true, show URL addresses after external links. # # latex_show_urls = False # Documents to append as an appendix to all manuals. # # latex_appendices = [] # If false, no module index is generated. # # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'arrayfire', 'ArrayFire Documentation', [author], 1) ] # If true, show URL addresses after external links. # # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'ArrayFire', 'ArrayFire Documentation', author, 'ArrayFire', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # # texinfo_appendices = [] # If false, no module index is generated. # # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # # texinfo_no_detailmenu = False python-arrayfire-3.3.20160624/docs/index.rst000077700000000000000000000000001276671162200231012arrayfire.rstustar00rootroot00000000000000python-arrayfire-3.3.20160624/docs/make.bat000066400000000000000000000170721276671162200201430ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. epub3 to make an epub3 echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled echo. coverage to run coverage check of the documentation if enabled echo. dummy to check syntax errors of document sources goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) REM Check if sphinx-build is available and fallback to Python version if any %SPHINXBUILD% 1>NUL 2>NUL if errorlevel 9009 goto sphinx_python goto sphinx_ok :sphinx_python set SPHINXBUILD=python -m sphinx.__init__ %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) :sphinx_ok if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\ArrayFire.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\ArrayFire.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "epub3" ( %SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3 if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub3 file is in %BUILDDIR%/epub3. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %~dp0 echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "coverage" ( %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage if errorlevel 1 exit /b 1 echo. echo.Testing of coverage in the sources finished, look at the ^ results in %BUILDDIR%/coverage/python.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) if "%1" == "dummy" ( %SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy if errorlevel 1 exit /b 1 echo. echo.Build finished. Dummy builder generates no files. goto end ) :end python-arrayfire-3.3.20160624/docs/modules.rst000066400000000000000000000001001276671162200207200ustar00rootroot00000000000000arrayfire ========= .. toctree:: :maxdepth: 4 arrayfire python-arrayfire-3.3.20160624/examples/000077500000000000000000000000001276671162200174155ustar00rootroot00000000000000python-arrayfire-3.3.20160624/examples/benchmarks/000077500000000000000000000000001276671162200215325ustar00rootroot00000000000000python-arrayfire-3.3.20160624/examples/benchmarks/bench_blas.py000066400000000000000000000017231276671162200241670ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import sys from time import time from arrayfire import (array, randu, matmul) import arrayfire as af def bench(A, iters = 100): start = time() for t in range(iters): B = af.matmul(A, A) af.sync() return (time() - start) / iters if __name__ == "__main__": if (len(sys.argv) > 1): af.set_device(int(sys.argv[1])) af.info() print("Benchmark N x N matrix multiply") for n in range(128, 2048 + 128, 128): A = af.randu(n, n) af.sync() t = bench(A) gflops = 2.0 * (n**3) / (t * 1E9) print("Time taken for %4d x %4d: %0.4f Gflops" % (n, n, gflops)) python-arrayfire-3.3.20160624/examples/benchmarks/bench_fft.py000066400000000000000000000017171276671162200240300ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import sys from time import time from arrayfire import (array, randu, matmul) import arrayfire as af def bench(A, iters = 100): start = time() for t in range(iters): B = af.fft2(A) af.sync() return (time() - start) / iters if __name__ == "__main__": if (len(sys.argv) > 1): af.set_device(int(sys.argv[1])) af.info() print("Benchmark N x N 2D fft") for M in range(7, 13): N = 1 << M A = af.randu(N, N) af.sync() t = bench(A) gflops = (10.0 * N * N * M) / (t * 1E9) print("Time taken for %4d x %4d: %0.4f Gflops" % (N, N, gflops)) python-arrayfire-3.3.20160624/examples/benchmarks/monte_carlo_pi.py000077500000000000000000000030051276671162200250770ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## from random import random from time import time from arrayfire import (array, randu) import arrayfire as af import sys #alias range / xrange because xrange is faster than range in python2 try: frange = xrange #Python2 except NameError: frange = range #Python3 def calc_pi_device(samples): x = randu(samples) y = randu(samples) return 4 * af.sum((x * x + y * y) < 1) / samples # Having the function outside is faster than the lambda inside def in_circle(x, y): return (x*x + y*y) < 1 def calc_pi_host(samples): count = sum(1 for k in frange(samples) if in_circle(random(), random())) return 4 * float(count) / samples def bench(calc_pi, samples=1000000, iters=25): func_name = calc_pi.__name__[8:] print("Monte carlo estimate of pi on %s with %d million samples: %f" % \ (func_name, samples/1e6, calc_pi(samples))) start = time() for k in frange(iters): calc_pi(samples) end = time() print("Average time taken: %f ms" % (1000 * (end - start) / iters)) if __name__ == "__main__": if (len(sys.argv) > 1): af.set_device(int(sys.argv[1])) af.info() bench(calc_pi_device) bench(calc_pi_host) python-arrayfire-3.3.20160624/examples/financial/000077500000000000000000000000001276671162200213415ustar00rootroot00000000000000python-arrayfire-3.3.20160624/examples/financial/black_scholes_options.py000066400000000000000000000035561276671162200262730ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af from time import time import math import sys sqrt2 = math.sqrt(2.0) def cnd(x): temp = (x > 0) return temp * (0.5 + af.erf(x/sqrt2)/2) + (1 - temp) * (0.5 - af.erf((-x)/sqrt2)/2) def black_scholes(S, X, R, V, T): # S = Underlying stock price # X = Strike Price # R = Risk free rate of interest # V = Volatility # T = Time to maturity d1 = af.log(S / X) d1 = d1 + (R + (V * V) * 0.5) * T d1 = d1 / (V * af.sqrt(T)) d2 = d1 - (V * af.sqrt(T)) cnd_d1 = cnd(d1) cnd_d2 = cnd(d2) C = S * cnd_d1 - (X * af.exp((-R) * T) * cnd_d2) P = X * af.exp((-R) * T) * (1 - cnd_d2) - (S * (1 -cnd_d1)) return (C, P) if __name__ == "__main__": if (len(sys.argv) > 1): af.set_device(int(sys.argv[1])) af.info() M = 4000 S = af.randu(M, 1) X = af.randu(M, 1) R = af.randu(M, 1) V = af.randu(M, 1) T = af.randu(M, 1) (C, P) = black_scholes(S, X, R, V, T) af.eval(C) af.eval(P) af.sync() num_iter = 100 for N in range(50, 501, 50): S = af.randu(M, N) X = af.randu(M, N) R = af.randu(M, N) V = af.randu(M, N) T = af.randu(M, N) af.sync() print("Input data size: %d elements" % (M * N)) start = time() for i in range(num_iter): (C, P) = black_scholes(S, X, R, V, T) af.eval(C) af.eval(P) af.sync() sec = (time() - start) / num_iter print("Mean GPU Time: %0.6f ms\n\n" % (1000.0 * sec)) python-arrayfire-3.3.20160624/examples/financial/heston_model.py000066400000000000000000000073511276671162200244010ustar00rootroot00000000000000#!/usr/bin/python ############################################################################################## # Copyright (c) 2015, Michael Nowotny # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. 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. # # 3. Neither the name of the copyright holder 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. ############################################################################################### import arrayfire as af import math import time def simulateHestonModel( T, N, R, mu, kappa, vBar, sigmaV, rho, x0, v0 ) : deltaT = T / (float)(N - 1) x = [af.constant(x0, R, dtype=af.Dtype.f32), af.constant(0, R, dtype=af.Dtype.f32)] v = [af.constant(v0, R, dtype=af.Dtype.f32), af.constant(0, R, dtype=af.Dtype.f32)] sqrtDeltaT = math.sqrt(deltaT) sqrtOneMinusRhoSquare = math.sqrt(1-rho**2) m = af.constant(0, 2, dtype=af.Dtype.f32) m[0] = rho m[1] = sqrtOneMinusRhoSquare zeroArray = af.constant(0, R, 1, dtype=af.Dtype.f32) for t in range(1, N) : tPrevious = (t + 1) % 2 tCurrent = t % 2 dBt = af.randn(R, 2, dtype=af.Dtype.f32) * sqrtDeltaT vLag = af.maxof(v[tPrevious], zeroArray) sqrtVLag = af.sqrt(vLag) x[tCurrent] = x[tPrevious] + (mu - 0.5 * vLag) * deltaT + sqrtVLag * dBt[:, 0] v[tCurrent] = vLag + kappa * (vBar - vLag) * deltaT + sigmaV * (sqrtVLag * af.matmul(dBt, m)) return (x[tCurrent], af.maxof(v[tCurrent], zeroArray)) def main(): T = 1 nT = 20 * T R_first = 1000 R = 5000000 x0 = 0 # initial log stock price v0 = 0.087**2 # initial volatility r = math.log(1.0319) # risk-free rate rho = -0.82 # instantaneous correlation between Brownian motions sigmaV = 0.14 # variance of volatility kappa = 3.46 # mean reversion speed vBar = 0.008 # mean variance k = math.log(0.95) # strike price # first run ( x, v ) = simulateHestonModel( T, nT, R_first, r, kappa, vBar, sigmaV, rho, x0, v0 ) # Price plain vanilla call option tic = time.time() ( x, v ) = simulateHestonModel( T, nT, R, r, kappa, vBar, sigmaV, rho, x0, v0 ) af.sync() toc = time.time() - tic K = math.exp(k) zeroConstant = af.constant(0, R, dtype=af.Dtype.f32) C_CPU = math.exp(-r * T) * af.mean(af.maxof(af.exp(x) - K, zeroConstant)) print("Time elapsed = {} secs".format(toc)) print("Call price = {}".format(C_CPU)) print(af.mean(v)) if __name__ == "__main__": main() python-arrayfire-3.3.20160624/examples/financial/monte_carlo_options.py000066400000000000000000000034731276671162200257770ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af from time import time import math import sys def monte_carlo_options(N, K, t, vol, r, strike, steps, use_barrier = True, B = None, ty = af.Dtype.f32): payoff = af.constant(0, N, 1, dtype = ty) dt = t / float(steps - 1) s = af.constant(strike, N, 1, dtype = ty) randmat = af.randn(N, steps - 1, dtype = ty) randmat = af.exp((r - (vol * vol * 0.5)) * dt + vol * math.sqrt(dt) * randmat); S = af.product(af.join(1, s, randmat), 1) if (use_barrier): S = S * af.all_true(S < B, 1) payoff = af.maxof(0, S - K) return af.mean(payoff) * math.exp(-r * t) def monte_carlo_simulate(N, use_barrier, num_iter = 10): steps = 180 stock_price = 100.0 maturity = 0.5 volatility = 0.3 rate = 0.01 strike = 100 barrier = 115.0 start = time() for i in range(num_iter): monte_carlo_options(N, stock_price, maturity, volatility, rate, strike, steps, use_barrier, barrier) return (time() - start) / num_iter if __name__ == "__main__": if (len(sys.argv) > 1): af.set_device(int(sys.argv[1])) af.info() monte_carlo_simulate(1000, use_barrier = False) monte_carlo_simulate(1000, use_barrier = True ) af.sync() for n in range(10000, 100001, 10000): print("Time for %7d paths - vanilla method: %4.3f ms, barrier method: % 4.3f ms\n" % (n, 1000 * monte_carlo_simulate(n, False, 100), 1000 * monte_carlo_simulate(n, True, 100))) python-arrayfire-3.3.20160624/examples/getting_started/000077500000000000000000000000001276671162200226045ustar00rootroot00000000000000python-arrayfire-3.3.20160624/examples/getting_started/convolve.py000066400000000000000000000024171276671162200250150ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af import sys from array import array def af_assert(left, right, eps=1E-6): if (af.max(af.abs(left -right)) > eps): raise ValueError("Arrays not within dictated precision") return if __name__ == "__main__": if (len(sys.argv) > 1): af.set_device(int(sys.argv[1])) af.info() h_dx = array('f', (1.0/12, -8.0/12, 0, 8.0/12, 1.0/12)) h_spread = array('f', (1.0/5, 1.0/5, 1.0/5, 1.0/5, 1.0/5)) img = af.randu(640, 480) dx = af.Array(h_dx, (5,1)) spread = af.Array(h_spread, (1, 5)) kernel = af.matmul(dx, spread) full_res = af.convolve2(img, kernel) sep_res = af.convolve2_separable(dx, spread, img) af_assert(full_res, sep_res) print("full 2D convolution time: %.5f ms" % (1000 * af.timeit(af.convolve2, img, kernel))) print("separable 2D convolution time: %.5f ms" % (1000 * af.timeit(af.convolve2_separable, dx, spread, img))) python-arrayfire-3.3.20160624/examples/getting_started/intro.py000066400000000000000000000032351276671162200243140ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af import sys from array import array if __name__ == "__main__": if (len(sys.argv) > 1): af.set_device(int(sys.argv[1])) af.info() print("\n---- Intro to ArrayFire using signed(s32) arrays ----\n") h_A = array('i', ( 1, 2, 4, -1, 2, 0, 4, 2, 3)) h_B = array('i', ( 2, 3, 5, 6, 0, 10,-12, 0, 1)) A = af.Array(h_A, (3,3)) B = af.Array(h_B, (3,3)) print("\n---- Sub referencing and sub assignment\n") af.display(A) af.display(A[0,:]) af.display(A[:,0]) A[0,0] = 11 A[1] = 100 af.display(A) af.display(B) A[1,:] = B[2,:] af.display(A) print("\n---- Bitwise operations\n") af.display(A & B) af.display(A | B) af.display(A ^ B) print("\n---- Transpose\n") af.display(A) af.display(af.transpose(A)) print("\n---- Flip Vertically / Horizontally\n") af.display(A) af.display(af.flip(A, 0)) af.display(af.flip(A, 1)) print("\n---- Sum, Min, Max along row / columns\n") af.display(A) af.display(af.sum(A, 0)) af.display(af.min(A, 0)) af.display(af.max(A, 0)) af.display(af.sum(A, 1)) af.display(af.min(A, 1)) af.display(af.max(A, 1)) print("\n---- Get minimum with index\n") (min_val, min_idx) = af.imin(A, 0) af.display(min_val) af.display(min_idx) python-arrayfire-3.3.20160624/examples/graphics/000077500000000000000000000000001276671162200212155ustar00rootroot00000000000000python-arrayfire-3.3.20160624/examples/graphics/conway.py000066400000000000000000000045721276671162200230770ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af import array from time import time h_kernel = array.array('f', (1, 1, 1, 1, 0, 1, 1, 1, 1)) reset = 500 game_w = 128 game_h = 128 fps = 30 print("Example demonstrating conway's game of life using arrayfire") print("The conway_pretty example visualizes all the states in Conway") print("Red : Cells that have died due to under population" ) print("Yellow: Cells that continue to live from previous state" ) print("Green : Cells that are new as a result of reproduction" ) print("Blue : Cells that have died due to over population" ) print("This examples is throttled to 30 FPS so as to be a better visualization") simple_win = af.Window(512, 512, "Conway's Game of Life - Current State") pretty_win = af.Window(512, 512, "Conway's Game of Life - Current State with visualization") simple_win.set_pos(25, 15) pretty_win.set_pos(600, 25) frame_count = 0 # Copy kernel that specifies neighborhood conditions kernel = af.Array(h_kernel, dims=(3,3)) # Generate the initial state with 0s and 1s state = (af.randu(game_h, game_w) > 0.4).as_type(af.Dtype.f32) # tile 3 times to display color display = af.tile(state, 1, 1, 3, 1) while (not simple_win.close()) and (not pretty_win.close()): delay = time() if (not simple_win.close()): simple_win.image(state) if (not pretty_win.close()): pretty_win.image(display) frame_count += 1 if (frame_count % reset == 0): state = (af.randu(game_h, game_w) > 0.4).as_type(af.Dtype.f32) neighborhood = af.convolve(state, kernel) # state == 1 && neighborhood < 2 --> state = 0 # state == 1 && neighborhood > 3 --> state = 0 # state == 0 && neighborhood == 3 --> state = 1 # else state remains un changed C0 = neighborhood == 2 C1 = neighborhood == 3 A0 = (state == 1) & (neighborhood < 2) A1 = (state != 0) & (C0 | C1) A2 = (state == 0) & C1 A3 = (state == 1) & (neighborhood > 3) display = af.join(2, A0 + A1, A1 + A2, A3).as_type(af.Dtype.f32) state = state * C0 + C1 while(time() - delay < (1.0 / fps)): pass python-arrayfire-3.3.20160624/examples/graphics/fractal.py000066400000000000000000000034201276671162200232020ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af import sys from math import sqrt width = 400 height = 400 def complex_grid(w, h, zoom, center): x = (af.iota(d0 = 1, d1 = h, tile_dims = (w, 1)) - h/2) / zoom + center[0] y = (af.iota(d0 = w, d1 = 1, tile_dims = (1, h)) - w/2) / zoom + center[1] return af.cplx(x, y) def mandelbrot(data, it, maxval): C = data Z = data mag = af.constant(0, *C.dims()) for ii in range(1, 1 + it): # Doing the calculation Z = Z * Z + C # Get indices where abs(Z) crosses maxval cond = ((af.abs(Z) > maxval)).as_type(af.Dtype.f32) mag = af.maxof(mag, cond * ii) C = C * (1 - cond) Z = Z * (1 - cond) af.eval(C) af.eval(Z) return mag / maxval def normalize(a): mx = af.max(a) mn = af.min(a) return (a - mn)/(mx - mn) if __name__ == "__main__": if (len(sys.argv) > 1): af.set_device(int(sys.argv[1])) af.info() print("ArrayFire Fractal Demo\n") win = af.Window(width, height, "Fractal Demo") win.set_colormap(af.COLORMAP.SPECTRUM) center = (-0.75, 0.1) for i in range(10, 400): zoom = i * i if not (i % 10): print("Iteration: %d zoom: %d" % (i, zoom)) c = complex_grid(width, height, zoom, center) it = sqrt(2*sqrt(abs(1-sqrt(5*zoom))))*100 if (win.close()): break mag = mandelbrot(c, int(it), 1000) win.image(normalize(mag)) python-arrayfire-3.3.20160624/examples/graphics/histogram.py000066400000000000000000000020351276671162200235640ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af import sys import os if __name__ == "__main__": if (len(sys.argv) == 1): raise RuntimeError("Expected to the image as the first argument") if not os.path.isfile(sys.argv[1]): raise RuntimeError("File %s not found" % sys.argv[1]) if (len(sys.argv) > 2): af.set_device(int(sys.argv[2])) af.info() hist_win = af.Window(512, 512, "3D Plot example using ArrayFire") img_win = af.Window(480, 640, "Input Image") img = af.load_image(sys.argv[1]).as_type(af.Dtype.u8) hist = af.histogram(img, 256, 0, 255) while (not hist_win.close()) and (not img_win.close()): hist_win.hist(hist, 0, 255) img_win.image(img) python-arrayfire-3.3.20160624/examples/graphics/plot2d.py000077500000000000000000000014061276671162200227770ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af import math POINTS = 10000 PRECISION = 1.0 / float(POINTS) val = -math.pi X = math.pi * (2 * (af.range(POINTS) / POINTS) - 1) win = af.Window(512, 512, "2D Plot example using ArrayFire") sign = 1.0 while not win.close(): Y = af.sin(X) win.plot(X, Y) X += PRECISION * sign val += PRECISION * sign if (val > math.pi): sign = -1.0 elif (val < -math.pi): sign = 1.0 python-arrayfire-3.3.20160624/examples/graphics/plot3.py000066400000000000000000000013721276671162200226330ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af af.info() ITERATIONS = 200 POINTS = int(10.0 * ITERATIONS) Z = 1 + af.range(POINTS) / ITERATIONS win = af.Window(800, 800, "3D Plot example using ArrayFire") t = 0.1 while not win.close(): X = af.cos(Z * t + t) / Z Y = af.sin(Z * t + t) / Z X = af.maxof(af.minof(X, 1), -1) Y = af.maxof(af.minof(Y, 1), -1) Pts = af.join(1, X, Y, Z) win.plot3(Pts) t = t + 0.01 python-arrayfire-3.3.20160624/examples/graphics/surface.py000066400000000000000000000013501276671162200232160ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af af.info() POINTS = 30 N = 2 * POINTS x = (af.iota(d0 = N, d1 = 1, tile_dims = (1, N)) - POINTS) / POINTS y = (af.iota(d0 = 1, d1 = N, tile_dims = (N, 1)) - POINTS) / POINTS win = af.Window(800, 800, "3D Surface example using ArrayFire") t = 0 while not win.close(): t = t + 0.07 z = 10*x*-af.abs(y) * af.cos(x*x*(y+t))+af.sin(y*(x+t))-1.5; win.surface(x, y, z) python-arrayfire-3.3.20160624/examples/helloworld/000077500000000000000000000000001276671162200215705ustar00rootroot00000000000000python-arrayfire-3.3.20160624/examples/helloworld/helloworld.py000077500000000000000000000011441276671162200243200ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af # Display backend information af.info() # Generate a uniform random array with a size of 5 elements a = af.randu(5, 1) # Print a and its minimum value print(a) # Print min and max values of a print("Minimum, Maximum: ", af.min(a), af.max(a)) python-arrayfire-3.3.20160624/setup.py000066400000000000000000000013751276671162200173170ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## from setuptools import setup, find_packages #from __af_version__ import full_version #TODO: #1) Look for af libraries during setup #2) Include test suite setup( author="Pavan Yalamanchili", author_email="pavan@arrayfire.com", name="arrayfire", version="3.3.20160624.post1", description="Python bindings for ArrayFire", license="BSD", url="http://arrayfire.com", packages=['arrayfire'], ) python-arrayfire-3.3.20160624/tests/000077500000000000000000000000001276671162200167415ustar00rootroot00000000000000python-arrayfire-3.3.20160624/tests/__main__.py000066400000000000000000000024151276671162200210350ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import sys from simple_tests import * tests = {} tests['simple'] = simple.tests def assert_valid(name, name_list, name_str): is_valid = any([name == val for val in name_list]) if not is_valid: err_str = "The first argument needs to be a %s name\n" % name_str err_str += "List of supported %ss: %s" % (name_str, str(list(name_list))) raise RuntimeError(err_str) if __name__ == "__main__": module_name = None num_args = len(sys.argv) if (num_args > 1): module_name = sys.argv[1].lower() assert_valid(sys.argv[1].lower(), tests.keys(), "module") if (module_name is None): for name in tests: tests[name].run() else: test = tests[module_name] test_list = None if (num_args > 2): test_list = sys.argv[2:] for test_name in test_list: assert_valid(test_name.lower(), test.keys(), "test") test.run(test_list) python-arrayfire-3.3.20160624/tests/simple/000077500000000000000000000000001276671162200202325ustar00rootroot00000000000000python-arrayfire-3.3.20160624/tests/simple/__init__.py000066400000000000000000000011231276671162200223400ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## from .algorithm import * from .arith import * from .array_test import * from .blas import * from .data import * from .device import * from .image import * from .index import * from .lapack import * from .signal import * from .statistics import * from ._util import tests python-arrayfire-3.3.20160624/tests/simple/_util.py000066400000000000000000000032071276671162200217220ustar00rootroot00000000000000####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import traceback import logging import arrayfire as af import sys class _simple_test_dict(dict): def __init__(self): self.print_str = "Simple %16s: %s" self.failed = False super(_simple_test_dict, self).__init__() def run(self, name_list=None, verbose=False): test_list = name_list if name_list is not None else self.keys() for key in test_list: self.print_log = '' try: test = self[key] except: print(self.print_str % (key, "NOTFOUND")) continue try: test(verbose) print(self.print_str % (key, "PASSED")) except Exception as e: print(self.print_str % (key, "FAILED")) self.failed = True if (not verbose): print(tests.print_log) logging.error(traceback.format_exc()) if (self.failed): sys.exit(1) tests = _simple_test_dict() def print_func(verbose): def print_func_impl(*args): _print_log = '' for arg in args: _print_log += str(arg) + '\n' if (verbose): print(_print_log) tests.print_log += _print_log return print_func_impl def display_func(verbose): return print_func(verbose) python-arrayfire-3.3.20160624/tests/simple/algorithm.py000066400000000000000000000044621276671162200226000ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af from . import _util def simple_algorithm(verbose = False): display_func = _util.display_func(verbose) print_func = _util.print_func(verbose) a = af.randu(3, 3) print_func(af.sum(a), af.product(a), af.min(a), af.max(a), af.count(a), af.any_true(a), af.all_true(a)) display_func(af.sum(a, 0)) display_func(af.sum(a, 1)) display_func(af.product(a, 0)) display_func(af.product(a, 1)) display_func(af.min(a, 0)) display_func(af.min(a, 1)) display_func(af.max(a, 0)) display_func(af.max(a, 1)) display_func(af.count(a, 0)) display_func(af.count(a, 1)) display_func(af.any_true(a, 0)) display_func(af.any_true(a, 1)) display_func(af.all_true(a, 0)) display_func(af.all_true(a, 1)) display_func(af.accum(a, 0)) display_func(af.accum(a, 1)) display_func(af.sort(a, is_ascending=True)) display_func(af.sort(a, is_ascending=False)) b = (a > 0.1) * a c = (a > 0.4) * a d = b / c print_func(af.sum(d)); print_func(af.sum(d, nan_val=0.0)); display_func(af.sum(d, dim=0, nan_val=0.0)); val,idx = af.sort_index(a, is_ascending=True) display_func(val) display_func(idx) val,idx = af.sort_index(a, is_ascending=False) display_func(val) display_func(idx) b = af.randu(3,3) keys,vals = af.sort_by_key(a, b, is_ascending=True) display_func(keys) display_func(vals) keys,vals = af.sort_by_key(a, b, is_ascending=False) display_func(keys) display_func(vals) c = af.randu(5,1) d = af.randu(5,1) cc = af.set_unique(c, is_sorted=False) dd = af.set_unique(af.sort(d), is_sorted=True) display_func(cc) display_func(dd) display_func(af.set_union(cc, dd, is_unique=True)) display_func(af.set_union(cc, dd, is_unique=False)) display_func(af.set_intersect(cc, cc, is_unique=True)) display_func(af.set_intersect(cc, cc, is_unique=False)) _util.tests['algorithm'] = simple_algorithm python-arrayfire-3.3.20160624/tests/simple/arith.py000066400000000000000000000105041276671162200217130ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af from . import _util def simple_arith(verbose = False): display_func = _util.display_func(verbose) print_func = _util.print_func(verbose) a = af.randu(3,3) b = af.constant(4, 3, 3) display_func(a) display_func(b) c = a + b d = a d += b display_func(c) display_func(d) display_func(a + 2) display_func(3 + a) c = a - b d = a d -= b display_func(c) display_func(d) display_func(a - 2) display_func(3 - a) c = a * b d = a d *= b display_func(c * 2) display_func(3 * d) display_func(a * 2) display_func(3 * a) c = a / b d = a d /= b display_func(c / 2.0) display_func(3.0 / d) display_func(a / 2) display_func(3 / a) c = a % b d = a d %= b display_func(c % 2.0) display_func(3.0 % d) display_func(a % 2) display_func(3 % a) c = a ** b d = a d **= b display_func(c ** 2.0) display_func(3.0 ** d) display_func(a ** 2) display_func(3 ** a) display_func(a < b) display_func(a < 0.5) display_func(0.5 < a) display_func(a <= b) display_func(a <= 0.5) display_func(0.5 <= a) display_func(a > b) display_func(a > 0.5) display_func(0.5 > a) display_func(a >= b) display_func(a >= 0.5) display_func(0.5 >= a) display_func(a != b) display_func(a != 0.5) display_func(0.5 != a) display_func(a == b) display_func(a == 0.5) display_func(0.5 == a) a = af.randu(3,3,dtype=af.Dtype.u32) b = af.constant(4, 3, 3, dtype=af.Dtype.u32) display_func(a & b) display_func(a & 2) c = a c &= 2 display_func(c) display_func(a | b) display_func(a | 2) c = a c |= 2 display_func(c) display_func(a >> b) display_func(a >> 2) c = a c >>= 2 display_func(c) display_func(a << b) display_func(a << 2) c = a c <<= 2 display_func(c) display_func(-a) display_func(+a) display_func(~a) display_func(a) display_func(af.cast(a, af.Dtype.c32)) display_func(af.maxof(a,b)) display_func(af.minof(a,b)) display_func(af.rem(a,b)) a = af.randu(3,3) - 0.5 b = af.randu(3,3) - 0.5 display_func(af.abs(a)) display_func(af.arg(a)) display_func(af.sign(a)) display_func(af.round(a)) display_func(af.trunc(a)) display_func(af.floor(a)) display_func(af.ceil(a)) display_func(af.hypot(a, b)) display_func(af.sin(a)) display_func(af.cos(a)) display_func(af.tan(a)) display_func(af.asin(a)) display_func(af.acos(a)) display_func(af.atan(a)) display_func(af.atan2(a, b)) c = af.cplx(a) d = af.cplx(a,b) display_func(c) display_func(d) display_func(af.real(d)) display_func(af.imag(d)) display_func(af.conjg(d)) display_func(af.sinh(a)) display_func(af.cosh(a)) display_func(af.tanh(a)) display_func(af.asinh(a)) display_func(af.acosh(a)) display_func(af.atanh(a)) a = af.abs(a) b = af.abs(b) display_func(af.root(a, b)) display_func(af.pow(a, b)) display_func(af.pow2(a)) display_func(af.sigmoid(a)) display_func(af.exp(a)) display_func(af.expm1(a)) display_func(af.erf(a)) display_func(af.erfc(a)) display_func(af.log(a)) display_func(af.log1p(a)) display_func(af.log10(a)) display_func(af.log2(a)) display_func(af.sqrt(a)) display_func(af.cbrt(a)) a = af.round(5 * af.randu(3,3) - 1) b = af.round(5 * af.randu(3,3) - 1) display_func(af.factorial(a)) display_func(af.tgamma(a)) display_func(af.lgamma(a)) display_func(af.iszero(a)) display_func(af.isinf(a/b)) display_func(af.isnan(a/a)) a = af.randu(5, 1) b = af.randu(1, 5) c = af.broadcast(lambda x,y: x+y, a, b) display_func(a) display_func(b) display_func(c) @af.broadcast def test_add(aa, bb): return aa + bb display_func(test_add(a, b)) _util.tests['arith'] = simple_arith python-arrayfire-3.3.20160624/tests/simple/array_test.py000066400000000000000000000037651276671162200227740ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af import array as host from . import _util def simple_array(verbose=False): display_func = _util.display_func(verbose) print_func = _util.print_func(verbose) a = af.Array([1, 2, 3]) display_func(a) display_func(a.T) display_func(a.H) print_func(a.shape) b = a.as_type(af.Dtype.s32) display_func(b) print_func(a.elements(), a.type(), a.dims(), a.numdims()) print_func(a.is_empty(), a.is_scalar(), a.is_column(), a.is_row()) print_func(a.is_complex(), a.is_real(), a.is_double(), a.is_single()) print_func(a.is_real_floating(), a.is_floating(), a.is_integer(), a.is_bool()) a = af.Array(host.array('i', [4, 5, 6])) display_func(a) print_func(a.elements(), a.type(), a.dims(), a.numdims()) print_func(a.is_empty(), a.is_scalar(), a.is_column(), a.is_row()) print_func(a.is_complex(), a.is_real(), a.is_double(), a.is_single()) print_func(a.is_real_floating(), a.is_floating(), a.is_integer(), a.is_bool()) a = af.Array(host.array('I', [7, 8, 9] * 3), (3,3)) display_func(a) print_func(a.elements(), a.type(), a.dims(), a.numdims()) print_func(a.is_empty(), a.is_scalar(), a.is_column(), a.is_row()) print_func(a.is_complex(), a.is_real(), a.is_double(), a.is_single()) print_func(a.is_real_floating(), a.is_floating(), a.is_integer(), a.is_bool()) c = a.to_ctype() for n in range(a.elements()): print_func(c[n]) c,s = a.to_ctype(True, True) for n in range(a.elements()): print_func(c[n]) print_func(s) arr = a.to_array() lst = a.to_list(True) print_func(arr) print_func(lst) _util.tests['array'] = simple_array python-arrayfire-3.3.20160624/tests/simple/blas.py000066400000000000000000000014311276671162200215240ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af from . import _util def simple_blas(verbose=False): display_func = _util.display_func(verbose) print_func = _util.print_func(verbose) a = af.randu(5,5) b = af.randu(5,5) display_func(af.matmul(a,b)) display_func(af.matmul(a,b,af.MATPROP.TRANS)) display_func(af.matmul(a,b,af.MATPROP.NONE, af.MATPROP.TRANS)) b = af.randu(5,1) display_func(af.dot(b,b)) _util.tests['blas'] = simple_blas python-arrayfire-3.3.20160624/tests/simple/data.py000066400000000000000000000043051276671162200215170ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af from . import _util def simple_data(verbose=False): display_func = _util.display_func(verbose) print_func = _util.print_func(verbose) display_func(af.constant(100, 3,3, dtype=af.Dtype.f32)) display_func(af.constant(25, 3,3, dtype=af.Dtype.c32)) display_func(af.constant(2**50, 3,3, dtype=af.Dtype.s64)) display_func(af.constant(2+3j, 3,3)) display_func(af.constant(3+5j, 3,3, dtype=af.Dtype.c32)) display_func(af.range(3, 3)) display_func(af.iota(3, 3, tile_dims=(2,2))) display_func(af.randu(3, 3, 1, 2)) display_func(af.randu(3, 3, 1, 2, af.Dtype.b8)) display_func(af.randu(3, 3, dtype=af.Dtype.c32)) display_func(af.randn(3, 3, 1, 2)) display_func(af.randn(3, 3, dtype=af.Dtype.c32)) af.set_seed(1024) assert(af.get_seed() == 1024) display_func(af.identity(3, 3, 1, 2, af.Dtype.b8)) display_func(af.identity(3, 3, dtype=af.Dtype.c32)) a = af.randu(3, 4) b = af.diag(a, extract=True) c = af.diag(a, 1, extract=True) display_func(a) display_func(b) display_func(c) display_func(af.diag(b, extract = False)) display_func(af.diag(c, 1, extract = False)) display_func(af.join(0, a, a)) display_func(af.join(1, a, a, a)) display_func(af.tile(a, 2, 2)) display_func(af.reorder(a, 1, 0)) display_func(af.shift(a, -1, 1)) display_func(af.moddims(a, 6, 2)) display_func(af.flat(a)) display_func(af.flip(a, 0)) display_func(af.flip(a, 1)) display_func(af.lower(a, False)) display_func(af.lower(a, True)) display_func(af.upper(a, False)) display_func(af.upper(a, True)) a = af.randu(5,5) display_func(af.transpose(a)) af.transpose_inplace(a) display_func(a) display_func(af.select(a > 0.3, a, -0.3)) af.replace(a, a > 0.3, -0.3) display_func(a) _util.tests['data'] = simple_data python-arrayfire-3.3.20160624/tests/simple/device.py000066400000000000000000000027721276671162200220530ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af from . import _util def simple_device(verbose=False): display_func = _util.display_func(verbose) print_func = _util.print_func(verbose) print_func(af.device_info()) print_func(af.get_device_count()) print_func(af.is_dbl_supported()) af.sync() curr_dev = af.get_device() print_func(curr_dev) for k in range(af.get_device_count()): af.set_device(k) dev = af.get_device() assert(k == dev) print_func(af.is_dbl_supported(k)) af.device_gc() mem_info_old = af.device_mem_info() a = af.randu(100, 100) af.sync(dev) mem_info = af.device_mem_info() assert(mem_info['alloc']['buffers'] == 1 + mem_info_old['alloc']['buffers']) assert(mem_info[ 'lock']['buffers'] == 1 + mem_info_old[ 'lock']['buffers']) af.set_device(curr_dev) a = af.randu(10,10) display_func(a) dev_ptr = af.get_device_ptr(a) print_func(dev_ptr) b = af.Array(src=dev_ptr, dims=a.dims(), dtype=a.dtype(), is_device=True) display_func(b) c = af.randu(10,10) af.lock_array(c) af.unlock_array(c) _util.tests['device'] = simple_device python-arrayfire-3.3.20160624/tests/simple/image.py000066400000000000000000000041431276671162200216700ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af from . import _util def simple_image(verbose = False): display_func = _util.display_func(verbose) print_func = _util.print_func(verbose) a = 10 * af.randu(6, 6) a3 = 10 * af.randu(5,5,3) dx,dy = af.gradient(a) display_func(dx) display_func(dy) display_func(af.resize(a, scale=0.5)) display_func(af.resize(a, odim0=8, odim1=8)) t = af.randu(3,2) display_func(af.transform(a, t)) display_func(af.rotate(a, 3.14)) display_func(af.translate(a, 1, 1)) display_func(af.scale(a, 1.2, 1.2, 7, 7)) display_func(af.skew(a, 0.02, 0.02)) h = af.histogram(a, 3) display_func(h) display_func(af.hist_equal(a, h)) display_func(af.dilate(a)) display_func(af.erode(a)) display_func(af.dilate3(a3)) display_func(af.erode3(a3)) display_func(af.bilateral(a, 1, 2)) display_func(af.mean_shift(a, 1, 2, 3)) display_func(af.medfilt(a)) display_func(af.minfilt(a)) display_func(af.maxfilt(a)) display_func(af.regions(af.round(a) > 3)) dx,dy = af.sobel_derivatives(a) display_func(dx) display_func(dy) display_func(af.sobel_filter(a)) display_func(af.gaussian_kernel(3, 3)) display_func(af.gaussian_kernel(3, 3, 1, 1)) ac = af.gray2rgb(a) display_func(ac) display_func(af.rgb2gray(ac)) ah = af.rgb2hsv(ac) display_func(ah) display_func(af.hsv2rgb(ah)) display_func(af.color_space(a, af.CSPACE.RGB, af.CSPACE.GRAY)) a = af.randu(6,6) b = af.unwrap(a, 2, 2, 2, 2) c = af.wrap(b, 6, 6, 2, 2, 2, 2) display_func(a) display_func(b) display_func(c) display_func(af.sat(a)) a = af.randu(10,10,3) display_func(af.rgb2ycbcr(a)) display_func(af.ycbcr2rgb(a)) _util.tests['image'] = simple_image python-arrayfire-3.3.20160624/tests/simple/index.py000066400000000000000000000035121276671162200217140ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af from arrayfire import ParallelRange import array as host from . import _util def simple_index(verbose=False): display_func = _util.display_func(verbose) print_func = _util.print_func(verbose) a = af.randu(5, 5) display_func(a) b = af.Array(a) display_func(b) c = a.copy() display_func(c) display_func(a[0,0]) display_func(a[0]) display_func(a[:]) display_func(a[:,:]) display_func(a[0:3,]) display_func(a[-2:-1,-1]) display_func(a[0:5]) display_func(a[0:5:2]) idx = af.Array(host.array('i', [0, 3, 2])) display_func(idx) aa = a[idx] display_func(aa) a[0] = 1 display_func(a) a[0] = af.randu(1, 5) display_func(a) a[:] = af.randu(5,5) display_func(a) a[:,-1] = af.randu(5,1) display_func(a) a[0:5:2] = af.randu(3, 5) display_func(a) a[idx, idx] = af.randu(3,3) display_func(a) a = af.randu(5,1) b = af.randu(5,1) display_func(a) display_func(b) for ii in ParallelRange(1,3): a[ii] = b[ii] display_func(a) for ii in ParallelRange(2,5): b[ii] = 2 display_func(b) a = af.randu(3,2) rows = af.constant(0, 1, dtype=af.Dtype.s32) b = a[:,rows] display_func(b) for r in rows: display_func(r) display_func(b[:,r]) a = af.randu(3) c = af.randu(3) b = af.constant(1,3,dtype=af.Dtype.b8) display_func(a) a[b] = c display_func(a) _util.tests['index'] = simple_index python-arrayfire-3.3.20160624/tests/simple/lapack.py000066400000000000000000000034511276671162200220420ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af from . import _util def simple_lapack(verbose=False): display_func = _util.display_func(verbose) print_func = _util.print_func(verbose) a = af.randu(5,5) l,u,p = af.lu(a) display_func(l) display_func(u) display_func(p) p = af.lu_inplace(a, "full") display_func(a) display_func(p) a = af.randu(5,3) q,r,t = af.qr(a) display_func(q) display_func(r) display_func(t) af.qr_inplace(a) display_func(a) a = af.randu(5, 5) a = af.matmulTN(a, a) + 10 * af.identity(5,5) R,info = af.cholesky(a) display_func(R) print_func(info) af.cholesky_inplace(a) display_func(a) a = af.randu(5,5) ai = af.inverse(a) display_func(a) display_func(ai) x0 = af.randu(5, 3) b = af.matmul(a, x0) x1 = af.solve(a, b) display_func(x0) display_func(x1) p = af.lu_inplace(a) x2 = af.solve_lu(a, p, b) display_func(x2) print_func(af.rank(a)) print_func(af.det(a)) print_func(af.norm(a, af.NORM.EUCLID)) print_func(af.norm(a, af.NORM.MATRIX_1)) print_func(af.norm(a, af.NORM.MATRIX_INF)) print_func(af.norm(a, af.NORM.MATRIX_L_PQ, 1, 1)) a = af.randu(10,10) display_func(a) u,s,vt = af.svd(a) display_func(af.matmul(af.matmul(u, af.diag(s, 0, False)), vt)) u,s,vt = af.svd_inplace(a) display_func(af.matmul(af.matmul(u, af.diag(s, 0, False)), vt)) _util.tests['lapack'] = simple_lapack python-arrayfire-3.3.20160624/tests/simple/signal.py000066400000000000000000000051761276671162200220720ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af from . import _util def simple_signal(verbose=False): display_func = _util.display_func(verbose) print_func = _util.print_func(verbose) a = af.randu(10, 1) pos0 = af.randu(10) * 10 display_func(af.approx1(a, pos0)) a = af.randu(3, 3) pos0 = af.randu(3, 3) * 10 pos1 = af.randu(3, 3) * 10 display_func(af.approx2(a, pos0, pos1)) a = af.randu(8, 1) display_func(a) display_func(af.fft(a)) display_func(af.dft(a)) display_func(af.real(af.ifft(af.fft(a)))) display_func(af.real(af.idft(af.dft(a)))) b = af.fft(a) af.ifft_inplace(b) display_func(b) af.fft_inplace(b) display_func(b) b = af.fft_r2c(a) c = af.fft_c2r(b) display_func(b) display_func(c) a = af.randu(4, 4) display_func(a) display_func(af.fft2(a)) display_func(af.dft(a)) display_func(af.real(af.ifft2(af.fft2(a)))) display_func(af.real(af.idft(af.dft(a)))) b = af.fft2(a) af.ifft2_inplace(b) display_func(b) af.fft2_inplace(b) display_func(b) b = af.fft2_r2c(a) c = af.fft2_c2r(b) display_func(b) display_func(c) a = af.randu(4, 4, 2) display_func(a) display_func(af.fft3(a)) display_func(af.dft(a)) display_func(af.real(af.ifft3(af.fft3(a)))) display_func(af.real(af.idft(af.dft(a)))) b = af.fft3(a) af.ifft3_inplace(b) display_func(b) af.fft3_inplace(b) display_func(b) b = af.fft3_r2c(a) c = af.fft3_c2r(b) display_func(b) display_func(c) a = af.randu(10, 1) b = af.randu(3, 1) display_func(af.convolve1(a, b)) display_func(af.fft_convolve1(a, b)) display_func(af.convolve(a, b)) display_func(af.fft_convolve(a, b)) a = af.randu(5, 5) b = af.randu(3, 3) display_func(af.convolve2(a, b)) display_func(af.fft_convolve2(a, b)) display_func(af.convolve(a, b)) display_func(af.fft_convolve(a, b)) a = af.randu(5, 5, 3) b = af.randu(3, 3, 2) display_func(af.convolve3(a, b)) display_func(af.fft_convolve3(a, b)) display_func(af.convolve(a, b)) display_func(af.fft_convolve(a, b)) b = af.randu(3, 1) x = af.randu(10, 1) a = af.randu(2, 1) display_func(af.fir(b, x)) display_func(af.iir(b, a, x)) _util.tests['signal'] = simple_signal python-arrayfire-3.3.20160624/tests/simple/statistics.py000066400000000000000000000024741276671162200230050ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import arrayfire as af from . import _util def simple_statistics(verbose=False): display_func = _util.display_func(verbose) print_func = _util.print_func(verbose) a = af.randu(5, 5) b = af.randu(5, 5) w = af.randu(5, 1) display_func(af.mean(a, dim=0)) display_func(af.mean(a, weights=w, dim=0)) print_func(af.mean(a)) print_func(af.mean(a, weights=w)) display_func(af.var(a, dim=0)) display_func(af.var(a, isbiased=True, dim=0)) display_func(af.var(a, weights=w, dim=0)) print_func(af.var(a)) print_func(af.var(a, isbiased=True)) print_func(af.var(a, weights=w)) display_func(af.stdev(a, dim=0)) print_func(af.stdev(a)) display_func(af.var(a, dim=0)) display_func(af.var(a, isbiased=True, dim=0)) print_func(af.var(a)) print_func(af.var(a, isbiased=True)) display_func(af.median(a, dim=0)) print_func(af.median(w)) print_func(af.corrcoef(a, b)) _util.tests['statistics'] = simple_statistics python-arrayfire-3.3.20160624/tests/simple_tests.py000077500000000000000000000011311276671162200220250ustar00rootroot00000000000000#!/usr/bin/python ####################################################### # Copyright (c) 2015, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-Clause ######################################################## import simple import sys if __name__ == "__main__": verbose = False if len(sys.argv) > 1: verbose = int(sys.argv[1]) test_list = None if len(sys.argv) > 2: test_list = sys.argv[2:] simple.tests.run(test_list, verbose)