├── .clang-format ├── .github └── workflows │ ├── pypipublish.yml │ └── test.yml ├── .gitignore ├── .pre-commit-config.yaml ├── CMakeLists.txt ├── LICENSE ├── README.md ├── cmake └── Finds2.cmake ├── docs ├── Makefile ├── api.rst ├── conf.py ├── index.rst └── make.bat ├── environment-dev.yml ├── include └── pys2index │ └── s2pointindex.hpp ├── pyproject.toml ├── src └── main.cpp └── tests └── test_s2pointindex.py /.clang-format: -------------------------------------------------------------------------------- 1 | BasedOnStyle: Mozilla 2 | AccessModifierOffset: '-4' 3 | AlignAfterOpenBracket: Align 4 | AlignEscapedNewlinesLeft: 'false' 5 | AllowAllParametersOfDeclarationOnNextLine: 'true' 6 | AllowShortBlocksOnASingleLine: 'false' 7 | AllowShortCaseLabelsOnASingleLine: 'false' 8 | AllowShortFunctionsOnASingleLine: 'false' 9 | AllowShortIfStatementsOnASingleLine: 'false' 10 | AllowShortLoopsOnASingleLine: 'false' 11 | AlwaysBreakTemplateDeclarations: 'true' 12 | SpaceAfterTemplateKeyword: 'true' 13 | BreakBeforeBinaryOperators: All 14 | BreakBeforeBraces: Allman 15 | BreakBeforeTernaryOperators: 'true' 16 | BreakConstructorInitializersBeforeComma: 'true' 17 | BreakStringLiterals: 'false' 18 | ColumnLimit: '100' 19 | ConstructorInitializerAllOnOneLineOrOnePerLine: 'false' 20 | ConstructorInitializerIndentWidth: '4' 21 | ContinuationIndentWidth: '4' 22 | Cpp11BracedListStyle: 'false' 23 | DerivePointerAlignment: 'false' 24 | DisableFormat: 'false' 25 | ExperimentalAutoDetectBinPacking: 'true' 26 | IndentCaseLabels: 'true' 27 | IndentWidth: '4' 28 | IndentWrappedFunctionNames: 'false' 29 | JavaScriptQuotes: Single 30 | KeepEmptyLinesAtTheStartOfBlocks: 'false' 31 | Language: Cpp 32 | MaxEmptyLinesToKeep: '2' 33 | NamespaceIndentation: All 34 | ObjCBlockIndentWidth: '4' 35 | ObjCSpaceAfterProperty: 'false' 36 | ObjCSpaceBeforeProtocolList: 'false' 37 | PointerAlignment: Left 38 | ReflowComments: 'true' 39 | SortIncludes: 'false' 40 | SpaceAfterCStyleCast: 'true' 41 | SpaceBeforeAssignmentOperators: 'true' 42 | SpaceBeforeParens: ControlStatements 43 | SpaceInEmptyParentheses: 'false' 44 | SpacesBeforeTrailingComments: '2' 45 | SpacesInAngles: 'false' 46 | SpacesInCStyleCastParentheses: 'false' 47 | SpacesInContainerLiterals: 'false' 48 | SpacesInParentheses: 'false' 49 | SpacesInSquareBrackets: 'false' 50 | Standard: c++17 51 | TabWidth: '4' 52 | UseTab: Never 53 | -------------------------------------------------------------------------------- /.github/workflows/pypipublish.yml: -------------------------------------------------------------------------------- 1 | on: 2 | # trigger action from GitHub GUI (testing, no publish) 3 | workflow_dispatch: 4 | release: 5 | types: 6 | - published 7 | 8 | name: Publish on PyPI 9 | 10 | jobs: 11 | make_sdist: 12 | name: Make Python SDist 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Checkout repo 16 | uses: actions/checkout@v4 17 | 18 | - name: Build SDist 19 | run: pipx run build --sdist 20 | 21 | - name: Upload SDist 22 | uses: actions/upload-artifact@v3 23 | with: 24 | path: dist/*.tar.gz 25 | 26 | upload: 27 | needs: [make_sdist] 28 | environment: pypi 29 | permissions: 30 | id-token: write 31 | runs-on: ubuntu-latest 32 | if: github.event_name == 'release' && github.event.action == 'published' 33 | steps: 34 | - name: Get dist files 35 | uses: actions/download-artifact@v3 36 | with: 37 | name: artifact 38 | path: dist 39 | 40 | - name: Publish on PyPI 41 | uses: pypa/gh-action-pypi-publish@release/v1 42 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | 3 | on: 4 | push: 5 | branches: 6 | - 'main' 7 | pull_request: 8 | branches: 9 | - 'main' 10 | 11 | jobs: 12 | test: 13 | name: pytest (${{ matrix.os }}, ${{ matrix.python-version }}) 14 | runs-on: ${{ matrix.os }} 15 | strategy: 16 | fail-fast: false 17 | matrix: 18 | os: ["ubuntu-latest", "macos-latest", "windows-latest"] 19 | python-version: ["3.9", "3.10", "3.11"] 20 | steps: 21 | - name: Checkout 22 | uses: actions/checkout@v2 23 | 24 | - name: Setup micromamba 25 | uses: mamba-org/setup-micromamba@v1 26 | with: 27 | environment-file: environment-dev.yml 28 | cache-environment: true 29 | cache-downloads: false 30 | create-args: >- 31 | python=${{ matrix.python-version }} 32 | 33 | - name: Build and install pys2index 34 | shell: bash -l {0} 35 | run: | 36 | python -m pip install . --no-build-isolation --no-deps -vv --config-settings=cmake.build-type=Debug 37 | python -OO -c "import pys2index" 38 | - name: Run tests 39 | shell: bash -l {0} 40 | run: pytest . --verbose --color=yes 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.egg-info/ 2 | .ipynb_checkpoints/ 3 | dist/ 4 | build/ 5 | *.py[cod] 6 | 7 | # OS X 8 | .DS_Store 9 | 10 | # C++ 11 | .ccls 12 | .ccls-cache/ 13 | compile_commands.json 14 | 15 | # doc 16 | docs/_build/ 17 | docs/_generate/ 18 | 19 | # misc 20 | .dir-locals.el 21 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/pre-commit/pre-commit-hooks 3 | rev: v4.5.0 4 | hooks: 5 | - id: trailing-whitespace 6 | - id: end-of-file-fixer 7 | - id: check-yaml 8 | - id: debug-statements 9 | - id: mixed-line-ending 10 | - repo: https://github.com/pre-commit/mirrors-clang-format 11 | rev: v17.0.4 12 | hooks: 13 | - id: clang-format 14 | args: [--style=file] 15 | 16 | ci: 17 | autoupdate_schedule: monthly 18 | autofix_commit_msg: "style(pre-commit.ci): auto fixes [...]" 19 | autoupdate_commit_msg: "ci(pre-commit.ci): autoupdate" 20 | autofix_prs: false 21 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.15) 2 | 3 | if(NOT SKBUILD_PROJECT_NAME) 4 | set(SKBUILD_PROJECT_NAME "pys2index") 5 | endif() 6 | 7 | if(NOT SKBUILD_PROJECT_VERSION) 8 | set(SKBUILD_PROJECT_VERSION 9999) 9 | endif() 10 | 11 | project( 12 | ${SKBUILD_PROJECT_NAME} 13 | LANGUAGES CXX) 14 | 15 | # https://gitlab.kitware.com/cmake/cmake/-/issues/16716 16 | set(PROJECT_VERSION ${SKBUILD_PROJECT_VERSION}) 17 | 18 | set(CMAKE_MODULE_PATH 19 | ${PROJECT_SOURCE_DIR}/cmake 20 | ${CMAKE_MODULE_PATH}) 21 | 22 | set(pys2index_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/include) 23 | 24 | if (CMAKE_CXX_COMPILER_ID MATCHES "Clang" OR CMAKE_CXX_COMPILER_ID MATCHES "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES "Intel") 25 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wunused-parameter -Wextra -Wreorder -Wconversion -fvisibility=hidden") 26 | endif() 27 | 28 | if(MSVC) 29 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /EHsc /MP /bigobj /J") 30 | set(CMAKE_EXE_LINKER_FLAGS /MANIFEST:NO) 31 | add_definitions(-D_USE_MATH_DEFINES) 32 | add_definitions(-DNOMINMAX) 33 | endif() 34 | 35 | # Dependencies 36 | # ============ 37 | 38 | find_package(xtensor REQUIRED) 39 | message(STATUS "Found xtensor: ${xtensor_INCLUDE_DIRS}") 40 | 41 | find_package(xtensor-python REQUIRED) 42 | message(STATUS "Found xtensor-python: ${xtensor-python_INCLUDE_DIRS}") 43 | 44 | find_package (Python COMPONENTS Interpreter Development.Module NumPy REQUIRED) 45 | message(STATUS "Found python v${Python_VERSION}: ${Python_EXECUTABLE}") 46 | message(STATUS "Found numpy v${Python_NumPy_VERSION}: ${Python_NumPy_INCLUDE_DIRS}") 47 | 48 | find_package(pybind11 REQUIRED) 49 | message(STATUS "Found pybind11 v${pybind11_VERSION}: ${pybind11_INCLUDE_DIRS}") 50 | 51 | find_package(s2 REQUIRED) 52 | 53 | # Build 54 | # ===== 55 | 56 | add_library(pys2index MODULE src/main.cpp) 57 | 58 | target_include_directories(pys2index PUBLIC ${pys2index_INCLUDE_DIR}) 59 | 60 | target_compile_features(pys2index PUBLIC cxx_std_17) 61 | target_compile_definitions(pys2index PRIVATE VERSION_INFO=${PROJECT_VERSION}) 62 | 63 | target_link_libraries(pys2index PRIVATE 64 | xtensor 65 | xtensor-python 66 | pybind11::module 67 | Python::NumPy 68 | s2 69 | ) 70 | 71 | pybind11_extension(pys2index) 72 | if(NOT MSVC AND NOT ${CMAKE_BUILD_TYPE} MATCHES Debug|RelWithDebInfo) 73 | # Strip unnecessary sections of the binary on Linux/macOS 74 | pybind11_strip(pys2index) 75 | endif() 76 | 77 | # Installation 78 | # ============ 79 | 80 | install(TARGETS pys2index LIBRARY DESTINATION .) 81 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2020, Benoit Bovy 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | 1. Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | 2. Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | 3. Neither the name of the copyright holder nor the names of its 17 | contributors may be used to endorse or promote products derived from 18 | this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 23 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 24 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 26 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 27 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 28 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pys2index 2 | 3 | [![test status](https://github.com/benbovy/pys2index/workflows/test/badge.svg)](https://github.com/benbovy/pys2index/actions) 4 | 5 | Python / NumPy compatible geographical index based on 6 | [s2geometry](https://s2geometry.io). 7 | 8 | This project doesn't provide Python wrappers for the whole `s2geometry` library. 9 | Instead, it aims to provide some index wrappers with an API similar to 10 | [scipy.spatial.cKDTree](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.html). 11 | 12 | ## Build Dependencies 13 | 14 | - C++17 compiler 15 | - CMake 16 | - [s2geometry](https://github.com/google/s2geometry) 17 | - [scikit-build-core](https://github.com/scikit-build/scikit-build-core) 18 | - [xtensor-python](https://github.com/xtensor-stack/xtensor-python) 19 | - [pybind11](https://github.com/pybind/pybind11) 20 | - Python 21 | - NumPy 22 | 23 | ## Installation 24 | 25 | ### Using conda 26 | 27 | pys2index can be installed using [conda](https://docs.conda.io) (or 28 | [mamba](https://github.com/mamba-org/mamba)): 29 | 30 | ``` bash 31 | $ conda install pys2index -c conda-forge 32 | ``` 33 | 34 | ### From source 35 | 36 | First, clone this repository: 37 | 38 | ``` bash 39 | $ git clone https://github.com/benbovy/pys2index 40 | $ cd pys2index 41 | ``` 42 | 43 | You can install all the dependencies using conda (or mamba): 44 | 45 | ``` bash 46 | $ conda install python cxx-compiler numpy s2geometry pybind11 xtensor-python cmake scikit-build-core -c conda-forge 47 | ``` 48 | 49 | Build and install this library 50 | 51 | ``` bash 52 | $ python -m pip install . --no-build-isolation 53 | ``` 54 | 55 | ## Usage 56 | 57 | ```python 58 | In [1]: import numpy as np 59 | 60 | In [2]: from pys2index import S2PointIndex 61 | 62 | In [3]: latlon_points = np.array([[40.0, 15.0], 63 | ...: [-20.0, 53.0], 64 | ...: [81.0, 153.0]]) 65 | ...: 66 | 67 | In [4]: index = S2PointIndex(latlon_points) 68 | 69 | In [5]: query_points = np.array([[-10.0, 60.0], 70 | ...: [45.0, -20.0], 71 | ...: [75.0, 122.0]]) 72 | ...: 73 | 74 | In [6]: distances, positions = index.query(query_points) 75 | 76 | In [7]: distances 77 | Out[7]: array([12.06534671, 26.07312392, 8.60671311]) 78 | 79 | In [8]: positions 80 | Out[8]: array([1, 0, 2]) 81 | 82 | In [9]: index.get_cell_ids() 83 | Out[9]: array([1386017682036854979, 2415595305706115691, 6525033740530229539], 84 | dtype=uint64) 85 | 86 | ``` 87 | 88 | ## Running the tests 89 | 90 | Running the tests requires `pytest` (it is also available on conda-forge). 91 | 92 | ```bash 93 | $ pytest . 94 | ``` 95 | -------------------------------------------------------------------------------- /cmake/Finds2.cmake: -------------------------------------------------------------------------------- 1 | # The MIT License (MIT) 2 | # 3 | # Copyright (c) 2020 Benoit Bovy 4 | # 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | # 12 | # The above copyright notice and this permission notice shall be included in all 13 | # copies or substantial portions of the Software. 14 | # 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | # SOFTWARE. 22 | 23 | # 24 | # FindS2 25 | # ------ 26 | # 27 | # Find S2 (S2Geometry) include directories and libraries. 28 | # 29 | # This module will set the following variables: 30 | # 31 | # S2_FOUND - System has S2 32 | # S2_INCLUDE_DIRS - The S2 include directories 33 | # S2_LIBRARIES - The libraries needed to use S2 34 | # 35 | # This module will also create the "tbb" target that may be used when building 36 | # executables and libraries. 37 | 38 | include(FindPackageHandleStandardArgs) 39 | 40 | if(NOT S2_ROOT AND DEFINED ENV{S2_DIR}) 41 | set(S2_ROOT "$ENV{S2_DIR}") 42 | endif() 43 | 44 | find_path(s2_INCLUDE_DIR s2/s2cell.h 45 | HINTS ${S2_ROOT} 46 | PATH_SUFFIXES include 47 | ) 48 | 49 | find_library(s2_LIBRARY 50 | NAMES s2 51 | HINTS ${S2_ROOT} 52 | PATH_SUFFIXES lib libs Library 53 | ) 54 | 55 | find_package_handle_standard_args(s2 56 | REQUIRED_VARS s2_INCLUDE_DIR s2_LIBRARY 57 | ) 58 | 59 | if(NOT CMAKE_VERSION VERSION_LESS 3.0 AND S2_FOUND) 60 | set(s2_INCLUDE_DIRS ${s2_INCLUDE_DIR}) 61 | set(s2_LIBRARIES ${s2_LIBRARY}) 62 | 63 | add_library(s2 SHARED IMPORTED) 64 | set_target_properties(s2 PROPERTIES 65 | INTERFACE_INCLUDE_DIRECTORIES ${s2_INCLUDE_DIRS} 66 | IMPORTED_LOCATION ${s2_LIBRARIES} 67 | IMPORTED_IMPLIB ${s2_LIBRARIES} 68 | ) 69 | 70 | mark_as_advanced(s2_INCLUDE_DIRS s2_LIBRARIES) 71 | endif() 72 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help 23 | help: 24 | @echo "Please use \`make ' where is one of" 25 | @echo " html to make standalone HTML files" 26 | @echo " dirhtml to make HTML files named index.html in directories" 27 | @echo " singlehtml to make a single large HTML file" 28 | @echo " pickle to make pickle files" 29 | @echo " json to make JSON files" 30 | @echo " htmlhelp to make HTML files and a HTML help project" 31 | @echo " qthelp to make HTML files and a qthelp project" 32 | @echo " applehelp to make an Apple Help Book" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | @echo " coverage to run coverage check of the documentation (if enabled)" 49 | 50 | .PHONY: clean 51 | clean: 52 | rm -rf $(BUILDDIR)/* 53 | 54 | .PHONY: html 55 | html: 56 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 57 | @echo 58 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 59 | 60 | .PHONY: dirhtml 61 | dirhtml: 62 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 63 | @echo 64 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 65 | 66 | .PHONY: singlehtml 67 | singlehtml: 68 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 69 | @echo 70 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 71 | 72 | .PHONY: pickle 73 | pickle: 74 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 75 | @echo 76 | @echo "Build finished; now you can process the pickle files." 77 | 78 | .PHONY: json 79 | json: 80 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 81 | @echo 82 | @echo "Build finished; now you can process the JSON files." 83 | 84 | .PHONY: htmlhelp 85 | htmlhelp: 86 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 87 | @echo 88 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 89 | ".hhp project file in $(BUILDDIR)/htmlhelp." 90 | 91 | .PHONY: qthelp 92 | qthelp: 93 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 94 | @echo 95 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 96 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 97 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python_example.qhcp" 98 | @echo "To view the help file:" 99 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python_example.qhc" 100 | 101 | .PHONY: applehelp 102 | applehelp: 103 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 104 | @echo 105 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 106 | @echo "N.B. You won't be able to view it unless you put it in" \ 107 | "~/Library/Documentation/Help or install it in your application" \ 108 | "bundle." 109 | 110 | .PHONY: devhelp 111 | devhelp: 112 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 113 | @echo 114 | @echo "Build finished." 115 | @echo "To view the help file:" 116 | @echo "# mkdir -p $$HOME/.local/share/devhelp/python_example" 117 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python_example" 118 | @echo "# devhelp" 119 | 120 | .PHONY: epub 121 | epub: 122 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 123 | @echo 124 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 125 | 126 | .PHONY: latex 127 | latex: 128 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 129 | @echo 130 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 131 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 132 | "(use \`make latexpdf' here to do that automatically)." 133 | 134 | .PHONY: latexpdf 135 | latexpdf: 136 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 137 | @echo "Running LaTeX files through pdflatex..." 138 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 139 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 140 | 141 | .PHONY: latexpdfja 142 | latexpdfja: 143 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 144 | @echo "Running LaTeX files through platex and dvipdfmx..." 145 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 146 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 147 | 148 | .PHONY: text 149 | text: 150 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 151 | @echo 152 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 153 | 154 | .PHONY: man 155 | man: 156 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 157 | @echo 158 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 159 | 160 | .PHONY: texinfo 161 | texinfo: 162 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 163 | @echo 164 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 165 | @echo "Run \`make' in that directory to run these through makeinfo" \ 166 | "(use \`make info' here to do that automatically)." 167 | 168 | .PHONY: info 169 | info: 170 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 171 | @echo "Running Texinfo files through makeinfo..." 172 | make -C $(BUILDDIR)/texinfo info 173 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 174 | 175 | .PHONY: gettext 176 | gettext: 177 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 178 | @echo 179 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 180 | 181 | .PHONY: changes 182 | changes: 183 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 184 | @echo 185 | @echo "The overview file is in $(BUILDDIR)/changes." 186 | 187 | .PHONY: linkcheck 188 | linkcheck: 189 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 190 | @echo 191 | @echo "Link check complete; look for any errors in the above output " \ 192 | "or in $(BUILDDIR)/linkcheck/output.txt." 193 | 194 | .PHONY: doctest 195 | doctest: 196 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 197 | @echo "Testing of doctests in the sources finished, look at the " \ 198 | "results in $(BUILDDIR)/doctest/output.txt." 199 | 200 | .PHONY: coverage 201 | coverage: 202 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 203 | @echo "Testing of coverage in the sources finished, look at the " \ 204 | "results in $(BUILDDIR)/coverage/python.txt." 205 | 206 | .PHONY: xml 207 | xml: 208 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 209 | @echo 210 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 211 | 212 | .PHONY: pseudoxml 213 | pseudoxml: 214 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 215 | @echo 216 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 217 | -------------------------------------------------------------------------------- /docs/api.rst: -------------------------------------------------------------------------------- 1 | API Reference 2 | ============= 3 | 4 | .. automodule:: pys2index 5 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # pys2index documentation build configuration file, created by 4 | # sphinx-quickstart on Fri Feb 26 00:29:33 2016. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sys 16 | import os 17 | 18 | # If extensions (or modules to document with autodoc) are in another directory, 19 | # add these directories to sys.path here. If the directory is relative to the 20 | # documentation root, use os.path.abspath to make it absolute, like shown here. 21 | #sys.path.insert(0, os.path.abspath('.')) 22 | 23 | # -- General configuration ------------------------------------------------ 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | #needs_sphinx = '1.0' 27 | 28 | # Add any Sphinx extension module names here, as strings. They can be 29 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 30 | # ones. 31 | extensions = [ 32 | 'sphinx.ext.autodoc', 33 | 'sphinx.ext.intersphinx', 34 | 'sphinx.ext.autosummary', 35 | 'sphinx.ext.napoleon', 36 | ] 37 | 38 | autosummary_generate = True 39 | 40 | # Add any paths that contain templates here, relative to this directory. 41 | templates_path = ['_templates'] 42 | 43 | # The suffix(es) of source filenames. 44 | # You can specify multiple suffix as a list of string: 45 | # source_suffix = ['.rst', '.md'] 46 | source_suffix = '.rst' 47 | 48 | # The encoding of source files. 49 | #source_encoding = 'utf-8-sig' 50 | 51 | # The master toctree document. 52 | master_doc = 'index' 53 | 54 | # General information about the project. 55 | project = u'pys2index' 56 | copyright = u'2020, Benoît Bovy' 57 | author = u'Benoît Bovy' 58 | 59 | # The version info for the project you're documenting, acts as replacement for 60 | # |version| and |release|, also used in various other places throughout the 61 | # built documents. 62 | # 63 | # The short X.Y version. 64 | version = u'0.2.0' 65 | # The full version, including alpha/beta/rc tags. 66 | release = u'0.2.0dev' 67 | 68 | # The language for content autogenerated by Sphinx. Refer to documentation 69 | # for a list of supported languages. 70 | # 71 | # This is also used if you do content translation via gettext catalogs. 72 | # Usually you set "language" from the command line for these cases. 73 | language = None 74 | 75 | # There are two options for replacing |today|: either, you set today to some 76 | # non-false value, then it is used: 77 | #today = '' 78 | # Else, today_fmt is used as the format for a strftime call. 79 | #today_fmt = '%B %d, %Y' 80 | 81 | # List of patterns, relative to source directory, that match files and 82 | # directories to ignore when looking for source files. 83 | exclude_patterns = ['_build'] 84 | 85 | # The reST default role (used for this markup: `text`) to use for all 86 | # documents. 87 | #default_role = None 88 | 89 | # If true, '()' will be appended to :func: etc. cross-reference text. 90 | #add_function_parentheses = True 91 | 92 | # If true, the current module name will be prepended to all description 93 | # unit titles (such as .. function::). 94 | #add_module_names = True 95 | 96 | # If true, sectionauthor and moduleauthor directives will be shown in the 97 | # output. They are ignored by default. 98 | #show_authors = False 99 | 100 | # The name of the Pygments (syntax highlighting) style to use. 101 | pygments_style = 'sphinx' 102 | 103 | # A list of ignored prefixes for module index sorting. 104 | #modindex_common_prefix = [] 105 | 106 | # If true, keep warnings as "system message" paragraphs in the built documents. 107 | #keep_warnings = False 108 | 109 | # If true, `todo` and `todoList` produce output, else they produce nothing. 110 | todo_include_todos = False 111 | 112 | 113 | # -- Options for HTML output ---------------------------------------------- 114 | 115 | # The theme to use for HTML and HTML Help pages. See the documentation for 116 | # a list of builtin themes. 117 | html_theme = 'sphinx_rtd_theme' 118 | 119 | # Theme options are theme-specific and customize the look and feel of a theme 120 | # further. For a list of options available for each theme, see the 121 | # documentation. 122 | #html_theme_options = {} 123 | 124 | # Add any paths that contain custom themes here, relative to this directory. 125 | #html_theme_path = [] 126 | 127 | # The name for this set of Sphinx documents. If None, it defaults to 128 | # " v documentation". 129 | #html_title = None 130 | 131 | # A shorter title for the navigation bar. Default is the same as html_title. 132 | #html_short_title = None 133 | 134 | # The name of an image file (relative to this directory) to place at the top 135 | # of the sidebar. 136 | #html_logo = None 137 | 138 | # The name of an image file (within the static path) to use as favicon of the 139 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 140 | # pixels large. 141 | #html_favicon = None 142 | 143 | # Add any paths that contain custom static files (such as style sheets) here, 144 | # relative to this directory. They are copied after the builtin static files, 145 | # so a file named "default.css" will overwrite the builtin "default.css". 146 | #html_static_path = ['_static'] 147 | 148 | # Add any extra paths that contain custom files (such as robots.txt or 149 | # .htaccess) here, relative to this directory. These files are copied 150 | # directly to the root of the documentation. 151 | #html_extra_path = [] 152 | 153 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 154 | # using the given strftime format. 155 | #html_last_updated_fmt = '%b %d, %Y' 156 | 157 | # If true, SmartyPants will be used to convert quotes and dashes to 158 | # typographically correct entities. 159 | #html_use_smartypants = True 160 | 161 | # Custom sidebar templates, maps document names to template names. 162 | #html_sidebars = {} 163 | 164 | # Additional templates that should be rendered to pages, maps page names to 165 | # template names. 166 | #html_additional_pages = {} 167 | 168 | # If false, no module index is generated. 169 | #html_domain_indices = True 170 | 171 | # If false, no index is generated. 172 | #html_use_index = True 173 | 174 | # If true, the index is split into individual pages for each letter. 175 | #html_split_index = False 176 | 177 | # If true, links to the reST sources are added to the pages. 178 | #html_show_sourcelink = True 179 | 180 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 181 | #html_show_sphinx = True 182 | 183 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 184 | #html_show_copyright = True 185 | 186 | # If true, an OpenSearch description file will be output, and all pages will 187 | # contain a tag referring to it. The value of this option must be the 188 | # base URL from which the finished HTML is served. 189 | #html_use_opensearch = '' 190 | 191 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 192 | #html_file_suffix = None 193 | 194 | # Language to be used for generating the HTML full-text search index. 195 | # Sphinx supports the following languages: 196 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 197 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' 198 | #html_search_language = 'en' 199 | 200 | # A dictionary with options for the search language support, empty by default. 201 | # Now only 'ja' uses this config value 202 | #html_search_options = {'type': 'default'} 203 | 204 | # The name of a javascript file (relative to the configuration directory) that 205 | # implements a search results scorer. If empty, the default will be used. 206 | #html_search_scorer = 'scorer.js' 207 | 208 | # Output file base name for HTML help builder. 209 | htmlhelp_basename = 'pys2indexdoc' 210 | 211 | # -- Options for LaTeX output --------------------------------------------- 212 | 213 | latex_elements = { 214 | # The paper size ('letterpaper' or 'a4paper'). 215 | #'papersize': 'letterpaper', 216 | 217 | # The font size ('10pt', '11pt' or '12pt'). 218 | #'pointsize': '10pt', 219 | 220 | # Additional stuff for the LaTeX preamble. 221 | #'preamble': '', 222 | 223 | # Latex figure (float) alignment 224 | #'figure_align': 'htbp', 225 | } 226 | 227 | # Grouping the document tree into LaTeX files. List of tuples 228 | # (source start file, target name, title, 229 | # author, documentclass [howto, manual, or own class]). 230 | latex_documents = [ 231 | (master_doc, 'pys2index.tex', u'pys2index Documentation', 232 | u'Benoît Bovy', 'manual'), 233 | ] 234 | 235 | # The name of an image file (relative to this directory) to place at the top of 236 | # the title page. 237 | #latex_logo = None 238 | 239 | # For "manual" documents, if this is true, then toplevel headings are parts, 240 | # not chapters. 241 | #latex_use_parts = False 242 | 243 | # If true, show page references after internal links. 244 | #latex_show_pagerefs = False 245 | 246 | # If true, show URL addresses after external links. 247 | #latex_show_urls = False 248 | 249 | # Documents to append as an appendix to all manuals. 250 | #latex_appendices = [] 251 | 252 | # If false, no module index is generated. 253 | #latex_domain_indices = True 254 | 255 | 256 | # -- Options for manual page output --------------------------------------- 257 | 258 | # One entry per manual page. List of tuples 259 | # (source start file, name, description, authors, manual section). 260 | man_pages = [ 261 | (master_doc, 'pys2index', u'pys2index Documentation', 262 | [author], 1) 263 | ] 264 | 265 | # If true, show URL addresses after external links. 266 | #man_show_urls = False 267 | 268 | 269 | # -- Options for Texinfo output ------------------------------------------- 270 | 271 | # Grouping the document tree into Texinfo files. List of tuples 272 | # (source start file, target name, title, author, 273 | # dir menu entry, description, category) 274 | texinfo_documents = [ 275 | (master_doc, 'pys2index', u'pys2index Documentation', 276 | author, 'pys2index', 'Python geographic index wrappers baed on s2geometry', 277 | 'Miscellaneous'), 278 | ] 279 | 280 | # Documents to append as an appendix to all manuals. 281 | #texinfo_appendices = [] 282 | 283 | # If false, no module index is generated. 284 | #texinfo_domain_indices = True 285 | 286 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 287 | #texinfo_show_urls = 'footnote' 288 | 289 | # If true, do not generate a @detailmenu in the "Top" node's menu. 290 | #texinfo_no_detailmenu = False 291 | 292 | 293 | # Example configuration for intersphinx: refer to the Python standard library. 294 | intersphinx_mapping = {'https://docs.python.org/': None} 295 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | pys2index Documentation 2 | ======================= 3 | 4 | Python / NumPy compatible geographical index based on s2geometry_. 5 | 6 | This project doesn't provide Python wrappers for the whole s2geometry library. 7 | Instead, it aims to provide some index wrappers with an API similar to 8 | ``scipy.spatial.cKDTree`` or ``sklearn.neighbors`` indexes. 9 | 10 | .. _s2geometry: https://s2geometry.io 11 | 12 | Contents: 13 | 14 | .. toctree:: 15 | :maxdepth: 1 16 | 17 | api 18 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | echo. coverage to run coverage check of the documentation if enabled 41 | goto end 42 | ) 43 | 44 | if "%1" == "clean" ( 45 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 46 | del /q /s %BUILDDIR%\* 47 | goto end 48 | ) 49 | 50 | 51 | REM Check if sphinx-build is available and fallback to Python version if any 52 | %SPHINXBUILD% 1>NUL 2>NUL 53 | if errorlevel 9009 goto sphinx_python 54 | goto sphinx_ok 55 | 56 | :sphinx_python 57 | 58 | set SPHINXBUILD=python -m sphinx.__init__ 59 | %SPHINXBUILD% 2> nul 60 | if errorlevel 9009 ( 61 | echo. 62 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 63 | echo.installed, then set the SPHINXBUILD environment variable to point 64 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 65 | echo.may add the Sphinx directory to PATH. 66 | echo. 67 | echo.If you don't have Sphinx installed, grab it from 68 | echo.http://sphinx-doc.org/ 69 | exit /b 1 70 | ) 71 | 72 | :sphinx_ok 73 | 74 | 75 | if "%1" == "html" ( 76 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 77 | if errorlevel 1 exit /b 1 78 | echo. 79 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 80 | goto end 81 | ) 82 | 83 | if "%1" == "dirhtml" ( 84 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 85 | if errorlevel 1 exit /b 1 86 | echo. 87 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 88 | goto end 89 | ) 90 | 91 | if "%1" == "singlehtml" ( 92 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 93 | if errorlevel 1 exit /b 1 94 | echo. 95 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 96 | goto end 97 | ) 98 | 99 | if "%1" == "pickle" ( 100 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 101 | if errorlevel 1 exit /b 1 102 | echo. 103 | echo.Build finished; now you can process the pickle files. 104 | goto end 105 | ) 106 | 107 | if "%1" == "json" ( 108 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 109 | if errorlevel 1 exit /b 1 110 | echo. 111 | echo.Build finished; now you can process the JSON files. 112 | goto end 113 | ) 114 | 115 | if "%1" == "htmlhelp" ( 116 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 117 | if errorlevel 1 exit /b 1 118 | echo. 119 | echo.Build finished; now you can run HTML Help Workshop with the ^ 120 | .hhp project file in %BUILDDIR%/htmlhelp. 121 | goto end 122 | ) 123 | 124 | if "%1" == "qthelp" ( 125 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 129 | .qhcp project file in %BUILDDIR%/qthelp, like this: 130 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\python_example.qhcp 131 | echo.To view the help file: 132 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\python_example.ghc 133 | goto end 134 | ) 135 | 136 | if "%1" == "devhelp" ( 137 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 138 | if errorlevel 1 exit /b 1 139 | echo. 140 | echo.Build finished. 141 | goto end 142 | ) 143 | 144 | if "%1" == "epub" ( 145 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 146 | if errorlevel 1 exit /b 1 147 | echo. 148 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 149 | goto end 150 | ) 151 | 152 | if "%1" == "latex" ( 153 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 154 | if errorlevel 1 exit /b 1 155 | echo. 156 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 157 | goto end 158 | ) 159 | 160 | if "%1" == "latexpdf" ( 161 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 162 | cd %BUILDDIR%/latex 163 | make all-pdf 164 | cd %~dp0 165 | echo. 166 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 167 | goto end 168 | ) 169 | 170 | if "%1" == "latexpdfja" ( 171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 172 | cd %BUILDDIR%/latex 173 | make all-pdf-ja 174 | cd %~dp0 175 | echo. 176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 177 | goto end 178 | ) 179 | 180 | if "%1" == "text" ( 181 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 182 | if errorlevel 1 exit /b 1 183 | echo. 184 | echo.Build finished. The text files are in %BUILDDIR%/text. 185 | goto end 186 | ) 187 | 188 | if "%1" == "man" ( 189 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 190 | if errorlevel 1 exit /b 1 191 | echo. 192 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 193 | goto end 194 | ) 195 | 196 | if "%1" == "texinfo" ( 197 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 198 | if errorlevel 1 exit /b 1 199 | echo. 200 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 201 | goto end 202 | ) 203 | 204 | if "%1" == "gettext" ( 205 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 206 | if errorlevel 1 exit /b 1 207 | echo. 208 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 209 | goto end 210 | ) 211 | 212 | if "%1" == "changes" ( 213 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 214 | if errorlevel 1 exit /b 1 215 | echo. 216 | echo.The overview file is in %BUILDDIR%/changes. 217 | goto end 218 | ) 219 | 220 | if "%1" == "linkcheck" ( 221 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 222 | if errorlevel 1 exit /b 1 223 | echo. 224 | echo.Link check complete; look for any errors in the above output ^ 225 | or in %BUILDDIR%/linkcheck/output.txt. 226 | goto end 227 | ) 228 | 229 | if "%1" == "doctest" ( 230 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 231 | if errorlevel 1 exit /b 1 232 | echo. 233 | echo.Testing of doctests in the sources finished, look at the ^ 234 | results in %BUILDDIR%/doctest/output.txt. 235 | goto end 236 | ) 237 | 238 | if "%1" == "coverage" ( 239 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage 240 | if errorlevel 1 exit /b 1 241 | echo. 242 | echo.Testing of coverage in the sources finished, look at the ^ 243 | results in %BUILDDIR%/coverage/python.txt. 244 | goto end 245 | ) 246 | 247 | if "%1" == "xml" ( 248 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 249 | if errorlevel 1 exit /b 1 250 | echo. 251 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 252 | goto end 253 | ) 254 | 255 | if "%1" == "pseudoxml" ( 256 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 257 | if errorlevel 1 exit /b 1 258 | echo. 259 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 260 | goto end 261 | ) 262 | 263 | :end 264 | -------------------------------------------------------------------------------- /environment-dev.yml: -------------------------------------------------------------------------------- 1 | name: pys2index-dev 2 | channels: 3 | - conda-forge 4 | dependencies: 5 | - python>=3.9 6 | - cxx-compiler 7 | - numpy 8 | - s2geometry 9 | - xtensor 10 | - xtensor-python>=0.24 11 | - scikit-build-core 12 | - cmake 13 | - pytest 14 | - pip 15 | -------------------------------------------------------------------------------- /include/pys2index/s2pointindex.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __S2POINTINDEX_H_ 2 | #define __S2POINTINDEX_H_ 3 | 4 | #include 5 | 6 | #include "pybind11/pybind11.h" 7 | 8 | #include "xtensor/xbuilder.hpp" 9 | #include "xtensor/xtensor.hpp" 10 | 11 | #define FORCE_IMPORT_ARRAY 12 | #include "xtensor-python/pytensor.hpp" 13 | 14 | #include "s2/s2cell_id.h" 15 | #include "s2/s2closest_point_query.h" 16 | #include "s2/s2latlng.h" 17 | #include "s2/s2point.h" 18 | #include "s2/s2point_index.h" 19 | 20 | namespace py = pybind11; 21 | 22 | 23 | namespace pys2index 24 | { 25 | 26 | class s2point_index 27 | { 28 | public: 29 | using index_type = S2PointIndex; 30 | using cell_ids_type = xt::pytensor; 31 | using positions_type = xt::pytensor; 32 | 33 | template 34 | using distances_type = xt::pytensor; 35 | 36 | template 37 | using query_return_type = std::tuple, positions_type>; 38 | 39 | template 40 | using points_type = xt::pytensor; 41 | 42 | s2point_index() = default; 43 | 44 | template 45 | static std::unique_ptr from_points(const points_type& latlon_points); 46 | 47 | static std::unique_ptr from_cell_ids(const cell_ids_type& cell_ids); 48 | 49 | template 50 | query_return_type query(const points_type& latlon_points); 51 | 52 | cell_ids_type get_cell_ids(); 53 | 54 | private: 55 | index_type m_index; 56 | cell_ids_type m_cell_ids; 57 | 58 | template 59 | void insert_latlon_points(const points_type& latlon_points); 60 | 61 | void insert_cell_ids(); 62 | }; 63 | 64 | template 65 | std::unique_ptr s2point_index::from_points(const points_type& latlon_points) 66 | { 67 | auto index = std::make_unique(); 68 | 69 | index->insert_latlon_points(latlon_points); 70 | 71 | return index; 72 | } 73 | 74 | std::unique_ptr s2point_index::from_cell_ids(const cell_ids_type& cell_ids) 75 | { 76 | auto index = std::make_unique(); 77 | 78 | index->m_cell_ids = cell_ids; 79 | index->insert_cell_ids(); 80 | 81 | return index; 82 | } 83 | 84 | template 85 | void s2point_index::insert_latlon_points(const points_type& latlon_points) 86 | { 87 | auto n_points = latlon_points.shape()[0]; 88 | m_cell_ids.resize({ n_points }); 89 | 90 | py::gil_scoped_release release; 91 | 92 | for (auto i = 0; i < n_points; ++i) 93 | { 94 | S2CellId c(S2LatLng::FromDegrees(latlon_points(i, 0), latlon_points(i, 1))); 95 | 96 | m_cell_ids(i) = c.id(); 97 | m_index.Add(c.ToPoint(), static_cast(i)); 98 | } 99 | 100 | py::gil_scoped_acquire acquire; 101 | } 102 | 103 | void s2point_index::insert_cell_ids() 104 | { 105 | auto num_points = m_cell_ids.size(); 106 | 107 | py::gil_scoped_release release; 108 | 109 | for (std::size_t i = 0; i < num_points; ++i) 110 | { 111 | S2CellId c(m_cell_ids(i)); 112 | m_index.Add(c.ToPoint(), static_cast(i)); 113 | } 114 | 115 | py::gil_scoped_acquire acquire; 116 | } 117 | 118 | template 119 | auto s2point_index::query(const points_type& latlon_points) -> query_return_type 120 | { 121 | auto n_points = latlon_points.shape()[0]; 122 | auto distances = distances_type::from_shape({ n_points }); 123 | auto positions = positions_type::from_shape({ n_points }); 124 | 125 | py::gil_scoped_release release; 126 | 127 | S2ClosestPointQuery query(&m_index); 128 | 129 | for (auto i = 0; i < n_points; ++i) 130 | { 131 | S2Point point(S2LatLng::FromDegrees(latlon_points(i, 0), latlon_points(i, 1))); 132 | S2ClosestPointQuery::PointTarget target(point); 133 | 134 | auto results = query.FindClosestPoint(&target); 135 | 136 | distances(i) = static_cast(results.distance().degrees()); 137 | positions(i) = static_cast(results.data()); 138 | } 139 | 140 | py::gil_scoped_acquire acquire; 141 | 142 | return std::make_tuple(std::move(distances), std::move(positions)); 143 | } 144 | 145 | auto s2point_index::get_cell_ids() -> cell_ids_type 146 | { 147 | cell_ids_type cell_ids(m_cell_ids); 148 | 149 | return cell_ids; 150 | } 151 | 152 | } 153 | 154 | 155 | #endif // __S2POINTINDEX_H_ 156 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ 3 | "scikit-build-core", 4 | "pybind11", 5 | ] 6 | build-backend = "scikit_build_core.build" 7 | 8 | [project] 9 | name = "pys2index" 10 | version = "0.2.0dev" 11 | description = "Python/NumPy compatible geographical index based on s2geometry" 12 | keywords = ["python", "numpy", "s2geometry", "index"] 13 | readme = "README.md" 14 | license = {text = "BSD-3-Clause"} 15 | authors = [ 16 | {name = "Benoît Bovy"}, 17 | ] 18 | maintainers = [ 19 | {name = "pys2index contributors"}, 20 | ] 21 | requires-python = ">=3.9" 22 | dependencies = ["numpy"] 23 | 24 | [project.urls] 25 | Repository = "https://github.com/benbovy/pys2index" 26 | 27 | [project.optional-dependencies] 28 | test = ["pytest>=6.0"] 29 | 30 | [tool.scikit-build] 31 | sdist.exclude = [ 32 | ".clang-format", 33 | ".gitignore", 34 | ".pre-commit-config.yaml", 35 | ".github", 36 | ] 37 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | #include "pybind11/pybind11.h" 2 | 3 | #define FORCE_IMPORT_ARRAY 4 | #include "xtensor-python/pytensor.hpp" 5 | 6 | #include "pys2index/s2pointindex.hpp" 7 | 8 | #define STRINGIFY(x) #x 9 | #define MACRO_STRINGIFY(x) STRINGIFY(x) 10 | 11 | namespace py = pybind11; 12 | namespace pys2 = pys2index; 13 | 14 | 15 | PYBIND11_MODULE(pys2index, m) 16 | { 17 | xt::import_numpy(); 18 | 19 | m.doc() = R"pbdoc( 20 | Python/NumPy compatible geographical index based on s2geometry 21 | 22 | .. currentmodule:: pys2index 23 | 24 | .. autosummary:: 25 | :toctree: _generate 26 | 27 | S2PointIndex 28 | S2PointIndex.query 29 | S2PointIndex.get_cell_ids 30 | )pbdoc"; 31 | 32 | py::class_ py_s2pointindex(m, "S2PointIndex", R"pbdoc( 33 | S2 index for fast geographic point problems. 34 | 35 | Parameters 36 | ---------- 37 | latlon_points : ndarray of shape (n_points, 2) 38 | 2-d array of point coordinates (latitude, longitude) in degrees. 39 | )pbdoc"); 40 | 41 | py_s2pointindex.def(py::init(&pys2::s2point_index::from_points)); 42 | py_s2pointindex.def(py::init(&pys2::s2point_index::from_points)); 43 | py_s2pointindex.def(py::init(&pys2::s2point_index::from_cell_ids)); 44 | 45 | py_s2pointindex.def("query", 46 | &pys2::s2point_index::query, 47 | R"pbdoc( 48 | Query the index for nearest neighbors. 49 | 50 | Parameters 51 | ---------- 52 | latlon_points : ndarray of shape (n_points, 2), dtype=double 53 | 2-d array of query point coordinates (latitude, longitude) in degrees. 54 | 55 | Returns 56 | ------- 57 | distances : ndarray of shape (n_points,), dtype=double 58 | Distance to the nearest neighbor of the cooresponding points (in degrees). 59 | positions : ndarray of shape (n_points,), dtype=int 60 | Indices of the nearest neighbor of the corresponding points. 61 | 62 | )pbdoc"); 63 | py_s2pointindex.def("query", 64 | &pys2::s2point_index::query, 65 | "Query the index for nearest neighbors (float version)."); 66 | 67 | py_s2pointindex.def( 68 | "get_cell_ids", &pys2::s2point_index::get_cell_ids, py::return_value_policy::move); 69 | 70 | py_s2pointindex.def(py::pickle([](pys2::s2point_index& idx) { return idx.get_cell_ids(); }, 71 | [](pys2::s2point_index::cell_ids_type& cell_ids) 72 | { return pys2::s2point_index::from_cell_ids(cell_ids); })); 73 | 74 | #ifdef VERSION_INFO 75 | m.attr("__version__") = MACRO_STRINGIFY(VERSION_INFO); 76 | #else 77 | m.attr("__version__") = "dev"; 78 | #endif 79 | } 80 | -------------------------------------------------------------------------------- /tests/test_s2pointindex.py: -------------------------------------------------------------------------------- 1 | import pickle 2 | 3 | import numpy as np 4 | import pytest 5 | 6 | from pys2index import S2PointIndex 7 | 8 | 9 | @pytest.fixture(params=[np.float32, np.float64]) 10 | def dtype(request): 11 | return request.param 12 | 13 | 14 | @pytest.fixture 15 | def index_points(dtype): 16 | lat, lon = np.meshgrid(np.linspace(-85, 85, 10), np.linspace(-179, 179, 10)) 17 | return np.stack((lat.ravel(), lon.ravel()), axis=1).astype(dtype) 18 | 19 | 20 | @pytest.fixture 21 | def query_points(index_points, dtype): 22 | # query point positions shifted randomly 23 | # - along latitude axis only (easier for testing distances) 24 | # - small perturbations (< index point spacing) 25 | npoints = index_points.shape[0] 26 | perturb_lat = np.random.uniform(-5.0, 5.0, npoints) 27 | perturn_lon = np.zeros(npoints) 28 | 29 | return (index_points + np.stack((perturb_lat, perturn_lon), axis=1)).astype(dtype) 30 | 31 | 32 | @pytest.fixture 33 | def distances(index_points, query_points): 34 | return np.abs(index_points[:, 0] - query_points[:, 0]) 35 | 36 | 37 | def test_s2pointindex_create(index_points): 38 | # just check that no error is raised at index construction 39 | index = S2PointIndex(index_points) 40 | assert isinstance(index, S2PointIndex) 41 | 42 | 43 | def test_s2pointindex_query(index_points, query_points, distances): 44 | index = S2PointIndex(index_points) 45 | dist, pos = index.query(query_points) 46 | 47 | np.testing.assert_array_equal(index_points[pos], index_points) 48 | np.testing.assert_allclose(dist, distances, atol=1e-6) 49 | 50 | 51 | def test_s2pointindex_pickle(index_points): 52 | index = S2PointIndex(index_points) 53 | 54 | expected = index.get_cell_ids() 55 | 56 | pickled = pickle.dumps(index) 57 | loaded = pickle.loads(pickled) 58 | 59 | np.testing.assert_array_equal(loaded.get_cell_ids(), expected) 60 | --------------------------------------------------------------------------------