├── ATT ├── attention_layer.py ├── attention_package.egg-info │ ├── PKG-INFO │ ├── SOURCES.txt │ ├── dependency_links.txt │ └── top_level.txt ├── pybind11-master │ ├── .appveyor.yml │ ├── .gitignore │ ├── .gitmodules │ ├── .readthedocs.yml │ ├── .travis.yml │ ├── CMakeLists.txt │ ├── CONTRIBUTING.md │ ├── ISSUE_TEMPLATE.md │ ├── LICENSE │ ├── MANIFEST.in │ ├── README.md │ ├── docs │ │ ├── Doxyfile │ │ ├── _static │ │ │ └── theme_overrides.css │ │ ├── advanced │ │ │ ├── cast │ │ │ │ ├── chrono.rst │ │ │ │ ├── custom.rst │ │ │ │ ├── eigen.rst │ │ │ │ ├── functional.rst │ │ │ │ ├── index.rst │ │ │ │ ├── overview.rst │ │ │ │ ├── stl.rst │ │ │ │ └── strings.rst │ │ │ ├── classes.rst │ │ │ ├── embedding.rst │ │ │ ├── exceptions.rst │ │ │ ├── functions.rst │ │ │ ├── misc.rst │ │ │ ├── pycpp │ │ │ │ ├── index.rst │ │ │ │ ├── numpy.rst │ │ │ │ ├── object.rst │ │ │ │ └── utilities.rst │ │ │ └── smart_ptrs.rst │ │ ├── basics.rst │ │ ├── benchmark.py │ │ ├── benchmark.rst │ │ ├── changelog.rst │ │ ├── classes.rst │ │ ├── compiling.rst │ │ ├── conf.py │ │ ├── faq.rst │ │ ├── index.rst │ │ ├── intro.rst │ │ ├── limitations.rst │ │ ├── pybind11-logo.png │ │ ├── pybind11_vs_boost_python1.png │ │ ├── pybind11_vs_boost_python1.svg │ │ ├── pybind11_vs_boost_python2.png │ │ ├── pybind11_vs_boost_python2.svg │ │ ├── reference.rst │ │ ├── release.rst │ │ ├── requirements.txt │ │ └── upgrade.rst │ ├── include │ │ └── pybind11 │ │ │ ├── attr.h │ │ │ ├── buffer_info.h │ │ │ ├── cast.h │ │ │ ├── chrono.h │ │ │ ├── common.h │ │ │ ├── complex.h │ │ │ ├── detail │ │ │ ├── class.h │ │ │ ├── common.h │ │ │ ├── descr.h │ │ │ ├── init.h │ │ │ ├── internals.h │ │ │ └── typeid.h │ │ │ ├── eigen.h │ │ │ ├── embed.h │ │ │ ├── eval.h │ │ │ ├── functional.h │ │ │ ├── iostream.h │ │ │ ├── numpy.h │ │ │ ├── operators.h │ │ │ ├── options.h │ │ │ ├── pybind11.h │ │ │ ├── pytypes.h │ │ │ ├── stl.h │ │ │ └── stl_bind.h │ ├── pybind11 │ │ ├── __init__.py │ │ ├── __main__.py │ │ └── _version.py │ ├── setup.cfg │ ├── setup.py │ ├── tests │ │ ├── CMakeLists.txt │ │ ├── conftest.py │ │ ├── constructor_stats.h │ │ ├── cross_module_gil_utils.cpp │ │ ├── local_bindings.h │ │ ├── object.h │ │ ├── pybind11_cross_module_tests.cpp │ │ ├── pybind11_tests.cpp │ │ ├── pybind11_tests.h │ │ ├── pytest.ini │ │ ├── test_async.cpp │ │ ├── test_async.py │ │ ├── test_buffers.cpp │ │ ├── test_buffers.py │ │ ├── test_builtin_casters.cpp │ │ ├── test_builtin_casters.py │ │ ├── test_call_policies.cpp │ │ ├── test_call_policies.py │ │ ├── test_callbacks.cpp │ │ ├── test_callbacks.py │ │ ├── test_chrono.cpp │ │ ├── test_chrono.py │ │ ├── test_class.cpp │ │ ├── test_class.py │ │ ├── test_cmake_build │ │ │ ├── CMakeLists.txt │ │ │ ├── embed.cpp │ │ │ ├── installed_embed │ │ │ │ └── CMakeLists.txt │ │ │ ├── installed_function │ │ │ │ └── CMakeLists.txt │ │ │ ├── installed_target │ │ │ │ └── CMakeLists.txt │ │ │ ├── main.cpp │ │ │ ├── subdirectory_embed │ │ │ │ └── CMakeLists.txt │ │ │ ├── subdirectory_function │ │ │ │ └── CMakeLists.txt │ │ │ ├── subdirectory_target │ │ │ │ └── CMakeLists.txt │ │ │ └── test.py │ │ ├── test_constants_and_functions.cpp │ │ ├── test_constants_and_functions.py │ │ ├── test_copy_move.cpp │ │ ├── test_copy_move.py │ │ ├── test_custom_type_casters.cpp │ │ ├── test_custom_type_casters.py │ │ ├── test_docstring_options.cpp │ │ ├── test_docstring_options.py │ │ ├── test_eigen.cpp │ │ ├── test_eigen.py │ │ ├── test_embed │ │ │ ├── CMakeLists.txt │ │ │ ├── catch.cpp │ │ │ ├── external_module.cpp │ │ │ ├── test_interpreter.cpp │ │ │ └── test_interpreter.py │ │ ├── test_enum.cpp │ │ ├── test_enum.py │ │ ├── test_eval.cpp │ │ ├── test_eval.py │ │ ├── test_eval_call.py │ │ ├── test_exceptions.cpp │ │ ├── test_exceptions.py │ │ ├── test_factory_constructors.cpp │ │ ├── test_factory_constructors.py │ │ ├── test_gil_scoped.cpp │ │ ├── test_gil_scoped.py │ │ ├── test_iostream.cpp │ │ ├── test_iostream.py │ │ ├── test_kwargs_and_defaults.cpp │ │ ├── test_kwargs_and_defaults.py │ │ ├── test_local_bindings.cpp │ │ ├── test_local_bindings.py │ │ ├── test_methods_and_attributes.cpp │ │ ├── test_methods_and_attributes.py │ │ ├── test_modules.cpp │ │ ├── test_modules.py │ │ ├── test_multiple_inheritance.cpp │ │ ├── test_multiple_inheritance.py │ │ ├── test_numpy_array.cpp │ │ ├── test_numpy_array.py │ │ ├── test_numpy_dtypes.cpp │ │ ├── test_numpy_dtypes.py │ │ ├── test_numpy_vectorize.cpp │ │ ├── test_numpy_vectorize.py │ │ ├── test_opaque_types.cpp │ │ ├── test_opaque_types.py │ │ ├── test_operator_overloading.cpp │ │ ├── test_operator_overloading.py │ │ ├── test_pickling.cpp │ │ ├── test_pickling.py │ │ ├── test_pytypes.cpp │ │ ├── test_pytypes.py │ │ ├── test_sequences_and_iterators.cpp │ │ ├── test_sequences_and_iterators.py │ │ ├── test_smart_ptr.cpp │ │ ├── test_smart_ptr.py │ │ ├── test_stl.cpp │ │ ├── test_stl.py │ │ ├── test_stl_binders.cpp │ │ ├── test_stl_binders.py │ │ ├── test_tagbased_polymorphic.cpp │ │ ├── test_tagbased_polymorphic.py │ │ ├── test_union.cpp │ │ ├── test_union.py │ │ ├── test_virtual_functions.cpp │ │ └── test_virtual_functions.py │ └── tools │ │ ├── FindCatch.cmake │ │ ├── FindEigen3.cmake │ │ ├── FindPythonLibsNew.cmake │ │ ├── check-style.sh │ │ ├── libsize.py │ │ ├── mkdoc.py │ │ ├── pybind11Config.cmake.in │ │ └── pybind11Tools.cmake ├── setup.py └── src │ ├── attention_cuda.cpp │ ├── attention_kernel.cu │ └── attention_kernel.h ├── README.md ├── assets └── teaser.jpg ├── config ├── coco.yaml ├── coco4x.yaml ├── coco8x.yaml └── config.py ├── lib ├── __init__.py ├── app │ └── inference.py ├── data │ └── dataset_homo.py ├── image │ ├── __init__.py │ ├── flow.py │ └── warping.py └── model │ ├── __init__.py │ ├── localtrans.py │ ├── network_utils.py │ └── transfomer.py ├── test.py ├── test.sh ├── train.py └── train.sh /ATT/attention_package.egg-info/PKG-INFO: -------------------------------------------------------------------------------- 1 | Metadata-Version: 1.0 2 | Name: attention-package 3 | Version: 0.2 4 | Summary: attention layer 5 | Home-page: UNKNOWN 6 | Author: Saurus 7 | Author-email: jia1saurus@gmail.com 8 | License: UNKNOWN 9 | Description: UNKNOWN 10 | Platform: UNKNOWN 11 | -------------------------------------------------------------------------------- /ATT/attention_package.egg-info/SOURCES.txt: -------------------------------------------------------------------------------- 1 | setup.py 2 | attention_package.egg-info/PKG-INFO 3 | attention_package.egg-info/SOURCES.txt 4 | attention_package.egg-info/dependency_links.txt 5 | attention_package.egg-info/top_level.txt 6 | src/attention_cuda.cpp 7 | src/attention_kernel.cu -------------------------------------------------------------------------------- /ATT/attention_package.egg-info/dependency_links.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /ATT/attention_package.egg-info/top_level.txt: -------------------------------------------------------------------------------- 1 | at_cuda 2 | -------------------------------------------------------------------------------- /ATT/pybind11-master/.appveyor.yml: -------------------------------------------------------------------------------- 1 | version: 1.0.{build} 2 | image: 3 | - Visual Studio 2017 4 | - Visual Studio 2015 5 | test: off 6 | skip_branch_with_pr: true 7 | build: 8 | parallel: true 9 | platform: 10 | - x64 11 | - x86 12 | environment: 13 | matrix: 14 | - PYTHON: 36 15 | CPP: 14 16 | CONFIG: Debug 17 | - PYTHON: 27 18 | CPP: 14 19 | CONFIG: Debug 20 | - CONDA: 36 21 | CPP: latest 22 | CONFIG: Release 23 | matrix: 24 | exclude: 25 | - image: Visual Studio 2015 26 | platform: x86 27 | - image: Visual Studio 2015 28 | CPP: latest 29 | - image: Visual Studio 2017 30 | CPP: latest 31 | platform: x86 32 | install: 33 | - ps: | 34 | if ($env:PLATFORM -eq "x64") { $env:CMAKE_ARCH = "x64" } 35 | if ($env:APPVEYOR_JOB_NAME -like "*Visual Studio 2017*") { 36 | $env:CMAKE_GENERATOR = "Visual Studio 15 2017" 37 | $env:CMAKE_INCLUDE_PATH = "C:\Libraries\boost_1_64_0" 38 | $env:CXXFLAGS = "-permissive-" 39 | } else { 40 | $env:CMAKE_GENERATOR = "Visual Studio 14 2015" 41 | } 42 | if ($env:PYTHON) { 43 | if ($env:PLATFORM -eq "x64") { $env:PYTHON = "$env:PYTHON-x64" } 44 | $env:PATH = "C:\Python$env:PYTHON\;C:\Python$env:PYTHON\Scripts\;$env:PATH" 45 | python -W ignore -m pip install --upgrade pip wheel 46 | python -W ignore -m pip install pytest numpy --no-warn-script-location 47 | } elseif ($env:CONDA) { 48 | if ($env:CONDA -eq "27") { $env:CONDA = "" } 49 | if ($env:PLATFORM -eq "x64") { $env:CONDA = "$env:CONDA-x64" } 50 | $env:PATH = "C:\Miniconda$env:CONDA\;C:\Miniconda$env:CONDA\Scripts\;$env:PATH" 51 | $env:PYTHONHOME = "C:\Miniconda$env:CONDA" 52 | conda --version 53 | conda install -y -q pytest numpy scipy 54 | } 55 | - ps: | 56 | Start-FileDownload 'http://bitbucket.org/eigen/eigen/get/3.3.3.zip' 57 | 7z x 3.3.3.zip -y > $null 58 | $env:CMAKE_INCLUDE_PATH = "eigen-eigen-67e894c6cd8f;$env:CMAKE_INCLUDE_PATH" 59 | build_script: 60 | - cmake -G "%CMAKE_GENERATOR%" -A "%CMAKE_ARCH%" 61 | -DPYBIND11_CPP_STANDARD=/std:c++%CPP% 62 | -DPYBIND11_WERROR=ON 63 | -DDOWNLOAD_CATCH=ON 64 | -DCMAKE_SUPPRESS_REGENERATION=1 65 | . 66 | - set MSBuildLogger="C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" 67 | - cmake --build . --config %CONFIG% --target pytest -- /m /v:m /logger:%MSBuildLogger% 68 | - cmake --build . --config %CONFIG% --target cpptest -- /m /v:m /logger:%MSBuildLogger% 69 | - if "%CPP%"=="latest" (cmake --build . --config %CONFIG% --target test_cmake_build -- /m /v:m /logger:%MSBuildLogger%) 70 | on_failure: if exist "tests\test_cmake_build" type tests\test_cmake_build\*.log* 71 | -------------------------------------------------------------------------------- /ATT/pybind11-master/.gitignore: -------------------------------------------------------------------------------- 1 | CMakeCache.txt 2 | CMakeFiles 3 | Makefile 4 | cmake_install.cmake 5 | .DS_Store 6 | *.so 7 | *.pyd 8 | *.dll 9 | *.sln 10 | *.sdf 11 | *.opensdf 12 | *.vcxproj 13 | *.vcxproj.user 14 | *.filters 15 | example.dir 16 | Win32 17 | x64 18 | Release 19 | Debug 20 | .vs 21 | CTestTestfile.cmake 22 | Testing 23 | autogen 24 | MANIFEST 25 | /.ninja_* 26 | /*.ninja 27 | /docs/.build 28 | *.py[co] 29 | *.egg-info 30 | *~ 31 | .*.swp 32 | .DS_Store 33 | /dist 34 | /build 35 | /cmake/ 36 | .cache/ 37 | sosize-*.txt 38 | pybind11Config*.cmake 39 | pybind11Targets.cmake 40 | -------------------------------------------------------------------------------- /ATT/pybind11-master/.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "tools/clang"] 2 | path = tools/clang 3 | url = ../../wjakob/clang-cindex-python3 4 | -------------------------------------------------------------------------------- /ATT/pybind11-master/.readthedocs.yml: -------------------------------------------------------------------------------- 1 | python: 2 | version: 3 3 | requirements_file: docs/requirements.txt 4 | -------------------------------------------------------------------------------- /ATT/pybind11-master/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Thank you for your interest in this project! Please refer to the following 2 | sections on how to contribute code and bug reports. 3 | 4 | ### Reporting bugs 5 | 6 | At the moment, this project is run in the spare time of a single person 7 | ([Wenzel Jakob](http://rgl.epfl.ch/people/wjakob)) with very limited resources 8 | for issue tracker tickets. Thus, before submitting a question or bug report, 9 | please take a moment of your time and ensure that your issue isn't already 10 | discussed in the project documentation provided at 11 | [http://pybind11.readthedocs.org/en/latest](http://pybind11.readthedocs.org/en/latest). 12 | 13 | Assuming that you have identified a previously unknown problem or an important 14 | question, it's essential that you submit a self-contained and minimal piece of 15 | code that reproduces the problem. In other words: no external dependencies, 16 | isolate the function(s) that cause breakage, submit matched and complete C++ 17 | and Python snippets that can be easily compiled and run on my end. 18 | 19 | ## Pull requests 20 | Contributions are submitted, reviewed, and accepted using Github pull requests. 21 | Please refer to [this 22 | article](https://help.github.com/articles/using-pull-requests) for details and 23 | adhere to the following rules to make the process as smooth as possible: 24 | 25 | * Make a new branch for every feature you're working on. 26 | * Make small and clean pull requests that are easy to review but make sure they 27 | do add value by themselves. 28 | * Add tests for any new functionality and run the test suite (``make pytest``) 29 | to ensure that no existing features break. 30 | * Please run ``flake8`` and ``tools/check-style.sh`` to check your code matches 31 | the project style. (Note that ``check-style.sh`` requires ``gawk``.) 32 | * This project has a strong focus on providing general solutions using a 33 | minimal amount of code, thus small pull requests are greatly preferred. 34 | 35 | ### Licensing of contributions 36 | 37 | pybind11 is provided under a BSD-style license that can be found in the 38 | ``LICENSE`` file. By using, distributing, or contributing to this project, you 39 | agree to the terms and conditions of this license. 40 | 41 | You are under no obligation whatsoever to provide any bug fixes, patches, or 42 | upgrades to the features, functionality or performance of the source code 43 | ("Enhancements") to anyone; however, if you choose to make your Enhancements 44 | available either publicly, or directly to the author of this software, without 45 | imposing a separate written license agreement for such Enhancements, then you 46 | hereby grant the following license: a non-exclusive, royalty-free perpetual 47 | license to install, use, modify, prepare derivative works, incorporate into 48 | other computer software, distribute, and sublicense such enhancements or 49 | derivative works thereof, in binary and source code form. 50 | -------------------------------------------------------------------------------- /ATT/pybind11-master/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Make sure you've completed the following steps before submitting your issue -- thank you! 2 | 3 | 1. Check if your question has already been answered in the [FAQ](http://pybind11.readthedocs.io/en/latest/faq.html) section. 4 | 2. Make sure you've read the [documentation](http://pybind11.readthedocs.io/en/latest/). Your issue may be addressed there. 5 | 3. If those resources didn't help and you only have a short question (not a bug report), consider asking in the [Gitter chat room](https://gitter.im/pybind/Lobby). 6 | 4. If you have a genuine bug report or a more complex question which is not answered in the previous items (or not suitable for chat), please fill in the details below. 7 | 5. Include a self-contained and minimal piece of code that reproduces the problem. If that's not possible, try to make the description as clear as possible. 8 | 9 | *After reading, remove this checklist and the template text in parentheses below.* 10 | 11 | ## Issue description 12 | 13 | (Provide a short description, state the expected behavior and what actually happens.) 14 | 15 | ## Reproducible example code 16 | 17 | (The code should be minimal, have no external dependencies, isolate the function(s) that cause breakage. Submit matched and complete C++ and Python snippets that can be easily compiled and run to diagnose the issue.) 18 | -------------------------------------------------------------------------------- /ATT/pybind11-master/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Wenzel Jakob , All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are met: 5 | 6 | 1. Redistributions of source code must retain the above copyright notice, this 7 | list of conditions and the following disclaimer. 8 | 9 | 2. Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | 3. Neither the name of the copyright holder nor the names of its contributors 14 | may be used to endorse or promote products derived from this software 15 | without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 18 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 19 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 20 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 21 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 22 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 23 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 24 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 25 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 26 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | 28 | Please also refer to the file CONTRIBUTING.md, which clarifies licensing of 29 | external contributions to this project including patches, pull requests, etc. 30 | -------------------------------------------------------------------------------- /ATT/pybind11-master/MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include include/pybind11 *.h 2 | include LICENSE README.md CONTRIBUTING.md 3 | -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/Doxyfile: -------------------------------------------------------------------------------- 1 | PROJECT_NAME = pybind11 2 | INPUT = ../include/pybind11/ 3 | RECURSIVE = YES 4 | 5 | GENERATE_HTML = NO 6 | GENERATE_LATEX = NO 7 | GENERATE_XML = YES 8 | XML_OUTPUT = .build/doxygenxml 9 | XML_PROGRAMLISTING = YES 10 | 11 | MACRO_EXPANSION = YES 12 | EXPAND_ONLY_PREDEF = YES 13 | EXPAND_AS_DEFINED = PYBIND11_RUNTIME_EXCEPTION 14 | 15 | ALIASES = "rst=\verbatim embed:rst" 16 | ALIASES += "endrst=\endverbatim" 17 | 18 | QUIET = YES 19 | WARNINGS = YES 20 | WARN_IF_UNDOCUMENTED = NO 21 | -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/_static/theme_overrides.css: -------------------------------------------------------------------------------- 1 | .wy-table-responsive table td, 2 | .wy-table-responsive table th { 3 | white-space: initial !important; 4 | } 5 | .rst-content table.docutils td { 6 | vertical-align: top !important; 7 | } 8 | div[class^='highlight'] pre { 9 | white-space: pre; 10 | white-space: pre-wrap; 11 | } 12 | -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/advanced/cast/chrono.rst: -------------------------------------------------------------------------------- 1 | Chrono 2 | ====== 3 | 4 | When including the additional header file :file:`pybind11/chrono.h` conversions 5 | from C++11 chrono datatypes to python datetime objects are automatically enabled. 6 | This header also enables conversions of python floats (often from sources such 7 | as ``time.monotonic()``, ``time.perf_counter()`` and ``time.process_time()``) 8 | into durations. 9 | 10 | An overview of clocks in C++11 11 | ------------------------------ 12 | 13 | A point of confusion when using these conversions is the differences between 14 | clocks provided in C++11. There are three clock types defined by the C++11 15 | standard and users can define their own if needed. Each of these clocks have 16 | different properties and when converting to and from python will give different 17 | results. 18 | 19 | The first clock defined by the standard is ``std::chrono::system_clock``. This 20 | clock measures the current date and time. However, this clock changes with to 21 | updates to the operating system time. For example, if your time is synchronised 22 | with a time server this clock will change. This makes this clock a poor choice 23 | for timing purposes but good for measuring the wall time. 24 | 25 | The second clock defined in the standard is ``std::chrono::steady_clock``. 26 | This clock ticks at a steady rate and is never adjusted. This makes it excellent 27 | for timing purposes, however the value in this clock does not correspond to the 28 | current date and time. Often this clock will be the amount of time your system 29 | has been on, although it does not have to be. This clock will never be the same 30 | clock as the system clock as the system clock can change but steady clocks 31 | cannot. 32 | 33 | The third clock defined in the standard is ``std::chrono::high_resolution_clock``. 34 | This clock is the clock that has the highest resolution out of the clocks in the 35 | system. It is normally a typedef to either the system clock or the steady clock 36 | but can be its own independent clock. This is important as when using these 37 | conversions as the types you get in python for this clock might be different 38 | depending on the system. 39 | If it is a typedef of the system clock, python will get datetime objects, but if 40 | it is a different clock they will be timedelta objects. 41 | 42 | Provided conversions 43 | -------------------- 44 | 45 | .. rubric:: C++ to Python 46 | 47 | - ``std::chrono::system_clock::time_point`` → ``datetime.datetime`` 48 | System clock times are converted to python datetime instances. They are 49 | in the local timezone, but do not have any timezone information attached 50 | to them (they are naive datetime objects). 51 | 52 | - ``std::chrono::duration`` → ``datetime.timedelta`` 53 | Durations are converted to timedeltas, any precision in the duration 54 | greater than microseconds is lost by rounding towards zero. 55 | 56 | - ``std::chrono::[other_clocks]::time_point`` → ``datetime.timedelta`` 57 | Any clock time that is not the system clock is converted to a time delta. 58 | This timedelta measures the time from the clocks epoch to now. 59 | 60 | .. rubric:: Python to C++ 61 | 62 | - ``datetime.datetime`` or ``datetime.date`` or ``datetime.time`` → ``std::chrono::system_clock::time_point`` 63 | Date/time objects are converted into system clock timepoints. Any 64 | timezone information is ignored and the type is treated as a naive 65 | object. 66 | 67 | - ``datetime.timedelta`` → ``std::chrono::duration`` 68 | Time delta are converted into durations with microsecond precision. 69 | 70 | - ``datetime.timedelta`` → ``std::chrono::[other_clocks]::time_point`` 71 | Time deltas that are converted into clock timepoints are treated as 72 | the amount of time from the start of the clocks epoch. 73 | 74 | - ``float`` → ``std::chrono::duration`` 75 | Floats that are passed to C++ as durations be interpreted as a number of 76 | seconds. These will be converted to the duration using ``duration_cast`` 77 | from the float. 78 | 79 | - ``float`` → ``std::chrono::[other_clocks]::time_point`` 80 | Floats that are passed to C++ as time points will be interpreted as the 81 | number of seconds from the start of the clocks epoch. 82 | -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/advanced/cast/custom.rst: -------------------------------------------------------------------------------- 1 | Custom type casters 2 | =================== 3 | 4 | In very rare cases, applications may require custom type casters that cannot be 5 | expressed using the abstractions provided by pybind11, thus requiring raw 6 | Python C API calls. This is fairly advanced usage and should only be pursued by 7 | experts who are familiar with the intricacies of Python reference counting. 8 | 9 | The following snippets demonstrate how this works for a very simple ``inty`` 10 | type that that should be convertible from Python types that provide a 11 | ``__int__(self)`` method. 12 | 13 | .. code-block:: cpp 14 | 15 | struct inty { long long_value; }; 16 | 17 | void print(inty s) { 18 | std::cout << s.long_value << std::endl; 19 | } 20 | 21 | The following Python snippet demonstrates the intended usage from the Python side: 22 | 23 | .. code-block:: python 24 | 25 | class A: 26 | def __int__(self): 27 | return 123 28 | 29 | from example import print 30 | print(A()) 31 | 32 | To register the necessary conversion routines, it is necessary to add 33 | a partial overload to the ``pybind11::detail::type_caster`` template. 34 | Although this is an implementation detail, adding partial overloads to this 35 | type is explicitly allowed. 36 | 37 | .. code-block:: cpp 38 | 39 | namespace pybind11 { namespace detail { 40 | template <> struct type_caster { 41 | public: 42 | /** 43 | * This macro establishes the name 'inty' in 44 | * function signatures and declares a local variable 45 | * 'value' of type inty 46 | */ 47 | PYBIND11_TYPE_CASTER(inty, _("inty")); 48 | 49 | /** 50 | * Conversion part 1 (Python->C++): convert a PyObject into a inty 51 | * instance or return false upon failure. The second argument 52 | * indicates whether implicit conversions should be applied. 53 | */ 54 | bool load(handle src, bool) { 55 | /* Extract PyObject from handle */ 56 | PyObject *source = src.ptr(); 57 | /* Try converting into a Python integer value */ 58 | PyObject *tmp = PyNumber_Long(source); 59 | if (!tmp) 60 | return false; 61 | /* Now try to convert into a C++ int */ 62 | value.long_value = PyLong_AsLong(tmp); 63 | Py_DECREF(tmp); 64 | /* Ensure return code was OK (to avoid out-of-range errors etc) */ 65 | return !(value.long_value == -1 && !PyErr_Occurred()); 66 | } 67 | 68 | /** 69 | * Conversion part 2 (C++ -> Python): convert an inty instance into 70 | * a Python object. The second and third arguments are used to 71 | * indicate the return value policy and parent object (for 72 | * ``return_value_policy::reference_internal``) and are generally 73 | * ignored by implicit casters. 74 | */ 75 | static handle cast(inty src, return_value_policy /* policy */, handle /* parent */) { 76 | return PyLong_FromLong(src.long_value); 77 | } 78 | }; 79 | }} // namespace pybind11::detail 80 | 81 | .. note:: 82 | 83 | A ``type_caster`` defined with ``PYBIND11_TYPE_CASTER(T, ...)`` requires 84 | that ``T`` is default-constructible (``value`` is first default constructed 85 | and then ``load()`` assigns to it). 86 | 87 | .. warning:: 88 | 89 | When using custom type casters, it's important to declare them consistently 90 | in every compilation unit of the Python extension module. Otherwise, 91 | undefined behavior can ensue. 92 | -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/advanced/cast/functional.rst: -------------------------------------------------------------------------------- 1 | Functional 2 | ########## 3 | 4 | The following features must be enabled by including :file:`pybind11/functional.h`. 5 | 6 | 7 | Callbacks and passing anonymous functions 8 | ========================================= 9 | 10 | The C++11 standard brought lambda functions and the generic polymorphic 11 | function wrapper ``std::function<>`` to the C++ programming language, which 12 | enable powerful new ways of working with functions. Lambda functions come in 13 | two flavors: stateless lambda function resemble classic function pointers that 14 | link to an anonymous piece of code, while stateful lambda functions 15 | additionally depend on captured variables that are stored in an anonymous 16 | *lambda closure object*. 17 | 18 | Here is a simple example of a C++ function that takes an arbitrary function 19 | (stateful or stateless) with signature ``int -> int`` as an argument and runs 20 | it with the value 10. 21 | 22 | .. code-block:: cpp 23 | 24 | int func_arg(const std::function &f) { 25 | return f(10); 26 | } 27 | 28 | The example below is more involved: it takes a function of signature ``int -> int`` 29 | and returns another function of the same kind. The return value is a stateful 30 | lambda function, which stores the value ``f`` in the capture object and adds 1 to 31 | its return value upon execution. 32 | 33 | .. code-block:: cpp 34 | 35 | std::function func_ret(const std::function &f) { 36 | return [f](int i) { 37 | return f(i) + 1; 38 | }; 39 | } 40 | 41 | This example demonstrates using python named parameters in C++ callbacks which 42 | requires using ``py::cpp_function`` as a wrapper. Usage is similar to defining 43 | methods of classes: 44 | 45 | .. code-block:: cpp 46 | 47 | py::cpp_function func_cpp() { 48 | return py::cpp_function([](int i) { return i+1; }, 49 | py::arg("number")); 50 | } 51 | 52 | After including the extra header file :file:`pybind11/functional.h`, it is almost 53 | trivial to generate binding code for all of these functions. 54 | 55 | .. code-block:: cpp 56 | 57 | #include 58 | 59 | PYBIND11_MODULE(example, m) { 60 | m.def("func_arg", &func_arg); 61 | m.def("func_ret", &func_ret); 62 | m.def("func_cpp", &func_cpp); 63 | } 64 | 65 | The following interactive session shows how to call them from Python. 66 | 67 | .. code-block:: pycon 68 | 69 | $ python 70 | >>> import example 71 | >>> def square(i): 72 | ... return i * i 73 | ... 74 | >>> example.func_arg(square) 75 | 100L 76 | >>> square_plus_1 = example.func_ret(square) 77 | >>> square_plus_1(4) 78 | 17L 79 | >>> plus_1 = func_cpp() 80 | >>> plus_1(number=43) 81 | 44L 82 | 83 | .. warning:: 84 | 85 | Keep in mind that passing a function from C++ to Python (or vice versa) 86 | will instantiate a piece of wrapper code that translates function 87 | invocations between the two languages. Naturally, this translation 88 | increases the computational cost of each function call somewhat. A 89 | problematic situation can arise when a function is copied back and forth 90 | between Python and C++ many times in a row, in which case the underlying 91 | wrappers will accumulate correspondingly. The resulting long sequence of 92 | C++ -> Python -> C++ -> ... roundtrips can significantly decrease 93 | performance. 94 | 95 | There is one exception: pybind11 detects case where a stateless function 96 | (i.e. a function pointer or a lambda function without captured variables) 97 | is passed as an argument to another C++ function exposed in Python. In this 98 | case, there is no overhead. Pybind11 will extract the underlying C++ 99 | function pointer from the wrapped function to sidestep a potential C++ -> 100 | Python -> C++ roundtrip. This is demonstrated in :file:`tests/test_callbacks.cpp`. 101 | 102 | .. note:: 103 | 104 | This functionality is very useful when generating bindings for callbacks in 105 | C++ libraries (e.g. GUI libraries, asynchronous networking libraries, etc.). 106 | 107 | The file :file:`tests/test_callbacks.cpp` contains a complete example 108 | that demonstrates how to work with callbacks and anonymous functions in 109 | more detail. 110 | -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/advanced/cast/index.rst: -------------------------------------------------------------------------------- 1 | Type conversions 2 | ################ 3 | 4 | Apart from enabling cross-language function calls, a fundamental problem 5 | that a binding tool like pybind11 must address is to provide access to 6 | native Python types in C++ and vice versa. There are three fundamentally 7 | different ways to do this—which approach is preferable for a particular type 8 | depends on the situation at hand. 9 | 10 | 1. Use a native C++ type everywhere. In this case, the type must be wrapped 11 | using pybind11-generated bindings so that Python can interact with it. 12 | 13 | 2. Use a native Python type everywhere. It will need to be wrapped so that 14 | C++ functions can interact with it. 15 | 16 | 3. Use a native C++ type on the C++ side and a native Python type on the 17 | Python side. pybind11 refers to this as a *type conversion*. 18 | 19 | Type conversions are the most "natural" option in the sense that native 20 | (non-wrapped) types are used everywhere. The main downside is that a copy 21 | of the data must be made on every Python ↔ C++ transition: this is 22 | needed since the C++ and Python versions of the same type generally won't 23 | have the same memory layout. 24 | 25 | pybind11 can perform many kinds of conversions automatically. An overview 26 | is provided in the table ":ref:`conversion_table`". 27 | 28 | The following subsections discuss the differences between these options in more 29 | detail. The main focus in this section is on type conversions, which represent 30 | the last case of the above list. 31 | 32 | .. toctree:: 33 | :maxdepth: 1 34 | 35 | overview 36 | strings 37 | stl 38 | functional 39 | chrono 40 | eigen 41 | custom 42 | 43 | -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/advanced/pycpp/index.rst: -------------------------------------------------------------------------------- 1 | Python C++ interface 2 | #################### 3 | 4 | pybind11 exposes Python types and functions using thin C++ wrappers, which 5 | makes it possible to conveniently call Python code from C++ without resorting 6 | to Python's C API. 7 | 8 | .. toctree:: 9 | :maxdepth: 2 10 | 11 | object 12 | numpy 13 | utilities 14 | -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/benchmark.py: -------------------------------------------------------------------------------- 1 | import random 2 | import os 3 | import time 4 | import datetime as dt 5 | 6 | nfns = 4 # Functions per class 7 | nargs = 4 # Arguments per function 8 | 9 | 10 | def generate_dummy_code_pybind11(nclasses=10): 11 | decl = "" 12 | bindings = "" 13 | 14 | for cl in range(nclasses): 15 | decl += "class cl%03i;\n" % cl 16 | decl += '\n' 17 | 18 | for cl in range(nclasses): 19 | decl += "class cl%03i {\n" % cl 20 | decl += "public:\n" 21 | bindings += ' py::class_(m, "cl%03i")\n' % (cl, cl) 22 | for fn in range(nfns): 23 | ret = random.randint(0, nclasses - 1) 24 | params = [random.randint(0, nclasses - 1) for i in range(nargs)] 25 | decl += " cl%03i *fn_%03i(" % (ret, fn) 26 | decl += ", ".join("cl%03i *" % p for p in params) 27 | decl += ");\n" 28 | bindings += ' .def("fn_%03i", &cl%03i::fn_%03i)\n' % \ 29 | (fn, cl, fn) 30 | decl += "};\n\n" 31 | bindings += ' ;\n' 32 | 33 | result = "#include \n\n" 34 | result += "namespace py = pybind11;\n\n" 35 | result += decl + '\n' 36 | result += "PYBIND11_MODULE(example, m) {\n" 37 | result += bindings 38 | result += "}" 39 | return result 40 | 41 | 42 | def generate_dummy_code_boost(nclasses=10): 43 | decl = "" 44 | bindings = "" 45 | 46 | for cl in range(nclasses): 47 | decl += "class cl%03i;\n" % cl 48 | decl += '\n' 49 | 50 | for cl in range(nclasses): 51 | decl += "class cl%03i {\n" % cl 52 | decl += "public:\n" 53 | bindings += ' py::class_("cl%03i")\n' % (cl, cl) 54 | for fn in range(nfns): 55 | ret = random.randint(0, nclasses - 1) 56 | params = [random.randint(0, nclasses - 1) for i in range(nargs)] 57 | decl += " cl%03i *fn_%03i(" % (ret, fn) 58 | decl += ", ".join("cl%03i *" % p for p in params) 59 | decl += ");\n" 60 | bindings += ' .def("fn_%03i", &cl%03i::fn_%03i, py::return_value_policy())\n' % \ 61 | (fn, cl, fn) 62 | decl += "};\n\n" 63 | bindings += ' ;\n' 64 | 65 | result = "#include \n\n" 66 | result += "namespace py = boost::python;\n\n" 67 | result += decl + '\n' 68 | result += "BOOST_PYTHON_MODULE(example) {\n" 69 | result += bindings 70 | result += "}" 71 | return result 72 | 73 | 74 | for codegen in [generate_dummy_code_pybind11, generate_dummy_code_boost]: 75 | print ("{") 76 | for i in range(0, 10): 77 | nclasses = 2 ** i 78 | with open("test.cpp", "w") as f: 79 | f.write(codegen(nclasses)) 80 | n1 = dt.datetime.now() 81 | os.system("g++ -Os -shared -rdynamic -undefined dynamic_lookup " 82 | "-fvisibility=hidden -std=c++14 test.cpp -I include " 83 | "-I /System/Library/Frameworks/Python.framework/Headers -o test.so") 84 | n2 = dt.datetime.now() 85 | elapsed = (n2 - n1).total_seconds() 86 | size = os.stat('test.so').st_size 87 | print(" {%i, %f, %i}," % (nclasses * nfns, elapsed, size)) 88 | print ("}") 89 | -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/benchmark.rst: -------------------------------------------------------------------------------- 1 | Benchmark 2 | ========= 3 | 4 | The following is the result of a synthetic benchmark comparing both compilation 5 | time and module size of pybind11 against Boost.Python. A detailed report about a 6 | Boost.Python to pybind11 conversion of a real project is available here: [#f1]_. 7 | 8 | .. [#f1] http://graylab.jhu.edu/RosettaCon2016/PyRosetta-4.pdf 9 | 10 | Setup 11 | ----- 12 | 13 | A python script (see the ``docs/benchmark.py`` file) was used to generate a set 14 | of files with dummy classes whose count increases for each successive benchmark 15 | (between 1 and 2048 classes in powers of two). Each class has four methods with 16 | a randomly generated signature with a return value and four arguments. (There 17 | was no particular reason for this setup other than the desire to generate many 18 | unique function signatures whose count could be controlled in a simple way.) 19 | 20 | Here is an example of the binding code for one class: 21 | 22 | .. code-block:: cpp 23 | 24 | ... 25 | class cl034 { 26 | public: 27 | cl279 *fn_000(cl084 *, cl057 *, cl065 *, cl042 *); 28 | cl025 *fn_001(cl098 *, cl262 *, cl414 *, cl121 *); 29 | cl085 *fn_002(cl445 *, cl297 *, cl145 *, cl421 *); 30 | cl470 *fn_003(cl200 *, cl323 *, cl332 *, cl492 *); 31 | }; 32 | ... 33 | 34 | PYBIND11_MODULE(example, m) { 35 | ... 36 | py::class_(m, "cl034") 37 | .def("fn_000", &cl034::fn_000) 38 | .def("fn_001", &cl034::fn_001) 39 | .def("fn_002", &cl034::fn_002) 40 | .def("fn_003", &cl034::fn_003) 41 | ... 42 | } 43 | 44 | The Boost.Python version looks almost identical except that a return value 45 | policy had to be specified as an argument to ``def()``. For both libraries, 46 | compilation was done with 47 | 48 | .. code-block:: bash 49 | 50 | Apple LLVM version 7.0.2 (clang-700.1.81) 51 | 52 | and the following compilation flags 53 | 54 | .. code-block:: bash 55 | 56 | g++ -Os -shared -rdynamic -undefined dynamic_lookup -fvisibility=hidden -std=c++14 57 | 58 | Compilation time 59 | ---------------- 60 | 61 | The following log-log plot shows how the compilation time grows for an 62 | increasing number of class and function declarations. pybind11 includes many 63 | fewer headers, which initially leads to shorter compilation times, but the 64 | performance is ultimately fairly similar (pybind11 is 19.8 seconds faster for 65 | the largest largest file with 2048 classes and a total of 8192 methods -- a 66 | modest **1.2x** speedup relative to Boost.Python, which required 116.35 67 | seconds). 68 | 69 | .. only:: not latex 70 | 71 | .. image:: pybind11_vs_boost_python1.svg 72 | 73 | .. only:: latex 74 | 75 | .. image:: pybind11_vs_boost_python1.png 76 | 77 | Module size 78 | ----------- 79 | 80 | Differences between the two libraries become much more pronounced when 81 | considering the file size of the generated Python plugin: for the largest file, 82 | the binary generated by Boost.Python required 16.8 MiB, which was **2.17 83 | times** / **9.1 megabytes** larger than the output generated by pybind11. For 84 | very small inputs, Boost.Python has an edge in the plot below -- however, note 85 | that it stores many definitions in an external library, whose size was not 86 | included here, hence the comparison is slightly shifted in Boost.Python's 87 | favor. 88 | 89 | .. only:: not latex 90 | 91 | .. image:: pybind11_vs_boost_python2.svg 92 | 93 | .. only:: latex 94 | 95 | .. image:: pybind11_vs_boost_python2.png 96 | 97 | 98 | -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/index.rst: -------------------------------------------------------------------------------- 1 | .. only: not latex 2 | 3 | .. image:: pybind11-logo.png 4 | 5 | pybind11 --- Seamless operability between C++11 and Python 6 | ========================================================== 7 | 8 | .. only: not latex 9 | 10 | Contents: 11 | 12 | .. toctree:: 13 | :maxdepth: 1 14 | 15 | intro 16 | changelog 17 | upgrade 18 | 19 | .. toctree:: 20 | :caption: The Basics 21 | :maxdepth: 2 22 | 23 | basics 24 | classes 25 | compiling 26 | 27 | .. toctree:: 28 | :caption: Advanced Topics 29 | :maxdepth: 2 30 | 31 | advanced/functions 32 | advanced/classes 33 | advanced/exceptions 34 | advanced/smart_ptrs 35 | advanced/cast/index 36 | advanced/pycpp/index 37 | advanced/embedding 38 | advanced/misc 39 | 40 | .. toctree:: 41 | :caption: Extra Information 42 | :maxdepth: 1 43 | 44 | faq 45 | benchmark 46 | limitations 47 | reference 48 | -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/intro.rst: -------------------------------------------------------------------------------- 1 | .. image:: pybind11-logo.png 2 | 3 | About this project 4 | ================== 5 | **pybind11** is a lightweight header-only library that exposes C++ types in Python 6 | and vice versa, mainly to create Python bindings of existing C++ code. Its 7 | goals and syntax are similar to the excellent `Boost.Python`_ library by David 8 | Abrahams: to minimize boilerplate code in traditional extension modules by 9 | inferring type information using compile-time introspection. 10 | 11 | .. _Boost.Python: http://www.boost.org/doc/libs/release/libs/python/doc/index.html 12 | 13 | The main issue with Boost.Python—and the reason for creating such a similar 14 | project—is Boost. Boost is an enormously large and complex suite of utility 15 | libraries that works with almost every C++ compiler in existence. This 16 | compatibility has its cost: arcane template tricks and workarounds are 17 | necessary to support the oldest and buggiest of compiler specimens. Now that 18 | C++11-compatible compilers are widely available, this heavy machinery has 19 | become an excessively large and unnecessary dependency. 20 | Think of this library as a tiny self-contained version of Boost.Python with 21 | everything stripped away that isn't relevant for binding generation. Without 22 | comments, the core header files only require ~4K lines of code and depend on 23 | Python (2.7 or 3.x, or PyPy2.7 >= 5.7) and the C++ standard library. This 24 | compact implementation was possible thanks to some of the new C++11 language 25 | features (specifically: tuples, lambda functions and variadic templates). Since 26 | its creation, this library has grown beyond Boost.Python in many ways, leading 27 | to dramatically simpler binding code in many common situations. 28 | 29 | Core features 30 | ************* 31 | The following core C++ features can be mapped to Python 32 | 33 | - Functions accepting and returning custom data structures per value, reference, or pointer 34 | - Instance methods and static methods 35 | - Overloaded functions 36 | - Instance attributes and static attributes 37 | - Arbitrary exception types 38 | - Enumerations 39 | - Callbacks 40 | - Iterators and ranges 41 | - Custom operators 42 | - Single and multiple inheritance 43 | - STL data structures 44 | - Smart pointers with reference counting like ``std::shared_ptr`` 45 | - Internal references with correct reference counting 46 | - C++ classes with virtual (and pure virtual) methods can be extended in Python 47 | 48 | Goodies 49 | ******* 50 | In addition to the core functionality, pybind11 provides some extra goodies: 51 | 52 | - Python 2.7, 3.x, and PyPy (PyPy2.7 >= 5.7) are supported with an 53 | implementation-agnostic interface. 54 | 55 | - It is possible to bind C++11 lambda functions with captured variables. The 56 | lambda capture data is stored inside the resulting Python function object. 57 | 58 | - pybind11 uses C++11 move constructors and move assignment operators whenever 59 | possible to efficiently transfer custom data types. 60 | 61 | - It's easy to expose the internal storage of custom data types through 62 | Pythons' buffer protocols. This is handy e.g. for fast conversion between 63 | C++ matrix classes like Eigen and NumPy without expensive copy operations. 64 | 65 | - pybind11 can automatically vectorize functions so that they are transparently 66 | applied to all entries of one or more NumPy array arguments. 67 | 68 | - Python's slice-based access and assignment operations can be supported with 69 | just a few lines of code. 70 | 71 | - Everything is contained in just a few header files; there is no need to link 72 | against any additional libraries. 73 | 74 | - Binaries are generally smaller by a factor of at least 2 compared to 75 | equivalent bindings generated by Boost.Python. A recent pybind11 conversion 76 | of `PyRosetta`_, an enormous Boost.Python binding project, reported a binary 77 | size reduction of **5.4x** and compile time reduction by **5.8x**. 78 | 79 | - Function signatures are precomputed at compile time (using ``constexpr``), 80 | leading to smaller binaries. 81 | 82 | - With little extra effort, C++ types can be pickled and unpickled similar to 83 | regular Python objects. 84 | 85 | .. _PyRosetta: http://graylab.jhu.edu/RosettaCon2016/PyRosetta-4.pdf 86 | 87 | Supported compilers 88 | ******************* 89 | 90 | 1. Clang/LLVM (any non-ancient version with C++11 support) 91 | 2. GCC 4.8 or newer 92 | 3. Microsoft Visual Studio 2015 or newer 93 | 4. Intel C++ compiler v17 or newer (v16 with pybind11 v2.0 and v15 with pybind11 v2.0 and a `workaround `_ ) 94 | -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/limitations.rst: -------------------------------------------------------------------------------- 1 | Limitations 2 | ########### 3 | 4 | pybind11 strives to be a general solution to binding generation, but it also has 5 | certain limitations: 6 | 7 | - pybind11 casts away ``const``-ness in function arguments and return values. 8 | This is in line with the Python language, which has no concept of ``const`` 9 | values. This means that some additional care is needed to avoid bugs that 10 | would be caught by the type checker in a traditional C++ program. 11 | 12 | - The NumPy interface ``pybind11::array`` greatly simplifies accessing 13 | numerical data from C++ (and vice versa), but it's not a full-blown array 14 | class like ``Eigen::Array`` or ``boost.multi_array``. 15 | 16 | These features could be implemented but would lead to a significant increase in 17 | complexity. I've decided to draw the line here to keep this project simple and 18 | compact. Users who absolutely require these features are encouraged to fork 19 | pybind11. 20 | 21 | -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/pybind11-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DSaurus/LocalTrans/4884f9001d006644c8b74fde41324a4795cb683b/ATT/pybind11-master/docs/pybind11-logo.png -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/pybind11_vs_boost_python1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DSaurus/LocalTrans/4884f9001d006644c8b74fde41324a4795cb683b/ATT/pybind11-master/docs/pybind11_vs_boost_python1.png -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/pybind11_vs_boost_python2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DSaurus/LocalTrans/4884f9001d006644c8b74fde41324a4795cb683b/ATT/pybind11-master/docs/pybind11_vs_boost_python2.png -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/reference.rst: -------------------------------------------------------------------------------- 1 | .. _reference: 2 | 3 | .. warning:: 4 | 5 | Please be advised that the reference documentation discussing pybind11 6 | internals is currently incomplete. Please refer to the previous sections 7 | and the pybind11 header files for the nitty gritty details. 8 | 9 | Reference 10 | ######### 11 | 12 | .. _macros: 13 | 14 | Macros 15 | ====== 16 | 17 | .. doxygendefine:: PYBIND11_MODULE 18 | 19 | .. _core_types: 20 | 21 | Convenience classes for arbitrary Python types 22 | ============================================== 23 | 24 | Common member functions 25 | ----------------------- 26 | 27 | .. doxygenclass:: object_api 28 | :members: 29 | 30 | Without reference counting 31 | -------------------------- 32 | 33 | .. doxygenclass:: handle 34 | :members: 35 | 36 | With reference counting 37 | ----------------------- 38 | 39 | .. doxygenclass:: object 40 | :members: 41 | 42 | .. doxygenfunction:: reinterpret_borrow 43 | 44 | .. doxygenfunction:: reinterpret_steal 45 | 46 | Convenience classes for specific Python types 47 | ============================================= 48 | 49 | .. doxygenclass:: module 50 | :members: 51 | 52 | .. doxygengroup:: pytypes 53 | :members: 54 | 55 | .. _extras: 56 | 57 | Passing extra arguments to ``def`` or ``class_`` 58 | ================================================ 59 | 60 | .. doxygengroup:: annotations 61 | :members: 62 | 63 | Embedding the interpreter 64 | ========================= 65 | 66 | .. doxygendefine:: PYBIND11_EMBEDDED_MODULE 67 | 68 | .. doxygenfunction:: initialize_interpreter 69 | 70 | .. doxygenfunction:: finalize_interpreter 71 | 72 | .. doxygenclass:: scoped_interpreter 73 | 74 | Redirecting C++ streams 75 | ======================= 76 | 77 | .. doxygenclass:: scoped_ostream_redirect 78 | 79 | .. doxygenclass:: scoped_estream_redirect 80 | 81 | .. doxygenfunction:: add_ostream_redirect 82 | 83 | Python built-in functions 84 | ========================= 85 | 86 | .. doxygengroup:: python_builtins 87 | :members: 88 | 89 | Inheritance 90 | =========== 91 | 92 | See :doc:`/classes` and :doc:`/advanced/classes` for more detail. 93 | 94 | .. doxygendefine:: PYBIND11_OVERLOAD 95 | 96 | .. doxygendefine:: PYBIND11_OVERLOAD_PURE 97 | 98 | .. doxygendefine:: PYBIND11_OVERLOAD_NAME 99 | 100 | .. doxygendefine:: PYBIND11_OVERLOAD_PURE_NAME 101 | 102 | .. doxygenfunction:: get_overload 103 | 104 | Exceptions 105 | ========== 106 | 107 | .. doxygenclass:: error_already_set 108 | :members: 109 | 110 | .. doxygenclass:: builtin_exception 111 | :members: 112 | 113 | 114 | Literals 115 | ======== 116 | 117 | .. doxygennamespace:: literals 118 | -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/release.rst: -------------------------------------------------------------------------------- 1 | To release a new version of pybind11: 2 | 3 | - Update the version number and push to pypi 4 | - Update ``pybind11/_version.py`` (set release version, remove 'dev'). 5 | - Update ``PYBIND11_VERSION_MAJOR`` etc. in ``include/pybind11/detail/common.h``. 6 | - Ensure that all the information in ``setup.py`` is up-to-date. 7 | - Update version in ``docs/conf.py``. 8 | - Tag release date in ``docs/changelog.rst``. 9 | - ``git add`` and ``git commit``. 10 | - if new minor version: ``git checkout -b vX.Y``, ``git push -u origin vX.Y`` 11 | - ``git tag -a vX.Y.Z -m 'vX.Y.Z release'``. 12 | - ``git push`` 13 | - ``git push --tags``. 14 | - ``python setup.py sdist upload``. 15 | - ``python setup.py bdist_wheel upload``. 16 | - Get back to work 17 | - Update ``_version.py`` (add 'dev' and increment minor). 18 | - Update version in ``docs/conf.py`` 19 | - Update version macros in ``include/pybind11/common.h`` 20 | - ``git add`` and ``git commit``. 21 | ``git push`` 22 | -------------------------------------------------------------------------------- /ATT/pybind11-master/docs/requirements.txt: -------------------------------------------------------------------------------- 1 | breathe == 4.5.0 2 | -------------------------------------------------------------------------------- /ATT/pybind11-master/include/pybind11/common.h: -------------------------------------------------------------------------------- 1 | #include "detail/common.h" 2 | #warning "Including 'common.h' is deprecated. It will be removed in v3.0. Use 'pybind11.h'." 3 | -------------------------------------------------------------------------------- /ATT/pybind11-master/include/pybind11/complex.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/complex.h: Complex number support 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #pragma once 11 | 12 | #include "pybind11.h" 13 | #include 14 | 15 | /// glibc defines I as a macro which breaks things, e.g., boost template names 16 | #ifdef I 17 | # undef I 18 | #endif 19 | 20 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 21 | 22 | template struct format_descriptor, detail::enable_if_t::value>> { 23 | static constexpr const char c = format_descriptor::c; 24 | static constexpr const char value[3] = { 'Z', c, '\0' }; 25 | static std::string format() { return std::string(value); } 26 | }; 27 | 28 | #ifndef PYBIND11_CPP17 29 | 30 | template constexpr const char format_descriptor< 31 | std::complex, detail::enable_if_t::value>>::value[3]; 32 | 33 | #endif 34 | 35 | NAMESPACE_BEGIN(detail) 36 | 37 | template struct is_fmt_numeric, detail::enable_if_t::value>> { 38 | static constexpr bool value = true; 39 | static constexpr int index = is_fmt_numeric::index + 3; 40 | }; 41 | 42 | template class type_caster> { 43 | public: 44 | bool load(handle src, bool convert) { 45 | if (!src) 46 | return false; 47 | if (!convert && !PyComplex_Check(src.ptr())) 48 | return false; 49 | Py_complex result = PyComplex_AsCComplex(src.ptr()); 50 | if (result.real == -1.0 && PyErr_Occurred()) { 51 | PyErr_Clear(); 52 | return false; 53 | } 54 | value = std::complex((T) result.real, (T) result.imag); 55 | return true; 56 | } 57 | 58 | static handle cast(const std::complex &src, return_value_policy /* policy */, handle /* parent */) { 59 | return PyComplex_FromDoubles((double) src.real(), (double) src.imag()); 60 | } 61 | 62 | PYBIND11_TYPE_CASTER(std::complex, _("complex")); 63 | }; 64 | NAMESPACE_END(detail) 65 | NAMESPACE_END(PYBIND11_NAMESPACE) 66 | -------------------------------------------------------------------------------- /ATT/pybind11-master/include/pybind11/detail/descr.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/detail/descr.h: Helper type for concatenating type signatures at compile time 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #pragma once 11 | 12 | #include "common.h" 13 | 14 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 15 | NAMESPACE_BEGIN(detail) 16 | 17 | #if !defined(_MSC_VER) 18 | # define PYBIND11_DESCR_CONSTEXPR static constexpr 19 | #else 20 | # define PYBIND11_DESCR_CONSTEXPR const 21 | #endif 22 | 23 | /* Concatenate type signatures at compile time */ 24 | template 25 | struct descr { 26 | char text[N + 1]; 27 | 28 | constexpr descr() : text{'\0'} { } 29 | constexpr descr(char const (&s)[N+1]) : descr(s, make_index_sequence()) { } 30 | 31 | template 32 | constexpr descr(char const (&s)[N+1], index_sequence) : text{s[Is]..., '\0'} { } 33 | 34 | template 35 | constexpr descr(char c, Chars... cs) : text{c, static_cast(cs)..., '\0'} { } 36 | 37 | static constexpr std::array types() { 38 | return {{&typeid(Ts)..., nullptr}}; 39 | } 40 | }; 41 | 42 | template 43 | constexpr descr plus_impl(const descr &a, const descr &b, 44 | index_sequence, index_sequence) { 45 | return {a.text[Is1]..., b.text[Is2]...}; 46 | } 47 | 48 | template 49 | constexpr descr operator+(const descr &a, const descr &b) { 50 | return plus_impl(a, b, make_index_sequence(), make_index_sequence()); 51 | } 52 | 53 | template 54 | constexpr descr _(char const(&text)[N]) { return descr(text); } 55 | constexpr descr<0> _(char const(&)[1]) { return {}; } 56 | 57 | template struct int_to_str : int_to_str { }; 58 | template struct int_to_str<0, Digits...> { 59 | static constexpr auto digits = descr(('0' + Digits)...); 60 | }; 61 | 62 | // Ternary description (like std::conditional) 63 | template 64 | constexpr enable_if_t> _(char const(&text1)[N1], char const(&)[N2]) { 65 | return _(text1); 66 | } 67 | template 68 | constexpr enable_if_t> _(char const(&)[N1], char const(&text2)[N2]) { 69 | return _(text2); 70 | } 71 | 72 | template 73 | constexpr enable_if_t _(const T1 &d, const T2 &) { return d; } 74 | template 75 | constexpr enable_if_t _(const T1 &, const T2 &d) { return d; } 76 | 77 | template auto constexpr _() -> decltype(int_to_str::digits) { 78 | return int_to_str::digits; 79 | } 80 | 81 | template constexpr descr<1, Type> _() { return {'%'}; } 82 | 83 | constexpr descr<0> concat() { return {}; } 84 | 85 | template 86 | constexpr descr concat(const descr &descr) { return descr; } 87 | 88 | template 89 | constexpr auto concat(const descr &d, const Args &...args) 90 | -> decltype(std::declval>() + concat(args...)) { 91 | return d + _(", ") + concat(args...); 92 | } 93 | 94 | template 95 | constexpr descr type_descr(const descr &descr) { 96 | return _("{") + descr + _("}"); 97 | } 98 | 99 | NAMESPACE_END(detail) 100 | NAMESPACE_END(PYBIND11_NAMESPACE) 101 | -------------------------------------------------------------------------------- /ATT/pybind11-master/include/pybind11/detail/typeid.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/detail/typeid.h: Compiler-independent access to type identifiers 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #pragma once 11 | 12 | #include 13 | #include 14 | 15 | #if defined(__GNUG__) 16 | #include 17 | #endif 18 | 19 | #include "common.h" 20 | 21 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 22 | NAMESPACE_BEGIN(detail) 23 | /// Erase all occurrences of a substring 24 | inline void erase_all(std::string &string, const std::string &search) { 25 | for (size_t pos = 0;;) { 26 | pos = string.find(search, pos); 27 | if (pos == std::string::npos) break; 28 | string.erase(pos, search.length()); 29 | } 30 | } 31 | 32 | PYBIND11_NOINLINE inline void clean_type_id(std::string &name) { 33 | #if defined(__GNUG__) 34 | int status = 0; 35 | std::unique_ptr res { 36 | abi::__cxa_demangle(name.c_str(), nullptr, nullptr, &status), std::free }; 37 | if (status == 0) 38 | name = res.get(); 39 | #else 40 | detail::erase_all(name, "class "); 41 | detail::erase_all(name, "struct "); 42 | detail::erase_all(name, "enum "); 43 | #endif 44 | detail::erase_all(name, "pybind11::"); 45 | } 46 | NAMESPACE_END(detail) 47 | 48 | /// Return a string representation of a C++ type 49 | template static std::string type_id() { 50 | std::string name(typeid(T).name()); 51 | detail::clean_type_id(name); 52 | return name; 53 | } 54 | 55 | NAMESPACE_END(PYBIND11_NAMESPACE) 56 | -------------------------------------------------------------------------------- /ATT/pybind11-master/include/pybind11/eval.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/exec.h: Support for evaluating Python expressions and statements 3 | from strings and files 4 | 5 | Copyright (c) 2016 Klemens Morgenstern and 6 | Wenzel Jakob 7 | 8 | All rights reserved. Use of this source code is governed by a 9 | BSD-style license that can be found in the LICENSE file. 10 | */ 11 | 12 | #pragma once 13 | 14 | #include "pybind11.h" 15 | 16 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 17 | 18 | enum eval_mode { 19 | /// Evaluate a string containing an isolated expression 20 | eval_expr, 21 | 22 | /// Evaluate a string containing a single statement. Returns \c none 23 | eval_single_statement, 24 | 25 | /// Evaluate a string containing a sequence of statement. Returns \c none 26 | eval_statements 27 | }; 28 | 29 | template 30 | object eval(str expr, object global = globals(), object local = object()) { 31 | if (!local) 32 | local = global; 33 | 34 | /* PyRun_String does not accept a PyObject / encoding specifier, 35 | this seems to be the only alternative */ 36 | std::string buffer = "# -*- coding: utf-8 -*-\n" + (std::string) expr; 37 | 38 | int start; 39 | switch (mode) { 40 | case eval_expr: start = Py_eval_input; break; 41 | case eval_single_statement: start = Py_single_input; break; 42 | case eval_statements: start = Py_file_input; break; 43 | default: pybind11_fail("invalid evaluation mode"); 44 | } 45 | 46 | PyObject *result = PyRun_String(buffer.c_str(), start, global.ptr(), local.ptr()); 47 | if (!result) 48 | throw error_already_set(); 49 | return reinterpret_steal(result); 50 | } 51 | 52 | template 53 | object eval(const char (&s)[N], object global = globals(), object local = object()) { 54 | /* Support raw string literals by removing common leading whitespace */ 55 | auto expr = (s[0] == '\n') ? str(module::import("textwrap").attr("dedent")(s)) 56 | : str(s); 57 | return eval(expr, global, local); 58 | } 59 | 60 | inline void exec(str expr, object global = globals(), object local = object()) { 61 | eval(expr, global, local); 62 | } 63 | 64 | template 65 | void exec(const char (&s)[N], object global = globals(), object local = object()) { 66 | eval(s, global, local); 67 | } 68 | 69 | template 70 | object eval_file(str fname, object global = globals(), object local = object()) { 71 | if (!local) 72 | local = global; 73 | 74 | int start; 75 | switch (mode) { 76 | case eval_expr: start = Py_eval_input; break; 77 | case eval_single_statement: start = Py_single_input; break; 78 | case eval_statements: start = Py_file_input; break; 79 | default: pybind11_fail("invalid evaluation mode"); 80 | } 81 | 82 | int closeFile = 1; 83 | std::string fname_str = (std::string) fname; 84 | #if PY_VERSION_HEX >= 0x03040000 85 | FILE *f = _Py_fopen_obj(fname.ptr(), "r"); 86 | #elif PY_VERSION_HEX >= 0x03000000 87 | FILE *f = _Py_fopen(fname.ptr(), "r"); 88 | #else 89 | /* No unicode support in open() :( */ 90 | auto fobj = reinterpret_steal(PyFile_FromString( 91 | const_cast(fname_str.c_str()), 92 | const_cast("r"))); 93 | FILE *f = nullptr; 94 | if (fobj) 95 | f = PyFile_AsFile(fobj.ptr()); 96 | closeFile = 0; 97 | #endif 98 | if (!f) { 99 | PyErr_Clear(); 100 | pybind11_fail("File \"" + fname_str + "\" could not be opened!"); 101 | } 102 | 103 | #if PY_VERSION_HEX < 0x03000000 && defined(PYPY_VERSION) 104 | PyObject *result = PyRun_File(f, fname_str.c_str(), start, global.ptr(), 105 | local.ptr()); 106 | (void) closeFile; 107 | #else 108 | PyObject *result = PyRun_FileEx(f, fname_str.c_str(), start, global.ptr(), 109 | local.ptr(), closeFile); 110 | #endif 111 | 112 | if (!result) 113 | throw error_already_set(); 114 | return reinterpret_steal(result); 115 | } 116 | 117 | NAMESPACE_END(PYBIND11_NAMESPACE) 118 | -------------------------------------------------------------------------------- /ATT/pybind11-master/include/pybind11/functional.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/functional.h: std::function<> support 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #pragma once 11 | 12 | #include "pybind11.h" 13 | #include 14 | 15 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 16 | NAMESPACE_BEGIN(detail) 17 | 18 | template 19 | struct type_caster> { 20 | using type = std::function; 21 | using retval_type = conditional_t::value, void_type, Return>; 22 | using function_type = Return (*) (Args...); 23 | 24 | public: 25 | bool load(handle src, bool convert) { 26 | if (src.is_none()) { 27 | // Defer accepting None to other overloads (if we aren't in convert mode): 28 | if (!convert) return false; 29 | return true; 30 | } 31 | 32 | if (!isinstance(src)) 33 | return false; 34 | 35 | auto func = reinterpret_borrow(src); 36 | 37 | /* 38 | When passing a C++ function as an argument to another C++ 39 | function via Python, every function call would normally involve 40 | a full C++ -> Python -> C++ roundtrip, which can be prohibitive. 41 | Here, we try to at least detect the case where the function is 42 | stateless (i.e. function pointer or lambda function without 43 | captured variables), in which case the roundtrip can be avoided. 44 | */ 45 | if (auto cfunc = func.cpp_function()) { 46 | auto c = reinterpret_borrow(PyCFunction_GET_SELF(cfunc.ptr())); 47 | auto rec = (function_record *) c; 48 | 49 | if (rec && rec->is_stateless && 50 | same_type(typeid(function_type), *reinterpret_cast(rec->data[1]))) { 51 | struct capture { function_type f; }; 52 | value = ((capture *) &rec->data)->f; 53 | return true; 54 | } 55 | } 56 | 57 | // ensure GIL is held during functor destruction 58 | struct func_handle { 59 | function f; 60 | func_handle(function&& f_) : f(std::move(f_)) {} 61 | func_handle(const func_handle&) = default; 62 | ~func_handle() { 63 | gil_scoped_acquire acq; 64 | function kill_f(std::move(f)); 65 | } 66 | }; 67 | 68 | // to emulate 'move initialization capture' in C++11 69 | struct func_wrapper { 70 | func_handle hfunc; 71 | func_wrapper(func_handle&& hf): hfunc(std::move(hf)) {} 72 | Return operator()(Args... args) const { 73 | gil_scoped_acquire acq; 74 | object retval(hfunc.f(std::forward(args)...)); 75 | /* Visual studio 2015 parser issue: need parentheses around this expression */ 76 | return (retval.template cast()); 77 | } 78 | }; 79 | 80 | value = func_wrapper(func_handle(std::move(func))); 81 | return true; 82 | } 83 | 84 | template 85 | static handle cast(Func &&f_, return_value_policy policy, handle /* parent */) { 86 | if (!f_) 87 | return none().inc_ref(); 88 | 89 | auto result = f_.template target(); 90 | if (result) 91 | return cpp_function(*result, policy).release(); 92 | else 93 | return cpp_function(std::forward(f_), policy).release(); 94 | } 95 | 96 | PYBIND11_TYPE_CASTER(type, _("Callable[[") + concat(make_caster::name...) + _("], ") 97 | + make_caster::name + _("]")); 98 | }; 99 | 100 | NAMESPACE_END(detail) 101 | NAMESPACE_END(PYBIND11_NAMESPACE) 102 | -------------------------------------------------------------------------------- /ATT/pybind11-master/include/pybind11/options.h: -------------------------------------------------------------------------------- 1 | /* 2 | pybind11/options.h: global settings that are configurable at runtime. 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #pragma once 11 | 12 | #include "detail/common.h" 13 | 14 | NAMESPACE_BEGIN(PYBIND11_NAMESPACE) 15 | 16 | class options { 17 | public: 18 | 19 | // Default RAII constructor, which leaves settings as they currently are. 20 | options() : previous_state(global_state()) {} 21 | 22 | // Class is non-copyable. 23 | options(const options&) = delete; 24 | options& operator=(const options&) = delete; 25 | 26 | // Destructor, which restores settings that were in effect before. 27 | ~options() { 28 | global_state() = previous_state; 29 | } 30 | 31 | // Setter methods (affect the global state): 32 | 33 | options& disable_user_defined_docstrings() & { global_state().show_user_defined_docstrings = false; return *this; } 34 | 35 | options& enable_user_defined_docstrings() & { global_state().show_user_defined_docstrings = true; return *this; } 36 | 37 | options& disable_function_signatures() & { global_state().show_function_signatures = false; return *this; } 38 | 39 | options& enable_function_signatures() & { global_state().show_function_signatures = true; return *this; } 40 | 41 | // Getter methods (return the global state): 42 | 43 | static bool show_user_defined_docstrings() { return global_state().show_user_defined_docstrings; } 44 | 45 | static bool show_function_signatures() { return global_state().show_function_signatures; } 46 | 47 | // This type is not meant to be allocated on the heap. 48 | void* operator new(size_t) = delete; 49 | 50 | private: 51 | 52 | struct state { 53 | bool show_user_defined_docstrings = true; //< Include user-supplied texts in docstrings. 54 | bool show_function_signatures = true; //< Include auto-generated function signatures in docstrings. 55 | }; 56 | 57 | static state &global_state() { 58 | static state instance; 59 | return instance; 60 | } 61 | 62 | state previous_state; 63 | }; 64 | 65 | NAMESPACE_END(PYBIND11_NAMESPACE) 66 | -------------------------------------------------------------------------------- /ATT/pybind11-master/pybind11/__init__.py: -------------------------------------------------------------------------------- 1 | from ._version import version_info, __version__ # noqa: F401 imported but unused 2 | 3 | 4 | def get_include(user=False): 5 | import os 6 | d = os.path.dirname(__file__) 7 | if os.path.exists(os.path.join(d, "include")): 8 | # Package is installed 9 | return os.path.join(d, "include") 10 | else: 11 | # Package is from a source directory 12 | return os.path.join(os.path.dirname(d), "include") 13 | -------------------------------------------------------------------------------- /ATT/pybind11-master/pybind11/__main__.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import argparse 4 | import sys 5 | import sysconfig 6 | 7 | from . import get_include 8 | 9 | 10 | def print_includes(): 11 | dirs = [sysconfig.get_path('include'), 12 | sysconfig.get_path('platinclude'), 13 | get_include()] 14 | 15 | # Make unique but preserve order 16 | unique_dirs = [] 17 | for d in dirs: 18 | if d not in unique_dirs: 19 | unique_dirs.append(d) 20 | 21 | print(' '.join('-I' + d for d in unique_dirs)) 22 | 23 | 24 | def main(): 25 | parser = argparse.ArgumentParser(prog='python -m pybind11') 26 | parser.add_argument('--includes', action='store_true', 27 | help='Include flags for both pybind11 and Python headers.') 28 | args = parser.parse_args() 29 | if not sys.argv[1:]: 30 | parser.print_help() 31 | if args.includes: 32 | print_includes() 33 | 34 | 35 | if __name__ == '__main__': 36 | main() 37 | -------------------------------------------------------------------------------- /ATT/pybind11-master/pybind11/_version.py: -------------------------------------------------------------------------------- 1 | version_info = (2, 5, 'dev1') 2 | __version__ = '.'.join(map(str, version_info)) 3 | -------------------------------------------------------------------------------- /ATT/pybind11-master/setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal=1 3 | 4 | [flake8] 5 | max-line-length = 99 6 | show_source = True 7 | exclude = .git, __pycache__, build, dist, docs, tools, venv 8 | ignore = 9 | # required for pretty matrix formatting: multiple spaces after `,` and `[` 10 | E201, E241, W504, 11 | # camelcase 'cPickle' imported as lowercase 'pickle' 12 | N813 13 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/cross_module_gil_utils.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/cross_module_gil_utils.cpp -- tools for acquiring GIL from a different module 3 | 4 | Copyright (c) 2019 Google LLC 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | #include 10 | #include 11 | 12 | // This file mimics a DSO that makes pybind11 calls but does not define a 13 | // PYBIND11_MODULE. The purpose is to test that such a DSO can create a 14 | // py::gil_scoped_acquire when the running thread is in a GIL-released state. 15 | // 16 | // Note that we define a Python module here for convenience, but in general 17 | // this need not be the case. The typical scenario would be a DSO that implements 18 | // shared logic used internally by multiple pybind11 modules. 19 | 20 | namespace { 21 | 22 | namespace py = pybind11; 23 | void gil_acquire() { py::gil_scoped_acquire gil; } 24 | 25 | constexpr char kModuleName[] = "cross_module_gil_utils"; 26 | 27 | #if PY_MAJOR_VERSION >= 3 28 | struct PyModuleDef moduledef = { 29 | PyModuleDef_HEAD_INIT, 30 | kModuleName, 31 | NULL, 32 | 0, 33 | NULL, 34 | NULL, 35 | NULL, 36 | NULL, 37 | NULL 38 | }; 39 | #else 40 | PyMethodDef module_methods[] = { 41 | {NULL, NULL, 0, NULL} 42 | }; 43 | #endif 44 | 45 | } // namespace 46 | 47 | extern "C" PYBIND11_EXPORT 48 | #if PY_MAJOR_VERSION >= 3 49 | PyObject* PyInit_cross_module_gil_utils() 50 | #else 51 | void initcross_module_gil_utils() 52 | #endif 53 | { 54 | 55 | PyObject* m = 56 | #if PY_MAJOR_VERSION >= 3 57 | PyModule_Create(&moduledef); 58 | #else 59 | Py_InitModule(kModuleName, module_methods); 60 | #endif 61 | 62 | if (m != NULL) { 63 | static_assert( 64 | sizeof(&gil_acquire) == sizeof(void*), 65 | "Function pointer must have the same size as void*"); 66 | PyModule_AddObject(m, "gil_acquire_funcaddr", 67 | PyLong_FromVoidPtr(reinterpret_cast(&gil_acquire))); 68 | } 69 | 70 | #if PY_MAJOR_VERSION >= 3 71 | return m; 72 | #endif 73 | } 74 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/local_bindings.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "pybind11_tests.h" 3 | 4 | /// Simple class used to test py::local: 5 | template class LocalBase { 6 | public: 7 | LocalBase(int i) : i(i) { } 8 | int i = -1; 9 | }; 10 | 11 | /// Registered with py::module_local in both main and secondary modules: 12 | using LocalType = LocalBase<0>; 13 | /// Registered without py::module_local in both modules: 14 | using NonLocalType = LocalBase<1>; 15 | /// A second non-local type (for stl_bind tests): 16 | using NonLocal2 = LocalBase<2>; 17 | /// Tests within-module, different-compilation-unit local definition conflict: 18 | using LocalExternal = LocalBase<3>; 19 | /// Mixed: registered local first, then global 20 | using MixedLocalGlobal = LocalBase<4>; 21 | /// Mixed: global first, then local 22 | using MixedGlobalLocal = LocalBase<5>; 23 | 24 | /// Registered with py::module_local only in the secondary module: 25 | using ExternalType1 = LocalBase<6>; 26 | using ExternalType2 = LocalBase<7>; 27 | 28 | using LocalVec = std::vector; 29 | using LocalVec2 = std::vector; 30 | using LocalMap = std::unordered_map; 31 | using NonLocalVec = std::vector; 32 | using NonLocalVec2 = std::vector; 33 | using NonLocalMap = std::unordered_map; 34 | using NonLocalMap2 = std::unordered_map; 35 | 36 | PYBIND11_MAKE_OPAQUE(LocalVec); 37 | PYBIND11_MAKE_OPAQUE(LocalVec2); 38 | PYBIND11_MAKE_OPAQUE(LocalMap); 39 | PYBIND11_MAKE_OPAQUE(NonLocalVec); 40 | //PYBIND11_MAKE_OPAQUE(NonLocalVec2); // same type as LocalVec2 41 | PYBIND11_MAKE_OPAQUE(NonLocalMap); 42 | PYBIND11_MAKE_OPAQUE(NonLocalMap2); 43 | 44 | 45 | // Simple bindings (used with the above): 46 | template 47 | py::class_ bind_local(Args && ...args) { 48 | return py::class_(std::forward(args)...) 49 | .def(py::init()) 50 | .def("get", [](T &i) { return i.i + Adjust; }); 51 | }; 52 | 53 | // Simulate a foreign library base class (to match the example in the docs): 54 | namespace pets { 55 | class Pet { 56 | public: 57 | Pet(std::string name) : name_(name) {} 58 | std::string name_; 59 | const std::string &name() { return name_; } 60 | }; 61 | } 62 | 63 | struct MixGL { int i; MixGL(int i) : i{i} {} }; 64 | struct MixGL2 { int i; MixGL2(int i) : i{i} {} }; 65 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/pybind11_tests.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/pybind11_tests.cpp -- pybind example plugin 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | #include "constructor_stats.h" 12 | 13 | #include 14 | #include 15 | 16 | /* 17 | For testing purposes, we define a static global variable here in a function that each individual 18 | test .cpp calls with its initialization lambda. It's convenient here because we can just not 19 | compile some test files to disable/ignore some of the test code. 20 | 21 | It is NOT recommended as a way to use pybind11 in practice, however: the initialization order will 22 | be essentially random, which is okay for our test scripts (there are no dependencies between the 23 | individual pybind11 test .cpp files), but most likely not what you want when using pybind11 24 | productively. 25 | 26 | Instead, see the "How can I reduce the build time?" question in the "Frequently asked questions" 27 | section of the documentation for good practice on splitting binding code over multiple files. 28 | */ 29 | std::list> &initializers() { 30 | static std::list> inits; 31 | return inits; 32 | } 33 | 34 | test_initializer::test_initializer(Initializer init) { 35 | initializers().push_back(init); 36 | } 37 | 38 | test_initializer::test_initializer(const char *submodule_name, Initializer init) { 39 | initializers().push_back([=](py::module &parent) { 40 | auto m = parent.def_submodule(submodule_name); 41 | init(m); 42 | }); 43 | } 44 | 45 | void bind_ConstructorStats(py::module &m) { 46 | py::class_(m, "ConstructorStats") 47 | .def("alive", &ConstructorStats::alive) 48 | .def("values", &ConstructorStats::values) 49 | .def_readwrite("default_constructions", &ConstructorStats::default_constructions) 50 | .def_readwrite("copy_assignments", &ConstructorStats::copy_assignments) 51 | .def_readwrite("move_assignments", &ConstructorStats::move_assignments) 52 | .def_readwrite("copy_constructions", &ConstructorStats::copy_constructions) 53 | .def_readwrite("move_constructions", &ConstructorStats::move_constructions) 54 | .def_static("get", (ConstructorStats &(*)(py::object)) &ConstructorStats::get, py::return_value_policy::reference_internal) 55 | 56 | // Not exactly ConstructorStats, but related: expose the internal pybind number of registered instances 57 | // to allow instance cleanup checks (invokes a GC first) 58 | .def_static("detail_reg_inst", []() { 59 | ConstructorStats::gc(); 60 | return py::detail::get_internals().registered_instances.size(); 61 | }) 62 | ; 63 | } 64 | 65 | PYBIND11_MODULE(pybind11_tests, m) { 66 | m.doc() = "pybind11 test module"; 67 | 68 | bind_ConstructorStats(m); 69 | 70 | #if !defined(NDEBUG) 71 | m.attr("debug_enabled") = true; 72 | #else 73 | m.attr("debug_enabled") = false; 74 | #endif 75 | 76 | py::class_(m, "UserType", "A `py::class_` type for testing") 77 | .def(py::init<>()) 78 | .def(py::init()) 79 | .def("get_value", &UserType::value, "Get value using a method") 80 | .def("set_value", &UserType::set, "Set value using a method") 81 | .def_property("value", &UserType::value, &UserType::set, "Get/set value using a property") 82 | .def("__repr__", [](const UserType& u) { return "UserType({})"_s.format(u.value()); }); 83 | 84 | py::class_(m, "IncType") 85 | .def(py::init<>()) 86 | .def(py::init()) 87 | .def("__repr__", [](const IncType& u) { return "IncType({})"_s.format(u.value()); }); 88 | 89 | for (const auto &initializer : initializers()) 90 | initializer(m); 91 | 92 | if (!py::hasattr(m, "have_eigen")) m.attr("have_eigen") = false; 93 | } 94 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/pybind11_tests.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | #if defined(_MSC_VER) && _MSC_VER < 1910 5 | // We get some really long type names here which causes MSVC 2015 to emit warnings 6 | # pragma warning(disable: 4503) // warning C4503: decorated name length exceeded, name was truncated 7 | #endif 8 | 9 | namespace py = pybind11; 10 | using namespace pybind11::literals; 11 | 12 | class test_initializer { 13 | using Initializer = void (*)(py::module &); 14 | 15 | public: 16 | test_initializer(Initializer init); 17 | test_initializer(const char *submodule_name, Initializer init); 18 | }; 19 | 20 | #define TEST_SUBMODULE(name, variable) \ 21 | void test_submodule_##name(py::module &); \ 22 | test_initializer name(#name, test_submodule_##name); \ 23 | void test_submodule_##name(py::module &variable) 24 | 25 | 26 | /// Dummy type which is not exported anywhere -- something to trigger a conversion error 27 | struct UnregisteredType { }; 28 | 29 | /// A user-defined type which is exported and can be used by any test 30 | class UserType { 31 | public: 32 | UserType() = default; 33 | UserType(int i) : i(i) { } 34 | 35 | int value() const { return i; } 36 | void set(int set) { i = set; } 37 | 38 | private: 39 | int i = -1; 40 | }; 41 | 42 | /// Like UserType, but increments `value` on copy for quick reference vs. copy tests 43 | class IncType : public UserType { 44 | public: 45 | using UserType::UserType; 46 | IncType() = default; 47 | IncType(const IncType &other) : IncType(other.value() + 1) { } 48 | IncType(IncType &&) = delete; 49 | IncType &operator=(const IncType &) = delete; 50 | IncType &operator=(IncType &&) = delete; 51 | }; 52 | 53 | /// Custom cast-only type that casts to a string "rvalue" or "lvalue" depending on the cast context. 54 | /// Used to test recursive casters (e.g. std::tuple, stl containers). 55 | struct RValueCaster {}; 56 | NAMESPACE_BEGIN(pybind11) 57 | NAMESPACE_BEGIN(detail) 58 | template<> class type_caster { 59 | public: 60 | PYBIND11_TYPE_CASTER(RValueCaster, _("RValueCaster")); 61 | static handle cast(RValueCaster &&, return_value_policy, handle) { return py::str("rvalue").release(); } 62 | static handle cast(const RValueCaster &, return_value_policy, handle) { return py::str("lvalue").release(); } 63 | }; 64 | NAMESPACE_END(detail) 65 | NAMESPACE_END(pybind11) 66 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | minversion = 3.0 3 | norecursedirs = test_cmake_build test_embed 4 | addopts = 5 | # show summary of skipped tests 6 | -rs 7 | # capture only Python print and C++ py::print, but not C output (low-level Python errors) 8 | --capture=sys 9 | filterwarnings = 10 | # make warnings into errors but ignore certain third-party extension issues 11 | error 12 | # importing scipy submodules on some version of Python 13 | ignore::ImportWarning 14 | # bogus numpy ABI warning (see numpy/#432) 15 | ignore:.*numpy.dtype size changed.*:RuntimeWarning 16 | ignore:.*numpy.ufunc size changed.*:RuntimeWarning 17 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_async.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_async.cpp -- __await__ support 3 | 4 | Copyright (c) 2019 Google Inc. 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | 12 | TEST_SUBMODULE(async_module, m) { 13 | struct DoesNotSupportAsync {}; 14 | py::class_(m, "DoesNotSupportAsync") 15 | .def(py::init<>()); 16 | struct SupportsAsync {}; 17 | py::class_(m, "SupportsAsync") 18 | .def(py::init<>()) 19 | .def("__await__", [](const SupportsAsync& self) -> py::object { 20 | static_cast(self); 21 | py::object loop = py::module::import("asyncio.events").attr("get_event_loop")(); 22 | py::object f = loop.attr("create_future")(); 23 | f.attr("set_result")(5); 24 | return f.attr("__await__")(); 25 | }); 26 | } 27 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_async.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import pytest 3 | from pybind11_tests import async_module as m 4 | 5 | 6 | @pytest.fixture 7 | def event_loop(): 8 | loop = asyncio.new_event_loop() 9 | yield loop 10 | loop.close() 11 | 12 | 13 | async def get_await_result(x): 14 | return await x 15 | 16 | 17 | def test_await(event_loop): 18 | assert 5 == event_loop.run_until_complete(get_await_result(m.SupportsAsync())) 19 | 20 | 21 | def test_await_missing(event_loop): 22 | with pytest.raises(TypeError): 23 | event_loop.run_until_complete(get_await_result(m.DoesNotSupportAsync())) 24 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_buffers.py: -------------------------------------------------------------------------------- 1 | import io 2 | import struct 3 | import sys 4 | 5 | import pytest 6 | 7 | from pybind11_tests import buffers as m 8 | from pybind11_tests import ConstructorStats 9 | 10 | PY3 = sys.version_info[0] >= 3 11 | 12 | pytestmark = pytest.requires_numpy 13 | 14 | with pytest.suppress(ImportError): 15 | import numpy as np 16 | 17 | 18 | def test_from_python(): 19 | with pytest.raises(RuntimeError) as excinfo: 20 | m.Matrix(np.array([1, 2, 3])) # trying to assign a 1D array 21 | assert str(excinfo.value) == "Incompatible buffer format!" 22 | 23 | m3 = np.array([[1, 2, 3], [4, 5, 6]]).astype(np.float32) 24 | m4 = m.Matrix(m3) 25 | 26 | for i in range(m4.rows()): 27 | for j in range(m4.cols()): 28 | assert m3[i, j] == m4[i, j] 29 | 30 | cstats = ConstructorStats.get(m.Matrix) 31 | assert cstats.alive() == 1 32 | del m3, m4 33 | assert cstats.alive() == 0 34 | assert cstats.values() == ["2x3 matrix"] 35 | assert cstats.copy_constructions == 0 36 | # assert cstats.move_constructions >= 0 # Don't invoke any 37 | assert cstats.copy_assignments == 0 38 | assert cstats.move_assignments == 0 39 | 40 | 41 | # PyPy: Memory leak in the "np.array(m, copy=False)" call 42 | # https://bitbucket.org/pypy/pypy/issues/2444 43 | @pytest.unsupported_on_pypy 44 | def test_to_python(): 45 | mat = m.Matrix(5, 4) 46 | assert memoryview(mat).shape == (5, 4) 47 | 48 | assert mat[2, 3] == 0 49 | mat[2, 3] = 4.0 50 | mat[3, 2] = 7.0 51 | assert mat[2, 3] == 4 52 | assert mat[3, 2] == 7 53 | assert struct.unpack_from('f', mat, (3 * 4 + 2) * 4) == (7, ) 54 | assert struct.unpack_from('f', mat, (2 * 4 + 3) * 4) == (4, ) 55 | 56 | mat2 = np.array(mat, copy=False) 57 | assert mat2.shape == (5, 4) 58 | assert abs(mat2).sum() == 11 59 | assert mat2[2, 3] == 4 and mat2[3, 2] == 7 60 | mat2[2, 3] = 5 61 | assert mat2[2, 3] == 5 62 | 63 | cstats = ConstructorStats.get(m.Matrix) 64 | assert cstats.alive() == 1 65 | del mat 66 | pytest.gc_collect() 67 | assert cstats.alive() == 1 68 | del mat2 # holds a mat reference 69 | pytest.gc_collect() 70 | assert cstats.alive() == 0 71 | assert cstats.values() == ["5x4 matrix"] 72 | assert cstats.copy_constructions == 0 73 | # assert cstats.move_constructions >= 0 # Don't invoke any 74 | assert cstats.copy_assignments == 0 75 | assert cstats.move_assignments == 0 76 | 77 | 78 | @pytest.unsupported_on_pypy 79 | def test_inherited_protocol(): 80 | """SquareMatrix is derived from Matrix and inherits the buffer protocol""" 81 | 82 | matrix = m.SquareMatrix(5) 83 | assert memoryview(matrix).shape == (5, 5) 84 | assert np.asarray(matrix).shape == (5, 5) 85 | 86 | 87 | @pytest.unsupported_on_pypy 88 | def test_pointer_to_member_fn(): 89 | for cls in [m.Buffer, m.ConstBuffer, m.DerivedBuffer]: 90 | buf = cls() 91 | buf.value = 0x12345678 92 | value = struct.unpack('i', bytearray(buf))[0] 93 | assert value == 0x12345678 94 | 95 | 96 | @pytest.unsupported_on_pypy 97 | def test_readonly_buffer(): 98 | buf = m.BufferReadOnly(0x64) 99 | view = memoryview(buf) 100 | assert view[0] == 0x64 if PY3 else b'd' 101 | assert view.readonly 102 | 103 | 104 | @pytest.unsupported_on_pypy 105 | def test_selective_readonly_buffer(): 106 | buf = m.BufferReadOnlySelect() 107 | 108 | memoryview(buf)[0] = 0x64 if PY3 else b'd' 109 | assert buf.value == 0x64 110 | 111 | io.BytesIO(b'A').readinto(buf) 112 | assert buf.value == ord(b'A') 113 | 114 | buf.readonly = True 115 | with pytest.raises(TypeError): 116 | memoryview(buf)[0] = 0 if PY3 else b'\0' 117 | with pytest.raises(TypeError): 118 | io.BytesIO(b'1').readinto(buf) 119 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_call_policies.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_call_policies.cpp -- keep_alive and call_guard 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | 12 | struct CustomGuard { 13 | static bool enabled; 14 | 15 | CustomGuard() { enabled = true; } 16 | ~CustomGuard() { enabled = false; } 17 | 18 | static const char *report_status() { return enabled ? "guarded" : "unguarded"; } 19 | }; 20 | bool CustomGuard::enabled = false; 21 | 22 | struct DependentGuard { 23 | static bool enabled; 24 | 25 | DependentGuard() { enabled = CustomGuard::enabled; } 26 | ~DependentGuard() { enabled = false; } 27 | 28 | static const char *report_status() { return enabled ? "guarded" : "unguarded"; } 29 | }; 30 | bool DependentGuard::enabled = false; 31 | 32 | TEST_SUBMODULE(call_policies, m) { 33 | // Parent/Child are used in: 34 | // test_keep_alive_argument, test_keep_alive_return_value, test_alive_gc_derived, 35 | // test_alive_gc_multi_derived, test_return_none, test_keep_alive_constructor 36 | class Child { 37 | public: 38 | Child() { py::print("Allocating child."); } 39 | Child(const Child &) = default; 40 | Child(Child &&) = default; 41 | ~Child() { py::print("Releasing child."); } 42 | }; 43 | py::class_(m, "Child") 44 | .def(py::init<>()); 45 | 46 | class Parent { 47 | public: 48 | Parent() { py::print("Allocating parent."); } 49 | ~Parent() { py::print("Releasing parent."); } 50 | void addChild(Child *) { } 51 | Child *returnChild() { return new Child(); } 52 | Child *returnNullChild() { return nullptr; } 53 | }; 54 | py::class_(m, "Parent") 55 | .def(py::init<>()) 56 | .def(py::init([](Child *) { return new Parent(); }), py::keep_alive<1, 2>()) 57 | .def("addChild", &Parent::addChild) 58 | .def("addChildKeepAlive", &Parent::addChild, py::keep_alive<1, 2>()) 59 | .def("returnChild", &Parent::returnChild) 60 | .def("returnChildKeepAlive", &Parent::returnChild, py::keep_alive<1, 0>()) 61 | .def("returnNullChildKeepAliveChild", &Parent::returnNullChild, py::keep_alive<1, 0>()) 62 | .def("returnNullChildKeepAliveParent", &Parent::returnNullChild, py::keep_alive<0, 1>()); 63 | 64 | #if !defined(PYPY_VERSION) 65 | // test_alive_gc 66 | class ParentGC : public Parent { 67 | public: 68 | using Parent::Parent; 69 | }; 70 | py::class_(m, "ParentGC", py::dynamic_attr()) 71 | .def(py::init<>()); 72 | #endif 73 | 74 | // test_call_guard 75 | m.def("unguarded_call", &CustomGuard::report_status); 76 | m.def("guarded_call", &CustomGuard::report_status, py::call_guard()); 77 | 78 | m.def("multiple_guards_correct_order", []() { 79 | return CustomGuard::report_status() + std::string(" & ") + DependentGuard::report_status(); 80 | }, py::call_guard()); 81 | 82 | m.def("multiple_guards_wrong_order", []() { 83 | return DependentGuard::report_status() + std::string(" & ") + CustomGuard::report_status(); 84 | }, py::call_guard()); 85 | 86 | #if defined(WITH_THREAD) && !defined(PYPY_VERSION) 87 | // `py::call_guard()` should work in PyPy as well, 88 | // but it's unclear how to test it without `PyGILState_GetThisThreadState`. 89 | auto report_gil_status = []() { 90 | auto is_gil_held = false; 91 | if (auto tstate = py::detail::get_thread_state_unchecked()) 92 | is_gil_held = (tstate == PyGILState_GetThisThreadState()); 93 | 94 | return is_gil_held ? "GIL held" : "GIL released"; 95 | }; 96 | 97 | m.def("with_gil", report_gil_status); 98 | m.def("without_gil", report_gil_status, py::call_guard()); 99 | #endif 100 | } 101 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_callbacks.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from pybind11_tests import callbacks as m 3 | from threading import Thread 4 | 5 | 6 | def test_callbacks(): 7 | from functools import partial 8 | 9 | def func1(): 10 | return "func1" 11 | 12 | def func2(a, b, c, d): 13 | return "func2", a, b, c, d 14 | 15 | def func3(a): 16 | return "func3({})".format(a) 17 | 18 | assert m.test_callback1(func1) == "func1" 19 | assert m.test_callback2(func2) == ("func2", "Hello", "x", True, 5) 20 | assert m.test_callback1(partial(func2, 1, 2, 3, 4)) == ("func2", 1, 2, 3, 4) 21 | assert m.test_callback1(partial(func3, "partial")) == "func3(partial)" 22 | assert m.test_callback3(lambda i: i + 1) == "func(43) = 44" 23 | 24 | f = m.test_callback4() 25 | assert f(43) == 44 26 | f = m.test_callback5() 27 | assert f(number=43) == 44 28 | 29 | 30 | def test_bound_method_callback(): 31 | # Bound Python method: 32 | class MyClass: 33 | def double(self, val): 34 | return 2 * val 35 | 36 | z = MyClass() 37 | assert m.test_callback3(z.double) == "func(43) = 86" 38 | 39 | z = m.CppBoundMethodTest() 40 | assert m.test_callback3(z.triple) == "func(43) = 129" 41 | 42 | 43 | def test_keyword_args_and_generalized_unpacking(): 44 | 45 | def f(*args, **kwargs): 46 | return args, kwargs 47 | 48 | assert m.test_tuple_unpacking(f) == (("positional", 1, 2, 3, 4, 5, 6), {}) 49 | assert m.test_dict_unpacking(f) == (("positional", 1), {"key": "value", "a": 1, "b": 2}) 50 | assert m.test_keyword_args(f) == ((), {"x": 10, "y": 20}) 51 | assert m.test_unpacking_and_keywords1(f) == ((1, 2), {"c": 3, "d": 4}) 52 | assert m.test_unpacking_and_keywords2(f) == ( 53 | ("positional", 1, 2, 3, 4, 5), 54 | {"key": "value", "a": 1, "b": 2, "c": 3, "d": 4, "e": 5} 55 | ) 56 | 57 | with pytest.raises(TypeError) as excinfo: 58 | m.test_unpacking_error1(f) 59 | assert "Got multiple values for keyword argument" in str(excinfo.value) 60 | 61 | with pytest.raises(TypeError) as excinfo: 62 | m.test_unpacking_error2(f) 63 | assert "Got multiple values for keyword argument" in str(excinfo.value) 64 | 65 | with pytest.raises(RuntimeError) as excinfo: 66 | m.test_arg_conversion_error1(f) 67 | assert "Unable to convert call argument" in str(excinfo.value) 68 | 69 | with pytest.raises(RuntimeError) as excinfo: 70 | m.test_arg_conversion_error2(f) 71 | assert "Unable to convert call argument" in str(excinfo.value) 72 | 73 | 74 | def test_lambda_closure_cleanup(): 75 | m.test_cleanup() 76 | cstats = m.payload_cstats() 77 | assert cstats.alive() == 0 78 | assert cstats.copy_constructions == 1 79 | assert cstats.move_constructions >= 1 80 | 81 | 82 | def test_cpp_function_roundtrip(): 83 | """Test if passing a function pointer from C++ -> Python -> C++ yields the original pointer""" 84 | 85 | assert m.test_dummy_function(m.dummy_function) == "matches dummy_function: eval(1) = 2" 86 | assert (m.test_dummy_function(m.roundtrip(m.dummy_function)) == 87 | "matches dummy_function: eval(1) = 2") 88 | assert m.roundtrip(None, expect_none=True) is None 89 | assert (m.test_dummy_function(lambda x: x + 2) == 90 | "can't convert to function pointer: eval(1) = 3") 91 | 92 | with pytest.raises(TypeError) as excinfo: 93 | m.test_dummy_function(m.dummy_function2) 94 | assert "incompatible function arguments" in str(excinfo.value) 95 | 96 | with pytest.raises(TypeError) as excinfo: 97 | m.test_dummy_function(lambda x, y: x + y) 98 | assert any(s in str(excinfo.value) for s in ("missing 1 required positional argument", 99 | "takes exactly 2 arguments")) 100 | 101 | 102 | def test_function_signatures(doc): 103 | assert doc(m.test_callback3) == "test_callback3(arg0: Callable[[int], int]) -> str" 104 | assert doc(m.test_callback4) == "test_callback4() -> Callable[[int], int]" 105 | 106 | 107 | def test_movable_object(): 108 | assert m.callback_with_movable(lambda _: None) is True 109 | 110 | 111 | def test_async_callbacks(): 112 | # serves as state for async callback 113 | class Item: 114 | def __init__(self, value): 115 | self.value = value 116 | 117 | res = [] 118 | 119 | # generate stateful lambda that will store result in `res` 120 | def gen_f(): 121 | s = Item(3) 122 | return lambda j: res.append(s.value + j) 123 | 124 | # do some work async 125 | work = [1, 2, 3, 4] 126 | m.test_async_callback(gen_f(), work) 127 | # wait until work is done 128 | from time import sleep 129 | sleep(0.5) 130 | assert sum(res) == sum([x + 3 for x in work]) 131 | 132 | 133 | def test_async_async_callbacks(): 134 | t = Thread(target=test_async_callbacks) 135 | t.start() 136 | t.join() 137 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_chrono.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_chrono.cpp -- test conversions to/from std::chrono types 3 | 4 | Copyright (c) 2016 Trent Houliston and 5 | Wenzel Jakob 6 | 7 | All rights reserved. Use of this source code is governed by a 8 | BSD-style license that can be found in the LICENSE file. 9 | */ 10 | 11 | #include "pybind11_tests.h" 12 | #include 13 | 14 | TEST_SUBMODULE(chrono, m) { 15 | using system_time = std::chrono::system_clock::time_point; 16 | using steady_time = std::chrono::steady_clock::time_point; 17 | 18 | using timespan = std::chrono::duration; 19 | using timestamp = std::chrono::time_point; 20 | 21 | // test_chrono_system_clock 22 | // Return the current time off the wall clock 23 | m.def("test_chrono1", []() { return std::chrono::system_clock::now(); }); 24 | 25 | // test_chrono_system_clock_roundtrip 26 | // Round trip the passed in system clock time 27 | m.def("test_chrono2", [](system_time t) { return t; }); 28 | 29 | // test_chrono_duration_roundtrip 30 | // Round trip the passed in duration 31 | m.def("test_chrono3", [](std::chrono::system_clock::duration d) { return d; }); 32 | 33 | // test_chrono_duration_subtraction_equivalence 34 | // Difference between two passed in time_points 35 | m.def("test_chrono4", [](system_time a, system_time b) { return a - b; }); 36 | 37 | // test_chrono_steady_clock 38 | // Return the current time off the steady_clock 39 | m.def("test_chrono5", []() { return std::chrono::steady_clock::now(); }); 40 | 41 | // test_chrono_steady_clock_roundtrip 42 | // Round trip a steady clock timepoint 43 | m.def("test_chrono6", [](steady_time t) { return t; }); 44 | 45 | // test_floating_point_duration 46 | // Roundtrip a duration in microseconds from a float argument 47 | m.def("test_chrono7", [](std::chrono::microseconds t) { return t; }); 48 | // Float durations (issue #719) 49 | m.def("test_chrono_float_diff", [](std::chrono::duration a, std::chrono::duration b) { 50 | return a - b; }); 51 | 52 | m.def("test_nano_timepoint", [](timestamp start, timespan delta) -> timestamp { 53 | return start + delta; 54 | }); 55 | } 56 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_cmake_build/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_custom_target(test_cmake_build) 2 | 3 | if(CMAKE_VERSION VERSION_LESS 3.1) 4 | # 3.0 needed for interface library for subdirectory_target/installed_target 5 | # 3.1 needed for cmake -E env for testing 6 | return() 7 | endif() 8 | 9 | include(CMakeParseArguments) 10 | function(pybind11_add_build_test name) 11 | cmake_parse_arguments(ARG "INSTALL" "" "" ${ARGN}) 12 | 13 | set(build_options "-DCMAKE_PREFIX_PATH=${PROJECT_BINARY_DIR}/mock_install" 14 | "-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}" 15 | "-DPYTHON_EXECUTABLE:FILEPATH=${PYTHON_EXECUTABLE}" 16 | "-DPYBIND11_CPP_STANDARD=${PYBIND11_CPP_STANDARD}") 17 | if(NOT ARG_INSTALL) 18 | list(APPEND build_options "-DPYBIND11_PROJECT_DIR=${PROJECT_SOURCE_DIR}") 19 | endif() 20 | 21 | add_custom_target(test_${name} ${CMAKE_CTEST_COMMAND} 22 | --quiet --output-log ${name}.log 23 | --build-and-test "${CMAKE_CURRENT_SOURCE_DIR}/${name}" 24 | "${CMAKE_CURRENT_BINARY_DIR}/${name}" 25 | --build-config Release 26 | --build-noclean 27 | --build-generator ${CMAKE_GENERATOR} 28 | $<$:--build-generator-platform> ${CMAKE_GENERATOR_PLATFORM} 29 | --build-makeprogram ${CMAKE_MAKE_PROGRAM} 30 | --build-target check 31 | --build-options ${build_options} 32 | ) 33 | if(ARG_INSTALL) 34 | add_dependencies(test_${name} mock_install) 35 | endif() 36 | add_dependencies(test_cmake_build test_${name}) 37 | endfunction() 38 | 39 | pybind11_add_build_test(subdirectory_function) 40 | pybind11_add_build_test(subdirectory_target) 41 | if(NOT ${PYTHON_MODULE_EXTENSION} MATCHES "pypy") 42 | pybind11_add_build_test(subdirectory_embed) 43 | endif() 44 | 45 | if(PYBIND11_INSTALL) 46 | add_custom_target(mock_install ${CMAKE_COMMAND} 47 | "-DCMAKE_INSTALL_PREFIX=${PROJECT_BINARY_DIR}/mock_install" 48 | -P "${PROJECT_BINARY_DIR}/cmake_install.cmake" 49 | ) 50 | 51 | pybind11_add_build_test(installed_function INSTALL) 52 | pybind11_add_build_test(installed_target INSTALL) 53 | if(NOT ${PYTHON_MODULE_EXTENSION} MATCHES "pypy") 54 | pybind11_add_build_test(installed_embed INSTALL) 55 | endif() 56 | endif() 57 | 58 | add_dependencies(check test_cmake_build) 59 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_cmake_build/embed.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | namespace py = pybind11; 3 | 4 | PYBIND11_EMBEDDED_MODULE(test_cmake_build, m) { 5 | m.def("add", [](int i, int j) { return i + j; }); 6 | } 7 | 8 | int main(int argc, char *argv[]) { 9 | if (argc != 2) 10 | throw std::runtime_error("Expected test.py file as the first argument"); 11 | auto test_py_file = argv[1]; 12 | 13 | py::scoped_interpreter guard{}; 14 | 15 | auto m = py::module::import("test_cmake_build"); 16 | if (m.attr("add")(1, 2).cast() != 3) 17 | throw std::runtime_error("embed.cpp failed"); 18 | 19 | py::module::import("sys").attr("argv") = py::make_tuple("test.py", "embed.cpp"); 20 | py::eval_file(test_py_file, py::globals()); 21 | } 22 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_cmake_build/installed_embed/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.0) 2 | project(test_installed_embed CXX) 3 | 4 | set(CMAKE_MODULE_PATH "") 5 | find_package(pybind11 CONFIG REQUIRED) 6 | message(STATUS "Found pybind11 v${pybind11_VERSION}: ${pybind11_INCLUDE_DIRS}") 7 | 8 | add_executable(test_cmake_build ../embed.cpp) 9 | target_link_libraries(test_cmake_build PRIVATE pybind11::embed) 10 | 11 | # Do not treat includes from IMPORTED target as SYSTEM (Python headers in pybind11::embed). 12 | # This may be needed to resolve header conflicts, e.g. between Python release and debug headers. 13 | set_target_properties(test_cmake_build PROPERTIES NO_SYSTEM_FROM_IMPORTED ON) 14 | 15 | add_custom_target(check $ ${PROJECT_SOURCE_DIR}/../test.py) 16 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_cmake_build/installed_function/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.12) 2 | project(test_installed_module CXX) 3 | 4 | set(CMAKE_MODULE_PATH "") 5 | 6 | find_package(pybind11 CONFIG REQUIRED) 7 | message(STATUS "Found pybind11 v${pybind11_VERSION}: ${pybind11_INCLUDE_DIRS}") 8 | 9 | pybind11_add_module(test_cmake_build SHARED NO_EXTRAS ../main.cpp) 10 | 11 | add_custom_target(check ${CMAKE_COMMAND} -E env PYTHONPATH=$ 12 | ${PYTHON_EXECUTABLE} ${PROJECT_SOURCE_DIR}/../test.py ${PROJECT_NAME}) 13 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_cmake_build/installed_target/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.0) 2 | project(test_installed_target CXX) 3 | 4 | set(CMAKE_MODULE_PATH "") 5 | 6 | find_package(pybind11 CONFIG REQUIRED) 7 | message(STATUS "Found pybind11 v${pybind11_VERSION}: ${pybind11_INCLUDE_DIRS}") 8 | 9 | add_library(test_cmake_build MODULE ../main.cpp) 10 | 11 | target_link_libraries(test_cmake_build PRIVATE pybind11::module) 12 | 13 | # make sure result is, for example, test_installed_target.so, not libtest_installed_target.dylib 14 | set_target_properties(test_cmake_build PROPERTIES PREFIX "${PYTHON_MODULE_PREFIX}" 15 | SUFFIX "${PYTHON_MODULE_EXTENSION}") 16 | 17 | # Do not treat includes from IMPORTED target as SYSTEM (Python headers in pybind11::module). 18 | # This may be needed to resolve header conflicts, e.g. between Python release and debug headers. 19 | set_target_properties(test_cmake_build PROPERTIES NO_SYSTEM_FROM_IMPORTED ON) 20 | 21 | add_custom_target(check ${CMAKE_COMMAND} -E env PYTHONPATH=$ 22 | ${PYTHON_EXECUTABLE} ${PROJECT_SOURCE_DIR}/../test.py ${PROJECT_NAME}) 23 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_cmake_build/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | namespace py = pybind11; 3 | 4 | PYBIND11_MODULE(test_cmake_build, m) { 5 | m.def("add", [](int i, int j) { return i + j; }); 6 | } 7 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_cmake_build/subdirectory_embed/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.0) 2 | project(test_subdirectory_embed CXX) 3 | 4 | set(PYBIND11_INSTALL ON CACHE BOOL "") 5 | set(PYBIND11_EXPORT_NAME test_export) 6 | 7 | add_subdirectory(${PYBIND11_PROJECT_DIR} pybind11) 8 | 9 | # Test basic target functionality 10 | add_executable(test_cmake_build ../embed.cpp) 11 | target_link_libraries(test_cmake_build PRIVATE pybind11::embed) 12 | 13 | add_custom_target(check $ ${PROJECT_SOURCE_DIR}/../test.py) 14 | 15 | # Test custom export group -- PYBIND11_EXPORT_NAME 16 | add_library(test_embed_lib ../embed.cpp) 17 | target_link_libraries(test_embed_lib PRIVATE pybind11::embed) 18 | 19 | install(TARGETS test_embed_lib 20 | EXPORT test_export 21 | ARCHIVE DESTINATION bin 22 | LIBRARY DESTINATION lib 23 | RUNTIME DESTINATION lib) 24 | install(EXPORT test_export 25 | DESTINATION lib/cmake/test_export/test_export-Targets.cmake) 26 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_cmake_build/subdirectory_function/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 2.8.12) 2 | project(test_subdirectory_module CXX) 3 | 4 | add_subdirectory(${PYBIND11_PROJECT_DIR} pybind11) 5 | pybind11_add_module(test_cmake_build THIN_LTO ../main.cpp) 6 | 7 | add_custom_target(check ${CMAKE_COMMAND} -E env PYTHONPATH=$ 8 | ${PYTHON_EXECUTABLE} ${PROJECT_SOURCE_DIR}/../test.py ${PROJECT_NAME}) 9 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_cmake_build/subdirectory_target/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.0) 2 | project(test_subdirectory_target CXX) 3 | 4 | add_subdirectory(${PYBIND11_PROJECT_DIR} pybind11) 5 | 6 | add_library(test_cmake_build MODULE ../main.cpp) 7 | 8 | target_link_libraries(test_cmake_build PRIVATE pybind11::module) 9 | 10 | # make sure result is, for example, test_installed_target.so, not libtest_installed_target.dylib 11 | set_target_properties(test_cmake_build PROPERTIES PREFIX "${PYTHON_MODULE_PREFIX}" 12 | SUFFIX "${PYTHON_MODULE_EXTENSION}") 13 | 14 | add_custom_target(check ${CMAKE_COMMAND} -E env PYTHONPATH=$ 15 | ${PYTHON_EXECUTABLE} ${PROJECT_SOURCE_DIR}/../test.py ${PROJECT_NAME}) 16 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_cmake_build/test.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import test_cmake_build 3 | 4 | assert test_cmake_build.add(1, 2) == 3 5 | print("{} imports, runs, and adds: 1 + 2 = 3".format(sys.argv[1])) 6 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_constants_and_functions.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_constants_and_functions.cpp -- global constants and functions, enumerations, raw byte strings 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | 12 | enum MyEnum { EFirstEntry = 1, ESecondEntry }; 13 | 14 | std::string test_function1() { 15 | return "test_function()"; 16 | } 17 | 18 | std::string test_function2(MyEnum k) { 19 | return "test_function(enum=" + std::to_string(k) + ")"; 20 | } 21 | 22 | std::string test_function3(int i) { 23 | return "test_function(" + std::to_string(i) + ")"; 24 | } 25 | 26 | py::str test_function4() { return "test_function()"; } 27 | py::str test_function4(char *) { return "test_function(char *)"; } 28 | py::str test_function4(int, float) { return "test_function(int, float)"; } 29 | py::str test_function4(float, int) { return "test_function(float, int)"; } 30 | 31 | py::bytes return_bytes() { 32 | const char *data = "\x01\x00\x02\x00"; 33 | return std::string(data, 4); 34 | } 35 | 36 | std::string print_bytes(py::bytes bytes) { 37 | std::string ret = "bytes["; 38 | const auto value = static_cast(bytes); 39 | for (size_t i = 0; i < value.length(); ++i) { 40 | ret += std::to_string(static_cast(value[i])) + " "; 41 | } 42 | ret.back() = ']'; 43 | return ret; 44 | } 45 | 46 | // Test that we properly handle C++17 exception specifiers (which are part of the function signature 47 | // in C++17). These should all still work before C++17, but don't affect the function signature. 48 | namespace test_exc_sp { 49 | int f1(int x) noexcept { return x+1; } 50 | int f2(int x) noexcept(true) { return x+2; } 51 | int f3(int x) noexcept(false) { return x+3; } 52 | #if defined(__GNUG__) 53 | # pragma GCC diagnostic push 54 | # pragma GCC diagnostic ignored "-Wdeprecated" 55 | #endif 56 | int f4(int x) throw() { return x+4; } // Deprecated equivalent to noexcept(true) 57 | #if defined(__GNUG__) 58 | # pragma GCC diagnostic pop 59 | #endif 60 | struct C { 61 | int m1(int x) noexcept { return x-1; } 62 | int m2(int x) const noexcept { return x-2; } 63 | int m3(int x) noexcept(true) { return x-3; } 64 | int m4(int x) const noexcept(true) { return x-4; } 65 | int m5(int x) noexcept(false) { return x-5; } 66 | int m6(int x) const noexcept(false) { return x-6; } 67 | #if defined(__GNUG__) 68 | # pragma GCC diagnostic push 69 | # pragma GCC diagnostic ignored "-Wdeprecated" 70 | #endif 71 | int m7(int x) throw() { return x-7; } 72 | int m8(int x) const throw() { return x-8; } 73 | #if defined(__GNUG__) 74 | # pragma GCC diagnostic pop 75 | #endif 76 | }; 77 | } 78 | 79 | 80 | TEST_SUBMODULE(constants_and_functions, m) { 81 | // test_constants 82 | m.attr("some_constant") = py::int_(14); 83 | 84 | // test_function_overloading 85 | m.def("test_function", &test_function1); 86 | m.def("test_function", &test_function2); 87 | m.def("test_function", &test_function3); 88 | 89 | #if defined(PYBIND11_OVERLOAD_CAST) 90 | m.def("test_function", py::overload_cast<>(&test_function4)); 91 | m.def("test_function", py::overload_cast(&test_function4)); 92 | m.def("test_function", py::overload_cast(&test_function4)); 93 | m.def("test_function", py::overload_cast(&test_function4)); 94 | #else 95 | m.def("test_function", static_cast(&test_function4)); 96 | m.def("test_function", static_cast(&test_function4)); 97 | m.def("test_function", static_cast(&test_function4)); 98 | m.def("test_function", static_cast(&test_function4)); 99 | #endif 100 | 101 | py::enum_(m, "MyEnum") 102 | .value("EFirstEntry", EFirstEntry) 103 | .value("ESecondEntry", ESecondEntry) 104 | .export_values(); 105 | 106 | // test_bytes 107 | m.def("return_bytes", &return_bytes); 108 | m.def("print_bytes", &print_bytes); 109 | 110 | // test_exception_specifiers 111 | using namespace test_exc_sp; 112 | py::class_(m, "C") 113 | .def(py::init<>()) 114 | .def("m1", &C::m1) 115 | .def("m2", &C::m2) 116 | .def("m3", &C::m3) 117 | .def("m4", &C::m4) 118 | .def("m5", &C::m5) 119 | .def("m6", &C::m6) 120 | .def("m7", &C::m7) 121 | .def("m8", &C::m8) 122 | ; 123 | m.def("f1", f1); 124 | m.def("f2", f2); 125 | m.def("f3", f3); 126 | m.def("f4", f4); 127 | } 128 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_constants_and_functions.py: -------------------------------------------------------------------------------- 1 | from pybind11_tests import constants_and_functions as m 2 | 3 | 4 | def test_constants(): 5 | assert m.some_constant == 14 6 | 7 | 8 | def test_function_overloading(): 9 | assert m.test_function() == "test_function()" 10 | assert m.test_function(7) == "test_function(7)" 11 | assert m.test_function(m.MyEnum.EFirstEntry) == "test_function(enum=1)" 12 | assert m.test_function(m.MyEnum.ESecondEntry) == "test_function(enum=2)" 13 | 14 | assert m.test_function() == "test_function()" 15 | assert m.test_function("abcd") == "test_function(char *)" 16 | assert m.test_function(1, 1.0) == "test_function(int, float)" 17 | assert m.test_function(1, 1.0) == "test_function(int, float)" 18 | assert m.test_function(2.0, 2) == "test_function(float, int)" 19 | 20 | 21 | def test_bytes(): 22 | assert m.print_bytes(m.return_bytes()) == "bytes[1 0 2 0]" 23 | 24 | 25 | def test_exception_specifiers(): 26 | c = m.C() 27 | assert c.m1(2) == 1 28 | assert c.m2(3) == 1 29 | assert c.m3(5) == 2 30 | assert c.m4(7) == 3 31 | assert c.m5(10) == 5 32 | assert c.m6(14) == 8 33 | assert c.m7(20) == 13 34 | assert c.m8(29) == 21 35 | 36 | assert m.f1(33) == 34 37 | assert m.f2(53) == 55 38 | assert m.f3(86) == 89 39 | assert m.f4(140) == 144 40 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_copy_move.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from pybind11_tests import copy_move_policies as m 3 | 4 | 5 | def test_lacking_copy_ctor(): 6 | with pytest.raises(RuntimeError) as excinfo: 7 | m.lacking_copy_ctor.get_one() 8 | assert "is non-copyable!" in str(excinfo.value) 9 | 10 | 11 | def test_lacking_move_ctor(): 12 | with pytest.raises(RuntimeError) as excinfo: 13 | m.lacking_move_ctor.get_one() 14 | assert "is neither movable nor copyable!" in str(excinfo.value) 15 | 16 | 17 | def test_move_and_copy_casts(): 18 | """Cast some values in C++ via custom type casters and count the number of moves/copies.""" 19 | 20 | cstats = m.move_and_copy_cstats() 21 | c_m, c_mc, c_c = cstats["MoveOnlyInt"], cstats["MoveOrCopyInt"], cstats["CopyOnlyInt"] 22 | 23 | # The type move constructions/assignments below each get incremented: the move assignment comes 24 | # from the type_caster load; the move construction happens when extracting that via a cast or 25 | # loading into an argument. 26 | assert m.move_and_copy_casts(3) == 18 27 | assert c_m.copy_assignments + c_m.copy_constructions == 0 28 | assert c_m.move_assignments == 2 29 | assert c_m.move_constructions >= 2 30 | assert c_mc.alive() == 0 31 | assert c_mc.copy_assignments + c_mc.copy_constructions == 0 32 | assert c_mc.move_assignments == 2 33 | assert c_mc.move_constructions >= 2 34 | assert c_c.alive() == 0 35 | assert c_c.copy_assignments == 2 36 | assert c_c.copy_constructions >= 2 37 | assert c_m.alive() + c_mc.alive() + c_c.alive() == 0 38 | 39 | 40 | def test_move_and_copy_loads(): 41 | """Call some functions that load arguments via custom type casters and count the number of 42 | moves/copies.""" 43 | 44 | cstats = m.move_and_copy_cstats() 45 | c_m, c_mc, c_c = cstats["MoveOnlyInt"], cstats["MoveOrCopyInt"], cstats["CopyOnlyInt"] 46 | 47 | assert m.move_only(10) == 10 # 1 move, c_m 48 | assert m.move_or_copy(11) == 11 # 1 move, c_mc 49 | assert m.copy_only(12) == 12 # 1 copy, c_c 50 | assert m.move_pair((13, 14)) == 27 # 1 c_m move, 1 c_mc move 51 | assert m.move_tuple((15, 16, 17)) == 48 # 2 c_m moves, 1 c_mc move 52 | assert m.copy_tuple((18, 19)) == 37 # 2 c_c copies 53 | # Direct constructions: 2 c_m moves, 2 c_mc moves, 1 c_c copy 54 | # Extra moves/copies when moving pairs/tuples: 3 c_m, 3 c_mc, 2 c_c 55 | assert m.move_copy_nested((1, ((2, 3, (4,)), 5))) == 15 56 | 57 | assert c_m.copy_assignments + c_m.copy_constructions == 0 58 | assert c_m.move_assignments == 6 59 | assert c_m.move_constructions == 9 60 | assert c_mc.copy_assignments + c_mc.copy_constructions == 0 61 | assert c_mc.move_assignments == 5 62 | assert c_mc.move_constructions == 8 63 | assert c_c.copy_assignments == 4 64 | assert c_c.copy_constructions == 6 65 | assert c_m.alive() + c_mc.alive() + c_c.alive() == 0 66 | 67 | 68 | @pytest.mark.skipif(not m.has_optional, reason='no ') 69 | def test_move_and_copy_load_optional(): 70 | """Tests move/copy loads of std::optional arguments""" 71 | 72 | cstats = m.move_and_copy_cstats() 73 | c_m, c_mc, c_c = cstats["MoveOnlyInt"], cstats["MoveOrCopyInt"], cstats["CopyOnlyInt"] 74 | 75 | # The extra move/copy constructions below come from the std::optional move (which has to move 76 | # its arguments): 77 | assert m.move_optional(10) == 10 # c_m: 1 move assign, 2 move construct 78 | assert m.move_or_copy_optional(11) == 11 # c_mc: 1 move assign, 2 move construct 79 | assert m.copy_optional(12) == 12 # c_c: 1 copy assign, 2 copy construct 80 | # 1 move assign + move construct moves each of c_m, c_mc, 1 c_c copy 81 | # +1 move/copy construct each from moving the tuple 82 | # +1 move/copy construct each from moving the optional (which moves the tuple again) 83 | assert m.move_optional_tuple((3, 4, 5)) == 12 84 | 85 | assert c_m.copy_assignments + c_m.copy_constructions == 0 86 | assert c_m.move_assignments == 2 87 | assert c_m.move_constructions == 5 88 | assert c_mc.copy_assignments + c_mc.copy_constructions == 0 89 | assert c_mc.move_assignments == 2 90 | assert c_mc.move_constructions == 5 91 | assert c_c.copy_assignments == 2 92 | assert c_c.copy_constructions == 5 93 | assert c_m.alive() + c_mc.alive() + c_c.alive() == 0 94 | 95 | 96 | def test_private_op_new(): 97 | """An object with a private `operator new` cannot be returned by value""" 98 | 99 | with pytest.raises(RuntimeError) as excinfo: 100 | m.private_op_new_value() 101 | assert "is neither movable nor copyable" in str(excinfo.value) 102 | 103 | assert m.private_op_new_reference().value == 1 104 | 105 | 106 | def test_move_fallback(): 107 | """#389: rvp::move should fall-through to copy on non-movable objects""" 108 | 109 | m2 = m.get_moveissue2(2) 110 | assert m2.value == 2 111 | m1 = m.get_moveissue1(1) 112 | assert m1.value == 1 113 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_custom_type_casters.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from pybind11_tests import custom_type_casters as m 3 | 4 | 5 | def test_noconvert_args(msg): 6 | a = m.ArgInspector() 7 | assert msg(a.f("hi")) == """ 8 | loading ArgInspector1 argument WITH conversion allowed. Argument value = hi 9 | """ 10 | assert msg(a.g("this is a", "this is b")) == """ 11 | loading ArgInspector1 argument WITHOUT conversion allowed. Argument value = this is a 12 | loading ArgInspector1 argument WITH conversion allowed. Argument value = this is b 13 | 13 14 | loading ArgInspector2 argument WITH conversion allowed. Argument value = (default arg inspector 2) 15 | """ # noqa: E501 line too long 16 | assert msg(a.g("this is a", "this is b", 42)) == """ 17 | loading ArgInspector1 argument WITHOUT conversion allowed. Argument value = this is a 18 | loading ArgInspector1 argument WITH conversion allowed. Argument value = this is b 19 | 42 20 | loading ArgInspector2 argument WITH conversion allowed. Argument value = (default arg inspector 2) 21 | """ # noqa: E501 line too long 22 | assert msg(a.g("this is a", "this is b", 42, "this is d")) == """ 23 | loading ArgInspector1 argument WITHOUT conversion allowed. Argument value = this is a 24 | loading ArgInspector1 argument WITH conversion allowed. Argument value = this is b 25 | 42 26 | loading ArgInspector2 argument WITH conversion allowed. Argument value = this is d 27 | """ 28 | assert (a.h("arg 1") == 29 | "loading ArgInspector2 argument WITHOUT conversion allowed. Argument value = arg 1") 30 | assert msg(m.arg_inspect_func("A1", "A2")) == """ 31 | loading ArgInspector2 argument WITH conversion allowed. Argument value = A1 32 | loading ArgInspector1 argument WITHOUT conversion allowed. Argument value = A2 33 | """ 34 | 35 | assert m.floats_preferred(4) == 2.0 36 | assert m.floats_only(4.0) == 2.0 37 | with pytest.raises(TypeError) as excinfo: 38 | m.floats_only(4) 39 | assert msg(excinfo.value) == """ 40 | floats_only(): incompatible function arguments. The following argument types are supported: 41 | 1. (f: float) -> float 42 | 43 | Invoked with: 4 44 | """ 45 | 46 | assert m.ints_preferred(4) == 2 47 | assert m.ints_preferred(True) == 0 48 | with pytest.raises(TypeError) as excinfo: 49 | m.ints_preferred(4.0) 50 | assert msg(excinfo.value) == """ 51 | ints_preferred(): incompatible function arguments. The following argument types are supported: 52 | 1. (i: int) -> int 53 | 54 | Invoked with: 4.0 55 | """ # noqa: E501 line too long 56 | 57 | assert m.ints_only(4) == 2 58 | with pytest.raises(TypeError) as excinfo: 59 | m.ints_only(4.0) 60 | assert msg(excinfo.value) == """ 61 | ints_only(): incompatible function arguments. The following argument types are supported: 62 | 1. (i: int) -> int 63 | 64 | Invoked with: 4.0 65 | """ 66 | 67 | 68 | def test_custom_caster_destruction(): 69 | """Tests that returning a pointer to a type that gets converted with a custom type caster gets 70 | destroyed when the function has py::return_value_policy::take_ownership policy applied.""" 71 | 72 | cstats = m.destruction_tester_cstats() 73 | # This one *doesn't* have take_ownership: the pointer should be used but not destroyed: 74 | z = m.custom_caster_no_destroy() 75 | assert cstats.alive() == 1 and cstats.default_constructions == 1 76 | assert z 77 | 78 | # take_ownership applied: this constructs a new object, casts it, then destroys it: 79 | z = m.custom_caster_destroy() 80 | assert z 81 | assert cstats.default_constructions == 2 82 | 83 | # Same, but with a const pointer return (which should *not* inhibit destruction): 84 | z = m.custom_caster_destroy_const() 85 | assert z 86 | assert cstats.default_constructions == 3 87 | 88 | # Make sure we still only have the original object (from ..._no_destroy()) alive: 89 | assert cstats.alive() == 1 90 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_docstring_options.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_docstring_options.cpp -- generation of docstrings and signatures 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | 12 | TEST_SUBMODULE(docstring_options, m) { 13 | // test_docstring_options 14 | { 15 | py::options options; 16 | options.disable_function_signatures(); 17 | 18 | m.def("test_function1", [](int, int) {}, py::arg("a"), py::arg("b")); 19 | m.def("test_function2", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring"); 20 | 21 | m.def("test_overloaded1", [](int) {}, py::arg("i"), "Overload docstring"); 22 | m.def("test_overloaded1", [](double) {}, py::arg("d")); 23 | 24 | m.def("test_overloaded2", [](int) {}, py::arg("i"), "overload docstring 1"); 25 | m.def("test_overloaded2", [](double) {}, py::arg("d"), "overload docstring 2"); 26 | 27 | m.def("test_overloaded3", [](int) {}, py::arg("i")); 28 | m.def("test_overloaded3", [](double) {}, py::arg("d"), "Overload docstr"); 29 | 30 | options.enable_function_signatures(); 31 | 32 | m.def("test_function3", [](int, int) {}, py::arg("a"), py::arg("b")); 33 | m.def("test_function4", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring"); 34 | 35 | options.disable_function_signatures().disable_user_defined_docstrings(); 36 | 37 | m.def("test_function5", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring"); 38 | 39 | { 40 | py::options nested_options; 41 | nested_options.enable_user_defined_docstrings(); 42 | m.def("test_function6", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring"); 43 | } 44 | } 45 | 46 | m.def("test_function7", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring"); 47 | 48 | { 49 | py::options options; 50 | options.disable_user_defined_docstrings(); 51 | 52 | struct DocstringTestFoo { 53 | int value; 54 | void setValue(int v) { value = v; } 55 | int getValue() const { return value; } 56 | }; 57 | py::class_(m, "DocstringTestFoo", "This is a class docstring") 58 | .def_property("value_prop", &DocstringTestFoo::getValue, &DocstringTestFoo::setValue, "This is a property docstring") 59 | ; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_docstring_options.py: -------------------------------------------------------------------------------- 1 | from pybind11_tests import docstring_options as m 2 | 3 | 4 | def test_docstring_options(): 5 | # options.disable_function_signatures() 6 | assert not m.test_function1.__doc__ 7 | 8 | assert m.test_function2.__doc__ == "A custom docstring" 9 | 10 | # docstring specified on just the first overload definition: 11 | assert m.test_overloaded1.__doc__ == "Overload docstring" 12 | 13 | # docstring on both overloads: 14 | assert m.test_overloaded2.__doc__ == "overload docstring 1\noverload docstring 2" 15 | 16 | # docstring on only second overload: 17 | assert m.test_overloaded3.__doc__ == "Overload docstr" 18 | 19 | # options.enable_function_signatures() 20 | assert m.test_function3.__doc__ .startswith("test_function3(a: int, b: int) -> None") 21 | 22 | assert m.test_function4.__doc__ .startswith("test_function4(a: int, b: int) -> None") 23 | assert m.test_function4.__doc__ .endswith("A custom docstring\n") 24 | 25 | # options.disable_function_signatures() 26 | # options.disable_user_defined_docstrings() 27 | assert not m.test_function5.__doc__ 28 | 29 | # nested options.enable_user_defined_docstrings() 30 | assert m.test_function6.__doc__ == "A custom docstring" 31 | 32 | # RAII destructor 33 | assert m.test_function7.__doc__ .startswith("test_function7(a: int, b: int) -> None") 34 | assert m.test_function7.__doc__ .endswith("A custom docstring\n") 35 | 36 | # Suppression of user-defined docstrings for non-function objects 37 | assert not m.DocstringTestFoo.__doc__ 38 | assert not m.DocstringTestFoo.value_prop.__doc__ 39 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_embed/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | if(${PYTHON_MODULE_EXTENSION} MATCHES "pypy") 2 | add_custom_target(cpptest) # Dummy target on PyPy. Embedding is not supported. 3 | set(_suppress_unused_variable_warning "${DOWNLOAD_CATCH}") 4 | return() 5 | endif() 6 | 7 | find_package(Catch 1.9.3) 8 | if(CATCH_FOUND) 9 | message(STATUS "Building interpreter tests using Catch v${CATCH_VERSION}") 10 | else() 11 | message(STATUS "Catch not detected. Interpreter tests will be skipped. Install Catch headers" 12 | " manually or use `cmake -DDOWNLOAD_CATCH=1` to fetch them automatically.") 13 | return() 14 | endif() 15 | 16 | add_executable(test_embed 17 | catch.cpp 18 | test_interpreter.cpp 19 | ) 20 | target_include_directories(test_embed PRIVATE ${CATCH_INCLUDE_DIR}) 21 | pybind11_enable_warnings(test_embed) 22 | 23 | if(NOT CMAKE_VERSION VERSION_LESS 3.0) 24 | target_link_libraries(test_embed PRIVATE pybind11::embed) 25 | else() 26 | target_include_directories(test_embed PRIVATE ${PYBIND11_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS}) 27 | target_compile_options(test_embed PRIVATE ${PYBIND11_CPP_STANDARD}) 28 | target_link_libraries(test_embed PRIVATE ${PYTHON_LIBRARIES}) 29 | endif() 30 | 31 | find_package(Threads REQUIRED) 32 | target_link_libraries(test_embed PUBLIC ${CMAKE_THREAD_LIBS_INIT}) 33 | 34 | add_custom_target(cpptest COMMAND $ 35 | WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) 36 | 37 | pybind11_add_module(external_module THIN_LTO external_module.cpp) 38 | set_target_properties(external_module PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) 39 | add_dependencies(cpptest external_module) 40 | 41 | add_dependencies(check cpptest) 42 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_embed/catch.cpp: -------------------------------------------------------------------------------- 1 | // The Catch implementation is compiled here. This is a standalone 2 | // translation unit to avoid recompiling it for every test change. 3 | 4 | #include 5 | 6 | #ifdef _MSC_VER 7 | // Silence MSVC C++17 deprecation warning from Catch regarding std::uncaught_exceptions (up to catch 8 | // 2.0.1; this should be fixed in the next catch release after 2.0.1). 9 | # pragma warning(disable: 4996) 10 | #endif 11 | 12 | #define CATCH_CONFIG_RUNNER 13 | #include 14 | 15 | namespace py = pybind11; 16 | 17 | int main(int argc, char *argv[]) { 18 | py::scoped_interpreter guard{}; 19 | auto result = Catch::Session().run(argc, argv); 20 | 21 | return result < 0xff ? result : 0xff; 22 | } 23 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_embed/external_module.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | namespace py = pybind11; 4 | 5 | /* Simple test module/test class to check that the referenced internals data of external pybind11 6 | * modules aren't preserved over a finalize/initialize. 7 | */ 8 | 9 | PYBIND11_MODULE(external_module, m) { 10 | class A { 11 | public: 12 | A(int value) : v{value} {}; 13 | int v; 14 | }; 15 | 16 | py::class_(m, "A") 17 | .def(py::init()) 18 | .def_readwrite("value", &A::v); 19 | 20 | m.def("internals_at", []() { 21 | return reinterpret_cast(&py::detail::get_internals()); 22 | }); 23 | } 24 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_embed/test_interpreter.py: -------------------------------------------------------------------------------- 1 | from widget_module import Widget 2 | 3 | 4 | class DerivedWidget(Widget): 5 | def __init__(self, message): 6 | super(DerivedWidget, self).__init__(message) 7 | 8 | def the_answer(self): 9 | return 42 10 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_enum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_enums.cpp -- enumerations 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | 12 | TEST_SUBMODULE(enums, m) { 13 | // test_unscoped_enum 14 | enum UnscopedEnum { 15 | EOne = 1, 16 | ETwo, 17 | EThree 18 | }; 19 | py::enum_(m, "UnscopedEnum", py::arithmetic(), "An unscoped enumeration") 20 | .value("EOne", EOne, "Docstring for EOne") 21 | .value("ETwo", ETwo, "Docstring for ETwo") 22 | .value("EThree", EThree, "Docstring for EThree") 23 | .export_values(); 24 | 25 | // test_scoped_enum 26 | enum class ScopedEnum { 27 | Two = 2, 28 | Three 29 | }; 30 | py::enum_(m, "ScopedEnum", py::arithmetic()) 31 | .value("Two", ScopedEnum::Two) 32 | .value("Three", ScopedEnum::Three); 33 | 34 | m.def("test_scoped_enum", [](ScopedEnum z) { 35 | return "ScopedEnum::" + std::string(z == ScopedEnum::Two ? "Two" : "Three"); 36 | }); 37 | 38 | // test_binary_operators 39 | enum Flags { 40 | Read = 4, 41 | Write = 2, 42 | Execute = 1 43 | }; 44 | py::enum_(m, "Flags", py::arithmetic()) 45 | .value("Read", Flags::Read) 46 | .value("Write", Flags::Write) 47 | .value("Execute", Flags::Execute) 48 | .export_values(); 49 | 50 | // test_implicit_conversion 51 | class ClassWithUnscopedEnum { 52 | public: 53 | enum EMode { 54 | EFirstMode = 1, 55 | ESecondMode 56 | }; 57 | 58 | static EMode test_function(EMode mode) { 59 | return mode; 60 | } 61 | }; 62 | py::class_ exenum_class(m, "ClassWithUnscopedEnum"); 63 | exenum_class.def_static("test_function", &ClassWithUnscopedEnum::test_function); 64 | py::enum_(exenum_class, "EMode") 65 | .value("EFirstMode", ClassWithUnscopedEnum::EFirstMode) 66 | .value("ESecondMode", ClassWithUnscopedEnum::ESecondMode) 67 | .export_values(); 68 | 69 | // test_enum_to_int 70 | m.def("test_enum_to_int", [](int) { }); 71 | m.def("test_enum_to_uint", [](uint32_t) { }); 72 | m.def("test_enum_to_long_long", [](long long) { }); 73 | 74 | // test_duplicate_enum_name 75 | enum SimpleEnum 76 | { 77 | ONE, TWO, THREE 78 | }; 79 | 80 | m.def("register_bad_enum", [m]() { 81 | py::enum_(m, "SimpleEnum") 82 | .value("ONE", SimpleEnum::ONE) //NOTE: all value function calls are called with the same first parameter value 83 | .value("ONE", SimpleEnum::TWO) 84 | .value("ONE", SimpleEnum::THREE) 85 | .export_values(); 86 | }); 87 | } 88 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_eval.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_eval.cpp -- Usage of eval() and eval_file() 3 | 4 | Copyright (c) 2016 Klemens D. Morgenstern 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | 11 | #include 12 | #include "pybind11_tests.h" 13 | 14 | TEST_SUBMODULE(eval_, m) { 15 | // test_evals 16 | 17 | auto global = py::dict(py::module::import("__main__").attr("__dict__")); 18 | 19 | m.def("test_eval_statements", [global]() { 20 | auto local = py::dict(); 21 | local["call_test"] = py::cpp_function([&]() -> int { 22 | return 42; 23 | }); 24 | 25 | // Regular string literal 26 | py::exec( 27 | "message = 'Hello World!'\n" 28 | "x = call_test()", 29 | global, local 30 | ); 31 | 32 | // Multi-line raw string literal 33 | py::exec(R"( 34 | if x == 42: 35 | print(message) 36 | else: 37 | raise RuntimeError 38 | )", global, local 39 | ); 40 | auto x = local["x"].cast(); 41 | 42 | return x == 42; 43 | }); 44 | 45 | m.def("test_eval", [global]() { 46 | auto local = py::dict(); 47 | local["x"] = py::int_(42); 48 | auto x = py::eval("x", global, local); 49 | return x.cast() == 42; 50 | }); 51 | 52 | m.def("test_eval_single_statement", []() { 53 | auto local = py::dict(); 54 | local["call_test"] = py::cpp_function([&]() -> int { 55 | return 42; 56 | }); 57 | 58 | auto result = py::eval("x = call_test()", py::dict(), local); 59 | auto x = local["x"].cast(); 60 | return result.is_none() && x == 42; 61 | }); 62 | 63 | m.def("test_eval_file", [global](py::str filename) { 64 | auto local = py::dict(); 65 | local["y"] = py::int_(43); 66 | 67 | int val_out; 68 | local["call_test2"] = py::cpp_function([&](int value) { val_out = value; }); 69 | 70 | auto result = py::eval_file(filename, global, local); 71 | return val_out == 43 && result.is_none(); 72 | }); 73 | 74 | m.def("test_eval_failure", []() { 75 | try { 76 | py::eval("nonsense code ..."); 77 | } catch (py::error_already_set &) { 78 | return true; 79 | } 80 | return false; 81 | }); 82 | 83 | m.def("test_eval_file_failure", []() { 84 | try { 85 | py::eval_file("non-existing file"); 86 | } catch (std::exception &) { 87 | return true; 88 | } 89 | return false; 90 | }); 91 | } 92 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_eval.py: -------------------------------------------------------------------------------- 1 | import os 2 | from pybind11_tests import eval_ as m 3 | 4 | 5 | def test_evals(capture): 6 | with capture: 7 | assert m.test_eval_statements() 8 | assert capture == "Hello World!" 9 | 10 | assert m.test_eval() 11 | assert m.test_eval_single_statement() 12 | 13 | filename = os.path.join(os.path.dirname(__file__), "test_eval_call.py") 14 | assert m.test_eval_file(filename) 15 | 16 | assert m.test_eval_failure() 17 | assert m.test_eval_file_failure() 18 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_eval_call.py: -------------------------------------------------------------------------------- 1 | # This file is called from 'test_eval.py' 2 | 3 | if 'call_test2' in locals(): 4 | call_test2(y) # noqa: F821 undefined name 5 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_gil_scoped.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_gil_scoped.cpp -- acquire and release gil 3 | 4 | Copyright (c) 2017 Borja Zarco (Google LLC) 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | #include 12 | 13 | 14 | class VirtClass { 15 | public: 16 | virtual ~VirtClass() {} 17 | virtual void virtual_func() {} 18 | virtual void pure_virtual_func() = 0; 19 | }; 20 | 21 | class PyVirtClass : public VirtClass { 22 | void virtual_func() override { 23 | PYBIND11_OVERLOAD(void, VirtClass, virtual_func,); 24 | } 25 | void pure_virtual_func() override { 26 | PYBIND11_OVERLOAD_PURE(void, VirtClass, pure_virtual_func,); 27 | } 28 | }; 29 | 30 | TEST_SUBMODULE(gil_scoped, m) { 31 | py::class_(m, "VirtClass") 32 | .def(py::init<>()) 33 | .def("virtual_func", &VirtClass::virtual_func) 34 | .def("pure_virtual_func", &VirtClass::pure_virtual_func); 35 | 36 | m.def("test_callback_py_obj", 37 | [](py::object func) { func(); }); 38 | m.def("test_callback_std_func", 39 | [](const std::function &func) { func(); }); 40 | m.def("test_callback_virtual_func", 41 | [](VirtClass &virt) { virt.virtual_func(); }); 42 | m.def("test_callback_pure_virtual_func", 43 | [](VirtClass &virt) { virt.pure_virtual_func(); }); 44 | m.def("test_cross_module_gil", 45 | []() { 46 | auto cm = py::module::import("cross_module_gil_utils"); 47 | auto gil_acquire = reinterpret_cast( 48 | PyLong_AsVoidPtr(cm.attr("gil_acquire_funcaddr").ptr())); 49 | py::gil_scoped_release gil_release; 50 | gil_acquire(); 51 | }); 52 | } 53 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_gil_scoped.py: -------------------------------------------------------------------------------- 1 | import multiprocessing 2 | import threading 3 | from pybind11_tests import gil_scoped as m 4 | 5 | 6 | def _run_in_process(target, *args, **kwargs): 7 | """Runs target in process and returns its exitcode after 10s (None if still alive).""" 8 | process = multiprocessing.Process(target=target, args=args, kwargs=kwargs) 9 | process.daemon = True 10 | try: 11 | process.start() 12 | # Do not need to wait much, 10s should be more than enough. 13 | process.join(timeout=10) 14 | return process.exitcode 15 | finally: 16 | if process.is_alive(): 17 | process.terminate() 18 | 19 | 20 | def _python_to_cpp_to_python(): 21 | """Calls different C++ functions that come back to Python.""" 22 | class ExtendedVirtClass(m.VirtClass): 23 | def virtual_func(self): 24 | pass 25 | 26 | def pure_virtual_func(self): 27 | pass 28 | 29 | extended = ExtendedVirtClass() 30 | m.test_callback_py_obj(lambda: None) 31 | m.test_callback_std_func(lambda: None) 32 | m.test_callback_virtual_func(extended) 33 | m.test_callback_pure_virtual_func(extended) 34 | 35 | 36 | def _python_to_cpp_to_python_from_threads(num_threads, parallel=False): 37 | """Calls different C++ functions that come back to Python, from Python threads.""" 38 | threads = [] 39 | for _ in range(num_threads): 40 | thread = threading.Thread(target=_python_to_cpp_to_python) 41 | thread.daemon = True 42 | thread.start() 43 | if parallel: 44 | threads.append(thread) 45 | else: 46 | thread.join() 47 | for thread in threads: 48 | thread.join() 49 | 50 | 51 | def test_python_to_cpp_to_python_from_thread(): 52 | """Makes sure there is no GIL deadlock when running in a thread. 53 | 54 | It runs in a separate process to be able to stop and assert if it deadlocks. 55 | """ 56 | assert _run_in_process(_python_to_cpp_to_python_from_threads, 1) == 0 57 | 58 | 59 | def test_python_to_cpp_to_python_from_thread_multiple_parallel(): 60 | """Makes sure there is no GIL deadlock when running in a thread multiple times in parallel. 61 | 62 | It runs in a separate process to be able to stop and assert if it deadlocks. 63 | """ 64 | assert _run_in_process(_python_to_cpp_to_python_from_threads, 8, parallel=True) == 0 65 | 66 | 67 | def test_python_to_cpp_to_python_from_thread_multiple_sequential(): 68 | """Makes sure there is no GIL deadlock when running in a thread multiple times sequentially. 69 | 70 | It runs in a separate process to be able to stop and assert if it deadlocks. 71 | """ 72 | assert _run_in_process(_python_to_cpp_to_python_from_threads, 8, parallel=False) == 0 73 | 74 | 75 | def test_python_to_cpp_to_python_from_process(): 76 | """Makes sure there is no GIL deadlock when using processes. 77 | 78 | This test is for completion, but it was never an issue. 79 | """ 80 | assert _run_in_process(_python_to_cpp_to_python) == 0 81 | 82 | 83 | def test_cross_module_gil(): 84 | """Makes sure that the GIL can be acquired by another module from a GIL-released state.""" 85 | m.test_cross_module_gil() # Should not raise a SIGSEGV 86 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_iostream.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_iostream.cpp -- Usage of scoped_output_redirect 3 | 4 | Copyright (c) 2017 Henry F. Schreiner 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | 11 | #include 12 | #include "pybind11_tests.h" 13 | #include 14 | 15 | 16 | void noisy_function(std::string msg, bool flush) { 17 | 18 | std::cout << msg; 19 | if (flush) 20 | std::cout << std::flush; 21 | } 22 | 23 | void noisy_funct_dual(std::string msg, std::string emsg) { 24 | std::cout << msg; 25 | std::cerr << emsg; 26 | } 27 | 28 | TEST_SUBMODULE(iostream, m) { 29 | 30 | add_ostream_redirect(m); 31 | 32 | // test_evals 33 | 34 | m.def("captured_output_default", [](std::string msg) { 35 | py::scoped_ostream_redirect redir; 36 | std::cout << msg << std::flush; 37 | }); 38 | 39 | m.def("captured_output", [](std::string msg) { 40 | py::scoped_ostream_redirect redir(std::cout, py::module::import("sys").attr("stdout")); 41 | std::cout << msg << std::flush; 42 | }); 43 | 44 | m.def("guard_output", &noisy_function, 45 | py::call_guard(), 46 | py::arg("msg"), py::arg("flush")=true); 47 | 48 | m.def("captured_err", [](std::string msg) { 49 | py::scoped_ostream_redirect redir(std::cerr, py::module::import("sys").attr("stderr")); 50 | std::cerr << msg << std::flush; 51 | }); 52 | 53 | m.def("noisy_function", &noisy_function, py::arg("msg"), py::arg("flush") = true); 54 | 55 | m.def("dual_guard", &noisy_funct_dual, 56 | py::call_guard(), 57 | py::arg("msg"), py::arg("emsg")); 58 | 59 | m.def("raw_output", [](std::string msg) { 60 | std::cout << msg << std::flush; 61 | }); 62 | 63 | m.def("raw_err", [](std::string msg) { 64 | std::cerr << msg << std::flush; 65 | }); 66 | 67 | m.def("captured_dual", [](std::string msg, std::string emsg) { 68 | py::scoped_ostream_redirect redirout(std::cout, py::module::import("sys").attr("stdout")); 69 | py::scoped_ostream_redirect redirerr(std::cerr, py::module::import("sys").attr("stderr")); 70 | std::cout << msg << std::flush; 71 | std::cerr << emsg << std::flush; 72 | }); 73 | } 74 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_local_bindings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_local_bindings.cpp -- tests the py::module_local class feature which makes a class 3 | binding local to the module in which it is defined. 4 | 5 | Copyright (c) 2017 Jason Rhinelander 6 | 7 | All rights reserved. Use of this source code is governed by a 8 | BSD-style license that can be found in the LICENSE file. 9 | */ 10 | 11 | #include "pybind11_tests.h" 12 | #include "local_bindings.h" 13 | #include 14 | #include 15 | #include 16 | 17 | TEST_SUBMODULE(local_bindings, m) { 18 | // test_load_external 19 | m.def("load_external1", [](ExternalType1 &e) { return e.i; }); 20 | m.def("load_external2", [](ExternalType2 &e) { return e.i; }); 21 | 22 | // test_local_bindings 23 | // Register a class with py::module_local: 24 | bind_local(m, "LocalType", py::module_local()) 25 | .def("get3", [](LocalType &t) { return t.i + 3; }) 26 | ; 27 | 28 | m.def("local_value", [](LocalType &l) { return l.i; }); 29 | 30 | // test_nonlocal_failure 31 | // The main pybind11 test module is loaded first, so this registration will succeed (the second 32 | // one, in pybind11_cross_module_tests.cpp, is designed to fail): 33 | bind_local(m, "NonLocalType") 34 | .def(py::init()) 35 | .def("get", [](LocalType &i) { return i.i; }) 36 | ; 37 | 38 | // test_duplicate_local 39 | // py::module_local declarations should be visible across compilation units that get linked together; 40 | // this tries to register a duplicate local. It depends on a definition in test_class.cpp and 41 | // should raise a runtime error from the duplicate definition attempt. If test_class isn't 42 | // available it *also* throws a runtime error (with "test_class not enabled" as value). 43 | m.def("register_local_external", [m]() { 44 | auto main = py::module::import("pybind11_tests"); 45 | if (py::hasattr(main, "class_")) { 46 | bind_local(m, "LocalExternal", py::module_local()); 47 | } 48 | else throw std::runtime_error("test_class not enabled"); 49 | }); 50 | 51 | // test_stl_bind_local 52 | // stl_bind.h binders defaults to py::module_local if the types are local or converting: 53 | py::bind_vector(m, "LocalVec"); 54 | py::bind_map(m, "LocalMap"); 55 | // and global if the type (or one of the types, for the map) is global: 56 | py::bind_vector(m, "NonLocalVec"); 57 | py::bind_map(m, "NonLocalMap"); 58 | 59 | // test_stl_bind_global 60 | // They can, however, be overridden to global using `py::module_local(false)`: 61 | bind_local(m, "NonLocal2"); 62 | py::bind_vector(m, "LocalVec2", py::module_local()); 63 | py::bind_map(m, "NonLocalMap2", py::module_local(false)); 64 | 65 | // test_mixed_local_global 66 | // We try this both with the global type registered first and vice versa (the order shouldn't 67 | // matter). 68 | m.def("register_mixed_global", [m]() { 69 | bind_local(m, "MixedGlobalLocal", py::module_local(false)); 70 | }); 71 | m.def("register_mixed_local", [m]() { 72 | bind_local(m, "MixedLocalGlobal", py::module_local()); 73 | }); 74 | m.def("get_mixed_gl", [](int i) { return MixedGlobalLocal(i); }); 75 | m.def("get_mixed_lg", [](int i) { return MixedLocalGlobal(i); }); 76 | 77 | // test_internal_locals_differ 78 | m.def("local_cpp_types_addr", []() { return (uintptr_t) &py::detail::registered_local_types_cpp(); }); 79 | 80 | // test_stl_caster_vs_stl_bind 81 | m.def("load_vector_via_caster", [](std::vector v) { 82 | return std::accumulate(v.begin(), v.end(), 0); 83 | }); 84 | 85 | // test_cross_module_calls 86 | m.def("return_self", [](LocalVec *v) { return v; }); 87 | m.def("return_copy", [](const LocalVec &v) { return LocalVec(v); }); 88 | 89 | class Cat : public pets::Pet { public: Cat(std::string name) : Pet(name) {}; }; 90 | py::class_(m, "Pet", py::module_local()) 91 | .def("get_name", &pets::Pet::name); 92 | // Binding for local extending class: 93 | py::class_(m, "Cat") 94 | .def(py::init()); 95 | m.def("pet_name", [](pets::Pet &p) { return p.name(); }); 96 | 97 | py::class_(m, "MixGL").def(py::init()); 98 | m.def("get_gl_value", [](MixGL &o) { return o.i + 10; }); 99 | 100 | py::class_(m, "MixGL2").def(py::init()); 101 | } 102 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_modules.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_modules.cpp -- nested modules, importing modules, and 3 | internal references 4 | 5 | Copyright (c) 2016 Wenzel Jakob 6 | 7 | All rights reserved. Use of this source code is governed by a 8 | BSD-style license that can be found in the LICENSE file. 9 | */ 10 | 11 | #include "pybind11_tests.h" 12 | #include "constructor_stats.h" 13 | 14 | TEST_SUBMODULE(modules, m) { 15 | // test_nested_modules 16 | py::module m_sub = m.def_submodule("subsubmodule"); 17 | m_sub.def("submodule_func", []() { return "submodule_func()"; }); 18 | 19 | // test_reference_internal 20 | class A { 21 | public: 22 | A(int v) : v(v) { print_created(this, v); } 23 | ~A() { print_destroyed(this); } 24 | A(const A&) { print_copy_created(this); } 25 | A& operator=(const A ©) { print_copy_assigned(this); v = copy.v; return *this; } 26 | std::string toString() { return "A[" + std::to_string(v) + "]"; } 27 | private: 28 | int v; 29 | }; 30 | py::class_(m_sub, "A") 31 | .def(py::init()) 32 | .def("__repr__", &A::toString); 33 | 34 | class B { 35 | public: 36 | B() { print_default_created(this); } 37 | ~B() { print_destroyed(this); } 38 | B(const B&) { print_copy_created(this); } 39 | B& operator=(const B ©) { print_copy_assigned(this); a1 = copy.a1; a2 = copy.a2; return *this; } 40 | A &get_a1() { return a1; } 41 | A &get_a2() { return a2; } 42 | 43 | A a1{1}; 44 | A a2{2}; 45 | }; 46 | py::class_(m_sub, "B") 47 | .def(py::init<>()) 48 | .def("get_a1", &B::get_a1, "Return the internal A 1", py::return_value_policy::reference_internal) 49 | .def("get_a2", &B::get_a2, "Return the internal A 2", py::return_value_policy::reference_internal) 50 | .def_readwrite("a1", &B::a1) // def_readonly uses an internal reference return policy by default 51 | .def_readwrite("a2", &B::a2); 52 | 53 | m.attr("OD") = py::module::import("collections").attr("OrderedDict"); 54 | 55 | // test_duplicate_registration 56 | // Registering two things with the same name 57 | m.def("duplicate_registration", []() { 58 | class Dupe1 { }; 59 | class Dupe2 { }; 60 | class Dupe3 { }; 61 | class DupeException { }; 62 | 63 | auto dm = py::module("dummy"); 64 | auto failures = py::list(); 65 | 66 | py::class_(dm, "Dupe1"); 67 | py::class_(dm, "Dupe2"); 68 | dm.def("dupe1_factory", []() { return Dupe1(); }); 69 | py::exception(dm, "DupeException"); 70 | 71 | try { 72 | py::class_(dm, "Dupe1"); 73 | failures.append("Dupe1 class"); 74 | } catch (std::runtime_error &) {} 75 | try { 76 | dm.def("Dupe1", []() { return Dupe1(); }); 77 | failures.append("Dupe1 function"); 78 | } catch (std::runtime_error &) {} 79 | try { 80 | py::class_(dm, "dupe1_factory"); 81 | failures.append("dupe1_factory"); 82 | } catch (std::runtime_error &) {} 83 | try { 84 | py::exception(dm, "Dupe2"); 85 | failures.append("Dupe2"); 86 | } catch (std::runtime_error &) {} 87 | try { 88 | dm.def("DupeException", []() { return 30; }); 89 | failures.append("DupeException1"); 90 | } catch (std::runtime_error &) {} 91 | try { 92 | py::class_(dm, "DupeException"); 93 | failures.append("DupeException2"); 94 | } catch (std::runtime_error &) {} 95 | 96 | return failures; 97 | }); 98 | } 99 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_modules.py: -------------------------------------------------------------------------------- 1 | from pybind11_tests import modules as m 2 | from pybind11_tests.modules import subsubmodule as ms 3 | from pybind11_tests import ConstructorStats 4 | 5 | 6 | def test_nested_modules(): 7 | import pybind11_tests 8 | assert pybind11_tests.__name__ == "pybind11_tests" 9 | assert pybind11_tests.modules.__name__ == "pybind11_tests.modules" 10 | assert pybind11_tests.modules.subsubmodule.__name__ == "pybind11_tests.modules.subsubmodule" 11 | assert m.__name__ == "pybind11_tests.modules" 12 | assert ms.__name__ == "pybind11_tests.modules.subsubmodule" 13 | 14 | assert ms.submodule_func() == "submodule_func()" 15 | 16 | 17 | def test_reference_internal(): 18 | b = ms.B() 19 | assert str(b.get_a1()) == "A[1]" 20 | assert str(b.a1) == "A[1]" 21 | assert str(b.get_a2()) == "A[2]" 22 | assert str(b.a2) == "A[2]" 23 | 24 | b.a1 = ms.A(42) 25 | b.a2 = ms.A(43) 26 | assert str(b.get_a1()) == "A[42]" 27 | assert str(b.a1) == "A[42]" 28 | assert str(b.get_a2()) == "A[43]" 29 | assert str(b.a2) == "A[43]" 30 | 31 | astats, bstats = ConstructorStats.get(ms.A), ConstructorStats.get(ms.B) 32 | assert astats.alive() == 2 33 | assert bstats.alive() == 1 34 | del b 35 | assert astats.alive() == 0 36 | assert bstats.alive() == 0 37 | assert astats.values() == ['1', '2', '42', '43'] 38 | assert bstats.values() == [] 39 | assert astats.default_constructions == 0 40 | assert bstats.default_constructions == 1 41 | assert astats.copy_constructions == 0 42 | assert bstats.copy_constructions == 0 43 | # assert astats.move_constructions >= 0 # Don't invoke any 44 | # assert bstats.move_constructions >= 0 # Don't invoke any 45 | assert astats.copy_assignments == 2 46 | assert bstats.copy_assignments == 0 47 | assert astats.move_assignments == 0 48 | assert bstats.move_assignments == 0 49 | 50 | 51 | def test_importing(): 52 | from pybind11_tests.modules import OD 53 | from collections import OrderedDict 54 | 55 | assert OD is OrderedDict 56 | assert str(OD([(1, 'a'), (2, 'b')])) == "OrderedDict([(1, 'a'), (2, 'b')])" 57 | 58 | 59 | def test_pydoc(): 60 | """Pydoc needs to be able to provide help() for everything inside a pybind11 module""" 61 | import pybind11_tests 62 | import pydoc 63 | 64 | assert pybind11_tests.__name__ == "pybind11_tests" 65 | assert pybind11_tests.__doc__ == "pybind11 test module" 66 | assert pydoc.text.docmodule(pybind11_tests) 67 | 68 | 69 | def test_duplicate_registration(): 70 | """Registering two things with the same name""" 71 | 72 | assert m.duplicate_registration() == [] 73 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_numpy_vectorize.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_numpy_vectorize.cpp -- auto-vectorize functions over NumPy array 3 | arguments 4 | 5 | Copyright (c) 2016 Wenzel Jakob 6 | 7 | All rights reserved. Use of this source code is governed by a 8 | BSD-style license that can be found in the LICENSE file. 9 | */ 10 | 11 | #include "pybind11_tests.h" 12 | #include 13 | 14 | double my_func(int x, float y, double z) { 15 | py::print("my_func(x:int={}, y:float={:.0f}, z:float={:.0f})"_s.format(x, y, z)); 16 | return (float) x*y*z; 17 | } 18 | 19 | TEST_SUBMODULE(numpy_vectorize, m) { 20 | try { py::module::import("numpy"); } 21 | catch (...) { return; } 22 | 23 | // test_vectorize, test_docs, test_array_collapse 24 | // Vectorize all arguments of a function (though non-vector arguments are also allowed) 25 | m.def("vectorized_func", py::vectorize(my_func)); 26 | 27 | // Vectorize a lambda function with a capture object (e.g. to exclude some arguments from the vectorization) 28 | m.def("vectorized_func2", 29 | [](py::array_t x, py::array_t y, float z) { 30 | return py::vectorize([z](int x, float y) { return my_func(x, y, z); })(x, y); 31 | } 32 | ); 33 | 34 | // Vectorize a complex-valued function 35 | m.def("vectorized_func3", py::vectorize( 36 | [](std::complex c) { return c * std::complex(2.f); } 37 | )); 38 | 39 | // test_type_selection 40 | // Numpy function which only accepts specific data types 41 | m.def("selective_func", [](py::array_t) { return "Int branch taken."; }); 42 | m.def("selective_func", [](py::array_t) { return "Float branch taken."; }); 43 | m.def("selective_func", [](py::array_t, py::array::c_style>) { return "Complex float branch taken."; }); 44 | 45 | 46 | // test_passthrough_arguments 47 | // Passthrough test: references and non-pod types should be automatically passed through (in the 48 | // function definition below, only `b`, `d`, and `g` are vectorized): 49 | struct NonPODClass { 50 | NonPODClass(int v) : value{v} {} 51 | int value; 52 | }; 53 | py::class_(m, "NonPODClass").def(py::init()); 54 | m.def("vec_passthrough", py::vectorize( 55 | [](double *a, double b, py::array_t c, const int &d, int &e, NonPODClass f, const double g) { 56 | return *a + b + c.at(0) + d + e + f.value + g; 57 | } 58 | )); 59 | 60 | // test_method_vectorization 61 | struct VectorizeTestClass { 62 | VectorizeTestClass(int v) : value{v} {}; 63 | float method(int x, float y) { return y + (float) (x + value); } 64 | int value = 0; 65 | }; 66 | py::class_ vtc(m, "VectorizeTestClass"); 67 | vtc .def(py::init()) 68 | .def_readwrite("value", &VectorizeTestClass::value); 69 | 70 | // Automatic vectorizing of methods 71 | vtc.def("method", py::vectorize(&VectorizeTestClass::method)); 72 | 73 | // test_trivial_broadcasting 74 | // Internal optimization test for whether the input is trivially broadcastable: 75 | py::enum_(m, "trivial") 76 | .value("f_trivial", py::detail::broadcast_trivial::f_trivial) 77 | .value("c_trivial", py::detail::broadcast_trivial::c_trivial) 78 | .value("non_trivial", py::detail::broadcast_trivial::non_trivial); 79 | m.def("vectorized_is_trivial", []( 80 | py::array_t arg1, 81 | py::array_t arg2, 82 | py::array_t arg3 83 | ) { 84 | ssize_t ndim; 85 | std::vector shape; 86 | std::array buffers {{ arg1.request(), arg2.request(), arg3.request() }}; 87 | return py::detail::broadcast(buffers, ndim, shape); 88 | }); 89 | } 90 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_opaque_types.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_opaque_types.cpp -- opaque types, passing void pointers 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | #include 12 | #include 13 | 14 | // IMPORTANT: Disable internal pybind11 translation mechanisms for STL data structures 15 | // 16 | // This also deliberately doesn't use the below StringList type alias to test 17 | // that MAKE_OPAQUE can handle a type containing a `,`. (The `std::allocator` 18 | // bit is just the default `std::vector` allocator). 19 | PYBIND11_MAKE_OPAQUE(std::vector>); 20 | 21 | using StringList = std::vector>; 22 | 23 | TEST_SUBMODULE(opaque_types, m) { 24 | // test_string_list 25 | py::class_(m, "StringList") 26 | .def(py::init<>()) 27 | .def("pop_back", &StringList::pop_back) 28 | /* There are multiple versions of push_back(), etc. Select the right ones. */ 29 | .def("push_back", (void (StringList::*)(const std::string &)) &StringList::push_back) 30 | .def("back", (std::string &(StringList::*)()) &StringList::back) 31 | .def("__len__", [](const StringList &v) { return v.size(); }) 32 | .def("__iter__", [](StringList &v) { 33 | return py::make_iterator(v.begin(), v.end()); 34 | }, py::keep_alive<0, 1>()); 35 | 36 | class ClassWithSTLVecProperty { 37 | public: 38 | StringList stringList; 39 | }; 40 | py::class_(m, "ClassWithSTLVecProperty") 41 | .def(py::init<>()) 42 | .def_readwrite("stringList", &ClassWithSTLVecProperty::stringList); 43 | 44 | m.def("print_opaque_list", [](const StringList &l) { 45 | std::string ret = "Opaque list: ["; 46 | bool first = true; 47 | for (auto entry : l) { 48 | if (!first) 49 | ret += ", "; 50 | ret += entry; 51 | first = false; 52 | } 53 | return ret + "]"; 54 | }); 55 | 56 | // test_pointers 57 | m.def("return_void_ptr", []() { return (void *) 0x1234; }); 58 | m.def("get_void_ptr_value", [](void *ptr) { return reinterpret_cast(ptr); }); 59 | m.def("return_null_str", []() { return (char *) nullptr; }); 60 | m.def("get_null_str_value", [](char *ptr) { return reinterpret_cast(ptr); }); 61 | 62 | m.def("return_unique_ptr", []() -> std::unique_ptr { 63 | StringList *result = new StringList(); 64 | result->push_back("some value"); 65 | return std::unique_ptr(result); 66 | }); 67 | } 68 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_opaque_types.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from pybind11_tests import opaque_types as m 3 | from pybind11_tests import ConstructorStats, UserType 4 | 5 | 6 | def test_string_list(): 7 | lst = m.StringList() 8 | lst.push_back("Element 1") 9 | lst.push_back("Element 2") 10 | assert m.print_opaque_list(lst) == "Opaque list: [Element 1, Element 2]" 11 | assert lst.back() == "Element 2" 12 | 13 | for i, k in enumerate(lst, start=1): 14 | assert k == "Element {}".format(i) 15 | lst.pop_back() 16 | assert m.print_opaque_list(lst) == "Opaque list: [Element 1]" 17 | 18 | cvp = m.ClassWithSTLVecProperty() 19 | assert m.print_opaque_list(cvp.stringList) == "Opaque list: []" 20 | 21 | cvp.stringList = lst 22 | cvp.stringList.push_back("Element 3") 23 | assert m.print_opaque_list(cvp.stringList) == "Opaque list: [Element 1, Element 3]" 24 | 25 | 26 | def test_pointers(msg): 27 | living_before = ConstructorStats.get(UserType).alive() 28 | assert m.get_void_ptr_value(m.return_void_ptr()) == 0x1234 29 | assert m.get_void_ptr_value(UserType()) # Should also work for other C++ types 30 | assert ConstructorStats.get(UserType).alive() == living_before 31 | 32 | with pytest.raises(TypeError) as excinfo: 33 | m.get_void_ptr_value([1, 2, 3]) # This should not work 34 | assert msg(excinfo.value) == """ 35 | get_void_ptr_value(): incompatible function arguments. The following argument types are supported: 36 | 1. (arg0: capsule) -> int 37 | 38 | Invoked with: [1, 2, 3] 39 | """ # noqa: E501 line too long 40 | 41 | assert m.return_null_str() is None 42 | assert m.get_null_str_value(m.return_null_str()) is not None 43 | 44 | ptr = m.return_unique_ptr() 45 | assert "StringList" in repr(ptr) 46 | assert m.print_opaque_list(ptr) == "Opaque list: [some value]" 47 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_operator_overloading.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from pybind11_tests import operators as m 3 | from pybind11_tests import ConstructorStats 4 | 5 | 6 | def test_operator_overloading(): 7 | v1 = m.Vector2(1, 2) 8 | v2 = m.Vector(3, -1) 9 | v3 = m.Vector2(1, 2) # Same value as v1, but different instance. 10 | assert v1 is not v3 11 | 12 | assert str(v1) == "[1.000000, 2.000000]" 13 | assert str(v2) == "[3.000000, -1.000000]" 14 | 15 | assert str(-v2) == "[-3.000000, 1.000000]" 16 | 17 | assert str(v1 + v2) == "[4.000000, 1.000000]" 18 | assert str(v1 - v2) == "[-2.000000, 3.000000]" 19 | assert str(v1 - 8) == "[-7.000000, -6.000000]" 20 | assert str(v1 + 8) == "[9.000000, 10.000000]" 21 | assert str(v1 * 8) == "[8.000000, 16.000000]" 22 | assert str(v1 / 8) == "[0.125000, 0.250000]" 23 | assert str(8 - v1) == "[7.000000, 6.000000]" 24 | assert str(8 + v1) == "[9.000000, 10.000000]" 25 | assert str(8 * v1) == "[8.000000, 16.000000]" 26 | assert str(8 / v1) == "[8.000000, 4.000000]" 27 | assert str(v1 * v2) == "[3.000000, -2.000000]" 28 | assert str(v2 / v1) == "[3.000000, -0.500000]" 29 | 30 | assert v1 == v3 31 | assert v1 != v2 32 | assert hash(v1) == 4 33 | # TODO(eric.cousineau): Make this work. 34 | # assert abs(v1) == "abs(Vector2)" 35 | 36 | v1 += 2 * v2 37 | assert str(v1) == "[7.000000, 0.000000]" 38 | v1 -= v2 39 | assert str(v1) == "[4.000000, 1.000000]" 40 | v1 *= 2 41 | assert str(v1) == "[8.000000, 2.000000]" 42 | v1 /= 16 43 | assert str(v1) == "[0.500000, 0.125000]" 44 | v1 *= v2 45 | assert str(v1) == "[1.500000, -0.125000]" 46 | v2 /= v1 47 | assert str(v2) == "[2.000000, 8.000000]" 48 | 49 | cstats = ConstructorStats.get(m.Vector2) 50 | assert cstats.alive() == 3 51 | del v1 52 | assert cstats.alive() == 2 53 | del v2 54 | assert cstats.alive() == 1 55 | del v3 56 | assert cstats.alive() == 0 57 | assert cstats.values() == [ 58 | '[1.000000, 2.000000]', 59 | '[3.000000, -1.000000]', 60 | '[1.000000, 2.000000]', 61 | '[-3.000000, 1.000000]', 62 | '[4.000000, 1.000000]', 63 | '[-2.000000, 3.000000]', 64 | '[-7.000000, -6.000000]', 65 | '[9.000000, 10.000000]', 66 | '[8.000000, 16.000000]', 67 | '[0.125000, 0.250000]', 68 | '[7.000000, 6.000000]', 69 | '[9.000000, 10.000000]', 70 | '[8.000000, 16.000000]', 71 | '[8.000000, 4.000000]', 72 | '[3.000000, -2.000000]', 73 | '[3.000000, -0.500000]', 74 | '[6.000000, -2.000000]', 75 | ] 76 | assert cstats.default_constructions == 0 77 | assert cstats.copy_constructions == 0 78 | assert cstats.move_constructions >= 10 79 | assert cstats.copy_assignments == 0 80 | assert cstats.move_assignments == 0 81 | 82 | 83 | def test_operators_notimplemented(): 84 | """#393: need to return NotSupported to ensure correct arithmetic operator behavior""" 85 | 86 | c1, c2 = m.C1(), m.C2() 87 | assert c1 + c1 == 11 88 | assert c2 + c2 == 22 89 | assert c2 + c1 == 21 90 | assert c1 + c2 == 12 91 | 92 | 93 | def test_nested(): 94 | """#328: first member in a class can't be used in operators""" 95 | 96 | a = m.NestA() 97 | b = m.NestB() 98 | c = m.NestC() 99 | 100 | a += 10 101 | assert m.get_NestA(a) == 13 102 | b.a += 100 103 | assert m.get_NestA(b.a) == 103 104 | c.b.a += 1000 105 | assert m.get_NestA(c.b.a) == 1003 106 | b -= 1 107 | assert m.get_NestB(b) == 3 108 | c.b -= 3 109 | assert m.get_NestB(c.b) == 1 110 | c *= 7 111 | assert m.get_NestC(c) == 35 112 | 113 | abase = a.as_base() 114 | assert abase.value == -2 115 | a.as_base().value += 44 116 | assert abase.value == 42 117 | assert c.b.a.as_base().value == -2 118 | c.b.a.as_base().value += 44 119 | assert c.b.a.as_base().value == 42 120 | 121 | del c 122 | pytest.gc_collect() 123 | del a # Shouldn't delete while abase is still alive 124 | pytest.gc_collect() 125 | 126 | assert abase.value == 42 127 | del abase, b 128 | pytest.gc_collect() 129 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_pickling.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_pickling.cpp -- pickle support 3 | 4 | Copyright (c) 2016 Wenzel Jakob 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | 12 | TEST_SUBMODULE(pickling, m) { 13 | // test_roundtrip 14 | class Pickleable { 15 | public: 16 | Pickleable(const std::string &value) : m_value(value) { } 17 | const std::string &value() const { return m_value; } 18 | 19 | void setExtra1(int extra1) { m_extra1 = extra1; } 20 | void setExtra2(int extra2) { m_extra2 = extra2; } 21 | int extra1() const { return m_extra1; } 22 | int extra2() const { return m_extra2; } 23 | private: 24 | std::string m_value; 25 | int m_extra1 = 0; 26 | int m_extra2 = 0; 27 | }; 28 | 29 | class PickleableNew : public Pickleable { 30 | public: 31 | using Pickleable::Pickleable; 32 | }; 33 | 34 | py::class_(m, "Pickleable") 35 | .def(py::init()) 36 | .def("value", &Pickleable::value) 37 | .def("extra1", &Pickleable::extra1) 38 | .def("extra2", &Pickleable::extra2) 39 | .def("setExtra1", &Pickleable::setExtra1) 40 | .def("setExtra2", &Pickleable::setExtra2) 41 | // For details on the methods below, refer to 42 | // http://docs.python.org/3/library/pickle.html#pickling-class-instances 43 | .def("__getstate__", [](const Pickleable &p) { 44 | /* Return a tuple that fully encodes the state of the object */ 45 | return py::make_tuple(p.value(), p.extra1(), p.extra2()); 46 | }) 47 | .def("__setstate__", [](Pickleable &p, py::tuple t) { 48 | if (t.size() != 3) 49 | throw std::runtime_error("Invalid state!"); 50 | /* Invoke the constructor (need to use in-place version) */ 51 | new (&p) Pickleable(t[0].cast()); 52 | 53 | /* Assign any additional state */ 54 | p.setExtra1(t[1].cast()); 55 | p.setExtra2(t[2].cast()); 56 | }); 57 | 58 | py::class_(m, "PickleableNew") 59 | .def(py::init()) 60 | .def(py::pickle( 61 | [](const PickleableNew &p) { 62 | return py::make_tuple(p.value(), p.extra1(), p.extra2()); 63 | }, 64 | [](py::tuple t) { 65 | if (t.size() != 3) 66 | throw std::runtime_error("Invalid state!"); 67 | auto p = PickleableNew(t[0].cast()); 68 | 69 | p.setExtra1(t[1].cast()); 70 | p.setExtra2(t[2].cast()); 71 | return p; 72 | } 73 | )); 74 | 75 | #if !defined(PYPY_VERSION) 76 | // test_roundtrip_with_dict 77 | class PickleableWithDict { 78 | public: 79 | PickleableWithDict(const std::string &value) : value(value) { } 80 | 81 | std::string value; 82 | int extra; 83 | }; 84 | 85 | class PickleableWithDictNew : public PickleableWithDict { 86 | public: 87 | using PickleableWithDict::PickleableWithDict; 88 | }; 89 | 90 | py::class_(m, "PickleableWithDict", py::dynamic_attr()) 91 | .def(py::init()) 92 | .def_readwrite("value", &PickleableWithDict::value) 93 | .def_readwrite("extra", &PickleableWithDict::extra) 94 | .def("__getstate__", [](py::object self) { 95 | /* Also include __dict__ in state */ 96 | return py::make_tuple(self.attr("value"), self.attr("extra"), self.attr("__dict__")); 97 | }) 98 | .def("__setstate__", [](py::object self, py::tuple t) { 99 | if (t.size() != 3) 100 | throw std::runtime_error("Invalid state!"); 101 | /* Cast and construct */ 102 | auto& p = self.cast(); 103 | new (&p) PickleableWithDict(t[0].cast()); 104 | 105 | /* Assign C++ state */ 106 | p.extra = t[1].cast(); 107 | 108 | /* Assign Python state */ 109 | self.attr("__dict__") = t[2]; 110 | }); 111 | 112 | py::class_(m, "PickleableWithDictNew") 113 | .def(py::init()) 114 | .def(py::pickle( 115 | [](py::object self) { 116 | return py::make_tuple(self.attr("value"), self.attr("extra"), self.attr("__dict__")); 117 | }, 118 | [](const py::tuple &t) { 119 | if (t.size() != 3) 120 | throw std::runtime_error("Invalid state!"); 121 | 122 | auto cpp_state = PickleableWithDictNew(t[0].cast()); 123 | cpp_state.extra = t[1].cast(); 124 | 125 | auto py_state = t[2].cast(); 126 | return std::make_pair(cpp_state, py_state); 127 | } 128 | )); 129 | #endif 130 | } 131 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_pickling.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from pybind11_tests import pickling as m 3 | 4 | try: 5 | import cPickle as pickle # Use cPickle on Python 2.7 6 | except ImportError: 7 | import pickle 8 | 9 | 10 | @pytest.mark.parametrize("cls_name", ["Pickleable", "PickleableNew"]) 11 | def test_roundtrip(cls_name): 12 | cls = getattr(m, cls_name) 13 | p = cls("test_value") 14 | p.setExtra1(15) 15 | p.setExtra2(48) 16 | 17 | data = pickle.dumps(p, 2) # Must use pickle protocol >= 2 18 | p2 = pickle.loads(data) 19 | assert p2.value() == p.value() 20 | assert p2.extra1() == p.extra1() 21 | assert p2.extra2() == p.extra2() 22 | 23 | 24 | @pytest.unsupported_on_pypy 25 | @pytest.mark.parametrize("cls_name", ["PickleableWithDict", "PickleableWithDictNew"]) 26 | def test_roundtrip_with_dict(cls_name): 27 | cls = getattr(m, cls_name) 28 | p = cls("test_value") 29 | p.extra = 15 30 | p.dynamic = "Attribute" 31 | 32 | data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL) 33 | p2 = pickle.loads(data) 34 | assert p2.value == p.value 35 | assert p2.extra == p.extra 36 | assert p2.dynamic == p.dynamic 37 | 38 | 39 | def test_enum_pickle(): 40 | from pybind11_tests import enums as e 41 | data = pickle.dumps(e.EOne, 2) 42 | assert e.EOne == pickle.loads(data) 43 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_tagbased_polymorphic.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_tagbased_polymorphic.cpp -- test of polymorphic_type_hook 3 | 4 | Copyright (c) 2018 Hudson River Trading LLC 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | #include 12 | 13 | struct Animal 14 | { 15 | // Make this type also a "standard" polymorphic type, to confirm that 16 | // specializing polymorphic_type_hook using enable_if_t still works 17 | // (https://github.com/pybind/pybind11/pull/2016/). 18 | virtual ~Animal() = default; 19 | 20 | // Enum for tag-based polymorphism. 21 | enum class Kind { 22 | Unknown = 0, 23 | Dog = 100, Labrador, Chihuahua, LastDog = 199, 24 | Cat = 200, Panther, LastCat = 299 25 | }; 26 | static const std::type_info* type_of_kind(Kind kind); 27 | static std::string name_of_kind(Kind kind); 28 | 29 | const Kind kind; 30 | const std::string name; 31 | 32 | protected: 33 | Animal(const std::string& _name, Kind _kind) 34 | : kind(_kind), name(_name) 35 | {} 36 | }; 37 | 38 | struct Dog : Animal 39 | { 40 | Dog(const std::string& _name, Kind _kind = Kind::Dog) : Animal(_name, _kind) {} 41 | std::string bark() const { return name_of_kind(kind) + " " + name + " goes " + sound; } 42 | std::string sound = "WOOF!"; 43 | }; 44 | 45 | struct Labrador : Dog 46 | { 47 | Labrador(const std::string& _name, int _excitement = 9001) 48 | : Dog(_name, Kind::Labrador), excitement(_excitement) {} 49 | int excitement; 50 | }; 51 | 52 | struct Chihuahua : Dog 53 | { 54 | Chihuahua(const std::string& _name) : Dog(_name, Kind::Chihuahua) { sound = "iyiyiyiyiyi"; } 55 | std::string bark() const { return Dog::bark() + " and runs in circles"; } 56 | }; 57 | 58 | struct Cat : Animal 59 | { 60 | Cat(const std::string& _name, Kind _kind = Kind::Cat) : Animal(_name, _kind) {} 61 | std::string purr() const { return "mrowr"; } 62 | }; 63 | 64 | struct Panther : Cat 65 | { 66 | Panther(const std::string& _name) : Cat(_name, Kind::Panther) {} 67 | std::string purr() const { return "mrrrRRRRRR"; } 68 | }; 69 | 70 | std::vector> create_zoo() 71 | { 72 | std::vector> ret; 73 | ret.emplace_back(new Labrador("Fido", 15000)); 74 | 75 | // simulate some new type of Dog that the Python bindings 76 | // haven't been updated for; it should still be considered 77 | // a Dog, not just an Animal. 78 | ret.emplace_back(new Dog("Ginger", Dog::Kind(150))); 79 | 80 | ret.emplace_back(new Chihuahua("Hertzl")); 81 | ret.emplace_back(new Cat("Tiger", Cat::Kind::Cat)); 82 | ret.emplace_back(new Panther("Leo")); 83 | return ret; 84 | } 85 | 86 | const std::type_info* Animal::type_of_kind(Kind kind) 87 | { 88 | switch (kind) { 89 | case Kind::Unknown: break; 90 | 91 | case Kind::Dog: break; 92 | case Kind::Labrador: return &typeid(Labrador); 93 | case Kind::Chihuahua: return &typeid(Chihuahua); 94 | case Kind::LastDog: break; 95 | 96 | case Kind::Cat: break; 97 | case Kind::Panther: return &typeid(Panther); 98 | case Kind::LastCat: break; 99 | } 100 | 101 | if (kind >= Kind::Dog && kind <= Kind::LastDog) return &typeid(Dog); 102 | if (kind >= Kind::Cat && kind <= Kind::LastCat) return &typeid(Cat); 103 | return nullptr; 104 | } 105 | 106 | std::string Animal::name_of_kind(Kind kind) 107 | { 108 | std::string raw_name = type_of_kind(kind)->name(); 109 | py::detail::clean_type_id(raw_name); 110 | return raw_name; 111 | } 112 | 113 | namespace pybind11 { 114 | template 115 | struct polymorphic_type_hook::value>> 116 | { 117 | static const void *get(const itype *src, const std::type_info*& type) 118 | { type = src ? Animal::type_of_kind(src->kind) : nullptr; return src; } 119 | }; 120 | } 121 | 122 | TEST_SUBMODULE(tagbased_polymorphic, m) { 123 | py::class_(m, "Animal") 124 | .def_readonly("name", &Animal::name); 125 | py::class_(m, "Dog") 126 | .def(py::init()) 127 | .def_readwrite("sound", &Dog::sound) 128 | .def("bark", &Dog::bark); 129 | py::class_(m, "Labrador") 130 | .def(py::init(), "name"_a, "excitement"_a = 9001) 131 | .def_readwrite("excitement", &Labrador::excitement); 132 | py::class_(m, "Chihuahua") 133 | .def(py::init()) 134 | .def("bark", &Chihuahua::bark); 135 | py::class_(m, "Cat") 136 | .def(py::init()) 137 | .def("purr", &Cat::purr); 138 | py::class_(m, "Panther") 139 | .def(py::init()) 140 | .def("purr", &Panther::purr); 141 | m.def("create_zoo", &create_zoo); 142 | }; 143 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_tagbased_polymorphic.py: -------------------------------------------------------------------------------- 1 | from pybind11_tests import tagbased_polymorphic as m 2 | 3 | 4 | def test_downcast(): 5 | zoo = m.create_zoo() 6 | assert [type(animal) for animal in zoo] == [ 7 | m.Labrador, m.Dog, m.Chihuahua, m.Cat, m.Panther 8 | ] 9 | assert [animal.name for animal in zoo] == [ 10 | "Fido", "Ginger", "Hertzl", "Tiger", "Leo" 11 | ] 12 | zoo[1].sound = "woooooo" 13 | assert [dog.bark() for dog in zoo[:3]] == [ 14 | "Labrador Fido goes WOOF!", 15 | "Dog Ginger goes woooooo", 16 | "Chihuahua Hertzl goes iyiyiyiyiyi and runs in circles" 17 | ] 18 | assert [cat.purr() for cat in zoo[3:]] == ["mrowr", "mrrrRRRRRR"] 19 | zoo[0].excitement -= 1000 20 | assert zoo[0].excitement == 14000 21 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_union.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | tests/test_class.cpp -- test py::class_ definitions and basic functionality 3 | 4 | Copyright (c) 2019 Roland Dreier 5 | 6 | All rights reserved. Use of this source code is governed by a 7 | BSD-style license that can be found in the LICENSE file. 8 | */ 9 | 10 | #include "pybind11_tests.h" 11 | 12 | TEST_SUBMODULE(union_, m) { 13 | union TestUnion { 14 | int value_int; 15 | unsigned value_uint; 16 | }; 17 | 18 | py::class_(m, "TestUnion") 19 | .def(py::init<>()) 20 | .def_readonly("as_int", &TestUnion::value_int) 21 | .def_readwrite("as_uint", &TestUnion::value_uint); 22 | } 23 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tests/test_union.py: -------------------------------------------------------------------------------- 1 | from pybind11_tests import union_ as m 2 | 3 | 4 | def test_union(): 5 | instance = m.TestUnion() 6 | 7 | instance.as_uint = 10 8 | assert instance.as_int == 10 9 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tools/FindCatch.cmake: -------------------------------------------------------------------------------- 1 | # - Find the Catch test framework or download it (single header) 2 | # 3 | # This is a quick module for internal use. It assumes that Catch is 4 | # REQUIRED and that a minimum version is provided (not EXACT). If 5 | # a suitable version isn't found locally, the single header file 6 | # will be downloaded and placed in the build dir: PROJECT_BINARY_DIR. 7 | # 8 | # This code sets the following variables: 9 | # CATCH_INCLUDE_DIR - path to catch.hpp 10 | # CATCH_VERSION - version number 11 | 12 | if(NOT Catch_FIND_VERSION) 13 | message(FATAL_ERROR "A version number must be specified.") 14 | elseif(Catch_FIND_REQUIRED) 15 | message(FATAL_ERROR "This module assumes Catch is not required.") 16 | elseif(Catch_FIND_VERSION_EXACT) 17 | message(FATAL_ERROR "Exact version numbers are not supported, only minimum.") 18 | endif() 19 | 20 | # Extract the version number from catch.hpp 21 | function(_get_catch_version) 22 | file(STRINGS "${CATCH_INCLUDE_DIR}/catch.hpp" version_line REGEX "Catch v.*" LIMIT_COUNT 1) 23 | if(version_line MATCHES "Catch v([0-9]+)\\.([0-9]+)\\.([0-9]+)") 24 | set(CATCH_VERSION "${CMAKE_MATCH_1}.${CMAKE_MATCH_2}.${CMAKE_MATCH_3}" PARENT_SCOPE) 25 | endif() 26 | endfunction() 27 | 28 | # Download the single-header version of Catch 29 | function(_download_catch version destination_dir) 30 | message(STATUS "Downloading catch v${version}...") 31 | set(url https://github.com/philsquared/Catch/releases/download/v${version}/catch.hpp) 32 | file(DOWNLOAD ${url} "${destination_dir}/catch.hpp" STATUS status) 33 | list(GET status 0 error) 34 | if(error) 35 | message(FATAL_ERROR "Could not download ${url}") 36 | endif() 37 | set(CATCH_INCLUDE_DIR "${destination_dir}" CACHE INTERNAL "") 38 | endfunction() 39 | 40 | # Look for catch locally 41 | find_path(CATCH_INCLUDE_DIR NAMES catch.hpp PATH_SUFFIXES catch) 42 | if(CATCH_INCLUDE_DIR) 43 | _get_catch_version() 44 | endif() 45 | 46 | # Download the header if it wasn't found or if it's outdated 47 | if(NOT CATCH_VERSION OR CATCH_VERSION VERSION_LESS ${Catch_FIND_VERSION}) 48 | if(DOWNLOAD_CATCH) 49 | _download_catch(${Catch_FIND_VERSION} "${PROJECT_BINARY_DIR}/catch/") 50 | _get_catch_version() 51 | else() 52 | set(CATCH_FOUND FALSE) 53 | return() 54 | endif() 55 | endif() 56 | 57 | set(CATCH_FOUND TRUE) 58 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tools/FindEigen3.cmake: -------------------------------------------------------------------------------- 1 | # - Try to find Eigen3 lib 2 | # 3 | # This module supports requiring a minimum version, e.g. you can do 4 | # find_package(Eigen3 3.1.2) 5 | # to require version 3.1.2 or newer of Eigen3. 6 | # 7 | # Once done this will define 8 | # 9 | # EIGEN3_FOUND - system has eigen lib with correct version 10 | # EIGEN3_INCLUDE_DIR - the eigen include directory 11 | # EIGEN3_VERSION - eigen version 12 | 13 | # Copyright (c) 2006, 2007 Montel Laurent, 14 | # Copyright (c) 2008, 2009 Gael Guennebaud, 15 | # Copyright (c) 2009 Benoit Jacob 16 | # Redistribution and use is allowed according to the terms of the 2-clause BSD license. 17 | 18 | if(NOT Eigen3_FIND_VERSION) 19 | if(NOT Eigen3_FIND_VERSION_MAJOR) 20 | set(Eigen3_FIND_VERSION_MAJOR 2) 21 | endif(NOT Eigen3_FIND_VERSION_MAJOR) 22 | if(NOT Eigen3_FIND_VERSION_MINOR) 23 | set(Eigen3_FIND_VERSION_MINOR 91) 24 | endif(NOT Eigen3_FIND_VERSION_MINOR) 25 | if(NOT Eigen3_FIND_VERSION_PATCH) 26 | set(Eigen3_FIND_VERSION_PATCH 0) 27 | endif(NOT Eigen3_FIND_VERSION_PATCH) 28 | 29 | set(Eigen3_FIND_VERSION "${Eigen3_FIND_VERSION_MAJOR}.${Eigen3_FIND_VERSION_MINOR}.${Eigen3_FIND_VERSION_PATCH}") 30 | endif(NOT Eigen3_FIND_VERSION) 31 | 32 | macro(_eigen3_check_version) 33 | file(READ "${EIGEN3_INCLUDE_DIR}/Eigen/src/Core/util/Macros.h" _eigen3_version_header) 34 | 35 | string(REGEX MATCH "define[ \t]+EIGEN_WORLD_VERSION[ \t]+([0-9]+)" _eigen3_world_version_match "${_eigen3_version_header}") 36 | set(EIGEN3_WORLD_VERSION "${CMAKE_MATCH_1}") 37 | string(REGEX MATCH "define[ \t]+EIGEN_MAJOR_VERSION[ \t]+([0-9]+)" _eigen3_major_version_match "${_eigen3_version_header}") 38 | set(EIGEN3_MAJOR_VERSION "${CMAKE_MATCH_1}") 39 | string(REGEX MATCH "define[ \t]+EIGEN_MINOR_VERSION[ \t]+([0-9]+)" _eigen3_minor_version_match "${_eigen3_version_header}") 40 | set(EIGEN3_MINOR_VERSION "${CMAKE_MATCH_1}") 41 | 42 | set(EIGEN3_VERSION ${EIGEN3_WORLD_VERSION}.${EIGEN3_MAJOR_VERSION}.${EIGEN3_MINOR_VERSION}) 43 | if(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) 44 | set(EIGEN3_VERSION_OK FALSE) 45 | else(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) 46 | set(EIGEN3_VERSION_OK TRUE) 47 | endif(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) 48 | 49 | if(NOT EIGEN3_VERSION_OK) 50 | 51 | message(STATUS "Eigen3 version ${EIGEN3_VERSION} found in ${EIGEN3_INCLUDE_DIR}, " 52 | "but at least version ${Eigen3_FIND_VERSION} is required") 53 | endif(NOT EIGEN3_VERSION_OK) 54 | endmacro(_eigen3_check_version) 55 | 56 | if (EIGEN3_INCLUDE_DIR) 57 | 58 | # in cache already 59 | _eigen3_check_version() 60 | set(EIGEN3_FOUND ${EIGEN3_VERSION_OK}) 61 | 62 | else (EIGEN3_INCLUDE_DIR) 63 | 64 | find_path(EIGEN3_INCLUDE_DIR NAMES signature_of_eigen3_matrix_library 65 | PATHS 66 | ${CMAKE_INSTALL_PREFIX}/include 67 | ${KDE4_INCLUDE_DIR} 68 | PATH_SUFFIXES eigen3 eigen 69 | ) 70 | 71 | if(EIGEN3_INCLUDE_DIR) 72 | _eigen3_check_version() 73 | endif(EIGEN3_INCLUDE_DIR) 74 | 75 | include(FindPackageHandleStandardArgs) 76 | find_package_handle_standard_args(Eigen3 DEFAULT_MSG EIGEN3_INCLUDE_DIR EIGEN3_VERSION_OK) 77 | 78 | mark_as_advanced(EIGEN3_INCLUDE_DIR) 79 | 80 | endif(EIGEN3_INCLUDE_DIR) 81 | 82 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tools/check-style.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Script to check include/test code for common pybind11 code style errors. 4 | # 5 | # This script currently checks for 6 | # 7 | # 1. use of tabs instead of spaces 8 | # 2. MSDOS-style CRLF endings 9 | # 3. trailing spaces 10 | # 4. missing space between keyword and parenthesis, e.g.: for(, if(, while( 11 | # 5. Missing space between right parenthesis and brace, e.g. 'for (...){' 12 | # 6. opening brace on its own line. It should always be on the same line as the 13 | # if/while/for/do statement. 14 | # 15 | # Invoke as: tools/check-style.sh 16 | # 17 | 18 | check_style_errors=0 19 | IFS=$'\n' 20 | 21 | found="$( GREP_COLORS='mt=41' GREP_COLOR='41' grep $'\t' include tests/*.{cpp,py,h} docs/*.rst -rn --color=always )" 22 | if [ -n "$found" ]; then 23 | # The mt=41 sets a red background for matched tabs: 24 | echo -e '\033[31;01mError: found tab characters in the following files:\033[0m' 25 | check_style_errors=1 26 | echo "$found" | sed -e 's/^/ /' 27 | fi 28 | 29 | 30 | found="$( grep -IUlr $'\r' include tests/*.{cpp,py,h} docs/*.rst --color=always )" 31 | if [ -n "$found" ]; then 32 | echo -e '\033[31;01mError: found CRLF characters in the following files:\033[0m' 33 | check_style_errors=1 34 | echo "$found" | sed -e 's/^/ /' 35 | fi 36 | 37 | found="$(GREP_COLORS='mt=41' GREP_COLOR='41' grep '[[:blank:]]\+$' include tests/*.{cpp,py,h} docs/*.rst -rn --color=always )" 38 | if [ -n "$found" ]; then 39 | # The mt=41 sets a red background for matched trailing spaces 40 | echo -e '\033[31;01mError: found trailing spaces in the following files:\033[0m' 41 | check_style_errors=1 42 | echo "$found" | sed -e 's/^/ /' 43 | fi 44 | 45 | found="$(grep '\<\(if\|for\|while\|catch\)(\|){' include tests/*.{cpp,h} -rn --color=always)" 46 | if [ -n "$found" ]; then 47 | echo -e '\033[31;01mError: found the following coding style problems:\033[0m' 48 | check_style_errors=1 49 | echo "$found" | sed -e 's/^/ /' 50 | fi 51 | 52 | found="$(awk ' 53 | function prefix(filename, lineno) { 54 | return " \033[35m" filename "\033[36m:\033[32m" lineno "\033[36m:\033[0m" 55 | } 56 | function mark(pattern, string) { sub(pattern, "\033[01;31m&\033[0m", string); return string } 57 | last && /^\s*{/ { 58 | print prefix(FILENAME, FNR-1) mark("\\)\\s*$", last) 59 | print prefix(FILENAME, FNR) mark("^\\s*{", $0) 60 | last="" 61 | } 62 | { last = /(if|for|while|catch|switch)\s*\(.*\)\s*$/ ? $0 : "" } 63 | ' $(find include -type f) tests/*.{cpp,h} docs/*.rst)" 64 | if [ -n "$found" ]; then 65 | check_style_errors=1 66 | echo -e '\033[31;01mError: braces should occur on the same line as the if/while/.. statement. Found issues in the following files:\033[0m' 67 | echo "$found" 68 | fi 69 | 70 | exit $check_style_errors 71 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tools/libsize.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function, division 2 | import os 3 | import sys 4 | 5 | # Internal build script for generating debugging test .so size. 6 | # Usage: 7 | # python libsize.py file.so save.txt -- displays the size of file.so and, if save.txt exists, compares it to the 8 | # size in it, then overwrites save.txt with the new size for future runs. 9 | 10 | if len(sys.argv) != 3: 11 | sys.exit("Invalid arguments: usage: python libsize.py file.so save.txt") 12 | 13 | lib = sys.argv[1] 14 | save = sys.argv[2] 15 | 16 | if not os.path.exists(lib): 17 | sys.exit("Error: requested file ({}) does not exist".format(lib)) 18 | 19 | libsize = os.path.getsize(lib) 20 | 21 | print("------", os.path.basename(lib), "file size:", libsize, end='') 22 | 23 | if os.path.exists(save): 24 | with open(save) as sf: 25 | oldsize = int(sf.readline()) 26 | 27 | if oldsize > 0: 28 | change = libsize - oldsize 29 | if change == 0: 30 | print(" (no change)") 31 | else: 32 | print(" (change of {:+} bytes = {:+.2%})".format(change, change / oldsize)) 33 | else: 34 | print() 35 | 36 | with open(save, 'w') as sf: 37 | sf.write(str(libsize)) 38 | 39 | -------------------------------------------------------------------------------- /ATT/pybind11-master/tools/pybind11Config.cmake.in: -------------------------------------------------------------------------------- 1 | # pybind11Config.cmake 2 | # -------------------- 3 | # 4 | # PYBIND11 cmake module. 5 | # This module sets the following variables in your project:: 6 | # 7 | # pybind11_FOUND - true if pybind11 and all required components found on the system 8 | # pybind11_VERSION - pybind11 version in format Major.Minor.Release 9 | # pybind11_INCLUDE_DIRS - Directories where pybind11 and python headers are located. 10 | # pybind11_INCLUDE_DIR - Directory where pybind11 headers are located. 11 | # pybind11_DEFINITIONS - Definitions necessary to use pybind11, namely USING_pybind11. 12 | # pybind11_LIBRARIES - compile flags and python libraries (as needed) to link against. 13 | # pybind11_LIBRARY - empty. 14 | # CMAKE_MODULE_PATH - appends location of accompanying FindPythonLibsNew.cmake and 15 | # pybind11Tools.cmake modules. 16 | # 17 | # 18 | # Available components: None 19 | # 20 | # 21 | # Exported targets:: 22 | # 23 | # If pybind11 is found, this module defines the following :prop_tgt:`IMPORTED` 24 | # interface library targets:: 25 | # 26 | # pybind11::module - for extension modules 27 | # pybind11::embed - for embedding the Python interpreter 28 | # 29 | # Python headers, libraries (as needed by platform), and the C++ standard 30 | # are attached to the target. Set PythonLibsNew variables to influence 31 | # python detection and CMAKE_CXX_STANDARD (11 or 14) to influence standard 32 | # setting. :: 33 | # 34 | # find_package(pybind11 CONFIG REQUIRED) 35 | # message(STATUS "Found pybind11 v${pybind11_VERSION}: ${pybind11_INCLUDE_DIRS}") 36 | # 37 | # # Create an extension module 38 | # add_library(mylib MODULE main.cpp) 39 | # target_link_libraries(mylib pybind11::module) 40 | # 41 | # # Or embed the Python interpreter into an executable 42 | # add_executable(myexe main.cpp) 43 | # target_link_libraries(myexe pybind11::embed) 44 | # 45 | # Suggested usage:: 46 | # 47 | # find_package with version info is not recommended except for release versions. :: 48 | # 49 | # find_package(pybind11 CONFIG) 50 | # find_package(pybind11 2.0 EXACT CONFIG REQUIRED) 51 | # 52 | # 53 | # The following variables can be set to guide the search for this package:: 54 | # 55 | # pybind11_DIR - CMake variable, set to directory containing this Config file 56 | # CMAKE_PREFIX_PATH - CMake variable, set to root directory of this package 57 | # PATH - environment variable, set to bin directory of this package 58 | # CMAKE_DISABLE_FIND_PACKAGE_pybind11 - CMake variable, disables 59 | # find_package(pybind11) when not REQUIRED, perhaps to force internal build 60 | 61 | @PACKAGE_INIT@ 62 | 63 | set(PN pybind11) 64 | 65 | # location of pybind11/pybind11.h 66 | set(${PN}_INCLUDE_DIR "${PACKAGE_PREFIX_DIR}/@CMAKE_INSTALL_INCLUDEDIR@") 67 | 68 | set(${PN}_LIBRARY "") 69 | set(${PN}_DEFINITIONS USING_${PN}) 70 | 71 | check_required_components(${PN}) 72 | 73 | # make detectable the FindPythonLibsNew.cmake module 74 | list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}) 75 | 76 | include(pybind11Tools) 77 | 78 | if(NOT (CMAKE_VERSION VERSION_LESS 3.0)) 79 | #----------------------------------------------------------------------------- 80 | # Don't include targets if this file is being picked up by another 81 | # project which has already built this as a subproject 82 | #----------------------------------------------------------------------------- 83 | if(NOT TARGET ${PN}::pybind11) 84 | include("${CMAKE_CURRENT_LIST_DIR}/${PN}Targets.cmake") 85 | 86 | find_package(PythonLibsNew ${PYBIND11_PYTHON_VERSION} MODULE REQUIRED) 87 | set_property(TARGET ${PN}::pybind11 APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES ${PYTHON_INCLUDE_DIRS}) 88 | set_property(TARGET ${PN}::embed APPEND PROPERTY INTERFACE_LINK_LIBRARIES ${PYTHON_LIBRARIES}) 89 | if(WIN32 OR CYGWIN) 90 | set_property(TARGET ${PN}::module APPEND PROPERTY INTERFACE_LINK_LIBRARIES ${PYTHON_LIBRARIES}) 91 | endif() 92 | 93 | if(CMAKE_VERSION VERSION_LESS 3.3) 94 | set_property(TARGET ${PN}::pybind11 APPEND PROPERTY INTERFACE_COMPILE_OPTIONS "${PYBIND11_CPP_STANDARD}") 95 | else() 96 | set_property(TARGET ${PN}::pybind11 APPEND PROPERTY INTERFACE_COMPILE_OPTIONS $<$:${PYBIND11_CPP_STANDARD}>) 97 | endif() 98 | 99 | get_property(_iid TARGET ${PN}::pybind11 PROPERTY INTERFACE_INCLUDE_DIRECTORIES) 100 | get_property(_ill TARGET ${PN}::module PROPERTY INTERFACE_LINK_LIBRARIES) 101 | set(${PN}_INCLUDE_DIRS ${_iid}) 102 | set(${PN}_LIBRARIES ${_ico} ${_ill}) 103 | endif() 104 | endif() 105 | -------------------------------------------------------------------------------- /ATT/setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | from setuptools import setup 4 | from torch.utils.cpp_extension import BuildExtension, CUDAExtension 5 | 6 | include_dirs = torch.utils.cpp_extension.include_paths() 7 | print(include_dirs) 8 | include_dirs.append('/media/yanshi/windows/attention_kernel/src') 9 | include_dirs.append('/media/yanshi/windows/attention_kernel/pybind11-master/include') 10 | print(include_dirs) 11 | 12 | setup( 13 | name="attention_package", 14 | version="0.2", 15 | description="attention layer", 16 | # url="https://github.com/jbarker-nvidia/pytorch-correlation", 17 | author="Saurus", 18 | author_email="jia1saurus@gmail.com", 19 | ext_modules = [ 20 | CUDAExtension(name='at_cuda', 21 | include_dirs = include_dirs, 22 | sources=['src/attention_kernel.cu', 'src/attention_cuda.cpp']) 23 | ], 24 | cmdclass={ 25 | 'build_ext' : BuildExtension 26 | } 27 | ) 28 | -------------------------------------------------------------------------------- /ATT/src/attention_cuda.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "attention_kernel.h" 5 | 6 | extern THCState *state; 7 | 8 | int hello_world(torch::Tensor test){ 9 | return 1; 10 | } 11 | 12 | int attention_cuda_forward(torch::Tensor input1, torch::Tensor input2, torch::Tensor output, int kernel_size, int pad_size, int stride){ 13 | int batch_size = input1.size(0); 14 | int input_rows = input1.size(1); 15 | int input_cols = input1.size(2); 16 | int input_ch = input1.size(3); 17 | 18 | int kernel_radius = kernel_size / 2; 19 | 20 | int output_cols = (input_cols - kernel_radius * 2 - 1) / stride + 1; 21 | int output_rows = (input_rows - kernel_radius * 2 - 1) / stride + 1; 22 | int output_ch = kernel_size * kernel_size; 23 | 24 | attention_forward_ongpu(input1.data(), input2.data(), output.data(), 25 | kernel_size, pad_size, stride, input_cols, input_rows, output_cols, output_rows, 26 | input_ch, output_ch, batch_size); 27 | 28 | return 1; 29 | } 30 | 31 | int attention_cuda_backward(torch::Tensor input1, torch::Tensor input2, torch::Tensor grad_input, torch::Tensor grad_input_padding, 32 | torch::Tensor grad_output1, torch::Tensor grad_output2, int kernel_size, int pad_size, int stride){ 33 | int batch_size = input1.size(0); 34 | int input_rows = input1.size(1); 35 | int input_cols = input1.size(2); 36 | int input_ch = input1.size(3); 37 | 38 | int kernel_radius = kernel_size / 2; 39 | 40 | int output_cols = (input_cols - kernel_radius * 2 - 1) / stride + 1; 41 | int output_rows = (input_rows - kernel_radius * 2 - 1) / stride + 1; 42 | int output_ch = kernel_size * kernel_size; 43 | 44 | attention_backward_ongpu(input1.data(), input2.data(), grad_input.data(), 45 | grad_input_padding.data(), grad_output1.data(), grad_output2.data(), kernel_size, 46 | pad_size, stride, input_cols, input_rows, output_cols, output_rows, input_ch, output_ch, batch_size); 47 | 48 | return 1; 49 | } 50 | 51 | int channel_attention_cuda_forward(torch::Tensor input1, torch::Tensor input2, torch::Tensor output, int kernel_size, int pad_size, int stride){ 52 | int batch_size = input1.size(0); 53 | int input1_rows = input1.size(1); 54 | int input1_cols = input1.size(2); 55 | int input1_chs = input1.size(3); 56 | 57 | int input2_rows = input2.size(1); 58 | int input2_cols = input2.size(2); 59 | int input2_chs = input2.size(3); 60 | 61 | int kernel_radius = kernel_size / 2; 62 | 63 | channel_attention_forward_ongpu(input1.data(), input2.data(), output.data(), 64 | kernel_size, pad_size, stride, input1_cols, input1_rows, input2_cols, input2_rows, input1_chs, input2_chs, batch_size); 65 | 66 | return 1; 67 | } 68 | 69 | int channel_attention_cuda_backward(torch::Tensor input1, torch::Tensor input2, torch::Tensor grad_input, torch::Tensor grad_output1, torch::Tensor grad_output2, 70 | int kernel_size, int pad_size, int stride){ 71 | int batch_size = input1.size(0); 72 | int input1_rows = input1.size(1); 73 | int input1_cols = input1.size(2); 74 | int input1_chs = input1.size(3); 75 | 76 | int input2_rows = input2.size(1); 77 | int input2_cols = input2.size(2); 78 | int input2_chs = input2.size(3); 79 | 80 | int kernel_radius = kernel_size / 2; 81 | 82 | channel_attention_backward_ongpu(input1.data(), input2.data(), grad_input.data(), grad_output1.data(), grad_output2.data(), 83 | kernel_size, pad_size, stride, input1_cols, input1_rows, input2_cols, input2_rows, input1_chs, input2_chs, batch_size); 84 | return 1; 85 | } 86 | 87 | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { 88 | m.def("forward", &attention_cuda_forward, "ATT forward"); 89 | m.def("backward", &attention_cuda_backward, "ATT backward"); 90 | m.def("channel_forward", &channel_attention_cuda_forward, "ATT channel forward"); 91 | m.def("channel_backward", &channel_attention_cuda_backward, "ATT channel backward"); 92 | m.def("test", &hello_world, "testing"); 93 | } -------------------------------------------------------------------------------- /ATT/src/attention_kernel.h: -------------------------------------------------------------------------------- 1 | #ifndef _ATTENTION_CUDA_KERNEL 2 | #define _ATTENTION_CUDA_KERNEL 3 | 4 | void attention_forward_ongpu(const float* input1, const float* input2, float* output, int kernel_size, int pad_size, int stride, 5 | int input_cols, int input_rows, int output_cols, int output_rows, int input_ch, int output_ch, int batch_size); 6 | 7 | void attention_backward_ongpu(const float* input1, const float* input2, const float* grad_input, const float* grad_input_padding, 8 | float* grad_output0, float* grad_output1, int kernel_size, int pad_size, int stride, 9 | int input_cols, int input_rows, int output_cols, int output_rows, int input_ch, int output_ch, int batch_size); 10 | 11 | void channel_attention_forward_ongpu(const float* input1, const float* input2, float* output, int kernel_size, int pad_size, int stride, 12 | int input1_cols, int input1_rows, int input2_cols, int input2_rows, int input1_chs, int input2_chs, int batch_size); 13 | 14 | void channel_attention_backward_ongpu(const float* input1, const float* input2, const float* grad_input, float* grad_output1, float* grad_output2, 15 | int kernel_size, int pad_size, int stride, int input1_cols, int input1_rows, int input2_cols, int input2_rows, int input1_chs, int input2_chs, int batch_size); 16 | 17 | #endif -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [LocalTrans: A Multiscale Local Transformer Network for Cross-Resolution Homography Estimation](http://www.liuyebin.com/localtrans/localtrans.html) 2 | Ruizhi Shao*, Gaochang Wu*, Yuemei Zhou, Ying Fu, Lu Fang, Yebin Liu 3 | 4 | [![report](https://img.shields.io/badge/arxiv-report-red)](https://arxiv.org/abs/2106.04067) 5 | 6 | This repository contains the official pytorch implementation of ”*LocalTrans: A Multiscale Local Transformer Network for Cross-Resolution Homography Estimation*“. 7 | 8 | ![Teaser Image](assets/teaser.jpg) 9 | 10 | ## Requirements 11 | - pytorch 12 | - matplotlib 13 | - numpy 14 | - cv2 15 | - tensorboard 16 | - kornia 17 | - imageio 18 | 19 | ## Pretrained Model 20 | We have provided pretrained model under several settings in [One Drive](https://mailstsinghuaeducn-my.sharepoint.com/:f:/g/personal/shaorz20_mails_tsinghua_edu_cn/Et6rFUvWy8VNjC6gDWhpOSoBjZ9ISDTGkaTBumLafQ9asw?e=IQe8Or) 21 | 22 | 23 | ## Training 24 | To train localtrans on the COCO dataset in different setting, run the following code: 25 | ``` 26 | sh train.sh 27 | ``` 28 | 29 | ## Testing 30 | Run the following code to test on the COCO test dataset. 31 | ``` 32 | sh test.sh 33 | ``` 34 | 35 | ## Citation 36 | ``` 37 | @inproceedings{shao2021localtrans, 38 | title={LocalTrans: A Multiscale Local Transformer Network for Cross-Resolution Homography Estimation}, 39 | author={Shao, Ruizhi and Wu, Gaochang and Zhou, Yuemei and Fu, Ying and Fang, Lu and Liu, Yebin}, 40 | booktitle={IEEE Conference on Computer Vision (ICCV 2021)}, 41 | year={2021}, 42 | } 43 | ``` 44 | -------------------------------------------------------------------------------- /assets/teaser.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DSaurus/LocalTrans/4884f9001d006644c8b74fde41324a4795cb683b/assets/teaser.jpg -------------------------------------------------------------------------------- /config/coco.yaml: -------------------------------------------------------------------------------- 1 | name: localtrans 2 | dataroot: /media/data1/shaoruizhi/AttentionWarping/train2014 3 | batch_size: 32 4 | epoch: 10000 5 | lr: 1e-4 6 | gpu_id: 0 7 | level: 3 8 | downsample: 1 9 | random_noise: True 10 | random_color: True 11 | random_bias: 0.5 12 | resume: True -------------------------------------------------------------------------------- /config/coco4x.yaml: -------------------------------------------------------------------------------- 1 | name: localtrans_4x 2 | dataroot: /media/data1/shaoruizhi/AttentionWarping/train2014 3 | batch_size: 32 4 | epoch: 10000 5 | lr: 1e-4 6 | gpu_id: 0 7 | level: 3 8 | downsample: 4 9 | random_noise: True 10 | random_color: True 11 | random_bias: 0.5 12 | resume: True -------------------------------------------------------------------------------- /config/coco8x.yaml: -------------------------------------------------------------------------------- 1 | name: localtrans_8x 2 | dataroot: /media/data1/shaoruizhi/AttentionWarping/train2014 3 | batch_size: 32 4 | epoch: 10000 5 | lr: 1e-4 6 | gpu_id: 0 7 | level: 3 8 | downsample: 8 9 | random_noise: True 10 | random_color: True 11 | random_bias: 0.5 12 | resume: True -------------------------------------------------------------------------------- /config/config.py: -------------------------------------------------------------------------------- 1 | def parse_config(argv=None): 2 | import configargparse 3 | arg_formatter = configargparse.ArgumentDefaultsHelpFormatter 4 | cfg_parser = configargparse.DefaultConfigFileParser 5 | description = 'project' 6 | parser = configargparse.ArgParser(formatter_class=arg_formatter, 7 | config_file_parser_class=cfg_parser, 8 | description=description, 9 | prog='localtrans') 10 | cfg = {} 11 | 12 | cfg["div_scale_list"] = [16, 8, 4] 13 | cfg["kernel_list"] = [9, 7, 5] 14 | cfg["bias_list"] = [0.5, 0.2, 0.075, 0.02] 15 | cfg["image_size"] = (128, 128) 16 | 17 | # general settings 18 | parser.add_argument('--config', is_config_file=True, help='config file path') 19 | parser.add_argument('--name', type=str, default='localtrans', help='name of a model/experiment.') 20 | parser.add_argument('--dataroot', type=str, default='train2014', help='name of a model/experiment.') 21 | parser.add_argument('--batch_size', type=int, default=32) 22 | parser.add_argument('--epoch', type=int, default=10000) 23 | parser.add_argument('--lr', type=float, default=1e-4) 24 | parser.add_argument('--gpu_id', type=int, default=0) 25 | parser.add_argument('--level', type=int, default=3) 26 | parser.add_argument('--downsample', type=int, default=1) 27 | parser.add_argument('--random_noise', type=bool, default=True) 28 | parser.add_argument('--random_color', type=bool, default=True) 29 | parser.add_argument('--random_bias', type=float, default=0.5) 30 | parser.add_argument('--resume', type=bool, default=True) 31 | parser.add_argument('--resume_dir', type=str) 32 | 33 | args, _ = parser.parse_known_args() 34 | 35 | return args -------------------------------------------------------------------------------- /lib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DSaurus/LocalTrans/4884f9001d006644c8b74fde41324a4795cb683b/lib/__init__.py -------------------------------------------------------------------------------- /lib/app/inference.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import lib.image.warping as warping 3 | import matplotlib.pyplot as plt 4 | import torch.nn.functional as F 5 | import cv2 6 | 7 | def torch2numpy(img): 8 | img = img.detach().cpu() 9 | img = img.squeeze(0).permute(1, 2, 0).numpy() 10 | return img 11 | 12 | def estimate_flow_homography(flow, W, H): 13 | rows = flow.shape[1] 14 | cols = flow.shape[2] 15 | grid = warping.gen_grid(cols, rows, 0.5, W-0.5, 0.5, H-0.5, 1) 16 | flow_grid = grid + flow 17 | homo, _ = cv2.findHomography(grid.reshape((-1, 2)).numpy(), flow_grid.reshape((-1, 2)).numpy(), 0) 18 | return homo 19 | 20 | def estimate_flow(net, img1, img2, start_i=0): 21 | H, W, C = img1.shape 22 | sample_data = warping.gen_grid(2 * (2 ** start_i), 2 * (2 ** start_i), 0.5, H - 0.5, 0.5, W - 0.5, 1) 23 | sample_data = warping.grid_to_sample(sample_data, W, H).cuda() 24 | net_img1 = img1.unsqueeze(0).permute(0, 3, 1, 2).cuda() 25 | net_img2 = img2.unsqueeze(0).permute(0, 3, 1, 2).cuda() 26 | flow = 0 27 | for i in range(start_i, 4): 28 | new_flow, sample_data_new, _ = net.forward(net_img1, net_img2, sample_data, i) 29 | flow = flow + new_flow 30 | if i == 3: 31 | break 32 | flow = warping.sample_upsample(flow) 33 | sample_data = sample_data_new 34 | 35 | return flow.detach().cpu().numpy() 36 | 37 | def estimate_warp(net, img1, img2, start_i=0): 38 | H, W, C = img1.shape 39 | sample_data = warping.gen_grid(2 * (2**start_i), 2 * (2**start_i), 0.5, H - 0.5, 0.5, W - 0.5, 1) 40 | sample_data = warping.grid_to_sample(sample_data, W, H).cuda() 41 | net_img1 = (torch.FloatTensor(img1) - 128) / 255 42 | net_img2 = (torch.FloatTensor(img2) - 128) / 255 43 | net_img1 = net_img1.unsqueeze(0).permute(0, 3, 1, 2).cuda() 44 | net_img2 = net_img2.unsqueeze(0).permute(0, 3, 1, 2).cuda() 45 | flow = 0 46 | for i in range(start_i, 4): 47 | new_flow, sample_data_new, _ = net.forward(net_img1, net_img2, sample_data, i) 48 | flow = flow + new_flow 49 | flow = warping.sample_upsample(flow) 50 | sample_data = sample_data_new 51 | grid = warping.gen_grid(W, H, 0.5, W-0.5, 0.5, H-0.5, 1).cuda() 52 | flow = warping.sample_upsample(flow, size=(H, W)) 53 | 54 | sample_data = warping.sample_upsample(sample_data, size=(H, W)) 55 | 56 | sample_flow = grid + flow 57 | sample_flow = warping.grid_to_sample(sample_flow, W, H) 58 | sample_img2 = F.grid_sample(net_img2, sample_data) 59 | 60 | # show_img1 = torch2numpy(net_img1 / 2 + net_img2 / 2) 61 | # show_img2 = torch2numpy(net_img1 / 2 + sample_img2 / 2) 62 | # plt.subplot(223) 63 | # plt.imshow(torch2numpy(net_img1 + 0.5)[:, :, ::-1]) 64 | # plt.subplot(224) 65 | # plt.imshow(torch2numpy(net_img2 + 0.5)[:, :, ::-1]) 66 | # plt.subplot(221) 67 | # plt.imshow( (show_img1+0.5)[:, :, ::-1]) 68 | # plt.subplot(222) 69 | # plt.imshow((show_img2 + 0.5)[:, :, ::-1]) 70 | # plt.show() 71 | return flow.detach().cpu().numpy() -------------------------------------------------------------------------------- /lib/image/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DSaurus/LocalTrans/4884f9001d006644c8b74fde41324a4795cb683b/lib/image/__init__.py -------------------------------------------------------------------------------- /lib/image/flow.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def make_color_wheel(): 5 | """ 6 | Generate color wheel according Middlebury color code 7 | :return: Color wheel 8 | """ 9 | RY = 15 10 | YG = 6 11 | GC = 4 12 | CB = 11 13 | BM = 13 14 | MR = 6 15 | 16 | ncols = RY + YG + GC + CB + BM + MR 17 | 18 | colorwheel = np.zeros([ncols, 3]) 19 | 20 | col = 0 21 | 22 | # RY 23 | colorwheel[0:RY, 0] = 255 24 | colorwheel[0:RY, 1] = np.transpose(np.floor(255*np.arange(0, RY) / RY)) 25 | col += RY 26 | 27 | # YG 28 | colorwheel[col:col+YG, 0] = 255 - np.transpose(np.floor(255*np.arange(0, YG) / YG)) 29 | colorwheel[col:col+YG, 1] = 255 30 | col += YG 31 | 32 | # GC 33 | colorwheel[col:col+GC, 1] = 255 34 | colorwheel[col:col+GC, 2] = np.transpose(np.floor(255*np.arange(0, GC) / GC)) 35 | col += GC 36 | 37 | # CB 38 | colorwheel[col:col+CB, 1] = 255 - np.transpose(np.floor(255*np.arange(0, CB) / CB)) 39 | colorwheel[col:col+CB, 2] = 255 40 | col += CB 41 | 42 | # BM 43 | colorwheel[col:col+BM, 2] = 255 44 | colorwheel[col:col+BM, 0] = np.transpose(np.floor(255*np.arange(0, BM) / BM)) 45 | col += + BM 46 | 47 | # MR 48 | colorwheel[col:col+MR, 2] = 255 - np.transpose(np.floor(255 * np.arange(0, MR) / MR)) 49 | colorwheel[col:col+MR, 0] = 255 50 | 51 | return colorwheel 52 | 53 | def compute_color(u, v): 54 | """ 55 | compute optical flow color map 56 | :param u: optical flow horizontal map 57 | :param v: optical flow vertical map 58 | :return: optical flow in color code 59 | """ 60 | [h, w] = u.shape 61 | img = np.zeros([h, w, 3]) 62 | nanIdx = np.isnan(u) | np.isnan(v) 63 | u[nanIdx] = 0 64 | v[nanIdx] = 0 65 | 66 | colorwheel = make_color_wheel() 67 | ncols = np.size(colorwheel, 0) 68 | 69 | rad = np.sqrt(u**2+v**2) 70 | 71 | a = np.arctan2(-v, -u) / np.pi 72 | 73 | fk = (a+1) / 2 * (ncols - 1) + 1 74 | 75 | k0 = np.floor(fk).astype(int) 76 | 77 | k1 = k0 + 1 78 | k1[k1 == ncols+1] = 1 79 | f = fk - k0 80 | 81 | for i in range(0, np.size(colorwheel,1)): 82 | tmp = colorwheel[:, i] 83 | col0 = tmp[k0-1] / 255 84 | col1 = tmp[k1-1] / 255 85 | col = (1-f) * col0 + f * col1 86 | 87 | idx = rad <= 1 88 | col[idx] = 1-rad[idx]*(1-col[idx]) 89 | notidx = np.logical_not(idx) 90 | 91 | col[notidx] *= 0.75 92 | img[:, :, i] = np.uint8(np.floor(255 * col*(1-nanIdx))) 93 | 94 | return img 95 | 96 | def flow_to_image(flow): 97 | """ 98 | Convert flow into middlebury color code image 99 | :param flow: optical flow map 100 | :return: optical flow image in middlebury color 101 | """ 102 | u = flow[:, :, 0] 103 | v = flow[:, :, 1] 104 | 105 | maxu = -999. 106 | maxv = -999. 107 | minu = 999. 108 | minv = 999. 109 | UNKNOWN_FLOW_THRESH = 1e7 110 | SMALLFLOW = 0.0 111 | LARGEFLOW = 1e8 112 | 113 | idxUnknow = (abs(u) > UNKNOWN_FLOW_THRESH) | (abs(v) > UNKNOWN_FLOW_THRESH) 114 | u[idxUnknow] = 0 115 | v[idxUnknow] = 0 116 | 117 | maxu = max(maxu, np.max(u)) 118 | minu = min(minu, np.min(u)) 119 | 120 | maxv = max(maxv, np.max(v)) 121 | minv = min(minv, np.min(v)) 122 | 123 | rad = np.sqrt(u ** 2 + v ** 2) 124 | maxrad = max(-1, np.max(rad)) 125 | 126 | u = u/(maxrad + np.finfo(float).eps) 127 | v = v/(maxrad + np.finfo(float).eps) 128 | 129 | img = compute_color(u, v) 130 | 131 | idx = np.repeat(idxUnknow[:, :, np.newaxis], 3, axis=2) 132 | img[idx] = 0 133 | 134 | return np.uint8(img) -------------------------------------------------------------------------------- /lib/model/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DSaurus/LocalTrans/4884f9001d006644c8b74fde41324a4795cb683b/lib/model/__init__.py -------------------------------------------------------------------------------- /lib/model/localtrans.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import matplotlib.pyplot as plt 5 | 6 | from lib.model.network_utils import * 7 | from ATT.attention_layer import Correlation, AttentionLayer 8 | from lib.model.network_utils import * 9 | from lib.image.warping import * 10 | 11 | 12 | class conv3x3(nn.Module): 13 | def __init__(self, in_c, out_c): 14 | super(conv3x3, self).__init__() 15 | self.conv = nn.Sequential(nn.Conv2d(in_c, out_c, 3, 1, 1), nn.BatchNorm2d(out_c), nn.ReLU()) 16 | 17 | def forward(self, x): 18 | return self.conv(x) 19 | 20 | class LocalTrans(nn.Module): 21 | def __init__(self): 22 | super(LocalTrans, self).__init__() 23 | self.conv1 = nn.Sequential(conv3x3(3, 32), conv3x3(32, 32), nn.MaxPool2d(2, 2)) 24 | self.conv2 = nn.Sequential(conv3x3(32, 64), conv3x3(64, 64), nn.MaxPool2d(2, 2)) 25 | self.conv3 = nn.Sequential(conv3x3(64, 64), conv3x3(64, 64), nn.MaxPool2d(2, 2)) 26 | self.conv4 = nn.Sequential(conv3x3(64, 128), conv3x3(128, 128), nn.MaxPool2d(2, 2)) 27 | 28 | self.transformer1 = AttentionLayer(128, 4, 32, 32, 5, 2) 29 | self.transformer2 = AttentionLayer(64, 2, 32, 32, 7, 3) 30 | self.transformer3 = AttentionLayer(64, 2, 32, 32, 9, 4) 31 | self.transformer4 = AttentionLayer(64, 2, 32, 32, 9, 4) 32 | self.transformer5 = AttentionLayer(64, 2, 32, 32, 9, 4) 33 | self.transformer = [self.transformer1, self.transformer2, self.transformer3, self.transformer4, self.transformer5] 34 | 35 | self.homo1 = nn.Sequential(conv3x3(25, 128), conv3x3(128, 128), nn.MaxPool2d(2, 2), 36 | conv3x3(128, 256), conv3x3(256, 256), nn.MaxPool2d(2, 2), 37 | conv3x3(256, 256), conv3x3(256, 256), nn.AvgPool2d(2, 2), nn.Conv2d(256, 8, 1)) 38 | self.homo2 = nn.Sequential(conv3x3(49, 128), conv3x3(128, 128), nn.MaxPool2d(2, 2), 39 | conv3x3(128, 128), conv3x3(128, 128), nn.MaxPool2d(2, 2), 40 | conv3x3(128, 256), conv3x3(256, 256), nn.MaxPool2d(2, 2), 41 | conv3x3(256, 256), conv3x3(256, 256), nn.AvgPool2d(2, 2), nn.Conv2d(256, 8, 1)) 42 | self.homo3 = nn.Sequential(conv3x3(81, 128), conv3x3(128, 128), nn.MaxPool2d(2, 2), 43 | conv3x3(128, 128), conv3x3(128, 128), nn.MaxPool2d(2, 2), 44 | conv3x3(128, 256), conv3x3(256, 256), nn.MaxPool2d(2, 2), 45 | conv3x3(256, 256), conv3x3(256, 256), nn.MaxPool2d(2, 2), 46 | conv3x3(256, 256), conv3x3(256, 256), nn.AvgPool2d(2, 2), nn.Conv2d(256, 8, 1)) 47 | self.homo4 = nn.Sequential(conv3x3(81, 128), conv3x3(128, 128), nn.MaxPool2d(2, 2), 48 | conv3x3(128, 128), conv3x3(128, 128), nn.MaxPool2d(2, 2), 49 | conv3x3(128, 256), conv3x3(256, 256), nn.MaxPool2d(2, 2), 50 | conv3x3(256, 256), conv3x3(256, 256), nn.MaxPool2d(2, 2), 51 | conv3x3(256, 256), conv3x3(256, 256), nn.AvgPool2d(2, 2), nn.Conv2d(256, 8, 1)) 52 | self.homo5 = nn.Sequential(conv3x3(81, 128), conv3x3(128, 128), nn.MaxPool2d(2, 2), 53 | conv3x3(128, 128), conv3x3(128, 128), nn.MaxPool2d(2, 2), 54 | conv3x3(128, 256), conv3x3(256, 256), nn.MaxPool2d(2, 2), 55 | conv3x3(256, 256), conv3x3(256, 256), nn.MaxPool2d(2, 2), 56 | conv3x3(256, 256), conv3x3(256, 256), nn.AvgPool2d(2, 2), nn.Conv2d(256, 8, 1)) 57 | 58 | self.homo_estim = [self.homo1, self.homo2, self.homo3, self.homo4, self.homo5] 59 | 60 | self.kernel_list = [5, 7, 9, 9, 9] 61 | self.pad_list = [2, 3, 4, 4, 4] 62 | self.scale_list = [16, 8, 4, 4, 4] 63 | self.bias_list = [2, 1, 0.5, 0.25, 0.125] 64 | 65 | def forward(self, x, y, L, show=False): 66 | device = x.device 67 | B, C, H, W = x.shape 68 | 69 | x, y = self.conv2(self.conv1(x)), self.conv2(self.conv1(y)) 70 | if L <= 1: 71 | x, y = self.conv3(x), self.conv3(y) 72 | if L <= 0: 73 | x, y = self.conv4(x), self.conv4(y) 74 | 75 | transformer = self.transformer[L] 76 | x, y = transformer(x, y) 77 | 78 | scale = self.scale_list[L] 79 | corr = Correlation.apply(x.contiguous(), y.contiguous(), self.kernel_list[L], self.pad_list[L]) 80 | corr = corr.permute(0, 3, 1, 2) / x.shape[1] 81 | homo_flow = self.homo_estim[L](corr) * scale * self.bias_list[L] 82 | if show: 83 | return homo_flow.reshape(B, 2, 2, 2), corr, x, y 84 | else: 85 | return homo_flow.reshape(B, 2, 2, 2) -------------------------------------------------------------------------------- /lib/model/network_utils.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | 3 | def conv(in_chs, out_chs, kernel_size=3, stride=1, padding=1): 4 | return nn.Sequential( 5 | nn.Conv2d(in_chs, out_chs, kernel_size, stride, padding), 6 | nn.LeakyReLU(0.1) 7 | ) 8 | 9 | class IdentityBlock(nn.Module): 10 | def __init__(self, channels, filters): 11 | super(IdentityBlock, self).__init__() 12 | self.channels = channels 13 | self.filters = filters 14 | self.net = nn.Sequential( 15 | nn.Conv2d(channels, filters[0], 1), 16 | nn.BatchNorm2d(filters[0]), 17 | nn.ReLU(True), 18 | nn.Conv2d(filters[0], filters[1], 3, padding=1), 19 | nn.BatchNorm2d(filters[1]), 20 | nn.ReLU(True), 21 | nn.Conv2d(filters[1], filters[2], 1), 22 | nn.BatchNorm2d(filters[2]) 23 | ) 24 | self.channel_net = nn.Conv2d(channels, filters[2], 1, 1, 0) 25 | 26 | self.relu = nn.ReLU(True) 27 | 28 | def forward(self, x): 29 | y = self.net(x) 30 | if self.channels != self.filters[2]: 31 | y = self.channel_net(x) + y 32 | else: 33 | y = x + y 34 | y = self.relu(y) 35 | 36 | return y 37 | 38 | 39 | class ConvBlock(nn.Module): 40 | def __init__(self, channels, filters, stride=2): 41 | super(ConvBlock, self).__init__() 42 | self.channels = channels 43 | self.filters = filters 44 | self.net = nn.Sequential( 45 | nn.Conv2d(channels, filters[0], 1, stride=stride), 46 | nn.BatchNorm2d(filters[0]), 47 | nn.ReLU(True), 48 | nn.Conv2d(filters[0], filters[1], 3, padding=1), 49 | nn.BatchNorm2d(filters[1]), 50 | nn.ReLU(True), 51 | nn.Conv2d(filters[1], filters[2], 1), 52 | nn.BatchNorm2d(filters[2]) 53 | ) 54 | self.downsample = nn.Sequential( 55 | nn.Conv2d(channels, filters[2], 1, stride=stride), 56 | nn.BatchNorm2d(filters[2]) 57 | ) 58 | self.relu = nn.ReLU(True) 59 | 60 | def forward(self, x): 61 | y = self.net(x) 62 | x = self.downsample(x) 63 | y = x + y 64 | y = self.relu(y) 65 | 66 | return y 67 | 68 | 69 | class DeConvBlock(nn.Module): 70 | def __init__(self, channels, filters, stride=2): 71 | super(DeConvBlock, self).__init__() 72 | self.net = nn.Sequential( 73 | nn.UpsamplingBilinear2d(scale_factor=2), 74 | nn.Conv2d(channels, filters[0], 1), 75 | nn.Conv2d(filters[0], filters[1], 3, padding=1), 76 | nn.BatchNorm2d(filters[1]), 77 | nn.ReLU(True), 78 | nn.Conv2d(filters[1], filters[2], 1), 79 | nn.BatchNorm2d(filters[2]) 80 | ) 81 | self.upsample = nn.Sequential( 82 | nn.UpsamplingBilinear2d(scale_factor=2), 83 | nn.Conv2d(channels, filters[2], 1), 84 | nn.BatchNorm2d(filters[2]) 85 | ) 86 | self.batch_relu = nn.Sequential( 87 | nn.BatchNorm2d(filters[2]), 88 | nn.ReLU(True) 89 | ) 90 | 91 | def forward(self, x): 92 | y = self.net(x) 93 | x = self.upsample(x) 94 | x = x + y 95 | x = self.batch_relu(x) 96 | 97 | return x -------------------------------------------------------------------------------- /test.sh: -------------------------------------------------------------------------------- 1 | python test.py --config config/coco4x.yaml -------------------------------------------------------------------------------- /train.sh: -------------------------------------------------------------------------------- 1 | # python train.py --config config/coco4x.yaml --resume 1 2 | python train.py --config config/coco8x.yaml --resume_dir /media/data1/shaoruizhi/localtrans/results/checkpoints/localtrans_8x --------------------------------------------------------------------------------