diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4916921cc..c176f13e1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,57 +8,64 @@ jobs: fail-fast: false matrix: include: + - BUILD_TYPE: Debug + WITH_BFD: yes + PYTHON_VERSION: '3.12' + TEST_SYMPY: yes + OS: ubuntu-22.04 + CC: gcc + - BUILD_TYPE: Debug WITH_BFD: yes PYTHON_VERSION: '3.11' TEST_SYMPY: yes - OS: ubuntu-20.04 + OS: ubuntu-22.04 CC: gcc - BUILD_TYPE: Debug WITH_BFD: yes PYTHON_VERSION: '3.10' TEST_SYMPY: yes - OS: ubuntu-20.04 + OS: ubuntu-22.04 CC: gcc - BUILD_TYPE: Debug WITH_BFD: yes PYTHON_VERSION: '3.9' TEST_SYMPY: yes - OS: ubuntu-20.04 + OS: ubuntu-22.04 CC: gcc - BUILD_TYPE: Release - PYTHON_VERSION: '3.7' + PYTHON_VERSION: '3.13' BUILD_SHARED_LIBS: yes - OS: ubuntu-20.04 + OS: ubuntu-22.04 CC: gcc - BUILD_TYPE: Release - PYTHON_VERSION: '3.7' + PYTHON_VERSION: '3.13' WITH_MPFR: yes INTEGER_CLASS: gmpxx WITH_NUMPY: no - OS: ubuntu-20.04 + OS: ubuntu-22.04 CC: gcc - BUILD_TYPE: Release - PYTHON_VERSION: '3.8' + PYTHON_VERSION: '3.13' WITH_MPC: yes - OS: ubuntu-20.04 + OS: ubuntu-22.04 CC: gcc - BUILD_TYPE: Release WITH_MPFR: yes - PYTHON_VERSION: '3.8' - OS: ubuntu-20.04 + PYTHON_VERSION: '3.13' + OS: ubuntu-22.04 CC: gcc - BUILD_TYPE: Release PYTHON_VERSION: '3.9' WITH_MPC: yes - OS: ubuntu-20.04 + OS: ubuntu-22.04 CC: gcc - BUILD_TYPE: Release @@ -66,70 +73,73 @@ jobs: WITH_MPC: yes INTEGER_CLASS: flint WITH_FLINT: yes - OS: ubuntu-20.04 + OS: ubuntu-22.04 CC: gcc #- BUILD_TYPE: Debug # PYTHON_VERSION: '3.9' # WITH_BFD: yes # WITH_PIRANHA: yes - # OS: ubuntu-20.04 + # OS: ubuntu-22.04 # CC: gcc - BUILD_TYPE: Debug - PYTHON_VERSION: '3.8' + PYTHON_VERSION: '3.13' WITH_BFD: yes BUILD_SHARED_LIBS: yes - OS: ubuntu-20.04 + OS: ubuntu-22.04 CC: clang - BUILD_TYPE: Release - PYTHON_VERSION: '3.7' + PYTHON_VERSION: '3.13' WITH_NUMPY: yes - OS: ubuntu-20.04 + OS: ubuntu-22.04 CC: clang - BUILD_TYPE: Debug - PYTHON_VERSION: '3.10' + PYTHON_VERSION: '3.12' WITH_SYMPY: yes - WITH_LLVM: 14 + WITH_LLVM: 18 WITH_SCIPY: yes + WITH_LATEST_GCC: yes INTEGER_CLASS: 'boostmp' PYTEST_ADDOPTS: '-k "not integer_nthroot"' - OS: ubuntu-22.04 - EXTRA_APT_REPOSITORY: 'deb http://apt.llvm.org/jammy/ llvm-toolchain-jammy-14 main' - EXTRA_APT_PACKAGES: 'llvm-14' + OS: ubuntu-24.04 + CC: gcc # ubuntu nobel uses gcc-13 + #EXTRA_APT_REPOSITORY: 'deb http://apt.llvm.org/jammy/ llvm-toolchain-nobel-18 main' + EXTRA_APT_PACKAGES: 'llvm-18' - BUILD_TYPE: Debug - PYTHON_VERSION: '3.7' + PYTHON_VERSION: '3.13' WITH_SCIPY: yes WITH_LLVM: 5.0 - OS: macos-latest + OS: macos-13 CC: clang - BUILD_TYPE: Release PYTHON_VERSION: '3.9' WITH_NUMPY: no - OS: macos-latest + OS: macos-13 CC: clang - BUILD_TYPE: Debug - PYTHON_VERSION: '3.7' + PYTHON_VERSION: '3.13' WITH_NUMPY: no - OS: macos-latest + OS: macos-13 CC: gcc - BUILD_TYPE: Release - PYTHON_VERSION: '3.8' - OS: macos-latest + PYTHON_VERSION: '3.13' + OS: macos-13 CC: gcc - BUILD_TYPE: Release - PYTHON_VERSION: '3.8' - OS: ubuntu-20.04 + PYTHON_VERSION: '3.11' + OS: ubuntu-22.04 WITH_MPC: yes WITH_MPFR: yes WITH_FLINT: yes + WITH_FLINT_PY: yes WITH_SCIPY: yes WITH_DOCS: yes INTEGER_CLASS: flint @@ -137,11 +147,21 @@ jobs: CC: gcc steps: + + - uses: conda-incubator/setup-miniconda@v3 + if: matrix.MSYS_ENV == '' + with: + activate-environment: symengine + channel-priority: strict + architecture: x86_64 + channels: conda-forge + conda-remove-defaults: "true" + - name: Checkout code - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Build and test symengine - shell: bash + shell: bash -el {0} run: | source bin/test_symengine_unix.sh env: @@ -176,6 +196,7 @@ jobs: WITH_MPC: ${{ matrix.WITH_MPC }} MAKEFLAGS: ${{ matrix.MAKEFLAGS }} BUILD_SHARED_LIBS: ${{ matrix.BUILD_SHARED_LIBS }} + PYTHON_VERSION: ${{ matrix.PYTHON_VERSION }} - name: Deploy Documentation if: ${{ (github.ref == 'refs/heads/main' && github.repository == 'Symengine/symengine.py') || (github.ref == 'refs/heads/master' && github.repository == 'Symengine/symengine.py')}} diff --git a/.gitignore b/.gitignore index 1ef1e18ed..f93c02277 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,8 @@ cython_test.cpp *.vcxproj *.filters symengine/lib/symengine_wrapper.cpp +symengine/lib/symengine_wrapper.pyx +symengine/lib/symengine_wrapper.pxd # Config Files symengine/lib/config.pxi diff --git a/.mailmap b/.mailmap index 71840613b..11654a9b0 100644 --- a/.mailmap +++ b/.mailmap @@ -21,3 +21,5 @@ Abhinav Agarwal Nilay Pochhi Björn Dahlgren Richard Otis richardotis +Firat Bezir +Adrian Ostrowski <81568391+aostrowski-hbn@users.noreply.github.com> diff --git a/AUTHORS b/AUTHORS index b0719fd56..484d38bee 100644 --- a/AUTHORS +++ b/AUTHORS @@ -35,3 +35,7 @@ Garming Sam Pieter Eendebak Ayush Kumar Christian Clauss +Moraxyc +Aaron Miller <78561124+aaron-skydio@users.noreply.github.com> +Firat Bezir +Adrian Ostrowski diff --git a/CMakeLists.txt b/CMakeLists.txt index 0cf3c25c1..e83c95b18 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,8 +1,11 @@ -cmake_minimum_required(VERSION 2.8.12) +cmake_minimum_required(VERSION 2.8.12...4.0.0) if (POLICY CMP0057) cmake_policy(SET CMP0057 NEW) # needed for llvm >= 16 endif () +if (POLICY CMP0074) + cmake_policy(SET CMP0074 NEW) # allow user to set *_ROOT variables +endif() project(python_wrapper) @@ -10,7 +13,7 @@ set(CMAKE_PREFIX_PATH ${SymEngine_DIR} ${CMAKE_PREFIX_PATH}) include(GNUInstallDirs) -find_package(SymEngine 0.8.1 REQUIRED CONFIG +find_package(SymEngine 0.14.0 REQUIRED CONFIG PATH_SUFFIXES lib/cmake/symengine cmake/symengine CMake/) message("SymEngine_DIR : " ${SymEngine_DIR}) message("SymEngine Version : " ${SymEngine_VERSION}) diff --git a/README.md b/README.md index f6fc3742f..e13eb7272 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,8 @@ Python wrappers to the C++ library [SymEngine](https://github.com/symengine/symengine), a fast C++ symbolic manipulation library. -[![Build Status](https://travis-ci.org/symengine/symengine.py.svg)](https://travis-ci.org/symengine/symengine.py) [![Build status](https://ci.appveyor.com/api/projects/status/sl189l9ck3gd8qvk/branch/master?svg=true)](https://ci.appveyor.com/project/symengine/symengine-py/branch/master) +[![Build Status](https://travis-ci.org/symengine/symengine.py.svg)](https://travis-ci.org/symengine/symengine.py) +[![Build status](https://ci.appveyor.com/api/projects/status/sl189l9ck3gd8qvk/branch/master?svg=true)](https://ci.appveyor.com/project/symengine/symengine-py/branch/master) ## Installation @@ -11,71 +12,107 @@ a fast C++ symbolic manipulation library. See License section for information about wheels - pip install symengine --user +```bash +pip install symengine --user +``` ### Conda package manager - conda install python-symengine -c symengine -c conda-forge - -optionally, you may choose to install an early [developer preview](https://github.com/symengine/python-symengine-feedstock): - - conda install python-symengine -c symengine/label/dev -c conda-forge +```bash +conda install python-symengine -c conda-forge +``` ### Build from source Install prerequisites. - CMake >= 2.8.12 - Python3 >= 3.7 - Cython >= 0.29.24 - SymEngine >= 0.7.0 +```bash +CMake >= 2.8.12 +Python3 >= 3.8 +Cython >= 0.29.24 +SymEngine >= 0.7.0 +``` -For SymEngine, only a specific commit/tag (see symengine_version.txt) is supported. -Latest git master branch may not work as there may be breaking changes in SymEngine. +For **SymEngine**, only a specific commit/tag (see `symengine_version.txt`) is +supported. The latest git master branch may not work as there may be breaking +changes in **SymEngine**. Python wrappers can be installed by, - python setup.py install +```bash +python setup.py install +``` -Additional options to setup.py are +Additional options to `setup.py` are: - python setup.py install build_ext - --symengine-dir=/path/to/symengine/install/dir # Path to SymEngine install directory or build directory - --compiler=mingw32|msvc|cygwin # Select the compiler for Windows - --generator=cmake-generator # CMake Generator - --build-type=Release|Debug # Set build-type for multi-configuration generators like MSVC - --define="var1=value1;var2=value2" # Give options to CMake - --inplace # Build the extension in source tree +```bash +python setup.py install build_ext + --symengine-dir=/path/to/symengine/install/dir # Path to SymEngine install directory or build directory + --compiler=mingw32|msvc|cygwin # Select the compiler for Windows + --generator=cmake-generator # CMake Generator + --build-type=Release|Debug # Set build-type for multi-configuration generators like MSVC + --define="var1=value1;var2=value2" # Give options to CMake + --inplace # Build the extension in source tree +``` -Standard options to setup.py like `--user`, `--prefix` can be used to -configure install location. NumPy is used if found by default, if you wish +Standard options to `setup.py` like `--user`, `--prefix` can be used to +configure install location. NumPy is used if found by default, if you wish to make your choice of NumPy use explicit: then add -e.g. ``WITH_NUMPY=False`` to ``--define``. - -Use SymEngine from Python as follows: - - >>> from symengine import var - >>> var("x y z") - (x, y, z) - >>> e = (x+y+z)**2 - >>> e.expand() - 2*x*y + 2*x*z + 2*y*z + x**2 + y**2 + z**2 - -You can read Python tests in `symengine/tests` to see what features are -implemented. - +e.g. `WITH_NUMPY=False` to `--define`. + +### Notes on Dependencies + +If you intend to evaluate floating-point expressions (using **lambdify**), +you should consider linking against **LLVM**. Many users might also benefit +from linking against **FLINT**, as it is now LGPL-licensed. + +In general, **sudo** is only required if you are installing to the default +prefix (`/usr/local`). We recommend specifying a custom prefix +(`--prefix=$HOME/.local`) to avoid requiring administrative privileges, +which most users can do without using **sudo**. + +If you're uncomfortable specifying the prefix manually, we suggest using +**Conda** or installing the pre-built wheels via **pip** instead of building +from source. + +## Verification + +You can verify the installation of **SymEngine** by using the provided code +snippet in this README. This snippet ensures that the installation works as +expected and that basic functionality is available. + +```python +from symengine import var +x, y, z = var('x y z') +e = (x + y + z)**2 +expanded_e = e.expand() +print(expanded_e) +``` +This will output: +```python +x**2 + y**2 + z**2 + 2*x*y + 2*x*z + 2*y*z +``` + +Note: The verification code provided above checks the functionality of +SymEngine. For additional verification specific to SymEngine, please refer to +the [official SymEngine Python bindings repository](https://github.com/symengine/symengine.py) +for further tests and examples. ## License -symengine.py is MIT licensed and uses several LGPL, BSD-3 and MIT licensed libraries - -Licenses for the dependencies of pip wheels are as follows, - -pip wheels on Unix use GMP (LGPL-3.0-or-later), MPFR (LGPL-3.0-or-later), -MPC (LGPL-3.0-or-later), LLVM (Apache-2.0), zlib (Zlib), libxml2 (MIT), -zstd (BSD-3-Clause) and symengine (MIT AND BSD-3-Clause). -pip wheels on Windows use MPIR (LGPL-3.0-or-later) instead of GMP above and -pthreads-win32 (LGPL-3.0-or-later) additionally. -NumPy (BSD-3-Clause) and SymPy (BSD-3-Clause) are optional dependencies. -Sources for these binary dependencies can be found on https://github.com/symengine/symengine-wheels/releases +symengine.py is MIT licensed and uses several LGPL, BSD-3, and MIT licensed +libraries. + +Licenses for the dependencies of pip wheels are as follows: + +- pip wheels on Unix use **GMP** (LGPL-3.0-or-later), + **MPFR** (LGPL-3.0-or-later), **MPC** (LGPL-3.0-or-later), + **LLVM** (Apache-2.0), **zlib** (Zlib), **libxml2** (MIT), + **zstd** (BSD-3-Clause), and **symengine** (MIT AND BSD-3-Clause). +- pip wheels on Windows use **MPIR** (LGPL-3.0-or-later) instead of **GMP** + above and **pthreads-win32** (LGPL-3.0-or-later) additionally. +- **NumPy** (BSD-3-Clause) and **SymPy** (BSD-3-Clause) are optional + dependencies. +- Sources for these binary dependencies can be found on + [symengine-wheels](https://github.com/symengine/symengine-wheels/releases). diff --git a/appveyor.yml b/appveyor.yml index 30da13f3a..ce1c487ce 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,51 +1,59 @@ version: '{build}' -# Uncomment this to enable the fast build environment if your account does not -# support it automatically: -#os: Visual Studio 2015 RC +image: "Visual Studio 2019" environment: global: PLATFORMTOOLSET: "v140" matrix: + - BUILD_TYPE: "Release" + COMPILER: MSVC15 + PLATFORM: "Win32" + PYTHON_VERSION: 39 + CONDA_INSTALL_LOCN: C:\\Miniconda38-x64 + WITH_MPFR: yes + WITH_MPC: yes - BUILD_TYPE: "Release" COMPILER: MSVC15 PLATFORM: "x64" PYTHON_VERSION: 310-x64 - CONDA_INSTALL_LOCN: C:\\Miniconda36-x64 + CONDA_INSTALL_LOCN: C:\\Miniconda38-x64 WITH_MPFR: yes WITH_MPC: yes - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 - BUILD_TYPE: "Release" COMPILER: MSVC15 PLATFORM: "x64" - PYTHON_VERSION: 38-x64 - CONDA_INSTALL_LOCN: C:\\Miniconda36-x64 - - BUILD_TYPE: "Debug" - COMPILER: MinGW-w64 - PYTHON_VERSION: 37-x64 - WITH_NUMPY: no + PYTHON_VERSION: 312-x64 + CONDA_INSTALL_LOCN: C:\\Miniconda38-x64 - BUILD_TYPE: "Release" - COMPILER: MinGW-w64 - PYTHON_VERSION: 37-x64 - - BUILD_TYPE: "Debug" - COMPILER: MinGW-w64 - PYTHON_VERSION: 37-x64 + COMPILER: MSVC15 + PLATFORM: "x64" + PYTHON_VERSION: 39-x64 WITH_SYMPY: no + CONDA_INSTALL_LOCN: C:\\Miniconda38-x64 - BUILD_TYPE: "Release" COMPILER: MSVC15 - PLATFORM: "Win32" - PYTHON_VERSION: 37 - CONDA_INSTALL_LOCN: C:\\Miniconda36 - WITH_MPFR: yes - WITH_MPC: yes + PLATFORM: "x64" + PYTHON_VERSION: 311-x64 + WITH_NUMPY: no + CONDA_INSTALL_LOCN: C:\\Miniconda38-x64 + #- BUILD_TYPE: "Debug" + # COMPILER: MinGW-w64 + # PYTHON_VERSION: 39-x64 + # WITH_NUMPY: no + #- BUILD_TYPE: "Release" + # COMPILER: MinGW-w64 + # PYTHON_VERSION: 39-x64 + #- BUILD_TYPE: "Debug" + # COMPILER: MinGW-w64 + # PYTHON_VERSION: 39-x64 + # WITH_SYMPY: no - BUILD_TYPE: "Release" COMPILER: MSVC15 PLATFORM: "x64" PYTHON_VERSION: 310-x64 - CONDA_INSTALL_LOCN: C:\\Miniconda36-x64 - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 + CONDA_INSTALL_LOCN: C:\\Miniconda38-x64 WITH_MPFR: yes WITH_MPC: yes WITH_LLVM: yes @@ -53,19 +61,21 @@ environment: install: - set PYTHON_SOURCE_DIR=%CD% - git clone https://github.com/sympy/symengine symengine-cpp +- if [%PLATFORM%]==[Win32] set "CONDA_SUBDIR=win-32" - if [%COMPILER%]==[MSVC15] call %CONDA_INSTALL_LOCN%\Scripts\activate.bat -- if [%COMPILER%]==[MSVC15] conda install --yes --quiet conda python=3.6 -- if [%COMPILER%]==[MSVC15] conda config --add channels conda-forge -- if [%COMPILER%]==[MSVC15] if [%BUILD_TYPE%]==[Debug] conda config --add channels symengine/label/debug -- if [%COMPILER%]==[MSVC15] conda install --yes mpir=3.0.0 vc=14 +- if [%COMPILER%]==[MSVC15] set "CONDA_DEPS=mpir=3.0.0 vc=14" +- if [%COMPILER%]==[MSVC15] if [%WITH_MPFR%]==[yes] set "CONDA_DEPS=%CONDA_DEPS% mpfr=3.1.5" +- if [%COMPILER%]==[MSVC15] if [%WITH_MPC%]==[yes] set "CONDA_DEPS=%CONDA_DEPS% mpc=1.0.3" +- if [%COMPILER%]==[MSVC15] if [%WITH_LLVM%]==[yes] set "CONDA_DEPS=%CONDA_DEPS% llvmdev=4.0" +- if [%COMPILER%]==[MSVC15] set "CONDA_DEPS=%CONDA_DEPS% -c conda-forge" +- if [%COMPILER%]==[MSVC15] if [%BUILD_TYPE%]==[Debug] set "CONDA_DEPS=%CONDA_DEPS% -c symengine/label/debug" +- if [%COMPILER%]==[MSVC15] conda create -n deps --yes %CONDA_DEPS% +- if [%COMPILER%]==[MSVC15] call conda activate deps - if [%COMPILER%]==[MSVC15] echo %CONDA_PREFIX% - if [%COMPILER%]==[MSVC15] echo %PATH% - if [%COMPILER%]==[MSVC15] set "PATH=%PATH%;%CONDA_PREFIX%\\Library\\bin;%CONDA_PREFIX%" - if [%COMPILER%]==[MSVC15] echo %PATH% -- if [%COMPILER%]==[MSVC15] if [%WITH_MPFR%]==[yes] conda install --yes mpfr=3.1.5 -- if [%COMPILER%]==[MSVC15] if [%WITH_MPC%]==[yes] conda install --yes mpc=1.0.3 -- if [%COMPILER%]==[MSVC15] if [%WITH_LLVM%]==[yes] conda install --yes llvmdev=3.9 - if [%COMPILER%]==[MinGW] set "PATH=C:\MinGW\bin;%PATH%" - if [%COMPILER%]==[MinGW] mingw-get update @@ -87,8 +97,7 @@ install: - set "PATH=C:\Python%PYTHON_VERSION%;C:\Python%PYTHON_VERSION%\Scripts;%PATH%" - echo %PATH% -- pip install nose pytest -- pip install --install-option="--no-cython-compile" cython +- pip install nose pytest cython setuptools - if NOT [%WITH_NUMPY%]==[no] pip install numpy - if NOT [%WITH_SYMPY%]==[no] pip install sympy @@ -103,15 +112,16 @@ install: - if [%COMPILER%]==[MinGW] set "CMAKE_GENERATOR=MinGW Makefiles" - if [%COMPILER%]==[MinGW-w64] set "CMAKE_GENERATOR=MinGW Makefiles" -- if [%COMPILER%]==[MSVC15] cmake -DCMAKE_PREFIX_PATH=%CONDA_PREFIX%\Library .. -- if [%COMPILER%]==[MinGW] cmake -DCMAKE_PREFIX_PATH=C:\MinGW -DCMAKE_BUILD_TYPE=%BUILD_TYPE% .. -- if [%COMPILER%]==[MinGW-w64] cmake -DCMAKE_PREFIX_PATH=C:\mingw64 -DCMAKE_BUILD_TYPE=%BUILD_TYPE% .. +- if [%COMPILER%]==[MSVC15] set "CMAKE_ARGS=-DCMAKE_PREFIX_PATH=%CONDA_PREFIX%\\Library" +- if [%COMPILER%]==[MinGW] set "CMAKE_ARGS=-DCMAKE_PREFIX_PATH=C:\MinGW -DCMAKE_BUILD_TYPE=%BUILD_TYPE%" +- if [%COMPILER%]==[MinGW-w64] set "CMAKE_ARGS=-DCMAKE_PREFIX_PATH=C:\mingw64 -DCMAKE_BUILD_TYPE=%BUILD_TYPE%" -- if [%WITH_MPFR%]==[yes] cmake -DWITH_MPFR=yes .. -- if [%WITH_MPC%]==[yes] cmake -DWITH_MPC=yes .. -- if [%WITH_LLVM%]==[yes] cmake -DWITH_LLVM=yes -DMSVC_USE_MT=no .. +- if [%WITH_MPFR%]==[yes] set "CMAKE_ARGS=%CMAKE_ARGS% -DWITH_MPFR=yes" +- if [%WITH_MPC%]==[yes] set "CMAKE_ARGS=%CMAKE_ARGS% -DWITH_MPC=yes" +- if [%WITH_LLVM%]==[yes] set "CMAKE_ARGS=%CMAKE_ARGS% -DWITH_LLVM=yes -DMSVC_USE_MT=no" -- cmake -DBUILD_SHARED_LIBS=yes -DBUILD_TESTS=no -DBUILD_BENCHMARKS=no -DCMAKE_INSTALL_PREFIX=C:\symengine .. +- echo "CMAKE_ARGS=%CMAKE_ARGS%" +- cmake %CMAKE_ARGS% -DBUILD_SHARED_LIBS=yes -DBUILD_TESTS=no -DBUILD_BENCHMARKS=no -DCMAKE_INSTALL_PREFIX=C:\symengine .. - cmake --build . --config %BUILD_TYPE% --target install - cd ../../ diff --git a/bin/install_travis.sh b/bin/install_travis.sh index 581354a06..f63a47479 100644 --- a/bin/install_travis.sh +++ b/bin/install_travis.sh @@ -2,7 +2,7 @@ # symengine's bin/install_travis.sh will install miniconda -export conda_pkgs="python=${PYTHON_VERSION} pip 'cython>=0.29.24' pytest gmp mpfr" +export conda_pkgs="python=${PYTHON_VERSION} pip pytest setuptools gmp mpfr" if [[ "${WITH_NUMPY}" != "no" ]]; then export conda_pkgs="${conda_pkgs} numpy"; @@ -16,6 +16,10 @@ if [[ "${WITH_DOCS}" == "yes" ]]; then export conda_pkgs="${conda_pkgs} sphinx recommonmark"; fi +if [[ "${WITH_FLINT_PY}" == "yes" ]]; then + export conda_pkgs="${conda_pkgs} python-flint"; # python-flint affects sympy, see e.g. sympy/sympy#26645 +fi + if [[ "${WITH_SAGE}" == "yes" ]]; then # This is split to avoid the 10 minute limit conda install -q sagelib=8.1 @@ -23,11 +27,10 @@ if [[ "${WITH_SAGE}" == "yes" ]]; then export conda_pkgs="${conda_pkgs} sage=8.1"; fi -conda install -q ${conda_pkgs} +conda install -q ${conda_pkgs} "cython>=0.29.24" if [[ "${WITH_SYMPY}" != "no" ]]; then pip install sympy; fi -conda clean --all -source activate $our_install_dir; +conda clean --all \ No newline at end of file diff --git a/bin/test_symengine_unix.sh b/bin/test_symengine_unix.sh index 976f305d1..0c62b7d14 100644 --- a/bin/test_symengine_unix.sh +++ b/bin/test_symengine_unix.sh @@ -10,7 +10,7 @@ cd .. # Setup travis for C++ library cd $SOURCE_DIR -source bin/test_symengine_unix.sh +source bin/test_symengine.sh # Setup travis for Python wrappers cd $PYTHON_SOURCE_DIR diff --git a/cmake/FindCython.cmake b/cmake/FindCython.cmake index 318f58e48..beac6c568 100644 --- a/cmake/FindCython.cmake +++ b/cmake/FindCython.cmake @@ -63,26 +63,13 @@ if(NOT CYTHON_INCLUDE_DIRECTORIES) endif(NOT CYTHON_INCLUDE_DIRECTORIES) # Cythonizes the .pyx files into .cpp file (but doesn't compile it) -macro(CYTHON_ADD_MODULE_PYX name) - if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${name}.pxd) - set(DEPENDS ${name}.pyx ${name}.pxd) - else(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${name}.pxd) - set(DEPENDS ${name}.pyx) - endif(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${name}.pxd) +macro(CYTHON_ADD_MODULE_PYX cpp_name pyx_name) # Allow the user to specify dependencies as optional arguments set(DEPENDS ${DEPENDS} ${ARGN}) add_custom_command( - OUTPUT ${name}.cpp + OUTPUT ${cpp_name} COMMAND ${CYTHON_BIN} - ARGS ${CYTHON_FLAGS} -I ${CYTHON_INCLUDE_DIRECTORIES} -o ${name}.cpp ${CMAKE_CURRENT_SOURCE_DIR}/${name}.pyx - DEPENDS ${DEPENDS} - COMMENT "Cythonizing ${name}.pyx") + ARGS ${CYTHON_FLAGS} -I ${CYTHON_INCLUDE_DIRECTORIES} -o ${cpp_name} ${pyx_name} + DEPENDS ${DEPENDS} ${pyx_name} + COMMENT "Cythonizing ${pyx_name}") endmacro(CYTHON_ADD_MODULE_PYX) - -# Cythonizes and compiles a .pyx file -macro(CYTHON_ADD_MODULE name) - CYTHON_ADD_MODULE_PYX(${name}) - # We need Python for this: - find_package(Python REQUIRED) - add_python_library(${name} ${name}.cpp ${ARGN}) -endmacro(CYTHON_ADD_MODULE) diff --git a/cmake/FindPython.cmake b/cmake/FindPython.cmake index 52539cb79..c1f6c4396 100644 --- a/cmake/FindPython.cmake +++ b/cmake/FindPython.cmake @@ -1,7 +1,7 @@ set(PYTHON_BIN python CACHE STRING "Python executable name") execute_process( - COMMAND ${PYTHON_BIN} -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())" + COMMAND ${PYTHON_BIN} -c "from sysconfig import get_paths; print(get_paths()['include'])" OUTPUT_VARIABLE PYTHON_SYS_PATH ) string(STRIP ${PYTHON_SYS_PATH} PYTHON_SYS_PATH) @@ -16,32 +16,42 @@ set(PYTHON_INSTALL_HEADER_PATH ${PYTHON_INCLUDE_PATH}/symengine CACHE BOOL "Python install headers path") execute_process( - COMMAND ${PYTHON_BIN} -c "from distutils.sysconfig import get_config_var; print(get_config_var('LIBDIR'))" + COMMAND ${PYTHON_BIN} -c "from sysconfig import get_config_var; print(get_config_var('LIBDIR'))" OUTPUT_VARIABLE PYTHON_LIB_PATH ) string(STRIP ${PYTHON_LIB_PATH} PYTHON_LIB_PATH) execute_process( - COMMAND ${PYTHON_BIN} -c "import sys; print(sys.prefix)" - OUTPUT_VARIABLE PYTHON_PREFIX_PATH - ) + COMMAND ${PYTHON_BIN} -c "import sys; print(sys.prefix)" + OUTPUT_VARIABLE PYTHON_PREFIX_PATH +) string(STRIP ${PYTHON_PREFIX_PATH} PYTHON_PREFIX_PATH) execute_process( - COMMAND ${PYTHON_BIN} -c "import sys; print('%s.%s' % sys.version_info[:2])" + COMMAND ${PYTHON_BIN} -c "import sys; print('%s.%s' % sys.version_info[:2])" OUTPUT_VARIABLE PYTHON_VERSION - ) +) string(STRIP ${PYTHON_VERSION} PYTHON_VERSION) message(STATUS "Python version: ${PYTHON_VERSION}") string(REPLACE "." "" PYTHON_VERSION_WITHOUT_DOTS ${PYTHON_VERSION}) +execute_process( + COMMAND ${PYTHON_BIN} -c "import sysconfig;print(bool(sysconfig.get_config_var('Py_GIL_DISABLED')))" + OUTPUT_VARIABLE PY_GIL_DISABLED +) +string(STRIP ${PY_GIL_DISABLED} PY_GIL_DISABLED) + +if ("${PY_GIL_DISABLED}" STREQUAL "True") + set (PY_THREAD "t") +endif() + if (${CMAKE_SYSTEM_NAME} STREQUAL "Windows") FIND_LIBRARY(PYTHON_LIBRARY NAMES - python${PYTHON_VERSION} + python${PYTHON_VERSION}${PY_THREAD} python${PYTHON_VERSION}m - python${PYTHON_VERSION_WITHOUT_DOTS} + python${PYTHON_VERSION_WITHOUT_DOTS}${PY_THREAD} PATHS ${PYTHON_LIB_PATH} ${PYTHON_PREFIX_PATH}/lib ${PYTHON_PREFIX_PATH}/libs PATH_SUFFIXES ${CMAKE_LIBRARY_ARCHITECTURE} NO_DEFAULT_PATH @@ -50,9 +60,9 @@ if (${CMAKE_SYSTEM_NAME} STREQUAL "Windows") endif() execute_process( - COMMAND ${PYTHON_BIN} -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())" - OUTPUT_VARIABLE PYTHON_INSTALL_PATH_tmp - ) + COMMAND ${PYTHON_BIN} -c "from sysconfig import get_paths; print(get_paths()['platlib'])" + OUTPUT_VARIABLE PYTHON_INSTALL_PATH_tmp +) string(STRIP ${PYTHON_INSTALL_PATH_tmp} PYTHON_INSTALL_PATH_tmp) set(PYTHON_INSTALL_PATH ${PYTHON_INSTALL_PATH_tmp} CACHE BOOL "Python install path") @@ -120,7 +130,7 @@ macro(ADD_PYTHON_LIBRARY name) configure_file(${CMAKE_SOURCE_DIR}/cmake/version_script.txt ${CMAKE_CURRENT_BINARY_DIR}/version_script_${name}.txt @ONLY) set_property(TARGET ${name} APPEND_STRING PROPERTY - LINK_FLAGS " -Wl,--version-script=${CMAKE_CURRENT_BINARY_DIR}/version_script_${name}.txt") + LINK_FLAGS " \"-Wl,--version-script=${CMAKE_CURRENT_BINARY_DIR}/version_script_${name}.txt\"") ELSE() add_library(${name} SHARED ${ARGN}) ENDIF() @@ -129,5 +139,9 @@ macro(ADD_PYTHON_LIBRARY name) IF(${CMAKE_SYSTEM_NAME} STREQUAL "Windows") target_link_libraries(${name} ${PYTHON_LIBRARY}) set_target_properties(${name} PROPERTIES SUFFIX ".pyd") + IF("${PY_GIL_DISABLED}" STREQUAL "True") + target_compile_definitions(${name} PRIVATE Py_GIL_DISABLED=1) + ENDIF() ENDIF() + endmacro(ADD_PYTHON_LIBRARY) diff --git a/cmake/cython_test.pyx b/cmake/cython_test.pyx index 22cdb17c6..e97be0b43 100644 --- a/cmake/cython_test.pyx +++ b/cmake/cython_test.pyx @@ -1,6 +1,3 @@ -# Test that numpy works in Cython: -from numpy cimport ndarray - # Test that libcpp module is present: from libcpp.vector cimport vector from libcpp.string cimport string @@ -78,8 +75,8 @@ cdef extern from "" namespace "SymEngine": string get_name() nogil cdef extern from "" namespace "SymEngine": - cdef RCP[Basic] add(RCP[Basic] &a, RCP[Basic] &b) nogil except+ - cdef RCP[Basic] sub(RCP[Basic] &a, RCP[Basic] &b) nogil except+ + cdef RCP[Basic] add(RCP[Basic] &a, RCP[Basic] &b) nogil except + + cdef RCP[Basic] sub(RCP[Basic] &a, RCP[Basic] &b) nogil except + cdef cppclass Add(Basic): void as_two_terms(const Ptr[RCP[Basic]] &a, const Ptr[RCP[Basic]] &b) diff --git a/cmake/get_suffix.py b/cmake/get_suffix.py index 8fc5b1050..42470fce5 100644 --- a/cmake/get_suffix.py +++ b/cmake/get_suffix.py @@ -1,4 +1,4 @@ -from distutils.sysconfig import get_config_var +from sysconfig import get_config_var extsuffix = get_config_var('EXT_SUFFIX') if extsuffix is None: print("") diff --git a/cmake/preprocess.py b/cmake/preprocess.py new file mode 100644 index 000000000..a99d24898 --- /dev/null +++ b/cmake/preprocess.py @@ -0,0 +1,38 @@ +import sys + + +def main(input_name, output_name, replacements): + replacements = dict((item.split("=")[0], item.split("=")[1] == "True") for item in replacements) + with open(input_name, "r") as inp: + text = inp.readlines() + + new_text = [] + in_cond = [True] + nspaces = [0] + for i, line in enumerate(text): + if line.strip().startswith("IF"): + s = len(line) - len(line.lstrip()) + while s <= nspaces[-1] and len(in_cond) > 1: + in_cond = in_cond[:-1] + nspaces = nspaces[:-1] + + cond = line.lstrip()[3:-2] + in_cond.append(replacements[cond]) + nspaces.append(s) + elif line.strip().startswith("ELSE"): + in_cond[-1] = not in_cond[-1] and in_cond[-2] + + if len(line) > 1 and not line.strip().startswith(("IF", "ELSE")): + while len(in_cond) > 1 and (len(line) <= nspaces[-1] or not line.startswith(" "*nspaces[-1]) or line[nspaces[-1]] != " "): + in_cond = in_cond[:-1] + nspaces = nspaces[:-1] + if len(line) == 1: + new_text.append(line) + elif in_cond[-1] and not line.strip().startswith(("IF", "ELSE")): + new_text.append(line[4*(len(in_cond) - 1):]) + + with open(output_name, "w") as out: + out.writelines(new_text) + +if __name__ == "__main__": + main(sys.argv[1], sys.argv[2], sys.argv[3:]) diff --git a/setup.py b/setup.py index 88f2d1c7b..23d948ef6 100644 --- a/setup.py +++ b/setup.py @@ -5,8 +5,8 @@ import platform # Make sure the system has the right Python version. -if sys.version_info[:2] < (3, 7): - print("SymEngine requires Python 3.7 or newer. " +if sys.version_info[:2] < (3, 9): + print("SymEngine requires Python 3.9 or newer. " "Python %d.%d detected" % sys.version_info[:2]) sys.exit(-1) @@ -117,7 +117,7 @@ def cmake_build(self): cmake_cmd = ["cmake", source_dir, "-DCMAKE_BUILD_TYPE=" + cmake_build_type[0], - "-DSYMENGINE_INSTALL_PY_FILES=OFF", + "-DSYMENGINE_INSTALL_PY_FILES=ON", ] cmake_cmd.extend(process_opts(cmake_opts)) if not path.exists(path.join(build_dir, "CMakeCache.txt")): @@ -222,17 +222,17 @@ def finalize_options(self): ''' setup(name="symengine", - version="0.10.0", + version="0.14.1", description="Python library providing wrappers to SymEngine", - setup_requires=['cython>=0.29.24'], + setup_requires=['cython>=0.29.24', 'setuptools'], long_description=long_description, author="SymEngine development team", author_email="symengine@googlegroups.com", license="MIT", url="https://github.com/symengine/symengine.py", - python_requires='>=3.7,<4', + python_requires='>=3.9,<4', zip_safe=False, - packages=['symengine', 'symengine.lib', 'symengine.tests'], + packages=[], cmdclass = cmdclass, classifiers=[ 'License :: OSI Approved :: MIT License', @@ -241,9 +241,10 @@ def finalize_options(self): 'Topic :: Scientific/Engineering', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Scientific/Engineering :: Physics', - 'Programming Language :: Python :: 3.7', - 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', + 'Programming Language :: Python :: 3.11', + 'Programming Language :: Python :: 3.12', + 'Programming Language :: Python :: 3.13', ] ) diff --git a/symengine/CMakeLists.txt b/symengine/CMakeLists.txt index 907e6f648..bedec397d 100644 --- a/symengine/CMakeLists.txt +++ b/symengine/CMakeLists.txt @@ -1,10 +1,17 @@ add_subdirectory(lib) if (SYMENGINE_INSTALL_PY_FILES) - add_subdirectory(tests) - - set(PY_PATH ${PYTHON_INSTALL_PATH}/symengine) - install(FILES __init__.py utilities.py sympy_compat.py functions.py printing.py - DESTINATION ${PY_PATH} - ) + add_subdirectory(tests) + set(PY_PATH ${PYTHON_INSTALL_PATH}/symengine) + install( + FILES + __init__.py + functions.py + printing.py + sympy_compat.py + test_utilities.py + utilities.py + DESTINATION + ${PY_PATH} +) endif () diff --git a/symengine/__init__.py b/symengine/__init__.py index 19c0d69be..e9545baf6 100644 --- a/symengine/__init__.py +++ b/symengine/__init__.py @@ -1,7 +1,7 @@ import os import sys -if sys.version_info >= (3, 8, 0) and sys.platform == 'win32' \ +if sys.platform == 'win32' \ and 'SYMENGINE_PY_ADD_PATH_TO_SEARCH_DIRS' in os.environ: for directory in os.environ['PATH'].split(';'): if os.path.isdir(directory): @@ -26,7 +26,7 @@ Gt, Lt, And, Or, Not, Nand, Nor, Xor, Xnor, perfect_power, integer_nthroot, isprime, sqrt_mod, Expr, cse, count_ops, ccode, Piecewise, Contains, Interval, FiniteSet, linsolve, - FunctionSymbol as AppliedUndef, + FunctionSymbol, golden_ratio as GoldenRatio, catalan as Catalan, eulergamma as EulerGamma, @@ -37,6 +37,7 @@ from .printing import init_printing +AppliedUndef = FunctionSymbol # an alias EmptySet = wrapper.S.EmptySet UniversalSet = wrapper.S.UniversalSet Reals = wrapper.S.Reals @@ -62,7 +63,7 @@ def __getattr__(name): raise AttributeError(f"module 'symengine' has no attribute '{name}'") -__version__ = "0.10.0" +__version__ = "0.14.1" # To not expose internals diff --git a/symengine/lib/CMakeLists.txt b/symengine/lib/CMakeLists.txt index bf5cc9f80..7683d4aa8 100644 --- a/symengine/lib/CMakeLists.txt +++ b/symengine/lib/CMakeLists.txt @@ -1,13 +1,47 @@ set(SRC - symengine_wrapper.cpp + ${CMAKE_CURRENT_BINARY_DIR}/symengine_wrapper.cpp pywrapper.cpp ) -configure_file(config.pxi.in config.pxi) +include_directories(BEFORE ${CMAKE_CURRENT_BINARY_DIR}) -include_directories(BEFORE ${python_wrapper_BINARY_DIR}/symengine/lib) +add_custom_command( + OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/symengine_wrapper.pxd + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/symengine_wrapper.in.pxd + ${PROJECT_SOURCE_DIR}/cmake/preprocess.py + COMMAND ${PYTHON_BIN} ${PROJECT_SOURCE_DIR}/cmake/preprocess.py + ${CMAKE_CURRENT_SOURCE_DIR}/symengine_wrapper.in.pxd + ${CMAKE_CURRENT_BINARY_DIR}/symengine_wrapper.pxd + HAVE_SYMENGINE_MPFR=${HAVE_SYMENGINE_MPFR} + HAVE_SYMENGINE_MPC=${HAVE_SYMENGINE_MPC} + HAVE_SYMENGINE_PIRANHA=${HAVE_SYMENGINE_PIRANHA} + HAVE_SYMENGINE_FLINT=${HAVE_SYMENGINE_FLINT} + HAVE_SYMENGINE_LLVM=${HAVE_SYMENGINE_LLVM} + HAVE_SYMENGINE_LLVM_LONG_DOUBLE=${HAVE_SYMENGINE_LLVM_LONG_DOUBLE} + COMMENT "Preprocessing symengine_wrapper.in.pxd" +) +add_custom_command( + OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/symengine_wrapper.pyx + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/symengine_wrapper.in.pyx + ${CMAKE_CURRENT_SOURCE_DIR}/symengine_wrapper.in.pxd + ${CMAKE_CURRENT_BINARY_DIR}/symengine_wrapper.pxd + ${PROJECT_SOURCE_DIR}/cmake/preprocess.py + COMMAND ${PYTHON_BIN} ${PROJECT_SOURCE_DIR}/cmake/preprocess.py + ${CMAKE_CURRENT_SOURCE_DIR}/symengine_wrapper.in.pyx + ${CMAKE_CURRENT_BINARY_DIR}/symengine_wrapper.pyx + HAVE_SYMENGINE_MPFR=${HAVE_SYMENGINE_MPFR} + HAVE_SYMENGINE_MPC=${HAVE_SYMENGINE_MPC} + HAVE_SYMENGINE_PIRANHA=${HAVE_SYMENGINE_PIRANHA} + HAVE_SYMENGINE_FLINT=${HAVE_SYMENGINE_FLINT} + HAVE_SYMENGINE_LLVM=${HAVE_SYMENGINE_LLVM} + HAVE_SYMENGINE_LLVM_LONG_DOUBLE=${HAVE_SYMENGINE_LLVM_LONG_DOUBLE} + COMMENT "Preprocessing symengine_wrapper.in.pyx" +) -cython_add_module_pyx(symengine_wrapper symengine.pxd) +cython_add_module_pyx(symengine_wrapper.cpp + ${CMAKE_CURRENT_BINARY_DIR}/symengine_wrapper.pyx + ${CMAKE_CURRENT_BINARY_DIR}/symengine_wrapper.pxd + ${CMAKE_CURRENT_SOURCE_DIR}/symengine.pxd) add_python_library(symengine_wrapper ${SRC}) target_link_libraries(symengine_wrapper ${SYMENGINE_LIBRARIES}) if (CMAKE_CXX_COMPILER_ID MATCHES GNU|Clang) @@ -18,10 +52,6 @@ if (CMAKE_CXX_COMPILER_ID MATCHES GNU|Clang) ) endif() -add_custom_target(cython - COMMAND cython symengine_wrapper.pyx - ) - set(PY_PATH ${PYTHON_INSTALL_PATH}/symengine/lib) install(TARGETS symengine_wrapper RUNTIME DESTINATION ${PY_PATH} @@ -29,9 +59,8 @@ install(TARGETS symengine_wrapper LIBRARY DESTINATION ${PY_PATH} ) install(FILES - ${CMAKE_CURRENT_BINARY_DIR}/config.pxi symengine.pxd - symengine_wrapper.pxd + ${CMAKE_CURRENT_BINARY_DIR}/symengine_wrapper.pxd pywrapper.h DESTINATION ${PY_PATH} ) diff --git a/symengine/lib/config.pxi.in b/symengine/lib/config.pxi.in deleted file mode 100644 index 26a33012e..000000000 --- a/symengine/lib/config.pxi.in +++ /dev/null @@ -1,6 +0,0 @@ -DEF HAVE_SYMENGINE_MPFR = ${HAVE_SYMENGINE_MPFR} -DEF HAVE_SYMENGINE_MPC = ${HAVE_SYMENGINE_MPC} -DEF HAVE_SYMENGINE_PIRANHA = ${HAVE_SYMENGINE_PIRANHA} -DEF HAVE_SYMENGINE_FLINT = ${HAVE_SYMENGINE_FLINT} -DEF HAVE_SYMENGINE_LLVM = ${HAVE_SYMENGINE_LLVM} -DEF HAVE_SYMENGINE_LLVM_LONG_DOUBLE = ${HAVE_SYMENGINE_LLVM_LONG_DOUBLE} diff --git a/symengine/lib/pywrapper.cpp b/symengine/lib/pywrapper.cpp index 4f45a0b7d..5ab5e5866 100644 --- a/symengine/lib/pywrapper.cpp +++ b/symengine/lib/pywrapper.cpp @@ -292,7 +292,7 @@ PyObject* pickle_loads(const std::string &pickle_str) { return obj; } -RCP load_basic(cereal::PortableBinaryInputArchive &ar, RCP &) +RCP load_basic(RCPBasicAwareInputArchive &ar, RCP &) { bool is_pysymbol; bool store_pickle; @@ -324,7 +324,7 @@ std::string pickle_dumps(const PyObject * obj) { return std::string(buffer, size); } -void save_basic(cereal::PortableBinaryOutputArchive &ar, const Symbol &b) +void save_basic(RCPBasicAwareOutputArchive &ar, const Symbol &b) { bool is_pysymbol = is_a_sub(b); ar(is_pysymbol); @@ -344,7 +344,7 @@ std::string wrapper_dumps(const Basic &x) std::ostringstream oss; unsigned short major = SYMENGINE_MAJOR_VERSION; unsigned short minor = SYMENGINE_MINOR_VERSION; - cereal::PortableBinaryOutputArchive{oss}(major, minor, + RCPBasicAwareOutputArchive{oss}(major, minor, x.rcp_from_this()); return oss.str(); } @@ -354,7 +354,7 @@ RCP wrapper_loads(const std::string &serialized) unsigned short major, minor; RCP obj; std::istringstream iss(serialized); - cereal::PortableBinaryInputArchive iarchive{iss}; + RCPBasicAwareInputArchive iarchive{iss}; iarchive(major, minor); if (major != SYMENGINE_MAJOR_VERSION or minor != SYMENGINE_MINOR_VERSION) { throw SerializationError(StreamFmt() diff --git a/symengine/lib/symengine.pxd b/symengine/lib/symengine.pxd index 449ffc01b..65b3456aa 100644 --- a/symengine/lib/symengine.pxd +++ b/symengine/lib/symengine.pxd @@ -4,8 +4,21 @@ from libcpp.map cimport map from libcpp.vector cimport vector from cpython.ref cimport PyObject from libcpp.pair cimport pair +from libcpp.set cimport set +from libcpp.unordered_map cimport unordered_map -include "config.pxi" +cdef extern from "" namespace "std": + # Cython's libcpp.set does not support multiset in 0.29.x + cdef cppclass multiset[T]: + cppclass iterator: + T& operator*() + iterator operator++() nogil + iterator operator--() nogil + bint operator==(iterator) nogil + bint operator!=(iterator) nogil + iterator begin() nogil + iterator end() nogil + iterator insert(T&) nogil cdef extern from 'symengine/mp_class.h' namespace "SymEngine": ctypedef unsigned long mp_limb_t @@ -31,94 +44,6 @@ cdef extern from 'symengine/mp_class.h' namespace "SymEngine": rational_class(mpq_t) const mpq_t get_mpq_t(const rational_class &a) -cdef extern from "" namespace "std": -# Cython's libcpp.set does not support two template arguments to set. -# Methods to declare and iterate a set with a custom compare are given here - cdef cppclass set[T, U]: - cppclass iterator: - T& operator*() - iterator operator++() nogil - iterator operator--() nogil - bint operator==(iterator) nogil - bint operator!=(iterator) nogil - iterator begin() nogil - iterator end() nogil - iterator insert(T&) nogil - - cdef cppclass multiset[T, U]: - cppclass iterator: - T& operator*() - iterator operator++() nogil - iterator operator--() nogil - bint operator==(iterator) nogil - bint operator!=(iterator) nogil - iterator begin() nogil - iterator end() nogil - iterator insert(T&) nogil - -cdef extern from "" namespace "std" nogil: - cdef cppclass unordered_map[T, U]: - cppclass iterator: - pair[T, U]& operator*() - iterator operator++() - iterator operator--() - bint operator==(iterator) - bint operator!=(iterator) - cppclass reverse_iterator: - pair[T, U]& operator*() - iterator operator++() - iterator operator--() - bint operator==(reverse_iterator) - bint operator!=(reverse_iterator) - cppclass const_iterator(iterator): - pass - cppclass const_reverse_iterator(reverse_iterator): - pass - unordered_map() except + - unordered_map(unordered_map&) except + - #unordered_map(key_compare&) - U& operator[](T&) - #unordered_map& operator=(unordered_map&) - bint operator==(unordered_map&, unordered_map&) - bint operator!=(unordered_map&, unordered_map&) - bint operator<(unordered_map&, unordered_map&) - bint operator>(unordered_map&, unordered_map&) - bint operator<=(unordered_map&, unordered_map&) - bint operator>=(unordered_map&, unordered_map&) - U& at(T&) - iterator begin() - const_iterator const_begin "begin"() - void clear() - size_t count(T&) - bint empty() - iterator end() - const_iterator const_end "end"() - pair[iterator, iterator] equal_range(T&) - #pair[const_iterator, const_iterator] equal_range(key_type&) - void erase(iterator) - void erase(iterator, iterator) - size_t erase(T&) - iterator find(T&) - const_iterator const_find "find"(T&) - pair[iterator, bint] insert(pair[T, U]) # XXX pair[T,U]& - iterator insert(iterator, pair[T, U]) # XXX pair[T,U]& - #void insert(input_iterator, input_iterator) - #key_compare key_comp() - iterator lower_bound(T&) - const_iterator const_lower_bound "lower_bound"(T&) - size_t max_size() - reverse_iterator rbegin() - const_reverse_iterator const_rbegin "rbegin"() - reverse_iterator rend() - const_reverse_iterator const_rend "rend"() - size_t size() - void swap(unordered_map&) - iterator upper_bound(T&) - const_iterator const_upper_bound "upper_bound"(T&) - #value_compare value_comp() - void max_load_factor(float) - float max_load_factor() - cdef extern from "" namespace "SymEngine": cdef enum ENull: null @@ -136,7 +61,12 @@ cdef extern from "" namespace "SymEngine": cdef extern from "" namespace "SymEngine": ctypedef Basic const_Basic "const SymEngine::Basic" - ctypedef RCP[const Basic] rcp_const_basic "SymEngine::RCP" + # RCP[const_Basic] instead of RCP[const Basic] is because of https://github.com/cython/cython/issues/5478 + ctypedef RCP[const_Basic] rcp_const_basic "SymEngine::RCP" + #cdef cppclass rcp_const_basic "SymEngine::RCP": + # Basic& operator*() nogil + # void reset() nogil except + + # pass # Cython has broken support for the following: # ctypedef map[rcp_const_basic, rcp_const_basic] map_basic_basic # So instead we replicate the map features we need here @@ -178,8 +108,9 @@ cdef extern from "" namespace "SymEngine": ctypedef map[RCP[Integer], unsigned] map_integer_uint "SymEngine::map_integer_uint" cdef struct RCPIntegerKeyLess cdef struct RCPBasicKeyLess - ctypedef set[rcp_const_basic, RCPBasicKeyLess] set_basic "SymEngine::set_basic" - ctypedef multiset[rcp_const_basic, RCPBasicKeyLess] multiset_basic "SymEngine::multiset_basic" + ctypedef set[rcp_const_basic] set_basic "SymEngine::set_basic" + ctypedef multiset[rcp_const_basic] multiset_basic "SymEngine::multiset_basic" + cdef cppclass Basic: string __str__() nogil except + unsigned int hash() nogil except + @@ -229,105 +160,17 @@ cdef extern from "" namespace "SymEngine": Ptr[RCP[Basic]] outArg(rcp_const_basic &arg) nogil Ptr[RCP[Integer]] outArg_Integer "SymEngine::outArg>"(RCP[const Integer] &arg) nogil - bool is_a_Add "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Mul "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Pow "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Integer "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Rational "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Complex "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Symbol "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Dummy "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Constant "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Infty "SymEngine::is_a"(const Basic &b) nogil - bool is_a_NaN "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Sin "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Cos "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Tan "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Cot "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Csc "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Sec "SymEngine::is_a"(const Basic &b) nogil - bool is_a_ASin "SymEngine::is_a"(const Basic &b) nogil - bool is_a_ACos "SymEngine::is_a"(const Basic &b) nogil - bool is_a_ATan "SymEngine::is_a"(const Basic &b) nogil - bool is_a_ACot "SymEngine::is_a"(const Basic &b) nogil - bool is_a_ACsc "SymEngine::is_a"(const Basic &b) nogil - bool is_a_ASec "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Sinh "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Cosh "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Tanh "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Coth "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Csch "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Sech "SymEngine::is_a"(const Basic &b) nogil - bool is_a_ASinh "SymEngine::is_a"(const Basic &b) nogil - bool is_a_ACosh "SymEngine::is_a"(const Basic &b) nogil - bool is_a_ATanh "SymEngine::is_a"(const Basic &b) nogil - bool is_a_ACoth "SymEngine::is_a"(const Basic &b) nogil - bool is_a_ACsch "SymEngine::is_a"(const Basic &b) nogil - bool is_a_ASech "SymEngine::is_a"(const Basic &b) nogil - bool is_a_FunctionSymbol "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Abs "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Max "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Min "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Gamma "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Derivative "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Subs "SymEngine::is_a"(const Basic &b) nogil - bool is_a_PyFunction "SymEngine::is_a"(const Basic &b) nogil - bool is_a_RealDouble "SymEngine::is_a"(const Basic &b) nogil - bool is_a_ComplexDouble "SymEngine::is_a"(const Basic &b) nogil - bool is_a_RealMPFR "SymEngine::is_a"(const Basic &b) nogil - bool is_a_ComplexMPC "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Log "SymEngine::is_a"(const Basic &b) nogil - bool is_a_BooleanAtom "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Equality "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Unequality "SymEngine::is_a"(const Basic &b) nogil - bool is_a_LessThan "SymEngine::is_a"(const Basic &b) nogil - bool is_a_StrictLessThan "SymEngine::is_a"(const Basic &b) nogil - bool is_a_PyNumber "SymEngine::is_a"(const Basic &b) nogil - bool is_a_ATan2 "SymEngine::is_a"(const Basic &b) nogil - bool is_a_LambertW "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Zeta "SymEngine::is_a"(const Basic &b) nogil - bool is_a_DirichletEta "SymEngine::is_a"(const Basic &b) nogil - bool is_a_KroneckerDelta "SymEngine::is_a"(const Basic &b) nogil - bool is_a_LeviCivita "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Erf "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Erfc "SymEngine::is_a"(const Basic &b) nogil - bool is_a_LowerGamma "SymEngine::is_a"(const Basic &b) nogil - bool is_a_UpperGamma "SymEngine::is_a"(const Basic &b) nogil - bool is_a_LogGamma "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Beta "SymEngine::is_a"(const Basic &b) nogil - bool is_a_PolyGamma "SymEngine::is_a"(const Basic &b) nogil - bool is_a_PySymbol "SymEngine::is_a_sub"(const Basic &b) nogil - bool is_a_Sign "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Floor "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Ceiling "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Conjugate "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Interval "SymEngine::is_a"(const Basic &b) nogil - bool is_a_EmptySet "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Reals "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Rationals "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Integers "SymEngine::is_a"(const Basic &b) nogil - bool is_a_UniversalSet "SymEngine::is_a"(const Basic &b) nogil - bool is_a_FiniteSet "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Union "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Complement "SymEngine::is_a"(const Basic &b) nogil - bool is_a_ConditionSet "SymEngine::is_a"(const Basic &b) nogil - bool is_a_ImageSet "SymEngine::is_a"(const Basic &b) nogil - bool is_a_UnevaluatedExpr "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Piecewise "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Contains "SymEngine::is_a"(const Basic &b) nogil - bool is_a_And "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Not "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Or "SymEngine::is_a"(const Basic &b) nogil - bool is_a_Xor "SymEngine::is_a"(const Basic &b) nogil + bool is_a[T] (const Basic &b) nogil + bool is_a_sub[T] (const Basic &b) nogil rcp_const_basic expand(rcp_const_basic &o, bool deep) nogil except + void as_numer_denom(rcp_const_basic &x, const Ptr[RCP[Basic]] &numer, const Ptr[RCP[Basic]] &denom) nogil void as_real_imag(rcp_const_basic &x, const Ptr[RCP[Basic]] &real, const Ptr[RCP[Basic]] &imag) nogil void cse(vec_pair &replacements, vec_basic &reduced_exprs, const vec_basic &exprs) nogil except + cdef extern from "" namespace "SymEngine": - rcp_const_basic msubs (rcp_const_basic &x, const map_basic_basic &x) nogil - rcp_const_basic ssubs (rcp_const_basic &x, const map_basic_basic &x) nogil - rcp_const_basic xreplace (rcp_const_basic &x, const map_basic_basic &x) nogil + rcp_const_basic msubs (rcp_const_basic &x, const map_basic_basic &x) nogil except + + rcp_const_basic ssubs (rcp_const_basic &x, const map_basic_basic &x) nogil except + + rcp_const_basic xreplace (rcp_const_basic &x, const map_basic_basic &x) nogil except + cdef extern from "" namespace "SymEngine": rcp_const_basic diff "SymEngine::sdiff"(rcp_const_basic &arg, rcp_const_basic &x) nogil except + @@ -443,9 +286,9 @@ cdef extern from "" namespace "SymEngine": pass cdef extern from "" namespace "SymEngine": - cdef rcp_const_basic add(rcp_const_basic &a, rcp_const_basic &b) nogil except+ - cdef rcp_const_basic sub(rcp_const_basic &a, rcp_const_basic &b) nogil except+ - cdef rcp_const_basic add(const vec_basic &a) nogil except+ + cdef rcp_const_basic add(rcp_const_basic &a, rcp_const_basic &b) nogil except + + cdef rcp_const_basic sub(rcp_const_basic &a, rcp_const_basic &b) nogil except + + cdef rcp_const_basic add(const vec_basic &a) nogil except + cdef cppclass Add(Basic): void as_two_terms(const Ptr[RCP[Basic]] &a, const Ptr[RCP[Basic]] &b) @@ -453,21 +296,21 @@ cdef extern from "" namespace "SymEngine": const umap_basic_num &get_dict() cdef extern from "" namespace "SymEngine": - cdef rcp_const_basic mul(rcp_const_basic &a, rcp_const_basic &b) nogil except+ - cdef rcp_const_basic div(rcp_const_basic &a, rcp_const_basic &b) nogil except+ - cdef rcp_const_basic neg(rcp_const_basic &a) nogil except+ - cdef rcp_const_basic mul(const vec_basic &a) nogil except+ + cdef rcp_const_basic mul(rcp_const_basic &a, rcp_const_basic &b) nogil except + + cdef rcp_const_basic div(rcp_const_basic &a, rcp_const_basic &b) nogil except + + cdef rcp_const_basic neg(rcp_const_basic &a) nogil except + + cdef rcp_const_basic mul(const vec_basic &a) nogil except + cdef cppclass Mul(Basic): void as_two_terms(const Ptr[RCP[Basic]] &a, const Ptr[RCP[Basic]] &b) RCP[const Number] get_coef() const map_basic_basic &get_dict() - cdef RCP[const Mul] mul_from_dict "SymEngine::Mul::from_dict"(RCP[const Number] coef, map_basic_basic &&d) nogil + cdef RCP[const Mul] mul_from_dict "SymEngine::Mul::from_dict"(RCP[const Number] coef, map_basic_basic &d) nogil cdef extern from "" namespace "SymEngine": - cdef rcp_const_basic pow(rcp_const_basic &a, rcp_const_basic &b) nogil except+ - cdef rcp_const_basic sqrt(rcp_const_basic &x) nogil except+ - cdef rcp_const_basic exp(rcp_const_basic &x) nogil except+ + cdef rcp_const_basic pow(rcp_const_basic &a, rcp_const_basic &b) nogil except + + cdef rcp_const_basic sqrt(rcp_const_basic &x) nogil except + + cdef rcp_const_basic exp(rcp_const_basic &x) nogil except + cdef cppclass Pow(Basic): rcp_const_basic get_base() nogil @@ -491,9 +334,9 @@ cdef extern from "" namespace "SymEngine": void (*dec_ref)(void *), int (*comp)(void *, void *)) nogil rcp_const_basic make_rcp_RealDouble "SymEngine::make_rcp"(double x) nogil rcp_const_basic make_rcp_ComplexDouble "SymEngine::make_rcp"(double complex x) nogil - RCP[const PyModule] make_rcp_PyModule "SymEngine::make_rcp"(PyObject* (*) (rcp_const_basic x), \ - rcp_const_basic (*)(PyObject*), RCP[const Number] (*)(PyObject*, long bits), - rcp_const_basic (*)(PyObject*, rcp_const_basic)) nogil + RCP[const PyModule] make_rcp_PyModule "SymEngine::make_rcp"(PyObject* (*) (rcp_const_basic x) except +, \ + rcp_const_basic (*)(PyObject*) except +, RCP[const Number] (*)(PyObject*, long bits) except +, + rcp_const_basic (*)(PyObject*, rcp_const_basic) except +) except + rcp_const_basic make_rcp_PyNumber "SymEngine::make_rcp"(PyObject*, RCP[const PyModule] x) nogil RCP[const PyFunctionClass] make_rcp_PyFunctionClass "SymEngine::make_rcp"(PyObject* pyobject, string name, RCP[const PyModule] pymodule) nogil @@ -501,58 +344,58 @@ cdef extern from "" namespace "SymEngine": RCP[const PyFunctionClass] pyfunc_class, const PyObject* pyobject) nogil cdef extern from "" namespace "SymEngine": - cdef rcp_const_basic sin(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic cos(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic tan(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic cot(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic csc(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic sec(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic asin(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic acos(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic atan(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic acot(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic acsc(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic asec(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic sinh(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic cosh(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic tanh(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic coth(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic csch(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic sech(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic asinh(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic acosh(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic atanh(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic acoth(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic acsch(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic asech(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic function_symbol(string name, const vec_basic &arg) nogil except+ - cdef rcp_const_basic abs(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic max(const vec_basic &arg) nogil except+ - cdef rcp_const_basic min(const vec_basic &arg) nogil except+ - cdef rcp_const_basic gamma(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic atan2(rcp_const_basic &num, rcp_const_basic &den) nogil except+ - cdef rcp_const_basic lambertw(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic zeta(rcp_const_basic &s) nogil except+ - cdef rcp_const_basic zeta(rcp_const_basic &s, rcp_const_basic &a) nogil except+ - cdef rcp_const_basic dirichlet_eta(rcp_const_basic &s) nogil except+ - cdef rcp_const_basic kronecker_delta(rcp_const_basic &i, rcp_const_basic &j) nogil except+ - cdef rcp_const_basic levi_civita(const vec_basic &arg) nogil except+ - cdef rcp_const_basic erf(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic erfc(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic lowergamma(rcp_const_basic &s, rcp_const_basic &x) nogil except+ - cdef rcp_const_basic uppergamma(rcp_const_basic &s, rcp_const_basic &x) nogil except+ - cdef rcp_const_basic loggamma(rcp_const_basic &arg) nogil except+ - cdef rcp_const_basic beta(rcp_const_basic &x, rcp_const_basic &y) nogil except+ - cdef rcp_const_basic polygamma(rcp_const_basic &n, rcp_const_basic &x) nogil except+ - cdef rcp_const_basic digamma(rcp_const_basic &x) nogil except+ - cdef rcp_const_basic trigamma(rcp_const_basic &x) nogil except+ - cdef rcp_const_basic sign(rcp_const_basic &x) nogil except+ - cdef rcp_const_basic floor(rcp_const_basic &x) nogil except+ - cdef rcp_const_basic ceiling(rcp_const_basic &x) nogil except+ - cdef rcp_const_basic conjugate(rcp_const_basic &x) nogil except+ - cdef rcp_const_basic log(rcp_const_basic &x) nogil except+ - cdef rcp_const_basic log(rcp_const_basic &x, rcp_const_basic &y) nogil except+ - cdef rcp_const_basic unevaluated_expr(rcp_const_basic &x) nogil except+ + cdef rcp_const_basic sin(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic cos(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic tan(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic cot(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic csc(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic sec(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic asin(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic acos(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic atan(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic acot(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic acsc(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic asec(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic sinh(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic cosh(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic tanh(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic coth(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic csch(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic sech(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic asinh(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic acosh(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic atanh(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic acoth(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic acsch(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic asech(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic function_symbol(string name, const vec_basic &arg) nogil except + + cdef rcp_const_basic abs(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic max(const vec_basic &arg) nogil except + + cdef rcp_const_basic min(const vec_basic &arg) nogil except + + cdef rcp_const_basic gamma(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic atan2(rcp_const_basic &num, rcp_const_basic &den) nogil except + + cdef rcp_const_basic lambertw(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic zeta(rcp_const_basic &s) nogil except + + cdef rcp_const_basic zeta(rcp_const_basic &s, rcp_const_basic &a) nogil except + + cdef rcp_const_basic dirichlet_eta(rcp_const_basic &s) nogil except + + cdef rcp_const_basic kronecker_delta(rcp_const_basic &i, rcp_const_basic &j) nogil except + + cdef rcp_const_basic levi_civita(const vec_basic &arg) nogil except + + cdef rcp_const_basic erf(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic erfc(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic lowergamma(rcp_const_basic &s, rcp_const_basic &x) nogil except + + cdef rcp_const_basic uppergamma(rcp_const_basic &s, rcp_const_basic &x) nogil except + + cdef rcp_const_basic loggamma(rcp_const_basic &arg) nogil except + + cdef rcp_const_basic beta(rcp_const_basic &x, rcp_const_basic &y) nogil except + + cdef rcp_const_basic polygamma(rcp_const_basic &n, rcp_const_basic &x) nogil except + + cdef rcp_const_basic digamma(rcp_const_basic &x) nogil except + + cdef rcp_const_basic trigamma(rcp_const_basic &x) nogil except + + cdef rcp_const_basic sign(rcp_const_basic &x) nogil except + + cdef rcp_const_basic floor(rcp_const_basic &x) nogil except + + cdef rcp_const_basic ceiling(rcp_const_basic &x) nogil except + + cdef rcp_const_basic conjugate(rcp_const_basic &x) nogil except + + cdef rcp_const_basic log(rcp_const_basic &x) nogil except + + cdef rcp_const_basic log(rcp_const_basic &x, rcp_const_basic &y) nogil except + + cdef rcp_const_basic unevaluated_expr(rcp_const_basic &x) nogil except + cdef cppclass Function(Basic): pass @@ -720,71 +563,68 @@ cdef extern from "" namespace "SymEngine": cdef cppclass Conjugate(OneArgFunction): pass + cdef cppclass UnevaluatedExpr(OneArgFunction): + pass + cdef cppclass Log(Function): pass -IF HAVE_SYMENGINE_MPFR: - cdef extern from "mpfr.h": - ctypedef struct __mpfr_struct: - pass - ctypedef __mpfr_struct mpfr_t[1] - ctypedef __mpfr_struct* mpfr_ptr - ctypedef const __mpfr_struct* mpfr_srcptr - ctypedef long mpfr_prec_t - ctypedef enum mpfr_rnd_t: - MPFR_RNDN - MPFR_RNDZ - MPFR_RNDU - MPFR_RNDD - MPFR_RNDA - MPFR_RNDF - MPFR_RNDNA - - cdef extern from "" namespace "SymEngine": - cdef cppclass mpfr_class: - mpfr_class() nogil - mpfr_class(mpfr_prec_t prec) nogil - mpfr_class(string s, mpfr_prec_t prec, unsigned base) nogil - mpfr_class(mpfr_t m) nogil - mpfr_ptr get_mpfr_t() nogil - - cdef cppclass RealMPFR(Number): - RealMPFR(mpfr_class) nogil - mpfr_class as_mpfr() nogil - mpfr_prec_t get_prec() nogil - - RCP[const RealMPFR] real_mpfr(mpfr_class t) nogil -ELSE: - cdef extern from "" namespace "SymEngine": - cdef cppclass RealMPFR(Number): - pass - -IF HAVE_SYMENGINE_MPC: - cdef extern from "mpc.h": - ctypedef struct __mpc_struct: - pass - ctypedef __mpc_struct mpc_t[1] - ctypedef __mpc_struct* mpc_ptr - ctypedef const __mpc_struct* mpc_srcptr - - cdef extern from "" namespace "SymEngine": - cdef cppclass mpc_class: - mpc_class() nogil - mpc_class(mpfr_prec_t prec) nogil - mpc_class(mpc_t m) nogil - mpc_ptr get_mpc_t() nogil - mpc_class(string s, mpfr_prec_t prec, unsigned base) nogil - - cdef cppclass ComplexMPC(ComplexBase): - ComplexMPC(mpc_class) nogil - mpc_class as_mpc() nogil - mpfr_prec_t get_prec() nogil - - RCP[const ComplexMPC] complex_mpc(mpc_class t) nogil -ELSE: - cdef extern from "" namespace "SymEngine": - cdef cppclass ComplexMPC(Number): - pass +cdef extern from "": + # These come from mpfr.h, but don't include mpfr.h to not break + # builds without mpfr + ctypedef struct __mpfr_struct: + pass + ctypedef __mpfr_struct mpfr_t[1] + ctypedef __mpfr_struct* mpfr_ptr + ctypedef const __mpfr_struct* mpfr_srcptr + ctypedef long mpfr_prec_t + ctypedef enum mpfr_rnd_t: + MPFR_RNDN + MPFR_RNDZ + MPFR_RNDU + MPFR_RNDD + MPFR_RNDA + MPFR_RNDF + MPFR_RNDNA + +cdef extern from "" namespace "SymEngine": + cdef cppclass mpfr_class: + mpfr_class() nogil + mpfr_class(mpfr_prec_t prec) nogil + mpfr_class(string s, mpfr_prec_t prec, unsigned base) nogil + mpfr_class(mpfr_t m) nogil + mpfr_ptr get_mpfr_t() nogil + + cdef cppclass RealMPFR(Number): + RealMPFR(mpfr_class) nogil + mpfr_class as_mpfr() nogil + mpfr_prec_t get_prec() nogil + + RCP[const RealMPFR] real_mpfr(mpfr_class t) nogil + +cdef extern from "": + # These come from mpc.h, but don't include mpc.h to not break + # builds without mpc + ctypedef struct __mpc_struct: + pass + ctypedef __mpc_struct mpc_t[1] + ctypedef __mpc_struct* mpc_ptr + ctypedef const __mpc_struct* mpc_srcptr + +cdef extern from "" namespace "SymEngine": + cdef cppclass mpc_class: + mpc_class() nogil + mpc_class(mpfr_prec_t prec) nogil + mpc_class(mpc_t m) nogil + mpc_ptr get_mpc_t() nogil + mpc_class(string s, mpfr_prec_t prec, unsigned base) nogil + + cdef cppclass ComplexMPC(ComplexBase): + ComplexMPC(mpc_class) nogil + mpc_class as_mpc() nogil + mpfr_prec_t get_prec() nogil + + RCP[const ComplexMPC] complex_mpc(mpc_class t) nogil cdef extern from "" namespace "SymEngine": cdef cppclass MatrixBase: @@ -792,7 +632,7 @@ cdef extern from "" namespace "SymEngine": const unsigned ncols() nogil rcp_const_basic get(unsigned i, unsigned j) nogil rcp_const_basic set(unsigned i, unsigned j, rcp_const_basic e) nogil - string __str__() nogil except+ + string __str__() nogil except + bool eq(const MatrixBase &) nogil rcp_const_basic det() nogil void inv(MatrixBase &) @@ -839,7 +679,6 @@ cdef extern from "" namespace "SymEngine": tribool is_positive_definite() nogil tribool is_negative_definite() nogil - bool is_a_DenseMatrix "SymEngine::is_a"(const MatrixBase &b) nogil DenseMatrix* static_cast_DenseMatrix "static_cast"(const MatrixBase *a) void inverse_FFLU "SymEngine::inverse_fraction_free_LU"(const DenseMatrix &A, DenseMatrix &B) nogil except + @@ -930,7 +769,7 @@ cdef extern from "" namespace "SymEngine": unsigned next_prime() nogil cdef extern from "" namespace "SymEngine": - bool has_symbol(const Basic &b, const Symbol &x) nogil except + + bool has_symbol(const Basic &b, const Basic &x) nogil except + rcp_const_basic coeff(const Basic &b, const Basic &x, const Basic &n) nogil except + set_basic free_symbols(const Basic &b) nogil except + set_basic free_symbols(const MatrixBase &b) nogil except + @@ -938,7 +777,7 @@ cdef extern from "" namespace "SymEngine": cdef extern from "" namespace "SymEngine": cdef cppclass Boolean(Basic): - RCP[const Boolean] logical_not() nogil except+ + RCP[const Boolean] logical_not() nogil except + cdef cppclass BooleanAtom(Boolean): bool get_val() nogil cdef cppclass Relational(Boolean): @@ -966,38 +805,28 @@ cdef extern from "" namespace "SymEngine": rcp_const_basic boolTrue rcp_const_basic boolFalse - bool is_a_Relational(const Basic &b) nogil - cdef RCP[const Boolean] Eq(rcp_const_basic &lhs) nogil except+ - cdef RCP[const Boolean] Eq(rcp_const_basic &lhs, rcp_const_basic &rhs) nogil except+ - cdef RCP[const Boolean] Ne(rcp_const_basic &lhs, rcp_const_basic &rhs) nogil except+ - cdef RCP[const Boolean] Ge(rcp_const_basic &lhs, rcp_const_basic &rhs) nogil except+ - cdef RCP[const Boolean] Gt(rcp_const_basic &lhs, rcp_const_basic &rhs) nogil except+ - cdef RCP[const Boolean] Le(rcp_const_basic &lhs, rcp_const_basic &rhs) nogil except+ - cdef RCP[const Boolean] Lt(rcp_const_basic &lhs, rcp_const_basic &rhs) nogil except+ + cdef RCP[const Boolean] Eq(rcp_const_basic &lhs) nogil except + + cdef RCP[const Boolean] Eq(rcp_const_basic &lhs, rcp_const_basic &rhs) nogil except + + cdef RCP[const Boolean] Ne(rcp_const_basic &lhs, rcp_const_basic &rhs) nogil except + + cdef RCP[const Boolean] Ge(rcp_const_basic &lhs, rcp_const_basic &rhs) nogil except + + cdef RCP[const Boolean] Gt(rcp_const_basic &lhs, rcp_const_basic &rhs) nogil except + + cdef RCP[const Boolean] Le(rcp_const_basic &lhs, rcp_const_basic &rhs) nogil except + + cdef RCP[const Boolean] Lt(rcp_const_basic &lhs, rcp_const_basic &rhs) nogil except + ctypedef Boolean const_Boolean "const SymEngine::Boolean" ctypedef vector[pair[rcp_const_basic, RCP[const_Boolean]]] PiecewiseVec; ctypedef vector[RCP[Boolean]] vec_boolean "SymEngine::vec_boolean" - ctypedef set[RCP[Boolean], RCPBasicKeyLess] set_boolean "SymEngine::set_boolean" - cdef RCP[const Boolean] logical_and(set_boolean &s) nogil except+ - cdef RCP[const Boolean] logical_nand(set_boolean &s) nogil except+ - cdef RCP[const Boolean] logical_or(set_boolean &s) nogil except+ - cdef RCP[const Boolean] logical_not(RCP[const Boolean] &s) nogil except+ - cdef RCP[const Boolean] logical_nor(set_boolean &s) nogil except+ - cdef RCP[const Boolean] logical_xor(vec_boolean &s) nogil except+ - cdef RCP[const Boolean] logical_xnor(vec_boolean &s) nogil except+ + ctypedef set[RCP[Boolean]] set_boolean "SymEngine::set_boolean" + cdef RCP[const Boolean] logical_and(set_boolean &s) nogil except + + cdef RCP[const Boolean] logical_nand(set_boolean &s) nogil except + + cdef RCP[const Boolean] logical_or(set_boolean &s) nogil except + + cdef RCP[const Boolean] logical_not(RCP[const Boolean] &s) nogil except + + cdef RCP[const Boolean] logical_nor(set_boolean &s) nogil except + + cdef RCP[const Boolean] logical_xor(vec_boolean &s) nogil except + + cdef RCP[const Boolean] logical_xnor(vec_boolean &s) nogil except + cdef rcp_const_basic piecewise(PiecewiseVec vec) nogil except + cdef RCP[const Boolean] contains(rcp_const_basic &expr, RCP[const Set] &set) nogil -cdef extern from "" namespace "std": - cdef integer_class std_move_mpz "std::move" (integer_class) nogil - IF HAVE_SYMENGINE_MPFR: - cdef mpfr_class std_move_mpfr "std::move" (mpfr_class) nogil - IF HAVE_SYMENGINE_MPC: - cdef mpc_class std_move_mpc "std::move" (mpc_class) nogil - cdef map_basic_basic std_move_map_basic_basic "std::move" (map_basic_basic) nogil - cdef PiecewiseVec std_move_PiecewiseVec "std::move" (PiecewiseVec) nogil - cdef extern from "" namespace "SymEngine": cdef cppclass EvalfDomain: pass @@ -1045,13 +874,11 @@ cdef extern from "" namespace "SymEngine": ctypedef RCP[const SeriesCoeffInterface] rcp_const_seriescoeffinterface "SymEngine::RCP" rcp_const_seriescoeffinterface series "SymEngine::series"(rcp_const_basic &ex, RCP[const Symbol] &var, unsigned int prec) nogil except + -IF HAVE_SYMENGINE_MPFR: - cdef extern from "" namespace "SymEngine": - void eval_mpfr(mpfr_t result, const Basic &b, mpfr_rnd_t rnd) nogil except + +cdef extern from "" namespace "SymEngine": + void eval_mpfr(mpfr_t result, const Basic &b, mpfr_rnd_t rnd) nogil except + -IF HAVE_SYMENGINE_MPC: - cdef extern from "" namespace "SymEngine": - void eval_mpc(mpc_t result, const Basic &b, mpfr_rnd_t rnd) nogil except + +cdef extern from "" namespace "SymEngine": + void eval_mpc(mpc_t result, const Basic &b, mpfr_rnd_t rnd) nogil except + cdef extern from "" namespace "SymEngine": rcp_const_basic parse(const string &n) nogil except + @@ -1084,7 +911,7 @@ cdef extern from "" namespace "SymEngine": pass cdef cppclass ImageSet(Set): pass - ctypedef set[RCP[Set], RCPBasicKeyLess] set_set "SymEngine::set_set" + ctypedef set[RCP[Set]] set_set "SymEngine::set_set" cdef rcp_const_basic interval(RCP[const Number] &start, RCP[const Number] &end, bool l, bool r) nogil except + cdef RCP[const EmptySet] emptyset() nogil except + cdef RCP[const Reals] reals() nogil except + diff --git a/symengine/lib/symengine_wrapper.pxd b/symengine/lib/symengine_wrapper.in.pxd similarity index 88% rename from symengine/lib/symengine_wrapper.pxd rename to symengine/lib/symengine_wrapper.in.pxd index 0728c42bd..03dbf1f01 100644 --- a/symengine/lib/symengine_wrapper.pxd +++ b/symengine/lib/symengine_wrapper.in.pxd @@ -2,12 +2,11 @@ cimport symengine from symengine cimport RCP, map_basic_basic, rcp_const_basic +from libcpp.memory cimport unique_ptr from libcpp.vector cimport vector from libcpp.string cimport string from libcpp cimport bool as cppbool -include "config.pxi" - cdef class Basic(object): cdef rcp_const_basic thisptr @@ -46,7 +45,7 @@ cdef class _Lambdify(object): cpdef unsafe_eval(sef, inp, out, unsigned nbroadcast=*) cdef class LambdaDouble(_Lambdify): - cdef vector[symengine.LambdaRealDoubleVisitor] lambda_double + cdef unique_ptr[symengine.LambdaRealDoubleVisitor] lambda_visitor cdef _init(self, symengine.vec_basic& args_, symengine.vec_basic& outs_, cppbool cse) cpdef unsafe_real(self, double[::1] inp, double[::1] out, int inp_offset=*, int out_offset=*) cpdef as_scipy_low_level_callable(self) @@ -56,7 +55,7 @@ cdef class LambdaDouble(_Lambdify): int inp_offset=*, int out_offset=*) cdef class LambdaComplexDouble(_Lambdify): - cdef vector[symengine.LambdaComplexDoubleVisitor] lambda_double + cdef unique_ptr[symengine.LambdaComplexDoubleVisitor] lambda_visitor cdef _init(self, symengine.vec_basic& args_, symengine.vec_basic& outs_, cppbool cse) cpdef unsafe_complex(self, double complex[::1] inp, double complex[::1] out, int inp_offset=*, int out_offset=*) @@ -65,7 +64,7 @@ IF HAVE_SYMENGINE_LLVM: cdef int opt_level cdef class LLVMDouble(_LLVMLambdify): - cdef vector[symengine.LLVMDoubleVisitor] lambda_double + cdef unique_ptr[symengine.LLVMDoubleVisitor] lambda_visitor cdef _init(self, symengine.vec_basic& args_, symengine.vec_basic& outs_, cppbool cse) cdef _load(self, const string &s) cpdef unsafe_real(self, double[::1] inp, double[::1] out, int inp_offset=*, int out_offset=*) @@ -73,14 +72,14 @@ IF HAVE_SYMENGINE_LLVM: cpdef as_ctypes(self) cdef class LLVMFloat(_LLVMLambdify): - cdef vector[symengine.LLVMFloatVisitor] lambda_double + cdef unique_ptr[symengine.LLVMFloatVisitor] lambda_visitor cdef _init(self, symengine.vec_basic& args_, symengine.vec_basic& outs_, cppbool cse) cdef _load(self, const string &s) cpdef unsafe_real(self, float[::1] inp, float[::1] out, int inp_offset=*, int out_offset=*) IF HAVE_SYMENGINE_LLVM_LONG_DOUBLE: cdef class LLVMLongDouble(_LLVMLambdify): - cdef vector[symengine.LLVMLongDoubleVisitor] lambda_double + cdef unique_ptr[symengine.LLVMLongDoubleVisitor] lambda_visitor cdef _init(self, symengine.vec_basic& args_, symengine.vec_basic& outs_, cppbool cse) cdef _load(self, const string &s) cpdef unsafe_real(self, long double[::1] inp, long double[::1] out, int inp_offset=*, int out_offset=*) diff --git a/symengine/lib/symengine_wrapper.pyx b/symengine/lib/symengine_wrapper.in.pyx similarity index 92% rename from symengine/lib/symengine_wrapper.pyx rename to symengine/lib/symengine_wrapper.in.pyx index 24b52c0e7..6fe0ffa5e 100644 --- a/symengine/lib/symengine_wrapper.pyx +++ b/symengine/lib/symengine_wrapper.in.pyx @@ -5,6 +5,7 @@ from symengine cimport (RCP, pair, map_basic_basic, umap_int_basic, rcp_const_basic, std_pair_short_rcp_const_basic, rcp_const_seriescoeffinterface, CRCPBasic, tribool, is_indeterminate, is_true, is_false) from libcpp cimport bool as cppbool +from libcpp.utility cimport move from libcpp.string cimport string from libcpp.vector cimport vector from cpython cimport PyObject, Py_XINCREF, Py_XDECREF, \ @@ -30,7 +31,6 @@ try: except ImportError: have_numpy = False -include "config.pxi" class SympifyError(Exception): pass @@ -47,13 +47,13 @@ cpdef void assign_to_capsule(object capsule, object value): cdef object c2py(rcp_const_basic o): cdef Basic r cdef PyObject *obj - if (symengine.is_a_Add(deref(o))): + if (symengine.is_a[symengine.Add](deref(o))): r = Expr.__new__(Add) - elif (symengine.is_a_Mul(deref(o))): + elif (symengine.is_a[symengine.Mul](deref(o))): r = Expr.__new__(Mul) - elif (symengine.is_a_Pow(deref(o))): + elif (symengine.is_a[symengine.Pow](deref(o))): r = Expr.__new__(Pow) - elif (symengine.is_a_Integer(deref(o))): + elif (symengine.is_a[symengine.Integer](deref(o))): if (deref(symengine.rcp_static_cast_Integer(o)).is_zero()): return S.Zero elif (deref(symengine.rcp_static_cast_Integer(o)).is_one()): @@ -61,26 +61,26 @@ cdef object c2py(rcp_const_basic o): elif (deref(symengine.rcp_static_cast_Integer(o)).is_minus_one()): return S.NegativeOne r = Number.__new__(Integer) - elif (symengine.is_a_Rational(deref(o))): + elif (symengine.is_a[symengine.Rational](deref(o))): r = S.Half if (symengine.eq(deref(o), deref(r.thisptr))): return S.Half r = Number.__new__(Rational) - elif (symengine.is_a_Complex(deref(o))): + elif (symengine.is_a[symengine.Complex](deref(o))): r = S.ImaginaryUnit if (symengine.eq(deref(o), deref(r.thisptr))): return S.ImaginaryUnit r = Complex.__new__(Complex) - elif (symengine.is_a_Dummy(deref(o))): + elif (symengine.is_a[symengine.Dummy](deref(o))): r = Dummy.__new__(Dummy) - elif (symengine.is_a_Symbol(deref(o))): - if (symengine.is_a_PySymbol(deref(o))): + elif (symengine.is_a[symengine.Symbol](deref(o))): + if (symengine.is_a_sub[symengine.PySymbol](deref(o))): obj = deref(symengine.rcp_static_cast_PySymbol(o)).get_py_object() result = (obj) Py_XDECREF(obj); return result r = Symbol.__new__(Symbol) - elif (symengine.is_a_Constant(deref(o))): + elif (symengine.is_a[symengine.Constant](deref(o))): r = S.Pi if (symengine.eq(deref(o), deref(r.thisptr))): return S.Pi @@ -97,171 +97,171 @@ cdef object c2py(rcp_const_basic o): if (symengine.eq(deref(o), deref(r.thisptr))): return S.EulerGamma r = Constant.__new__(Constant) - elif (symengine.is_a_Infty(deref(o))): + elif (symengine.is_a[symengine.Infty](deref(o))): if (deref(symengine.rcp_static_cast_Infty(o)).is_positive()): return S.Infinity elif (deref(symengine.rcp_static_cast_Infty(o)).is_negative()): return S.NegativeInfinity return S.ComplexInfinity - elif (symengine.is_a_NaN(deref(o))): + elif (symengine.is_a[symengine.NaN](deref(o))): return S.NaN - elif (symengine.is_a_PyFunction(deref(o))): + elif (symengine.is_a[symengine.PyFunction](deref(o))): r = PyFunction.__new__(PyFunction) - elif (symengine.is_a_FunctionSymbol(deref(o))): + elif (symengine.is_a[symengine.FunctionSymbol](deref(o))): r = FunctionSymbol.__new__(FunctionSymbol) - elif (symengine.is_a_Abs(deref(o))): + elif (symengine.is_a[symengine.Abs](deref(o))): r = Function.__new__(Abs) - elif (symengine.is_a_Max(deref(o))): + elif (symengine.is_a[symengine.Max](deref(o))): r = Function.__new__(Max) - elif (symengine.is_a_Min(deref(o))): + elif (symengine.is_a[symengine.Min](deref(o))): r = Function.__new__(Min) - elif (symengine.is_a_BooleanAtom(deref(o))): + elif (symengine.is_a[symengine.BooleanAtom](deref(o))): if (deref(symengine.rcp_static_cast_BooleanAtom(o)).get_val()): return S.true return S.false - elif (symengine.is_a_Equality(deref(o))): + elif (symengine.is_a[symengine.Equality](deref(o))): r = Relational.__new__(Equality) - elif (symengine.is_a_Unequality(deref(o))): + elif (symengine.is_a[symengine.Unequality](deref(o))): r = Relational.__new__(Unequality) - elif (symengine.is_a_LessThan(deref(o))): + elif (symengine.is_a[symengine.LessThan](deref(o))): r = Relational.__new__(LessThan) - elif (symengine.is_a_StrictLessThan(deref(o))): + elif (symengine.is_a[symengine.StrictLessThan](deref(o))): r = Relational.__new__(StrictLessThan) - elif (symengine.is_a_Gamma(deref(o))): + elif (symengine.is_a[symengine.Gamma](deref(o))): r = Function.__new__(Gamma) - elif (symengine.is_a_Derivative(deref(o))): + elif (symengine.is_a[symengine.Derivative](deref(o))): r = Expr.__new__(Derivative) - elif (symengine.is_a_Subs(deref(o))): + elif (symengine.is_a[symengine.Subs](deref(o))): r = Expr.__new__(Subs) - elif (symengine.is_a_RealDouble(deref(o))): + elif (symengine.is_a[symengine.RealDouble](deref(o))): r = Number.__new__(RealDouble) - elif (symengine.is_a_ComplexDouble(deref(o))): + elif (symengine.is_a[symengine.ComplexDouble](deref(o))): r = ComplexDouble.__new__(ComplexDouble) - elif (symengine.is_a_RealMPFR(deref(o))): + elif (symengine.is_a[symengine.RealMPFR](deref(o))): r = Number.__new__(RealMPFR) - elif (symengine.is_a_ComplexMPC(deref(o))): + elif (symengine.is_a[symengine.ComplexMPC](deref(o))): r = ComplexMPC.__new__(ComplexMPC) - elif (symengine.is_a_Log(deref(o))): + elif (symengine.is_a[symengine.Log](deref(o))): r = Function.__new__(Log) - elif (symengine.is_a_Sin(deref(o))): + elif (symengine.is_a[symengine.Sin](deref(o))): r = Function.__new__(Sin) - elif (symengine.is_a_Cos(deref(o))): + elif (symengine.is_a[symengine.Cos](deref(o))): r = Function.__new__(Cos) - elif (symengine.is_a_Tan(deref(o))): + elif (symengine.is_a[symengine.Tan](deref(o))): r = Function.__new__(Tan) - elif (symengine.is_a_Cot(deref(o))): + elif (symengine.is_a[symengine.Cot](deref(o))): r = Function.__new__(Cot) - elif (symengine.is_a_Csc(deref(o))): + elif (symengine.is_a[symengine.Csc](deref(o))): r = Function.__new__(Csc) - elif (symengine.is_a_Sec(deref(o))): + elif (symengine.is_a[symengine.Sec](deref(o))): r = Function.__new__(Sec) - elif (symengine.is_a_ASin(deref(o))): + elif (symengine.is_a[symengine.ASin](deref(o))): r = Function.__new__(ASin) - elif (symengine.is_a_ACos(deref(o))): + elif (symengine.is_a[symengine.ACos](deref(o))): r = Function.__new__(ACos) - elif (symengine.is_a_ATan(deref(o))): + elif (symengine.is_a[symengine.ATan](deref(o))): r = Function.__new__(ATan) - elif (symengine.is_a_ACot(deref(o))): + elif (symengine.is_a[symengine.ACot](deref(o))): r = Function.__new__(ACot) - elif (symengine.is_a_ACsc(deref(o))): + elif (symengine.is_a[symengine.ACsc](deref(o))): r = Function.__new__(ACsc) - elif (symengine.is_a_ASec(deref(o))): + elif (symengine.is_a[symengine.ASec](deref(o))): r = Function.__new__(ASec) - elif (symengine.is_a_Sinh(deref(o))): + elif (symengine.is_a[symengine.Sinh](deref(o))): r = Function.__new__(Sinh) - elif (symengine.is_a_Cosh(deref(o))): + elif (symengine.is_a[symengine.Cosh](deref(o))): r = Function.__new__(Cosh) - elif (symengine.is_a_Tanh(deref(o))): + elif (symengine.is_a[symengine.Tanh](deref(o))): r = Function.__new__(Tanh) - elif (symengine.is_a_Coth(deref(o))): + elif (symengine.is_a[symengine.Coth](deref(o))): r = Function.__new__(Coth) - elif (symengine.is_a_Csch(deref(o))): + elif (symengine.is_a[symengine.Csch](deref(o))): r = Function.__new__(Csch) - elif (symengine.is_a_Sech(deref(o))): + elif (symengine.is_a[symengine.Sech](deref(o))): r = Function.__new__(Sech) - elif (symengine.is_a_ASinh(deref(o))): + elif (symengine.is_a[symengine.ASinh](deref(o))): r = Function.__new__(ASinh) - elif (symengine.is_a_ACosh(deref(o))): + elif (symengine.is_a[symengine.ACosh](deref(o))): r = Function.__new__(ACosh) - elif (symengine.is_a_ATanh(deref(o))): + elif (symengine.is_a[symengine.ATanh](deref(o))): r = Function.__new__(ATanh) - elif (symengine.is_a_ACoth(deref(o))): + elif (symengine.is_a[symengine.ACoth](deref(o))): r = Function.__new__(ACoth) - elif (symengine.is_a_ACsch(deref(o))): + elif (symengine.is_a[symengine.ACsch](deref(o))): r = Function.__new__(ACsch) - elif (symengine.is_a_ASech(deref(o))): + elif (symengine.is_a[symengine.ASech](deref(o))): r = Function.__new__(ASech) - elif (symengine.is_a_ATan2(deref(o))): + elif (symengine.is_a[symengine.ATan2](deref(o))): r = Function.__new__(ATan2) - elif (symengine.is_a_LambertW(deref(o))): + elif (symengine.is_a[symengine.LambertW](deref(o))): r = Function.__new__(LambertW) - elif (symengine.is_a_Zeta(deref(o))): + elif (symengine.is_a[symengine.Zeta](deref(o))): r = Function.__new__(zeta) - elif (symengine.is_a_DirichletEta(deref(o))): + elif (symengine.is_a[symengine.Dirichlet_eta](deref(o))): r = Function.__new__(dirichlet_eta) - elif (symengine.is_a_KroneckerDelta(deref(o))): + elif (symengine.is_a[symengine.KroneckerDelta](deref(o))): r = Function.__new__(KroneckerDelta) - elif (symengine.is_a_LeviCivita(deref(o))): + elif (symengine.is_a[symengine.LeviCivita](deref(o))): r = Function.__new__(LeviCivita) - elif (symengine.is_a_Erf(deref(o))): + elif (symengine.is_a[symengine.Erf](deref(o))): r = Function.__new__(erf) - elif (symengine.is_a_Erfc(deref(o))): + elif (symengine.is_a[symengine.Erfc](deref(o))): r = Function.__new__(erfc) - elif (symengine.is_a_LowerGamma(deref(o))): + elif (symengine.is_a[symengine.LowerGamma](deref(o))): r = Function.__new__(lowergamma) - elif (symengine.is_a_UpperGamma(deref(o))): + elif (symengine.is_a[symengine.UpperGamma](deref(o))): r = Function.__new__(uppergamma) - elif (symengine.is_a_LogGamma(deref(o))): + elif (symengine.is_a[symengine.LogGamma](deref(o))): r = Function.__new__(loggamma) - elif (symengine.is_a_Beta(deref(o))): + elif (symengine.is_a[symengine.Beta](deref(o))): r = Function.__new__(beta) - elif (symengine.is_a_PolyGamma(deref(o))): + elif (symengine.is_a[symengine.PolyGamma](deref(o))): r = Function.__new__(polygamma) - elif (symengine.is_a_Sign(deref(o))): + elif (symengine.is_a[symengine.Sign](deref(o))): r = Function.__new__(sign) - elif (symengine.is_a_Floor(deref(o))): + elif (symengine.is_a[symengine.Floor](deref(o))): r = Function.__new__(floor) - elif (symengine.is_a_Ceiling(deref(o))): + elif (symengine.is_a[symengine.Ceiling](deref(o))): r = Function.__new__(ceiling) - elif (symengine.is_a_Conjugate(deref(o))): + elif (symengine.is_a[symengine.Conjugate](deref(o))): r = Function.__new__(conjugate) - elif (symengine.is_a_PyNumber(deref(o))): + elif (symengine.is_a[symengine.PyNumber](deref(o))): r = PyNumber.__new__(PyNumber) - elif (symengine.is_a_Piecewise(deref(o))): + elif (symengine.is_a[symengine.Piecewise](deref(o))): r = Function.__new__(Piecewise) - elif (symengine.is_a_Contains(deref(o))): + elif (symengine.is_a[symengine.Contains](deref(o))): r = Boolean.__new__(Contains) - elif (symengine.is_a_Interval(deref(o))): + elif (symengine.is_a[symengine.Interval](deref(o))): r = Set.__new__(Interval) - elif (symengine.is_a_EmptySet(deref(o))): + elif (symengine.is_a[symengine.EmptySet](deref(o))): r = Set.__new__(EmptySet) - elif (symengine.is_a_Reals(deref(o))): + elif (symengine.is_a[symengine.Reals](deref(o))): r = Set.__new__(Reals) - elif (symengine.is_a_Integers(deref(o))): + elif (symengine.is_a[symengine.Integers](deref(o))): r = Set.__new__(Integers) - elif (symengine.is_a_Rationals(deref(o))): + elif (symengine.is_a[symengine.Rationals](deref(o))): r = Set.__new__(Rationals) - elif (symengine.is_a_UniversalSet(deref(o))): + elif (symengine.is_a[symengine.UniversalSet](deref(o))): r = Set.__new__(UniversalSet) - elif (symengine.is_a_FiniteSet(deref(o))): + elif (symengine.is_a[symengine.FiniteSet](deref(o))): r = Set.__new__(FiniteSet) - elif (symengine.is_a_Union(deref(o))): + elif (symengine.is_a[symengine.Union](deref(o))): r = Set.__new__(Union) - elif (symengine.is_a_Complement(deref(o))): + elif (symengine.is_a[symengine.Complement](deref(o))): r = Set.__new__(Complement) - elif (symengine.is_a_ConditionSet(deref(o))): + elif (symengine.is_a[symengine.ConditionSet](deref(o))): r = Set.__new__(ConditionSet) - elif (symengine.is_a_ImageSet(deref(o))): + elif (symengine.is_a[symengine.ImageSet](deref(o))): r = Set.__new__(ImageSet) - elif (symengine.is_a_And(deref(o))): + elif (symengine.is_a[symengine.And](deref(o))): r = Boolean.__new__(And) - elif (symengine.is_a_Not(deref(o))): + elif (symengine.is_a[symengine.Not](deref(o))): r = Boolean.__new__(Not) - elif (symengine.is_a_Or(deref(o))): + elif (symengine.is_a[symengine.Or](deref(o))): r = Boolean.__new__(Or) - elif (symengine.is_a_Xor(deref(o))): + elif (symengine.is_a[symengine.Xor](deref(o))): r = Boolean.__new__(Xor) - elif (symengine.is_a_UnevaluatedExpr(deref(o))): + elif (symengine.is_a[symengine.UnevaluatedExpr](deref(o))): r = Function.__new__(UnevaluatedExpr) else: raise Exception("Unsupported SymEngine class.") @@ -870,6 +870,12 @@ cdef class Basic(object): cdef Basic B = B_ return c2py(symengine.add(A.thisptr, B.thisptr)) + def __radd__(Basic self, b): + B_ = _sympify(b, False) + if B_ is None or isinstance(B_, MatrixBase): return NotImplemented + cdef Basic B = B_ + return c2py(symengine.add(B.thisptr, self.thisptr)) + def __sub__(a, b): cdef Basic A = _sympify(a, False) B_ = _sympify(b, False) @@ -877,6 +883,12 @@ cdef class Basic(object): cdef Basic B = B_ return c2py(symengine.sub(A.thisptr, B.thisptr)) + def __rsub__(Basic self, b): + B_ = _sympify(b, False) + if B_ is None or isinstance(B_, MatrixBase): return NotImplemented + cdef Basic B = B_ + return c2py(symengine.sub(B.thisptr, self.thisptr)) + def __mul__(a, b): cdef Basic A = _sympify(a, False) B_ = _sympify(b, False) @@ -884,12 +896,45 @@ cdef class Basic(object): cdef Basic B = B_ return c2py(symengine.mul(A.thisptr, B.thisptr)) + def __rmul__(Basic self, b): + B_ = _sympify(b, False) + if B_ is None or isinstance(B_, MatrixBase): return NotImplemented + cdef Basic B = B_ + return c2py(symengine.mul(B.thisptr, self.thisptr)) + def __truediv__(a, b): cdef Basic A = _sympify(a, False) - cdef Basic B = _sympify(b, False) - if A is None or B is None: return NotImplemented + B_ = _sympify(b, False) + if A is None or B_ is None or isinstance(B_, MatrixBase): return NotImplemented + cdef Basic B = B_ return c2py(symengine.div(A.thisptr, B.thisptr)) + def __rtruediv__(Basic self, b): + B_ = _sympify(b, False) + if B_ is None or isinstance(B_, MatrixBase): return NotImplemented + cdef Basic B = B_ + return c2py(symengine.div(B.thisptr, self.thisptr)) + + def __floordiv__(x, y): + return floor(x/y) + + def __rfloordiv__(y, x): + return floor(x/y) + + def __mod__(x, y): + return x - y * floor(x/y) + + def __rmod__(y, x): + return x - y * floor(x/y) + + def __divmod__(x, y): + f = floor(x/y) + return f, x - y * f + + def __rdivmod__(y, x): + f = floor(x/y) + return f, x - y * f + def __pow__(a, b, c): if c is not None: return powermod(a, b, c) @@ -898,9 +943,17 @@ cdef class Basic(object): if A is None or B is None: return NotImplemented return c2py(symengine.pow(A.thisptr, B.thisptr)) + def __rpow__(Basic self, b): + cdef Basic B = _sympify(b, False) + if B is None: return NotImplemented + return c2py(symengine.pow(B.thisptr, self.thisptr)) + def __neg__(Basic self not None): return c2py(symengine.neg(self.thisptr)) + def __pos__(self): + return self + def __abs__(Basic self not None): return c2py(symengine.abs(self.thisptr)) @@ -1160,15 +1213,17 @@ cdef class Basic(object): def __int__(self): return int(float(self)) - def __long__(self): - return long(float(self)) - def __complex__(self): f = self.n(real=False) if not isinstance(f, (ComplexDouble, RealDouble)): raise TypeError("Can't convert expression to float") return complex(f) + def as_powers_dict(self): + d = collections.defaultdict(int) + d[self] = 1 + return d + def series(ex, x=None, x0=0, n=6, as_deg_coef_pair=False): # TODO: check for x0 an infinity, see sympy/core/expr.py @@ -1345,6 +1400,11 @@ cdef class ImaginaryUnit(Complex): def __cinit__(Basic self): self.thisptr = symengine.I + def as_powers_dict(self): + d = collections.defaultdict(int) + d[minus_one] = half + return d + I = ImaginaryUnit() @@ -1460,9 +1520,6 @@ cdef class BooleanTrue(BooleanAtom): def _sage_(self): return True - def __nonzero__(self): - return True - def __bool__(self): return True @@ -1567,7 +1624,9 @@ class Equality(Relational): def is_Equality(self): return True - func = __class__ + @property + def func(self): + return self.__class__ Eq = Equality @@ -1588,7 +1647,9 @@ class Unequality(Relational): s = self.args_as_sage() return sage.ne(*s) - func = __class__ + @property + def func(self): + return self.__class__ Ne = Unequality @@ -1820,15 +1881,6 @@ class Integer(Rational): else: return NotImplemented - def __floordiv__(x, y): - return quotient(x, y) - - def __mod__(x, y): - return mod(x, y) - - def __divmod__(x, y): - return quotient_mod(x, y) - def _sympy_(Basic self): import sympy return sympy.Integer(int(self)) @@ -1984,7 +2036,7 @@ class RealMPFR(Float): cdef string i_ = str(i).encode("utf-8") cdef symengine.mpfr_class m m = symengine.mpfr_class(i_, prec, base) - return c2py(symengine.real_mpfr(symengine.std_move_mpfr(m))) + return c2py(symengine.real_mpfr(move[symengine.mpfr_class](m))) def get_prec(Basic self): return Integer(deref(symengine.rcp_static_cast_RealMPFR(self.thisptr)).get_prec()) @@ -2013,7 +2065,7 @@ cdef class ComplexMPC(ComplexBase): return cdef string i_ = ("(" + str(i) + " " + str(j) + ")").encode("utf-8") cdef symengine.mpc_class m = symengine.mpc_class(i_, prec, base) - self.thisptr = symengine.complex_mpc(symengine.std_move_mpc(m)) + self.thisptr = symengine.complex_mpc(move[symengine.mpc_class](m)) def _sympy_(self): import sympy @@ -2078,6 +2130,13 @@ cdef class NegativeInfinity(Number): import sage.all as sage return -sage.oo + def as_powers_dict(self): + d = collections.defaultdict(int) + d[minus_one] = 1 + d[oo] = 1 + return d + + minus_oo = NegativeInfinity() @@ -2272,10 +2331,32 @@ class Mul(AssocOp): d = collections.defaultdict(int) d[c2py(symengine.mul_from_dict(\ (one), - symengine.std_move_map_basic_basic(dict)))] =\ + move[symengine.map_basic_basic](dict)))] =\ c2py(deref(X).get_coef()) return d + def as_powers_dict(Basic self): + cdef RCP[const symengine.Mul] X = symengine.rcp_static_cast_Mul(self.thisptr) + cdef map_basic_basic m = deref(X).get_dict() + coef = c2py((deref(X).get_coef())) + if coef == 1: + d = collections.defaultdict(int) + else: + d = coef.as_powers_dict() + + it = m.begin() + it_end = m.end() + while it != it_end: + base = c2py((deref(it).first)) + exp = c2py((deref(it).second)) + if base.is_Rational and base.p < base.q and base.p > 0: + d[1/base] -= exp + else: + d[base] += exp + inc(it) + + return d + class Pow(Expr): @@ -2319,12 +2400,28 @@ class Pow(Expr): def func(self): return self.__class__ + def as_powers_dict(Basic self): + d = collections.defaultdict(int) + base, exp = self.as_base_exp() + if base.is_Rational and base.p < base.q and base.p > 0: + d[1/base] = -exp + else: + d[base] = exp + return d + class Function(Expr): def __new__(cls, *args, **kwargs): - if cls == Function and len(args) == 1: - return UndefFunction(args[0]) + if cls == Function: + nargs = len(args) + if nargs == 0: + raise TypeError("Required at least one argument to Function") + elif nargs == 1: + return UndefFunction(args[0]) + elif nargs > 1: + raise TypeError(f"Unexpected extra arguments {args[1:]}.") + return super(Function, cls).__new__(cls) @property @@ -2745,6 +2842,10 @@ class FunctionSymbol(Function): name = deref(X).get_name().decode("utf-8") return str(name) + @property + def name(Basic self): + return self.get_name() + def _sympy_(self): import sympy name = self.get_name() @@ -3343,6 +3444,19 @@ cdef class DenseMatrixBase(MatrixBase): raise ShapeError("Invalid shapes for matrix addition. Got %s %s" % (a_.shape, b_.shape)) return a_.add_matrix(b_) + def __radd__(MatrixBase self, a): + a = _sympify(a, False) + if not isinstance(a, MatrixBase): + return NotImplemented + cdef MatrixBase a_ = a + if (a_.shape == (0, 0)): + return self + if (self.shape == (0, 0)): + return a_ + if (self.shape != a_.shape): + raise ShapeError("Invalid shapes for matrix addition. Got %s %s" % (a_.shape, self.shape)) + return a_.add_matrix(self) + def __mul__(a, b): a = _sympify(a, False) b = _sympify(b, False) @@ -3360,6 +3474,17 @@ cdef class DenseMatrixBase(MatrixBase): else: return NotImplemented + def __rmul__(Basic self, a): + a = _sympify(a, False) + if isinstance(a, MatrixBase): + if (a.ncols() != self.nrows()): + raise ShapeError("Invalid shapes for matrix multiplication. Got %s %s" % (a.shape, self.shape)) + return a.mul_matrix(self) + elif isinstance(a, Basic): + return self.mul_scalar(a) + else: + return NotImplemented + def __matmul__(a, b): a = _sympify(a, False) b = _sympify(b, False) @@ -3367,8 +3492,31 @@ cdef class DenseMatrixBase(MatrixBase): raise ShapeError("Invalid shapes for matrix multiplication. Got %s %s" % (a.shape, b.shape)) return a.mul_matrix(b) + def __rmatmul__(Basic self, a): + a = _sympify(a, False) + if (a.ncols() != self.nrows()): + raise ShapeError("Invalid shapes for matrix multiplication. Got %s %s" % (a.shape, self.shape)) + return a.mul_matrix(self) + def __truediv__(a, b): - return div_matrices(a, b) + a = _sympify(a, False) + b = _sympify(b, False) + if isinstance(a, MatrixBase): + if isinstance(b, MatrixBase): + return a.mul_matrix(b.inv()) + elif isinstance(b, Basic): + return a.mul_scalar(1/b) + else: + return NotImplemented + else: + return NotImplemented + + def __rtruediv__(Basic self, a): + a = _sympify(a, False) + if isinstance(a, MatrixBase): + return a.mul_matrix(self.inv()) + else: + return NotImplemented def __sub__(a, b): a = _sympify(a, False) @@ -3381,9 +3529,21 @@ cdef class DenseMatrixBase(MatrixBase): raise ShapeError("Invalid shapes for matrix subtraction. Got %s %s" % (a.shape, b.shape)) return a_.add_matrix(-b_) + def __rsub__(MatrixBase self, a): + a = _sympify(a, False) + if not isinstance(a, MatrixBase): + return NotImplemented + cdef MatrixBase a_ = a + if (a_.shape != self.shape): + raise ShapeError("Invalid shapes for matrix subtraction. Got %s %s" % (a.shape, self.shape)) + return a_.add_matrix(-self) + def __neg__(self): return self.mul_scalar(-1) + def __abs__(self): + return self.applyfunc(abs) + def __getitem__(self, item): if isinstance(item, slice): if (self.ncols() == 0 or self.nrows() == 0): @@ -3989,19 +4149,6 @@ cdef class DenseMatrixBase(MatrixBase): return self.applyfunc(lambda x : x.expand(*args, **kwargs)) -def div_matrices(a, b): - a = _sympify(a, False) - b = _sympify(b, False) - if isinstance(a, MatrixBase): - if isinstance(b, MatrixBase): - return a.mul_matrix(b.inv()) - elif isinstance(b, Basic): - return a.mul_scalar(1/b) - else: - return NotImplemented - else: - return NotImplemented - class DenseMatrixBaseIter(object): def __init__(self, d): @@ -4797,12 +4944,11 @@ def powermod_list(a, b, m): def has_symbol(obj, symbol=None): cdef Basic b = _sympify(obj) cdef Basic s = _sympify(symbol) - require(s, Symbol) + require(s, (Symbol, FunctionSymbol)) if (not symbol): return not b.free_symbols.empty() else: - return symengine.has_symbol(deref(b.thisptr), - deref(symengine.rcp_static_cast_Symbol(s.thisptr))) + return symengine.has_symbol(deref(b.thisptr), deref(s.thisptr)) cdef class _Lambdify(object): @@ -4983,24 +5129,24 @@ cdef class _Lambdify(object): return result -cdef double _scipy_callback_lambda_real(int n, double *x, void *user_data) nogil: +cdef double _scipy_callback_lambda_real(int n, double *x, void *user_data) noexcept nogil: cdef symengine.LambdaRealDoubleVisitor* lamb = user_data cdef double result deref(lamb).call(&result, x) return result -cdef void _ctypes_callback_lambda_real(double *output, const double *input, void *user_data) nogil: +cdef void _ctypes_callback_lambda_real(double *output, const double *input, void *user_data) noexcept nogil: cdef symengine.LambdaRealDoubleVisitor* lamb = user_data deref(lamb).call(output, input) IF HAVE_SYMENGINE_LLVM: - cdef double _scipy_callback_llvm_real(int n, double *x, void *user_data) nogil: + cdef double _scipy_callback_llvm_real(int n, double *x, void *user_data) noexcept nogil: cdef symengine.LLVMDoubleVisitor* lamb = user_data cdef double result deref(lamb).call(&result, x) return result - cdef void _ctypes_callback_llvm_real(double *output, const double *input, void *user_data) nogil: + cdef void _ctypes_callback_llvm_real(double *output, const double *input, void *user_data) noexcept nogil: cdef symengine.LLVMDoubleVisitor* lamb = user_data deref(lamb).call(output, input) @@ -5021,11 +5167,11 @@ cdef class LambdaDouble(_Lambdify): pass cdef _init(self, symengine.vec_basic& args_, symengine.vec_basic& outs_, cppbool cse): - self.lambda_double.resize(1) - self.lambda_double[0].init(args_, outs_, cse) + self.lambda_visitor.reset(new symengine.LambdaRealDoubleVisitor()) + deref(self.lambda_visitor).init(args_, outs_, cse) cpdef unsafe_real(self, double[::1] inp, double[::1] out, int inp_offset=0, int out_offset=0): - self.lambda_double[0].call(&out[out_offset], &inp[inp_offset]) + deref(self.lambda_visitor).call(&out[out_offset], &inp[inp_offset]) cpdef unsafe_eval(self, inp, out, unsigned nbroadcast=1): cdef double[::1] c_inp, c_out @@ -5033,7 +5179,7 @@ cdef class LambdaDouble(_Lambdify): c_inp = np.ascontiguousarray(inp.ravel(order=self.order), dtype=self.numpy_dtype) c_out = out for idx in range(nbroadcast): - self.lambda_double[0].call(&c_out[idx*self.tot_out_size], &c_inp[idx*self.args_size]) + deref(self.lambda_visitor).call(&c_out[idx*self.tot_out_size], &c_inp[idx*self.args_size]) cpdef as_scipy_low_level_callable(self): from ctypes import c_double, c_void_p, c_int, cast, POINTER, CFUNCTYPE @@ -5041,7 +5187,7 @@ cdef class LambdaDouble(_Lambdify): raise RuntimeError("SciPy LowLevelCallable supports only functions with 1 output") addr1 = cast(&_scipy_callback_lambda_real, CFUNCTYPE(c_double, c_int, POINTER(c_double), c_void_p)) - addr2 = cast(&self.lambda_double[0], c_void_p) + addr2 = cast(self.lambda_visitor.get(), c_void_p) return create_low_level_callable(self, addr1, addr2) cpdef as_ctypes(self): @@ -5056,7 +5202,7 @@ cdef class LambdaDouble(_Lambdify): from ctypes import c_double, c_void_p, c_int, cast, POINTER, CFUNCTYPE addr1 = cast(&_ctypes_callback_lambda_real, CFUNCTYPE(c_void_p, POINTER(c_double), POINTER(c_double), c_void_p)) - addr2 = cast(&self.lambda_double[0], c_void_p) + addr2 = cast(self.lambda_visitor.get(), c_void_p) return addr1, addr2 @@ -5066,11 +5212,11 @@ cdef class LambdaComplexDouble(_Lambdify): pass cdef _init(self, symengine.vec_basic& args_, symengine.vec_basic& outs_, cppbool cse): - self.lambda_double.resize(1) - self.lambda_double[0].init(args_, outs_, cse) + self.lambda_visitor.reset(new symengine.LambdaComplexDoubleVisitor()) + deref(self.lambda_visitor).init(args_, outs_, cse) cpdef unsafe_complex(self, double complex[::1] inp, double complex[::1] out, int inp_offset=0, int out_offset=0): - self.lambda_double[0].call(&out[out_offset], &inp[inp_offset]) + deref(self.lambda_visitor).call(&out[out_offset], &inp[inp_offset]) cpdef unsafe_eval(self, inp, out, unsigned nbroadcast=1): cdef double complex[::1] c_inp, c_out @@ -5078,7 +5224,7 @@ cdef class LambdaComplexDouble(_Lambdify): c_inp = np.ascontiguousarray(inp.ravel(order=self.order), dtype=self.numpy_dtype) c_out = out for idx in range(nbroadcast): - self.lambda_double[0].call(&c_out[idx*self.tot_out_size], &c_inp[idx*self.args_size]) + deref(self.lambda_visitor).call(&c_out[idx*self.tot_out_size], &c_inp[idx*self.args_size]) IF HAVE_SYMENGINE_LLVM: @@ -5087,23 +5233,23 @@ IF HAVE_SYMENGINE_LLVM: self.opt_level = opt_level cdef _init(self, symengine.vec_basic& args_, symengine.vec_basic& outs_, cppbool cse): - self.lambda_double.resize(1) - self.lambda_double[0].init(args_, outs_, cse, self.opt_level) + self.lambda_visitor.reset(new symengine.LLVMDoubleVisitor()) + deref(self.lambda_visitor).init(args_, outs_, cse, self.opt_level) cdef _load(self, const string &s): - self.lambda_double.resize(1) - self.lambda_double[0].loads(s) + self.lambda_visitor.reset(new symengine.LLVMDoubleVisitor()) + deref(self.lambda_visitor).loads(s) def __reduce__(self): """ Interface for pickle. Note that the resulting object is platform dependent. """ - cdef bytes s = self.lambda_double[0].dumps() + cdef bytes s = deref(self.lambda_visitor).dumps() return llvm_loading_func, (self.args_size, self.tot_out_size, self.out_shapes, self.real, \ self.n_exprs, self.order, self.accum_out_sizes, self.numpy_dtype, s) cpdef unsafe_real(self, double[::1] inp, double[::1] out, int inp_offset=0, int out_offset=0): - self.lambda_double[0].call(&out[out_offset], &inp[inp_offset]) + deref(self.lambda_visitor).call(&out[out_offset], &inp[inp_offset]) cpdef unsafe_eval(self, inp, out, unsigned nbroadcast=1): cdef double[::1] c_inp, c_out @@ -5111,7 +5257,7 @@ IF HAVE_SYMENGINE_LLVM: c_inp = np.ascontiguousarray(inp.ravel(order=self.order), dtype=self.numpy_dtype) c_out = out for idx in range(nbroadcast): - self.lambda_double[0].call(&c_out[idx*self.tot_out_size], &c_inp[idx*self.args_size]) + deref(self.lambda_visitor).call(&c_out[idx*self.tot_out_size], &c_inp[idx*self.args_size]) cpdef as_scipy_low_level_callable(self): from ctypes import c_double, c_void_p, c_int, cast, POINTER, CFUNCTYPE @@ -5121,7 +5267,7 @@ IF HAVE_SYMENGINE_LLVM: raise RuntimeError("SciPy LowLevelCallable supports only functions with 1 output") addr1 = cast(&_scipy_callback_llvm_real, CFUNCTYPE(c_double, c_int, POINTER(c_double), c_void_p)) - addr2 = cast(&self.lambda_double[0], c_void_p) + addr2 = cast(self.lambda_visitor.get(), c_void_p) return create_low_level_callable(self, addr1, addr2) cpdef as_ctypes(self): @@ -5138,7 +5284,7 @@ IF HAVE_SYMENGINE_LLVM: raise RuntimeError("Lambda function has to be real") addr1 = cast(&_ctypes_callback_llvm_real, CFUNCTYPE(c_void_p, POINTER(c_double), POINTER(c_double), c_void_p)) - addr2 = cast(&self.lambda_double[0], c_void_p) + addr2 = cast(self.lambda_visitor.get(), c_void_p) return addr1, addr2 cdef class LLVMFloat(_LLVMLambdify): @@ -5146,23 +5292,23 @@ IF HAVE_SYMENGINE_LLVM: self.opt_level = opt_level cdef _init(self, symengine.vec_basic& args_, symengine.vec_basic& outs_, cppbool cse): - self.lambda_double.resize(1) - self.lambda_double[0].init(args_, outs_, cse, self.opt_level) + self.lambda_visitor.reset(new symengine.LLVMFloatVisitor()) + deref(self.lambda_visitor).init(args_, outs_, cse, self.opt_level) cdef _load(self, const string &s): - self.lambda_double.resize(1) - self.lambda_double[0].loads(s) + self.lambda_visitor.reset(new symengine.LLVMFloatVisitor()) + deref(self.lambda_visitor).loads(s) def __reduce__(self): """ Interface for pickle. Note that the resulting object is platform dependent. """ - cdef bytes s = self.lambda_double[0].dumps() + cdef bytes s = deref(self.lambda_visitor).dumps() return llvm_float_loading_func, (self.args_size, self.tot_out_size, self.out_shapes, self.real, \ self.n_exprs, self.order, self.accum_out_sizes, self.numpy_dtype, s) cpdef unsafe_real(self, float[::1] inp, float[::1] out, int inp_offset=0, int out_offset=0): - self.lambda_double[0].call(&out[out_offset], &inp[inp_offset]) + deref(self.lambda_visitor).call(&out[out_offset], &inp[inp_offset]) cpdef unsafe_eval(self, inp, out, unsigned nbroadcast=1): cdef float[::1] c_inp, c_out @@ -5170,7 +5316,7 @@ IF HAVE_SYMENGINE_LLVM: c_inp = np.ascontiguousarray(inp.ravel(order=self.order), dtype=self.numpy_dtype) c_out = out for idx in range(nbroadcast): - self.lambda_double[0].call(&c_out[idx*self.tot_out_size], &c_inp[idx*self.args_size]) + deref(self.lambda_visitor).call(&c_out[idx*self.tot_out_size], &c_inp[idx*self.args_size]) IF HAVE_SYMENGINE_LLVM_LONG_DOUBLE: cdef class LLVMLongDouble(_LLVMLambdify): @@ -5178,23 +5324,23 @@ IF HAVE_SYMENGINE_LLVM: self.opt_level = opt_level cdef _init(self, symengine.vec_basic& args_, symengine.vec_basic& outs_, cppbool cse): - self.lambda_double.resize(1) - self.lambda_double[0].init(args_, outs_, cse, self.opt_level) + self.lambda_visitor.reset(new symengine.LLVMLongDoubleVisitor()) + deref(self.lambda_visitor).init(args_, outs_, cse, self.opt_level) cdef _load(self, const string &s): - self.lambda_double.resize(1) - self.lambda_double[0].loads(s) + self.lambda_visitor.reset(new symengine.LLVMLongDoubleVisitor()) + deref(self.lambda_visitor).loads(s) def __reduce__(self): """ Interface for pickle. Note that the resulting object is platform dependent. """ - cdef bytes s = self.lambda_double[0].dumps() + cdef bytes s = deref(self.lambda_visitor).dumps() return llvm_long_double_loading_func, (self.args_size, self.tot_out_size, self.out_shapes, self.real, \ self.n_exprs, self.order, self.accum_out_sizes, self.numpy_dtype, s) cpdef unsafe_real(self, long double[::1] inp, long double[::1] out, int inp_offset=0, int out_offset=0): - self.lambda_double[0].call(&out[out_offset], &inp[inp_offset]) + deref(self.lambda_visitor).call(&out[out_offset], &inp[inp_offset]) cpdef unsafe_eval(self, inp, out, unsigned nbroadcast=1): cdef long double[::1] c_inp, c_out @@ -5202,7 +5348,7 @@ IF HAVE_SYMENGINE_LLVM: c_inp = np.ascontiguousarray(inp.ravel(order=self.order), dtype=self.numpy_dtype) c_out = out for idx in range(nbroadcast): - self.lambda_double[0].call(&c_out[idx*self.tot_out_size], &c_inp[idx*self.args_size]) + deref(self.lambda_visitor).call(&c_out[idx*self.tot_out_size], &c_inp[idx*self.args_size]) def llvm_loading_func(*args): return LLVMDouble(args, _load=True) @@ -5326,7 +5472,7 @@ def piecewise(*v): p.first = e.thisptr p.second = symengine.rcp_static_cast_Boolean(b.thisptr) vec.push_back(p) - return c2py(symengine.piecewise(symengine.std_move_PiecewiseVec(vec))) + return c2py(symengine.piecewise(move[symengine.PiecewiseVec](vec))) def interval(start, end, left_open=False, right_open=False): diff --git a/symengine/tests/CMakeLists.txt b/symengine/tests/CMakeLists.txt index ebd4dfaa2..4f19093b7 100644 --- a/symengine/tests/CMakeLists.txt +++ b/symengine/tests/CMakeLists.txt @@ -1,13 +1,19 @@ set(PY_PATH ${PYTHON_INSTALL_PATH}/symengine/tests) -install(FILES __init__.py +install( + FILES + __init__.py test_arit.py + test_cse.py test_dict_basic.py test_eval.py test_expr.py test_functions.py - test_number.py + test_lambdify.py + test_logic.py test_matrices.py test_ntheory.py + test_number.py + test_pickling.py test_printing.py test_sage.py test_series_expansion.py @@ -16,10 +22,9 @@ install(FILES __init__.py test_subs.py test_symbol.py test_sympify.py + test_sympy_compat.py test_sympy_conv.py test_var.py - test_lambdify.py - test_sympy_compat.py - test_logic.py - DESTINATION ${PY_PATH} - ) + DESTINATION + ${PY_PATH} +) diff --git a/symengine/tests/test_arit.py b/symengine/tests/test_arit.py index b81165145..931b8adb5 100644 --- a/symengine/tests/test_arit.py +++ b/symengine/tests/test_arit.py @@ -1,7 +1,7 @@ from symengine.test_utilities import raises from symengine import (Symbol, Integer, Add, Mul, Pow, Rational, sqrt, - symbols, S, I, count_ops) + symbols, S, I, count_ops, floor) def test_arit1(): @@ -95,6 +95,12 @@ def test_arit8(): assert (2*y**(-2*x**2)) * (3*y**(2*x**2)) == 6 +def test_unary(): + x = Symbol("x") + assert -x == 0 - x + assert +x == x + + def test_expand1(): x = Symbol("x") y = Symbol("y") @@ -165,12 +171,23 @@ def test_as_numer_denom(): assert x == Integer(-5) assert y == Integer(1) + +def test_floor(): + exprs = [Symbol("x"), Symbol("y"), Integer(2), Rational(-3, 5), Integer(-3)] + + for x in exprs: + for y in exprs: + assert x // y == floor(x / y) + assert x == y * (x // y) + x % y + + def test_as_real_imag(): x, y = (5 + 6 * I).as_real_imag() assert x == 5 assert y == 6 + def test_from_args(): x = Symbol("x") y = Symbol("y") diff --git a/symengine/tests/test_expr.py b/symengine/tests/test_expr.py index f69099a56..8cbf4ab7b 100644 --- a/symengine/tests/test_expr.py +++ b/symengine/tests/test_expr.py @@ -1,4 +1,4 @@ -from symengine import Symbol, Integer +from symengine import Symbol, Integer, oo from symengine.test_utilities import raises @@ -12,3 +12,17 @@ def test_as_coefficients_dict(): [0, 0, 3, 0] assert (3.0*x*y).as_coefficients_dict()[3.0*x*y] == 0 assert (3.0*x*y).as_coefficients_dict()[x*y] == 3.0 + + +def test_as_powers_dict(): + x = Symbol('x') + y = Symbol('y') + + assert (2*x**y).as_powers_dict() == {2: 1, x: y} + assert (2*x**2*y**3).as_powers_dict() == {2: 1, x: 2, y: 3} + assert (-oo).as_powers_dict() == {Integer(-1): 1, oo: 1} + assert (x**y).as_powers_dict() == {x: y} + assert ((1/Integer(2))**y).as_powers_dict() == {Integer(2): -y} + assert (x*(1/Integer(2))**y).as_powers_dict() == {x: Integer(1), Integer(2): -y} + assert (2**y).as_powers_dict() == {2: y} + assert (2**-y).as_powers_dict() == {2: -y} diff --git a/symengine/tests/test_functions.py b/symengine/tests/test_functions.py index 267506daa..207add989 100644 --- a/symengine/tests/test_functions.py +++ b/symengine/tests/test_functions.py @@ -85,6 +85,7 @@ def test_derivative(): assert s.variables == (x,) fxy = Function("f")(x, y) + assert (1+fxy).has(fxy) g = Derivative(Function("f")(x, y), x, 2, y, 1) assert g == fxy.diff(x, x, y) assert g == fxy.diff(y, 1, x, 2) @@ -102,6 +103,18 @@ def test_derivative(): assert i == fxy.diff(y, 1, x) +def test_function(): + x = Symbol("x") + fx = Function("f")(x) + assert fx == function_symbol("f", x) + + raises(TypeError, lambda: Function("f", "x")) + raises(TypeError, lambda: Function("f", x)) + raises(TypeError, lambda: Function()) + + assert fx.name == "f" + + def test_abs(): x = Symbol("x") e = abs(x) diff --git a/symengine/tests/test_logic.py b/symengine/tests/test_logic.py index 7c01f8e9b..3d0c33911 100644 --- a/symengine/tests/test_logic.py +++ b/symengine/tests/test_logic.py @@ -27,6 +27,10 @@ def test_relationals(): assert Ge(1, 1) == true assert Eq(I, 2) == false assert Ne(I, 2) == true + eq = Eq(x, y) + assert eq.func(*eq.args) == eq + ne = Ne(x, y) + assert ne.func(*ne.args) == ne def test_rich_cmp(): @@ -118,4 +122,3 @@ def test_Contains(): assert Contains(x, Interval(1, 1)) != false assert Contains(oo, Interval(-oo, oo)) == false assert Contains(-oo, Interval(-oo, oo)) == false - diff --git a/symengine/tests/test_matrices.py b/symengine/tests/test_matrices.py index de9975299..9733e10b1 100644 --- a/symengine/tests/test_matrices.py +++ b/symengine/tests/test_matrices.py @@ -286,11 +286,13 @@ def test_mul_scalar(): assert a * A == DenseMatrix(2, 2, [a, 2*a, 3*a, 4*a]) -def test_neg(): +def test_neg_abs(): A = DenseMatrix(2, 3, [1, 2, 3, 4, 5, 6]) B = DenseMatrix(2, 3, [-1, -2, -3, -4, -5, -6]) assert -A == B + assert A == abs(B) + def test_sub(): A = DenseMatrix(2, 2, [1, 2, 3, 4]) diff --git a/symengine/tests/test_subs.py b/symengine/tests/test_subs.py index 4d8c6f0a4..b346659bf 100644 --- a/symengine/tests/test_subs.py +++ b/symengine/tests/test_subs.py @@ -1,7 +1,7 @@ import unittest from symengine.test_utilities import raises -from symengine import Symbol, sin, cos, sqrt, Add, function_symbol, have_numpy +from symengine import Symbol, sin, cos, sqrt, Add, function_symbol, have_numpy, log def test_basic(): @@ -24,6 +24,12 @@ def test_sin(): assert e.subs(x, 0) == 1 +def test_subs_exception(): + x = Symbol("x") + expr = sin(log(x)) + raises(RuntimeError, lambda: expr.subs({x: 0})) + + def test_args(): x = Symbol("x") e = cos(x) diff --git a/symengine_version.txt b/symengine_version.txt index c91125db5..e49372bea 100644 --- a/symengine_version.txt +++ b/symengine_version.txt @@ -1 +1 @@ -v0.10.1 +c9510fb4b5c30b84adb993573a51f2a9a38a4cfe