repo_id
stringlengths
21
96
file_path
stringlengths
31
155
content
stringlengths
1
92.9M
__index_level_0__
int64
0
0
rapidsai_public_repos/gpu-bdb/gpu_bdb
rapidsai_public_repos/gpu-bdb/gpu_bdb/benchmark_runner/benchmark_config.yaml
# benchmark config yaml ### Please fill these accordingly data_dir: output_dir: file_format: parquet output_filetype: parquet split_row_groups: False repartition_small_table: True benchmark_runner_include_sql: backend: GPU scheduler_file_path: dask_profile: False verify_results: False verify_dir: sheet: tab: get_read_time: False start_local_cluster: False
0
rapidsai_public_repos/gpu-bdb/gpu_bdb
rapidsai_public_repos/gpu-bdb/gpu_bdb/benchmark_runner/__init__.py
# Copyright (c) 2020, NVIDIA CORPORATION.
0
rapidsai_public_repos/gpu-bdb/gpu_bdb/benchmark_runner
rapidsai_public_repos/gpu-bdb/gpu_bdb/benchmark_runner/slurm/run_bench.sh
#!/bin/bash set -e pipefail ######################################################### ### Core Benchmark Configuration ### ######################################################### export DATA_DIRECTORY="" export OUTPUT_DIRECTORY="" export GOOGLE_SPREADSHEET_NAME="GPU-BDB" export GOOGLE_SPREADSHEET_TAB="SF1K TCP Runs" ######################################################### ### Run Configuration ### ######################################################### export USERNAME=$(whoami) # Repository home export GPU_BDB_HOME=$HOME/gpu-bdb # Conda environment information export CONDA_ENV_NAME="rapids-gpu-bdb" export CONDA_ENV_PATH="/opt/conda/etc/profile.d/conda.sh" # Logging, scratch space, and scheduler file path # for your machine or cluster export LOCAL_DIRECTORY=$HOME/dask-local-directory export LOGDIR=$LOCAL_DIRECTORY/logs export SCHEDULER_FILE=$LOCAL_DIRECTORY/scheduler.json export STATUS_FILE=$LOGDIR/status.txt # Communication protocol export CLUSTER_MODE=TCP # Scheduler configuration for your machine or cluster export INTERFACE="enp97s0f1" export NUM_WORKERS=${NUM_WORKERS:-8} # Cluster memory configuration export MAX_SYSTEM_MEMORY=$(free -m | awk '/^Mem:/{print $2}')M export DEVICE_MEMORY_LIMIT=70GB export POOL_SIZE=78GB # Dask-cuda optional configuration export DASK_JIT_UNSPILL=True export DASK_EXPLICIT_COMMS=False # BSQL export RUNNER_INCLUDE_BSQL=False export BLAZING_ALLOCATOR_MODE="existing" export BLAZING_LOGGING_DIRECTORY=/gpu-bdb-data/gpu-bdb/blazing_log rm -rf $BLAZING_LOGGING_DIRECTORY/* # Dask/distributed configuration export DASK_DISTRIBUTED__COMM__TIMEOUTS__CONNECT="100s" export DASK_DISTRIBUTED__COMM__TIMEOUTS__TCP="600s" export DASK_DISTRIBUTED__COMM__RETRY__DELAY__MIN="1s" export DASK_DISTRIBUTED__COMM__RETRY__DELAY__MAX="60s" ######################################################### ### Launch the Run ### ######################################################### source $CONDA_ENV_PATH conda activate $CONDA_ENV_NAME if [[ "$SLURM_NODEID" -eq 0 ]]; then bash $GPU_BDB_HOME/gpu_bdb/cluster_configuration/cluster-startup-slurm.sh SCHEDULER echo "STARTED SCHEDULER NODE" sleep 10 echo "STARTED" > ${STATUS_FILE} cd $GPU_BDB_HOME/gpu_bdb echo "Starting waiter.." python benchmark_runner/wait.py benchmark_runner/benchmark_config.yaml # echo "Starting load test.." # python queries/load_test/gpu_bdb_load_test.py --config_file benchmark_runner/benchmark_config.yaml > $LOGDIR/load_test.log echo "Starting E2E run.." python benchmark_runner.py --config_file benchmark_runner/benchmark_config.yaml > $LOGDIR/benchmark_runner.log echo "FINISHED" > ${STATUS_FILE} else sleep 15 # Sleep and wait for the scheduler to spin up echo $LOGDIR echo ls -l $LOGDIR bash $GPU_BDB_HOME/gpu_bdb/cluster_configuration/cluster-startup-slurm.sh echo "STARTING WORKER NODES" sleep 10 fi # Keep polling status_file until job is done until grep -q "FINISHED" "${STATUS_FILE}" do sleep 30 done pkill dask
0
rapidsai_public_repos/gpu-bdb/gpu_bdb/benchmark_runner
rapidsai_public_repos/gpu-bdb/gpu_bdb/benchmark_runner/slurm/run.sh
#!/bin/bash ACCOUNT=rapids PARTITION=backfill NODES=1 GPUS_PER_NODE=16 export NUM_WORKERS=$((NODES*GPUS_PER_NODE)) DATA_PATH="/lustre/fsw/rapids" MOUNT_PATH="/gpu-bdb-data/" IMAGE=${IMAGE:-/lustre/fsw/rapids/gpu-bdb/containers/gpu-bdb-20210421.sqsh} RUN_BENCH_PATH=${RUN_BENCH_PATH:-$HOME/gpu-bdb/gpu_bdb/benchmark_runner/slurm/run_bench.sh} rm *.out rm -rf $HOME/dask-local-directory/* srun \ --account $ACCOUNT \ --partition $PARTITION \ --nodes $NODES \ --exclusive \ --job-name ${ACCOUNT}-gpubdb:run_bench \ --gpus-per-node $GPUS_PER_NODE \ --time 120 \ --container-mounts $DATA_PATH:$MOUNT_PATH,$HOME:$HOME \ --container-image=$IMAGE \ bash -c "$RUN_BENCH_PATH"
0
rapidsai_public_repos/gpu-bdb/gpu_bdb/benchmark_runner
rapidsai_public_repos/gpu-bdb/gpu_bdb/benchmark_runner/slurm/Dockerfile
ARG CUDA_VER=11.2.0 ARG LINUX_VER=ubuntu18.04 FROM nvidia/cuda:${CUDA_VER}-devel-${LINUX_VER} RUN apt update -y && apt-get --fix-missing upgrade -y && apt install -y git ADD https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh /miniconda.sh RUN bash /miniconda.sh -b -p /opt/conda ENV GCC_VERSION=9 ENV CXX_VERSION=9 ENV CC=/usr/bin/gcc ENV CXX=/usr/bin/g++ ARG CONDA_HOME=/opt/conda ENV CONDA_HOME="$CONDA_HOME" ENV CUDA_HOME="/usr/local/cuda-11.2" ENV CUDA_PATH="$CUDA_HOME" ARG CUDA_SHORT_VERSION ENV CUDA_SHORT_VERSION="$CUDA_SHORT_VERSION" ARG PARALLEL_LEVEL=4 ENV PARALLEL_LEVEL=${PARALLEL_LEVEL} ENV PATH="$CONDA_HOME/bin:\ /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:\ $CUDA_HOME/bin" SHELL ["/bin/bash", "-c"] ENV CONDA_ENV="rapids-gpu-bdb" COPY /rapids-gpu-bdb-cuda11.2.yml /rapids-gpu-bdb-cuda11.2.yml RUN conda env create --name ${CONDA_ENV} --file /rapids-gpu-bdb-cuda11.2.yml RUN conda install -n ${CONDA_ENV} -c conda-forge spacy oauth2client gspread -q -y RUN source activate ${CONDA_ENV} && python -m spacy download en_core_web_sm # need to configure tzdata otherwise (seemingly) ARG DEBIAN_FRONTEND=noninteractive RUN set -x \ # Install dependencies && mkdir -p /etc/bash_completion.d \ && apt update -y --fix-missing || true \ && apt upgrade -y --fix-missing || true \ && apt install -y --fix-missing software-properties-common \ && add-apt-repository -y ppa:git-core/ppa || true \ && apt install -y --fix-missing --no-install-recommends \ ed vim bc nano less git wget sudo tzdata \ apt-utils apt-transport-https \ gcc g++ ninja-build bash-completion \ curl libssl-dev libcurl4-openssl-dev zlib1g-dev \ # ucx and ucx-py dependencies unzip automake autoconf libb2-dev libzstd-dev \ libtool librdmacm-dev libnuma-dev \ && bash -c "echo -e '\ deb http://archive.ubuntu.com/ubuntu/ xenial universe\n\ deb http://archive.ubuntu.com/ubuntu/ xenial-updates universe\ '" >> /etc/apt/sources.list.d/xenial.list \ && apt update -y || true && apt install -y libibcm-dev \ && rm /etc/apt/sources.list.d/xenial.list \ # cleanup && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* # Install ibverbs from MOFED ADD https://www.mellanox.com/downloads/ofed/MLNX_OFED-5.2-2.2.0.0/MLNX_OFED_LINUX-5.2-2.2.0.0-ubuntu18.04-x86_64.tgz /MLNX_OFED_LINUX-5.2-2.2.0.0-ubuntu18.04-x86_64.tgz RUN tar -xzf /MLNX_OFED_LINUX-5.2-2.2.0.0-ubuntu18.04-x86_64.tgz && \ cd MLNX_OFED_LINUX-5.2-2.2.0.0-ubuntu18.04-x86_64 && \ echo y | ./mlnxofedinstall --user-space-only --without-fw-update --without-neohost-backend\ && rm -rf /var/lib/apt/lists/* \ && rm -rf /MLNX_OFED_LINUX* RUN rm -rf /MLNX_OFED_LINUX-5.2-2.2.0.0-ubuntu18.04-x86_64* RUN /opt/conda/bin/conda install -n $CONDA_ENV -c conda-forge autoconf cython automake make libtool \ pkg-config m4 \ --force --no-deps -y -q ADD creds.json /creds.json ENV GOOGLE_SHEETS_CREDENTIALS_PATH=/creds.json RUN conda clean --all WORKDIR /
0
rapidsai_public_repos/gpu-bdb/gpu_bdb/benchmark_runner
rapidsai_public_repos/gpu-bdb/gpu_bdb/benchmark_runner/slurm/rapids-gpu-bdb-cuda11.2.yml
channels: - rapidsai-nightly - nvidia - conda-forge dependencies: - python=3.8 - cudatoolkit=11.2 - cudf - rmm - dask-cuda - dask-cudf - cuml - dask - distributed - scipy - scikit-learn - spacy=2.3 - oauth2client - asyncssh - psutil - ipykernel - jupyterlab - gspread - oauth2client - numba>=0.54.* - maven - google-api-python-client - pip - pip: - jupyter-server-proxy
0
rapidsai_public_repos
rapidsai_public_repos/cuspatial/.pre-commit-config.yaml
# Copyright (c) 2019-2023, NVIDIA CORPORATION. repos: - repo: https://github.com/PyCQA/isort rev: 5.12.0 hooks: - id: isort # Use the config file specific to each subproject so that each # project can specify its own first/third-party packages. args: ["--config-root=python/", "--resolve-all-configs"] files: python/.* types_or: [python, cython, pyi] - repo: https://github.com/psf/black rev: 22.3.0 hooks: - id: black files: python/cuspatial/.* # Explicitly specify the pyproject.toml at the repo root, not per-project. args: ["--config", "pyproject.toml"] - repo: https://github.com/PyCQA/flake8 rev: 5.0.4 hooks: - id: flake8 args: ["--config=.flake8"] files: python/.*$ types: [file] types_or: [python, cython] additional_dependencies: ["flake8-force"] - repo: https://github.com/MarcoGorelli/cython-lint rev: v0.1.10 hooks: - id: cython-lint - repo: https://github.com/pre-commit/mirrors-clang-format rev: v16.0.6 hooks: - id: clang-format types_or: [c, c++, cuda] args: ["-fallback-style=none", "-style=file", "-i"] - repo: https://github.com/codespell-project/codespell rev: v2.2.4 hooks: - id: codespell args: ["--config pyproject.toml"] additional_dependencies: ["tomli"] - repo: https://github.com/rapidsai/dependency-file-generator rev: v1.5.1 hooks: - id: rapids-dependency-file-generator args: ["--clean"] default_language_version: python: python3
0
rapidsai_public_repos
rapidsai_public_repos/cuspatial/pyproject.toml
[tool.black] line-length = 79 target-version = ["py39"] include = '\.py?$' force-exclude = ''' /( thirdparty | \.eggs | \.git | \.hg | \.mypy_cache | \.tox | \.venv | _build | buck-out | build | dist )/ ''' [tool.codespell] # note: pre-commit passes explicit lists of files here, which this skip file list doesn't override - # this is only to allow you to run codespell interactively skip = "./pyproject.toml,./.git,./cpp/build,.*egg-info.*,./.mypy_cache" # ignore short words, and typename parameters like OffsetT ignore-regex = "\\b(.{1,4}|[A-Z]\\w*T)\\b" ignore-words-list = "inout,unparseable" builtin = "clear" quiet-level = 3
0
rapidsai_public_repos
rapidsai_public_repos/cuspatial/.flake8
# Copyright (c) 2019-2023, NVIDIA CORPORATION. [flake8] filename = *.py, *.pyx, *.pxd, *.pxi exclude = __init__.py, *.egg, build, docs, .git force-check = True ignore = # line break before binary operator W503, # whitespace before : E203 per-file-ignores = # Rules ignored only in Cython: # E211: whitespace before '(' (used in multi-line imports) # E225: Missing whitespace around operators (breaks cython casting syntax like <int>) # E226: Missing whitespace around arithmetic operators (breaks cython pointer syntax like int*) # E227: Missing whitespace around bitwise or shift operator (Can also break casting syntax) # E275: Missing whitespace after keyword (Doesn't work with Cython except?) # E402: invalid syntax (works for Python, not Cython) # E999: invalid syntax (works for Python, not Cython) # W504: line break after binary operator (breaks lines that end with a pointer) *.pyx: E211, E225, E226, E227, E275, E402, E999, W504 *.pxd: E211, E225, E226, E227, E275, E402, E999, W504 *.pxi: E211, E225, E226, E227, E275, E402, E999, W504
0
rapidsai_public_repos
rapidsai_public_repos/cuspatial/fetch_rapids.cmake
# ============================================================================= # Copyright (c) 2018-2022, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and limitations under # the License. # ============================================================================= if(NOT EXISTS ${CMAKE_CURRENT_BINARY_DIR}/CUSPATIAL_RAPIDS.cmake) file(DOWNLOAD https://raw.githubusercontent.com/rapidsai/rapids-cmake/branch-23.12/RAPIDS.cmake ${CMAKE_BINARY_DIR}/CUSPATIAL_RAPIDS.cmake ) endif() include(${CMAKE_BINARY_DIR}/CUSPATIAL_RAPIDS.cmake)
0
rapidsai_public_repos
rapidsai_public_repos/cuspatial/README.md
# <div align="left"><img src="https://rapids.ai/assets/images/rapids_logo.png" width="90px"/>&nbsp;cuSpatial - GPU-Accelerated Vector Geospatial Data Analysis</div> > **Note** > > cuSpatial depends on [cuDF](https://github.com/rapidsai/cudf) and [RMM](https://github.com/rapidsai/rmm) from [RAPIDS](https://rapids.ai/). ## cuProj - GPU-accelerated Coordinate Reference System (CRS) Transformations cuProj is a new RAPIDS library housed within the cuSpatial repo that provides GPU-accelerated transformations of coordinates between coordinate reference systems (CRS). cuProj is available as of release 23.10 with support for transformations of WGS84 coordinates to and from Universal Transverse Mercator (UTM) :globe_with_meridians:. To learn more about cuProj, see the [Python cuProj README](python/cuproj/README.md) or the [c++ libcuproj README](cpp/cuproj/README.md). ## Resources - [cuSpatial User's Guide](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html): Python API reference and guides - [cuSpatial Developer Documentation](https://docs.rapids.ai/api/cuspatial/stable/developer_guide/index.html): Understand cuSpatial's architecture - [Getting Started](https://docs.rapids.ai/install#selector): Installation options for cuSpatial - [cuSpatial Community](https://github.com/rapidsai/cuspatial/discussions): Get help, collaborate, and ask the team questions - [cuSpatial Issues](https://github.com/rapidsai/cuspatial/issues/new/choose): Request a feature/documentation or report a bug ## Overview cuSpatial accelerates vector geospatial operations through GPU parallelization. As part of the RAPIDS libraries, cuSpatial is inherently connected to [cuDF](https://github.com/rapidsai/cudf), [cuML](https://github.com/rapidsai/cuml), and [cuGraph](https://github.com/rapidsai/cugraph), enabling GPU acceleration across entire workflows. cuSpatial represents data in [GeoArrow](https://github.com/geoarrow/geoarrow) format, which enables compatibility with the [Apache Arrow](https://arrow.apache.org) ecosystem. cuSpatial's Python API is closely matched to GeoPandas and data can seamlessly transition between the two: ```python import geopandas from shapely.geometry import Polygon import cuspatial p1 = Polygon([(0, 0), (1, 0), (1, 1)]) p2 = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]) geoseries = geopandas.GeoSeries([p1, p2]) cuspatial_geoseries = cuspatial.from_geopandas(geoseries) print(cuspatial_geoseries) ``` Output: ``` 0 POLYGON ((0 0, 1 0, 1 1, 0 0)) 1 POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0)) ``` For additional examples, browse the complete [API documentation](https://docs.rapids.ai/api/cuspatial/stable/), or check out more detailed [notebooks](https://github.com/rapidsai/notebooks-contrib). the [NYC Taxi][1] and [Weather][2] notebooks make use of cuSpatial. ## Supported Geospatial Operations cuSpatial is constantly working on new features! Check out the [epics](https://github.com/orgs/rapidsai/projects/41/views/4) for a high-level view of our development, or the [roadmap](https://github.com/orgs/rapidsai/projects/41/views/5) for the details! ### Core Spatial Functions - [Spatial relationship queries (DE-9IM)](https://docs.rapids.ai/api/cuspatial/stable/api_docs/geopandas_compatibility/#cuspatial.GeoSeries.contains) - [Linestring-Linestring Intersections](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#Linestring-Intersections) - Cartesian distance between any two geometries (ST_Distance) - [Haversine distance](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#cuspatial.haversine_distance) - [Hausdorff distance](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#cuspatial.directed_hausdorff_distance) - [Spatial window filtering](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#cuspatial.points_in_spatial_window) ### Indexing and Join Functions - [Quadtree indexing](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#Quadtree-Indexing) - [Spatial joins](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#Indexed-Spatial-Joins) - [Quadtree-based point-in-polygon](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#cuspatial.quadtree_point_in_polygon) - [Quadtree-based point-to-nearest-linestring](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#cuspatial.quadtree_point_to_nearest_linestring) ### Trajectory Functions - [Deriving trajectories from point location data](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#cuspatial.derive_trajectories) - [Computing distance/speed of trajectories](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#cuspatial.trajectory_distances_and_speeds) - [Computing spatial bounding boxes of trajectories](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#cuspatial.trajectory_bounding_boxes) ### What if operations I need aren't supported? Thanks to the `from_geopandas` and `to_geopandas` functions you can accelerate what cuSpatial supports, and leave the rest of the workflow in place. ```mermaid --- title: Integrating into Existing Workflows --- %%{init: { 'logLevel': 'debug', 'theme': 'base', 'gitGraph': {'showBranches': false}, 'themeVariables': {'commitLabelColor': '#000000', 'commitLabelBackground': '#ffffff', 'commitLabelFontSize': '14px'}} }%% gitGraph commit id: "Existing Workflow Start" commit id: "GeoPandas IO" commit id: "Geospatial Analytics" branch a checkout a commit id: "from_geopandas" commit id: "cuSpatial GPU Acceleration" branch b checkout b commit id: "cuDF" commit id: "cuML" commit id: "cuGraph" checkout a merge b commit id: "to_geopandas" checkout main merge a commit id: "Continue Work" ``` ## Using cuSpatial **CUDA/GPU requirements** - CUDA 11.2+ with a [compatible, supported driver](https://docs.nvidia.com/datacenter/tesla/drivers/#cuda-drivers) - Linux native: Pascal architecture or newer ([Compute Capability >=6.0](https://developer.nvidia.com/cuda-gpus)) - WSL2: Volta architecture or newer ([Compute Capability >=7.0](https://developer.nvidia.com/cuda-gpus)) ### Quick start: Docker Use the [RAPIDS Release Selector](https://docs.rapids.ai/install#selector), selecting `Docker` as the installation method. All RAPIDS Docker images contain cuSpatial. An example command from the Release Selector: ```shell docker run --gpus all --pull always --rm -it \ --shm-size=1g --ulimit memlock=-1 --ulimit stack=67108864 \ -p 8888:8888 -p 8787:8787 -p 8786:8786 \ nvcr.io/nvidia/rapidsai/notebooks:23.12-cuda11.8-py3.10 ``` ### Install with Conda To install via conda: > **Note** cuSpatial is supported only on Linux or [through WSL](https://rapids.ai/wsl2.html), and with Python versions 3.9 and 3.10 cuSpatial can be installed with conda (miniconda, or the full Anaconda distribution) from the rapidsai channel: ```shell conda install -c rapidsai -c conda-forge -c nvidia \ cuspatial=23.12 python=3.10 cudatoolkit=11.8 ``` We also provide nightly Conda packages built from the HEAD of our latest development branch. See the [RAPIDS installation documentation](https://docs.rapids.ai/install) for more OS and version info. ### Install with pip To install via pip: > **Note** cuSpatial is supported only on Linux or [through WSL](https://rapids.ai/wsl2.html), and with Python versions 3.9 and 3.10 The cuSpatial pip packages can be installed from NVIDIA's PyPI index. pip installations require using the matching wheel to the system's installed CUDA toolkit. - For CUDA 11 toolkits, install the `-cu11` wheels - For CUDA 12 toolkits install the `-cu12` wheels - If your installation has a CUDA 12 driver but a CUDA 11 toolkit, use the `-cu11` wheels. ```shell pip install cuspatial-cu12 --extra-index-url=https://pypi.nvidia.com pip install cuspatial-cu11 --extra-index-url=https://pypi.nvidia.com ``` #### Troubleshooting Fiona/GDAL versions cuSpatial depends on [`geopandas`](https://github.com/geopandas/geopandas), which uses [`fiona >= 1.8.19`](https://pypi.org/project/Fiona/), to read common GIS formats with GDAL. Fiona requires GDAL is already present on your system, but its minimum required version may be newer than the version of GDAL in your OS's package manager. Fiona checks the GDAL version at install time and fails with an error like this if a compatible version of GDAL isn't installed: ``` ERROR: GDAL >= 3.2 is required for fiona. Please upgrade GDAL. ``` There are two ways to fix this: 1. Install a version of GDAL that meets fiona's minimum required version * Ubuntu users can install a newer GDAL with the [UbuntuGIS PPA](https://wiki.ubuntu.com/UbuntuGIS): ```shell sudo -y add-apt-repository ppa:ubuntugis/ppa sudo apt install libgdal-dev ``` 2. Pin fiona's version to a range that's compatible with your version of `libgdal-dev` * For Ubuntu20.04 ([GDAL v3.0.4](https://packages.ubuntu.com/focal/libgdal-dev)): ```shell pip install --no-binary fiona --extra-index-url=https://pypi.nvidia.com cuspatial-cu12 'fiona>=1.8.19,<1.9' ``` * For Ubuntu22.04 ([GDAL v3.4.1](https://packages.ubuntu.com/jammy/libgdal-dev)): ```shell pip install --no-binary fiona --extra-index-url=https://pypi.nvidia.com cuspatial-cu12 'fiona>=1.9' ``` ### Build/Install from source To build and install cuSpatial from source please see the [build documentation](https://docs.rapids.ai/api/cuspatial/stable/developer_guide/build.html). ## Citing cuSpatial If you find cuSpatial useful in your published work, please consider citing the repository. ```bibtex @misc{cuspatial:23.12, author = {{NVIDIA Corporation}}, title = {cuSpatial: GPU-Accelerated Geospatial and Spatiotemporal Algorithms}, year = {2023}, publisher = {NVIDIA}, howpublished = {\url{https://github.com/rapidsai/cuspatial}}, note = {Software available from github.com}, } ``` [1]:https://github.com/rapidsai-community/notebooks-contrib/blob/main/community_tutorials_and_guides/taxi/NYCTaxi-E2E.ipynb [2]:https://github.com/rapidsai-community/notebooks-contrib/blob/main/community_tutorials_and_guides/weather.ipynb
0
rapidsai_public_repos
rapidsai_public_repos/cuspatial/CHANGELOG.md
# cuSpatial 23.10.00 (11 Oct 2023) ## 🚨 Breaking Changes - Update to Cython 3.0.0 ([#1235](https://github.com/rapidsai/cuspatial/pull/1235)) [@vyasr](https://github.com/vyasr) ## πŸ› Bug Fixes - Add `curl` for notebook testing ([#1281](https://github.com/rapidsai/cuspatial/pull/1281)) [@raydouglass](https://github.com/raydouglass) - Use `conda mambabuild` not `mamba mambabuild` ([#1265](https://github.com/rapidsai/cuspatial/pull/1265)) [@bdice](https://github.com/bdice) - Add back deleted conda env files ([#1261](https://github.com/rapidsai/cuspatial/pull/1261)) [@harrism](https://github.com/harrism) ## πŸ“– Documentation - [REVIEW] Add cudf example code for haversine distance into 23.10 ([#1260](https://github.com/rapidsai/cuspatial/pull/1260)) [@taureandyernv](https://github.com/taureandyernv) ## πŸ› οΈ Improvements - Benchmark `GeoSeries.Distance` ([#1277](https://github.com/rapidsai/cuspatial/pull/1277)) [@isVoid](https://github.com/isVoid) - fix update-version.sh ([#1272](https://github.com/rapidsai/cuspatial/pull/1272)) [@trxcllnt](https://github.com/trxcllnt) - Update image names ([#1269](https://github.com/rapidsai/cuspatial/pull/1269)) [@AyodeAwe](https://github.com/AyodeAwe) - Update to clang 16.0.6. ([#1266](https://github.com/rapidsai/cuspatial/pull/1266)) [@bdice](https://github.com/bdice) - Simplify wheel build scripts and allow alphas of RAPIDS dependencies ([#1264](https://github.com/rapidsai/cuspatial/pull/1264)) [@divyegala](https://github.com/divyegala) - Update devcontainers to align with other RAPIDS repositories ([#1263](https://github.com/rapidsai/cuspatial/pull/1263)) [@trxcllnt](https://github.com/trxcllnt) - Use `copy-pr-bot` ([#1262](https://github.com/rapidsai/cuspatial/pull/1262)) [@ajschmidt8](https://github.com/ajschmidt8) - Add binary_predicates.ipynb workflow and test data to package. ([#1258](https://github.com/rapidsai/cuspatial/pull/1258)) [@thomcom](https://github.com/thomcom) - Re-enable cuspatial tests and dependency. ([#1253](https://github.com/rapidsai/cuspatial/pull/1253)) [@thomcom](https://github.com/thomcom) - Fix 23.08 -&gt; 23.10 automerge ([#1251](https://github.com/rapidsai/cuspatial/pull/1251)) [@thomcom](https://github.com/thomcom) - Change path to trajectories_extracted.p to improve CI run consistency. ([#1247](https://github.com/rapidsai/cuspatial/pull/1247)) [@thomcom](https://github.com/thomcom) - Update to Cython 3.0.0 ([#1235](https://github.com/rapidsai/cuspatial/pull/1235)) [@vyasr](https://github.com/vyasr) - Branch 23.10 merge 23.08 ([#1230](https://github.com/rapidsai/cuspatial/pull/1230)) [@vyasr](https://github.com/vyasr) # cuSpatial 23.08.00 (9 Aug 2023) ## 🚨 Breaking Changes - Simplify point-in-polygon header only APIs ([#1192](https://github.com/rapidsai/cuspatial/pull/1192)) [@isVoid](https://github.com/isVoid) ## πŸ› Bug Fixes - Update nightly wheel tests for cuproj ([#1250](https://github.com/rapidsai/cuspatial/pull/1250)) [@raydouglass](https://github.com/raydouglass) - Update GeoDataFrame to Use the Structured GatherMap Class ([#1219](https://github.com/rapidsai/cuspatial/pull/1219)) [@isVoid](https://github.com/isVoid) - Add streams to allocate_like call ([#1218](https://github.com/rapidsai/cuspatial/pull/1218)) [@isVoid](https://github.com/isVoid) - Add CUDA major to `cuspatial`&#39;s `build/string` ([#1211](https://github.com/rapidsai/cuspatial/pull/1211)) [@jakirkham](https://github.com/jakirkham) - Fix overflowing in `intersection_intermediates.remove_if` ([#1209](https://github.com/rapidsai/cuspatial/pull/1209)) [@isVoid](https://github.com/isVoid) - Sort the mergeable segments before computing merged segments ([#1207](https://github.com/rapidsai/cuspatial/pull/1207)) [@isVoid](https://github.com/isVoid) - Fix a small typo in pairwise_linestring_distance ([#1199](https://github.com/rapidsai/cuspatial/pull/1199)) [@isVoid](https://github.com/isVoid) - Improve Polygon.contains(LineString) predicate logic. ([#1186](https://github.com/rapidsai/cuspatial/pull/1186)) [@thomcom](https://github.com/thomcom) - Use grid_stride_range in kernel loops ([#1178](https://github.com/rapidsai/cuspatial/pull/1178)) [@harrism](https://github.com/harrism) - Better support for binary predicates with large inputs. ([#1166](https://github.com/rapidsai/cuspatial/pull/1166)) [@thomcom](https://github.com/thomcom) ## πŸ“– Documentation - cuProj Python and C++ Documentation ([#1237](https://github.com/rapidsai/cuspatial/pull/1237)) [@harrism](https://github.com/harrism) - cuSpatial 23.08 README updates ([#1232](https://github.com/rapidsai/cuspatial/pull/1232)) [@jarmak-nv](https://github.com/jarmak-nv) - Add author credit to zipcode counting notebook, fix cudf string processing argument ([#1201](https://github.com/rapidsai/cuspatial/pull/1201)) [@isVoid](https://github.com/isVoid) - Remove `osmnx` dependency and use a small local dataset ([#1195](https://github.com/rapidsai/cuspatial/pull/1195)) [@isVoid](https://github.com/isVoid) ## πŸš€ New Features - Add `geoseries.distance` ([#1231](https://github.com/rapidsai/cuspatial/pull/1231)) [@isVoid](https://github.com/isVoid) - Initial Python bindings for cuProj ([#1217](https://github.com/rapidsai/cuspatial/pull/1217)) [@harrism](https://github.com/harrism) - WGS84 to UTM benchmark (C++) ([#1216](https://github.com/rapidsai/cuspatial/pull/1216)) [@harrism](https://github.com/harrism) - Adding Spherical Surface Processing Capability to Point-in-Polygon Queries ([#1212](https://github.com/rapidsai/cuspatial/pull/1212)) [@ayasar70](https://github.com/ayasar70) - WGS84 &lt;--&gt; UTM projection header-only API ([#1191](https://github.com/rapidsai/cuspatial/pull/1191)) [@harrism](https://github.com/harrism) - External issue triage GHA ([#1177](https://github.com/rapidsai/cuspatial/pull/1177)) [@jarmak-nv](https://github.com/jarmak-nv) - Binary Predicates Introduction and Benchmark Notebook ([#1156](https://github.com/rapidsai/cuspatial/pull/1156)) [@thomcom](https://github.com/thomcom) - Add cmake infrastructure for internal projection library ([#1132](https://github.com/rapidsai/cuspatial/pull/1132)) [@harrism](https://github.com/harrism) ## πŸ› οΈ Improvements - Switch to new wheel building pipeline ([#1227](https://github.com/rapidsai/cuspatial/pull/1227)) [@vyasr](https://github.com/vyasr) - Use Google Benchmark from rapids-cmake in cuproj. ([#1225](https://github.com/rapidsai/cuspatial/pull/1225)) [@bdice](https://github.com/bdice) - Use rapids-cmake to supply Google Benchmark library. ([#1224](https://github.com/rapidsai/cuspatial/pull/1224)) [@bdice](https://github.com/bdice) - Revert CUDA 12.0 CI workflows to branch-23.08. ([#1223](https://github.com/rapidsai/cuspatial/pull/1223)) [@bdice](https://github.com/bdice) - Update to `rapidsai/devcontainers:23.08` ([#1214](https://github.com/rapidsai/cuspatial/pull/1214)) [@trxcllnt](https://github.com/trxcllnt) - Add Comprehensive Test for Multigeometry Range Classes ([#1197](https://github.com/rapidsai/cuspatial/pull/1197)) [@isVoid](https://github.com/isVoid) - Update to CMake 3.26.4 ([#1196](https://github.com/rapidsai/cuspatial/pull/1196)) [@vyasr](https://github.com/vyasr) - Simplify point-in-polygon header only APIs ([#1192](https://github.com/rapidsai/cuspatial/pull/1192)) [@isVoid](https://github.com/isVoid) - Forward merge `branch-23.06` into `branch-23.08` ([#1190](https://github.com/rapidsai/cuspatial/pull/1190)) [@raydouglass](https://github.com/raydouglass) - use rapids-upload-docs script ([#1181](https://github.com/rapidsai/cuspatial/pull/1181)) [@AyodeAwe](https://github.com/AyodeAwe) - Remove Stale Demo Scripts ([#1180](https://github.com/rapidsai/cuspatial/pull/1180)) [@isVoid](https://github.com/isVoid) - Updates Build Instructions to Adjust for Devcontainer Instructions and Remove Stale Information ([#1179](https://github.com/rapidsai/cuspatial/pull/1179)) [@isVoid](https://github.com/isVoid) - Fix branch-23.06 forward-merge into branch-23.08 ([#1175](https://github.com/rapidsai/cuspatial/pull/1175)) [@trxcllnt](https://github.com/trxcllnt) - Remove documentation build scripts for Jenkins ([#1169](https://github.com/rapidsai/cuspatial/pull/1169)) [@ajschmidt8](https://github.com/ajschmidt8) - cuSpatial: Build CUDA 12 packages ([#1044](https://github.com/rapidsai/cuspatial/pull/1044)) [@isVoid](https://github.com/isVoid) # cuSpatial 23.06.00 (7 Jun 2023) ## 🚨 Breaking Changes - Reorganize cuSpatial headers ([#1097](https://github.com/rapidsai/cuspatial/pull/1097)) [@harrism](https://github.com/harrism) - Update minimum Python version to Python 3.9 ([#1089](https://github.com/rapidsai/cuspatial/pull/1089)) [@shwina](https://github.com/shwina) - Move `experimental` headers into main `include/cuspatial` directory ([#1081](https://github.com/rapidsai/cuspatial/pull/1081)) [@harrism](https://github.com/harrism) - Improve Hausdorff Many Column Performance ([#916](https://github.com/rapidsai/cuspatial/pull/916)) [@isVoid](https://github.com/isVoid) ## πŸ› Bug Fixes - Fix scatter bug due to overlapping range in `pairwise_linestring_intersection` ([#1152](https://github.com/rapidsai/cuspatial/pull/1152)) [@isVoid](https://github.com/isVoid) - Pin cuml dependency in notebook testing environment to nightlies ([#1110](https://github.com/rapidsai/cuspatial/pull/1110)) [@isVoid](https://github.com/isVoid) - Fix a bug in point-in-polygon kernel: if the point is collinear with an edge, result is asserted false ([#1108](https://github.com/rapidsai/cuspatial/pull/1108)) [@isVoid](https://github.com/isVoid) - Fix a bug in segment intersection primitive where two collinear segment touch at endpoints is miscomputed as a degenerate segment ([#1093](https://github.com/rapidsai/cuspatial/pull/1093)) [@isVoid](https://github.com/isVoid) - Update `CMAKE_CUDA_ARCHITECTURE` to use new value ([#1070](https://github.com/rapidsai/cuspatial/pull/1070)) [@isVoid](https://github.com/isVoid) - Bug fix in `pairwise_linestring_intersection` ([#1069](https://github.com/rapidsai/cuspatial/pull/1069)) [@isVoid](https://github.com/isVoid) ## πŸ“– Documentation - Add documentation for `pairwise_linestring_polygon_distance`, `pairwise_polygon_distance` ([#1145](https://github.com/rapidsai/cuspatial/pull/1145)) [@isVoid](https://github.com/isVoid) - Make User Guide appear in Docs page header ([#1133](https://github.com/rapidsai/cuspatial/pull/1133)) [@jarmak-nv](https://github.com/jarmak-nv) - Add Hausdorff Clustering Notebooks ([#922](https://github.com/rapidsai/cuspatial/pull/922)) [@isVoid](https://github.com/isVoid) ## πŸš€ New Features - Add Benchmark to `pairwise_linestring_polygon_distance` ([#1153](https://github.com/rapidsai/cuspatial/pull/1153)) [@isVoid](https://github.com/isVoid) - Adds `pairwise_point_polygon_distance` benchmark ([#1131](https://github.com/rapidsai/cuspatial/pull/1131)) [@isVoid](https://github.com/isVoid) - Reorganize cuSpatial headers ([#1097](https://github.com/rapidsai/cuspatial/pull/1097)) [@harrism](https://github.com/harrism) - Python API for `pairwise_polygon_distance` ([#1074](https://github.com/rapidsai/cuspatial/pull/1074)) [@isVoid](https://github.com/isVoid) - Column API for `pairwise_polygon_distance` ([#1073](https://github.com/rapidsai/cuspatial/pull/1073)) [@isVoid](https://github.com/isVoid) - Header only API for polygon-polygon distance ([#1065](https://github.com/rapidsai/cuspatial/pull/1065)) [@isVoid](https://github.com/isVoid) - Python API for linestring polygon distance ([#1031](https://github.com/rapidsai/cuspatial/pull/1031)) [@isVoid](https://github.com/isVoid) - Column API for linestring-polygon distance ([#1030](https://github.com/rapidsai/cuspatial/pull/1030)) [@isVoid](https://github.com/isVoid) ## πŸ› οΈ Improvements - Fix `cudf::column` constructor args ([#1151](https://github.com/rapidsai/cuspatial/pull/1151)) [@trxcllnt](https://github.com/trxcllnt) - cuSpatial pip packages ([#1148](https://github.com/rapidsai/cuspatial/pull/1148)) [@trxcllnt](https://github.com/trxcllnt) - Refactor `ST_Distance` header only API ([#1143](https://github.com/rapidsai/cuspatial/pull/1143)) [@isVoid](https://github.com/isVoid) - Run docs nightly ([#1141](https://github.com/rapidsai/cuspatial/pull/1141)) [@AyodeAwe](https://github.com/AyodeAwe) - Add `multilinestring_segment_manager` for segment related methods in multilinestring ranges ([#1134](https://github.com/rapidsai/cuspatial/pull/1134)) [@isVoid](https://github.com/isVoid) - Improve zipcode counting notebook by adding GPU backed WKT parser ([#1130](https://github.com/rapidsai/cuspatial/pull/1130)) [@isVoid](https://github.com/isVoid) - Delete add_issue_to_project.yml ([#1129](https://github.com/rapidsai/cuspatial/pull/1129)) [@jarmak-nv](https://github.com/jarmak-nv) - Bump Gtest version following Rapids-cmake change ([#1126](https://github.com/rapidsai/cuspatial/pull/1126)) [@isVoid](https://github.com/isVoid) - Refactor ST_Distance Column API and Cython ([#1124](https://github.com/rapidsai/cuspatial/pull/1124)) [@isVoid](https://github.com/isVoid) - Reorganize src, tests, and benchmarks ([#1115](https://github.com/rapidsai/cuspatial/pull/1115)) [@harrism](https://github.com/harrism) - Add Legal Terms to Trajectory Clustering Notebook ([#1111](https://github.com/rapidsai/cuspatial/pull/1111)) [@isVoid](https://github.com/isVoid) - Enable sccache hits from local builds ([#1109](https://github.com/rapidsai/cuspatial/pull/1109)) [@AyodeAwe](https://github.com/AyodeAwe) - Revert to branch-23.06 for shared-action-workflows ([#1107](https://github.com/rapidsai/cuspatial/pull/1107)) [@shwina](https://github.com/shwina) - Update minimum Python version to Python 3.9 ([#1089](https://github.com/rapidsai/cuspatial/pull/1089)) [@shwina](https://github.com/shwina) - Remove usage of rapids-get-rapids-version-from-git ([#1088](https://github.com/rapidsai/cuspatial/pull/1088)) [@jjacobelli](https://github.com/jjacobelli) - Add `contains`predicate. ([#1086](https://github.com/rapidsai/cuspatial/pull/1086)) [@thomcom](https://github.com/thomcom) - Binary Predicate Test Dispatching ([#1085](https://github.com/rapidsai/cuspatial/pull/1085)) [@thomcom](https://github.com/thomcom) - Move `experimental` headers into main `include/cuspatial` directory ([#1081](https://github.com/rapidsai/cuspatial/pull/1081)) [@harrism](https://github.com/harrism) - Update clang-format to 15.0.7 ([#1072](https://github.com/rapidsai/cuspatial/pull/1072)) [@bdice](https://github.com/bdice) - Use ARC V2 self-hosted runners for GPU jobs ([#1066](https://github.com/rapidsai/cuspatial/pull/1066)) [@jjacobelli](https://github.com/jjacobelli) - Implement and Test All non-multi-Feature Spatial Predicate Combinations ([#1064](https://github.com/rapidsai/cuspatial/pull/1064)) [@thomcom](https://github.com/thomcom) - Reduced equals time and fixed a bug. ([#1051](https://github.com/rapidsai/cuspatial/pull/1051)) [@thomcom](https://github.com/thomcom) - use make_device_vector in pairwise_point_in_polygon_test ([#1049](https://github.com/rapidsai/cuspatial/pull/1049)) [@cwharris](https://github.com/cwharris) - Use thrust::host_vector instead of std::vector&lt;bool&gt; in tests ([#1048](https://github.com/rapidsai/cuspatial/pull/1048)) [@cwharris](https://github.com/cwharris) - Branch 23.06 merge 23.04 (2) ([#1035](https://github.com/rapidsai/cuspatial/pull/1035)) [@harrism](https://github.com/harrism) - Pairwise Multipoint Equals Count function ([#1022](https://github.com/rapidsai/cuspatial/pull/1022)) [@thomcom](https://github.com/thomcom) - Branch 23.06 merge 23.04 ([#1021](https://github.com/rapidsai/cuspatial/pull/1021)) [@harrism](https://github.com/harrism) - Add GTC 2023 Reverse GeoCoding Demo Notebook ([#1001](https://github.com/rapidsai/cuspatial/pull/1001)) [@thomcom](https://github.com/thomcom) - Improve Hausdorff Many Column Performance ([#916](https://github.com/rapidsai/cuspatial/pull/916)) [@isVoid](https://github.com/isVoid) # cuSpatial 23.04.00 (6 Apr 2023) ## 🚨 Breaking Changes - Consistently validate polygon inputs for GeoArrow offset format ([#973](https://github.com/rapidsai/cuspatial/pull/973)) [@harrism](https://github.com/harrism) - Remove cubic spline interpolation ([#959](https://github.com/rapidsai/cuspatial/pull/959)) [@harrism](https://github.com/harrism) - Refactors API to accept GeoSeries input for projection and trajectory functions ([#955](https://github.com/rapidsai/cuspatial/pull/955)) [@isVoid](https://github.com/isVoid) - Refactors `filtering.py`, `indexing.py` to Accept GeoSeries ([#938](https://github.com/rapidsai/cuspatial/pull/938)) [@isVoid](https://github.com/isVoid) - Refactors `bounding.py` to accept GeoSeries Input ([#934](https://github.com/rapidsai/cuspatial/pull/934)) [@isVoid](https://github.com/isVoid) - Remove shapefile reader, conda GDAL dependency, move cmake gdal dependency to cpp tests only ([#932](https://github.com/rapidsai/cuspatial/pull/932)) [@harrism](https://github.com/harrism) - Refactor `directed_hausdorff_distance` and `haversine_distance` into `GeoSeries` Interface ([#924](https://github.com/rapidsai/cuspatial/pull/924)) [@isVoid](https://github.com/isVoid) ## πŸ› Bug Fixes - Bug Fix: point-in-multipolygon reduction using the wrong key-compare functor ([#1043](https://github.com/rapidsai/cuspatial/pull/1043)) [@isVoid](https://github.com/isVoid) - Fix quotes in backticks in Developer Guide ([#1034](https://github.com/rapidsai/cuspatial/pull/1034)) [@harrism](https://github.com/harrism) - Attempt to Fix Broken C++ Build After `cudftestutil` is Made a Shared Lib ([#996](https://github.com/rapidsai/cuspatial/pull/996)) [@isVoid](https://github.com/isVoid) - Consistently validate polygon inputs for GeoArrow offset format ([#973](https://github.com/rapidsai/cuspatial/pull/973)) [@harrism](https://github.com/harrism) - Fix OB bug in `linestring_intersection_intermediates.remove_if` Function ([#945](https://github.com/rapidsai/cuspatial/pull/945)) [@isVoid](https://github.com/isVoid) - Fix broken `point_indices` methods in `PolygonGeoColumnAccessor` ([#907](https://github.com/rapidsai/cuspatial/pull/907)) [@isVoid](https://github.com/isVoid) - Fix multiple bugs in user guide ([#906](https://github.com/rapidsai/cuspatial/pull/906)) [@isVoid](https://github.com/isVoid) - `_from_point_xy` improvements ([#905](https://github.com/rapidsai/cuspatial/pull/905)) [@isVoid](https://github.com/isVoid) - Add `valid_count` and `has_nulls` to GeoColumn ([#894](https://github.com/rapidsai/cuspatial/pull/894)) [@thomcom](https://github.com/thomcom) ## πŸ“– Documentation - : Fix linestring link in readme ([#1003](https://github.com/rapidsai/cuspatial/pull/1003)) [@jarmak-nv](https://github.com/jarmak-nv) - : Move build instructions to dev guide ([#999](https://github.com/rapidsai/cuspatial/pull/999)) [@jarmak-nv](https://github.com/jarmak-nv) - Add `pairwise_linestring_intersection` example in user guide ([#989](https://github.com/rapidsai/cuspatial/pull/989)) [@isVoid](https://github.com/isVoid) - Update cuSpatial Readme ([#977](https://github.com/rapidsai/cuspatial/pull/977)) [@jarmak-nv](https://github.com/jarmak-nv) - Add ZipCode Counting Notebook ([#919](https://github.com/rapidsai/cuspatial/pull/919)) [@isVoid](https://github.com/isVoid) ## πŸš€ New Features - Add segment Iterators, test multi*_range and miscellaneous lazy iterator additions ([#1026](https://github.com/rapidsai/cuspatial/pull/1026)) [@isVoid](https://github.com/isVoid) - Add Header Only API for Linestring-Polygon Distance ([#1011](https://github.com/rapidsai/cuspatial/pull/1011)) [@isVoid](https://github.com/isVoid) - Add `geometry_generator` factory for programmatic generation of geometry arrays ([#998](https://github.com/rapidsai/cuspatial/pull/998)) [@isVoid](https://github.com/isVoid) - Add python API `pairwise_point_polygon_distance` ([#988](https://github.com/rapidsai/cuspatial/pull/988)) [@isVoid](https://github.com/isVoid) - Add column API for `pairwise_point_polygon_distance` ([#984](https://github.com/rapidsai/cuspatial/pull/984)) [@isVoid](https://github.com/isVoid) - Add Header-Only `point_polygon_distance`, add non-owning polygon objects ([#976](https://github.com/rapidsai/cuspatial/pull/976)) [@isVoid](https://github.com/isVoid) - Remove cubic spline interpolation ([#959](https://github.com/rapidsai/cuspatial/pull/959)) [@harrism](https://github.com/harrism) - Remove shapefile reader, conda GDAL dependency, move cmake gdal dependency to cpp tests only ([#932](https://github.com/rapidsai/cuspatial/pull/932)) [@harrism](https://github.com/harrism) - Add `from_linestrings_xy` and `from_polygons_xy` ([#928](https://github.com/rapidsai/cuspatial/pull/928)) [@thomcom](https://github.com/thomcom) - Implement `geom_equals` and binary predicates that depend only on it. ([#926](https://github.com/rapidsai/cuspatial/pull/926)) [@thomcom](https://github.com/thomcom) - Add `apply_boolean_mask` Feature ([#918](https://github.com/rapidsai/cuspatial/pull/918)) [@isVoid](https://github.com/isVoid) - Add C++ Column API and Python API for `pairwise_linestring_intersection` ([#862](https://github.com/rapidsai/cuspatial/pull/862)) [@isVoid](https://github.com/isVoid) ## πŸ› οΈ Improvements - Refactor spatial join tests ([#1019](https://github.com/rapidsai/cuspatial/pull/1019)) [@harrism](https://github.com/harrism) - Reduce gtest times ([#1018](https://github.com/rapidsai/cuspatial/pull/1018)) [@harrism](https://github.com/harrism) - Intersection only predicates ([#1016](https://github.com/rapidsai/cuspatial/pull/1016)) [@thomcom](https://github.com/thomcom) - Updated binpred architecture ([#1009](https://github.com/rapidsai/cuspatial/pull/1009)) [@thomcom](https://github.com/thomcom) - Add `dependency-file-generator` as `pre-commit` hook ([#1008](https://github.com/rapidsai/cuspatial/pull/1008)) [@ajschmidt8](https://github.com/ajschmidt8) - Header-only quadtree_point_to_nearest_linestring ([#1005](https://github.com/rapidsai/cuspatial/pull/1005)) [@harrism](https://github.com/harrism) - Add codespell as a linter ([#992](https://github.com/rapidsai/cuspatial/pull/992)) [@bdice](https://github.com/bdice) - Pass `AWS_SESSION_TOKEN` and `SCCACHE_S3_USE_SSL` vars to conda build ([#982](https://github.com/rapidsai/cuspatial/pull/982)) [@ajschmidt8](https://github.com/ajschmidt8) - Header-only `quadtree_point_in_polygon` ([#979](https://github.com/rapidsai/cuspatial/pull/979)) [@harrism](https://github.com/harrism) - Update aarch64 to GCC 11 ([#978](https://github.com/rapidsai/cuspatial/pull/978)) [@bdice](https://github.com/bdice) - Remove GDAL dependency in quadtree spatial join tests. ([#974](https://github.com/rapidsai/cuspatial/pull/974)) [@harrism](https://github.com/harrism) - Enable discussions ([#966](https://github.com/rapidsai/cuspatial/pull/966)) [@jarmak-nv](https://github.com/jarmak-nv) - Fix docs build to be `pydata-sphinx-theme=0.13.0` compatible ([#964](https://github.com/rapidsai/cuspatial/pull/964)) [@galipremsagar](https://github.com/galipremsagar) - Update `.gitignore` for `ops-codeowners` ([#963](https://github.com/rapidsai/cuspatial/pull/963)) [@ajschmidt8](https://github.com/ajschmidt8) - Update to GCC 11 ([#961](https://github.com/rapidsai/cuspatial/pull/961)) [@bdice](https://github.com/bdice) - Add cuspatial devcontainers ([#960](https://github.com/rapidsai/cuspatial/pull/960)) [@trxcllnt](https://github.com/trxcllnt) - Make docs builds less verbose ([#956](https://github.com/rapidsai/cuspatial/pull/956)) [@AyodeAwe](https://github.com/AyodeAwe) - Refactors API to accept GeoSeries input for projection and trajectory functions ([#955](https://github.com/rapidsai/cuspatial/pull/955)) [@isVoid](https://github.com/isVoid) - Update Notebook with GeoSeries Usage and Add Notebook Tests ([#953](https://github.com/rapidsai/cuspatial/pull/953)) [@isVoid](https://github.com/isVoid) - Refactor functions in `join.py` to accept GeoSeries Input ([#948](https://github.com/rapidsai/cuspatial/pull/948)) [@isVoid](https://github.com/isVoid) - Skip docs job in nightly runs ([#944](https://github.com/rapidsai/cuspatial/pull/944)) [@AyodeAwe](https://github.com/AyodeAwe) - Refactors `filtering.py`, `indexing.py` to Accept GeoSeries ([#938](https://github.com/rapidsai/cuspatial/pull/938)) [@isVoid](https://github.com/isVoid) - Refactors `bounding.py` to accept GeoSeries Input ([#934](https://github.com/rapidsai/cuspatial/pull/934)) [@isVoid](https://github.com/isVoid) - Remove dead code from ContainsProperlyBinpred paths. ([#933](https://github.com/rapidsai/cuspatial/pull/933)) [@thomcom](https://github.com/thomcom) - Refactor `directed_hausdorff_distance` and `haversine_distance` into `GeoSeries` Interface ([#924](https://github.com/rapidsai/cuspatial/pull/924)) [@isVoid](https://github.com/isVoid) - Reduce error handling verbosity in CI tests scripts ([#912](https://github.com/rapidsai/cuspatial/pull/912)) [@AjayThorve](https://github.com/AjayThorve) - Use quadtree for `.contains_properly` ([#910](https://github.com/rapidsai/cuspatial/pull/910)) [@thomcom](https://github.com/thomcom) - Update shared workflow branches ([#909](https://github.com/rapidsai/cuspatial/pull/909)) [@ajschmidt8](https://github.com/ajschmidt8) - Remove gpuCI scripts. ([#904](https://github.com/rapidsai/cuspatial/pull/904)) [@bdice](https://github.com/bdice) - Allow initialization of a `GeoDataFrame` using a `cudf.DataFrame` ([#895](https://github.com/rapidsai/cuspatial/pull/895)) [@thomcom](https://github.com/thomcom) - Move date to build string in `conda` recipe ([#882](https://github.com/rapidsai/cuspatial/pull/882)) [@ajschmidt8](https://github.com/ajschmidt8) - Add docs build job ([#868](https://github.com/rapidsai/cuspatial/pull/868)) [@AyodeAwe](https://github.com/AyodeAwe) # cuSpatial 23.02.00 (9 Feb 2023) ## 🚨 Breaking Changes - Deprecate shapefile reader ([#872](https://github.com/rapidsai/cuspatial/pull/872)) [@harrism](https://github.com/harrism) - Remove deprecated min_size parameter from quadtree_on_points ([#843](https://github.com/rapidsai/cuspatial/pull/843)) [@harrism](https://github.com/harrism) - Remove deprecated lonlat_to_cartesian functions ([#842](https://github.com/rapidsai/cuspatial/pull/842)) [@harrism](https://github.com/harrism) ## πŸ› Bug Fixes - pre-commit: Update isort version to 5.12.0 ([#877](https://github.com/rapidsai/cuspatial/pull/877)) [@wence-](https://github.com/wence-) - Use vector equivalence macros consistently in header-only API tests. ([#873](https://github.com/rapidsai/cuspatial/pull/873)) [@harrism](https://github.com/harrism) - Fix: Sort Intersection Result by Keys in `intersection_with_duplicate` Test ([#857](https://github.com/rapidsai/cuspatial/pull/857)) [@isVoid](https://github.com/isVoid) - Add `reset_index` to `GeoSeries` and `GeoDataFrame` ([#856](https://github.com/rapidsai/cuspatial/pull/856)) [@thomcom](https://github.com/thomcom) - Update `memory_usage` with tweaked sizes ([#855](https://github.com/rapidsai/cuspatial/pull/855)) [@thomcom](https://github.com/thomcom) - Fix a bug preventing `align` from working with a basic slice. ([#850](https://github.com/rapidsai/cuspatial/pull/850)) [@thomcom](https://github.com/thomcom) - Fix failed automerge Branch 23.02 merge 22.12 ([#811](https://github.com/rapidsai/cuspatial/pull/811)) [@harrism](https://github.com/harrism) ## πŸ“– Documentation - Fix documentation author ([#866](https://github.com/rapidsai/cuspatial/pull/866)) [@bdice](https://github.com/bdice) ## πŸš€ New Features - Deprecate shapefile reader ([#872](https://github.com/rapidsai/cuspatial/pull/872)) [@harrism](https://github.com/harrism) - Add Header Only API `pairwise_linestring_intersection` ([#852](https://github.com/rapidsai/cuspatial/pull/852)) [@isVoid](https://github.com/isVoid) - Adds `remove_if` Function to `linestring_intersection_intermediates` ([#851](https://github.com/rapidsai/cuspatial/pull/851)) [@isVoid](https://github.com/isVoid) - Add `find_point_on_segment` internal API ([#819](https://github.com/rapidsai/cuspatial/pull/819)) [@isVoid](https://github.com/isVoid) - Add `find_and_combine_segment` internal API ([#818](https://github.com/rapidsai/cuspatial/pull/818)) [@isVoid](https://github.com/isVoid) - Add `pairwise_linestring_intersection_with_duplicates` API ([#813](https://github.com/rapidsai/cuspatial/pull/813)) [@isVoid](https://github.com/isVoid) ## πŸ› οΈ Improvements - Update shared workflow branches ([#897](https://github.com/rapidsai/cuspatial/pull/897)) [@ajschmidt8](https://github.com/ajschmidt8) - Add print_env.sh to improve bug reporting ([#874](https://github.com/rapidsai/cuspatial/pull/874)) [@jarmak-nv](https://github.com/jarmak-nv) - Refactor calls to `data_array_view` ([#871](https://github.com/rapidsai/cuspatial/pull/871)) [@galipremsagar](https://github.com/galipremsagar) - Build CUDA 11.8 and Python 3.10 Packages ([#865](https://github.com/rapidsai/cuspatial/pull/865)) [@bdice](https://github.com/bdice) - Update workflows for nightly tests ([#864](https://github.com/rapidsai/cuspatial/pull/864)) [@ajschmidt8](https://github.com/ajschmidt8) - Enable `Recently Updated` Check ([#863](https://github.com/rapidsai/cuspatial/pull/863)) [@ajschmidt8](https://github.com/ajschmidt8) - Add header-only `cuspatial::join_quadtree_and_bounding_boxes` ([#861](https://github.com/rapidsai/cuspatial/pull/861)) [@trxcllnt](https://github.com/trxcllnt) - Remove deprecated min_size parameter from quadtree_on_points ([#843](https://github.com/rapidsai/cuspatial/pull/843)) [@harrism](https://github.com/harrism) - Remove deprecated lonlat_to_cartesian functions ([#842](https://github.com/rapidsai/cuspatial/pull/842)) [@harrism](https://github.com/harrism) - Use Libcudf Test Macro ([#841](https://github.com/rapidsai/cuspatial/pull/841)) [@isVoid](https://github.com/isVoid) - Add Missing License in `Distance.py` ([#840](https://github.com/rapidsai/cuspatial/pull/840)) [@isVoid](https://github.com/isVoid) - Enable copy_prs. ([#837](https://github.com/rapidsai/cuspatial/pull/837)) [@bdice](https://github.com/bdice) - Add GitHub Actions Workflows ([#836](https://github.com/rapidsai/cuspatial/pull/836)) [@bdice](https://github.com/bdice) - Implement all binary operations that depend only on point-in-polygon ([#834](https://github.com/rapidsai/cuspatial/pull/834)) [@thomcom](https://github.com/thomcom) - Header-only polygon_bounding_boxes and linestring_bounding_boxes, `make_geometry_id_iterator` utility, and `box&lt;T&gt;` class. ([#820](https://github.com/rapidsai/cuspatial/pull/820)) [@harrism](https://github.com/harrism) # cuSpatial 22.12.00 (8 Dec 2022) ## 🚨 Breaking Changes - Update quadtree spatial join docstrings ([#797](https://github.com/rapidsai/cuspatial/pull/797)) [@trxcllnt](https://github.com/trxcllnt) - Rename lonlat_to_cartesian to sinusoidal_projection ([#794](https://github.com/rapidsai/cuspatial/pull/794)) [@harrism](https://github.com/harrism) - Consolidate bounding box code ([#793](https://github.com/rapidsai/cuspatial/pull/793)) [@harrism](https://github.com/harrism) - Globally replace &quot;polyline&quot; with &quot;linestring&quot; ([#788](https://github.com/rapidsai/cuspatial/pull/788)) [@harrism](https://github.com/harrism) - Refactor of `pairwise_linestring_distance` to use `multilinestring_range`, adds support to multilinestring distance ([#755](https://github.com/rapidsai/cuspatial/pull/755)) [@isVoid](https://github.com/isVoid) - Introduce `multilinestring_range` structure, simplifies point-linestring distance API ([#747](https://github.com/rapidsai/cuspatial/pull/747)) [@isVoid](https://github.com/isVoid) - Add python bindings for (multi)point-(multi)point distance ([#734](https://github.com/rapidsai/cuspatial/pull/734)) [@isVoid](https://github.com/isVoid) - Introduce `multipoint_range` interface; Refactors `point_distance` API to support multipoint to multipoint distance. ([#731](https://github.com/rapidsai/cuspatial/pull/731)) [@isVoid](https://github.com/isVoid) ## πŸ› Bug Fixes - Add Floating Point Equality Tests to Build List ([#812](https://github.com/rapidsai/cuspatial/pull/812)) [@isVoid](https://github.com/isVoid) - Fix a Bug in Segment Intersection Primitive ([#808](https://github.com/rapidsai/cuspatial/pull/808)) [@isVoid](https://github.com/isVoid) - Don&#39;t use CMake 3.25.0 as it has a FindCUDAToolkit show stopping bug ([#805](https://github.com/rapidsai/cuspatial/pull/805)) [@robertmaynard](https://github.com/robertmaynard) - Fix style checks. ([#791](https://github.com/rapidsai/cuspatial/pull/791)) [@bdice](https://github.com/bdice) - Force using old fmt in nvbench. ([#783](https://github.com/rapidsai/cuspatial/pull/783)) [@isVoid](https://github.com/isVoid) - Fix issue with `.loc` returning values out of order. ([#782](https://github.com/rapidsai/cuspatial/pull/782)) [@thomcom](https://github.com/thomcom) - address issue with vector equivalent utility ([#777](https://github.com/rapidsai/cuspatial/pull/777)) [@isVoid](https://github.com/isVoid) ## πŸ“– Documentation - Add symlink to `users.ipynb` for notebooks CI ([#790](https://github.com/rapidsai/cuspatial/pull/790)) [@thomcom](https://github.com/thomcom) - Fix failed automerge (branch 22.12 merge 22.10) ([#740](https://github.com/rapidsai/cuspatial/pull/740)) [@harrism](https://github.com/harrism) ## πŸš€ New Features - Add `find_duplicate_points` Internal API ([#815](https://github.com/rapidsai/cuspatial/pull/815)) [@isVoid](https://github.com/isVoid) - Add Internal Function `intersection_count_upper_bound` ([#795](https://github.com/rapidsai/cuspatial/pull/795)) [@isVoid](https://github.com/isVoid) - Support `Multilinestring` in column API and python Bindings for `pairwise_linestring_distance` ([#786](https://github.com/rapidsai/cuspatial/pull/786)) [@isVoid](https://github.com/isVoid) - Introduce Segment Intersection Primitive ([#778](https://github.com/rapidsai/cuspatial/pull/778)) [@isVoid](https://github.com/isVoid) - Introduce ULP Based Floating Point Equality Test to Device Function ([#773](https://github.com/rapidsai/cuspatial/pull/773)) [@isVoid](https://github.com/isVoid) - Augment Cuspatial Test Utility to Allow User Specified Abs Error ([#752](https://github.com/rapidsai/cuspatial/pull/752)) [@isVoid](https://github.com/isVoid) - Create `pairwise_point_in_polygon` to be used by pairwise `GeoSeries` ([#750](https://github.com/rapidsai/cuspatial/pull/750)) [@thomcom](https://github.com/thomcom) - Replacing markdown issue templates with yml forms ([#748](https://github.com/rapidsai/cuspatial/pull/748)) [@jarmak-nv](https://github.com/jarmak-nv) - Introduce `multilinestring_range` structure, simplifies point-linestring distance API ([#747](https://github.com/rapidsai/cuspatial/pull/747)) [@isVoid](https://github.com/isVoid) - Add python bindings for (multi)point-(multi)point distance ([#734](https://github.com/rapidsai/cuspatial/pull/734)) [@isVoid](https://github.com/isVoid) - Introduce `multipoint_range` interface; Refactors `point_distance` API to support multipoint to multipoint distance. ([#731](https://github.com/rapidsai/cuspatial/pull/731)) [@isVoid](https://github.com/isVoid) ## πŸ› οΈ Improvements - Set max version pin for `gdal` ([#806](https://github.com/rapidsai/cuspatial/pull/806)) [@ajschmidt8](https://github.com/ajschmidt8) - Update Dependency List with `dependencies.yaml` ([#803](https://github.com/rapidsai/cuspatial/pull/803)) [@isVoid](https://github.com/isVoid) - Labeler: Change cpp label to libcuspatial ([#800](https://github.com/rapidsai/cuspatial/pull/800)) [@jarmak-nv](https://github.com/jarmak-nv) - Update pre-commit configuration and CI ([#799](https://github.com/rapidsai/cuspatial/pull/799)) [@bdice](https://github.com/bdice) - Update quadtree spatial join docstrings ([#797](https://github.com/rapidsai/cuspatial/pull/797)) [@trxcllnt](https://github.com/trxcllnt) - Rename lonlat_to_cartesian to sinusoidal_projection ([#794](https://github.com/rapidsai/cuspatial/pull/794)) [@harrism](https://github.com/harrism) - Consolidate bounding box code ([#793](https://github.com/rapidsai/cuspatial/pull/793)) [@harrism](https://github.com/harrism) - Globally replace &quot;polyline&quot; with &quot;linestring&quot; ([#788](https://github.com/rapidsai/cuspatial/pull/788)) [@harrism](https://github.com/harrism) - Fix conda channel order ([#787](https://github.com/rapidsai/cuspatial/pull/787)) [@harrism](https://github.com/harrism) - Delete deprecated board GitHub Actions ([#779](https://github.com/rapidsai/cuspatial/pull/779)) [@jarmak-nv](https://github.com/jarmak-nv) - Better slicing via `union_offsets` ([#776](https://github.com/rapidsai/cuspatial/pull/776)) [@thomcom](https://github.com/thomcom) - Header-only refactoring of trajectory_distances_and_speeds ([#769](https://github.com/rapidsai/cuspatial/pull/769)) [@harrism](https://github.com/harrism) - Allow None rows in `GeoSeries` and an `align` method to match `GeoPandas` ([#760](https://github.com/rapidsai/cuspatial/pull/760)) [@thomcom](https://github.com/thomcom) - Refactor of `pairwise_linestring_distance` to use `multilinestring_range`, adds support to multilinestring distance ([#755](https://github.com/rapidsai/cuspatial/pull/755)) [@isVoid](https://github.com/isVoid) - Remove stale labeler ([#751](https://github.com/rapidsai/cuspatial/pull/751)) [@raydouglass](https://github.com/raydouglass) - Create `GeoSeries.contains_properly` method using point_in_polygon. ([#749](https://github.com/rapidsai/cuspatial/pull/749)) [@thomcom](https://github.com/thomcom) - Header-only trajectory_bounding_boxes ([#741](https://github.com/rapidsai/cuspatial/pull/741)) [@harrism](https://github.com/harrism) - Update Conda Recipe and `README.md` ([#730](https://github.com/rapidsai/cuspatial/pull/730)) [@isVoid](https://github.com/isVoid) - Remove `cudf/cuda.cuh` Dependency ([#729](https://github.com/rapidsai/cuspatial/pull/729)) [@isVoid](https://github.com/isVoid) # cuSpatial 22.10.00 (12 Oct 2022) ## 🚨 Breaking Changes - Remove lonlat_2d and cartesian_2d types ([#662](https://github.com/rapidsai/cuspatial/pull/662)) [@harrism](https://github.com/harrism) - Add Multi-Geometry support to `point_linestring_distance` and build python bindings ([#660](https://github.com/rapidsai/cuspatial/pull/660)) [@isVoid](https://github.com/isVoid) - Decouple `interpolate` functions from trajectory ([#645](https://github.com/rapidsai/cuspatial/pull/645)) [@isVoid](https://github.com/isVoid) ## πŸ› Bug Fixes - Fix error in users.ipynb ([#726](https://github.com/rapidsai/cuspatial/pull/726)) [@thomcom](https://github.com/thomcom) - `unwrap_pyoptcol` is missing `except` keyword that causes exceptions ignored, fixes function bug ([#719](https://github.com/rapidsai/cuspatial/pull/719)) [@isVoid](https://github.com/isVoid) - Fix all unexecutable code examples I can find. ([#693](https://github.com/rapidsai/cuspatial/pull/693)) [@thomcom](https://github.com/thomcom) - Add Union-style indexing to `.points`, `.multipoints`, `.lines`, and `.polygons` `GeoSeries` accessors ([#685](https://github.com/rapidsai/cuspatial/pull/685)) [@thomcom](https://github.com/thomcom) - Rewrite `copy_type_metadata` to reuse the inherited method and handle geocolumns specifically. ([#684](https://github.com/rapidsai/cuspatial/pull/684)) [@isVoid](https://github.com/isVoid) - Fix `GeoDataframe` slicing issue by adding `_slice_` method. ([#680](https://github.com/rapidsai/cuspatial/pull/680)) [@thomcom](https://github.com/thomcom) - Fix and tidy coordinate_transform_test ([#671](https://github.com/rapidsai/cuspatial/pull/671)) [@harrism](https://github.com/harrism) - `linestring_distance` Header Only API Returns Past-the-End iterator ([#670](https://github.com/rapidsai/cuspatial/pull/670)) [@isVoid](https://github.com/isVoid) ## πŸ“– Documentation - Update link to c++ developer guide ([#718](https://github.com/rapidsai/cuspatial/pull/718)) [@isVoid](https://github.com/isVoid) - Add C++ doc links to `library_design.md` and minor documentation fixes ([#700](https://github.com/rapidsai/cuspatial/pull/700)) [@isVoid](https://github.com/isVoid) - Document that minimum required CMake version is now 3.23.1 ([#689](https://github.com/rapidsai/cuspatial/pull/689)) [@robertmaynard](https://github.com/robertmaynard) - Publish Developer Guide ([#673](https://github.com/rapidsai/cuspatial/pull/673)) [@harrism](https://github.com/harrism) - Add TESTING.md and BENCHMARKING.md ([#672](https://github.com/rapidsai/cuspatial/pull/672)) [@harrism](https://github.com/harrism) - Add DOCUMENTATION.md ([#667](https://github.com/rapidsai/cuspatial/pull/667)) [@harrism](https://github.com/harrism) - Branch 22.10 merge 22.08 ([#654](https://github.com/rapidsai/cuspatial/pull/654)) [@harrism](https://github.com/harrism) - Add Developer Guides, replace internal.md, CONTRIBUTING.md ([#625](https://github.com/rapidsai/cuspatial/pull/625)) [@isVoid](https://github.com/isVoid) - Add Markdown Parser to Sphinx ([#621](https://github.com/rapidsai/cuspatial/pull/621)) [@isVoid](https://github.com/isVoid) - Simplify PR template ([#617](https://github.com/rapidsai/cuspatial/pull/617)) [@harrism](https://github.com/harrism) - Add libcuspatial C++ developer guide. ([#606](https://github.com/rapidsai/cuspatial/pull/606)) [@harrism](https://github.com/harrism) ## πŸš€ New Features - Initialize a `GeoDataFrame` with `dict`. ([#712](https://github.com/rapidsai/cuspatial/pull/712)) [@thomcom](https://github.com/thomcom) - Vectorized Load, refactors `type_utils.hpp` into `iterator_factory.cuh` ([#692](https://github.com/rapidsai/cuspatial/pull/692)) [@isVoid](https://github.com/isVoid) - Accept `None` and python list in `GeoSeries` constructor ([#686](https://github.com/rapidsai/cuspatial/pull/686)) [@isVoid](https://github.com/isVoid) - Python API for point-linestring nearest points ([#681](https://github.com/rapidsai/cuspatial/pull/681)) [@isVoid](https://github.com/isVoid) - cuSpatial Python User Guide ([#666](https://github.com/rapidsai/cuspatial/pull/666)) [@thomcom](https://github.com/thomcom) - Add Multi-Geometry support to `point_linestring_distance` and build python bindings ([#660](https://github.com/rapidsai/cuspatial/pull/660)) [@isVoid](https://github.com/isVoid) - Add C++ API for `point_linestring_nearest_points` ([#658](https://github.com/rapidsai/cuspatial/pull/658)) [@isVoid](https://github.com/isVoid) - Auto-add new Issues and PRs to cuspatial&#39;s project ([#618](https://github.com/rapidsai/cuspatial/pull/618)) [@jarmak-nv](https://github.com/jarmak-nv) - Integrate `GeoSeries` with `read_polygon_shapefile` ([#609](https://github.com/rapidsai/cuspatial/pull/609)) [@thomcom](https://github.com/thomcom) - Memory_usage method for GeoSeries/GeoDataFrame and `GeoDataFrame` refactor. ([#604](https://github.com/rapidsai/cuspatial/pull/604)) [@thomcom](https://github.com/thomcom) - Add Point Linestring Distance ([#573](https://github.com/rapidsai/cuspatial/pull/573)) [@isVoid](https://github.com/isVoid) ## πŸ› οΈ Improvements - Update to the latest version 3 of GDAL. ([#675](https://github.com/rapidsai/cuspatial/pull/675)) [@thomcom](https://github.com/thomcom) - Expand expect_vector_equivalent to handle std::vector of vec_2d&lt;T&gt; and move traits out of detail ([#669](https://github.com/rapidsai/cuspatial/pull/669)) [@harrism](https://github.com/harrism) - Statically link all CUDA toolkit libraries ([#665](https://github.com/rapidsai/cuspatial/pull/665)) [@trxcllnt](https://github.com/trxcllnt) - Remove lonlat_2d and cartesian_2d types ([#662](https://github.com/rapidsai/cuspatial/pull/662)) [@harrism](https://github.com/harrism) - Rename Test Folders to Align with Module Names ([#661](https://github.com/rapidsai/cuspatial/pull/661)) [@isVoid](https://github.com/isVoid) - Move `GeoSeries` `GeoDataframe` into `core` package and hide column implementation in internal `_column` package ([#657](https://github.com/rapidsai/cuspatial/pull/657)) [@isVoid](https://github.com/isVoid) - Refactor spatial related functions under `spatial` package ([#656](https://github.com/rapidsai/cuspatial/pull/656)) [@isVoid](https://github.com/isVoid) - Add Missing Thrust Headers for Thrust 1.17 ([#655](https://github.com/rapidsai/cuspatial/pull/655)) [@isVoid](https://github.com/isVoid) - Decouple `interpolate` functions from trajectory ([#645](https://github.com/rapidsai/cuspatial/pull/645)) [@isVoid](https://github.com/isVoid) - Add header only `cuspatial::quadtree_on_points` ([#639](https://github.com/rapidsai/cuspatial/pull/639)) [@trxcllnt](https://github.com/trxcllnt) - Header-only refactoring of derive_trajectories ([#628](https://github.com/rapidsai/cuspatial/pull/628)) [@harrism](https://github.com/harrism) - Add python benchmarks. ([#600](https://github.com/rapidsai/cuspatial/pull/600)) [@thomcom](https://github.com/thomcom) - Fix compile error in distance benchmark ([#596](https://github.com/rapidsai/cuspatial/pull/596)) [@trxcllnt](https://github.com/trxcllnt) # cuSpatial 22.08.00 (17 Aug 2022) ## 🚨 Breaking Changes - Pairwise Point to Point Distance; Rename Folder `distances` to `distance` ([#558](https://github.com/rapidsai/cuspatial/pull/558)) [@isVoid](https://github.com/isVoid) ## πŸ› Bug Fixes - Fix Broken Link in NYC Taxi Notebook ([#616](https://github.com/rapidsai/cuspatial/pull/616)) [@isVoid](https://github.com/isVoid) - Add missing rmm includes ([#590](https://github.com/rapidsai/cuspatial/pull/590)) [@harrism](https://github.com/harrism) - Fix failed automerge 22.06 into 22.08 ([#562](https://github.com/rapidsai/cuspatial/pull/562)) [@harrism](https://github.com/harrism) - Bump cuspatial python version in scikit-build ([#550](https://github.com/rapidsai/cuspatial/pull/550)) [@isVoid](https://github.com/isVoid) ## πŸ“– Documentation - Defer loading of `custom.js` ([#631](https://github.com/rapidsai/cuspatial/pull/631)) [@galipremsagar](https://github.com/galipremsagar) - Use documented header template for `doxygen` ([#619](https://github.com/rapidsai/cuspatial/pull/619)) [@galipremsagar](https://github.com/galipremsagar) - Fix issues with day &amp; night modes in python docs ([#613](https://github.com/rapidsai/cuspatial/pull/613)) [@isVoid](https://github.com/isVoid) ## πŸš€ New Features - Add NVBench and linestring distance benchmark ([#577](https://github.com/rapidsai/cuspatial/pull/577)) [@isVoid](https://github.com/isVoid) - Pairwise Point to Point Distance; Rename Folder `distances` to `distance` ([#558](https://github.com/rapidsai/cuspatial/pull/558)) [@isVoid](https://github.com/isVoid) ## πŸ› οΈ Improvements - Bump `gdal` version ([#623](https://github.com/rapidsai/cuspatial/pull/623)) [@ajschmidt8](https://github.com/ajschmidt8) - Build benchmarks in CI ([#597](https://github.com/rapidsai/cuspatial/pull/597)) [@vyasr](https://github.com/vyasr) - Add benchmark for points_in_spatial_window ([#595](https://github.com/rapidsai/cuspatial/pull/595)) [@harrism](https://github.com/harrism) - Update isort to version 5.10.1 ([#589](https://github.com/rapidsai/cuspatial/pull/589)) [@vyasr](https://github.com/vyasr) - Header-only Refactor of `point_in_polygon` ([#587](https://github.com/rapidsai/cuspatial/pull/587)) [@isVoid](https://github.com/isVoid) - Remove GeoArrow glue code replacing gpu storage with cudf.Series and host storage with pyarrow ([#585](https://github.com/rapidsai/cuspatial/pull/585)) [@thomcom](https://github.com/thomcom) - Create `pygeoarrow` and use it for cuSpatial feature storage and i/o ([#583](https://github.com/rapidsai/cuspatial/pull/583)) [@thomcom](https://github.com/thomcom) - Header-only refactoring of `points_in_spatial_window` ([#579](https://github.com/rapidsai/cuspatial/pull/579)) [@harrism](https://github.com/harrism) - Update Python version support. ([#574](https://github.com/rapidsai/cuspatial/pull/574)) [@bdice](https://github.com/bdice) - Combine `device_atomics` ([#561](https://github.com/rapidsai/cuspatial/pull/561)) [@isVoid](https://github.com/isVoid) - Relocate Utility Files ([#560](https://github.com/rapidsai/cuspatial/pull/560)) [@isVoid](https://github.com/isVoid) - Fuse `transform` and `copy_if` operations in `quadtree_point_in_polygon` ([#559](https://github.com/rapidsai/cuspatial/pull/559)) [@trxcllnt](https://github.com/trxcllnt) - Remove `itstimestamp` and `types.hpp` ([#554](https://github.com/rapidsai/cuspatial/pull/554)) [@isVoid](https://github.com/isVoid) - Change build.sh to find C++ library by default and avoid shadowing CMAKE_ARGS ([#543](https://github.com/rapidsai/cuspatial/pull/543)) [@vyasr](https://github.com/vyasr) - Add missing Thrust includes ([#539](https://github.com/rapidsai/cuspatial/pull/539)) [@bdice](https://github.com/bdice) - Refactor Hausdorff distance to header-only API ([#538](https://github.com/rapidsai/cuspatial/pull/538)) [@harrism](https://github.com/harrism) # cuSpatial 22.06.00 (7 Jun 2022) ## πŸ› Bug Fixes - Fix out of bounds access in spline interpolation ([#544](https://github.com/rapidsai/cuspatial/pull/544)) [@vyasr](https://github.com/vyasr) - Fix `libcuspatial` recipe dependencies ([#513](https://github.com/rapidsai/cuspatial/pull/513)) [@ajschmidt8](https://github.com/ajschmidt8) ## πŸ“– Documentation - Add Doxygen Documentation for `libcuspatial` ([#534](https://github.com/rapidsai/cuspatial/pull/534)) [@isVoid](https://github.com/isVoid) - add units to haversine distance docstring ([#522](https://github.com/rapidsai/cuspatial/pull/522)) [@bandersen23](https://github.com/bandersen23) - Merge branch-22.04 into branch-22.06 ([#518](https://github.com/rapidsai/cuspatial/pull/518)) [@harrism](https://github.com/harrism) ## πŸš€ New Features - Refactor `linestring_distance` to header only API ([#526](https://github.com/rapidsai/cuspatial/pull/526)) [@isVoid](https://github.com/isVoid) - Python Bindings for Pairwise Linestring Distance ([#521](https://github.com/rapidsai/cuspatial/pull/521)) [@isVoid](https://github.com/isVoid) - Refactor lonlat_to_cartesian to header-only API ([#514](https://github.com/rapidsai/cuspatial/pull/514)) [@harrism](https://github.com/harrism) - C++ pairwise linestring distance ([#510](https://github.com/rapidsai/cuspatial/pull/510)) [@isVoid](https://github.com/isVoid) ## πŸ› οΈ Improvements - Fix library directory for installation ([#537](https://github.com/rapidsai/cuspatial/pull/537)) [@vyasr](https://github.com/vyasr) - Fix conda recipes ([#532](https://github.com/rapidsai/cuspatial/pull/532)) [@Ethyling](https://github.com/Ethyling) - Fix various issues with CMake exports ([#527](https://github.com/rapidsai/cuspatial/pull/527)) [@vyasr](https://github.com/vyasr) - Build cuspatial with scikit-build ([#524](https://github.com/rapidsai/cuspatial/pull/524)) [@vyasr](https://github.com/vyasr) - Update Documentation with Pydata Sphinx Theme, and more ([#523](https://github.com/rapidsai/cuspatial/pull/523)) [@isVoid](https://github.com/isVoid) - Use conda to build python packages during GPU tests ([#517](https://github.com/rapidsai/cuspatial/pull/517)) [@Ethyling](https://github.com/Ethyling) - Replace `CUDA_TRY` with `CUSPATIAL_CUDA_TRY` ([#516](https://github.com/rapidsai/cuspatial/pull/516)) [@isVoid](https://github.com/isVoid) - Use rapids-cmake for builds ([#515](https://github.com/rapidsai/cuspatial/pull/515)) [@vyasr](https://github.com/vyasr) - Update black to 22.3.0, update usage of libcudf macros, and remove direct column indexing ([#511](https://github.com/rapidsai/cuspatial/pull/511)) [@charlesbluca](https://github.com/charlesbluca) - Enable building static libs ([#506](https://github.com/rapidsai/cuspatial/pull/506)) [@trxcllnt](https://github.com/trxcllnt) - Add clang-format to pre-commit hook ([#505](https://github.com/rapidsai/cuspatial/pull/505)) [@isVoid](https://github.com/isVoid) - Add libcuspatial-tests package ([#499](https://github.com/rapidsai/cuspatial/pull/499)) [@Ethyling](https://github.com/Ethyling) - Use conda compilers ([#495](https://github.com/rapidsai/cuspatial/pull/495)) [@Ethyling](https://github.com/Ethyling) - Build packages using mambabuild ([#486](https://github.com/rapidsai/cuspatial/pull/486)) [@Ethyling](https://github.com/Ethyling) - Refactor haversine_distance to a header-only API ([#477](https://github.com/rapidsai/cuspatial/pull/477)) [@harrism](https://github.com/harrism) # cuSpatial 22.04.00 (6 Apr 2022) ## πŸ› Bug Fixes - Swap NumericalColumn.values_host for now removed to_array ([#485](https://github.com/rapidsai/cuspatial/pull/485)) [@vyasr](https://github.com/vyasr) ## πŸ“– Documentation - Improve point_in_polygon documentation regarding poly_ring_offsets ([#497](https://github.com/rapidsai/cuspatial/pull/497)) [@harrism](https://github.com/harrism) - Fix documentation of return type of quadtree_point_in_polygon ([#490](https://github.com/rapidsai/cuspatial/pull/490)) [@harrism](https://github.com/harrism) ## πŸ› οΈ Improvements - Temporarily disable new `ops-bot` functionality ([#501](https://github.com/rapidsai/cuspatial/pull/501)) [@ajschmidt8](https://github.com/ajschmidt8) - Pin gtest/gmock to 1.10.0 in dev envs ([#498](https://github.com/rapidsai/cuspatial/pull/498)) [@trxcllnt](https://github.com/trxcllnt) - Add `.github/ops-bot.yaml` config file ([#496](https://github.com/rapidsai/cuspatial/pull/496)) [@ajschmidt8](https://github.com/ajschmidt8) - Add CMake `install` rule for tests ([#488](https://github.com/rapidsai/cuspatial/pull/488)) [@ajschmidt8](https://github.com/ajschmidt8) - replace `ccache` with `sccache` ([#483](https://github.com/rapidsai/cuspatial/pull/483)) [@AyodeAwe](https://github.com/AyodeAwe) # cuSpatial 22.02.00 (2 Feb 2022) ## πŸ› Bug Fixes - Always upload cuspatial packages ([#481](https://github.com/rapidsai/cuspatial/pull/481)) [@raydouglass](https://github.com/raydouglass) - Remove use of libcudf&#39;s CUDA_HOST_DEVICE macro ([#475](https://github.com/rapidsai/cuspatial/pull/475)) [@harrism](https://github.com/harrism) ## πŸ› οΈ Improvements - Prepare upload scripts for Python 3.7 removal ([#479](https://github.com/rapidsai/cuspatial/pull/479)) [@Ethyling](https://github.com/Ethyling) - Fix `test_pip_bitmap_column_to_binary_array` test ([#472](https://github.com/rapidsai/cuspatial/pull/472)) [@Ethyling](https://github.com/Ethyling) - Fix imports tests syntax ([#471](https://github.com/rapidsai/cuspatial/pull/471)) [@Ethyling](https://github.com/Ethyling) - Remove `IncludeCategories` from `.clang-format` ([#470](https://github.com/rapidsai/cuspatial/pull/470)) [@codereport](https://github.com/codereport) - Fix Forward-Merge Conflicts in #464 ([#466](https://github.com/rapidsai/cuspatial/pull/466)) [@ajschmidt8](https://github.com/ajschmidt8) # cuSpatial 21.12.00 (9 Dec 2021) ## πŸ› Bug Fixes - Remove use of now removed cudf Table object. ([#455](https://github.com/rapidsai/cuspatial/pull/455)) [@vyasr](https://github.com/vyasr) ## πŸ› οΈ Improvements - Update DEFAULT_CUDA_VER in ci/cpu/prebuild.sh ([#468](https://github.com/rapidsai/cuspatial/pull/468)) [@Ethyling](https://github.com/Ethyling) - Fix Changelog Merge Conflicts for `branch-21.12` ([#467](https://github.com/rapidsai/cuspatial/pull/467)) [@ajschmidt8](https://github.com/ajschmidt8) - Upgrade `clang` to `11.1.0` ([#463](https://github.com/rapidsai/cuspatial/pull/463)) [@galipremsagar](https://github.com/galipremsagar) - NVCC warnings are errors ([#458](https://github.com/rapidsai/cuspatial/pull/458)) [@trxcllnt](https://github.com/trxcllnt) - Update `conda` recipes for Enhanced Compatibility effort ([#457](https://github.com/rapidsai/cuspatial/pull/457)) [@ajschmidt8](https://github.com/ajschmidt8) # cuSpatial 21.10.00 (7 Oct 2021) ## πŸ› Bug Fixes - Stop using now removed _apply_support_method function. ([#448](https://github.com/rapidsai/cuspatial/pull/448)) [@vyasr](https://github.com/vyasr) - Remove cudf.core ([#444](https://github.com/rapidsai/cuspatial/pull/444)) [@thomcom](https://github.com/thomcom) - FIX Sync version update script with CMakeLists and update version in … ([#438](https://github.com/rapidsai/cuspatial/pull/438)) [@dillon-cullinan](https://github.com/dillon-cullinan) ## πŸ› οΈ Improvements - Fix default cuda version in prebuild.sh for arm64 ([#451](https://github.com/rapidsai/cuspatial/pull/451)) [@Ethyling](https://github.com/Ethyling) - Skip imports tests on arm64 ([#450](https://github.com/rapidsai/cuspatial/pull/450)) [@Ethyling](https://github.com/Ethyling) - Update Cython Table APIs to match changes in cudf. ([#449](https://github.com/rapidsai/cuspatial/pull/449)) [@vyasr](https://github.com/vyasr) - Fix Forward-Merge Conflicts ([#445](https://github.com/rapidsai/cuspatial/pull/445)) [@ajschmidt8](https://github.com/ajschmidt8) - Update cudf table apis ([#437](https://github.com/rapidsai/cuspatial/pull/437)) [@vyasr](https://github.com/vyasr) - ENH Replace gpuci_conda_retry with gpuci_mamba_retry ([#432](https://github.com/rapidsai/cuspatial/pull/432)) [@dillon-cullinan](https://github.com/dillon-cullinan) - Pin gdal to 3.3.x ([#420](https://github.com/rapidsai/cuspatial/pull/420)) [@weiji14](https://github.com/weiji14) # cuSpatial 21.08.00 (4 Aug 2021) ## πŸ› Bug Fixes - Fix usage of assert_columns* APIs. ([#433](https://github.com/rapidsai/cuspatial/pull/433)) [@vyasr](https://github.com/vyasr) - Switch to using public cudf testing utilities ([#431](https://github.com/rapidsai/cuspatial/pull/431)) [@vyasr](https://github.com/vyasr) - Update CMake, fix testing use of assert_eq, and correct metadata copying ([#430](https://github.com/rapidsai/cuspatial/pull/430)) [@vyasr](https://github.com/vyasr) - Improve Hausdorff perf and accept larger number of inputs. ([#424](https://github.com/rapidsai/cuspatial/pull/424)) [@cwharris](https://github.com/cwharris) - Fix a critical issue with `parallel_search` functor. ([#405](https://github.com/rapidsai/cuspatial/pull/405)) [@thomcom](https://github.com/thomcom) ## πŸ› οΈ Improvements - Updating Clang Version to 11.0.0 ([#426](https://github.com/rapidsai/cuspatial/pull/426)) [@codereport](https://github.com/codereport) - Update sphinx config ([#421](https://github.com/rapidsai/cuspatial/pull/421)) [@ajschmidt8](https://github.com/ajschmidt8) - Bump isort, enable Cython package resorting ([#419](https://github.com/rapidsai/cuspatial/pull/419)) [@charlesbluca](https://github.com/charlesbluca) - Fix `21.08` forward-merge conflicts ([#418](https://github.com/rapidsai/cuspatial/pull/418)) [@ajschmidt8](https://github.com/ajschmidt8) - Correct the docs example for `cuspatial.CubicSpline` ([#411](https://github.com/rapidsai/cuspatial/pull/411)) [@thomcom](https://github.com/thomcom) - Update version to 21.08.00 in cmakelists ([#410](https://github.com/rapidsai/cuspatial/pull/410)) [@harrism](https://github.com/harrism) - Fix merge conflicts ([#408](https://github.com/rapidsai/cuspatial/pull/408)) [@ajschmidt8](https://github.com/ajschmidt8) - Support spaces in build.sh paths ([#385](https://github.com/rapidsai/cuspatial/pull/385)) [@jolorunyomi](https://github.com/jolorunyomi) # cuSpatial 21.06.00 (9 Jun 2021) ## πŸš€ New Features - `from_geopandas` converts GeoPandas GeoSeries objects into cuspatial GeoArrow form. ([#300](https://github.com/rapidsai/cuspatial/pull/300)) [@thomcom](https://github.com/thomcom) ## πŸ› οΈ Improvements - Update environment variable used to determine `cuda_version` ([#407](https://github.com/rapidsai/cuspatial/pull/407)) [@ajschmidt8](https://github.com/ajschmidt8) - Update `CHANGELOG.md` links for calver ([#404](https://github.com/rapidsai/cuspatial/pull/404)) [@ajschmidt8](https://github.com/ajschmidt8) - Move rmm::device_buffer instead of copying ([#403](https://github.com/rapidsai/cuspatial/pull/403)) [@harrism](https://github.com/harrism) - Update docs build script ([#402](https://github.com/rapidsai/cuspatial/pull/402)) [@ajschmidt8](https://github.com/ajschmidt8) - Update cuspatial version for calver, fix CMake FindPackage cudf ([#401](https://github.com/rapidsai/cuspatial/pull/401)) [@trxcllnt](https://github.com/trxcllnt) - Improve performance of quadtree point-to-polyline join ([#362](https://github.com/rapidsai/cuspatial/pull/362)) [@trxcllnt](https://github.com/trxcllnt) # cuSpatial 0.19.0 (21 Apr 2021) ## πŸ› Bug Fixes - Revert &quot;Update conda recipes pinning of repo dependencies&quot; ([#372](https://github.com//rapidsai/cuspatial/pull/372)) [@raydouglass](https://github.com/raydouglass) - Update conda recipes pinning of repo dependencies ([#370](https://github.com//rapidsai/cuspatial/pull/370)) [@mike-wendt](https://github.com/mike-wendt) - Rename cartesian_product_group_index_iterator_test.cpp to .cu ([#369](https://github.com//rapidsai/cuspatial/pull/369)) [@trxcllnt](https://github.com/trxcllnt) ## πŸš€ New Features - Auto-label PRs based on their content ([#337](https://github.com//rapidsai/cuspatial/pull/337)) [@jolorunyomi](https://github.com/jolorunyomi) ## πŸ› οΈ Improvements - Set `install_rpath` for libcuspatial ([#375](https://github.com//rapidsai/cuspatial/pull/375)) [@trxcllnt](https://github.com/trxcllnt) - ENH Reduce cuspatial library size ([#373](https://github.com//rapidsai/cuspatial/pull/373)) [@dillon-cullinan](https://github.com/dillon-cullinan) - Eliminate literals passed to device_uvector::set_element_async ([#367](https://github.com//rapidsai/cuspatial/pull/367)) [@harrism](https://github.com/harrism) - Update Changelog Link ([#366](https://github.com//rapidsai/cuspatial/pull/366)) [@ajschmidt8](https://github.com/ajschmidt8) - Rework libcuspatial CMakeLists.txt to export targets for CPM ([#365](https://github.com//rapidsai/cuspatial/pull/365)) [@trxcllnt](https://github.com/trxcllnt) - Prepare Changelog for Automation ([#364](https://github.com//rapidsai/cuspatial/pull/364)) [@ajschmidt8](https://github.com/ajschmidt8) - Update 0.18 changelog entry ([#363](https://github.com//rapidsai/cuspatial/pull/363)) [@ajschmidt8](https://github.com/ajschmidt8) - ENH Build with `cmake --build` &amp; Pass ccache variables to conda recipe &amp; use Ninja in CI ([#359](https://github.com//rapidsai/cuspatial/pull/359)) [@Ethyling](https://github.com/Ethyling) - Update make_counting_transform_iterator namespace in tests ([#353](https://github.com//rapidsai/cuspatial/pull/353)) [@trxcllnt](https://github.com/trxcllnt) - Fix merge conflicts in #348 ([#349](https://github.com//rapidsai/cuspatial/pull/349)) [@ajschmidt8](https://github.com/ajschmidt8) - Pin gdal to 3.2.x ([#347](https://github.com//rapidsai/cuspatial/pull/347)) [@weiji14](https://github.com/weiji14) # cuSpatial 0.18.0 (24 Feb 2021) ## Documentation πŸ“– - Fix directed_hausdorff_distance space_offsets name + documentation (#332) @cwharris ## New Features πŸš€ - New build process script changes &amp; gpuCI enhancements (#338) @raydouglass ## Improvements πŸ› οΈ - Update stale GHA with exemptions &amp; new labels (#357) @mike-wendt - Add GHA to mark issues/prs as stale/rotten (#355) @Ethyling - Prepare Changelog for Automation (#345) @ajschmidt8 - Pin gdal to 3.1.x (#339) @weiji14 - Use simplified `rmm::exec_policy` (#331) @harrism - Upgrade to libcu++ on GitHub (#297) @trxcllnt # cuSpatial 0.17.0 (10 Dec 2020) ## New Features ## Improvements - PR #310 Pin cmake policies to cmake 3.17 version - PR #321 Improvements to gpuCI scripts - PR #325 Convert `cudaStream_t` to `rmm::cuda_stream_view` ## Bug Fixes - PR #320 Fix quadtree construction bug: zero out `device_uvector` before `scatter` - PR #328 Fix point in polygon test for cudf::gather breaking change # cuSpatial 0.16.0 (21 Oct 2020) ## New Features - PR #290 Add Java bindings and a cuSpatial JAR package for Java users. ## Improvements - PR #278 Update googlebenchmark version to match rmm & cudf. - PR #286 Upgrade Thrust to latest commit. - PR #287 Replace RMM get_default_resource with get_current_device_resource. - PR #289 Fix cmake warnings for GoogleTest amd GoogleBenchmark external projects. - PR #292 Update include paths to libcudf test utilities. - PR #295 Use move from libcpp.utility. - PR #299 Update ci/local/README.md - PR #303 Update yml files to include CUDA 11.0 and remove old supported versions ## Bug Fixes - PR #291 Fix mislabeled columns in Python spatial join result table. - PR #294 Fix include of deprecated RMM header file. - PR #296 Updates for RMM being header only. - PR #298 Fix Python docs to render first argument of each public function. - PR #322 Fix build issues related to libcudf split build changes - PR #323 Add cuda to target_link_libraries # cuSpatial 0.15.0 (26 Aug 2020) ## New Features - PR #146 quadtree-polygon pairing for spatial filtering - PR #149 Add quadtree-based point-in-polygon and point-to-nearest-polyline ## Improvements - PR #237 Remove nvstrings references from CMakeLists.txt. - PR #239 Add docs build script. - PR #238 Fix library and include paths in CMakeLists.txt and setup.py. - PR #240 Remove deprecated RMM header references. - PR #243 Install dependencies via meta package. - PR #247 Use rmm::device_uvector and cudf::UINT types for quadtree construction. - PR #246 Hausdorff performance improvement. - PR #253 Update conda upload versions for new supported CUDA/Python. - PR #250 Cartesian product iterator + more Hausdorff performance improvements. - PR #260 Replace RMM `cnmem_memory_resource` with `pool_memory_resource` in benchmark fixture. - PR #264 Rename `quad_bbox_join` to `join_quadtree_and_bounding_boxes`. - PR #268 Fix cudf timestamp construction. - PR #267 Fix branch-0.15 conda dev environment dependencies ## Bug Fixes - PR #244 Restrict gdal version. - PR #245 Pin gdal to be compatible with cuxfilter. - PR #242 Fix benchmark_fixture to use memory resources. - PR #248 Fix build by updating type_id usages after upstream breaking changes. - PR #252 Fix CI style check failures. - PR #254 Fix issue with incorrect docker image being used in local build script. - PR #258 Fix compiler errors from cudf's new duration types. - PR #281 Patch Thrust to workaround `CUDA_CUB_RET_IF_FAIL` macro clearing CUDA errors # cuSpatial 0.14.0 (03 Jun 2020) ## New Features - PR #143 Support constructing quadtrees on point data - PR #182 Local gpuCI build script - PR #145 Support computing polygon and polyline bounding boxes - PR #208 NYC Taxi Years Correlation Notebook (thanks @taureandyernv) ## Improvements - PR #147 Update Conda/CMake configs to match other RAPIDS projects - PR #163 Fix cudf legacy Cython imports/cimports - PR #166 Move trajectory.hpp files to legacy - PR #167 Align utility.hpp with libcudf style - PR #171 Update trajectory.hpp to libcudf++ - PR #173 Move hausdorff.hpp files to legacy - PR #172 Move coordinate_transform.hpp files to legacy - PR #170 Update coordinate_transform.hpp to libcudf++ - PR #174 Update hausdorff.hpp to libcudf++ - PR #183 Add libcuspatial benchmark scaffolding - PR #186 Move haversine.hpp files to legacy - PR #194 Add .clang-format & format all files - PR #190 Port coordinate_transform.hpp cython files - PR #191 Move point_in_polygon.hpp files to legacy - PR #193 Move shapefile_readers.hpp files to legacy - PR #196 Move utilities/utilities.hpp to legacy - PR #195 Fix PIP docs - PR #197 Move query.hpp files to legacy - PR #198 Port spatial_window queries to libcudf++ - PR #192 Update point_in_polygon.hpp to libcudf++ - PR #201 Update trajectory cython to libcudf++ - PR #189 Update haversine.hpp files to libcudf++ - PR #200 Update shapefile_readers.hpp to libcudf++ - PR #203 Port point_in_polygon.hpp cython files - PR #202 Update haversine cython to libcudf++ - PR #204 Port shapefile_readers.hpp cython files - PR #205 Port hausdorff.hpp cython to libcudf++ - PR #206 Remove legacy code. - PR #214 Install gdal>=3.0.2 in build.sh - PR #222 Fix potential thrust launch failure in quadtree building - PR #221 Add python methods to api.rst, fix formatting - PR #225 Add short git commit to conda package - PR #228 Fix polygon and polyline docstrings ## Bug Fixes - PR #141 Fix dangling exec_policy pointer and invalid num_ring argument. - PR #169 Fix shapefile reader compilation with GCC 7.x / CUDA 10.2 - PR #178 Fix broken haversine tests introduced by upstream CUDF PRs. - PR #175 Address RMM API changes by eliminating the use of the RMM_API - PR #199 Fix coordinate transform tests - PR #212 Rename calls to cudf::experimental namespace to cudf:: - PR #215 Replace legacy RMM calls - PR #218 Fix benchmark build by removing test_benchmark.cpp - PR #232 Fix conda dependencies # cuSpatial 0.13.0 (31 Mar 2020) ## New Features - PR #126 Create and build cuSpatial Docs - PR #130 Add cubic spline fit and interpolation ## Improvements - PR #128 Use RMM's `DeviceBuffer` for Python allocations - PR #142 Disable deprecation warnings by default - PR #138 Update Build instructions in the README ## Bug Fixes - PR #123 Update references to error utils after libcudf changes - PR #136 Remove build erroring for deprecation warnings # cuSpatial 0.12.0 (04 Feb 2020) ## New Features ## Improvements - PR #109 Update OPS codeowners group name - PR #113 Support libcudf++ ## Bug Fixes - PR #116 Fix API issue with shapefile reader # cuSpatial 0.11.0 (11 Dec 2019) ## New Features - PR #86 Add Shapefile reader for polygons - PR #92 Python bindings for shapefile reader ## Improvements - PR #104 Remove unused CUDA conda labels ## Bug Fixes - PR #94 Add legacy headers as cudf migrates - PR #98 Updates to accommodate cudf refactoring - PR #103 Update the include paths for cuda_utils # cuSpatial 0.10.0 (16 Oct 2019) ## New Features - PR #7 Initial code - PR #18 Python initial unit tests and bindings - PR #32 Python API first pass - PR #37 Python __init__.py package design - PR #38 Add __init__.py empties to resolve issue with PYTHONPATH - PR #25 Add gpuCI integration ## Improvements - PR #31 Add Github CODEOWNERS - PR #39 Add cython headers to install, python / cmake packaging cleanup - PR #41 Python and Cython style cleanup, pre-commit hook - PR #44 Update all demos with Python API - PR #45 Improve documentation in haversine and point in polygon - PR #50 Validate that distance and speed work with all datetimes - PR #58 Hausdorff distance returns a DataFrame, and better docs. - PR #61 Point-in-polygon DataFrame output - PR #59 Improve detail of point in polygon docs - PR #64 Use YYMMDD tag in nightly build - PR #68 Use YYMMDD tag in nightly build of cuspatial python - PR #97 Drop `cython` from run requirements - PR #82 Added update-version.sh - PR #86 Add Shapefile reader for polygons ## Bug Fixes - PR #16 `cuspatial::subset_trajectory_id()` test improvements and bug fixes - PR #17 Update issue / PR templates - PR #23 Fix cudf Cython imports - PR #24 `cuspatial::derive_trajectories()` test improvements and bug fixes - PR #33 `cuspatial::trajectory_distance_and_speed()` test improvements and bug fixes - PR #49 Docstring for haversine and argument ordering was backwards - PR #66 added missing header in tests - PR #70 Require width parameterization of bitmap to binary conversion
0
rapidsai_public_repos
rapidsai_public_repos/cuspatial/build.sh
#!/bin/bash # Copyright (c) 2019, NVIDIA CORPORATION. # cuSpatial build script # This script is used to build the component(s) in this repo from # source, and can be called with various options to customize the # build as needed (see the help output for details) # Abort script on first error set -e NUMARGS=$# ARGS=$* # NOTE: ensure all dir changes are relative to the location of this # script, and that this script resides in the repo dir! REPODIR=$(cd $(dirname $0); pwd) VALIDARGS="clean libcuspatial cuspatial cuproj tests benchmarks -v -g -n -h --allgpuarch --show_depr_warn" HELP="$0 [clean] [libcuspatial] [cuspatial] [tests] [-v] [-g] [-n] [-h] [-l] [--show_depr_warn] [--cmake-args=\"<args>\"] clean - remove all existing build artifacts and configuration (start over) libcuspatial - build the libcuspatial C++ code only cuspatial - build the cuspatial Python package cuproj - build the cuproj Python package tests - build tests benchmarks - build benchmarks -v - verbose build mode -g - build for debug -n - no install step (does not affect Python) -h - print this text --allgpuarch - build for all supported GPU architectures --show_depr_warn - show cmake deprecation warnings --cmake-args=\\\"<args>\\\" - pass arbitrary list of CMake configuration options (escape all quotes in argument) default action (no args) is to build and install 'libcuspatial' then 'cuspatial' targets " LIBCUSPATIAL_BUILD_DIR=${REPODIR}/cpp/build LIBCUPROJ_BUILD_DIR=${REPODIR}/cpp/build/cuproj CUSPATIAL_BUILD_DIR=${REPODIR}/python/cuspatial/_skbuild CUPROJ_BUILD_DIR=${REPODIR}/python/cuproj/_skbuild BUILD_DIRS="${LIBCUSPATIAL_BUILD_DIR} ${CUSPATIAL_BUILD_DIR} ${LIBCUPROJ_BUILD_DIR} ${CUPROJ_BUILD_DIR}" # Set defaults for vars modified by flags to this script VERBOSE_FLAG="" BUILD_TESTS=OFF BUILD_BENCHMARKS=OFF BUILD_TYPE=Release BUILD_ALL_GPU_ARCH=0 INSTALL_TARGET=install BUILD_DISABLE_DEPRECATION_WARNING=ON # Set defaults for vars that may not have been defined externally # FIXME: if INSTALL_PREFIX is not set, check PREFIX, then check # CONDA_PREFIX, but there is no fallback from there! INSTALL_PREFIX=${INSTALL_PREFIX:=${PREFIX:=${CONDA_PREFIX}}} PARALLEL_LEVEL=${PARALLEL_LEVEL:=""} function hasArg { (( ${NUMARGS} != 0 )) && (echo " ${ARGS} " | grep -q " $1 ") } function cmakeArgs { # Check for multiple cmake args options if [[ $(echo $ARGS | { grep -Eo "\-\-cmake\-args" || true; } | wc -l ) -gt 1 ]]; then echo "Multiple --cmake-args options were provided, please provide only one: ${ARGS}" exit 1 fi # Check for cmake args option if [[ -n $(echo $ARGS | { grep -E "\-\-cmake\-args" || true; } ) ]]; then # There are possible weird edge cases that may cause this regex filter to output nothing and fail silently # the true pipe will catch any weird edge cases that may happen and will cause the program to fall back # on the invalid option error EXTRA_CMAKE_ARGS=$(echo $ARGS | { grep -Eo "\-\-cmake\-args=\".+\"" || true; }) if [[ -n ${EXTRA_CMAKE_ARGS} ]]; then # Remove the full EXTRA_CMAKE_ARGS argument from list of args so that it passes validArgs function ARGS=${ARGS//$EXTRA_CMAKE_ARGS/} # Filter the full argument down to just the extra string that will be added to cmake call EXTRA_CMAKE_ARGS=$(echo $EXTRA_CMAKE_ARGS | grep -Eo "\".+\"" | sed -e 's/^"//' -e 's/"$//') fi fi } if hasArg -h; then echo "${HELP}" exit 0 fi # Check for valid usage if (( ${NUMARGS} != 0 )); then cmakeArgs for a in ${ARGS}; do if ! (echo " ${VALIDARGS} " | grep -q " ${a} "); then echo "Invalid option: ${a}" exit 1 fi done fi # Process flags if hasArg -v; then VERBOSE_FLAG="-v" fi if hasArg -g; then BUILD_TYPE=Debug fi if hasArg -n; then INSTALL_TARGET="" fi if hasArg --allgpuarch; then BUILD_ALL_GPU_ARCH=1 fi if hasArg --show_depr_warn; then BUILD_DISABLE_DEPRECATION_WARNING=OFF fi if hasArg tests; then BUILD_TESTS=ON fi if hasArg benchmarks; then BUILD_BENCHMARKS=ON fi # Append `-DFIND_CUSPATIAL_CPP=ON` to EXTRA_CMAKE_ARGS unless a user specified the option. if [[ "${EXTRA_CMAKE_ARGS}" != *"DFIND_CUSPATIAL_CPP"* ]]; then EXTRA_CMAKE_ARGS="${EXTRA_CMAKE_ARGS} -DFIND_CUSPATIAL_CPP=ON" fi # Append `-DFIND_CUPROJ_CPP=ON` to EXTRA_CMAKE_ARGS unless a user specified the option. if [[ "${EXTRA_CMAKE_ARGS}" != *"DFIND_CUPROJ_CPP"* ]]; then EXTRA_CMAKE_ARGS="${EXTRA_CMAKE_ARGS} -DFIND_CUPROJ_CPP=ON" fi # If clean given, run it prior to any other steps if hasArg clean; then # If the dirs to clean are mounted dirs in a container, the # contents should be removed but the mounted dirs will remain. # The find removes all contents but leaves the dirs, the rmdir # attempts to remove the dirs but can fail safely. for bd in ${BUILD_DIRS}; do if [ -d ${bd} ]; then find ${bd} -mindepth 1 -delete rmdir ${bd} || true fi done fi if (( ${BUILD_ALL_GPU_ARCH} == 0 )); then CUSPATIAL_CMAKE_CUDA_ARCHITECTURES="-DCMAKE_CUDA_ARCHITECTURES=NATIVE" echo "Building for the architecture of the GPU in the system..." else CUSPATIAL_CMAKE_CUDA_ARCHITECTURES="-DCMAKE_CUDA_ARCHITECTURES=RAPIDS" echo "Building for *ALL* supported GPU architectures..." fi ################################################################################ # Configure, build, and install libcuspatial if (( ${NUMARGS} == 0 )) || hasArg libcuspatial; then mkdir -p ${LIBCUSPATIAL_BUILD_DIR} cd ${LIBCUSPATIAL_BUILD_DIR} cmake -DCMAKE_INSTALL_PREFIX=${INSTALL_PREFIX} \ ${CUSPATIAL_CMAKE_CUDA_ARCHITECTURES} \ -DCMAKE_CXX11_ABI=ON \ -DBUILD_TESTS=${BUILD_TESTS} \ -DBUILD_BENCHMARKS=${BUILD_BENCHMARKS} \ -DDISABLE_DEPRECATION_WARNING=${BUILD_DISABLE_DEPRECATION_WARNING} \ -DCMAKE_BUILD_TYPE=${BUILD_TYPE} \ ${EXTRA_CMAKE_ARGS} \ .. cmake --build . -j ${PARALLEL_LEVEL} ${VERBOSE_FLAG} if [[ ${INSTALL_TARGET} != "" ]]; then cmake --build . -j ${PARALLEL_LEVEL} --target install ${VERBOSE_FLAG} fi fi # Build and install the cuspatial Python package if (( ${NUMARGS} == 0 )) || hasArg cuspatial; then cd ${REPODIR}/python/cuspatial SKBUILD_CONFIGURE_OPTIONS="-DCMAKE_PREFIX_PATH=${INSTALL_PREFIX} -DCMAKE_LIBRARY_PATH=${LIBCUSPATIAL_BUILD_DIR} ${EXTRA_CMAKE_ARGS}" \ SKBUILD_BUILD_OPTIONS="-j${PARALLEL_LEVEL:-1}" \ python -m pip install --no-build-isolation --no-deps . fi # Build and install the cuproj Python package if (( ${NUMARGS} == 0 )) || hasArg cuproj; then cd ${REPODIR}/python/cuproj SKBUILD_CONFIGURE_OPTIONS="-DCMAKE_PREFIX_PATH=${INSTALL_PREFIX} -DCMAKE_LIBRARY_PATH=${LIBCUPROJ_BUILD_DIR} ${EXTRA_CMAKE_ARGS}" \ SKBUILD_BUILD_OPTIONS="-j${PARALLEL_LEVEL:-1}" \ python -m pip install --no-build-isolation --no-deps . fi
0
rapidsai_public_repos
rapidsai_public_repos/cuspatial/dependencies.yaml
# Dependency list for https://github.com/rapidsai/dependency-file-generator files: all: output: conda matrix: cuda: ["11.8", "12.0"] arch: [x86_64] includes: - build_cpp - build_python - cudatoolkit - develop - docs - py_version - depends_on_rmm - depends_on_cudf - depends_on_cuml - depends_on_cupy - run_python_cuspatial - test_python_cuspatial - test_python_cuproj - notebooks test_cpp: output: none includes: - cudatoolkit test_python: output: none includes: - cudatoolkit - py_version - test_python_cuspatial - test_python_cuproj test_notebooks: output: none includes: - cudatoolkit - depends_on_cuml - notebooks - py_version checks: output: none includes: - develop - py_version docs: output: none includes: - cudatoolkit - docs - py_version py_build_cuspatial: output: [pyproject] pyproject_dir: python/cuspatial extras: table: build-system includes: - depends_on_rmm - depends_on_cudf - build_cpp - build_python - build_wheels py_run_cuspatial: output: [pyproject] pyproject_dir: python/cuspatial extras: table: project includes: - depends_on_rmm - depends_on_cudf - run_python_cuspatial py_test_cuspatial: output: [pyproject] pyproject_dir: python/cuspatial extras: table: project.optional-dependencies key: test includes: - test_python_cuspatial py_build_cuproj: output: [pyproject] pyproject_dir: python/cuproj extras: table: build-system includes: - depends_on_rmm - build_cpp_cuproj - build_python_cuproj - build_wheels py_run_cuproj: output: [pyproject] pyproject_dir: python/cuproj extras: table: project includes: - depends_on_rmm - depends_on_cupy py_test_cuproj: output: [pyproject] pyproject_dir: python/cuproj extras: table: project.optional-dependencies key: test includes: - test_python_cuproj - depends_on_cuspatial channels: - rapidsai - rapidsai-nightly - conda-forge - nvidia dependencies: build_cpp: common: - output_types: [conda, requirements, pyproject] packages: - ninja - cmake>=3.26.4 - output_types: conda packages: - c-compiler - cxx-compiler - gmock>=1.13.0 - gtest>=1.13.0 - libcudf==23.12.* - librmm==23.12.* - proj - sqlite specific: - output_types: conda matrices: - matrix: arch: x86_64 packages: - &gcc_amd64 gcc_linux-64=11.* - &sysroot_amd64 sysroot_linux-64==2.17 - matrix: arch: aarch64 packages: - &gcc_aarch64 gcc_linux-aarch64=11.* - &sysroot_aarch64 sysroot_linux-aarch64==2.17 - output_types: conda matrices: - matrix: arch: x86_64 cuda: "11.8" packages: - nvcc_linux-64=11.8 - matrix: arch: aarch64 cuda: "11.8" packages: - nvcc_linux-aarch64=11.8 - matrix: cuda: "12.0" packages: - cuda-version=12.0 - cuda-nvcc build_cpp_cuproj: common: - output_types: [conda, requirements, pyproject] packages: - ninja - cmake>=3.26.4 - output_types: conda packages: - c-compiler - cxx-compiler - gmock>=1.13.0 - gtest>=1.13.0 - librmm==23.12.* - proj - sqlite specific: - output_types: conda matrices: - matrix: arch: x86_64 packages: - *gcc_amd64 - *sysroot_amd64 - matrix: arch: aarch64 packages: - *gcc_aarch64 - *sysroot_aarch64 - output_types: conda matrices: - matrix: arch: x86_64 cuda: "11.8" packages: - nvcc_linux-64=11.8 - matrix: arch: aarch64 cuda: "11.8" packages: - nvcc_linux-aarch64=11.8 - matrix: cuda: "12.0" packages: - cuda-version=12.0 - cuda-nvcc build_python: common: - output_types: [conda, requirements, pyproject] packages: - cython>=3.0.0 - scikit-build>=0.13.1 - setuptools specific: - output_types: conda matrices: - matrix: arch: x86_64 packages: - *gcc_amd64 - *sysroot_amd64 - matrix: arch: aarch64 packages: - *gcc_aarch64 - *sysroot_aarch64 build_python_cuproj: common: - output_types: [conda, requirements, pyproject] packages: - cython>=3.0.0 - scikit-build>=0.13.1 - setuptools specific: - output_types: conda matrices: - matrix: arch: x86_64 packages: - *gcc_amd64 - *sysroot_amd64 - matrix: arch: aarch64 packages: - *gcc_aarch64 - *sysroot_aarch64 build_wheels: common: - output_types: [requirements, pyproject] packages: - wheel - setuptools cudatoolkit: specific: - output_types: conda matrices: - matrix: cuda: "12.0" packages: - cuda-version=12.0 - cuda-cudart-dev - cuda-nvrtc-dev - cuda-cupti-dev - matrix: cuda: "11.8" packages: - cuda-version=11.8 - cudatoolkit - matrix: cuda: "11.5" packages: - cuda-version=11.5 - cudatoolkit - matrix: cuda: "11.4" packages: - cuda-version=11.4 - cudatoolkit - matrix: cuda: "11.2" packages: - cuda-version=11.2 - cudatoolkit develop: common: - output_types: [conda, requirements] packages: - pre-commit - output_types: conda packages: - clang-tools=16.0.6 docs: common: - output_types: [conda] packages: - doxygen - output_types: [conda, requirements] packages: - ipython - myst-parser - nbsphinx - numpydoc # https://github.com/pydata/pydata-sphinx-theme/issues/1539 - pydata-sphinx-theme!=0.14.2 - sphinx<6 notebooks: common: - output_types: [conda, requirements, pyproject] packages: - ipython - ipywidgets - notebook - pydeck - shapely - scikit-image - output_types: [requirements, pyproject] packages: - pyproj>=3.6.0,<3.7a0 - output_types: [conda] packages: - curl py_version: specific: - output_types: conda matrices: - matrix: py: "3.9" packages: - python=3.9 - matrix: py: "3.10" packages: - python=3.10 - matrix: packages: - python>=3.9,<3.11 run_python_cuspatial: common: - output_types: [conda, requirements, pyproject] packages: - geopandas>=0.11.0 test_python_cuspatial: common: - output_types: [conda, requirements, pyproject] packages: - pytest - pytest-cov - pytest-xdist test_python_cuproj: common: - output_types: [conda, requirements, pyproject] packages: - pytest - pytest-cov - pytest-xdist - geopandas>=0.11.0 - output_types: [requirements, pyproject] packages: - pyproj>=3.6.0,<3.7a0 depends_on_rmm: common: - output_types: conda packages: - &rmm_conda rmm==23.12.* - output_types: requirements packages: # pip recognizes the index as a global option for the requirements.txt file - --extra-index-url=https://pypi.nvidia.com specific: - output_types: [requirements, pyproject] matrices: - matrix: {cuda: "12.2"} packages: &rmm_packages_pip_cu12 - rmm-cu12==23.12.* - {matrix: {cuda: "12.1"}, packages: *rmm_packages_pip_cu12} - {matrix: {cuda: "12.0"}, packages: *rmm_packages_pip_cu12} - matrix: {cuda: "11.8"} packages: &rmm_packages_pip_cu11 - rmm-cu11==23.12.* - {matrix: {cuda: "11.5"}, packages: *rmm_packages_pip_cu11} - {matrix: {cuda: "11.4"}, packages: *rmm_packages_pip_cu11} - {matrix: {cuda: "11.2"}, packages: *rmm_packages_pip_cu11} - {matrix: null, packages: [*rmm_conda]} depends_on_cudf: common: - output_types: conda packages: - &cudf_conda cudf==23.12.* - output_types: requirements packages: # pip recognizes the index as a global option for the requirements.txt file - --extra-index-url=https://pypi.nvidia.com specific: - output_types: [requirements, pyproject] matrices: - matrix: {cuda: "12.2"} packages: &cudf_packages_pip_cu12 - cudf-cu12==23.12.* - {matrix: {cuda: "12.1"}, packages: *cudf_packages_pip_cu12} - {matrix: {cuda: "12.0"}, packages: *cudf_packages_pip_cu12} - matrix: {cuda: "11.8"} packages: &cudf_packages_pip_cu11 - cudf-cu11==23.12.* - {matrix: {cuda: "11.5"}, packages: *cudf_packages_pip_cu11} - {matrix: {cuda: "11.4"}, packages: *cudf_packages_pip_cu11} - {matrix: {cuda: "11.2"}, packages: *cudf_packages_pip_cu11} - {matrix: null, packages: [*cudf_conda]} depends_on_cuml: common: - output_types: conda packages: - &cuml_conda cuml==23.12.* - output_types: requirements packages: # pip recognizes the index as a global option for the requirements.txt file - --extra-index-url=https://pypi.nvidia.com specific: - output_types: [requirements, pyproject] matrices: - matrix: {cuda: "12.2"} packages: &cuml_packages_pip_cu12 - cuml-cu12==23.12.* - {matrix: {cuda: "12.1"}, packages: *cuml_packages_pip_cu12} - {matrix: {cuda: "12.0"}, packages: *cuml_packages_pip_cu12} - matrix: {cuda: "11.8"} packages: &cuml_packages_pip_cu11 - cuml-cu11==23.12.* - {matrix: {cuda: "11.5"}, packages: *cuml_packages_pip_cu11} - {matrix: {cuda: "11.4"}, packages: *cuml_packages_pip_cu11} - {matrix: {cuda: "11.2"}, packages: *cuml_packages_pip_cu11} - {matrix: null, packages: [*cuml_conda]} depends_on_cuspatial: common: - output_types: conda packages: - &cuspatial_conda cuspatial==23.12.* - output_types: requirements packages: # pip recognizes the index as a global option for the requirements.txt file - --extra-index-url=https://pypi.nvidia.com specific: - output_types: [requirements, pyproject] matrices: - matrix: {cuda: "12.2"} packages: &cuspatial_packages_pip_cu12 - cuspatial-cu12==23.12.* - {matrix: {cuda: "12.1"}, packages: *cuspatial_packages_pip_cu12} - {matrix: {cuda: "12.0"}, packages: *cuspatial_packages_pip_cu12} - matrix: {cuda: "11.8"} packages: &cuspatial_packages_pip_cu11 - cuspatial-cu11==23.12.* - {matrix: {cuda: "11.5"}, packages: *cuspatial_packages_pip_cu11} - {matrix: {cuda: "11.4"}, packages: *cuspatial_packages_pip_cu11} - {matrix: {cuda: "11.2"}, packages: *cuspatial_packages_pip_cu11} - {matrix: null, packages: [*cuspatial_conda]} depends_on_cupy: common: - output_types: conda packages: - cupy>=12.0.0 specific: - output_types: [requirements, pyproject] matrices: # All CUDA 12 + x86_64 versions - matrix: {cuda: "12.2", arch: x86_64} packages: &cupy_packages_cu12_x86_64 - cupy-cuda12x>=12.0.0 - {matrix: {cuda: "12.1", arch: x86_64}, packages: *cupy_packages_cu12_x86_64} - {matrix: {cuda: "12.0", arch: x86_64}, packages: *cupy_packages_cu12_x86_64} # All CUDA 12 + aarch64 versions - matrix: {cuda: "12.2", arch: aarch64} packages: &cupy_packages_cu12_aarch64 - cupy-cuda12x -f https://pip.cupy.dev/aarch64 # TODO: Verify that this works. - {matrix: {cuda: "12.1", arch: aarch64}, packages: *cupy_packages_cu12_aarch64} - {matrix: {cuda: "12.0", arch: aarch64}, packages: *cupy_packages_cu12_aarch64} # All CUDA 11 + x86_64 versions - matrix: {cuda: "11.8", arch: x86_64} packages: &cupy_packages_cu11_x86_64 - cupy-cuda11x>=12.0.0 - {matrix: {cuda: "11.5", arch: x86_64}, packages: *cupy_packages_cu11_x86_64} - {matrix: {cuda: "11.4", arch: x86_64}, packages: *cupy_packages_cu11_x86_64} - {matrix: {cuda: "11.2", arch: x86_64}, packages: *cupy_packages_cu11_x86_64} # All CUDA 11 + aarch64 versions - matrix: {cuda: "11.8", arch: aarch64} packages: &cupy_packages_cu11_aarch64 - cupy-cuda11x -f https://pip.cupy.dev/aarch64 # TODO: Verify that this works. - {matrix: {cuda: "11.5", arch: aarch64}, packages: *cupy_packages_cu11_aarch64} - {matrix: {cuda: "11.4", arch: aarch64}, packages: *cupy_packages_cu11_aarch64} - {matrix: {cuda: "11.2", arch: aarch64}, packages: *cupy_packages_cu11_aarch64} - {matrix: null, packages: [cupy-cuda11x>=12.0.0]}
0
rapidsai_public_repos
rapidsai_public_repos/cuspatial/CONTRIBUTING.md
# Contributing to cuSpatial See [cuspatial contributing guide](https://docs.rapids.ai/api/cuspatial/nightly/developer_guide/contributing_guide.html)
0
rapidsai_public_repos
rapidsai_public_repos/cuspatial/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2019 NVIDIA Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
0
rapidsai_public_repos
rapidsai_public_repos/cuspatial/VERSION
23.12.00
0
rapidsai_public_repos
rapidsai_public_repos/cuspatial/print_env.sh
#!/usr/bin/env bash # Copyright (c) 2022, NVIDIA CORPORATION. # Reports relevant environment information useful for diagnosing and # debugging cuSpatial issues. # Usage: # "./print_env.sh" - prints to stdout # "./print_env.sh > env.txt" - prints to file "env.txt" print_env() { echo "**git***" if [ "$(git rev-parse --is-inside-work-tree 2>/dev/null)" == "true" ]; then git log --decorate -n 1 echo "**git submodules***" git submodule status --recursive else echo "Not inside a git repository" fi echo echo "***OS Information***" cat /etc/*-release uname -a echo echo "***GPU Information***" nvidia-smi echo echo "***CPU***" lscpu echo echo "***CMake***" which cmake && cmake --version echo echo "***g++***" which g++ && g++ --version echo echo "***nvcc***" which nvcc && nvcc --version echo echo "***Python***" which python && python -c "import sys; print('Python {0}.{1}.{2}'.format(sys.version_info[0], sys.version_info[1], sys.version_info[2]))" echo echo "***Environment Variables***" printf '%-32s: %s\n' PATH $PATH printf '%-32s: %s\n' LD_LIBRARY_PATH $LD_LIBRARY_PATH printf '%-32s: %s\n' NUMBAPRO_NVVM $NUMBAPRO_NVVM printf '%-32s: %s\n' NUMBAPRO_LIBDEVICE $NUMBAPRO_LIBDEVICE printf '%-32s: %s\n' CONDA_PREFIX $CONDA_PREFIX printf '%-32s: %s\n' PYTHON_PATH $PYTHON_PATH echo # Print conda packages if conda exists if type "conda" &> /dev/null; then echo '***conda packages***' which conda && conda list echo # Print pip packages if pip exists elif type "pip" &> /dev/null; then echo "conda not found" echo "***pip packages***" which pip && pip list echo else echo "conda not found" echo "pip not found" fi } echo "<details><summary>Click here to see environment details</summary><pre>" echo " " print_env | while read -r line; do echo " $line" done echo "</pre></details>"
0
rapidsai_public_repos/cuspatial/python
rapidsai_public_repos/cuspatial/python/cuproj/pyproject.toml
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. [build-system] build-backend = "setuptools.build_meta" requires = [ "cmake>=3.26.4", "cython>=3.0.0", "ninja", "rmm==23.12.*", "scikit-build>=0.13.1", "setuptools", "wheel", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. [project] name = "cuproj" dynamic = ["version"] description = "cuProj: GPU-Accelerated Coordinate Projection" readme = { file = "README.md", content-type = "text/markdown" } authors = [{ name = "NVIDIA Corporation" }] license = { text = "Apache 2.0" } requires-python = ">=3.9" dependencies = [ "cupy-cuda11x>=12.0.0", "rmm==23.12.*", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. classifiers = [ "Intended Audience :: Developers", "Topic :: Database", "Topic :: Scientific/Engineering", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", ] [project.optional-dependencies] test = [ "cuspatial==23.12.*", "geopandas>=0.11.0", "pyproj>=3.6.0,<3.7a0", "pytest", "pytest-cov", "pytest-xdist", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. [project.urls] Homepage = "https://github.com/rapidsai/cuspatial/python/cuproj" Documentation = "https://docs.rapids.ai/api/cuproj/stable/" [tool.setuptools] license-files = ["LICENSE"] [tool.setuptools.dynamic] version = {file = "cuproj/VERSION"} [tool.isort] line_length = 79 multi_line_output = 3 include_trailing_comma = true force_grid_wrap = 0 combine_as_imports = true order_by_type = true known_dask = ["dask", "distributed", "dask_cuda"] known_rapids = ["rmm", "cudf"] known_first_party = ["cuspatial", "cuproj"] default_section = "THIRDPARTY" sections = [ "FUTURE", "STDLIB", "THIRDPARTY", "DASK", "RAPIDS", "FIRSTPARTY", "LOCALFOLDER", ] skip = [ "thirdparty", ".eggs", ".git", ".hg", ".mypy_cache", ".tox", ".venv", "_build", "buck-out", "build", "dist", "__init__.py", ]
0
rapidsai_public_repos/cuspatial/python
rapidsai_public_repos/cuspatial/python/cuproj/CMakeLists.txt
# ============================================================================= # Copyright (c) 2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and limitations under # the License. # ============================================================================= cmake_minimum_required(VERSION 3.26.4 FATAL_ERROR) set(cuproj_version 23.12.00) include(../../fetch_rapids.cmake) include(rapids-cuda) rapids_cuda_init_architectures(cuproj-python) project( cuproj-python VERSION ${cuproj_version} LANGUAGES # TODO: Building Python extension modules via the python_extension_module requires the C # language to be enabled here. The test project that is built in scikit-build to verify # various linking options for the python library is hardcoded to build with C, so until # that is fixed we need to keep C. C CXX CUDA) option(FIND_CUPROJ_CPP "Search for existing cuproj C++ installations before defaulting to local files" OFF) option(CUPROJ_BUILD_WHEELS "Whether this build is generating a Python wheel." OFF) # If the user requested it we attempt to find cuproj. if(FIND_CUPROJ_CPP) find_package(cuproj ${cuproj_version}) else() set(cuproj_FOUND OFF) endif() if(NOT cuproj_FOUND) set(BUILD_TESTS OFF) set(BUILD_BENCHMARKS OFF) set(_exclude_from_all "") if(CUPROJ_BUILD_WHEELS) # Statically link cudart if building wheels set(CUDA_STATIC_RUNTIME ON) # Need to set this so all the cuproj targets are global, not only cuproj::cuproj # https://cmake.org/cmake/help/latest/variable/CMAKE_FIND_PACKAGE_TARGETS_GLOBAL.html#variable:CMAKE_FIND_PACKAGE_TARGETS_GLOBAL set(CMAKE_FIND_PACKAGE_TARGETS_GLOBAL ON) # Don't install the cuProj C++ targets into wheels set(_exclude_from_all EXCLUDE_FROM_ALL) endif() add_subdirectory(../../cpp/cuproj cuproj-cpp ${_exclude_from_all}) set(cython_lib_dir cuproj) if(CUPROJ_BUILD_WHEELS) include(../cuspatial/cmake/Modules/WheelHelpers.cmake) endif() # Since there are multiple subpackages of cuproj._lib that require access to libcuspatial, we place the # library in the cuproj directory as a single source of truth and modify the other rpaths # appropriately. install(TARGETS cuproj DESTINATION ${cython_lib_dir}) endif() add_subdirectory(cuproj/cuprojshim) include(rapids-cython) rapids_cython_init() add_subdirectory(cuproj/_lib) if(DEFINED cython_lib_dir) rapids_cython_add_rpath_entries(TARGET cuproj PATHS "${cython_lib_dir}") endif()
0
rapidsai_public_repos/cuspatial/python
rapidsai_public_repos/cuspatial/python/cuproj/README.md
# <div align="left"><img src="https://rapids.ai/assets/images/rapids_logo.png" width="90px"/>&nbsp;cuProj: GPU-Accelerated Coordinate Projection</div> > **Note** > > cuProj depends on [RMM](https://github.com/rapidsai/rmm) from [RAPIDS](https://rapids.ai/). ## Resources - [cuProj User's Guide](https://docs.rapids.ai/api/cuproj/stable/user_guide/cuproj_api_examples.html): Python API reference and guides - [cuProj Developer Documentation](https://docs.rapids.ai/api/cuproj/stable/developer_guide/index.html): Understand cuProj's architecture - [Getting Started](https://docs.rapids.ai/install): Instructions for installing cuSpatial/cuProj - [cuProj/cuSpatial Community](https://github.com/rapidsai/cuspatial/discussions): Get help, collaborate, and ask the team questions - [cuProj Issues](https://github.com/rapidsai/cuspatial/issues/new/choose): Request a feature/documentation or report a bug (file issues in cuSpatial repo). ## Overview cuProj is a library and Python package for accelerated geographic and geodetic coordinate transformations. cuProj can transform billions of geospatial coordinates per second from one coordinate reference system (CRS) to another on GPUs. This includes cartographic projections as well as geodetic transformations. cuProj is implemented in CUDA C++ to run on GPUs to provide the highest performance. cuProj provides a Python API that closely matches the [PyProj](https://pyproj4.github.io/pyproj/stable/) API, as well as a header-only C++ API. While the C++ API does not match the API of [Proj](https://proj.org/), it is designed to eventually expand to support many of the same features and transformations that Proj supports. Currently cuProj only supports a subset of the Proj transformations. The following transformations are supported: - WGS84 (EPSG: 4326) to/from any of the 60 UTM zone transformations (EPSG: 32601-32660, 32701-32760). ## Example The Python API is closely matched to PyProj and data can seamlessly transition between the two: ```python import cuproj import pyproj # Create a PyProj transformer pyproj_transformer = pyproj.Transformer.from_crs("EPSG:4326", "EPSG:32613") # Create a cuProj transformer cuproj_transformer = cuproj.Transformer.from_crs("EPSG:4326", "EPSG:32613") # Transform a grid of points around the San Francisco Bay using PyProj num_points = 10000 grid_side = int(np.sqrt(num_points)) x, y = np.meshgrid(np.linspace(min_corner[0], max_corner[0], grid_side), np.linspace(min_corner[1], max_corner[1], grid_side)) grid = [x.reshape(-1), y.reshape(-1)] pyproj_result = pyproj_transformer.transform(*grid) # Transform a grid of points around the San Francisco Bay using cuProj cuproj_result = cuproj_transformer.transform(*grid) ``` Note that the cuProj transformer is created from the same CRSs as the PyProj transformer. The transformer can then be used to transform a grid of points. The result of the transformation is returned as a tuple of x and y coordinates. The result of the PyProj transformation is a tuple of Numpy arrays, while the result of the cuProj transformation is a tuple of [CuPy](https://cupy.dev/) arrays. Also note that in the above example, the input data are in host memory, so cuProj will create a copy in device memory first. Data already on the device will not be copied, resulting in higher performance. See the [simple cuProj Benchmark notebook](../../notebooks/simple_cuproj_benchmark.ipynb) for an example.
0
rapidsai_public_repos/cuspatial/python
rapidsai_public_repos/cuspatial/python/cuproj/setup.py
# Copyright (c) 2018-2023, NVIDIA CORPORATION. from setuptools import find_packages from skbuild import setup packages = find_packages(include=["cuproj*"]) setup( packages=packages, package_data={ key: ["VERSION", "*.pxd", "*.hpp", "*.cuh"] for key in packages }, zip_safe=False, )
0
rapidsai_public_repos/cuspatial/python
rapidsai_public_repos/cuspatial/python/cuproj/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2019 NVIDIA Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
0
rapidsai_public_repos/cuspatial/python
rapidsai_public_repos/cuspatial/python/cuproj/.coveragerc
# Configuration file for Python coverage tests [run] source = cuproj
0
rapidsai_public_repos/cuspatial/python/cuproj
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/transformer.py
import cupy as cp from cuproj._lib.transform import Transformer as _Transformer class Transformer: """A transformer object to transform coordinates from one CRS to another. Notes ----- Currently only the EPSG authority is supported. Currently only projection from WGS84 to UTM (and vice versa) is supported. Examples -------- >>> from cuproj import Transformer >>> transformer = Transformer.from_crs("epsg:4326", "epsg:32631") >>> transformer.transform(2, 49) (500000.0, 5460836.5) >>> transformer.transform(500000, 5460836.5, direction="INVERSE") (2.0, 49.0) """ def __init__(self, crs_from, crs_to): """Construct a Transformer object. Parameters ---------- from_crs : CRS The source CRS. to_crs : CRS The target CRS. Source and target CRS may be: - An authority string [i.e. 'epsg:4326'] - An EPSG integer code [i.e. 4326] - A tuple of (β€œauth_name”: β€œauth_code”) [i.e ('epsg', '4326')] Notes ----- Currently only the EPSG authority is supported. Examples -------- >>> from cuproj import Transformer >>> transformer = Transformer("epsg:4326", "epsg:32631") >>> transformer = Transformer(4326, 32631) """ self._crs_from = crs_from self._crs_to = crs_to self._proj = _Transformer(crs_from, crs_to) @staticmethod def from_crs(crs_from, crs_to): """Create a transformer from a source CRS to a target CRS. Parameters ---------- crs_from : CRS The source CRS. crs_to : CRS The target CRS. Source and target CRS may be: - An authority string [i.e. 'epsg:4326'] - An EPSG integer code [i.e. 4326] - A tuple of (β€œauth_name”: β€œauth_code”) [i.e ('epsg', '4326')] Notes ----- Currently only the EPSG authority is supported. Returns ------- Transformer A transformer object to transform coordinates from one CRS to another. """ return Transformer(crs_from, crs_to) def transform(self, x, y, direction="FORWARD"): """Transform coordinates from one CRS to another. If the input data is already in device memory, and the input implements `__cuda_array_interface__ <https://numba.readthedocs.io/en/stable/cuda/cuda_array_interface.html>`_ , the data will be used directly. If the data is in host memory, it will be copied to the device. Parameters ---------- x : float or array_like The x coordinate(s) to transform. y : float or array_like The y coordinate(s) to transform. direction : str, optional The direction of the transformation. Either "FORWARD" or "INVERSE". Default is "FORWARD". Returns ------- tuple A tuple of transformed x and y coordinates as cupy (device) arrays. """ if direction not in ("FORWARD", "INVERSE"): raise ValueError(f"Invalid direction: {direction}") isfloat = False if isinstance(x, float) and isinstance(y, float): isfloat = True x = cp.asarray([x], dtype='f8') y = cp.asarray([y], dtype='f8') else: x = cp.asarray(x, x.dtype) y = cp.asarray(y, y.dtype) resx, resy = self._proj.transform(x, y, direction) if isfloat: resx, resy = resx.get()[0], resy.get()[0] return resx, resy
0
rapidsai_public_repos/cuspatial/python/cuproj
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/_version.py
# Copyright (c) 2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import importlib.resources __version__ = ( importlib.resources.files("cuproj").joinpath("VERSION").read_text().strip() ) __git_commit__ = ""
0
rapidsai_public_repos/cuspatial/python/cuproj
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. from ._version import __git_commit__, __version__ from .transformer import Transformer
0
rapidsai_public_repos/cuspatial/python/cuproj
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/VERSION
23.12.00
0
rapidsai_public_repos/cuspatial/python/cuproj/cuproj
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/cuprojshim/CMakeLists.txt
# ============================================================================= # Copyright (c) 2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and limitations under # the License. # ============================================================================= cmake_minimum_required(VERSION 3.26.4 FATAL_ERROR) set(cuproj_version 23.12.00) include(../../../../fetch_rapids.cmake) include(rapids-cmake) include(rapids-cpm) include(rapids-cuda) include(rapids-find) rapids_cuda_init_architectures(CUPROJSHIM) project( CUPROJSHIM VERSION ${cuproj_version} LANGUAGES CXX CUDA) ################################################################################################### # - build options --------------------------------------------------------------------------------- option(USE_NVTX "Build with NVTX support" ON) option(PER_THREAD_DEFAULT_STREAM "Build with per-thread default stream" OFF) option(DISABLE_DEPRECATION_WARNING "Disable warnings generated from deprecated declarations." OFF) # Option to enable line info in CUDA device compilation to allow introspection when profiling / memchecking option(CUDA_ENABLE_LINEINFO "Enable the -lineinfo option for nvcc (useful for cuda-memcheck / profiler" OFF) # cudart can be statically linked or dynamically linked. The python ecosystem wants dynamic linking option(CUDA_STATIC_RUNTIME "Statically link the CUDA toolkit runtime and libraries" OFF) message(STATUS "CUPROJSHIM: Build with NVTX support: ${USE_NVTX}") message(STATUS "CUPROJSHIM: Build with per-thread default stream: ${PER_THREAD_DEFAULT_STREAM}") message(STATUS "CUPROJSHIM: Disable warnings generated from deprecated declarations: ${DISABLE_DEPRECATION_WARNING}") message(STATUS "CUPROJSHIM: Enable the -lineinfo option for nvcc (useful for cuda-memcheck / profiler: ${CUDA_ENABLE_LINEINFO}") message(STATUS "CUPROJSHIM: Statically link the CUDA toolkit runtime and libraries: ${CUDA_STATIC_RUNTIME}") rapids_cmake_build_type("Release") set(CUPROJSHIM_CXX_FLAGS "") set(CUPROJSHIM_CUDA_FLAGS "") set(CUPROJSHIM_CXX_DEFINITIONS "") set(CUPROJSHIM_CUDA_DEFINITIONS "") # Set RMM logging level set(RMM_LOGGING_LEVEL "INFO" CACHE STRING "Choose the logging level.") set_property(CACHE RMM_LOGGING_LEVEL PROPERTY STRINGS "TRACE" "DEBUG" "INFO" "WARN" "ERROR" "CRITICAL" "OFF") message(STATUS "CUPROJSHIM: RMM_LOGGING_LEVEL = '${RMM_LOGGING_LEVEL}'.") ################################################################################################### # - conda environment ----------------------------------------------------------------------------- rapids_cmake_support_conda_env(conda_env MODIFY_PREFIX_PATH) ################################################################################################### # - compiler options ------------------------------------------------------------------------------ rapids_cuda_init_runtime(USE_STATIC ${CUDA_STATIC_RUNTIME}) rapids_find_package( CUDAToolkit REQUIRED BUILD_EXPORT_SET cuprojshim-exports INSTALL_EXPORT_SET cuprojshim-exports ) # * find CUDAToolkit package # * determine GPU architectures # * enable the CMake CUDA language # * set other CUDA compilation flags include(../../../../cpp/cuproj/cmake/modules/ConfigureCUDA.cmake) ################################################################################################### # - dependencies ---------------------------------------------------------------------------------- # add third party dependencies using CPM rapids_cpm_init() # find or add RMM include(../../../../cpp/cuproj/cmake/thirdparty/get_rmm.cmake) ################################################################################################### # - library targets ------------------------------------------------------------------------------- add_library(cuprojshim STATIC src/cuprojshim.cu) set_target_properties(cuprojshim PROPERTIES BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN" # set target compile options CXX_STANDARD 17 CXX_STANDARD_REQUIRED ON CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON POSITION_INDEPENDENT_CODE ON INTERFACE_POSITION_INDEPENDENT_CODE ON ) # Use `CUPROJ_*_FLAGS` here because we reuse the cuProj's ConfigureCUDA.cmake above target_compile_options(cuprojshim PRIVATE "$<$<COMPILE_LANGUAGE:CXX>:${CUPROJ_CXX_FLAGS}>" "$<$<COMPILE_LANGUAGE:CUDA>:${CUPROJ_CUDA_FLAGS}>" ) # Use `CUPROJ_*_DEFINITIONS` here because we reuse the cuProj's ConfigureCUDA.cmake above target_compile_definitions(cuprojshim PUBLIC "$<$<COMPILE_LANGUAGE:CXX>:${CUPROJ_CXX_DEFINITIONS}>" "$<$<COMPILE_LANGUAGE:CUDA>:${CUPROJ_CUDA_DEFINITIONS}>" ) # Specify include paths for the current target and dependents target_include_directories(cuprojshim PUBLIC "$<BUILD_INTERFACE:${CUPROJ_SOURCE_DIR}/include>" PUBLIC "$<BUILD_INTERFACE:${CUPROJSHIM_SOURCE_DIR}/include>" PRIVATE "$<BUILD_INTERFACE:${CUPROJSHIM_SOURCE_DIR}>" INTERFACE "$<INSTALL_INTERFACE:include>") # Add Conda library, and include paths if specified if(TARGET conda_env) target_link_libraries(cuprojshim PRIVATE conda_env) endif() # Workaround until https://github.com/rapidsai/rapids-cmake/issues/176 is resolved if(NOT BUILD_SHARED_LIBS) if(TARGET conda_env) install(TARGETS conda_env EXPORT cuprojshim-exports) endif() endif() # Per-thread default stream if(PER_THREAD_DEFAULT_STREAM) target_compile_definitions(cuprojshim PUBLIC CUDA_API_PER_THREAD_DEFAULT_STREAM) endif() # Disable NVTX if necessary if(NOT USE_NVTX) target_compile_definitions(cuprojshim PUBLIC NVTX_DISABLE) endif() # Define spdlog level target_compile_definitions(cuprojshim PUBLIC "SPDLOG_ACTIVE_LEVEL=SPDLOG_LEVEL_${RMM_LOGGING_LEVEL}") target_link_libraries(cuprojshim PUBLIC cuproj::cuproj rmm::rmm) add_library(cuproj::cuprojshim ALIAS cuprojshim)
0
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/cuprojshim
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/cuprojshim/include/cuprojshim.hpp
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cuproj/projection.cuh> #include <cuproj/vec_2d.hpp> #include <memory> namespace cuprojshim { template <typename T> cuproj::projection<cuproj::vec_2d<T>>* make_projection(std::string const& src_epsg, std::string const& dst_epsg); template <typename T> void transform(cuproj::projection<cuproj::vec_2d<T>> const& proj, cuproj::vec_2d<T>* xy_in, cuproj::vec_2d<T>* xy_out, std::size_t n, cuproj::direction dir); template <typename T> void transform(cuproj::projection<cuproj::vec_2d<T>> const& proj, T* x_in, T* y_in, T* x_out, T* y_out, std::size_t n, cuproj::direction dir); } // namespace cuprojshim #ifdef __CUDACC__ #include "detail/cuprojshim.hpp" #endif
0
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/cuprojshim/include
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/cuprojshim/include/detail/cuprojshim.hpp
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <cuproj/projection.cuh> #include <cuproj/projection_factories.cuh> #include <cuproj/vec_2d.hpp> #include <thrust/iterator/transform_iterator.h> #include <thrust/iterator/transform_output_iterator.h> #include <thrust/iterator/zip_iterator.h> #include <thrust/tuple.h> #include <iterator> #include <type_traits> namespace cuprojshim { namespace detail { /** * @internal * @brief Helper to convert a tuple of elements into a `vec_2d` */ template <typename T, typename VectorType = cuproj::vec_2d<T>> struct tuple_to_vec_2d { __device__ VectorType operator()(thrust::tuple<T, T> const& pos) { return VectorType{thrust::get<0>(pos), thrust::get<1>(pos)}; } }; /** * @internal * @brief Helper to convert a `vec_2d` into a tuple of elements */ template <typename T, typename VectorType = cuproj::vec_2d<T>> struct vec_2d_to_tuple { __device__ thrust::tuple<T, T> operator()(VectorType const& xy) { return thrust::make_tuple(xy.x, xy.y); } }; /** * @brief Create an iterator to `vec_2d` data from two input iterators. * * Interleaves x and y coordinates from separate iterators into a single * iterator to xy- coordinates. * * @tparam VectorType cuSpatial vector type, must be `vec_2d` * @tparam FirstIter Iterator type to the first component of `vec_2d`. Must meet * the requirements of [LegacyRandomAccessIterator][LinkLRAI] and be * device-accessible. * @tparam SecondIter Iterator type to the second component of `vec_2d`. Must * meet the requirements of [LegacyRandomAccessIterator][LinkLRAI] and be * device-accessible. * @param first Iterator to beginning of `vec_2d::x` * @param second Iterator to beginning of `vec_2d::y` * @return Iterator to `vec_2d` * * @pre `first` and `second` must iterate on same data type. * * [LinkLRAI]: https://en.cppreference.com/w/cpp/named_req/RandomAccessIterator * "LegacyRandomAccessIterator" */ template <typename FirstIter, typename SecondIter> auto make_vec_2d_iterator(FirstIter first, SecondIter second) { using T = typename std::iterator_traits<FirstIter>::value_type; static_assert(std::is_same<T, typename std::iterator_traits<SecondIter>::value_type>(), "Iterator value_type mismatch"); auto zipped = thrust::make_zip_iterator(first, second); return thrust::make_transform_iterator(zipped, tuple_to_vec_2d<T>()); } /** * @brief Create an output iterator to `vec_2d` data from two output iterators. * * Creates an output iterator from separate iterators to x and y data to which * can be written interleaved x/y data. This allows using two separate arrays of * output data with APIs that expect an iterator to structured data. * * @tparam VectorType cuSpatial vector type, must be `vec_2d` * @tparam FirstIter Iterator type to the first component of `vec_2d`. Must meet * the requirements of [LegacyRandomAccessIterator][LinkLRAI], be mutable and be * device-accessible. * @tparam SecondIter Iterator type to the second component of `vec_2d`. Must * meet the requirements of [LegacyRandomAccessIterator][LinkLRAI], be mutable * and be device-accessible. * @param first Iterator to beginning of `x` data. * @param second Iterator to beginning of `y` data. * @return Iterator to `vec_2d` * * @pre `first` and `second` must iterate on same data type. * * [LinkLRAI]: https://en.cppreference.com/w/cpp/named_req/RandomAccessIterator * "LegacyRandomAccessIterator" */ template <typename FirstIter, typename SecondIter> auto make_vec_2d_output_iterator(FirstIter first, SecondIter second) { using T = typename std::iterator_traits<FirstIter>::value_type; auto zipped_out = thrust::make_zip_iterator(thrust::make_tuple(first, second)); return thrust::transform_output_iterator(zipped_out, vec_2d_to_tuple<T>()); } } // namespace detail template <typename T> cuproj::projection<cuproj::vec_2d<T>>* make_projection(std::string const& src_epsg, std::string const& dst_epsg) { return cuproj::make_projection<cuproj::vec_2d<T>>(src_epsg, dst_epsg); } template <typename T> void transform(cuproj::projection<cuproj::vec_2d<T>> const& proj, cuproj::vec_2d<T>* xy_in, cuproj::vec_2d<T>* xy_out, std::size_t n, cuproj::direction dir) { proj.transform(xy_in, xy_in + n, xy_out, dir); } template <typename T> void transform(cuproj::projection<cuproj::vec_2d<T>> const& proj, T* x_in, T* y_in, T* x_out, T* y_out, std::size_t n, cuproj::direction dir) { auto xy_in = detail::make_vec_2d_iterator(x_in, y_in); auto xy_out = detail::make_vec_2d_output_iterator(x_out, y_out); proj.transform(xy_in, xy_in + n, xy_out, dir); } } // namespace cuprojshim
0
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/cuprojshim
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/cuprojshim/src/cuprojshim.cu
/* * Copyright (c) 2023, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cuprojshim.hpp> namespace cuprojshim { // explicit template instantiations // float template cuproj::projection<cuproj::vec_2d<float>>* make_projection<float>( std::string const& src_epsg, std::string const& dst_epsg); template void transform<float>(cuproj::projection<cuproj::vec_2d<float>> const& proj, cuproj::vec_2d<float>* xy_in, cuproj::vec_2d<float>* xy_out, std::size_t n, cuproj::direction dir); template void transform<float>(cuproj::projection<cuproj::vec_2d<float>> const& proj, float* x_in, float* y_in, float* x_out, float* y_out, std::size_t n, cuproj::direction dir); // double template cuproj::projection<cuproj::vec_2d<double>>* make_projection<double>( std::string const& src_epsg, std::string const& dst_epsg); template void transform<double>(cuproj::projection<cuproj::vec_2d<double>> const& proj, cuproj::vec_2d<double>* xy_in, cuproj::vec_2d<double>* xy_out, std::size_t n, cuproj::direction dir); template void transform<double>(cuproj::projection<cuproj::vec_2d<double>> const& proj, double* x_in, double* y_in, double* x_out, double* y_out, std::size_t n, cuproj::direction dir); } // namespace cuprojshim
0
rapidsai_public_repos/cuspatial/python/cuproj/cuproj
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/tests/test_transform.py
import cupy as cp import geopandas as gpd import numpy as np import pytest from cupy.testing import assert_allclose from pyproj import Transformer from pyproj.enums import TransformDirection from shapely.geometry import Point import cuspatial from cuproj import Transformer as cuTransformer valid_crs_combos = [ (4326, 32756), (32756, 4326), (4326, 32610), (32610, 4326)] invalid_crs_combos = [ (4326, 4326), (32756, 32756), (4326, 756), (756, 4326)] def to_epsg_string(code): return f"epsg:{code}" @pytest.mark.parametrize("crs_from, crs_to", valid_crs_combos) def test_valid_epsg_codes(crs_from, crs_to): Transformer.from_crs(crs_from, crs_to) @pytest.mark.parametrize("crs_from, crs_to", valid_crs_combos) def test_valid_epsg_strings(crs_from, crs_to): Transformer.from_crs(to_epsg_string(crs_from), to_epsg_string(crs_to)) @pytest.mark.parametrize("crs_from, crs_to", valid_crs_combos) def test_valid_uppercase_epsg_strings(crs_from, crs_to): Transformer.from_crs( to_epsg_string(crs_from).upper(), to_epsg_string(crs_to).upper()) @pytest.mark.parametrize("crs_from, crs_to", valid_crs_combos) def test_valid_epsg_mixed_ints_strings(crs_from, crs_to): Transformer.from_crs(to_epsg_string(crs_from), crs_to) Transformer.from_crs(str(crs_from), crs_to) Transformer.from_crs(crs_from, to_epsg_string(crs_to)) Transformer.from_crs(crs_from, str(crs_to)) @pytest.mark.parametrize("crs_from, crs_to", valid_crs_combos) def test_valid_epsg_tuples(crs_from, crs_to): Transformer.from_crs(("EPSG", crs_from), ("EPSG", crs_to)) Transformer.from_crs(("EPSG", crs_from), crs_to) Transformer.from_crs(("epsg", crs_from), to_epsg_string(crs_to)) Transformer.from_crs(("EPSG", crs_from), str(crs_to)) with pytest.raises(RuntimeError): Transformer.from_crs(("RPG", crs_from), crs_to) # invalid authority @pytest.mark.parametrize("crs_from, crs_to", invalid_crs_combos) def test_invalid_epsg_codes(crs_from, crs_to): with pytest.raises(RuntimeError): cuTransformer.from_crs(crs_from, crs_to) @pytest.mark.parametrize("crs_from, crs_to", invalid_crs_combos) def test_invalid_epsg_strings(crs_from, crs_to): with pytest.raises(RuntimeError): cuTransformer.from_crs( to_epsg_string(crs_from), to_epsg_string(crs_to)) def test_wgs84_to_utm_one_point(): # Sydney opera house latitude and longitude lat = -33.8587 lon = 151.2140 # Transform to UTM using PyProj transformer = Transformer.from_crs( "EPSG:4326", "EPSG:32756") pyproj_x, pyproj_y = transformer.transform(lat, lon) # Transform to UTM using cuproj cu_transformer = cuTransformer.from_crs("epsg:4326", "EPSG:32756") cuproj_x, cuproj_y = cu_transformer.transform(lat, lon) assert_allclose(cuproj_x, pyproj_x) assert_allclose(cuproj_y, pyproj_y) grid_corners = [ # San Francisco ((37.7081, -122.5149), (37.8324, -122.3573), "EPSG:32610"), # Sydney ((-33.9, 151.2), (-33.7, 151.3), "EPSG:32756"), # London ((51.3, -0.5), (51.6, 0.3), "EPSG:32630"), # New York City ((40.4774, -74.2591), (40.9176, -73.7004), "EPSG:32618"), # Ushuaia, Argentina ((-54.9, -68.4), (-54.7, -68.1), "EPSG:32719"), # McMurdo Station, Antarctica ((-77.9, 166.4), (-77.7, 166.7), "EPSG:32706"), # Singapore ((1.2, 103.6), (1.5, 104.0), "EPSG:32648")] container_types = [list, tuple, np.asarray, cp.asarray] def run_forward_and_inverse_transforms( dtype, container_type, min_corner, max_corner, crs_to): num_points_x = 100 num_points_y = 100 x, y = np.meshgrid( np.linspace(min_corner[0], max_corner[0], num_points_y, dtype=dtype), np.linspace(min_corner[1], max_corner[1], num_points_x, dtype=dtype)) grid = [x.reshape(-1), y.reshape(-1)] # Transform to UTM using PyProj transformer = Transformer.from_crs("EPSG:4326", crs_to) pyproj_x, pyproj_y = transformer.transform(*grid) # Transform to UTM using cuproj cu_grid = container_type(grid) cu_transformer = cuTransformer.from_crs("EPSG:4326", crs_to) cuproj_x, cuproj_y = cu_transformer.transform(*cu_grid) # Expect within 5m for float32, 100nm for float64 atol = 5 if dtype == cp.float32 else 1e-07 assert_allclose(cuproj_x, pyproj_x, atol=atol) assert_allclose(cuproj_y, pyproj_y, atol=atol) # Transform back to WGS84 using PyProj pyproj_x_back, pyproj_y_back = transformer.transform( pyproj_x, pyproj_y, direction=TransformDirection.INVERSE) # Transform back to WGS84 using cuproj cuproj_x_back, cuproj_y_back = cu_transformer.transform( cuproj_x, cuproj_y, direction="INVERSE") assert_allclose(cuproj_x_back, pyproj_x_back, atol=atol) assert_allclose(cuproj_y_back, pyproj_y_back, atol=atol) # Also test inverse-constructed Transformers # Transform back to WGS84 using PyProj transformer = Transformer.from_crs(crs_to, "EPSG:4326") pyproj_x_back, pyproj_y_back = transformer.transform( pyproj_x, pyproj_y) # Transform back to WGS84 using cuproj cu_transformer = cuTransformer.from_crs(crs_to, "EPSG:4326") cuproj_x_back, cuproj_y_back = cu_transformer.transform( cuproj_x, cuproj_y) assert_allclose(cuproj_x_back, pyproj_x_back, atol=atol) assert_allclose(cuproj_y_back, pyproj_y_back, atol=atol) # test float and double @pytest.mark.parametrize("dtype", [cp.float32, cp.float64]) # test with grids of points @pytest.mark.parametrize("container_type", container_types) # test with various container types (host and device) @pytest.mark.parametrize("min_corner, max_corner, crs_to", grid_corners) def test_wgs84_to_utm_grid(dtype, container_type, min_corner, max_corner, crs_to): run_forward_and_inverse_transforms( dtype, container_type, min_corner, max_corner, crs_to) # test __cuda_array_interface__ support by using cuspatial geoseries as input def test_geoseries_input(): s = gpd.GeoSeries( [ Point(grid_corners[0][0]), Point(grid_corners[0][1]), ] ) gs = cuspatial.from_geopandas(s) # Transform to UTM using PyProj transformer = Transformer.from_crs("EPSG:4326", grid_corners[0][2]) pyproj_x, pyproj_y = transformer.transform(s.x.values, s.y.values) # Transform to UTM using cuproj cu_transformer = cuTransformer.from_crs("EPSG:4326", grid_corners[0][2]) cuproj_x, cuproj_y = cu_transformer.transform(gs.points.x, gs.points.y) assert_allclose(cuproj_x, pyproj_x) assert_allclose(cuproj_y, pyproj_y)
0
rapidsai_public_repos/cuspatial/python/cuproj/cuproj
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/_lib/CMakeLists.txt
# ============================================================================= # Copyright (c) 2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and limitations under # the License. # ============================================================================= set(cython_sources transform.pyx) set(linked_libraries cuprojshim) rapids_cython_create_modules( CXX ASSOCIATED_TARGETS cuproj SOURCE_FILES "${cython_sources}" LINKED_LIBRARIES "${linked_libraries}" )
0
rapidsai_public_repos/cuspatial/python/cuproj/cuproj
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/_lib/transform.pyx
import cupy as cp from libc.stdint cimport uintptr_t from libcpp.string cimport string from cuproj._lib.cpp.cuprojshim cimport make_projection, transform, vec_2d from cuproj._lib.cpp.operation cimport direction from cuproj._lib.cpp.projection cimport projection cdef direction_string_to_enum(dir: str): return direction.FORWARD if dir == "FORWARD" else direction.INVERSE cdef class Transformer: cdef projection[vec_2d[float]]* proj_32 cdef projection[vec_2d[double]]* proj_64 def __init__(self, crs_from, crs_to): if isinstance(crs_from, int): crs_from = str(crs_from) elif isinstance(crs_from, tuple): crs_from = str.join(":", crs_from) if isinstance(crs_to, int): crs_to = str(crs_to) elif isinstance(crs_to, tuple): crs_to = str.join(":", crs_to) if (not isinstance(crs_from, str) or not isinstance(crs_to, str)): raise TypeError( "crs_from and crs_to must be strings or integers") crs_from_b = crs_from.encode('utf-8') crs_to_b = crs_to.encode('utf-8') self.proj_32 = make_projection[float]( <string> crs_from_b, <string> crs_to_b) self.proj_64 = make_projection[double]( <string> crs_from_b, <string> crs_to_b) def __del__(self): del self.proj_32 del self.proj_64 def transform(self, x, y, dir): if (len(x.shape) != 1): raise TypeError("x must be a 1D array") if (len(y.shape) != 1): raise TypeError("y must be a 1D array") if (x.shape[0] != y.shape[0]): raise TypeError("x and y must have the same length") if isinstance(x.dtype, cp.floating): raise TypeError("x must be of floating point type") if isinstance(y.dtype, cp.floating): raise TypeError("y must be of floating point type") if (x.dtype != y.dtype): raise TypeError("x and y must have the same dtype") if (x.dtype == cp.float32): return self.transform_32(x, y, dir) else: return self.transform_64(x, y, dir) def transform_32(self, x, y, dir): cdef int size = x.shape[0] result_x = cp.ndarray((size,), order='C', dtype=x.dtype) result_y = cp.ndarray((size,), order='C', dtype=y.dtype) cdef float* x_in = \ <float*> <uintptr_t> x.__cuda_array_interface__['data'][0] cdef float* y_in = \ <float*> <uintptr_t> y.__cuda_array_interface__['data'][0] cdef float* x_out = <float*> <uintptr_t> result_x.data.ptr cdef float* y_out = <float*> <uintptr_t> result_y.data.ptr cdef direction d = direction_string_to_enum(dir) with nogil: transform( self.proj_32[0], x_in, y_in, x_out, y_out, size, d) return result_x, result_y def transform_64(self, x, y, dir): cdef int size = x.shape[0] result_x = cp.ndarray((size,), order='C', dtype=cp.float64) result_y = cp.ndarray((size,), order='C', dtype=cp.float64) cdef double* x_in = \ <double*> <uintptr_t> x.__cuda_array_interface__['data'][0] cdef double* y_in = \ <double*> <uintptr_t> y.__cuda_array_interface__['data'][0] cdef double* x_out = <double*> <uintptr_t> result_x.data.ptr cdef double* y_out = <double*> <uintptr_t> result_y.data.ptr cdef direction d = direction_string_to_enum(dir) with nogil: transform( self.proj_64[0], x_in, y_in, x_out, y_out, size, d) return result_x, result_y
0
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/_lib
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/_lib/cpp/projection.pxd
from libcpp.vector cimport vector from cuproj._lib.cpp.operation cimport direction, operation_type from cuproj._lib.cpp.projection_parameters cimport projection_parameters cdef extern from "cuproj/projection.cuh" namespace "cuproj" nogil: cdef cppclass projection[Coordinate, T=*]: projection() projection(vector[operation_type], projection_parameters[T], direction=direction.FORWARD) void transform[CoordIter](CoordIter, CoordIter, CoordIter, direction)
0
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/_lib
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/_lib/cpp/operation.pxd
cdef extern from "cuproj/operation/operation.cuh" namespace "cuproj" nogil: cdef enum operation_type: AXIS_SWAP = 0 DEGREES_TO_RADIANS = 1 CLAMP_ANGULAR_COORDINATES = 2 OFFSET_SCALE_CARTESIAN_COORDINATES = 3 TRANSVERSE_MERCATOR = 4 cdef enum direction: FORWARD = 0 INVERSE = 1
0
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/_lib
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/_lib/cpp/cuprojshim.pxd
from libcpp.string cimport string from cuproj._lib.cpp.operation cimport direction from cuproj._lib.cpp.projection cimport projection cdef extern from "cuprojshim.hpp" namespace "cuproj" nogil: cdef cppclass vec_2d[T]: T x T y cdef extern from "cuprojshim.hpp" namespace "cuprojshim" nogil: projection[vec_2d[T]]* make_projection[T](string, string) except + void transform[T]( projection[vec_2d[T]], vec_2d[T]*, vec_2d[T]*, size_t, direction ) except+ void transform[T]( projection[vec_2d[T]], T*, T*, T*, T*, size_t, direction ) except +
0
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/_lib
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/_lib/cpp/ellipsoid.pxd
cdef extern from "cuproj/ellipsoid.hpp" namespace "cuproj" nogil: cdef cppclass ellipsoid[T]: ellipsoid() except+ ellipsoid(T, T) except+
0
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/_lib
rapidsai_public_repos/cuspatial/python/cuproj/cuproj/_lib/cpp/projection_parameters.pxd
from cuproj._lib.cpp.ellipsoid cimport ellipsoid cdef extern from "cuproj/projection_parameters.hpp" namespace "cuproj" nogil: cdef enum hemisphere: NORTH = 0 SOUTH = 1 cdef cppclass projection_parameters[T]: projection_parameters( ellipsoid[T], int, hemisphere, T, T ) except+
0
rapidsai_public_repos/cuspatial/python
rapidsai_public_repos/cuspatial/python/cuspatial/pyproject.toml
# Copyright (c) 2022-2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. [build-system] build-backend = "setuptools.build_meta" requires = [ "cmake>=3.26.4", "cudf==23.12.*", "cython>=3.0.0", "ninja", "rmm==23.12.*", "scikit-build>=0.13.1", "setuptools", "wheel", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. [project] name = "cuspatial" dynamic = ["version"] description = "cuSpatial: GPU-Accelerated Spatial and Trajectory Data Management and Analytics Library" readme = { file = "README.md", content-type = "text/markdown" } authors = [ { name = "NVIDIA Corporation" }, ] license = { text = "Apache 2.0" } requires-python = ">=3.9" dependencies = [ "cudf==23.12.*", "geopandas>=0.11.0", "rmm==23.12.*", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. classifiers = [ "Intended Audience :: Developers", "Topic :: Database", "Topic :: Scientific/Engineering", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", ] [project.optional-dependencies] test = [ "pytest", "pytest-cov", "pytest-xdist", ] # This list was generated by `rapids-dependency-file-generator`. To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. [project.urls] Homepage = "https://github.com/rapidsai/cuspatial" Documentation = "https://docs.rapids.ai/api/cuspatial/stable/" [tool.setuptools] license-files = ["LICENSE"] [tool.setuptools.dynamic] version = {file = "cuspatial/VERSION"} [tool.isort] line_length = 79 multi_line_output = 3 include_trailing_comma = true force_grid_wrap = 0 combine_as_imports = true order_by_type = true known_dask = [ "dask", "distributed", "dask_cuda", ] known_rapids = [ "rmm", "cudf", ] known_first_party = [ "cuspatial", ] default_section = "THIRDPARTY" sections = [ "FUTURE", "STDLIB", "THIRDPARTY", "DASK", "RAPIDS", "FIRSTPARTY", "LOCALFOLDER", ] skip = [ "thirdparty", ".eggs", ".git", ".hg", ".mypy_cache", ".tox", ".venv", "_build", "buck-out", "build", "dist", "__init__.py", ]
0
rapidsai_public_repos/cuspatial/python
rapidsai_public_repos/cuspatial/python/cuspatial/CMakeLists.txt
# ============================================================================= # Copyright (c) 2022-2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and limitations under # the License. # ============================================================================= cmake_minimum_required(VERSION 3.26.4 FATAL_ERROR) set(cuspatial_version 23.12.00) include(../../fetch_rapids.cmake) include(rapids-cuda) rapids_cuda_init_architectures(cuspatial-python) project( cuspatial-python VERSION ${cuspatial_version} LANGUAGES # TODO: Building Python extension modules via the python_extension_module requires the C # language to be enabled here. The test project that is built in scikit-build to verify # various linking options for the python library is hardcoded to build with C, so until # that is fixed we need to keep C. C CXX CUDA) option(FIND_CUSPATIAL_CPP "Search for existing cuspatial C++ installations before defaulting to local files" OFF) option(CUSPATIAL_BUILD_WHEELS "Whether this build is generating a Python wheel." OFF) # If the user requested it we attempt to find cuspatial. if(FIND_CUSPATIAL_CPP) find_package(cuspatial ${cuspatial_version}) else() set(cuspatial_FOUND OFF) endif() if(NOT cuspatial_FOUND) set(BUILD_TESTS OFF) set(BUILD_BENCHMARKS OFF) set(_exclude_from_all "") if(CUSPATIAL_BUILD_WHEELS) # Statically link cudart if building wheels set(CUDA_STATIC_RUNTIME ON) set(CUSPATIAL_USE_CUDF_STATIC ON) set(CUSPATIAL_EXCLUDE_CUDF_FROM_ALL ON) # Always build wheels against the pyarrow libarrow. set(USE_LIBARROW_FROM_PYARROW ON) # Need to set this so all the nvcomp targets are global, not only nvcomp::nvcomp # https://cmake.org/cmake/help/latest/variable/CMAKE_FIND_PACKAGE_TARGETS_GLOBAL.html#variable:CMAKE_FIND_PACKAGE_TARGETS_GLOBAL set(CMAKE_FIND_PACKAGE_TARGETS_GLOBAL ON) # Don't install the cuSpatial C++ targets into wheels set(_exclude_from_all EXCLUDE_FROM_ALL) endif() add_subdirectory(../../cpp cuspatial-cpp ${_exclude_from_all}) set(cython_lib_dir cuspatial) if(CUSPATIAL_BUILD_WHEELS) include(cmake/Modules/WheelHelpers.cmake) get_target_property(_nvcomp_link_libs nvcomp::nvcomp INTERFACE_LINK_LIBRARIES) # Ensure all the shared objects we need at runtime are in the wheel add_target_libs_to_wheel(LIB_DIR ${cython_lib_dir} TARGETS arrow_shared nvcomp::nvcomp ${_nvcomp_link_libs}) endif() # Since there are multiple subpackages of cuspatial._lib that require access to libcuspatial, we place the # library in the cuspatial directory as a single source of truth and modify the other rpaths # appropriately. install(TARGETS cuspatial DESTINATION ${cython_lib_dir}) endif() include(rapids-cython) rapids_cython_init() add_subdirectory(cuspatial/_lib) if(DEFINED cython_lib_dir) rapids_cython_add_rpath_entries(TARGET cuspatial PATHS "${cython_lib_dir}") endif()
0
rapidsai_public_repos/cuspatial/python
rapidsai_public_repos/cuspatial/python/cuspatial/README.md
# <div align="left"><img src="https://rapids.ai/assets/images/rapids_logo.png" width="90px"/>&nbsp;cuSpatial - GPU-Accelerated Vector Geospatial Data Analysis</div> > **Note** > > cuSpatial depends on [cuDF](https://github.com/rapidsai/cudf) and [RMM](https://github.com/rapidsai/rmm) from [RAPIDS](https://rapids.ai/). ## cuProj - GPU-accelerated Coordinate Reference System (CRS) Transformations cuProj is a new RAPIDS library housed within the cuSpatial repo that provides GPU-accelerated transformations of coordinates between coordinate reference systems (CRS). cuProj is available as of release 23.10 with support for transformations of WGS84 coordinates to and from Universal Transverse Mercator (UTM) :globe_with_meridians:. To learn more about cuProj, see the [Python cuProj README](python/cuproj/README.md) or the [c++ libcuproj README](cpp/cuproj/README.md). ## Resources - [cuSpatial User's Guide](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html): Python API reference and guides - [cuSpatial Developer Documentation](https://docs.rapids.ai/api/cuspatial/stable/developer_guide/index.html): Understand cuSpatial's architecture - [Getting Started](https://docs.rapids.ai/install#selector): Installation options for cuSpatial - [cuSpatial Community](https://github.com/rapidsai/cuspatial/discussions): Get help, collaborate, and ask the team questions - [cuSpatial Issues](https://github.com/rapidsai/cuspatial/issues/new/choose): Request a feature/documentation or report a bug ## Overview cuSpatial accelerates vector geospatial operations through GPU parallelization. As part of the RAPIDS libraries, cuSpatial is inherently connected to [cuDF](https://github.com/rapidsai/cudf), [cuML](https://github.com/rapidsai/cuml), and [cuGraph](https://github.com/rapidsai/cugraph), enabling GPU acceleration across entire workflows. cuSpatial represents data in [GeoArrow](https://github.com/geoarrow/geoarrow) format, which enables compatibility with the [Apache Arrow](https://arrow.apache.org) ecosystem. cuSpatial's Python API is closely matched to GeoPandas and data can seamlessly transition between the two: ```python import geopandas from shapely.geometry import Polygon import cuspatial p1 = Polygon([(0, 0), (1, 0), (1, 1)]) p2 = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]) geoseries = geopandas.GeoSeries([p1, p2]) cuspatial_geoseries = cuspatial.from_geopandas(geoseries) print(cuspatial_geoseries) ``` Output: ``` 0 POLYGON ((0 0, 1 0, 1 1, 0 0)) 1 POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0)) ``` For additional examples, browse the complete [API documentation](https://docs.rapids.ai/api/cuspatial/stable/), or check out more detailed [notebooks](https://github.com/rapidsai/notebooks-contrib). the [NYC Taxi][1] and [Weather][2] notebooks make use of cuSpatial. ## Supported Geospatial Operations cuSpatial is constantly working on new features! Check out the [epics](https://github.com/orgs/rapidsai/projects/41/views/4) for a high-level view of our development, or the [roadmap](https://github.com/orgs/rapidsai/projects/41/views/5) for the details! ### Core Spatial Functions - [Spatial relationship queries (DE-9IM)](https://docs.rapids.ai/api/cuspatial/stable/api_docs/geopandas_compatibility/#cuspatial.GeoSeries.contains) - [Linestring-Linestring Intersections](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#Linestring-Intersections) - Cartesian distance between any two geometries (ST_Distance) - [Haversine distance](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#cuspatial.haversine_distance) - [Hausdorff distance](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#cuspatial.directed_hausdorff_distance) - [Spatial window filtering](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#cuspatial.points_in_spatial_window) ### Indexing and Join Functions - [Quadtree indexing](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#Quadtree-Indexing) - [Spatial joins](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#Indexed-Spatial-Joins) - [Quadtree-based point-in-polygon](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#cuspatial.quadtree_point_in_polygon) - [Quadtree-based point-to-nearest-linestring](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#cuspatial.quadtree_point_to_nearest_linestring) ### Trajectory Functions - [Deriving trajectories from point location data](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#cuspatial.derive_trajectories) - [Computing distance/speed of trajectories](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#cuspatial.trajectory_distances_and_speeds) - [Computing spatial bounding boxes of trajectories](https://docs.rapids.ai/api/cuspatial/stable/user_guide/cuspatial_api_examples.html#cuspatial.trajectory_bounding_boxes) ### What if operations I need aren't supported? Thanks to the `from_geopandas` and `to_geopandas` functions you can accelerate what cuSpatial supports, and leave the rest of the workflow in place. ```mermaid --- title: Integrating into Existing Workflows --- %%{init: { 'logLevel': 'debug', 'theme': 'base', 'gitGraph': {'showBranches': false}, 'themeVariables': {'commitLabelColor': '#000000', 'commitLabelBackground': '#ffffff', 'commitLabelFontSize': '14px'}} }%% gitGraph commit id: "Existing Workflow Start" commit id: "GeoPandas IO" commit id: "Geospatial Analytics" branch a checkout a commit id: "from_geopandas" commit id: "cuSpatial GPU Acceleration" branch b checkout b commit id: "cuDF" commit id: "cuML" commit id: "cuGraph" checkout a merge b commit id: "to_geopandas" checkout main merge a commit id: "Continue Work" ``` ## Using cuSpatial **CUDA/GPU requirements** - CUDA 11.2+ with a [compatible, supported driver](https://docs.nvidia.com/datacenter/tesla/drivers/#cuda-drivers) - Linux native: Pascal architecture or newer ([Compute Capability >=6.0](https://developer.nvidia.com/cuda-gpus)) - WSL2: Volta architecture or newer ([Compute Capability >=7.0](https://developer.nvidia.com/cuda-gpus)) ### Quick start: Docker Use the [RAPIDS Release Selector](https://docs.rapids.ai/install#selector), selecting `Docker` as the installation method. All RAPIDS Docker images contain cuSpatial. An example command from the Release Selector: ```shell docker run --gpus all --pull always --rm -it \ --shm-size=1g --ulimit memlock=-1 --ulimit stack=67108864 \ -p 8888:8888 -p 8787:8787 -p 8786:8786 \ nvcr.io/nvidia/rapidsai/notebooks:23.12-cuda11.8-py3.10 ``` ### Install with Conda To install via conda: > **Note** cuSpatial is supported only on Linux or [through WSL](https://rapids.ai/wsl2.html), and with Python versions 3.9 and 3.10 cuSpatial can be installed with conda (miniconda, or the full Anaconda distribution) from the rapidsai channel: ```shell conda install -c rapidsai -c conda-forge -c nvidia \ cuspatial=23.12 python=3.10 cudatoolkit=11.8 ``` We also provide nightly Conda packages built from the HEAD of our latest development branch. See the [RAPIDS installation documentation](https://docs.rapids.ai/install) for more OS and version info. ### Install with pip To install via pip: > **Note** cuSpatial is supported only on Linux or [through WSL](https://rapids.ai/wsl2.html), and with Python versions 3.9 and 3.10 The cuSpatial pip packages can be installed from NVIDIA's PyPI index. pip installations require using the matching wheel to the system's installed CUDA toolkit. - For CUDA 11 toolkits, install the `-cu11` wheels - For CUDA 12 toolkits install the `-cu12` wheels - If your installation has a CUDA 12 driver but a CUDA 11 toolkit, use the `-cu11` wheels. ```shell pip install cuspatial-cu12 --extra-index-url=https://pypi.nvidia.com pip install cuspatial-cu11 --extra-index-url=https://pypi.nvidia.com ``` #### Troubleshooting Fiona/GDAL versions cuSpatial depends on [`geopandas`](https://github.com/geopandas/geopandas), which uses [`fiona >= 1.8.19`](https://pypi.org/project/Fiona/), to read common GIS formats with GDAL. Fiona requires GDAL is already present on your system, but its minimum required version may be newer than the version of GDAL in your OS's package manager. Fiona checks the GDAL version at install time and fails with an error like this if a compatible version of GDAL isn't installed: ``` ERROR: GDAL >= 3.2 is required for fiona. Please upgrade GDAL. ``` There are two ways to fix this: 1. Install a version of GDAL that meets fiona's minimum required version * Ubuntu users can install a newer GDAL with the [UbuntuGIS PPA](https://wiki.ubuntu.com/UbuntuGIS): ```shell sudo -y add-apt-repository ppa:ubuntugis/ppa sudo apt install libgdal-dev ``` 2. Pin fiona's version to a range that's compatible with your version of `libgdal-dev` * For Ubuntu20.04 ([GDAL v3.0.4](https://packages.ubuntu.com/focal/libgdal-dev)): ```shell pip install --no-binary fiona --extra-index-url=https://pypi.nvidia.com cuspatial-cu12 'fiona>=1.8.19,<1.9' ``` * For Ubuntu22.04 ([GDAL v3.4.1](https://packages.ubuntu.com/jammy/libgdal-dev)): ```shell pip install --no-binary fiona --extra-index-url=https://pypi.nvidia.com cuspatial-cu12 'fiona>=1.9' ``` ### Build/Install from source To build and install cuSpatial from source please see the [build documentation](https://docs.rapids.ai/api/cuspatial/stable/developer_guide/build.html). ## Citing cuSpatial If you find cuSpatial useful in your published work, please consider citing the repository. ```bibtex @misc{cuspatial:23.12, author = {{NVIDIA Corporation}}, title = {cuSpatial: GPU-Accelerated Geospatial and Spatiotemporal Algorithms}, year = {2023}, publisher = {NVIDIA}, howpublished = {\url{https://github.com/rapidsai/cuspatial}}, note = {Software available from github.com}, } ``` [1]:https://github.com/rapidsai-community/notebooks-contrib/blob/main/community_tutorials_and_guides/taxi/NYCTaxi-E2E.ipynb [2]:https://github.com/rapidsai-community/notebooks-contrib/blob/main/community_tutorials_and_guides/weather.ipynb
0
rapidsai_public_repos/cuspatial/python
rapidsai_public_repos/cuspatial/python/cuspatial/setup.py
# Copyright (c) 2018-2023, NVIDIA CORPORATION. from setuptools import find_packages from skbuild import setup packages = find_packages(include=["cuspatial*"]) setup( packages=packages, package_data={ key: ["VERSION", "*.pxd", "*.hpp", "*.cuh"] for key in packages }, zip_safe=False, )
0
rapidsai_public_repos/cuspatial/python
rapidsai_public_repos/cuspatial/python/cuspatial/LICENSE
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2019 NVIDIA Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
0
rapidsai_public_repos/cuspatial/python
rapidsai_public_repos/cuspatial/python/cuspatial/.coveragerc
# Configuration file for Python coverage tests [run] source = cuspatial
0
rapidsai_public_repos/cuspatial/python/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_version.py
# Copyright (c) 2023, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import importlib.resources __version__ = ( importlib.resources.files("cuspatial") .joinpath("VERSION") .read_text() .strip() ) __git_commit__ = ""
0
rapidsai_public_repos/cuspatial/python/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. from ._version import __git_commit__, __version__ from .core.geodataframe import GeoDataFrame from .core.geoseries import GeoSeries from .core.spatial import ( directed_hausdorff_distance, haversine_distance, join_quadtree_and_bounding_boxes, linestring_bounding_boxes, pairwise_linestring_distance, pairwise_linestring_polygon_distance, pairwise_point_distance, pairwise_point_linestring_distance, pairwise_point_linestring_nearest_points, pairwise_point_polygon_distance, pairwise_polygon_distance, point_in_polygon, points_in_spatial_window, polygon_bounding_boxes, quadtree_on_points, quadtree_point_in_polygon, quadtree_point_to_nearest_linestring, sinusoidal_projection, ) from .core.trajectory import ( derive_trajectories, trajectory_bounding_boxes, trajectory_distances_and_speeds, ) from .io.geopandas import from_geopandas
0
rapidsai_public_repos/cuspatial/python/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/VERSION
23.12.00
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/utils/join_utils.py
# Copyright (c) 2023, NVIDIA CORPORATION. import operator from numba import cuda import rmm from cudf.core.buffer import acquire_spill_lock @cuda.jit def binarize(in_col, out, width): """Convert any positive integer to a binary array.""" i = cuda.grid(1) if i < in_col.size: n = in_col[i] idx = width - 1 out[i, idx] = operator.mod(n, 2) idx -= 1 while n > 1: n = operator.rshift(n, 1) out[i, idx] = operator.mod(n, 2) idx -= 1 def apply_binarize(in_col, width): buf = rmm.DeviceBuffer(size=(in_col.size * width)) out = cuda.as_cuda_array(buf).view("int8").reshape((in_col.size, width)) if out.size > 0: out[:] = 0 binarize.forall(out.size)(in_col, out, width) return out def pip_bitmap_column_to_binary_array(polygon_bitmap_column, width): """Convert the bitmap output of point_in_polygon to an array of 0s and 1s. """ with acquire_spill_lock(): binary_maps = apply_binarize( polygon_bitmap_column.data_array_view(mode="read"), width ) return binary_maps
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/utils/column_utils.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. from typing import TypeVar import numpy as np from cudf.api.types import is_datetime_dtype from cudf.core.column.column import column_empty from cuspatial.core._column.geometa import Feature_Enum from cuspatial.core.dtypes import ( linestring_dtype, multipoint_dtype, point_dtype, polygon_dtype, ) GeoSeries = TypeVar("GeoSeries", bound="GeoSeries") def normalize_point_columns(*cols): """ Normalize the input columns by inferring a common floating point dtype. If the common dtype isn't a floating point dtype, promote the common dtype to float64. Parameters ---------- {params} Returns ------- tuple : the input columns cast to the inferred common floating point dtype """ dtype = np.result_type(*cols) if not np.issubdtype(dtype, np.floating): dtype = np.float32 if dtype.itemsize <= 4 else np.float64 return (x.astype(dtype) for x in cols) def normalize_timestamp_column(ts, fallback_dtype="datetime64[ms]"): """ Normalize the input timestamp column to one of the cuDF timestamp dtypes. If the input column's dtype isn't an np.datetime64, cast the column to the supplied `fallback_dtype` parameter. Parameters ---------- {params} Returns ------- column : the input column """ return ts if is_datetime_dtype(ts.dtype) else ts.astype(fallback_dtype) def contain_single_type_geometry(gs: GeoSeries): """ Returns true if `gs` contains only single type of geometries A geometry is considered as the same type to its multi-geometry variant. """ has_points = len(gs.points.xy) > 0 has_multipoints = len(gs.multipoints.xy) > 0 has_lines = len(gs.lines.xy) > 0 has_polygons = len(gs.polygons.xy) > 0 return ( len(gs) > 0 and ((has_points or has_multipoints) + has_lines + has_polygons) == 1 ) def contains_only_points(gs: GeoSeries): """ Returns true if `gs` contains only points or multipoints """ points = gs._column._meta.input_types == Feature_Enum.POINT.value mpoints = gs._column._meta.input_types == Feature_Enum.MULTIPOINT.value return (points | mpoints).all() def contains_only_multipoints(gs: GeoSeries): """ Returns true if `gs` contains only multipoints """ return ( gs._column._meta.input_types == Feature_Enum.MULTIPOINT.value ).all() def contains_only_linestrings(gs: GeoSeries): """ Returns true if `gs` contains only linestrings """ return ( gs._column._meta.input_types == Feature_Enum.LINESTRING.value ).all() def contains_only_polygons(gs: GeoSeries): """ Returns true if `gs` contains only polygons """ return (gs._column._meta.input_types == Feature_Enum.POLYGON.value).all() def has_same_geometry(lhs: GeoSeries, rhs: GeoSeries): """ Returns true if `lhs` and `rhs` have only features of the same homogeneous geometry type. """ if contains_only_points(lhs) and contains_only_points(rhs): return True elif contains_only_multipoints(lhs) and contains_only_multipoints(rhs): return True elif contains_only_linestrings(lhs) and contains_only_linestrings(rhs): return True elif contains_only_polygons(lhs) and contains_only_polygons(rhs): return True else: return False def has_multipolygons(gs: GeoSeries): """ Returns true if `gs` contains any MultiPolygons """ return len(gs.polygons.geometry_offset) != len(gs.polygons.part_offset) def empty_geometry_column(feature: Feature_Enum, base_type): """Return a geometry column of type `feature`. Length is 0.""" if feature == Feature_Enum.POINT: return column_empty(0, point_dtype(base_type), masked=False) elif feature == Feature_Enum.MULTIPOINT: return column_empty(0, multipoint_dtype(base_type), masked=False) elif feature == Feature_Enum.LINESTRING: return column_empty(0, linestring_dtype(base_type), masked=False) elif feature == Feature_Enum.POLYGON: return column_empty(0, polygon_dtype(base_type), masked=False)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/utils/binpred_utils.py
# Copyright (c) 2023, NVIDIA CORPORATION. import cupy as cp import numpy as np import cudf import cuspatial from cuspatial.core._column.geocolumn import ColumnType from cuspatial.core._column.geometa import Feature_Enum """Column-Type objects to use for simple syntax in the `DispatchDict` contained in each `feature_<predicate>.py` file. For example, instead of writing out `ColumnType.POINT`, we can just write `Point`. """ Point = ColumnType.POINT MultiPoint = ColumnType.MULTIPOINT LineString = ColumnType.LINESTRING Polygon = ColumnType.POLYGON def _false_series(size): """Return a Series of False values""" return cudf.Series(cp.zeros(size, dtype=cp.bool_)) def _true_series(size): """Return a Series of True values""" return cudf.Series(cp.ones(size, dtype=cp.bool_)) def _zero_series(size): """Return a Series of zeros""" return cudf.Series(cp.zeros(size, dtype=cp.int32)) def _one_series(size): """Return a Series of ones""" return cudf.Series(cp.ones(size, dtype=cp.int32)) def _count_results_in_multipoint_geometries(point_indices, point_result): """Count the number of points in each multipoint geometry. Parameters ---------- point_indices : cudf.Series The indices of the points in the original (rhs) GeoSeries. point_result : cudf.DataFrame The result of a contains_properly call. Returns ------- cudf.Series The number of points that fell within a particular polygon id. cudf.Series The number of points in each multipoint geometry. """ point_indices_df = cudf.Series( point_indices, name="rhs_index", index=cudf.RangeIndex(len(point_indices), name="point_index"), ).reset_index() with_rhs_indices = point_result.merge(point_indices_df, on="point_index") # Because we are doing pairwise operations, we're only interested in the # results where polygon_index and rhs_index match pairwise_matches = with_rhs_indices[ with_rhs_indices["polygon_index"] == with_rhs_indices["rhs_index"] ] points_grouped_by_original_polygon = pairwise_matches[ ["point_index", "rhs_index"] ].drop_duplicates() hits = ( points_grouped_by_original_polygon.groupby("rhs_index") .count() .sort_index() ) expected_count = point_indices_df.groupby("rhs_index").count().sort_index() return hits, expected_count def _linestrings_from_polygons(geoseries): """Converts the exterior and interior rings of a geoseries of polygons into a geoseries of linestrings.""" xy = geoseries.polygons.xy parts = geoseries.polygons.part_offset.take( geoseries.polygons.geometry_offset ) rings = geoseries.polygons.ring_offset return cuspatial.GeoSeries.from_linestrings_xy( xy, rings, parts, ) def _linestrings_from_multipoints(geoseries): """Converts a geoseries of multipoints into a geoseries of linestrings.""" points = cudf.DataFrame( { "x": geoseries.multipoints.x.repeat(2).reset_index(drop=True), "y": geoseries.multipoints.y.repeat(2).reset_index(drop=True), } ).interleave_columns() result = cuspatial.GeoSeries.from_linestrings_xy( points, geoseries.multipoints.geometry_offset * 2, cp.arange(len(geoseries) + 1), ) return result def _linestrings_from_points(geoseries): """Converts a geoseries of points into a geoseries of linestrings. Linestrings converted to points are represented as a segment of length two, with the beginning and ending of the segment being the same point. Example ------- >>> import cuspatial >>> from cuspatial.utils.binpred_utils import ( ... _linestrings_from_points ... ) >>> from shapely.geometry import Point >>> points = cuspatial.GeoSeries([Point(0, 0), Point(1, 1)]) >>> linestrings = _linestrings_from_points(points) >>> linestrings Out[1]: 0 LINESTRING (0.00000 0.00000, 0.00000 0.00000) 1 LINESTRING (1.00000 1.00000, 1.00000 1.00000) dtype: geometry """ x = cp.repeat(geoseries.points.x, 2) y = cp.repeat(geoseries.points.y, 2) xy = cudf.DataFrame({"x": x, "y": y}).interleave_columns() parts = cp.arange((len(geoseries) + 1)) * 2 geometries = cp.arange(len(geoseries) + 1) return cuspatial.GeoSeries.from_linestrings_xy(xy, parts, geometries) def _linestrings_from_geometry(geoseries): """Wrapper function that converts any homogeneous geoseries into a geoseries of linestrings.""" if geoseries.column_type == ColumnType.POINT: return _linestrings_from_points(geoseries) if geoseries.column_type == ColumnType.MULTIPOINT: return _linestrings_from_multipoints(geoseries) elif geoseries.column_type == ColumnType.LINESTRING: return geoseries elif geoseries.column_type == ColumnType.POLYGON: return _linestrings_from_polygons(geoseries) else: raise NotImplementedError( "Cannot convert type {} to linestrings".format(geoseries.type) ) def _multipoints_from_points(geoseries): """Converts a geoseries of points into a geoseries of length 1 multipoints.""" result = cuspatial.GeoSeries.from_multipoints_xy( geoseries.points.xy, cp.arange((len(geoseries) + 1)) ) return result def _multipoints_from_linestrings(geoseries): """Converts a geoseries of linestrings into a geoseries of multipoints. MultiLineStrings are converted into a single multipoint.""" xy = geoseries.lines.xy mpoints = geoseries.lines.part_offset.take(geoseries.lines.geometry_offset) return cuspatial.GeoSeries.from_multipoints_xy(xy, mpoints) def _multipoints_from_polygons(geoseries): """Converts a geoseries of polygons into a geoseries of multipoints. All exterior and interior points become points in each multipoint object. """ xy = geoseries.polygons.xy polygon_offsets = geoseries.polygons.ring_offset.take( geoseries.polygons.part_offset.take(geoseries.polygons.geometry_offset) ) # Drop the endpoint from all polygons return cuspatial.GeoSeries.from_multipoints_xy(xy, polygon_offsets) def _multipoints_from_geometry(geoseries): """Wrapper function that converts any homogeneous geoseries into a geoseries of multipoints.""" if geoseries.column_type == ColumnType.POINT: return _multipoints_from_points(geoseries) elif geoseries.column_type == ColumnType.MULTIPOINT: return geoseries elif geoseries.column_type == ColumnType.LINESTRING: return _multipoints_from_linestrings(geoseries) elif geoseries.column_type == ColumnType.POLYGON: return _multipoints_from_polygons(geoseries) else: raise NotImplementedError( "Cannot convert type {} to multipoints".format(geoseries.type) ) def _points_from_linestrings(geoseries): """Convert a geoseries of linestrings into a geoseries of points. The length of the result is equal to the sum of the lengths of the linestrings in the original geoseries.""" return cuspatial.GeoSeries.from_points_xy(geoseries.lines.xy) def _points_from_polygons(geoseries): """Convert a geoseries of linestrings into a geoseries of points. The length of the result is equal to the sum of the lengths of the polygons in the original geoseries.""" return cuspatial.GeoSeries.from_points_xy(geoseries.polygons.xy) def _points_from_geometry(geoseries): """Wrapper function that converts any homogeneous geoseries into a geoseries of points.""" if geoseries.column_type == ColumnType.POINT: return geoseries elif geoseries.column_type == ColumnType.LINESTRING: return _points_from_linestrings(geoseries) elif geoseries.column_type == ColumnType.POLYGON: return _points_from_polygons(geoseries) else: raise NotImplementedError( "Cannot convert type {} to points".format(geoseries.type) ) def _linestring_to_boundary(geoseries): """Convert a geoseries of linestrings to a geoseries of multipoints containing only the start and end of the linestrings.""" x = geoseries.lines.x y = geoseries.lines.y starts = geoseries.lines.part_offset.take(geoseries.lines.geometry_offset) ends = (starts - 1)[1:] starts = starts[:-1] points_x = cudf.DataFrame( { "starts": x[starts].reset_index(drop=True), "ends": x[ends].reset_index(drop=True), } ).interleave_columns() points_y = cudf.DataFrame( { "starts": y[starts].reset_index(drop=True), "ends": y[ends].reset_index(drop=True), } ).interleave_columns() xy = cudf.DataFrame({"x": points_x, "y": points_y}).interleave_columns() mpoints = cp.arange(len(starts) + 1) * 2 return cuspatial.GeoSeries.from_multipoints_xy(xy, mpoints) def _polygon_to_boundary(geoseries): """Convert a geoseries of polygons to a geoseries of linestrings or multilinestrings containing only the exterior and interior boundaries of the polygons.""" xy = geoseries.polygons.xy parts = geoseries.polygons.part_offset.take( geoseries.polygons.geometry_offset ) rings = geoseries.polygons.ring_offset return cuspatial.GeoSeries.from_linestrings_xy( xy, rings, parts, ) def _is_complex(geoseries): """Returns True if the GeoSeries contains non-point features that need to be reconstructed after basic predicates have computed.""" if len(geoseries.polygons.xy) > 0: return True if len(geoseries.lines.xy) > 0: return True if len(geoseries.multipoints.xy) > 0: return True return False def _open_polygon_rings(geoseries): """Converts a geoseries of polygons into a geoseries of linestrings by opening the rings of each polygon.""" x = geoseries.polygons.x y = geoseries.polygons.y parts = geoseries.polygons.part_offset.take( geoseries.polygons.geometry_offset ) rings_mask = geoseries.polygons.ring_offset - 1 rings_mask[0] = 0 mask = _true_series(len(x)) mask[rings_mask[1:]] = False x = x[mask] y = y[mask] xy = cudf.DataFrame({"x": x, "y": y}).interleave_columns() rings = geoseries.polygons.ring_offset - cp.arange(len(rings_mask)) return cuspatial.GeoSeries.from_linestrings_xy( xy, rings, parts, ) def _points_and_lines_to_multipoints(geoseries, offsets): # TODO: This modification drops linestrings which are not used # in geopandas intersection results for contains. """Converts a geoseries of points and lines into a geoseries of multipoints. Given a geoseries of points and lines, this function will return a geoseries of multipoints. The multipoints will contain the points and lines in the same order as the original geoseries. The offsets parameter groups the points and lines into multipoints. The offsets parameter must be a list of integers that contains the offsets of the multipoints in the original geoseries. A group of four points and lines can be arranged into four sets of multipoints depending on the offset used: >>> import cuspatial >>> from cuspatial.utils.binpred_utils import ( ... _points_and_lines_to_multipoints ... ) >>> from shapely.geometry import Point, LineString >>> mixed = cuspatial.GeoSeries([ ... Point(0, 0), ... LineString([(1, 1), (2, 2)]), ... Point(3, 3), ... LineString([(4, 4), (5, 5)]), ... ]) >>> offsets = [0, 4] >>> # Place all of the points and linestrings into a single >>> # multipoint >>> _points_and_lines_to_multipoints(mixed, offsets) 0 MULTIPOINT (0.00000 0.00000, 1.00000, 1.0000, ... dtype: geometry >>> offsets = [0, 1, 2, 3, 4] >>> # Place each point and linestring into its own multipoint >>> _points_and_lines_to_multipoints(mixed, offsets) 0 MULTIPOINT (0.00000 0.00000) 1 MULTIPOINT (1.00000, 1.00000, 2.00000, 2.00000) 2 MULTIPOINT (3.00000 3.00000) 3 MULTIPOINT (4.00000, 4.00000, 5.00000, 5.00000) dtype: geometry >>> offsets = [0, 2, 4] >>> # Split the points and linestrings into two multipoints >>> _points_and_lines_to_multipoints(mixed, offsets) 0 MULTIPOINT (0.00000 0.00000, 1.00000, 1.0000, ... 1 MULTIPOINT (3.00000 3.00000, 4.00000, 4.0000, ... dtype: geometry """ points_mask = geoseries.feature_types == Feature_Enum.POINT.value lines_mask = geoseries.feature_types == Feature_Enum.LINESTRING.value if (points_mask + lines_mask).sum() != len(geoseries): raise ValueError("Geoseries must contain only points and lines") points = geoseries[points_mask] lines = geoseries[lines_mask] points_offsets = _zero_series(len(geoseries)) points_offsets[points_mask] = 1 lines_series = geoseries[lines_mask] lines_sizes = lines_series.sizes xy = _zero_series(len(points.points.xy) + len(lines.lines.xy)) sizes = _zero_series(len(geoseries)) if (lines_sizes != 0).all(): lines_sizes.index = points_offsets[lines_mask].index points_offsets[lines_mask] = lines_series.sizes.values sizes[lines_mask] = lines.sizes.values * 2 sizes[points_mask] = 2 # TODO Inevitable host device copy points_xy_mask = cp.array(np.repeat(points_mask, sizes.values_host)) xy.iloc[points_xy_mask] = points.points.xy.reset_index(drop=True) xy.iloc[~points_xy_mask] = lines.lines.xy.reset_index(drop=True) collected_offsets = cudf.concat( [cudf.Series([0]), sizes.cumsum()] ).reset_index(drop=True)[offsets] result = cuspatial.GeoSeries.from_multipoints_xy( xy, collected_offsets // 2 ) return result def _multipoints_is_degenerate(geoseries): """Only tests if the first two points are degenerate.""" offsets = geoseries.multipoints.geometry_offset[:-1] sizes_mask = geoseries.sizes > 1 x1 = geoseries.multipoints.x[offsets[sizes_mask]] x2 = geoseries.multipoints.x[offsets[sizes_mask] + 1] y1 = geoseries.multipoints.y[offsets[sizes_mask]] y2 = geoseries.multipoints.y[offsets[sizes_mask] + 1] result = _false_series(len(geoseries)) is_degenerate = ( x1.reset_index(drop=True) == x2.reset_index(drop=True) ) & (y1.reset_index(drop=True) == y2.reset_index(drop=True)) result[sizes_mask] = is_degenerate.reset_index(drop=True) return result def _pli_features_rebuild_offsets(pli, features): """Takes a modified pairwise_linestring_intersection (_pli) result (specifically the first two elements of its result tuple: `(offsets, GeoSeries)` and returns a new `offsets` buffer that corresponds with the items in the GeoSeries. The GeoSeries in this call is modified from the original pairwise_linestring_intersection result because it must be a homogeneous GeoSeries, where the result of pairwise-linestring-intersection is a mixed GeoSeries containing Points and LineStrings. The original offsets buffer at `pli[0]` refers to the geometry pair from which the feature intersections from `pli[1]` were computed. The new offsets buffer specifies the same thing, but now accounts for the missing values (either Points or LineStrings) that are present in `pli[1]` but missing in the `features` argument. See the docs for `_pli_points_to_multipoints` and `_pli_lines_to_multipoints` for the rest of the explanation. """ in_sizes = ( features.sizes if len(features) > 0 else _zero_series(len(pli[0]) - 1) ) offsets = cudf.Series(pli[0]) offset_sizes = offsets[1:].reset_index(drop=True) - offsets[ :-1 ].reset_index(drop=True) in_indices = offset_sizes.index.repeat(offset_sizes) if len(in_indices) == 0: return _zero_series(len(pli[0])) # Just replacing the indices from the feature series with # the corresponding indices that are specified by the offsets buffer. # This is because cudf.Series.replace is extremely slow. in_sizes_df = in_sizes.reset_index() in_sizes_df.columns = ["index", "sizes"] sizes_replacement_series = cudf.Series(in_indices).reset_index() sizes_replacement_series.columns = ["index", "new_index"] new_in_sizes_index = in_sizes_df.merge( sizes_replacement_series, on="index" ) in_sizes.index = new_in_sizes_index.sort_values("index")["new_index"] # Recompute the offsets for the new series grouped_sizes = in_sizes.groupby(level=0).sum().sort_index() out_sizes = _zero_series(len(pli[0]) - 1) out_sizes.iloc[grouped_sizes.index] = grouped_sizes offsets = cudf.concat([cudf.Series([0]), out_sizes.cumsum()]) return offsets def _pli_points_to_multipoints(pli): """Takes a tuple (specifically the first two values returned by pairwise_linestring_intersection (pli)) with offsets in position 0 and a mixed GeoSeries in position 1. Extracts the points from the mixed GeoSeries such that one MultiPoint is returned for all of the Point rows that fall within each of the ranges specified by the offsets argument. Example ------- pli = ( cudf.Series([0, 2, 4, 6]), cuspatial.GeoSeries([ Point(0, 0), LineString([(1, 1), (2, 2)]), Point(3, 3), Point(4, 4), Point(5, 5), LineString([(6, 6), (7, 7)]), ]) ) multipoints_from_points = _pli_points_to_multipoints(pli) print(multipoints_from_points) 0 MULTIPOINT (0.00000 0.00000) 1 MULTIPOINT (3.00000 3.00000, 4.00000 4.00000) 2 MULTIPOINT (5.00000 5.00000) dtype: geometry """ points = pli[1][pli[1].feature_types == Feature_Enum.POINT.value] offsets = _pli_features_rebuild_offsets(pli, points) xy = ( points.points.xy if len(points.points.xy) > 0 else cudf.Series([], dtype=cp.float64) ) multipoints = cuspatial.GeoSeries.from_multipoints_xy(xy, offsets) return multipoints def _pli_lines_to_multipoints(pli): """Works identically to `_pli_points_to_multipoints`, converting the mixed GeoSeries result of `pairwise_linestring_intersection` (pli) to a GeoSeries of MultiPoints using only the points contained in the LineString intersections from the result of pairwise_linestring_intersection.""" lines = pli[1][pli[1].feature_types == Feature_Enum.LINESTRING.value] offsets = _pli_features_rebuild_offsets(pli, lines) xy = ( lines.lines.xy if len(lines.lines.xy) > 0 else cudf.Series([], dtype=cp.float64) ) multipoints = cuspatial.GeoSeries.from_multipoints_xy(xy, offsets) return multipoints
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/test_geodataframe.py
# Copyright (c) 2020-2021, NVIDIA CORPORATION. import geopandas as gpd import numpy as np import pandas as pd import pytest from geopandas.testing import assert_geodataframe_equal from shapely.affinity import rotate from shapely.geometry import ( LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, ) import cudf import cuspatial np.random.seed(0) def random_polygon(distance_from_origin): outer = Point(distance_from_origin * 2, 0).buffer(1) inners = [] for i in range(np.random.randint(1, 4)): inner = Point(distance_from_origin + i * 0.1, 0).buffer(0.01) inners.append(inner) together = Polygon(outer, inners) result = rotate(together, np.random.random() * 2 * np.pi, use_radians=True) return result def random_multipolygon(size): polygons = [] for i in range(size): polygons.append(random_polygon(i)) result = MultiPolygon(polygons) return result def generator(size, has_z=False): obj_type = np.random.randint(1, 7) if obj_type == 1: return Point(np.random.random(2)) else: if obj_type == 2: points = np.random.random(size * 2).reshape(size, 2) return MultiPoint(points) elif obj_type == 3: points = np.random.random(size * 2).reshape(size, 2) return LineString(points) elif obj_type == 4: num_lines = np.random.randint(3, np.ceil(np.sqrt(size)) + 3) points = np.random.random(num_lines * size * 2).reshape( num_lines, size, 2 ) return MultiLineString(tuple(points)) elif obj_type == 5: return random_polygon(size) elif obj_type == 6: return random_multipolygon(size) def assert_eq_point(p1, p2): assert type(p1) == type(p2) assert p1.x == p2.x assert p1.y == p2.y assert p1.has_z == p2.has_z if p1.has_z: assert p1.z == p2.z assert True def assert_eq_multipoint(p1, p2): assert type(p1) == type(p2) assert len(p1) == len(p2) for i in range(len(p1)): assert_eq_point(p1[i], p2[i]) def assert_eq_polygon(p1, p2): if not p1.equals(p2): raise ValueError def assert_eq_multipolygon(p1, p2): if not p1.equals(p2): raise ValueError def assert_eq_geo_df(geo1, geo2): if type(geo1) != type(geo2): assert TypeError assert geo1.columns.equals(geo2.columns) for col in geo1.columns: if geo1[col].dtype == "geometry": assert geo1[col].equals(geo2[col]) else: pd.testing.assert_series_equal(geo1[col], geo2[col]) def test_select_multiple_columns(gpdf): cugpdf = cuspatial.from_geopandas(gpdf) pd.testing.assert_frame_equal( cugpdf[["geometry", "key"]].to_pandas(), gpdf[["geometry", "key"]] ) def test_type_persistence(gpdf): cugpdf = cuspatial.from_geopandas(gpdf) assert type(cugpdf["geometry"]) == cuspatial.GeoSeries def test_interleaved_point(gpdf, polys): cugpdf = cuspatial.from_geopandas(gpdf) cugs = cugpdf["geometry"] gs = gpdf["geometry"] pd.testing.assert_series_equal( cugs.points.x.to_pandas().reset_index(drop=True), gs[gs.type == "Point"].x.reset_index(drop=True), ) pd.testing.assert_series_equal( cugs.points.y.to_pandas().reset_index(drop=True), gs[gs.type == "Point"].y.reset_index(drop=True), ) def test_interleaved_multipoint(gpdf, polys): cugpdf = cuspatial.from_geopandas(gpdf) cugs = cugpdf["geometry"] gs = gpdf["geometry"] cudf.testing.assert_series_equal( cudf.Series.from_arrow(cugs.multipoints.x.to_arrow()), cudf.Series( np.array( [ np.array(p.__geo_interface__["coordinates"])[:, 0] for p in gs[gs.type == "MultiPoint"] ] ).flatten() ), ) cudf.testing.assert_series_equal( cudf.Series.from_arrow(cugs.multipoints.y.to_arrow()), cudf.Series( np.array( [ np.array(p.__geo_interface__["coordinates"])[:, 1] for p in gs[gs.type == "MultiPoint"] ] ).flatten() ), ) def test_interleaved_lines(gpdf, polys): cugpdf = cuspatial.from_geopandas(gpdf) cugs = cugpdf["geometry"] cudf.testing.assert_series_equal( cudf.Series.from_arrow(cugs.lines.x.to_arrow()), cudf.Series( np.array([range(11, 34, 2)]).flatten(), dtype="float64", ), ) cudf.testing.assert_series_equal( cudf.Series.from_arrow(cugs.lines.y.to_arrow()), cudf.Series( np.array([range(12, 35, 2)]).flatten(), dtype="float64", ), ) def test_interleaved_polygons(gpdf, polys): cugpdf = cuspatial.from_geopandas(gpdf) cugs = cugpdf["geometry"] cudf.testing.assert_series_equal( cudf.Series.from_arrow(cugs.polygons.x.to_arrow()), cudf.Series(polys[:, 0], dtype="float64"), ) cudf.testing.assert_series_equal( cudf.Series.from_arrow(cugs.polygons.y.to_arrow()), cudf.Series(polys[:, 1], dtype="float64"), ) def test_to_geopandas_with_geopandas_dataset(): df = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres")) gdf = cuspatial.from_geopandas(df) assert_eq_geo_df(df, gdf.to_geopandas()) def test_to_shapely_random(): geos_list = [] for i in range(250): geo = generator(3) geos_list.append(geo) gi = gpd.GeoDataFrame( {"geometry": geos_list, "integer": range(len(geos_list))} ) cugpdf = cuspatial.from_geopandas(gi) cugpdf_back = cugpdf.to_geopandas() assert_eq_geo_df(gi, cugpdf_back) @pytest.mark.parametrize( "pre_slice", [ (slice(0, 12)), (slice(0, 10, 1)), (slice(0, 3, 1)), (slice(3, 6, 1)), (slice(6, 9, 1)), ], ) def test_pre_slice(gpdf, pre_slice): geometries = gpdf.iloc[pre_slice, :] gi = gpd.GeoDataFrame(geometries) cugpdf = cuspatial.from_geopandas(gi) cugpdf_back = cugpdf.to_geopandas() assert_eq_geo_df(gi, cugpdf_back) @pytest.mark.parametrize( "post_slice", [ (slice(0, 12)), (slice(0, 10, 1)), (slice(0, 3, 1)), (slice(3, 6, 1)), (slice(6, 9, 1)), ], ) def test_post_slice(gpdf, post_slice): geometries = gpdf gi = gpd.GeoDataFrame(geometries) cugpdf = cuspatial.from_geopandas(gi) cugpdf_back = cugpdf.to_geopandas() assert_eq_geo_df(gi[post_slice], cugpdf_back[post_slice]) @pytest.mark.parametrize( "inline_slice", [ (slice(0, 12)), (slice(0, 10, 1)), (slice(0, 3, 1)), (slice(3, 6, 1)), (slice(6, 9, 1)), ], ) def test_inline_slice(gpdf, inline_slice): gi = gpd.GeoDataFrame(gpdf) cugpdf = cuspatial.from_geopandas(gi) assert_eq_geo_df(gi[inline_slice], cugpdf[inline_slice].to_pandas()) def test_slice_column_order(gpdf): gi = gpd.GeoDataFrame(gpdf) cugpdf = cuspatial.from_geopandas(gi) slice_df = cuspatial.core.geodataframe.GeoDataFrame( { "geo1": cugpdf["geometry"], "data1": np.arange(len(cugpdf)), "geo2": cugpdf["geometry"], "data2": np.arange(len(cugpdf)), } ) slice_gi = slice_df.to_pandas() assert_eq_geo_df(slice_gi[0:5], slice_df[0:5].to_pandas()) slice_df = cuspatial.core.geodataframe.GeoDataFrame( { "data1": np.arange(len(cugpdf)), "geo1": cugpdf["geometry"], "geo2": cugpdf["geometry"], "data2": np.arange(len(cugpdf)), } ) slice_gi = slice_df.to_pandas() assert_eq_geo_df(slice_gi[5:], slice_df[5:].to_pandas()) slice_df = cuspatial.core.geodataframe.GeoDataFrame( { "data1": np.arange(len(cugpdf)), "geo4": cugpdf["geometry"], "data2": np.arange(len(cugpdf)), "geo3": cugpdf["geometry"], "data3": np.arange(len(cugpdf)), "geo2": cugpdf["geometry"], "geo1": cugpdf["geometry"], "data4": np.arange(len(cugpdf)), "data5": np.arange(len(cugpdf)), "data6": np.arange(len(cugpdf)), } ) slice_gi = slice_df.to_pandas() assert_eq_geo_df(slice_gi[5:], slice_df[5:].to_pandas()) @pytest.mark.parametrize( "df_boolmask", [ np.repeat(True, 12), np.repeat((np.repeat(True, 3), np.repeat(False, 3)), 2).flatten(), np.repeat(False, 12), np.repeat((np.repeat(False, 3), np.repeat(True, 3)), 2).flatten(), np.repeat([True, False], 6).flatten(), ], ) def test_boolmask(gpdf, df_boolmask): geometries = gpdf gi = gpd.GeoDataFrame(geometries) cugpdf = cuspatial.from_geopandas(gi) cugpdf_back = cugpdf.to_geopandas() assert_eq_geo_df(gi[df_boolmask], cugpdf_back[df_boolmask]) def test_memory_usage(gs): assert gs.memory_usage() == 224 host_dataframe = gpd.read_file( gpd.datasets.get_path("naturalearth_lowres") ) gpu_dataframe = cuspatial.from_geopandas(host_dataframe) # The df size is 8kb of cudf rows and 217kb of the geometry column assert gpu_dataframe.memory_usage().sum() == 224945 def test_from_dict(): p1 = Point([0, 1]) p2 = Point([2, 3]) p3 = Point([4, 5]) p4 = MultiPoint([[6, 7], [8, 9]]) gi = gpd.GeoDataFrame({"geometry": [p1, p2, p3, p4]}) cu = cuspatial.GeoDataFrame({"geometry": [p1, p2, p3, p4]}) assert_eq_geo_df(gi, cu.to_geopandas()) def test_from_dict2(): points = { "a": [Point(0, 1), Point(2, 3)], "b": [MultiPoint([(4, 5), (6, 7)]), Point(8, 9)], } gpu_points_df = cuspatial.GeoDataFrame(points) assert (gpu_points_df["a"].points.xy == cudf.Series([0, 1, 2, 3])).all() assert (gpu_points_df["b"].points.xy == cudf.Series([8, 9])).all() assert ( gpu_points_df["b"].multipoints.xy == cudf.Series([4, 5, 6, 7]) ).all() def test_from_gp_geoseries_dict(): gp_geo_series = { "gpa": gpd.GeoSeries([Point(0, 1)]), "gpb": gpd.GeoSeries([MultiPoint([(2, 3), (4, 5)])]), } gp_df = gpd.GeoDataFrame(gp_geo_series) gpu_gp_df = cuspatial.GeoDataFrame(gp_geo_series) assert_eq_geo_df(gp_df, gpu_gp_df.to_geopandas()) gp_df2 = gpd.GeoDataFrame({"gpdfa": gp_df["gpb"], "gpdfb": gp_df["gpa"]}) gpdf = cuspatial.GeoDataFrame( {"gpdfa": gpu_gp_df["gpb"], "gpdfb": gpu_gp_df["gpa"]} ) assert_eq_geo_df(gp_df2, gpdf.to_geopandas()) # Randomly collects 5 of 6 gpdf columns, slices them, and tries # to create a new DataFrame from a dict based on those columns. @pytest.mark.parametrize( "dict_slice", [ (slice(0, 12)), (slice(0, 10, 1)), (slice(0, 3, 1)), (slice(3, 6, 1)), (slice(6, 9, 1)), ], ) def test_from_dict_slices(gpdf, dict_slice): sliced = gpdf[dict_slice] sliced_dict = { char: sliced[col] for char, col in zip( np.array([*"abcdef"])[np.random.randint(0, 5, 5)], sliced.columns ) } gpdf = gpd.GeoDataFrame(sliced_dict) cugpdf = cuspatial.GeoDataFrame(sliced_dict) assert_eq_geo_df(gpdf, cugpdf.to_geopandas()) def test_from_dict_with_list(): dict_with_lists = { "a": [1, 2, 3, 4], "geometry": [ Point(0, 1), Point(2, 3), MultiPoint([(4, 5), (6, 7)]), Point(8, 9), ], "c": [*"abcd"], } assert_eq_geo_df( gpd.GeoDataFrame(dict_with_lists), cuspatial.GeoDataFrame(dict_with_lists).to_geopandas(), ) @pytest.mark.parametrize("level", [None, 0, 1]) @pytest.mark.parametrize("drop", [False, True]) @pytest.mark.parametrize("inplace", [False, True]) @pytest.mark.parametrize("col_level", [0, 1]) @pytest.mark.parametrize("col_fill", ["", "some_lv"]) def test_reset_index(level, drop, inplace, col_level, col_fill): if not drop and inplace: pytest.skip( "For exception checks, see " "test_reset_index_dup_level_name_exceptions" ) midx = pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1), ("b", 2)]) gpdf = gpd.GeoDataFrame( { "geometry": [ Point(0, 1), Point(2, 3), MultiPoint([(4, 5), (6, 7)]), Point(8, 9), ], "a": [*"abcd"], }, index=midx, ) gdf = cuspatial.from_geopandas(gpdf) expected = gpdf.reset_index(level, drop, inplace, col_level, col_fill) got = gdf.reset_index(level, drop, inplace, col_level, col_fill) if inplace: expected = gpdf got = gdf pd.testing.assert_frame_equal(expected, got.to_pandas()) def test_cudf_dataframe_init(): df = cudf.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) gdf = cuspatial.GeoDataFrame(df) assert_eq_geo_df(gdf.to_pandas(), df.to_pandas()) def test_apply_boolean_mask(gpdf, mask_factory): mask = mask_factory(len(gpdf)) expected = gpdf[mask] d_gpdf = cuspatial.from_geopandas(gpdf) got = d_gpdf[mask] assert_geodataframe_equal(expected, got.to_geopandas()) def test_apply_boolean_mask_length_one(mask_factory): geodf = gpd.GeoDataFrame({"geometry": [Point(0, 0)]}) mask = mask_factory(len(geodf)) expected = geodf[mask] d_geodf = cuspatial.from_geopandas(geodf) got = d_geodf[mask] assert_geodataframe_equal(expected, got.to_geopandas())
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/test_none.py
# Copyright (c) 2022 NVIDIA CORPORATION. import geopandas as gpd import pandas as pd from shapely.geometry import Point, Polygon import cuspatial def test_got_from_geopandas(): expected = gpd.GeoSeries([None]) got = cuspatial.from_geopandas(expected) pd.testing.assert_series_equal(expected, got.to_geopandas()) def test_mix_from_geopandas(): expected = gpd.GeoSeries([None, Point(0, 1), None]) got = cuspatial.from_geopandas(expected) pd.testing.assert_series_equal(expected, got.to_geopandas()) def test_first_from_geopandas(): expected = gpd.GeoSeries([Point(0, 1), None, None]) got = cuspatial.from_geopandas(expected) pd.testing.assert_series_equal(expected, got.to_geopandas()) def test_last_from_geopandas(): expected = gpd.GeoSeries([None, None, Point(0, 1)]) got = cuspatial.from_geopandas(expected) pd.testing.assert_series_equal(expected, got.to_geopandas()) def test_middle_from_geopandas(): expected = gpd.GeoSeries( [ Polygon(((-8, -8), (-8, 8), (8, 8), (8, -8))), Polygon(((-2, -2), (-2, 2), (2, 2), (2, -2))), None, Polygon(((-10, -2), (-10, 2), (-6, 2), (-6, -2))), None, Polygon(((-2, 8), (-2, 12), (2, 12), (2, 8))), Polygon(((6, 0), (8, 2), (10, 0), (8, -2))), None, Polygon(((-2, -8), (-2, -4), (2, -4), (2, -8))), ] ) got = cuspatial.from_geopandas(expected) pd.testing.assert_series_equal(expected, got.to_geopandas())
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/test_from_geopandas.py
# Copyright (c) 2020-2021, NVIDIA CORPORATION. import geopandas as gpd import pandas as pd from shapely.geometry import ( LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, ) import cudf import cuspatial def test_geobuffer_len(gs): cugs = cuspatial.from_geopandas(gs) assert len(cugs._column) == 12 def test_mixed_dataframe(gs): gpdf = gpd.GeoDataFrame({"a": list(range(100, 100 + len(gs))), "b": gs}) cgdf = cuspatial.from_geopandas(gpdf) pd.testing.assert_series_equal(gpdf["a"], cgdf["a"].to_pandas()) assert gpdf["b"].equals(cgdf["b"].to_pandas()) pd.testing.assert_frame_equal(gpdf, cgdf.to_pandas()) def test_dataframe_column_access(gs): gpdf = gpd.GeoDataFrame({"a": list(range(0, len(gs))), "b": gs}) cgdf = cuspatial.from_geopandas(gpdf) assert gpdf["b"].equals(cgdf["b"].to_pandas()) def test_from_geoseries_complex(gs): cugs = cuspatial.from_geopandas(gs) assert cugs.points.xy.sum() == 18 assert cugs.lines.xy.sum() == 540 assert cugs.multipoints.xy.sum() == 36 assert cugs.polygons.xy.sum() == 7436 assert cugs._column.polygons._column.base_children[0].sum() == 15 assert ( cugs._column.polygons._column.base_children[1].base_children[0].sum() == 38 ) def test_from_geopandas_point(): gs = gpd.GeoSeries(Point(1.0, 2.0)) cugs = cuspatial.from_geopandas(gs) cudf.testing.assert_series_equal( cudf.Series(cugs.points.xy), cudf.Series([1.0, 2.0], dtype="float64") ) def test_from_geopandas_multipoint(): gs = gpd.GeoSeries(MultiPoint([(1.0, 2.0), (3.0, 4.0)])) cugs = cuspatial.from_geopandas(gs) cudf.testing.assert_series_equal( cugs.multipoints.xy, cudf.Series([1.0, 2.0, 3.0, 4.0], dtype="float64"), ) cudf.testing.assert_series_equal( cudf.Series(cugs._column.mpoints._column.base_children[0]), cudf.Series([0, 2], dtype="int32"), ) def test_from_geopandas_linestring(): gs = gpd.GeoSeries(LineString(((4.0, 3.0), (2.0, 1.0)))) cugs = cuspatial.from_geopandas(gs) cudf.testing.assert_series_equal( cugs.lines.xy, cudf.Series([4.0, 3.0, 2.0, 1.0], dtype="float64") ) cudf.testing.assert_series_equal( cudf.Series(cugs._column.lines._column.base_children[0]), cudf.Series([0, 1], dtype="int32"), ) def test_from_geopandas_multilinestring(): gs = gpd.GeoSeries( MultiLineString( ( ((1.0, 2.0), (3.0, 4.0)), ((5.0, 6.0), (7.0, 8.0)), ) ) ) cugs = cuspatial.from_geopandas(gs) cudf.testing.assert_series_equal( cugs.lines.xy, cudf.Series([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0], dtype="float64"), ) cudf.testing.assert_series_equal( cudf.Series(cugs._column.lines._column.base_children[0]), cudf.Series([0, 2], dtype="int32"), ) def test_from_geopandas_polygon(): gs = gpd.GeoSeries( Polygon( ((0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (0.0, 0.0)), ) ) cugs = cuspatial.from_geopandas(gs) cudf.testing.assert_series_equal( cugs.polygons.xy, cudf.Series([0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0], dtype="float64"), ) cudf.testing.assert_series_equal( cudf.Series(cugs._column.polygons._column.base_children[0]), cudf.Series([0, 1], dtype="int32"), ) cudf.testing.assert_series_equal( cudf.Series( cugs._column.polygons._column.base_children[1].base_children[0] ), cudf.Series([0, 1], dtype="int32"), ) def test_from_geopandas_polygon_hole(): gs = gpd.GeoSeries( Polygon( ((0.0, 0.0), (0.0, 1.0), (1.0, 0.0)), [((1.0, 1.0), (1.0, 0.0), (0.0, 0.0))], ) ) cugs = cuspatial.from_geopandas(gs) cudf.testing.assert_series_equal( cugs.polygons.xy, cudf.Series( [ 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, ], dtype="float64", ), ) cudf.testing.assert_series_equal( cudf.Series(cugs._column.polygons._column.base_children[0]), cudf.Series([0, 1], dtype="int32"), ) cudf.testing.assert_series_equal( cudf.Series( cugs._column.polygons._column.base_children[1].base_children[0] ), cudf.Series([0, 2], dtype="int32"), ) def test_from_geopandas_multipolygon(): gs = gpd.GeoSeries( MultiPolygon( [ ( ((0.0, 0.0), (0.0, 1.0), (1.0, 0.0)), [((1.0, 1.0), (1.0, 0.0), (0.0, 0.0))], ) ] ) ) cugs = cuspatial.from_geopandas(gs) cudf.testing.assert_series_equal( cugs.polygons.xy, cudf.Series( [ 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, ], dtype="float64", ), ) cudf.testing.assert_series_equal( cudf.Series(cugs._column.polygons._column.base_children[0]), cudf.Series([0, 1], dtype="int32"), ) cudf.testing.assert_series_equal( cudf.Series( cugs._column.polygons._column.base_children[1].base_children[0] ), cudf.Series([0, 2], dtype="int32"), )
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/test_cudf_integration.py
# Copyright (c) 2022 NVIDIA CORPORATION. import geopandas as gpd import numpy as np import pandas as pd import cuspatial def test_sort_index_series(gs): gs.index = np.random.permutation(len(gs)) cugs = cuspatial.from_geopandas(gs) expected = gs.sort_index() got = cugs.sort_index().to_pandas() gpd.testing.assert_geoseries_equal(got, expected) def test_sort_index_dataframe(gpdf): gpdf.index = np.random.permutation(len(gpdf)) cugpdf = cuspatial.from_geopandas(gpdf) expected = gpdf.sort_index() got = cugpdf.sort_index().to_pandas() gpd.testing.assert_geodataframe_equal(got, expected) def test_sort_values(gpdf): cugpdf = cuspatial.from_geopandas(gpdf) expected = gpdf.sort_values("random") got = cugpdf.sort_values("random").to_pandas() gpd.testing.assert_geodataframe_equal(got, expected) def test_groupby(gpdf): cugpdf = cuspatial.from_geopandas(gpdf) expected = gpdf.groupby("key")[["integer", "random"]].min().sort_index() got = ( cugpdf.groupby("key")[["integer", "random"]] .min() .sort_index() .to_pandas() ) pd.testing.assert_frame_equal(got, expected)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/conftest.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. import geopandas as gpd import numpy as np import pandas as pd import pytest from shapely.affinity import rotate from shapely.geometry import ( LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, ) @pytest.fixture def gs(): g0 = Point(-1, 0) g1 = MultiPoint(((1, 2), (3, 4))) g2 = MultiPoint(((5, 6), (7, 8))) g3 = Point(9, 10) g4 = LineString(((11, 12), (13, 14))) g5 = MultiLineString((((15, 16), (17, 18)), ((19, 20), (21, 22)))) g6 = MultiLineString((((23, 24), (25, 26)), ((27, 28), (29, 30)))) g7 = LineString(((31, 32), (33, 34))) g8 = Polygon( ((35, 36), (37, 38), (39, 40), (41, 42)), ) g9 = MultiPolygon( [ ( ((43, 44), (45, 46), (47, 48)), [((49, 50), (51, 52), (53, 54))], ), ( ((55, 56), (57, 58), (59, 60)), [((61, 62), (63, 64), (65, 66))], ), ] ) g10 = MultiPolygon( [ ( ((67, 68), (69, 70), (71, 72)), [((73, 74), (75, 76), (77, 78))], ), ( ((79, 80), (81, 82), (83, 84)), [ ((85, 86), (87, 88), (89, 90)), ((91, 92), (93, 94), (95, 96)), ], ), ] ) g11 = Polygon( ((97, 98), (99, 101), (102, 103), (101, 108)), [((106, 107), (108, 109), (110, 111), (113, 108))], ) gs = gpd.GeoSeries([g0, g1, g2, g3, g4, g5, g6, g7, g8, g9, g10, g11]) return gs @pytest.fixture def gpdf(gs): int_col = list(range(len(gs))) random_col = int_col np.random.shuffle(random_col) str_col = [str(x) for x in int_col] key_col = np.repeat(np.arange(4), len(int_col) // 4) np.random.shuffle(key_col) result = gpd.GeoDataFrame( { "geometry": gs, "integer": int_col, "string": str_col, "random": random_col, "key": key_col, } ) result["float"] = result["integer"].astype("float64") return result @pytest.fixture def polys(): return np.array( ( (35, 36), (37, 38), (39, 40), (41, 42), (35, 36), (43, 44), (45, 46), (47, 48), (43, 44), (49, 50), (51, 52), (53, 54), (49, 50), (55, 56), (57, 58), (59, 60), (55, 56), (61, 62), (63, 64), (65, 66), (61, 62), (67, 68), (69, 70), (71, 72), (67, 68), (73, 74), (75, 76), (77, 78), (73, 74), (79, 80), (81, 82), (83, 84), (79, 80), (85, 86), (87, 88), (89, 90), (85, 86), (91, 92), (93, 94), (95, 96), (91, 92), (97, 98), (99, 101), (102, 103), (101, 108), (97, 98), (106, 107), (108, 109), (110, 111), (113, 108), (106, 107), ) ) @pytest.fixture def gs_sorted(gs): result = pd.concat( [ gs[gs.type == "Point"], gs[gs.type == "MultiPoint"], gs[gs.type == "LineString"], gs[gs.type == "MultiLineString"], gs[gs.type == "Polygon"], gs[gs.type == "MultiPolygon"], ] ) return result.reset_index(drop=True) @pytest.fixture def point_generator(): """Generator for n points. Usage: p=generator(n)""" rstate = np.random.RandomState(0) def generator(n): for _ in range(n): yield Point(rstate.uniform(0, 1), rstate.uniform(0, 1)) return generator @pytest.fixture def multipoint_generator(point_generator): """Generator for n multipoints. Usage: mp=generator(n, max_num_points)""" rstate = np.random.RandomState(0) def generator(n, max_num_geometries): for _ in range(n): num_geometries = rstate.randint(1, max_num_geometries) yield MultiPoint([*point_generator(num_geometries)]) return generator @pytest.fixture def linestring_generator(point_generator): """Generator for n linestrings. Usage: ls=generator(n, max_num_segments)""" rstate = np.random.RandomState(0) def generator(n, max_num_segments): for _ in range(n): num_segments = rstate.randint(1, max_num_segments) yield LineString([*point_generator(num_segments + 1)]) return generator @pytest.fixture def multilinestring_generator(linestring_generator): """Generator for n multilinestrings. Usage: mls=generator(n, max_num_lines, max_num_segments) """ rstate = np.random.RandomState(0) def generator(n, max_num_geometries, max_num_segments): for _ in range(n): num_geometries = rstate.randint(1, max_num_geometries) yield MultiLineString( [*linestring_generator(num_geometries, max_num_segments)] ) return generator @pytest.fixture def simple_polygon_generator(): """Generator for polygons with no interior ring. Usage: polygon_generator(n, distance_from_origin, radius) """ rstate = np.random.RandomState(0) def generator(n, distance_from_origin, radius=1.0): for _ in range(n): outer = Point(distance_from_origin * 2, 0).buffer(radius) circle = Polygon(outer) yield rotate(circle, rstate.random() * 2 * np.pi, use_radians=True) return generator @pytest.fixture def polygon_generator(): """Generator for complex polygons. Each polygon will have 1-4 randomly rotated interior rings. Each polygon is a circle, with very small inner rings located in a spiral around its center. Usage: poly=generator(n, distance_from_origin, radius) """ rstate = np.random.RandomState(0) def generator(n, distance_from_origin, radius=1.0): for _ in range(n): outer = Point(distance_from_origin * 2, 0).buffer(radius) inners = [] for i in range(rstate.randint(1, 4)): inner = Point(distance_from_origin + i * 0.1, 0).buffer( 0.01 * radius ) inners.append(inner) together = Polygon(outer, inners) yield rotate( together, rstate.random() * 2 * np.pi, use_radians=True ) return generator @pytest.fixture def multipolygon_generator(polygon_generator): """Generator for multi complex polygons. Usage: multipolygon_generator(n, max_per_multi) """ rstate = np.random.RandomState(0) def generator(n, max_per_multi, distance_from_origin, radius): for _ in range(n): num_polygons = rstate.randint(1, max_per_multi) yield MultiPolygon( [ *polygon_generator( num_polygons, distance_from_origin, radius ) ] ) return generator @pytest.fixture def slice_twenty(): return [ slice(0, 4), slice(4, 8), slice(8, 12), slice(12, 16), slice(16, 20), ] @pytest.fixture(params=["MaskOdd", "MaskEven", "MaskNone", "MaskAll"]) def mask_factory(request): kind = request.param def factory(length): mask = pd.Series([False] * length) if kind == "MaskOdd": mask[0::2] = True elif kind == "MaskEven": mask[1::2] = True elif kind == "MaskNone": pass elif kind == "MaskAll": mask[:] = True return mask return factory @pytest.fixture def naturalearth_cities(): return gpd.read_file(gpd.datasets.get_path("naturalearth_cities")) @pytest.fixture def naturalearth_lowres(): return gpd.read_file(gpd.datasets.get_path("naturalearth_lowres")) @pytest.fixture(scope="session") def predicate_passes(): """Used by test_binpred_test_dispatch.py to store test results.""" data = {} return data @pytest.fixture(scope="session") def predicate_fails(): """Used by test_binpred_test_dispatch.py to store test results.""" data = {} return data @pytest.fixture(scope="session") def feature_passes(): """Used by test_binpred_test_dispatch.py to store test results.""" data = {} return data @pytest.fixture(scope="session") def feature_fails(): """Used by test_binpred_test_dispatch.py to store test results.""" data = {} return data
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/test_geocolumn_accessor.py
# Copyright 2022 NVIDIA Corporation import cupy as cp import geopandas as gpd import pytest from shapely.geometry import ( LineString, MultiLineString, MultiPoint, MultiPolygon, Polygon, ) import cuspatial @pytest.mark.parametrize( "range, expected", [[slice(0, 3), [0, 3, 4, 5]], [slice(3, 6), [0, 30, 40, 41]]], ) def test_GeoColumnAccessor_polygon_offset(range, expected): gpdf = cuspatial.from_geopandas( gpd.read_file(gpd.datasets.get_path("naturalearth_lowres")) ) shorter = gpdf[range]["geometry"] expected = cp.array(expected) got = shorter.polygons.geometry_offset assert cp.array_equal(got, expected) @pytest.mark.parametrize( "range, expected", [ [[0, 2], [0, 2, 5]], [[0, 1, 2], [0, 2, 4, 7]], [[2, 4], [0, 3, 6]], [[4, 5], [0, 3, 5]], [[4, 3, 2], [0, 3, 5, 8]], ], ) def test_multipoint(range, expected): gs = cuspatial.from_geopandas( gpd.GeoSeries( [ MultiPoint([(0, 1), (0, 2)]), MultiPoint([(0, 3), (0, 4)]), MultiPoint([(0, 5), (0, 6), (0, 7)]), MultiPoint([(0, 8), (0, 9)]), MultiPoint([(0, 10), (0, 11), (0, 12)]), MultiPoint([(0, 13), (0, 14)]), ] ) ) t1 = gs[range] got = t1.multipoints.geometry_offset expected = cp.array(expected) assert cp.array_equal(got, expected) @pytest.mark.parametrize( "range, expected", [ [[0, 2], [0, 1, 3]], [[0, 1, 2], [0, 1, 2, 4]], [[2, 4], [0, 2, 4]], [[4, 5], [0, 2, 3]], [[4, 3, 2], [0, 2, 3, 5]], ], ) def test_multilines_geometry_offset(range, expected): gs = cuspatial.from_geopandas( gpd.GeoSeries( [ LineString([(0, 1), (0, 2)]), LineString([(0, 3), (0, 4)]), MultiLineString( [ LineString([(0, 5), (0, 6)]), LineString([(0, 7), (0, 8)]), ] ), LineString([(0, 9), (0, 10)]), MultiLineString( [ LineString([(0, 11), (0, 12)]), LineString([(0, 13), (0, 14)]), ] ), LineString([(0, 15), (0, 16)]), ] ) ) t1 = gs[range] got = t1.lines.geometry_offset expected = cp.array(expected) assert cp.array_equal(got, expected) @pytest.mark.parametrize( "range, expected", [ [[0, 2], [0, 2, 4, 6]], [[0, 1, 2], [0, 2, 4, 6, 8]], [[2, 4], [0, 2, 4, 7, 9]], [[4, 5], [0, 3, 5, 7]], [[4, 3, 2], [0, 3, 5, 7, 9, 11]], ], ) def test_multilines_part_offset(range, expected): gs = cuspatial.from_geopandas( gpd.GeoSeries( [ LineString([(0, 1), (0, 2)]), LineString([(0, 3), (0, 4)]), MultiLineString( [ LineString([(0, 5), (0, 6)]), LineString([(0, 7), (0, 8)]), ] ), LineString([(0, 9), (0, 10)]), MultiLineString( [ LineString([(0, 11), (0, 12), (0, 13)]), LineString([(0, 14), (0, 15)]), ] ), LineString([(0, 16), (0, 17)]), ] ) ) t1 = gs[range] got = t1.lines.part_offset expected = cp.array(expected) assert cp.array_equal(got, expected) @pytest.mark.parametrize( "range, expected", [ [[0, 2], [0, 1, 3]], [[0, 1, 2], [0, 1, 2, 4]], [[2, 4], [0, 2, 4]], [[4, 5], [0, 2, 3]], [[4, 3, 2], [0, 2, 3, 5]], ], ) def test_multipolygons_geometry_offset(range, expected): gs = cuspatial.from_geopandas( gpd.GeoSeries( [ Polygon([(0, 1), (0, 2), (0, 18)]), Polygon([(0, 3), (0, 4), (0, 19)]), MultiPolygon( [ Polygon([(0, 5), (0, 6), (0, 20)]), Polygon([(0, 7), (0, 8), (0, 21)]), ] ), Polygon([(0, 9), (0, 10), (0, 22)]), MultiPolygon( [ Polygon([(0, 11), (0, 12), (0, 13), (0, 22)]), Polygon([(0, 14), (0, 15), (0, 23)]), ] ), Polygon([(0, 16), (0, 17), (0, 24)]), ] ) ) t1 = gs[range] got = t1.polygons.geometry_offset expected = cp.array(expected) assert cp.array_equal(got, expected) @pytest.mark.parametrize( "range, expected", [ [[0, 2], [0, 1, 2, 3]], [[0, 1, 2], [0, 1, 2, 3, 4]], [[2, 4], [0, 1, 2, 3, 4]], [[4, 5], [0, 1, 2, 3]], [[4, 3, 2], [0, 1, 2, 3, 4, 5]], ], ) def test_multipolygons_part_offset(range, expected): gs = cuspatial.from_geopandas( gpd.GeoSeries( [ Polygon([(0, 1), (0, 2), (0, 18)]), Polygon([(0, 3), (0, 4), (0, 19)]), MultiPolygon( [ Polygon([(0, 5), (0, 6), (0, 20)]), Polygon([(0, 7), (0, 8), (0, 21)]), ] ), Polygon([(0, 9), (0, 10), (0, 22)]), MultiPolygon( [ Polygon([(0, 11), (0, 12), (0, 13), (0, 22)]), Polygon([(0, 14), (0, 15), (0, 23)]), ] ), Polygon([(0, 16), (0, 17), (0, 24)]), ] ) ) t1 = gs[range] got = t1.polygons.part_offset expected = cp.array(expected) assert cp.array_equal(got, expected) @pytest.mark.parametrize( "range, expected", [ [[0, 2], [0, 4, 8, 12]], [[0, 1, 2], [0, 4, 8, 12, 16]], [[2, 4], [0, 4, 8, 13, 17]], [[4, 5], [0, 5, 9, 13]], [[4, 3, 2], [0, 5, 9, 13, 17, 21]], ], ) def test_multipolygons_ring_offset(range, expected): gs = cuspatial.from_geopandas( gpd.GeoSeries( [ Polygon([(0, 1), (0, 2), (0, 18), (0, 1)]), Polygon([(0, 3), (0, 4), (0, 19), (0, 3)]), MultiPolygon( [ Polygon([(0, 5), (0, 6), (0, 20), (0, 5)]), Polygon([(0, 7), (0, 8), (0, 21), (0, 7)]), ] ), Polygon([(0, 9), (0, 10), (0, 22), (0, 9)]), MultiPolygon( [ Polygon([(0, 11), (0, 12), (0, 13), (0, 22), (0, 11)]), Polygon([(0, 14), (0, 15), (0, 23), (0, 14)]), ] ), Polygon([(0, 16), (0, 17), (0, 24), (0, 16)]), ] ) ) t1 = gs[range] got = t1.polygons.ring_offset expected = cp.array(expected) assert cp.array_equal(got, expected)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/test_align.py
# Copyright (c) 2022 NVIDIA CORPORATION. import geopandas as gpd import numpy as np import pandas as pd from shapely.geometry import Polygon import cuspatial def test_align_more_values(): gpdlhs = gpd.GeoSeries( [ Polygon(((-8, -8), (-8, 8), (8, 8), (8, -8))), Polygon(((-2, -2), (-2, 2), (2, 2), (2, -2))), ] ) gpdrhs = gpdlhs.iloc[0:1] lhs = cuspatial.from_geopandas(gpdlhs) rhs = cuspatial.from_geopandas(gpdrhs) expected = gpdrhs.align(gpdlhs) got = rhs.align(lhs) pd.testing.assert_series_equal(expected[0], got[0].to_pandas()) pd.testing.assert_series_equal(expected[1], got[1].to_pandas()) expected = gpdlhs.align(gpdrhs) got = lhs.align(rhs) pd.testing.assert_series_equal(expected[0], got[0].to_pandas()) pd.testing.assert_series_equal(expected[1], got[1].to_pandas()) def test_align_some_different_values(): gpdlhs = gpd.GeoSeries( [ Polygon(((1, 2), (3, 4), (5, 6), (7, 8))), Polygon(((9, 10), (11, 12), (13, 14), (15, 16))), Polygon(((17, 18), (19, 20), (21, 22), (23, 24))), Polygon(((25, 26), (27, 28), (29, 30), (31, 32))), Polygon(((33, 34), (35, 36), (37, 38), (39, 40))), Polygon(((41, 42), (43, 44), (45, 46), (47, 48))), ] ) gpdlhs = gpdlhs gpdlhs.index = [0, 1, 2, 6, 7, 8] gpdrhs = gpdlhs gpdrhs.index = [0, 1, 2, 3, 4, 5] lhs = cuspatial.from_geopandas(gpdlhs) rhs = cuspatial.from_geopandas(gpdrhs) expected = gpdlhs.align(gpdrhs) got = lhs.align(rhs) pd.testing.assert_series_equal(expected[0], got[0].to_pandas()) pd.testing.assert_series_equal(expected[1], got[1].to_pandas()) def test_align_more_and_some_different_values(): gpdlhs = gpd.GeoSeries( [ Polygon(((1, 2), (3, 4), (5, 6), (7, 8))), Polygon(((9, 10), (11, 12), (13, 14), (15, 16))), Polygon(((17, 18), (19, 20), (21, 22), (23, 24))), Polygon(((25, 26), (27, 28), (29, 30), (31, 32))), Polygon(((33, 34), (35, 36), (37, 38), (39, 40))), Polygon(((41, 42), (43, 44), (45, 46), (47, 48))), ] ) gpdrhs = gpdlhs[0:3] gpdrhs.index = [0, 1, 2] gpdlhs = gpdlhs gpdlhs.index = [0, 1, 2, 3, 4, 5] lhs = cuspatial.from_geopandas(gpdlhs) rhs = cuspatial.from_geopandas(gpdrhs) expected = gpdlhs.align(gpdrhs) got = lhs.align(rhs) pd.testing.assert_series_equal(expected[0], got[0].to_pandas()) pd.testing.assert_series_equal(expected[1], got[1].to_pandas()) expected = gpdrhs.align(gpdlhs) got = rhs.align(lhs) pd.testing.assert_series_equal(expected[0], got[0].to_pandas()) pd.testing.assert_series_equal(expected[1], got[1].to_pandas()) def test_align_with_slice(): gpdlhs = gpd.GeoSeries( [ Polygon(((1, 2), (3, 4), (5, 6), (7, 8))), Polygon(((9, 10), (11, 12), (13, 14), (15, 16))), Polygon(((17, 18), (19, 20), (21, 22), (23, 24))), Polygon(((25, 26), (27, 28), (29, 30), (31, 32))), Polygon(((33, 34), (35, 36), (37, 38), (39, 40))), Polygon(((41, 42), (43, 44), (45, 46), (47, 48))), ] ) lhs = cuspatial.from_geopandas(gpdlhs) gpdlhs = gpdlhs[0:3] gpdrhs = gpdlhs[3:6] lhs = lhs[0:3] rhs = lhs[3:6] expected = gpdlhs.align(gpdrhs) got = lhs.align(rhs) pd.testing.assert_series_equal(expected[0], got[0].to_pandas()) pd.testing.assert_series_equal(expected[1], got[1].to_pandas()) expected = gpdrhs.align(gpdlhs) got = rhs.align(lhs) pd.testing.assert_series_equal(expected[0], got[0].to_pandas()) pd.testing.assert_series_equal(expected[1], got[1].to_pandas()) def test_align_out_of_orders_values(): gpdlhs = gpd.GeoSeries( [ None, None, None, Polygon(((1, 2), (3, 4), (5, 6), (7, 8))), Polygon(((9, 10), (11, 12), (13, 14), (15, 16))), Polygon(((17, 18), (19, 20), (21, 22), (23, 24))), Polygon(((25, 26), (27, 28), (29, 30), (31, 32))), Polygon(((33, 34), (35, 36), (37, 38), (39, 40))), Polygon(((41, 42), (43, 44), (45, 46), (47, 48))), ] ) gpdrhs = gpdlhs.iloc[np.random.permutation(len(gpdlhs))] lhs = cuspatial.from_geopandas(gpdlhs) rhs = cuspatial.from_geopandas(gpdrhs) expected = gpdlhs.align(gpdrhs) got = lhs.align(rhs) pd.testing.assert_series_equal(expected[0], got[0].to_pandas()) pd.testing.assert_series_equal(expected[1], got[1].to_pandas()) expected = gpdrhs.align(gpdlhs) got = rhs.align(lhs) pd.testing.assert_series_equal(expected[0], got[0].to_pandas()) pd.testing.assert_series_equal(expected[1], got[1].to_pandas()) def test_align_same_index(): gpdlhs = gpd.GeoSeries( [ Polygon(((1, 2), (3, 4), (5, 6), (7, 8))), Polygon(((9, 10), (11, 12), (13, 14), (15, 16))), Polygon(((17, 18), (19, 20), (21, 22), (23, 24))), Polygon(((25, 26), (27, 28), (29, 30), (31, 32))), Polygon(((33, 34), (35, 36), (37, 38), (39, 40))), Polygon(((41, 42), (43, 44), (45, 46), (47, 48))), ] ) gpdrhs = gpdlhs gpdlhs.index = [0, 1, 2, 3, 4, 5] gpdrhs.index = [0, 1, 2, 3, 4, 5] lhs = cuspatial.from_geopandas(gpdlhs) rhs = cuspatial.from_geopandas(gpdrhs) expected = gpdlhs.align(gpdrhs) got = lhs.align(rhs) pd.testing.assert_series_equal(expected[0], got[0].to_pandas()) pd.testing.assert_series_equal(expected[1], got[1].to_pandas()) expected = gpdrhs.align(gpdlhs) got = rhs.align(lhs) pd.testing.assert_series_equal(expected[0], got[0].to_pandas()) pd.testing.assert_series_equal(expected[1], got[1].to_pandas()) def test_align_similar_index(): gpdlhs = gpd.GeoSeries( [ Polygon(((1, 2), (3, 4), (5, 6), (7, 8))), Polygon(((9, 10), (11, 12), (13, 14), (15, 16))), Polygon(((17, 18), (19, 20), (21, 22), (23, 24))), Polygon(((25, 26), (27, 28), (29, 30), (31, 32))), Polygon(((33, 34), (35, 36), (37, 38), (39, 40))), Polygon(((41, 42), (43, 44), (45, 46), (47, 48))), ] ) gpdrhs = gpdlhs gpdlhs.index = [0, 1, 2, 3, 4, 5] gpdrhs.index = [1, 2, 3, 4, 5, 6] lhs = cuspatial.from_geopandas(gpdlhs) rhs = cuspatial.from_geopandas(gpdrhs) expected = gpdlhs.align(gpdrhs) got = lhs.align(rhs) pd.testing.assert_series_equal(expected[0], got[0].to_pandas()) pd.testing.assert_series_equal(expected[1], got[1].to_pandas()) expected = gpdrhs.align(gpdlhs) got = rhs.align(lhs) pd.testing.assert_series_equal(expected[0], got[0].to_pandas()) pd.testing.assert_series_equal(expected[1], got[1].to_pandas())
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/test_trajectory.py
# Copyright (c) 2019-2020, NVIDIA CORPORATION. import numpy as np import pytest from shapely.geometry import Point import cudf import cuspatial def test_trajectory_bounding_boxes_empty_float32(): result = cuspatial.trajectory_bounding_boxes( 0, cudf.Series(), cuspatial.GeoSeries.from_points_xy(cudf.Series([], dtype="f4")), ) cudf.testing.assert_frame_equal( result, cudf.DataFrame( { "x_min": cudf.Series([], dtype=np.float32), "y_min": cudf.Series([], dtype=np.float32), "x_max": cudf.Series([], dtype=np.float32), "y_max": cudf.Series([], dtype=np.float32), } ), ) def test_trajectory_bounding_boxes_empty_float64(): result = cuspatial.trajectory_bounding_boxes( 0, cudf.Series(), cuspatial.GeoSeries.from_points_xy(cudf.Series([], dtype="f8")), ) cudf.testing.assert_frame_equal( result, cudf.DataFrame( { "x_min": cudf.Series([], dtype=np.float64), "y_min": cudf.Series([], dtype=np.float64), "x_max": cudf.Series([], dtype=np.float64), "y_max": cudf.Series([], dtype=np.float64), } ), ) def test_trajectory_bounding_boxes_zeros(): result = cuspatial.trajectory_bounding_boxes( 1, cudf.Series([0]), cuspatial.GeoSeries([Point(0, 0)]) ) cudf.testing.assert_frame_equal( result, cudf.DataFrame( {"x_min": [0.0], "y_min": [0.0], "x_max": [0.0], "y_max": [0.0]} ), ) def test_trajectory_bounding_boxes_ones(): result = cuspatial.trajectory_bounding_boxes( 1, cudf.Series([1]), cuspatial.GeoSeries([Point(1, 1)]) ) cudf.testing.assert_frame_equal( result, cudf.DataFrame( {"x_min": [1.0], "y_min": [1.0], "x_max": [1.0], "y_max": [1.0]} ), ) def test_trajectory_bounding_boxes_zero_to_one(): result = cuspatial.trajectory_bounding_boxes( 1, cudf.Series([0, 0]), cuspatial.GeoSeries([Point(0, 0), Point(0, 1)]) ) cudf.testing.assert_frame_equal( result, cudf.DataFrame( {"x_min": [0.0], "y_min": [0.0], "x_max": [0.0], "y_max": [1.0]} ), ) def test_trajectory_bounding_boxes_zero_to_one_xy(): result = cuspatial.trajectory_bounding_boxes( 1, cudf.Series([0, 0]), cuspatial.GeoSeries([Point(0, 0), Point(1, 1)]) ) cudf.testing.assert_frame_equal( result, cudf.DataFrame( {"x_min": [0.0], "y_min": [0.0], "x_max": [1.0], "y_max": [1.0]} ), ) def test_trajectory_bounding_boxes_subsetted(): result = cuspatial.trajectory_bounding_boxes( 2, cudf.Series([0, 0, 1, 1]), cuspatial.GeoSeries( [Point(0, 0), Point(1, 1), Point(-1, -1), Point(2, 2)] ), ) cudf.testing.assert_frame_equal( result, cudf.DataFrame( { "x_min": [0.0, -1.0], "y_min": [0.0, -1.0], "x_max": [1.0, 2.0], "y_max": [1.0, 2.0], } ), ) def test_trajectory_bounding_boxes_intersected(): result = cuspatial.trajectory_bounding_boxes( 2, cudf.Series([0, 0, 1, 1]), cuspatial.GeoSeries( [Point(0, 0), Point(2, 2), Point(1, 1), Point(3, 3)] ), ) cudf.testing.assert_frame_equal( result, cudf.DataFrame( { "x_min": [0.0, 1.0], "y_min": [0.0, 1.0], "x_max": [2.0, 3.0], "y_max": [2.0, 3.0], } ), ) def test_trajectory_bounding_boxes_two_and_three(): result = cuspatial.trajectory_bounding_boxes( 2, cudf.Series([0, 0, 1, 1, 1]), cuspatial.GeoSeries( [Point(0, 0), Point(2, 2), Point(1, 1), Point(3, 3), Point(2, 2)] ), ) cudf.testing.assert_frame_equal( result, cudf.DataFrame( { "x_min": [0.0, 1.0], "y_min": [0.0, 1.0], "x_max": [2.0, 3.0], "y_max": [2.0, 3.0], } ), ) def test_derive_trajectories_zeros(): objects, traj_offsets = cuspatial.derive_trajectories( cudf.Series([0]), # object_id cuspatial.GeoSeries([Point(0, 0)]), cudf.Series([0]), # timestamp ) cudf.testing.assert_series_equal( traj_offsets, cudf.Series([0], dtype="int32") ) cudf.testing.assert_frame_equal( objects, cudf.DataFrame( { "object_id": cudf.Series([0], dtype="int32"), "x": cudf.Series([0], dtype="float64"), "y": cudf.Series([0], dtype="float64"), "timestamp": cudf.Series([0], dtype="datetime64[ms]"), } ), ) def test_derive_trajectories_ones(): objects, traj_offsets = cuspatial.derive_trajectories( cudf.Series([1]), # object_id cuspatial.GeoSeries([Point(1, 1)]), cudf.Series([1]), # timestamp ) cudf.testing.assert_series_equal( traj_offsets, cudf.Series([0], dtype="int32") ) cudf.testing.assert_frame_equal( objects, cudf.DataFrame( { "object_id": cudf.Series([1], dtype="int32"), "x": cudf.Series([1], dtype="float64"), "y": cudf.Series([1], dtype="float64"), "timestamp": cudf.Series([1], dtype="datetime64[ms]"), } ), ) def test_derive_trajectories_two(): objects, traj_offsets = cuspatial.derive_trajectories( cudf.Series([0, 1]), # object_id cuspatial.GeoSeries([Point(0, 0), Point(1, 1)]), cudf.Series([0, 1]), # timestamp ) cudf.testing.assert_series_equal( traj_offsets, cudf.Series([0, 1], dtype="int32") ) cudf.testing.assert_frame_equal( objects, cudf.DataFrame( { "object_id": cudf.Series([0, 1], dtype="int32"), "x": cudf.Series([0, 1], dtype="float64"), "y": cudf.Series([0, 1], dtype="float64"), "timestamp": cudf.Series([0, 1], dtype="datetime64[ms]"), } ), ) def test_derive_trajectories_many(): np.random.seed(0) object_id = cudf.Series(np.random.randint(0, 10, 10), dtype="int32") xs = cudf.Series(np.random.randint(0, 10, 10).astype("f8")) ys = cudf.Series(np.random.randint(0, 10, 10).astype("f8")) points = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame({"x": xs, "y": ys}).interleave_columns() ) timestamp = cudf.Series(np.random.randint(0, 10, 10)) objects, traj_offsets = cuspatial.derive_trajectories( object_id, points, timestamp ) sorted_idxs = cudf.DataFrame({"id": object_id, "ts": timestamp}).argsort() cudf.testing.assert_series_equal( traj_offsets, cudf.Series([0, 1, 2, 5, 6, 8, 9], dtype="int32") ) cudf.testing.assert_frame_equal( objects, cudf.DataFrame( { "object_id": object_id.sort_values().reset_index(drop=True), "x": xs.take(sorted_idxs) .reset_index(drop=True) .astype("float64"), "y": ys.take(sorted_idxs) .reset_index(drop=True) .astype("float64"), "timestamp": timestamp.take(sorted_idxs) .reset_index(drop=True) .astype("datetime64[ms]"), }, index=cudf.core.index.RangeIndex(0, 10), ), ) def test_trajectory_distances_and_speeds_zeros(): points = cuspatial.GeoSeries([Point(0, 0)]) objects, traj_offsets = cuspatial.derive_trajectories([0], points, [0]) trajs = cuspatial.GeoSeries.from_points_xy( objects[["x", "y"]].interleave_columns() ) result = cuspatial.trajectory_distances_and_speeds( len(traj_offsets), objects["object_id"], trajs, objects["timestamp"], ) cudf.testing.assert_series_equal( result["distance"], cudf.Series([0.0]), check_names=False ) cudf.testing.assert_series_equal( result["speed"], cudf.Series([0.0]), check_names=False ) def test_trajectory_distances_and_speeds_ones(): points = cuspatial.GeoSeries([Point(0, 0)]) objects, traj_offsets = cuspatial.derive_trajectories( [1], points, [1], # object_id # xs # ys # timestamp ) trajs = cuspatial.GeoSeries.from_points_xy( objects[["x", "y"]].interleave_columns() ) result = cuspatial.trajectory_distances_and_speeds( len(traj_offsets), objects["object_id"], trajs, objects["timestamp"], ) cudf.testing.assert_series_equal( result["distance"], cudf.Series([0.0]), check_names=False ) cudf.testing.assert_series_equal( result["speed"], cudf.Series([0.0]), check_names=False ) def test_derive_one_trajectory_one_meter_one_second(): points = cuspatial.GeoSeries([Point(0, 0), Point(0.001, 0.0)]) objects, traj_offsets = cuspatial.derive_trajectories( [0, 0], # object_id points, [0, 1000], # timestamp ) trajs = cuspatial.GeoSeries.from_points_xy( objects[["x", "y"]].interleave_columns() ) result = cuspatial.trajectory_distances_and_speeds( len(traj_offsets), objects["object_id"], trajs, objects["timestamp"], ) cudf.testing.assert_series_equal( result["distance"], cudf.Series([1.0]), check_names=False ) cudf.testing.assert_series_equal( result["speed"], cudf.Series([1.0]), check_names=False ) def test_derive_two_trajectories_one_meter_one_second(): points = cuspatial.GeoSeries( [ Point(0, 0), Point(0.001, 0.0), Point(0.0, 0.0), Point(0.0, 0.001), ] ) objects, traj_offsets = cuspatial.derive_trajectories( [0, 0, 1, 1], # object_id points, [0, 1000, 0, 1000], # timestamp ) trajs = cuspatial.GeoSeries.from_points_xy( objects[["x", "y"]].interleave_columns() ) result = cuspatial.trajectory_distances_and_speeds( len(traj_offsets), objects["object_id"], trajs, objects["timestamp"], ) cudf.testing.assert_series_equal( result["distance"], cudf.Series([1.0, 1.0]), check_names=False ) cudf.testing.assert_series_equal( result["speed"], cudf.Series([1.0, 1.0]), check_names=False ) def test_trajectory_distances_and_speeds_single_trajectory(): x = cudf.Series( [1.0, 2.0, 3.0, 5.0, 7.0, 1.0, 2.0, 3.0, 6.0, 0.0, 3.0, 6.0] ) # xs y = cudf.Series( [0.0, 1.0, 2.0, 3.0, 1.0, 3.0, 5.0, 6.0, 5.0, 4.0, 7.0, 4.0] ) # ys points = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame({"x": x, "y": y}).interleave_columns() ) objects, traj_offsets = cuspatial.derive_trajectories( [0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2], # object_id points, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], # timestamp ) trajs = cuspatial.GeoSeries.from_points_xy( objects[["x", "y"]].interleave_columns() ) result = cuspatial.trajectory_distances_and_speeds( len(traj_offsets), objects["object_id"], trajs, objects["timestamp"], ) cudf.testing.assert_series_equal( result["distance"], cudf.Series([7892.922363, 6812.55908203125, 8485.28125]), check_names=False, ) cudf.testing.assert_series_equal( result["speed"], cudf.Series([1973230.625, 2270853.0, 4242640.5]), check_names=False, ) # fast! ######################### # Measure that distance and speed are calculatd # correctly using each of the four cudf datetime # resolutions. # # Compute the distance and speed of two trajectories, # each over 0.001 km in 1 second. # If datetime type conversion wasn't supported, speed # would be different for each test. ######################### @pytest.mark.parametrize( "timestamp_type", [ ("datetime64[ns]", 1000000000), ("datetime64[us]", 1000000), ("datetime64[ms]", 1000), ("datetime64[s]", 1), ], ) def test_trajectory_distances_and_speeds_timestamp_types(timestamp_type): points = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame( { "x": cudf.Series([0.0, 0.001, 0.0, 0.0]), "y": cudf.Series([0.0, 0.0, 0.0, 0.001]), } ).interleave_columns() ) objects, traj_offsets = cuspatial.derive_trajectories( # object_id cudf.Series([0, 0, 1, 1]), points, # timestamp cudf.Series([0, timestamp_type[1], 0, timestamp_type[1]]).astype( timestamp_type[0] ), ) trajs = cuspatial.GeoSeries.from_points_xy( objects[["x", "y"]].interleave_columns() ) result = cuspatial.trajectory_distances_and_speeds( len(traj_offsets), objects["object_id"], trajs, objects["timestamp"], ) cudf.testing.assert_frame_equal( result, cudf.DataFrame({"distance": [1.0, 1.0], "speed": [1.0, 1.0]}), check_names=False, )
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/test_geoseries.py
# Copyright (c) 2020-2021, NVIDIA CORPORATION. from enum import Enum from numbers import Integral import cupy as cp import geopandas as gpd import numpy as np import pandas as pd import pytest from geopandas.testing import assert_geoseries_equal from shapely.affinity import rotate from shapely.geometry import ( LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, ) import cudf from cudf.testing import assert_series_equal import cuspatial np.random.seed(0) class Test_Feature_Enum(Enum): POINT = 0 MULTIPOINT = 1 LINESTRING = 2 POLYGON = 3 def random_polygon(distance_from_origin): outer = Point(distance_from_origin * 2, 0).buffer(1) inners = [] for i in range(np.random.randint(1, 4)): inner = Point(distance_from_origin + i * 0.1, 0).buffer(0.01) inners.append(inner) together = Polygon(outer, inners) result = rotate(together, np.random.random() * 2 * np.pi, use_radians=True) return result def random_multipolygon(size): polygons = [] for i in range(size): polygons.append(random_polygon(i)) result = MultiPolygon(polygons) return result def generate_random_shapely_feature( size: Integral, has_z: bool = False, obj_type: Test_Feature_Enum = None ): obj_type = obj_type.value if obj_type else np.random.randint(1, 7) if obj_type == 1: return Point(np.random.random(2)) else: if obj_type == 2: points = np.random.random(size * 2).reshape(size, 2) return MultiPoint(points) elif obj_type == 3: points = np.random.random(size * 2).reshape(size, 2) return LineString(points) elif obj_type == 4: num_lines = np.random.randint(3, np.ceil(np.sqrt(size)) + 3) points = np.random.random(num_lines * size * 2).reshape( num_lines, size, 2 ) return MultiLineString(tuple(points)) elif obj_type == 5: return random_polygon(size) elif obj_type == 6: return random_multipolygon(size) def generator(size: Integral, obj_type: Test_Feature_Enum = None): geos_list = [] for i in range(size): geo = generate_random_shapely_feature(3, obj_type) geos_list.append(geo) return geos_list def assert_eq_point(p1, p2): assert type(p1) == type(p2) assert p1.x == p2.x assert p1.y == p2.y assert p1.has_z == p2.has_z if p1.has_z: assert p1.z == p2.z assert True def assert_eq_multipoint(p1, p2): assert type(p1) == type(p2) assert len(p1) == len(p2) for i in range(len(p1)): assert_eq_point(p1[i], p2[i]) def assert_eq_linestring(p1, p2): assert type(p1) == type(p2) assert p1 == p2 def assert_eq_multilinestring(p1, p2): for i in range(len(p1)): assert_eq_linestring(p1[i], p2[i]) def assert_eq_polygon(p1, p2): if not p1.equals(p2): raise ValueError def assert_eq_multipolygon(p1, p2): if not p1.equals(p2): raise ValueError def assert_eq_geo(geo1, geo2): if type(geo1) != type(geo2): assert TypeError result = geo1.equals(geo2) if isinstance(result, bool): assert result else: assert result.all() def test_interleaved_point(gs, polys): cugs = cuspatial.from_geopandas(gs) pd.testing.assert_series_equal( cugs.points.x.to_pandas(), gs[gs.type == "Point"].x, check_index=False, ) pd.testing.assert_series_equal( cugs.points.y.to_pandas(), gs[gs.type == "Point"].y, check_index=False, ) cudf.testing.assert_series_equal( cugs.multipoints.x.reset_index(drop=True), cudf.Series( np.array( [ np.array(p.__geo_interface__["coordinates"])[:, 0] for p in gs[gs.type == "MultiPoint"] ] ).flatten() ).reset_index(drop=True), ) cudf.testing.assert_series_equal( cugs.multipoints.y.reset_index(drop=True), cudf.Series( np.array( [ np.array(p.__geo_interface__["coordinates"])[:, 1] for p in gs[gs.type == "MultiPoint"] ] ).flatten() ).reset_index(drop=True), ) cudf.testing.assert_series_equal( cugs.lines.x.reset_index(drop=True), cudf.Series( np.array([range(11, 34, 2)]).flatten(), dtype="float64", ).reset_index(drop=True), ) cudf.testing.assert_series_equal( cugs.lines.y.reset_index(drop=True), cudf.Series( np.array([range(12, 35, 2)]).flatten(), dtype="float64", ).reset_index(drop=True), ) cudf.testing.assert_series_equal( cugs.polygons.x.reset_index(drop=True), cudf.Series(polys[:, 0], dtype="float64").reset_index(drop=True), ) cudf.testing.assert_series_equal( cugs.polygons.y.reset_index(drop=True), cudf.Series(polys[:, 1], dtype="float64").reset_index(drop=True), ) def test_to_shapely_random(): geos_list = generator(250) gi = gpd.GeoSeries(geos_list) cugs = cuspatial.from_geopandas(gi) cugs_back = cugs.to_geopandas() assert_eq_geo(gi, cugs_back) @pytest.mark.parametrize( "pre_slice", [ list(np.arange(10)), slice(0, 12), slice(0, 10, 1), slice(0, 3, 1), slice(3, 6, 1), slice(6, 9, 1), ], ) def test_to_shapely(gs, pre_slice): geometries = gs[pre_slice] gi = gpd.GeoSeries(geometries) cugs = cuspatial.from_geopandas(gi) cugs_back = cugs.to_geopandas() assert_eq_geo(gi, cugs_back) @pytest.mark.parametrize( "series_boolmask", [ np.repeat(True, 12), np.repeat((np.repeat(True, 3), np.repeat(False, 3)), 2).flatten(), np.repeat(False, 12), np.repeat((np.repeat(False, 3), np.repeat(True, 3)), 2).flatten(), np.repeat([True, False], 6).flatten(), ], ) def test_boolmask(gs, series_boolmask): gi = gpd.GeoSeries(gs) cugs = cuspatial.from_geopandas(gi) assert_eq_geo(gi[series_boolmask], cugs[series_boolmask].to_geopandas()) def test_getitem_points(): p0 = Point([1, 2]) p1 = Point([3, 4]) p2 = Point([5, 6]) gps = gpd.GeoSeries([p0, p1, p2]) cus = cuspatial.from_geopandas(gps).to_pandas() assert_eq_point(cus[0], p0) assert_eq_point(cus[1], p1) assert_eq_point(cus[2], p2) def test_getitem_lines(): p0 = LineString([[1, 2], [3, 4]]) p1 = LineString([[1, 2], [3, 4], [5, 6], [7, 8]]) p2 = LineString([[1, 2], [3, 4], [5, 6]]) gps = gpd.GeoSeries([p0, p1, p2]) cus = cuspatial.from_geopandas(gps).to_pandas() assert_eq_linestring(cus[0], p0) assert_eq_linestring(cus[1], p1) assert_eq_linestring(cus[2], p2) def test_getitem_slice_same_index(): gps = gpd.GeoSeries(generator(3, Test_Feature_Enum.POINT)) cus = cuspatial.from_geopandas(gps) assert_eq_geo(cus[0:1].to_geopandas(), gps[0:1]) assert_eq_geo(cus[0:1].to_geopandas(), gps[0:1]) assert_eq_geo(cus[0:1].to_geopandas(), gps[0:1]) assert_eq_geo(cus[0:3].to_geopandas(), gps[0:3]) assert_eq_geo(cus[1:3].to_geopandas(), gps[1:3]) assert_eq_geo(cus[2:3].to_geopandas(), gps[2:3]) def test_getitem_slice_points_loc(): p0 = Point([1, 2]) p1 = Point([3, 4]) p2 = Point([5, 6]) gps = gpd.GeoSeries([p0, p1, p2]) cus = cuspatial.from_geopandas(gps) assert_eq_point(cus[0:1][0], gps[0:1][0]) assert_eq_point(cus[0:2][0], gps[0:2][0]) assert_eq_point(cus[1:2][1], gps[1:2][1]) assert_eq_point(cus[0:3][0], gps[0:3][0]) assert_eq_point(cus[1:3][1], gps[1:3][1]) assert_eq_point(cus[2:3][2], gps[2:3][2]) def test_getitem_slice_points(): p0 = Point([1, 2]) p1 = Point([3, 4]) p2 = Point([5, 6]) gps = gpd.GeoSeries([p0, p1, p2]) cus = cuspatial.from_geopandas(gps) assert_eq_point(cus[0:1].iloc[0], gps[0:1].iloc[0]) assert_eq_point(cus[0:2].iloc[0], gps[0:2].iloc[0]) assert_eq_point(cus[1:2].iloc[0], gps[1:2].iloc[0]) assert_eq_point(cus[0:3].iloc[0], gps[0:3].iloc[0]) assert_eq_point(cus[1:3].iloc[0], gps[1:3].iloc[0]) assert_eq_point(cus[2:3].iloc[0], gps[2:3].iloc[0]) def test_getitem_slice_lines(): p0 = LineString([[1, 2], [3, 4]]) p1 = LineString([[1, 2], [3, 4], [5, 6], [7, 8]]) p2 = LineString([[1, 2], [3, 4], [5, 6]]) gps = gpd.GeoSeries([p0, p1, p2]) cus = cuspatial.from_geopandas(gps) assert_eq_linestring(cus[0:1].iloc[0], gps[0:1].iloc[0]) assert_eq_linestring(cus[0:2].iloc[0], gps[0:2].iloc[0]) assert_eq_linestring(cus[1:2].iloc[0], gps[1:2].iloc[0]) assert_eq_linestring(cus[0:3].iloc[0], gps[0:3].iloc[0]) assert_eq_linestring(cus[1:3].iloc[0], gps[1:3].iloc[0]) assert_eq_linestring(cus[2:3].iloc[0], gps[2:3].iloc[0]) def test_getitem_slice_mlines(gs): gps = gs[gs.type == "MultiLineString"] cus = cuspatial.from_geopandas(gps) assert_eq_linestring(cus[0:1].iloc[0], gps[0:1].iloc[0]) assert_eq_linestring(cus[0:2].iloc[0], gps[0:2].iloc[0]) assert_eq_linestring(cus[1:2].iloc[0], gps[1:2].iloc[0]) def test_getitem_slice_polygons(gs): gps = gs[gs.type == "Polygon"] cus = cuspatial.from_geopandas(gps) assert_eq_linestring(cus[0:1].iloc[0], gps[0:1].iloc[0]) assert_eq_linestring(cus[0:2].iloc[0], gps[0:2].iloc[0]) assert_eq_linestring(cus[1:2].iloc[0], gps[1:2].iloc[0]) def test_getitem_slice_mpolygons(gs): gps = gs[gs.type == "MultiPolygon"] cus = cuspatial.from_geopandas(gps) assert_eq_linestring(cus[0:1].iloc[0], gps[0:1].iloc[0]) assert_eq_linestring(cus[0:2].iloc[0], gps[0:2].iloc[0]) assert_eq_linestring(cus[1:2].iloc[0], gps[1:2].iloc[0]) @pytest.mark.parametrize( "series_slice", [ list(np.arange(10)), slice(0, 10, 1), slice(0, 3, 1), slice(3, 6, 1), slice(6, 9, 1), ], ) def test_size(gs, series_slice): geometries = gs[series_slice] gi = gpd.GeoSeries(geometries) cugs = cuspatial.from_geopandas(gi) assert len(gi) == len(cugs) def test_geometry_point_slicing(gs): cugs = cuspatial.from_geopandas(gs) assert (cugs[:1].points.x == cudf.Series([-1])).all() assert (cugs[:1].points.y == cudf.Series([0])).all() assert (cugs[:1].points.xy == cudf.Series([-1, 0])).all() assert (cugs[3:].points.x == cudf.Series([9])).all() assert (cugs[3:].points.y == cudf.Series([10])).all() assert (cugs[3:].points.xy == cudf.Series([9, 10])).all() assert (cugs[0:4].points.x == cudf.Series([-1, 9])).all() assert (cugs[0:4].points.y == cudf.Series([0, 10])).all() assert (cugs[0:4].points.xy == cudf.Series([-1, 0, 9, 10])).all() def test_geometry_multipoint_slicing(gs): cugs = cuspatial.from_geopandas(gs) assert (cugs[:2].multipoints.x == cudf.Series([1, 3])).all() assert (cugs[:2].multipoints.y == cudf.Series([2, 4])).all() assert (cugs[:2].multipoints.xy == cudf.Series([1, 2, 3, 4])).all() assert (cugs[2:].multipoints.x == cudf.Series([5, 7])).all() assert (cugs[2:].multipoints.y == cudf.Series([6, 8])).all() assert (cugs[2:].multipoints.xy == cudf.Series([5, 6, 7, 8])).all() assert (cugs[0:4].multipoints.x == cudf.Series([1, 3, 5, 7])).all() assert (cugs[0:4].multipoints.y == cudf.Series([2, 4, 6, 8])).all() assert ( cugs[0:4].multipoints.xy == cudf.Series([1, 2, 3, 4, 5, 6, 7, 8]) ).all() def test_geometry_linestring_slicing(gs): cugs = cuspatial.from_geopandas(gs) assert (cugs[:5].lines.x == cudf.Series([11, 13])).all() assert (cugs[:5].lines.y == cudf.Series([12, 14])).all() assert (cugs[:5].lines.xy == cudf.Series([11, 12, 13, 14])).all() assert (cugs[:6].lines.x == cudf.Series([11, 13, 15, 17, 19, 21])).all() assert (cugs[:6].lines.y == cudf.Series([12, 14, 16, 18, 20, 22])).all() assert ( cugs[:6].lines.xy == cudf.Series([11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]) ).all() assert (cugs[7:].lines.x == cudf.Series([31, 33])).all() assert (cugs[7:].lines.y == cudf.Series([32, 34])).all() assert (cugs[7:].lines.xy == cudf.Series([31, 32, 33, 34])).all() assert (cugs[6:].lines.x == cudf.Series([23, 25, 27, 29, 31, 33])).all() assert (cugs[6:].lines.y == cudf.Series([24, 26, 28, 30, 32, 34])).all() assert ( cugs[6:].lines.xy == cudf.Series([23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34]) ).all() def test_geometry_polygon_slicing(gs): cugs = cuspatial.from_geopandas(gs) assert (cugs[:9].polygons.x == cudf.Series([35, 37, 39, 41, 35])).all() assert (cugs[:9].polygons.y == cudf.Series([36, 38, 40, 42, 36])).all() assert ( cugs[:9].polygons.xy == cudf.Series([35, 36, 37, 38, 39, 40, 41, 42, 35, 36]) ).all() assert ( cugs[:10].polygons.x == cudf.Series( [ 35, 37, 39, 41, 35, 43, 45, 47, 43, 49, 51, 53, 49, 55, 57, 59, 55, 61, 63, 65, 61, ] ) ).all() assert ( cugs[:10].polygons.y == cudf.Series( [ 36, 38, 40, 42, 36, 44, 46, 48, 44, 50, 52, 54, 50, 56, 58, 60, 56, 62, 64, 66, 62, ] ) ).all() assert ( cugs[11:].polygons.x == cudf.Series([97, 99, 102, 101, 97, 106, 108, 110, 113, 106]) ).all() assert ( cugs[11:].polygons.y == cudf.Series([98, 101, 103, 108, 98, 107, 109, 111, 108, 107]) ).all() assert ( cugs[11:].polygons.xy == cudf.Series( [ 97, 98, 99, 101, 102, 103, 101, 108, 97, 98, 106, 107, 108, 109, 110, 111, 113, 108, 106, 107, ] ) ).all() def test_loc(gs): index = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"] gs.index = index cugs = cuspatial.from_geopandas(gs) gsslice = gs[0:5] cugsslice = cugs[0:5] assert_eq_geo(gsslice, cugsslice.to_geopandas()) gsslice = gs[["l", "k", "j", "i"]] cugsslice = cugs[["l", "k", "j", "i"]] assert_eq_geo(gsslice, cugsslice.to_geopandas()) @pytest.mark.parametrize( "data", [ None, [], [ Point(1, 1), MultiPoint([(2, 2), (3, 3)]), Point(4, 4), Polygon([(0, 0), (1, 1), (0, 1), (0, 0)]), ], gpd.GeoSeries( [ MultiLineString( [[(0, 0), (1, 2), (1, 0)], [(-1, -1), (-1, 3), (0, 0)]] ), MultiPolygon( [ Polygon([(0, 0), (1, 1), (0, 1), (0, 0)]), Polygon([(2, 2), (2, 3), (3, 3), (2, 2)]), ] ), ] ), ], ) def test_construction_from_foreign_object(data): cugs = cuspatial.GeoSeries(data) gps = gpd.GeoSeries(data) assert_geoseries_equal(cugs.to_geopandas(), gps) def test_memory_usage_simple(gs): cugs = cuspatial.from_geopandas(gs) assert cugs.memory_usage() == 1616 def test_memory_usage_large(): host_dataframe = gpd.read_file( gpd.datasets.get_path("naturalearth_lowres") ) geometry = cuspatial.from_geopandas(host_dataframe)["geometry"] # the geometry column from naturalearth_lowres is 217kb of coordinates assert geometry.memory_usage() == 216793 @pytest.mark.parametrize("level", [None, 0, 1]) @pytest.mark.parametrize("drop", [False, True]) @pytest.mark.parametrize("inplace", [False, True]) @pytest.mark.parametrize("name", [None, "ser"]) def test_reset_index(level, drop, name, inplace): if not drop and inplace: pytest.skip( "For exception checks, see " "test_reset_index_dup_level_name_exceptions" ) midx = pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1), ("b", 2)]) gps = gpd.GeoSeries( [Point(0, 0), Point(0, 1), Point(2, 2), Point(3, 3)], index=midx ) gs = cuspatial.from_geopandas(gps) expected = gps.reset_index(level, drop, name, inplace) got = gs.reset_index(level, drop, name, inplace) if inplace: expected = gps got = gs if drop: pd.testing.assert_series_equal(expected, got.to_pandas()) else: pd.testing.assert_frame_equal(expected, got.to_pandas()) def test_geocolumn_polygon_accessor(): s = gpd.GeoSeries( [ Polygon([(0.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)]), MultiPolygon( [ Polygon([(1.0, 1.0), (2.0, 1.0), (2.0, 2.0), (1.0, 1.0)]), Polygon([(5.0, 5.0), (4.0, 4.0), (4.0, 5.0), (5.0, 5.0)]), ] ), Polygon( [(3.0, 3.0), (2.0, 3.0), (2.0, 2.0), (3.0, 2.0), (3.0, 3.0)] ), ] ) gs = cuspatial.from_geopandas(s) expected_xy = [ 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 2.0, 1.0, 2.0, 2.0, 1.0, 1.0, 5.0, 5.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 3.0, 3.0, 2.0, 3.0, 2.0, 2.0, 3.0, 2.0, 3.0, 3.0, ] cp.testing.assert_array_equal(gs.polygons.xy, cp.array(expected_xy)) expected_ring_offset = [0, 4, 8, 12, 17] cp.testing.assert_array_equal( gs.polygons.ring_offset, cp.array(expected_ring_offset) ) expected_part_offset = [0, 1, 2, 3, 4] cp.testing.assert_array_equal( gs.polygons.part_offset, cp.array(expected_part_offset) ) expected_geometry_offset = [0, 1, 3, 4] cp.testing.assert_array_equal( gs.polygons.geometry_offset, cp.array(expected_geometry_offset) ) expected_point_indices = [ 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, ] cp.testing.assert_array_equal( gs.polygons.point_indices(), cp.array(expected_point_indices) ) def test_from_points_xy(point_generator): hs = gpd.GeoSeries(point_generator(10)) gs = cuspatial.from_geopandas(hs) gs2 = cuspatial.GeoSeries.from_points_xy(gs.points.xy) gpd.testing.assert_geoseries_equal(hs, gs2.to_geopandas()) def test_from_multipoints_xy(multipoint_generator): hs = gpd.GeoSeries(multipoint_generator(10, max_num_geometries=10)) gs = cuspatial.from_geopandas(hs) gs2 = cuspatial.GeoSeries.from_multipoints_xy( gs.multipoints.xy, gs.multipoints.geometry_offset ) gpd.testing.assert_geoseries_equal(hs, gs2.to_geopandas()) def test_from_linestrings_xy(linestring_generator): hs = gpd.GeoSeries(linestring_generator(10, 10)) gs = cuspatial.from_geopandas(hs) gs2 = cuspatial.GeoSeries.from_linestrings_xy( gs.lines.xy, gs.lines.part_offset, gs.lines.geometry_offset ) gpd.testing.assert_geoseries_equal(hs, gs2.to_geopandas()) def test_from_polygons_xy(polygon_generator): hs = gpd.GeoSeries(polygon_generator(10, 10)) gs = cuspatial.from_geopandas(hs) gs2 = cuspatial.GeoSeries.from_polygons_xy( gs.polygons.xy, gs.polygons.ring_offset, gs.polygons.part_offset, gs.polygons.geometry_offset, ) gpd.testing.assert_geoseries_equal(hs, gs2.to_geopandas()) def test_from_linestrings_xy_example(): linestrings_xy = cudf.Series([0.0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]) part_offset = cudf.Series([0, 6]) geometry_offset = cudf.Series([0, 1]) gline = cuspatial.GeoSeries.from_linestrings_xy( linestrings_xy, part_offset, geometry_offset ) hline = gpd.GeoSeries( [ LineString([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]), ] ) gpd.testing.assert_geoseries_equal( gline.to_geopandas(), hline, check_less_precise=True ) def test_from_polygons_xy_example(): polygons_xy = cudf.Series([0.0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 0, 0]) ring_offset = cudf.Series([0, 6]) part_offset = cudf.Series([0, 1]) geometry_offset = cudf.Series([0, 1]) gpolygon = cuspatial.GeoSeries.from_polygons_xy( polygons_xy, ring_offset, part_offset, geometry_offset, ) hpolygon = gpd.GeoSeries( [Polygon([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (0, 0)])] ) gpd.testing.assert_geoseries_equal(gpolygon.to_geopandas(), hpolygon) @pytest.mark.parametrize( "s", [ gpd.GeoSeries(), gpd.GeoSeries([Point(0, 0)]), gpd.GeoSeries([None]), gpd.GeoSeries([Point(0, 0), None, Point(1, 1)]), gpd.GeoSeries([Point(0, 0), None, LineString([(1, 1), (2, 2)]), None]), ], ) def test_isna(s): assert_series_equal(cudf.Series(s.isna()), cuspatial.GeoSeries(s).isna()) @pytest.mark.parametrize( "s", [ gpd.GeoSeries(), gpd.GeoSeries([Point(0, 0)]), gpd.GeoSeries([None]), gpd.GeoSeries([Point(0, 0), None, Point(1, 1)]), gpd.GeoSeries([Point(0, 0), None, LineString([(1, 1), (2, 2)]), None]), ], ) def test_notna(s): assert_series_equal(cudf.Series(s.notna()), cuspatial.GeoSeries(s).notna())
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/basicpreds/test_equals_count.py
from pandas.testing import assert_series_equal from shapely.geometry import MultiPoint, Point import cudf import cuspatial from cuspatial.core.binops.equals_count import pairwise_multipoint_equals_count def test_pairwise_multipoint_equals_count_example_1(): p1 = cuspatial.GeoSeries([MultiPoint([Point(0, 0)])]) p2 = cuspatial.GeoSeries([MultiPoint([Point(0, 0)])]) got = pairwise_multipoint_equals_count(p1, p2) expected = cudf.Series([1], dtype="uint32") assert_series_equal(got.to_pandas(), expected.to_pandas()) def test_pairwise_multipoint_equals_count_example_2(): p1 = cuspatial.GeoSeries([MultiPoint([Point(0, 0)])]) p2 = cuspatial.GeoSeries([MultiPoint([Point(1, 1)])]) got = pairwise_multipoint_equals_count(p1, p2) expected = cudf.Series([0], dtype="uint32") assert_series_equal(got.to_pandas(), expected.to_pandas()) def test_pairwise_multipoint_equals_count_example_3(): p1 = cuspatial.GeoSeries( [ MultiPoint([Point(0, 0)]), MultiPoint([Point(3, 3)]), MultiPoint([Point(2, 2)]), ] ) p2 = cuspatial.GeoSeries( [ MultiPoint([Point(2, 2), Point(0, 0), Point(1, 1)]), MultiPoint([Point(0, 0), Point(1, 1), Point(2, 2)]), MultiPoint([Point(1, 1), Point(2, 2), Point(0, 0)]), ] ) got = pairwise_multipoint_equals_count(p1, p2) expected = cudf.Series([1, 0, 1], dtype="uint32") assert_series_equal(got.to_pandas(), expected.to_pandas()) def test_pairwise_multipoint_equals_count_three_match_two_mismatch(): p1 = cuspatial.GeoSeries( [ MultiPoint([Point(3, 3)]), MultiPoint([Point(0, 0)]), MultiPoint([Point(3, 3)]), ] ) p2 = cuspatial.GeoSeries( [ MultiPoint([Point(0, 0), Point(1, 1), Point(2, 2)]), MultiPoint([Point(0, 0), Point(1, 1), Point(2, 2)]), MultiPoint([Point(0, 0), Point(1, 1), Point(2, 2)]), ] ) got = pairwise_multipoint_equals_count(p1, p2) expected = cudf.Series([0, 1, 0], dtype="uint32") assert_series_equal(got.to_pandas(), expected.to_pandas()) def test_pairwise_multipoint_equals_count_five(): p1 = cuspatial.GeoSeries( [ MultiPoint([Point(0, 0)]), MultiPoint([Point(1, 1)]), MultiPoint([Point(2, 2)]), MultiPoint([Point(3, 3)]), MultiPoint([Point(4, 4)]), ] ) p2 = cuspatial.GeoSeries( [ MultiPoint([Point(0, 0)]), MultiPoint([Point(0, 0)]), MultiPoint([Point(2, 2)]), MultiPoint([Point(2, 2)]), MultiPoint([Point(3, 3)]), ] ) got = pairwise_multipoint_equals_count(p1, p2) expected = cudf.Series([1, 0, 1, 0, 0], dtype="uint32") assert_series_equal(got.to_pandas(), expected.to_pandas()) def test_pairwise_multipoint_equals_two_and_three(): p1 = cuspatial.GeoSeries( [ MultiPoint([Point(0, 0), Point(1, 1), Point(1, 1)]), MultiPoint([Point(0, 0), Point(1, 1), Point(1, 1)]), ] ) p2 = cuspatial.GeoSeries( [ MultiPoint([Point(0, 0), Point(1, 1), Point(2, 2)]), MultiPoint([Point(0, 0), Point(1, 1), Point(2, 2)]), ] ) got = pairwise_multipoint_equals_count(p1, p2) expected = cudf.Series([3, 3], dtype="uint32") assert_series_equal(got.to_pandas(), expected.to_pandas()) def test_pairwise_multipoint_equals_two_and_three_one_match(): p1 = cuspatial.GeoSeries( [ MultiPoint([Point(0, 0), Point(1, 1), Point(1, 1)]), MultiPoint([Point(0, 0), Point(1, 1), Point(1, 1)]), ] ) p2 = cuspatial.GeoSeries( [ MultiPoint([Point(0, 0), Point(2, 2), Point(2, 2)]), MultiPoint([Point(2, 2), Point(2, 2), Point(0, 0)]), ] ) got = pairwise_multipoint_equals_count(p1, p2) expected = cudf.Series([1, 1], dtype="uint32") assert_series_equal(got.to_pandas(), expected.to_pandas())
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/basicpreds/test_contains_basic_predicate.py
# Copyright (c) 2023, NVIDIA CORPORATION. from shapely.geometry import LineString, Point, Polygon import cuspatial from cuspatial.core.binpreds.basic_predicates import ( _basic_contains_any, _basic_contains_count, ) def test_basic_contains_any_outside(): lhs = cuspatial.GeoSeries([Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])]) rhs = cuspatial.GeoSeries([Point(2, 2)]) got = _basic_contains_any(lhs, rhs).to_pandas() expected = [False] assert (got == expected).all() def test_basic_contains_any_inside(): lhs = cuspatial.GeoSeries([Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])]) rhs = cuspatial.GeoSeries([LineString([(0.5, 0.5), (1.5, 1.5)])]) got = _basic_contains_any(lhs, rhs).to_pandas() expected = [True] assert (got == expected).all() def test_basic_contains_any_point(): lhs = cuspatial.GeoSeries([Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])]) rhs = cuspatial.GeoSeries([Point(0, 0)]) got = _basic_contains_any(lhs, rhs).to_pandas() expected = [True] assert (got == expected).all() def test_basic_contains_any_edge(): lhs = cuspatial.GeoSeries([Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])]) rhs = cuspatial.GeoSeries([Point(0, 0.5)]) got = _basic_contains_any(lhs, rhs).to_pandas() expected = [True] assert (got == expected).all() def test_basic_contains_count_outside(): lhs = cuspatial.GeoSeries([Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])]) rhs = cuspatial.GeoSeries([Point(2, 2)]) got = _basic_contains_count(lhs, rhs).to_pandas() expected = [0] assert (got == expected).all() def test_basic_contains_count_inside(): lhs = cuspatial.GeoSeries([Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])]) rhs = cuspatial.GeoSeries([LineString([(0.5, 0.5), (1.5, 1.5)])]) got = _basic_contains_count(lhs, rhs).to_pandas() expected = [1] assert (got == expected).all() def test_basic_contains_count_point(): lhs = cuspatial.GeoSeries([Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])]) rhs = cuspatial.GeoSeries([Point(0, 0)]) got = _basic_contains_count(lhs, rhs).to_pandas() expected = [0] assert (got == expected).all() def test_basic_contains_count_edge(): lhs = cuspatial.GeoSeries([Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])]) rhs = cuspatial.GeoSeries([Point(0, 0.5)]) got = _basic_contains_count(lhs, rhs).to_pandas() expected = [0] assert (got == expected).all()
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/basicpreds/test_equals_basic_predicate.py
import pandas as pd from pandas.testing import assert_series_equal from shapely.geometry import Point import cuspatial from cuspatial.core.binpreds.basic_predicates import _basic_equals_any def test_single_true(): p1 = cuspatial.GeoSeries([Point(0, 0)]) p2 = cuspatial.GeoSeries([Point(0, 0)]) result = _basic_equals_any(p1, p2) assert_series_equal(result.to_pandas(), pd.Series([True])) def test_single_false(): p1 = cuspatial.GeoSeries([Point(0, 0)]) p2 = cuspatial.GeoSeries([Point(1, 1)]) result = _basic_equals_any(p1, p2) assert_series_equal(result.to_pandas(), pd.Series([False])) def test_true_false(): p1 = cuspatial.GeoSeries([Point(0, 0), Point(1, 1)]) p2 = cuspatial.GeoSeries([Point(0, 0), Point(2, 2)]) result = _basic_equals_any(p1, p2) assert_series_equal(result.to_pandas(), pd.Series([True, False])) def test_false_true(): p1 = cuspatial.GeoSeries([Point(0, 0), Point(0, 0)]) p2 = cuspatial.GeoSeries([Point(1, 1), Point(0, 0)]) result = _basic_equals_any(p1, p2) assert_series_equal(result.to_pandas(), pd.Series([False, True])) def test_true_false_true(): p1 = cuspatial.GeoSeries([Point(0, 0), Point(1, 1), Point(2, 2)]) p2 = cuspatial.GeoSeries([Point(0, 0), Point(2, 2), Point(2, 2)]) result = _basic_equals_any(p1, p2) assert_series_equal(result.to_pandas(), pd.Series([True, False, True])) def test_false_true_false(): p1 = cuspatial.GeoSeries([Point(0, 0), Point(0, 0), Point(0, 0)]) p2 = cuspatial.GeoSeries([Point(1, 1), Point(0, 0), Point(2, 2)]) result = _basic_equals_any(p1, p2) assert_series_equal(result.to_pandas(), pd.Series([False, True, False]))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/basicpreds/test_intersects_basic_predicate.py
import pandas as pd from pandas.testing import assert_series_equal from shapely.geometry import LineString, Point, Polygon import cuspatial from cuspatial.core.binpreds.basic_predicates import _basic_intersects def test_single_true(): p1 = cuspatial.GeoSeries([Point(0, 0)]) p2 = cuspatial.GeoSeries([Point(0, 0)]) result = _basic_intersects(p1, p2) assert_series_equal(result.to_pandas(), pd.Series([True])) def test_single_false(): p1 = cuspatial.GeoSeries([Point(0, 0)]) p2 = cuspatial.GeoSeries([Point(1, 1)]) result = _basic_intersects(p1, p2) assert_series_equal(result.to_pandas(), pd.Series([False])) def test_true_false(): p1 = cuspatial.GeoSeries([Point(0, 0), Point(1, 1)]) p2 = cuspatial.GeoSeries([Point(0, 0), Point(2, 2)]) result = _basic_intersects(p1, p2) assert_series_equal(result.to_pandas(), pd.Series([True, False])) def test_false_true(): p1 = cuspatial.GeoSeries([Point(0, 0), Point(0, 0)]) p2 = cuspatial.GeoSeries([Point(1, 1), Point(0, 0)]) result = _basic_intersects(p1, p2) assert_series_equal(result.to_pandas(), pd.Series([False, True])) def test_true_false_true(): p1 = cuspatial.GeoSeries([Point(0, 0), Point(1, 1), Point(2, 2)]) p2 = cuspatial.GeoSeries([Point(0, 0), Point(2, 2), Point(2, 2)]) result = _basic_intersects(p1, p2) assert_series_equal(result.to_pandas(), pd.Series([True, False, True])) def test_false_true_false(): p1 = cuspatial.GeoSeries([Point(0, 0), Point(0, 0), Point(0, 0)]) p2 = cuspatial.GeoSeries([Point(1, 1), Point(0, 0), Point(2, 2)]) result = _basic_intersects(p1, p2) assert_series_equal(result.to_pandas(), pd.Series([False, True, False])) def test_linestring_polygon_within(): lhs = cuspatial.GeoSeries( [ LineString([(0, 0), (1, 1)]), LineString([(0, 0), (1, 1)]), LineString([(0, 0), (1, 1)]), ] ) rhs = cuspatial.GeoSeries( [ Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]), Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]), Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]), ] ) result = _basic_intersects(lhs, rhs) assert_series_equal(result.to_pandas(), pd.Series([True, True, True]))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/basicpreds/test_intersections.py
import geopandas as gpd import pandas as pd from geopandas.testing import assert_geoseries_equal from pandas.testing import assert_frame_equal, assert_series_equal from shapely.geometry import LineString, MultiLineString, Point import cuspatial from cuspatial.core.binops.intersection import pairwise_linestring_intersection def run_test(s1, s2, expect_offset, expect_geom, expect_ids): offset, geoms, ids = pairwise_linestring_intersection( cuspatial.from_geopandas(s1), cuspatial.from_geopandas(s2) ) assert_series_equal(expect_offset, offset.to_pandas(), check_dtype=False) assert_geoseries_equal(expect_geom, geoms.to_geopandas()) assert_frame_equal(expect_ids, ids.to_pandas()) def test_empty(): s1 = gpd.GeoSeries([]) s2 = gpd.GeoSeries([]) expect_offset = pd.Series([0]) expect_geom = gpd.GeoSeries([]) expect_ids = pd.DataFrame( { "lhs_linestring_id": [], "lhs_segment_id": [], "rhs_linestring_id": [], "rhs_segment_id": [], } ) run_test(s1, s2, expect_offset, expect_geom, expect_ids) def test_one_pair(): s1 = gpd.GeoSeries([LineString([(0, 0), (1, 1)])]) s2 = gpd.GeoSeries([LineString([(0, 1), (1, 0)])]) expect_offset = pd.Series([0, 1]) expect_geom = s1.intersection(s2) expect_ids = pd.DataFrame( { "lhs_linestring_id": [[0]], "lhs_segment_id": [[0]], "rhs_linestring_id": [[0]], "rhs_segment_id": [[0]], } ) run_test(s1, s2, expect_offset, expect_geom, expect_ids) def test_two_pairs(): s1 = gpd.GeoSeries( [LineString([(0, 0), (1, 1)]), LineString([(0, 2), (2, 2), (2, 0)])] ) s2 = gpd.GeoSeries( [ LineString([(0, 1), (1, 0)]), LineString([(1, 1), (1, 3), (3, 3), (3, 1), (1.5, 1)]), ] ) expect_offset = pd.Series([0, 1, 3]) expect_geom = gpd.GeoSeries([Point(0.5, 0.5), Point(1, 2), Point(2, 1)]) expect_ids = pd.DataFrame( { "lhs_linestring_id": [[0], [0, 0]], "lhs_segment_id": [[0], [0, 1]], "rhs_linestring_id": [[0], [0, 0]], "rhs_segment_id": [[0], [0, 3]], } ) run_test(s1, s2, expect_offset, expect_geom, expect_ids) def test_one_pair_with_overlap(): s1 = gpd.GeoSeries([LineString([(-1, 0), (0, 0), (0, 1), (-1, 1)])]) s2 = gpd.GeoSeries([LineString([(1, 0), (0, 0), (0, 1), (1, 1)])]) expect_offset = pd.Series([0, 1]) expect_geom = s1.intersection(s2) expect_ids = pd.DataFrame( { "lhs_linestring_id": [[0]], "lhs_segment_id": [[1]], "rhs_linestring_id": [[0]], "rhs_segment_id": [[1]], } ) run_test(s1, s2, expect_offset, expect_geom, expect_ids) def test_two_pairs_with_intersect_and_overlap(): s1 = gpd.GeoSeries( [ LineString([(-1, 0), (0, 0), (0, 1), (-1, 1)]), LineString([(-1, -1), (1, 1), (-1, 1)]), ] ) s2 = gpd.GeoSeries( [ LineString([(1, 0), (0, 0), (0, 1), (1, 1)]), LineString([(-1, 1), (1, -1), (-1, -1), (1, 1)]), ] ) expect_offset = pd.Series([0, 1, 3]) expect_geom = gpd.GeoSeries( [ LineString([(0, 0), (0, 1)]), Point(-1, 1), LineString([(-1, -1), (1, 1)]), ] ) expect_ids = pd.DataFrame( { "lhs_linestring_id": [[0], [0, 0]], "lhs_segment_id": [[1], [1, 0]], "rhs_linestring_id": [[0], [0, 0]], "rhs_segment_id": [[1], [0, 2]], } ) run_test(s1, s2, expect_offset, expect_geom, expect_ids) def test_one_pair_multilinestring(): s1 = gpd.GeoSeries( [MultiLineString([[(0, 0), (1, 1)], [(-1, 1), (0, 0)]])] ) s2 = gpd.GeoSeries( [MultiLineString([[(0, 1), (1, 0)], [(-0.5, 0.5), (0, 0)]])] ) expect_offset = pd.Series([0, 2]) expect_geom = gpd.GeoSeries( [ Point(0.5, 0.5), LineString([(-0.5, 0.5), (0, 0)]), ] ) expect_ids = pd.DataFrame( { "lhs_linestring_id": [[0, 1]], "lhs_segment_id": [[0, 0]], "rhs_linestring_id": [[0, 1]], "rhs_segment_id": [[0, 0]], } ) run_test(s1, s2, expect_offset, expect_geom, expect_ids) def test_three_pairs_identical_has_ring(): lhs = gpd.GeoSeries( [ LineString([(0, 0), (1, 1)]), LineString([(0, 0), (1, 1)]), LineString([(0, 0), (1, 1)]), ] ) rhs = gpd.GeoSeries( [ LineString([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]), LineString([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]), LineString([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]), ] ) expect_offset = pd.Series([0, 2, 4, 6]) expect_geom = gpd.GeoSeries( [ Point(0, 0), Point(1, 1), Point(0, 0), Point(1, 1), Point(0, 0), Point(1, 1), ] ) expect_ids = pd.DataFrame( { "lhs_linestring_id": [[0, 0], [0, 0], [0, 0]], "lhs_segment_id": [[0, 0], [0, 0], [0, 0]], "rhs_linestring_id": [[0, 0], [0, 0], [0, 0]], "rhs_segment_id": [[0, 1], [0, 1], [0, 1]], } ) run_test(lhs, rhs, expect_offset, expect_geom, expect_ids) def test_three_pairs_identical_no_ring(): lhs = gpd.GeoSeries( [ LineString([(0, 0), (1, 1)]), LineString([(0, 0), (1, 1)]), LineString([(0, 0), (1, 1)]), ] ) rhs = gpd.GeoSeries( [ LineString([(0, 0), (0, 1), (1, 1), (1, 0)]), LineString([(0, 0), (0, 1), (1, 1), (1, 0)]), LineString([(0, 0), (0, 1), (1, 1), (1, 0)]), ] ) expect_offset = pd.Series([0, 2, 4, 6]) expect_geom = gpd.GeoSeries( [ Point(0, 0), Point(1, 1), Point(0, 0), Point(1, 1), Point(0, 0), Point(1, 1), ] ) expect_ids = pd.DataFrame( { "lhs_linestring_id": [[0, 0], [0, 0], [0, 0]], "lhs_segment_id": [[0, 0], [0, 0], [0, 0]], "rhs_linestring_id": [[0, 0], [0, 0], [0, 0]], "rhs_segment_id": [[0, 1], [0, 1], [0, 1]], } ) run_test(lhs, rhs, expect_offset, expect_geom, expect_ids)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial/filtering/test_points_in_spatial_window.py
# Copyright (c) 2019-2023, NVIDIA CORPORATION. import geopandas as gpd import pytest from geopandas.testing import assert_geoseries_equal from shapely.geometry import Point import cuspatial def test_zeros(): result = cuspatial.points_in_spatial_window( # noqa: F841 cuspatial.GeoSeries([Point(0, 0)]), 0, 0, 0, 0 ) assert result.empty def test_centered(): s = cuspatial.GeoSeries([Point(0, 0)]) result = cuspatial.points_in_spatial_window(s, -1, 1, -1, 1) assert_geoseries_equal(result.to_geopandas(), gpd.GeoSeries([Point(0, 0)])) @pytest.mark.parametrize( "coords", [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] ) def test_corners(coords): x, y = coords result = cuspatial.points_in_spatial_window( cuspatial.GeoSeries([Point(x, y)]), -1.1, 1.1, -1.1, 1.1 ) assert_geoseries_equal(result.to_geopandas(), gpd.GeoSeries([Point(x, y)])) def test_pair(): result = cuspatial.points_in_spatial_window( cuspatial.GeoSeries([Point(0, 1), Point(1, 0)]), -1.1, 1.1, -1.1, 1.1 ) assert_geoseries_equal( result.to_geopandas(), gpd.GeoSeries([Point(0, 1), Point(1, 0)]) ) def test_oob(): result = cuspatial.points_in_spatial_window( cuspatial.GeoSeries([Point(-2.0, 2.0), Point(2.0, -2.0)]), -1, 1, -1, 1, ) assert_geoseries_equal(result.to_geopandas(), gpd.GeoSeries([])) def test_half(): result = cuspatial.points_in_spatial_window( cuspatial.GeoSeries( [ Point(-1.0, 1.0), Point(1.0, -1.0), Point(3.0, 3.0), Point(-3.0, -3.0), ] ), -2, 2, -2, 2, ) assert_geoseries_equal( result.to_geopandas(), gpd.GeoSeries([Point(-1.0, 1.0), Point(1.0, -1.0)]), )
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial/projection/test_sinusoidal_projection.py
# Copyright (c) 2019-2023, NVIDIA CORPORATION. import pytest from geopandas.testing import assert_geoseries_equal from shapely.geometry import Point import cudf import cuspatial def test_camera_oob_0(): with pytest.raises(RuntimeError): result = cuspatial.sinusoidal_projection( # noqa: F841 -200, 0, cuspatial.GeoSeries([Point(0, 0)]) ) def test_camera_oob_1(): with pytest.raises(RuntimeError): result = cuspatial.sinusoidal_projection( # noqa: F841 200, 0, cuspatial.GeoSeries([Point(0, 0)]) ) def test_camera_oob_2(): with pytest.raises(RuntimeError): result = cuspatial.sinusoidal_projection( # noqa: F841 0, -100, cuspatial.GeoSeries([Point(0, 0)]) ) def test_camera_oob_3(): with pytest.raises(RuntimeError): result = cuspatial.sinusoidal_projection( # noqa: F841 0, 100, cuspatial.GeoSeries([Point(0, 0)]) ) @pytest.mark.parametrize("corner", [0, 1, 2, 3]) def test_camera_corners(corner): x = [-180.0, 180.0, -180.0, 180.0] y = [-90.0, 90.0, 90.0, -90.0] lonlat = cuspatial.GeoSeries.from_points_xy([x[corner], y[corner]]) result = cuspatial.sinusoidal_projection(x[corner], y[corner], lonlat) assert_geoseries_equal( result.to_geopandas(), cuspatial.GeoSeries([Point(0.0, 0.0)]).to_geopandas(), ) def test_longest_distance(): result = cuspatial.sinusoidal_projection( -180, -90, cuspatial.GeoSeries.from_points_xy([180.0, 90.0]) ) assert_geoseries_equal( result.to_geopandas(), cuspatial.GeoSeries([Point(-40000.0, -20000.0)]).to_geopandas(), ) def test_half_distance(): result = cuspatial.sinusoidal_projection( -180.0, -90.0, cuspatial.GeoSeries([Point(0.0, 0.0)]) ) assert_geoseries_equal( result.to_geopandas(), cuspatial.GeoSeries( [Point(-14142.135623730952, -10000.0)] ).to_geopandas(), ) def test_zeros(): result = cuspatial.sinusoidal_projection( 0.0, 0.0, cuspatial.GeoSeries([Point(0.0, 0.0)]) ) assert_geoseries_equal( result.to_geopandas(), cuspatial.GeoSeries([Point(0.0, 0.0)]).to_geopandas(), ) def test_values(): cam_lon = -90.66511046 cam_lat = 42.49197018 py_lon = cudf.Series([-90.66518941, -90.66540743, -90.66489239]) py_lat = cudf.Series([42.49207437, 42.49202408, 42.49266787]) lonlat = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame({"x": py_lon, "y": py_lat}).interleave_columns() ) # note: x/y coordinates in killometers -km result = cuspatial.sinusoidal_projection(cam_lon, cam_lat, lonlat) expected = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame( { "x": [0.0064683857, 0.024330807, -0.0178664241], "y": [-0.0115766660, -0.005988880, -0.0775211111], } ).interleave_columns() ) assert_geoseries_equal( result.to_geopandas(), expected.to_geopandas(), check_less_precise=True )
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial/nearest_points/test_nearest_points.py
import geopandas as gpd import pytest import shapely from geopandas.testing import assert_geodataframe_equal from shapely.geometry import LineString, MultiLineString, MultiPoint, Point import cuspatial def compute_point_linestring_nearest_point_host(gs1, gs2): gpdf = gpd.GeoDataFrame({"lhs": gs1, "rhs": gs2}) nearest_points = gpdf.apply( lambda row: shapely.ops.nearest_points(row["lhs"], row["rhs"]), axis=1, result_type="expand", ) # Compute point geometry id def point_idx_in_multipoint(row): point = row["nearest_points"] multipoint = row["points"] if not isinstance(multipoint, MultiPoint): return 0 for i, g in enumerate(multipoint.geoms): if g.equals(point): return i return -1 points_gpdf = gpd.GeoDataFrame( {"nearest_points": nearest_points[0], "points": gs1} ) point_geometry_id = points_gpdf.apply(point_idx_in_multipoint, axis=1) # compute linestring geometry id and segment id # shapely's predicate between point and linestring is too strict, # thus this resorts to a custom approxmated method via # `approximate_point_on_line` def point_idx_in_multilinestring(row): multilinestring = row["lines"] point = row["nearest_points"] for i, line in enumerate(multilinestring.geoms): for j, segment in enumerate( zip(line.coords[:-1], line.coords[1:]) ): if LineString(segment).intersects(point.buffer(1e-8)): return [i, j] return [-1, -1] lines_gpdf = gpd.GeoDataFrame( {"nearest_points": nearest_points[1], "lines": gs2} ) line_geometry_id = lines_gpdf.apply( point_idx_in_multilinestring, axis=1, result_type="expand" ) return gpd.GeoDataFrame( { "point_geometry_id": point_geometry_id, "linestring_geometry_id": line_geometry_id[0], "segment_id": line_geometry_id[1], "geometry": nearest_points[1], } ) def test_empty_input(): points = cuspatial.GeoSeries([]) linestrings = cuspatial.GeoSeries([]) result = cuspatial.pairwise_point_linestring_nearest_points( points, linestrings ) expected = gpd.GeoDataFrame( { "point_geometry_id": [], "linestring_geometry_id": [], "segment_id": [], "geometry": gpd.GeoSeries(), } ) assert_geodataframe_equal( result.to_pandas(), expected, check_index_type=False ) def test_single(): points = cuspatial.GeoSeries([Point(0, 0)]) linestrings = cuspatial.GeoSeries([LineString([(2, 2), (1, 1)])]) result = cuspatial.pairwise_point_linestring_nearest_points( points, linestrings ) expected = gpd.GeoDataFrame( { "point_geometry_id": [0], "linestring_geometry_id": [0], "segment_id": [0], "geometry": gpd.GeoSeries([Point(1, 1)]), } ) assert_geodataframe_equal( result.to_pandas(), expected, check_dtype=False, check_index_type=False ) def test_multipoints(): points = cuspatial.GeoSeries( [MultiPoint([(0, 0), (0.5, 0.5), (1.0, 0.5)])] ) linestrings = cuspatial.GeoSeries([LineString([(2, 2), (1, 1)])]) result = cuspatial.pairwise_point_linestring_nearest_points( points, linestrings ) expected = gpd.GeoDataFrame( { "point_geometry_id": [2], "linestring_geometry_id": [0], "segment_id": [0], "geometry": gpd.GeoSeries([Point(1, 1)]), } ) assert_geodataframe_equal( result.to_pandas(), expected, check_dtype=False, check_index_type=False ) def test_multilinestrings(): points = cuspatial.GeoSeries([Point(0.5, 0.5)]) linestrings = cuspatial.GeoSeries( [ MultiLineString( [ [(2, 2), (1, 1)], [(1, 1), (2, 0)], [(2, 0), (3, 1)], [(3, 1), (2, 2)], ] ) ] ) result = cuspatial.pairwise_point_linestring_nearest_points( points, linestrings ) expected = gpd.GeoDataFrame( { "point_geometry_id": [0], "linestring_geometry_id": [0], "segment_id": [0], "geometry": gpd.GeoSeries([Point(1, 1)]), } ) assert_geodataframe_equal( result.to_pandas(), expected, check_dtype=False, check_index_type=False ) def test_random_input_nearest_point( multipoint_generator, multilinestring_generator ): num_pairs = 10 max_num_points_per_multipoint = 10 max_num_linestring_per_multilinestring = 10 max_num_segments_per_linestring = 50 points = gpd.GeoSeries( [*multipoint_generator(num_pairs, max_num_points_per_multipoint)] ) linestrings = gpd.GeoSeries( [ *multilinestring_generator( num_pairs, max_num_linestring_per_multilinestring, max_num_segments_per_linestring, ) ] ) d_points = cuspatial.from_geopandas(points) d_linestrings = cuspatial.from_geopandas(linestrings) result = cuspatial.pairwise_point_linestring_nearest_points( d_points, d_linestrings ) expected = compute_point_linestring_nearest_point_host(points, linestrings) assert_geodataframe_equal( result.to_pandas(), expected, check_dtype=False, check_index_type=False, check_less_precise=True, ) def test_input_length_unequal(): d_points = cuspatial.GeoSeries([Point(1, 1), Point(0, 0)]) d_lines = cuspatial.GeoSeries( [ MultiLineString( [ [(1, 2), (3, 4)], [(1, 2), (3, 4)], ] ) ] ) with pytest.raises( ValueError, match="should have the same number of geometries" ): cuspatial.pairwise_point_linestring_nearest_points(d_points, d_lines) def test_contains_mixed_geometries(): d_point_lines = cuspatial.GeoSeries( [Point(1, 1), MultiLineString([[(1, 2), (3, 4)]])] ) d_lines = cuspatial.GeoSeries( [ MultiLineString([[(1, 2), (3, 4)], [(1, 2), (3, 4)]]), MultiLineString([[(5, 6), (7, 8)], [(5, 6), (7, 8)]]), ] ) with pytest.raises(ValueError, match="must contain only point geometries"): cuspatial.pairwise_point_linestring_nearest_points( d_point_lines, d_lines ) def test_contains_mixed_geometries2(): d_points = cuspatial.GeoSeries([Point(1, 1), Point(2, 2)]) d_lines_point = cuspatial.GeoSeries( [MultiLineString([[(1, 2), (3, 4)], [(1, 2), (3, 4)]]), Point(5, 6)] ) with pytest.raises( ValueError, match="must contain only linestring geometries" ): cuspatial.pairwise_point_linestring_nearest_points( d_points, d_lines_point )
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial/join/test_point_in_polygon.py
# Copyright (c) 2019, NVIDIA CORPORATION. import numpy as np import cudf import cuspatial from cuspatial.core.spatial.join import pip_bitmap_column_to_binary_array def test_empty(): result = cuspatial.point_in_polygon( cuspatial.GeoSeries([]), cuspatial.GeoSeries([]) ) cudf.testing.assert_frame_equal(result, cudf.DataFrame()) def test_one_point_in(): result = cuspatial.point_in_polygon( cuspatial.GeoSeries.from_points_xy( cudf.Series([0.0, 0.0], dtype="f8") ), cuspatial.GeoSeries.from_polygons_xy( cudf.Series([-1, -1, 0, 1, 1, -1, -1, -1], dtype="f8"), cudf.Series([0, 4]), cudf.Series([0, 1]), cudf.Series([0, 1]), ), ) expected = cudf.DataFrame({0: True}) cudf.testing.assert_frame_equal(expected, result) def test_one_point_out(): result = cuspatial.point_in_polygon( cuspatial.GeoSeries.from_points_xy(cudf.Series([1, 1], dtype="f8")), cuspatial.GeoSeries.from_polygons_xy( cudf.Series([-1, -1, 0, 1, 1, -1, -1, -1], dtype="f8"), cudf.Series([0, 4]), cudf.Series([0, 1]), cudf.Series([0, 1]), ), ) expected = cudf.DataFrame({0: False}) cudf.testing.assert_frame_equal(expected, result) def test_one_point_in_two_rings(): result = cuspatial.point_in_polygon( cuspatial.GeoSeries.from_points_xy(cudf.Series([0, 0], dtype="f8")), cuspatial.GeoSeries.from_polygons_xy( cudf.Series( [-1, -1, 1, 0, -1, 1, -1, -1, 3, -1, 5, 0, 3, 1, 3, -1], dtype="f8", ), cudf.Series([0, 4, 8]), cudf.Series([0, 2]), cudf.Series([0, 1]), ), ) expected = cudf.DataFrame({0: True}) cudf.testing.assert_frame_equal(expected, result) # Note this test uses unclosed polygons which we don't strictly support, but # currently work with our point-in-polygon algorithm. This may change in the # future. def test_one_point_in_two_unclosed_rings(): result = cuspatial.point_in_polygon( cuspatial.GeoSeries.from_points_xy(cudf.Series([0, 0], dtype="f8")), cuspatial.GeoSeries.from_polygons_xy( cudf.Series( [-1, -1, 1, 0, 0, 0.5, -1, 1, 3, -1, 5, 0, 4, 0.5, 3, 1], dtype="f8", ), cudf.Series([0, 4, 8]), cudf.Series([0, 2]), cudf.Series([0, 1]), ), ) expected = cudf.DataFrame({0: True}) cudf.testing.assert_frame_equal(expected, result) def test_one_point_out_two_rings(): result = cuspatial.point_in_polygon( cuspatial.GeoSeries.from_points_xy(cudf.Series([1, 1], dtype="f8")), cuspatial.GeoSeries.from_polygons_xy( cudf.Series( [-1, -1, 1, 0, -1, 1, -1, -1, 3, -1, 5, 0, 3, 1, 3, -1], dtype="f8", ), cudf.Series([0, 4, 8]), cudf.Series([0, 2]), cudf.Series([0, 1]), ), ) expected = cudf.DataFrame({0: False}) cudf.testing.assert_frame_equal(expected, result) # Note this test uses unclosed polygons which we don't strictly support, but # currently work with our point-in-polygon algorithm. This may change in the # future. def test_one_point_out_two_unclosed_rings(): result = cuspatial.point_in_polygon( cuspatial.GeoSeries.from_points_xy(cudf.Series([1, 1], dtype="f8")), cuspatial.GeoSeries.from_polygons_xy( cudf.Series( [-1, -1, 1, 0, 0, 0.5, -1, 1, 3, -1, 5, 0, 4, 0.5, 3, 1], dtype="f8", ), cudf.Series([0, 4, 8]), cudf.Series([0, 2]), cudf.Series([0, 1]), ), ) expected = cudf.DataFrame({0: False}) cudf.testing.assert_frame_equal(expected, result) def test_two_point_in_one_out_two_rings(): result = cuspatial.point_in_polygon( cuspatial.GeoSeries.from_points_xy( cudf.Series([0, 0, 1, 1], dtype="f8") ), cuspatial.GeoSeries.from_polygons_xy( cudf.Series( [-1, -1, 1, 0, -1, 1, -1, -1, 3, -1, 5, 0, 3, 1, 3, -1], dtype="f8", ), cudf.Series([0, 4, 8]), cudf.Series([0, 2]), cudf.Series([0, 1]), ), ) expected = cudf.DataFrame({0: [True, False]}) cudf.testing.assert_frame_equal(expected, result) def test_two_point_out_one_in_two_rings(): result = cuspatial.point_in_polygon( cuspatial.GeoSeries.from_points_xy( cudf.Series([1, 1, 0, 0], dtype="f8") ), cuspatial.GeoSeries.from_polygons_xy( cudf.Series( [-1, -1, 1, 0, -1, 1, -1, -1, 3, -1, 5, 0, 3, 1, 3, -1], dtype="f8", ), cudf.Series([0, 4, 8]), cudf.Series([0, 2]), cudf.Series([0, 1]), ), ) expected = cudf.DataFrame({0: [False, True]}) cudf.testing.assert_frame_equal(expected, result) def test_two_points_out_two_rings(): result = cuspatial.point_in_polygon( cuspatial.GeoSeries.from_points_xy( cudf.Series([1, 1, -1, 1], dtype="f8") ), cuspatial.GeoSeries.from_polygons_xy( cudf.Series( [-1, -1, 1, 0, -1, 1, -1, -1, 3, -1, 5, 0, 3, 1, 3, -1], dtype="f8", ), cudf.Series([0, 4, 8]), cudf.Series([0, 2]), cudf.Series([0, 1]), ), ) expected = cudf.DataFrame({0: [False, False]}) cudf.testing.assert_frame_equal(expected, result) def test_two_points_in_two_rings(): result = cuspatial.point_in_polygon( cuspatial.GeoSeries.from_points_xy( cudf.Series([0, 0, 0, 4], dtype="f8") ), cuspatial.GeoSeries.from_polygons_xy( cudf.Series( [-1, -1, 0, 1, 1, -1, -1, -1, -1, 3, 0, 5, 1, 3, -1, 3], dtype="f8", ), cudf.Series([0, 4, 8]), cudf.Series([0, 2]), cudf.Series([0, 1]), ), ) expected = cudf.DataFrame({0: [True, True]}) cudf.testing.assert_frame_equal(expected, result) def test_three_points_two_features(): result = cuspatial.point_in_polygon( cuspatial.GeoSeries.from_points_xy( cudf.Series([0, 0, -8, -8, 6.0, 6.0], dtype="f8") ), cuspatial.GeoSeries.from_polygons_xy( cudf.Series( [ -10.0, -10.0, 5, -10, 5, 5, -10, 5, -10, -10, 0, 0, 10, 0, 10, 10, 0, 10, 0, 0, ], dtype="f8", ), cudf.Series([0, 5, 10]), cudf.Series([0, 1, 2]), cudf.Series([0, 1, 2]), ), ) expected = cudf.DataFrame() expected[0] = [True, True, False] expected[1] = [False, False, True] cudf.testing.assert_frame_equal(expected, result) def test_pip_bitmap_column_to_binary_array(): col = cudf.Series([0b00000000, 0b00001101, 0b00000011, 0b00001001])._column got = pip_bitmap_column_to_binary_array(col, width=4) expected = np.array( [[0, 0, 0, 0], [1, 1, 0, 1], [0, 0, 1, 1], [1, 0, 0, 1]], dtype="int8" ) np.testing.assert_array_equal(got.copy_to_host(), expected) col = cudf.Series([])._column got = pip_bitmap_column_to_binary_array(col, width=0) expected = np.array([], dtype="int8").reshape(0, 0) np.testing.assert_array_equal(got.copy_to_host(), expected) col = cudf.Series([None, None], dtype="float64")._column got = pip_bitmap_column_to_binary_array(col, width=0) expected = np.array([], dtype="int8").reshape(2, 0) np.testing.assert_array_equal(got.copy_to_host(), expected) col = cudf.Series( [ 0b000000011101110, 0b000000000001101, 0b111001110011010, ] )._column got = pip_bitmap_column_to_binary_array(col, width=15) expected = np.array( [ [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1], [1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0], ], dtype="int8", ) np.testing.assert_array_equal(got.copy_to_host(), expected) col = cudf.Series([0, 0, 0])._column got = pip_bitmap_column_to_binary_array(col, width=3) expected = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]], dtype="int8") np.testing.assert_array_equal(got.copy_to_host(), expected)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial/join/test_spatial_join.py
# Copyright (c) 2020-2022, NVIDIA CORPORATION. import cupy as cp import numpy as np import pytest import cudf import cuspatial bbox_1 = (0, 1, 0, 1) bbox_2 = (0, 2, 0, 2) small_poly_offsets = cudf.Series([0, 1, 2, 3, 4], dtype=np.uint32) small_ring_offsets = cudf.Series([0, 4, 10, 14, 19], dtype=np.uint32) small_poly_xs = cudf.Series( [ 2.488450, 1.333584, 3.460720, 2.488450, 5.039823, 5.561707, 7.103516, 7.190674, 5.998939, 5.039823, 5.998939, 5.573720, 6.703534, 5.998939, 2.088115, 1.034892, 2.415080, 3.208660, 2.088115, ] ) # noqa: E501 small_poly_ys = cudf.Series( [ 5.856625, 5.008840, 4.586599, 5.856625, 4.229242, 1.825073, 1.503906, 4.025879, 5.653384, 4.229242, 1.235638, 0.197808, 0.086693, 1.235638, 4.541529, 3.530299, 2.896937, 3.745936, 4.541529, ] ) # noqa: E501 small_points_x = cudf.Series( [ 1.9804558865545805, 0.1895259128530169, 1.2591725716781235, 0.8178039499335275, 0.48171647380517046, 1.3890664414691907, 0.2536015260915061, 3.1907684812039956, 3.028362149164369, 3.918090468102582, 3.710910700915217, 3.0706987088385853, 3.572744183805594, 3.7080407833612004, 3.70669993057843, 3.3588457228653024, 2.0697434332621234, 2.5322042870739683, 2.175448214220591, 2.113652420701984, 2.520755151373394, 2.9909779614491687, 2.4613232527836137, 4.975578758530645, 4.07037627210835, 4.300706849071861, 4.5584381091040616, 4.822583857757069, 4.849847745942472, 4.75489831780737, 4.529792124514895, 4.732546857961497, 3.7622247877537456, 3.2648444465931474, 3.01954722322135, 3.7164018490892348, 3.7002781846945347, 2.493975723955388, 2.1807636574967466, 2.566986568683904, 2.2006520196663066, 2.5104987015171574, 2.8222482218882474, 2.241538022180476, 2.3007438625108882, 6.0821276168848994, 6.291790729917634, 6.109985464455084, 6.101327777646798, 6.325158445513714, 6.6793884701899, 6.4274219368674315, 6.444584786789386, 7.897735998643542, 7.079453687660189, 7.430677191305505, 7.5085184104988, 7.886010001346151, 7.250745898479374, 7.769497359206111, 1.8703303641352362, 1.7015273093278767, 2.7456295127617385, 2.2065031771469, 3.86008672302403, 1.9143371250907073, 3.7176098065039747, 0.059011873032214, 3.1162712022943757, 2.4264509160270813, 3.154282922203257, ] ) # noqa: E501 small_points_y = cudf.Series( [ 1.3472225743317712, 0.5431061133894604, 0.1448705855995005, 0.8138440641113271, 1.9022922214961997, 1.5177694304735412, 1.8762161698642947, 0.2621847215928189, 0.027638405909631958, 0.3338651960183463, 0.9937713340192049, 0.9376313558467103, 0.33184908855075124, 0.09804238103130436, 0.7485845679979923, 0.2346381514128677, 1.1809465376402173, 1.419555755682142, 1.2372448404986038, 1.2774712415624014, 1.902015274420646, 1.2420487904041893, 1.0484414482621331, 0.9606291981013242, 1.9486902798139454, 0.021365525588281198, 1.8996548860019926, 0.3234041700489503, 1.9531893897409585, 0.7800065259479418, 1.942673409259531, 0.5659923375279095, 2.8709552313924487, 2.693039435509084, 2.57810040095543, 2.4612194182614333, 2.3345952955903906, 3.3999020934055837, 3.2296461832828114, 3.6607732238530897, 3.7672478678985257, 3.0668114607133137, 3.8159308233351266, 3.8812819070357545, 3.6045900851589048, 2.5470532680258002, 2.983311357415729, 2.2235950639628523, 2.5239201807166616, 2.8765450351723674, 2.5605928243991434, 2.9754616970668213, 2.174562817047202, 3.380784914178574, 3.063690547962938, 3.380489849365283, 3.623862886287816, 3.538128217886674, 3.4154469467473447, 3.253257011908445, 4.209727933188015, 7.478882372510933, 7.474216636277054, 6.896038613284851, 7.513564222799629, 6.885401350515916, 6.194330707468438, 5.823535317960799, 6.789029097334483, 5.188939408363776, 5.788316610960881, ] ) # noqa: E501 @pytest.mark.parametrize("dtype", [np.float32, np.float64]) def test_empty(dtype): points = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame( { "x": cudf.Series([], dtype=dtype), # x "y": cudf.Series([], dtype=dtype), # y } ).interleave_columns() ) order, quadtree = cuspatial.quadtree_on_points( points, *bbox_1, # bbox 1, # scale 1, # max_depth 1, # min_size ) poly_bboxes = cuspatial.polygon_bounding_boxes(cuspatial.GeoSeries([])) poly_bboxes = poly_bboxes.astype(dtype) # empty should not throw intersections = cuspatial.join_quadtree_and_bounding_boxes( quadtree, poly_bboxes, *bbox_1, 1, 1, # bbox # scale # max_depth ) cudf.testing.assert_frame_equal( intersections, cudf.DataFrame( { "bbox_offset": cudf.Series([], dtype=np.uint32), "quad_offset": cudf.Series([], dtype=np.uint32), } ), ) @pytest.mark.parametrize("dtype", [np.float32, np.float64]) def test_polygon_join_small(dtype): x_min = 0 x_max = 8 y_min = 0 y_max = 8 scale = 1 max_depth = 3 min_size = 12 points_x = small_points_x.astype(dtype) points_y = small_points_y.astype(dtype) points = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame( { "x": points_x, # x "y": points_y, # y } ).interleave_columns() ) poly_points_x = small_poly_xs.astype(dtype) poly_points_y = small_poly_ys.astype(dtype) point_indices, quadtree = cuspatial.quadtree_on_points( points, x_min, x_max, y_min, y_max, scale, max_depth, min_size, ) xy = cudf.DataFrame( {"x": poly_points_x, "y": poly_points_y} ).interleave_columns() polygons = cuspatial.GeoSeries.from_polygons_xy( xy, small_ring_offsets, small_poly_offsets, cp.arange(len(small_poly_offsets)), ) poly_bboxes = cuspatial.polygon_bounding_boxes(polygons) intersections = cuspatial.join_quadtree_and_bounding_boxes( quadtree, poly_bboxes, x_min, x_max, y_min, y_max, scale, max_depth, ) cudf.testing.assert_frame_equal( intersections, cudf.DataFrame( { "bbox_offset": cudf.Series( [3, 3, 1, 2, 1, 1, 0, 3], dtype=np.uint32 ), "quad_offset": cudf.Series( [10, 11, 6, 6, 12, 13, 2, 2], dtype=np.uint32 ), } ), ) @pytest.mark.parametrize("dtype", [np.float32, np.float64]) def test_linestring_join_small(dtype): x_min = 0 x_max = 8 y_min = 0 y_max = 8 scale = 1 max_depth = 3 min_size = 12 expansion_radius = 2.0 points_x = small_points_x.astype(dtype) points_y = small_points_y.astype(dtype) points = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame( { "x": points_x, # x "y": points_y, # y } ).interleave_columns() ) linestring_points_x = small_poly_xs.astype(dtype) linestring_points_y = small_poly_ys.astype(dtype) linestrings = cuspatial.GeoSeries.from_linestrings_xy( cudf.DataFrame( {"x": linestring_points_x, "y": linestring_points_y} ).interleave_columns(), small_ring_offsets, cp.arange(len(small_ring_offsets)), ) point_indices, quadtree = cuspatial.quadtree_on_points( points, x_min, x_max, y_min, y_max, scale, max_depth, min_size, ) linestring_bboxes = cuspatial.linestring_bounding_boxes( linestrings, expansion_radius, ) intersections = cuspatial.join_quadtree_and_bounding_boxes( quadtree, linestring_bboxes, x_min, x_max, y_min, y_max, scale, max_depth, ) cudf.testing.assert_frame_equal( intersections, cudf.DataFrame( { "bbox_offset": cudf.Series( [ 3, 1, 2, 3, 3, 0, 1, 2, 3, 0, 3, 1, 2, 3, 1, 2, 1, 2, 0, 1, 3, ], dtype=np.uint32, ), "quad_offset": cudf.Series( [ 3, 8, 8, 8, 9, 10, 10, 10, 10, 11, 11, 6, 6, 6, 12, 12, 13, 13, 2, 2, 2, ], dtype=np.uint32, ), } ), ) @pytest.mark.parametrize("dtype", [np.float32, np.float64]) def test_quadtree_point_in_polygon_small(dtype): x_min = 0 x_max = 8 y_min = 0 y_max = 8 scale = 1 max_depth = 3 min_size = 12 points_x = small_points_x.astype(dtype) points_y = small_points_y.astype(dtype) points = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame( { "x": points_x, # x "y": points_y, # y } ).interleave_columns() ) poly_points_x = small_poly_xs.astype(dtype) poly_points_y = small_poly_ys.astype(dtype) poly_points = cudf.DataFrame( {"x": poly_points_x, "y": poly_points_y} ).interleave_columns() polygons = cuspatial.GeoSeries.from_polygons_xy( poly_points, small_ring_offsets, small_poly_offsets, cp.arange(len(small_poly_offsets)), ) point_indices, quadtree = cuspatial.quadtree_on_points( points, x_min, x_max, y_min, y_max, scale, max_depth, min_size, ) xy = cudf.DataFrame( {"x": poly_points_x, "y": poly_points_y} ).interleave_columns() polygons = cuspatial.GeoSeries.from_polygons_xy( xy, small_ring_offsets, small_poly_offsets, cp.arange(len(small_poly_offsets)), ) poly_bboxes = cuspatial.polygon_bounding_boxes(polygons) intersections = cuspatial.join_quadtree_and_bounding_boxes( quadtree, poly_bboxes, x_min, x_max, y_min, y_max, scale, max_depth, ) polygons_and_points = cuspatial.quadtree_point_in_polygon( intersections, quadtree, point_indices, points, polygons ) cudf.testing.assert_frame_equal( polygons_and_points, cudf.DataFrame( { "polygon_index": cudf.Series( [3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 3], dtype=np.uint32, ), "point_index": cudf.Series( [ 28, 29, 30, 31, 32, 33, 34, 35, 45, 46, 47, 48, 49, 50, 51, 52, 54, 62, 60, ], dtype=np.uint32, ), } ), ) def run_test_quadtree_point_to_nearest_linestring_small( dtype, expected_distances ): x_min = 0 x_max = 8 y_min = 0 y_max = 8 scale = 1 max_depth = 3 min_size = 12 expansion_radius = 2.0 points_x = small_points_x.astype(dtype) points_y = small_points_y.astype(dtype) points = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame( { "x": points_x, # x "y": points_y, # y } ).interleave_columns() ) linestring_points_x = small_poly_xs.astype(dtype) linestring_points_y = small_poly_ys.astype(dtype) linestrings = cuspatial.GeoSeries.from_linestrings_xy( cudf.DataFrame( {"x": linestring_points_x, "y": linestring_points_y} ).interleave_columns(), small_ring_offsets, cp.arange(len(small_ring_offsets)), ) point_indices, quadtree = cuspatial.quadtree_on_points( points, x_min, x_max, y_min, y_max, scale, max_depth, min_size, ) linestring_bboxes = cuspatial.linestring_bounding_boxes( linestrings, expansion_radius, ) intersections = cuspatial.join_quadtree_and_bounding_boxes( quadtree, linestring_bboxes, x_min, x_max, y_min, y_max, scale, max_depth, ) p2np_result = cuspatial.quadtree_point_to_nearest_linestring( intersections, quadtree, point_indices, points, linestrings ) cudf.testing.assert_frame_equal( p2np_result, cudf.DataFrame( { "point_index": cudf.Series( [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, ], dtype=np.uint32, ), "linestring_index": cudf.Series( [ 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 3, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], dtype=np.uint32, ), "distance": cudf.Series(expected_distances, dtype=dtype), } ), ) @pytest.mark.parametrize("dtype", [np.float32, np.float64]) def test_quadtree_point_to_nearest_linestring_small(dtype): if dtype == np.float32: run_test_quadtree_point_to_nearest_linestring_small( dtype, [ 3.06755614, 2.55945015, 2.98496079, 1.71036518, 1.82931805, 1.60950696, 1.68141198, 2.38382101, 2.55103993, 1.66121042, 2.02551198, 2.06608653, 2.0054605, 1.86834478, 1.94656599, 2.2151804, 1.75039434, 1.48201656, 1.67690217, 1.6472789, 1.00051796, 1.75223088, 1.84907377, 1.00189602, 0.760027468, 0.65931344, 1.24821293, 1.32290053, 0.285818338, 0.204662085, 0.41061914, 0.566183507, 0.0462928228, 0.166630849, 0.449532568, 0.566757083, 0.842694938, 1.2851826, 0.761564255, 0.978420198, 0.917963803, 1.43116546, 0.964613676, 0.668479323, 0.983481824, 0.661732435, 0.862337708, 0.50195682, 0.675588429, 0.825302362, 0.460371286, 0.726516545, 0.5221892, 0.728920817, 0.0779202655, 0.262149751, 0.331539005, 0.711767673, 0.0811179057, 0.605163872, 0.0885084718, 1.51270044, 0.389437437, 0.487170845, 1.17812812, 1.8030436, 1.07697463, 1.1812768, 1.12407148, 1.63790822, 2.15100765, ], ) else: run_test_quadtree_point_to_nearest_linestring_small( dtype, [ 3.0675562686570932, 2.5594501016565698, 2.9849608928964071, 1.7103652150920774, 1.8293181280383963, 1.6095070428899729, 1.681412227243898, 2.3838209461314879, 2.5510398428020409, 1.6612106150272572, 2.0255119347250292, 2.0660867596957564, 2.005460353737949, 1.8683447535522375, 1.9465658908648766, 2.215180472008103, 1.7503944159063249, 1.4820166799617225, 1.6769023397521503, 1.6472789467219351, 1.0005181046076022, 1.7522309916961678, 1.8490738879835735, 1.0018961233717569, 0.76002760100291122, 0.65931355999132091, 1.2482129257770731, 1.3229005055827028, 0.28581819228716798, 0.20466187296772376, 0.41061901127492934, 0.56618357460517321, 0.046292709584059538, 0.16663093663041179, 0.44953247369220306, 0.56675685520587671, 0.8426949387264755, 1.2851826443010033, 0.7615641155638555, 0.97842040913621187, 0.91796378078050755, 1.4311654461101424, 0.96461369875795078, 0.66847988653443491, 0.98348202146010699, 0.66173276971965733, 0.86233789031448094, 0.50195678903916696, 0.6755886291567379, 0.82530249944765133, 0.46037120394920633, 0.72651648874084795, 0.52218906793095576, 0.72892093000338909, 0.077921089704128393, 0.26215098141130333, 0.33153993710577778, 0.71176747526132511, 0.081119666144327182, 0.60516346789266895, 0.088508309264124049, 1.5127004224070386, 0.38943741327066272, 0.48717099143018805, 1.1781283344854494, 1.8030436222567465, 1.0769747770485747, 1.181276832710481, 1.1240715558969043, 1.6379084234284416, 2.1510078772519496, ], )
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial/bounding/test_polygon_bounding_boxes.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. import pytest from shapely.geometry import MultiPolygon, Polygon import cudf import cuspatial def test_polygon_bounding_boxes_empty(): s = cuspatial.GeoSeries([]) result = cuspatial.polygon_bounding_boxes(s) cudf.testing.assert_frame_equal( result, cudf.DataFrame(columns=["minx", "miny", "maxx", "maxy"], dtype="f8"), ) def test_polygon_bounding_boxes_one(): s = cuspatial.GeoSeries( [ Polygon( [ (2.488450, 5.856625), (1.333584, 5.008840), (3.460720, 4.586599), ] ) ] ) result = cuspatial.polygon_bounding_boxes(s) cudf.testing.assert_frame_equal( result, cudf.from_pandas(s.to_geopandas().bounds) ) def test_polygon_bounding_boxes_small(): s = cuspatial.GeoSeries( [ Polygon( [ (2.488450, 5.856625), (1.333584, 5.008840), (3.460720, 4.586599), ] ), Polygon( [ (5.039823, 4.229242), (5.561707, 1.825073), (7.103516, 1.503906), (7.190674, 4.025879), (5.998939, 5.653384), ] ), Polygon( [ (5.998939, 1.235638), (5.573720, 0.197808), (6.703534, 0.086693), (5.998939, 1.235638), ] ), Polygon( [ (2.088115, 4.541529), (1.034892, 3.530299), (2.415080, 2.896937), (3.208660, 3.745936), (2.088115, 4.541529), ] ), ] ) result = cuspatial.polygon_bounding_boxes(s) cudf.testing.assert_frame_equal( result, cudf.from_pandas(s.to_geopandas().bounds) ) @pytest.mark.skip(reason="MultiPolygon not yet supported") def test_multipolygon_bounding_box(): s = cuspatial.GeoSeries( [ MultiPolygon( [ Polygon( [(0, 0), (1, 0), (1, -1), (2, -1), (2, 2), (0, 0)] ), Polygon([(-1, -1), (-2, -2), (-3, -2), (-1, -1)]), ] ), MultiPolygon([Polygon([(-1, 0), (-1, 1), (0, 0), (-1, 0)])]), ] ) expected = cuspatial.core.spatial.bounding.polygon_bounding_boxes(s) actual = s.to_geopandas().bounds cudf.testing.assert_frame_equal(expected, cudf.from_pandas(actual))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial/bounding/test_linestring_bounding_boxes.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. import numpy as np import pytest from shapely.geometry import MultiLineString import cudf import cuspatial def test_linestring_bounding_boxes_empty(): result = cuspatial.linestring_bounding_boxes( cuspatial.GeoSeries([]), 0, # expansion_radius ) cudf.testing.assert_frame_equal( result, cudf.DataFrame( { "minx": cudf.Series([]), "miny": cudf.Series([]), "maxx": cudf.Series([]), "maxy": cudf.Series([]), } ), ) @pytest.mark.parametrize("dtype", [np.float32, np.float64]) def test_linestring_bounding_boxes_one(dtype): s = cuspatial.GeoSeries.from_linestrings_xy( cudf.Series( [5.856625, 2.488450, 5.008840, 1.333584, 4.586599, 3.460720], dtype=dtype, ), cudf.Series([0, 3]), cudf.Series([0, 1]), ) result = cuspatial.linestring_bounding_boxes(s, 0) expected = cudf.DataFrame(s.to_geopandas().bounds, dtype=dtype) cudf.testing.assert_frame_equal(result, expected) @pytest.mark.parametrize("dtype", [np.float32, np.float64]) def test_linestring_bounding_boxes_small(dtype): s = cuspatial.GeoSeries.from_linestrings_xy( cudf.Series( [ 2.488450, 5.856625, 1.333584, 5.008840, 3.460720, 4.586599, 5.039823, 4.229242, 5.561707, 1.825073, 7.103516, 1.503906, 7.190674, 4.025879, 5.998939, 5.653384, 5.998939, 1.235638, 5.573720, 0.197808, 6.703534, 0.086693, 5.998939, 1.235638, 2.088115, 4.541529, 1.034892, 3.530299, 2.415080, 2.896937, 3.208660, 3.745936, 2.088115, 4.541529, ], dtype=dtype, ), cudf.Series([0, 3, 8, 12, 17]), cudf.Series([0, 1, 2, 3, 4]), ) result = cuspatial.linestring_bounding_boxes( s, 0.5, # expansion_radius ) cudf.testing.assert_frame_equal( result, cudf.DataFrame( { "minx": cudf.Series( [ 0.8335840000000001, 4.5398230000000002, 5.0737199999999998, 0.53489199999999992, ], dtype=dtype, ), "miny": cudf.Series( [ 4.0865989999999996, 1.003906, -0.41330699999999998, 2.3969369999999999, ], dtype=dtype, ), "maxx": cudf.Series( [ 3.9607199999999998, 7.6906739999999996, 7.2035340000000003, 3.7086600000000001, ], dtype=dtype, ), "maxy": cudf.Series( [ 6.3566250000000002, 6.153384, 1.735638, 5.0415289999999997, ], dtype=dtype, ), } ), ) def test_multilinestring_bounding_boxes_small(): s = cuspatial.GeoSeries( [ MultiLineString( [ [(0, 0), (1, 1), (2, 2), (3, 3)], [(1, 0.5), (2, 1), (3, 1.5), (4, 2)], ] ), MultiLineString( [ [(-1, -1), (-2, -3), (-3, 4), (-8, 1)], [(1, -1), (1, 6)], ] ), ] ) result = cuspatial.linestring_bounding_boxes(s, 0.0) expected = cudf.DataFrame(s.to_geopandas().bounds) cudf.testing.assert_frame_equal(result, expected)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial/distance/test_pairwise_linestring_distance.py
# Copyright (c) 2023, NVIDIA CORPORATION. from shapely.geometry import LineString import cudf from cudf.testing._utils import assert_eq import cuspatial def test_zero_pair(): ls1 = cuspatial.GeoSeries([]) ls2 = cuspatial.GeoSeries([]) got = cuspatial.pairwise_linestring_distance(ls1, ls2) expected = cudf.Series([], dtype="float64") assert_eq(got, expected) def test_one_pair(): ls1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (1.0, 1.0)]), ] ) ls2 = cuspatial.GeoSeries( [ LineString([(2.0, 2.0), (3.0, 3.0)]), ] ) got = cuspatial.pairwise_linestring_distance(ls1, ls2) expected = ls1.to_geopandas().distance(ls2.to_geopandas()) assert_eq(got, expected) def test_two_pairs(): ls1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (1.0, 1.0), (5.0, 10.2)]), LineString([(7.0, 11.4), (8.0, 12.8)]), ] ) ls2 = cuspatial.GeoSeries( [ LineString([(2.0, 2.0), (3.0, 3.0)]), LineString( [(-8.0, -8.0), (-10.0, -5.0), (-13.0, -15.0), (-3.0, -6.0)] ), ] ) got = cuspatial.pairwise_linestring_distance(ls1, ls2) expected = ls1.to_geopandas().distance(ls2.to_geopandas()) assert_eq(got, expected) def test_randomized_linestring_to_linestring(linestring_generator): ls1 = cuspatial.GeoSeries([*linestring_generator(100, 5)]) ls2 = cuspatial.GeoSeries([*linestring_generator(100, 5)]) got = cuspatial.pairwise_linestring_distance(ls1, ls2) expected = ls1.to_geopandas().distance(ls2.to_geopandas()) assert_eq(got, expected) def test_randomized_linestring_to_multilinestring( linestring_generator, multilinestring_generator ): ls1 = cuspatial.GeoSeries([*linestring_generator(100, 5)]) ls2 = cuspatial.GeoSeries([*multilinestring_generator(100, 20, 5)]) got = cuspatial.pairwise_linestring_distance(ls1, ls2) expected = ls1.to_geopandas().distance(ls2.to_geopandas()) assert_eq(got, expected) def test_randomized_multilinestring_to_linestring( linestring_generator, multilinestring_generator ): ls1 = cuspatial.GeoSeries([*multilinestring_generator(100, 20, 5)]) ls2 = cuspatial.GeoSeries([*linestring_generator(100, 5)]) got = cuspatial.pairwise_linestring_distance(ls1, ls2) expected = ls1.to_geopandas().distance(ls2.to_geopandas()) assert_eq(got, expected) def test_randomized_multilinestring_to_multilinestring( multilinestring_generator, ): ls1 = cuspatial.GeoSeries([*multilinestring_generator(100, 20, 5)]) ls2 = cuspatial.GeoSeries([*multilinestring_generator(100, 20, 5)]) got = cuspatial.pairwise_linestring_distance(ls1, ls2) expected = ls1.to_geopandas().distance(ls2.to_geopandas()) assert_eq(got, expected)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial/distance/test_pairwise_point_distance.py
# Copyright (c) 2023, NVIDIA CORPORATION. import geopandas as gpd import pytest from pandas.testing import assert_series_equal from shapely.geometry import LineString, Point import cuspatial def test_empty(): gs1 = cuspatial.GeoSeries([]) gs2 = cuspatial.GeoSeries([]) assert cuspatial.pairwise_point_distance(gs1, gs2).empty def test_point_point_random(point_generator): gs1 = gpd.GeoSeries([*point_generator(100)]) gs2 = gpd.GeoSeries([*point_generator(100)]) cugs1 = cuspatial.from_geopandas(gs1) cugs2 = cuspatial.from_geopandas(gs2) got = cuspatial.pairwise_point_distance(cugs1, cugs2) expected = gs1.distance(gs2) assert_series_equal(got.to_pandas(), expected) def test_point_multipoint_random(point_generator, multipoint_generator): gs1 = gpd.GeoSeries([*point_generator(100)]) gs2 = gpd.GeoSeries([*multipoint_generator(100, 5)]) cugs1 = cuspatial.from_geopandas(gs1) cugs2 = cuspatial.from_geopandas(gs2) got = cuspatial.pairwise_point_distance(cugs1, cugs2) expected = gs1.distance(gs2) assert_series_equal(got.to_pandas(), expected) def test_multipoint_point_random(point_generator, multipoint_generator): gs1 = gpd.GeoSeries([*multipoint_generator(100, 5)]) gs2 = gpd.GeoSeries([*point_generator(100)]) cugs1 = cuspatial.from_geopandas(gs1) cugs2 = cuspatial.from_geopandas(gs2) got = cuspatial.pairwise_point_distance(cugs1, cugs2) expected = gs1.distance(gs2) assert_series_equal(got.to_pandas(), expected) def test_multipoint_multipoint_random(multipoint_generator): gs1 = gpd.GeoSeries([*multipoint_generator(100, 5)]) gs2 = gpd.GeoSeries([*multipoint_generator(100, 5)]) cugs1 = cuspatial.from_geopandas(gs1) cugs2 = cuspatial.from_geopandas(gs2) got = cuspatial.pairwise_point_distance(cugs1, cugs2) expected = gs1.distance(gs2) assert_series_equal(got.to_pandas(), expected) def test_mismatched_input_size(): gs1 = cuspatial.GeoSeries([Point(0, 0)]) gs2 = cuspatial.GeoSeries([Point(0, 0), Point(1, 1)]) with pytest.raises(ValueError, match="must have the same length"): cuspatial.pairwise_point_distance(gs1, gs2) def test_mismatched_input_type(): gs1 = cuspatial.GeoSeries([Point(0, 0)]) gs2 = cuspatial.GeoSeries([LineString([(0, 0), (1, 1)])]) with pytest.raises(ValueError, match="must contain only points"): cuspatial.pairwise_point_distance(gs1, gs2) gs3 = cuspatial.GeoSeries([LineString([(0, 0), (1, 1)])]) gs4 = cuspatial.GeoSeries([Point(0, 0)]) with pytest.raises(ValueError, match="must contain only points"): cuspatial.pairwise_point_distance(gs3, gs4)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial/distance/test_pairwise_linestring_polygon_distance.py
# Copyright (c) 2023, NVIDIA CORPORATION. import geopandas as gpd import pytest from shapely.geometry import LineString, MultiLineString, MultiPolygon, Polygon import cudf from cudf.testing import assert_series_equal import cuspatial def test_linestring_polygon_empty(): lhs = cuspatial.GeoSeries.from_linestrings_xy([], [0], [0]) rhs = cuspatial.GeoSeries.from_polygons_xy([], [0], [0], [0]) got = cuspatial.pairwise_linestring_polygon_distance(lhs, rhs) expect = cudf.Series([], dtype="f8") assert_series_equal(got, expect) @pytest.mark.parametrize( "linestrings", [ [LineString([(0, 0), (1, 1)])], [MultiLineString([[(1, 1), (2, 2)], [(10, 10), (11, 11)]])], ], ) @pytest.mark.parametrize( "polygons", [ [Polygon([(0, 1), (1, 0), (-1, 0), (0, 1)])], [ MultiPolygon( [ Polygon([(-2, 0), (-1, 0), (-1, -1), (-2, 0)]), Polygon([(1, 0), (2, 0), (1, -1), (1, 0)]), ] ) ], ], ) def test_one_pair(linestrings, polygons): lhs = gpd.GeoSeries(linestrings) rhs = gpd.GeoSeries(polygons) dlhs = cuspatial.GeoSeries(linestrings) drhs = cuspatial.GeoSeries(polygons) expect = lhs.distance(rhs) got = cuspatial.pairwise_linestring_polygon_distance(dlhs, drhs) assert_series_equal(got, cudf.Series(expect)) @pytest.mark.parametrize( "linestrings", [ [LineString([(0, 0), (1, 1)]), LineString([(10, 10), (11, 11)])], [ MultiLineString([[(1, 1), (2, 2)], [(3, 3), (4, 4)]]), MultiLineString([[(10, 10), (11, 11)], [(12, 12), (13, 13)]]), ], ], ) @pytest.mark.parametrize( "polygons", [ [ Polygon([(0, 1), (1, 0), (-1, 0), (0, 1)]), Polygon([(-4, -4), (-4, -5), (-5, -5), (-5, -4), (-5, -5)]), ], [ MultiPolygon( [ Polygon([(0, 1), (1, 0), (-1, 0), (0, 1)]), Polygon([(0, 1), (1, 0), (0, -1), (-1, 0), (0, 1)]), ] ), MultiPolygon( [ Polygon( [(-4, -4), (-4, -5), (-5, -5), (-5, -4), (-5, -5)] ), Polygon([(-2, 0), (-2, -2), (0, -2), (0, 0), (-2, 0)]), ] ), ], ], ) def test_two_pair(linestrings, polygons): lhs = gpd.GeoSeries(linestrings) rhs = gpd.GeoSeries(polygons) dlhs = cuspatial.GeoSeries(linestrings) drhs = cuspatial.GeoSeries(polygons) expect = lhs.distance(rhs) got = cuspatial.pairwise_linestring_polygon_distance(dlhs, drhs) assert_series_equal(got, cudf.Series(expect)) def test_linestring_polygon_large(linestring_generator, polygon_generator): N = 100 linestrings = gpd.GeoSeries(linestring_generator(N, 5)) polygons = gpd.GeoSeries(polygon_generator(N, 10.0, 3.0)) dlinestrings = cuspatial.from_geopandas(linestrings) dpolygons = cuspatial.from_geopandas(polygons) expect = linestrings.distance(polygons) got = cuspatial.pairwise_linestring_polygon_distance( dlinestrings, dpolygons ) assert_series_equal(got, cudf.Series(expect))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial/distance/test_pairwise_polygon_distance.py
# Copyright (c) 2023, NVIDIA CORPORATION. import cupy as cp import geopandas as gpd import pytest from shapely.geometry import MultiPolygon, Polygon import cudf from cudf.testing import assert_series_equal import cuspatial def test_polygon_empty(): lhs = cuspatial.GeoSeries.from_polygons_xy([], [0], [0], [0]) rhs = cuspatial.GeoSeries.from_polygons_xy([], [0], [0], [0]) got = cuspatial.pairwise_polygon_distance(lhs, rhs) expect = cudf.Series([], dtype="f8") assert_series_equal(got, expect) @pytest.mark.parametrize( "polygons1", [ [Polygon([(10, 11), (11, 10), (11, 11), (10, 11)])], [ MultiPolygon( [ Polygon([(12, 10), (11, 10), (11, 11), (12, 10)]), Polygon([(11, 10), (12, 10), (11, 11), (11, 10)]), ] ) ], ], ) @pytest.mark.parametrize( "polygons2", [ [Polygon([(0, 1), (1, 0), (-1, 0), (0, 1)])], [ MultiPolygon( [ Polygon([(-2, 0), (-1, 0), (-1, -1), (-2, 0)]), Polygon([(1, 0), (2, 0), (1, -1), (1, 0)]), ] ) ], ], ) def test_one_pair(polygons1, polygons2): lhs = gpd.GeoSeries(polygons1) rhs = gpd.GeoSeries(polygons2) dlhs = cuspatial.GeoSeries(polygons1) drhs = cuspatial.GeoSeries(polygons2) expect = lhs.distance(rhs) got = cuspatial.pairwise_polygon_distance(dlhs, drhs) assert_series_equal(got, cudf.Series(expect)) @pytest.mark.parametrize( "polygons1", [ [ Polygon([(0, 1), (1, 0), (-1, 0), (0, 1)]), Polygon([(-4, -4), (-4, -5), (-5, -5), (-5, -4), (-5, -5)]), ], [ MultiPolygon( [ Polygon([(0, 1), (1, 0), (-1, 0), (0, 1)]), Polygon([(0, 1), (1, 0), (0, -1), (-1, 0), (0, 1)]), ] ), MultiPolygon( [ Polygon( [(-4, -4), (-4, -5), (-5, -5), (-5, -4), (-5, -5)] ), Polygon([(-2, 0), (-2, -2), (0, -2), (0, 0), (-2, 0)]), ] ), ], ], ) @pytest.mark.parametrize( "polygons2", [ [ Polygon([(0, 1), (1, 0), (-1, 0), (0, 1)]), Polygon([(-4, -4), (-4, -5), (-5, -5), (-5, -4), (-5, -5)]), ], [ MultiPolygon( [ Polygon([(0, 1), (1, 0), (-1, 0), (0, 1)]), Polygon([(0, 1), (1, 0), (0, -1), (-1, 0), (0, 1)]), ] ), MultiPolygon( [ Polygon( [(-4, -4), (-4, -5), (-5, -5), (-5, -4), (-5, -5)] ), Polygon([(-2, 0), (-2, -2), (0, -2), (0, 0), (-2, 0)]), ] ), ], ], ) def test_two_pair(polygons1, polygons2): lhs = gpd.GeoSeries(polygons1) rhs = gpd.GeoSeries(polygons2) dlhs = cuspatial.GeoSeries(polygons1) drhs = cuspatial.GeoSeries(polygons2) expect = lhs.distance(rhs) got = cuspatial.pairwise_polygon_distance(dlhs, drhs) assert_series_equal(got, cudf.Series(expect)) def test_linestring_polygon_large(polygon_generator): N = 100 polygons1 = gpd.GeoSeries(polygon_generator(N, 20.0, 5.0)) polygons2 = gpd.GeoSeries(polygon_generator(N, 10.0, 3.0)) dpolygons1 = cuspatial.from_geopandas(polygons1) dpolygons2 = cuspatial.from_geopandas(polygons2) expect = polygons1.distance(polygons2) got = cuspatial.pairwise_polygon_distance(dpolygons1, dpolygons2) assert_series_equal(got, cudf.Series(expect)) def test_point_polygon_geoboundaries(naturalearth_lowres): N = 50 lhs = naturalearth_lowres.geometry[:N].reset_index(drop=True) rhs = naturalearth_lowres.geometry[N : 2 * N].reset_index(drop=True) expect = lhs.distance(rhs) got = cuspatial.pairwise_polygon_distance( cuspatial.GeoSeries(lhs), cuspatial.GeoSeries(rhs) ) assert_series_equal(cudf.Series(expect), got) def test_self_distance(polygon_generator): N = 100 polygons = gpd.GeoSeries(polygon_generator(N, 20.0, 5.0)) polygons = cuspatial.from_geopandas(polygons) got = cuspatial.pairwise_polygon_distance(polygons, polygons) expect = cudf.Series(cp.zeros((N,))) assert_series_equal(got, expect) def test_touching_distance(): polygons1 = [Polygon([(0, 0), (1, 1), (1, 0), (0, 0)])] polygons2 = [Polygon([(1, 0.5), (2, 0), (3, 0.5), (1, 0.5)])] got = cuspatial.pairwise_polygon_distance( cuspatial.GeoSeries(polygons1), cuspatial.GeoSeries(polygons2) ) expect = gpd.GeoSeries(polygons1).distance(gpd.GeoSeries(polygons2)) assert_series_equal(got, cudf.Series(expect)) def test_distance_one(): polygons1 = [Polygon([(1, 1), (2, 1), (2, 2), (1, 2), (1, 1)])] polygons2 = [Polygon([(0, 0), (0, 1), (-1, 1), (-1, 0), (0, 0)])] got = cuspatial.pairwise_polygon_distance( cuspatial.GeoSeries(polygons1), cuspatial.GeoSeries(polygons2) ) expect = gpd.GeoSeries(polygons1).distance(gpd.GeoSeries(polygons2)) assert_series_equal(got, cudf.Series(expect))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial/distance/test_distance.py
from functools import partial from itertools import product import geopandas import pytest from shapely.geometry import ( LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, ) import cudf from cudf.testing import assert_series_equal import cuspatial geometry_types = set( [Point, LineString, Polygon, MultiPoint, MultiLineString, MultiPolygon] ) @pytest.fixture(params=set(product(geometry_types, geometry_types))) def _binary_op_combinations( request, point_generator, multipoint_generator, linestring_generator, multilinestring_generator, polygon_generator, multipolygon_generator, ): type_to_generator = { Point: point_generator, MultiPoint: multipoint_generator, LineString: linestring_generator, MultiLineString: multilinestring_generator, Polygon: polygon_generator, MultiPolygon: multipolygon_generator, } generator_parameters = { point_generator: {}, multipoint_generator: {"max_num_geometries": 10}, linestring_generator: {"max_num_segments": 10}, multilinestring_generator: { "max_num_geometries": 10, "max_num_segments": 10, }, polygon_generator: {"distance_from_origin": 10, "radius": 10}, multipolygon_generator: { "max_per_multi": 10, "distance_from_origin": 10, "radius": 10, }, } ty0, ty1 = request.param g0, g1 = type_to_generator[ty0], type_to_generator[ty1] p0, p1 = generator_parameters[g0], generator_parameters[g1] return (partial(g0, **p0), partial(g1, **p1)) def test_geoseires_distance_empty(): expected = geopandas.GeoSeries([]).distance(geopandas.GeoSeries([])) actual = cuspatial.GeoSeries([]).distance(cuspatial.GeoSeries([])) assert_series_equal(actual, cudf.Series(expected)) @pytest.mark.parametrize("n", [1, 100]) @pytest.mark.parametrize("align", [True, False]) @pytest.mark.parametrize( "index_shuffle", [ (lambda x: x, lambda x: reversed(x)), (lambda x: reversed(x), lambda x: x), ], ) def test_geoseries_distance_non_empty( _binary_op_combinations, n, align, index_shuffle ): g0, g1 = _binary_op_combinations sfl0, sfl1 = index_shuffle h0 = geopandas.GeoSeries([*g0(n=n)], index=sfl0(range(n))) h1 = geopandas.GeoSeries([*g1(n=n)], index=sfl1(range(n))) expected = h0.distance(h1, align=align) d0 = cuspatial.GeoSeries(h0) d1 = cuspatial.GeoSeries(h1) actual = d0.distance(d1, align=align) assert_series_equal(actual, cudf.Series(expected)) def test_geoseries_distance_indices_different(): h0 = geopandas.GeoSeries([Point(0, 0), Point(1, 1)], index=[0, 1]) h1 = geopandas.GeoSeries([Point(0, 0)], index=[0]) expected = h0.distance(h1) d0 = cuspatial.GeoSeries(h0) d1 = cuspatial.GeoSeries(h1) actual = d0.distance(d1) assert_series_equal(actual, cudf.Series(expected, nan_as_null=False)) def test_geoseries_distance_indices_different_not_aligned(): h0 = geopandas.GeoSeries([Point(0, 0), Point(1, 1)], index=[0, 1]) h1 = geopandas.GeoSeries([Point(0, 0)], index=[0]) d0 = cuspatial.GeoSeries(h0) d1 = cuspatial.GeoSeries(h1) try: h0.distance(h1, align=False) except Exception as e: with pytest.raises(e.__class__, match=e.__str__()): d0.distance(d1, align=False) @pytest.mark.parametrize("align", [True, False]) @pytest.mark.parametrize( "index", [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], ], ) def test_geoseries_distance_to_shapely_object( _binary_op_combinations, align, index ): g0, g1 = _binary_op_combinations h0 = geopandas.GeoSeries([*g0(n=10)], index=index) obj = [*g1(n=1)][0] expected = h0.distance(obj, align=align) d0 = cuspatial.GeoSeries(h0) actual = d0.distance(obj, align=align) assert_series_equal(actual, cudf.Series(expected))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial/distance/test_point_linestring_distance.py
import geopandas as gpd import pytest from shapely.geometry import ( LineString, MultiLineString, MultiPoint, Point, Polygon, ) import cudf from cuspatial import pairwise_point_linestring_distance from cuspatial.io.geopandas import from_geopandas @pytest.mark.parametrize( "points, lines", [ ([Point(0, 0)], [LineString([(1, 0), (0, 1)])]), ([MultiPoint([(0, 0), (0.5, 0.5)])], [LineString([(1, 0), (0, 1)])]), ( [Point(0, 0)], [MultiLineString([[(1, 0), (0, 1)], [(0, 0), (1, 1)]])], ), ( [MultiPoint([(0, 0), (1, 1)])], [MultiLineString([[(1, 0), (0, 1)], [(0, 0), (1, 1)]])], ), ], ) def test_one_pair(points, lines): hpts = gpd.GeoSeries(points) hls = gpd.GeoSeries(lines) gpts = from_geopandas(hpts) gls = from_geopandas(hls) got = pairwise_point_linestring_distance(gpts, gls) expected = hpts.distance(hls) cudf.testing.assert_series_equal(got, cudf.Series(expected)) @pytest.mark.parametrize("num_pairs", [1, 2, 100]) def test_random_point_linestring_pairs( num_pairs, point_generator, linestring_generator ): max_num_segments_per_linestring = 50 hpts = gpd.GeoSeries([*point_generator(num_pairs)]) hlines = gpd.GeoSeries( [*linestring_generator(num_pairs, max_num_segments_per_linestring)] ) gpts = from_geopandas(hpts) glines = from_geopandas(hlines) got = pairwise_point_linestring_distance(gpts, glines) expected = hpts.distance(hlines) cudf.testing.assert_series_equal(got, cudf.Series(expected)) @pytest.mark.parametrize("num_pairs", [1, 2, 100]) def test_random_multipoint_linestring_pairs( num_pairs, multipoint_generator, linestring_generator ): max_num_points_per_multipoint = 10 max_num_segments_per_linestring = 50 hpts = gpd.GeoSeries( [*multipoint_generator(num_pairs, max_num_points_per_multipoint)] ) hlines = gpd.GeoSeries( [*linestring_generator(num_pairs, max_num_segments_per_linestring)] ) gpts = from_geopandas(hpts) glines = from_geopandas(hlines) got = pairwise_point_linestring_distance(gpts, glines) expected = hpts.distance(hlines) cudf.testing.assert_series_equal(got, cudf.Series(expected)) @pytest.mark.parametrize("num_pairs", [1, 2, 100]) def test_random_point_multilinestring_pairs( num_pairs, point_generator, multilinestring_generator ): max_num_linestring_per_multilinestring = 10 max_num_segments_per_linestring = 50 hpts = gpd.GeoSeries([*point_generator(num_pairs)]) hlines = gpd.GeoSeries( [ *multilinestring_generator( num_pairs, max_num_linestring_per_multilinestring, max_num_segments_per_linestring, ) ] ) gpts = from_geopandas(hpts) glines = from_geopandas(hlines) got = pairwise_point_linestring_distance(gpts, glines) expected = hpts.distance(hlines) cudf.testing.assert_series_equal(got, cudf.Series(expected)) @pytest.mark.parametrize("num_pairs", [1, 2, 100]) def test_random_multipoint_multilinestring_pairs( num_pairs, multipoint_generator, multilinestring_generator ): max_num_points_per_multipoint = 10 max_num_linestring_per_multilinestring = 10 max_num_segments_per_linestring = 50 hpts = gpd.GeoSeries( [*multipoint_generator(num_pairs, max_num_points_per_multipoint)] ) hlines = gpd.GeoSeries( [ *multilinestring_generator( num_pairs, max_num_linestring_per_multilinestring, max_num_segments_per_linestring, ) ] ) gpts = from_geopandas(hpts) glines = from_geopandas(hlines) got = pairwise_point_linestring_distance(gpts, glines) expected = hpts.distance(hlines) cudf.testing.assert_series_equal(got, cudf.Series(expected)) @pytest.mark.parametrize( "lhs, rhs", [ ( [Point(0, 0), LineString([(1.0, 1.0), (1.0, 2.0)])], [ LineString([(0.5, 0.5), (1.2, 1.7)]), LineString([(8.0, 6.4), (11.3, 21.7)]), ], ), ( [Point(1.0, 2.0), Point(1.0, 1.0)], [ LineString([(0.5, 0.5), (1.2, 1.7)]), Polygon([(8.0, 6.4), (0.0, 0.0), (-5.0, -7.8)]), ], ), ], ) def test_mixed_geometry_series_raise(lhs, rhs): lhs = from_geopandas(gpd.GeoSeries(lhs)) rhs = from_geopandas(gpd.GeoSeries(rhs)) with pytest.raises(ValueError, match=".*must contain only.*"): pairwise_point_linestring_distance(lhs, rhs) def test_multipoint_multilinestring_sliced_pairs( multipoint_generator, multilinestring_generator ): num_pairs = 2 max_num_linestring_per_multilinestring = 2 max_num_segments_per_linestring = 2 max_num_points_per_multipoint = 2 hpts = gpd.GeoSeries( [*multipoint_generator(num_pairs, max_num_points_per_multipoint)] ) hlines = gpd.GeoSeries( [ *multilinestring_generator( num_pairs, max_num_linestring_per_multilinestring, max_num_segments_per_linestring, ) ] ) gpts = from_geopandas(hpts) glines = from_geopandas(hlines) hslicepts = hpts[0:1] hslicelines = hlines[0:1] slicegpts = gpts[0:1] sliceglines = glines[0:1] got = pairwise_point_linestring_distance(slicegpts, sliceglines) expected = hslicepts.distance(hslicelines) cudf.testing.assert_series_equal(got, cudf.Series(expected)) hslicepts = hpts[1:2] hslicelines = hlines[1:2] slicegpts = gpts[1:2] sliceglines = glines[1:2] got = pairwise_point_linestring_distance(slicegpts, sliceglines) expected = hslicepts.distance(hslicelines) # Just dropping the index for now, that is not libcuSpatial's problem got.index = [1] cudf.testing.assert_series_equal(got, cudf.Series(expected)) @pytest.mark.parametrize("slice_index", [0, 1, 2, 3, 4]) def test_multipoint_multilinestring_sliced_many( multipoint_generator, multilinestring_generator, slice_twenty, slice_index ): num_pairs = 20 max_num_linestring_per_multilinestring = 5 max_num_segments_per_linestring = 5 max_num_points_per_multipoint = 5 hpts = gpd.GeoSeries( [*multipoint_generator(num_pairs, max_num_points_per_multipoint)] ) hlines = gpd.GeoSeries( [ *multilinestring_generator( num_pairs, max_num_linestring_per_multilinestring, max_num_segments_per_linestring, ) ] ) gpts = from_geopandas(hpts) glines = from_geopandas(hlines) pslice = slice_twenty[slice_index] hslicepts = hpts[pslice] hslicelines = hlines[pslice] slicegpts = gpts[pslice] sliceglines = glines[pslice] got = pairwise_point_linestring_distance(slicegpts, sliceglines) expected = hslicepts.distance(hslicelines) got.index = cudf.RangeIndex(pslice.start, pslice.stop) cudf.testing.assert_series_equal(got, cudf.Series(expected)) def test_multipoint_multilinestring_sliced_noncontiguous( multipoint_generator, multilinestring_generator ): num_pairs = 20 max_num_linestring_per_multilinestring = 5 max_num_segments_per_linestring = 5 max_num_points_per_multipoint = 5 hpts = gpd.GeoSeries( [*multipoint_generator(num_pairs, max_num_points_per_multipoint)] ) hlines = gpd.GeoSeries( [ *multilinestring_generator( num_pairs, max_num_linestring_per_multilinestring, max_num_segments_per_linestring, ) ] ) gpts = from_geopandas(hpts) glines = from_geopandas(hlines) pslice = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] hslicepts = hpts[pslice] hslicelines = hlines[pslice] slicegpts = gpts[pslice] sliceglines = glines[pslice] got = pairwise_point_linestring_distance(slicegpts, sliceglines) expected = hslicepts.distance(hslicelines) got.index = pslice cudf.testing.assert_series_equal(got, cudf.Series(expected))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial/distance/test_pairwise_point_polygon_distance.py
# Copyright (c) 2023, NVIDIA CORPORATION. import geopandas as gpd import pytest from shapely.geometry import MultiPoint, MultiPolygon, Point, Polygon import cudf from cudf.testing import assert_series_equal import cuspatial def test_point_polygon_empty(): lhs = cuspatial.GeoSeries.from_points_xy([]) rhs = cuspatial.GeoSeries.from_polygons_xy([], [0], [0], [0]) got = cuspatial.pairwise_point_polygon_distance(lhs, rhs) expect = cudf.Series([], dtype="f8") assert_series_equal(got, expect) def test_multipoint_polygon_empty(): lhs = cuspatial.GeoSeries.from_multipoints_xy([], [0]) rhs = cuspatial.GeoSeries.from_polygons_xy([], [0], [0], [0]) got = cuspatial.pairwise_point_polygon_distance(lhs, rhs) expect = cudf.Series([], dtype="f8") assert_series_equal(got, expect) @pytest.mark.parametrize( "points", [[Point(0, 0)], [MultiPoint([(1, 1), (2, 2)])]] ) @pytest.mark.parametrize( "polygons", [ [Polygon([(0, 1), (1, 0), (-1, 0), (0, 1)])], [ MultiPolygon( [ Polygon([(-2, 0), (-1, 0), (-1, -1), (-2, 0)]), Polygon([(1, 0), (2, 0), (1, -1), (1, 0)]), ] ) ], ], ) def test_one_pair(points, polygons): lhs = gpd.GeoSeries(points) rhs = gpd.GeoSeries(polygons) dlhs = cuspatial.GeoSeries(points) drhs = cuspatial.GeoSeries(polygons) expect = lhs.distance(rhs) got = cuspatial.pairwise_point_polygon_distance(dlhs, drhs) assert_series_equal(got, cudf.Series(expect)) @pytest.mark.parametrize( "points", [ [Point(0, 0), Point(3, -3)], [MultiPoint([(1, 1), (2, 2)]), MultiPoint([(3, 3), (4, 4)])], ], ) @pytest.mark.parametrize( "polygons", [ [ Polygon([(0, 1), (1, 0), (-1, 0), (0, 1)]), Polygon([(-4, -4), (-4, -5), (-5, -5), (-5, -4), (-5, -5)]), ], [ MultiPolygon( [ Polygon([(0, 1), (1, 0), (-1, 0), (0, 1)]), Polygon([(0, 1), (1, 0), (0, -1), (-1, 0), (0, 1)]), ] ), MultiPolygon( [ Polygon( [(-4, -4), (-4, -5), (-5, -5), (-5, -4), (-5, -5)] ), Polygon([(-2, 0), (-2, -2), (0, -2), (0, 0), (-2, 0)]), ] ), ], ], ) def test_two_pair(points, polygons): lhs = gpd.GeoSeries(points) rhs = gpd.GeoSeries(polygons) dlhs = cuspatial.GeoSeries(points) drhs = cuspatial.GeoSeries(polygons) expect = lhs.distance(rhs) got = cuspatial.pairwise_point_polygon_distance(dlhs, drhs) assert_series_equal(got, cudf.Series(expect)) def test_point_polygon_large(point_generator, polygon_generator): N = 100 points = gpd.GeoSeries(point_generator(N)) polygons = gpd.GeoSeries(polygon_generator(N, 1.0, 1.5)) dpoints = cuspatial.from_geopandas(points) dpolygons = cuspatial.from_geopandas(polygons) expect = points.distance(polygons) got = cuspatial.pairwise_point_polygon_distance(dpoints, dpolygons) assert_series_equal(got, cudf.Series(expect)) def test_point_polygon_geocities(naturalearth_cities, naturalearth_lowres): N = 100 gpu_cities = cuspatial.from_geopandas(naturalearth_cities.geometry) gpu_countries = cuspatial.from_geopandas(naturalearth_lowres.geometry) expect = naturalearth_cities.geometry[:N].distance( naturalearth_lowres.geometry[:N] ) got = cuspatial.pairwise_point_polygon_distance( gpu_cities[:N], gpu_countries[:N] ) assert_series_equal(cudf.Series(expect), got)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial/distance/test_hausdorff_distance.py
# Copyright (c) 2019-2023, NVIDIA CORPORATION. from shapely.geometry import MultiPoint import cudf import cuspatial def _test_hausdorff_from_list_of_spaces(spaces): s = cuspatial.GeoSeries([MultiPoint(coords) for coords in spaces]) return cuspatial.directed_hausdorff_distance(s) def test_empty(): actual = _test_hausdorff_from_list_of_spaces([]) expected = cudf.DataFrame([]) cudf.testing.assert_frame_equal(expected, actual) def test_zeros(): actual = _test_hausdorff_from_list_of_spaces([[(0, 0)]]) expected = cudf.DataFrame([0.0]) cudf.testing.assert_frame_equal(expected, actual) def test_large(): actual = _test_hausdorff_from_list_of_spaces( [[(0.0, 0.0), (0.0, 1.0)], [(-1.0, 0.0), (-1.0, 1.0)]] ) expected = cudf.DataFrame({0: [0.0, 1.0], 1: [1.0, 0.0]}) cudf.testing.assert_frame_equal(expected, actual) def test_count_one(): actual = _test_hausdorff_from_list_of_spaces([[(0.0, 0.0)], [(0.0, 1.0)]]) expected = cudf.DataFrame({0: [0.0, 1.0], 1: [1.0, 0.0]}) cudf.testing.assert_frame_equal(expected, actual) def test_count_two(): actual = _test_hausdorff_from_list_of_spaces( [[(0.0, 0.0), (0.0, -1.0)], [(1.0, 1.0), (0.0, -1.0)]] ) expected = cudf.DataFrame( {0: [0.0, 1.4142135623730951], 1: [1.0, 0.0000000000000000]} ) cudf.testing.assert_frame_equal(expected, actual) def test_values(): actual = _test_hausdorff_from_list_of_spaces( [ [(0.0, 1.0), (1.0, 2.0), (2.0, 3.0), (3.0, 5.0), (1.0, 7.0)], [(3.0, 0.0), (5.0, 2.0), (6.0, 3.0), (5.0, 6.0)], [(4.0, 1.0), (7.0, 3.0), (4.0, 6.0)], ] ) expected = cudf.DataFrame( { 0: [0.000000, 3.605551, 4.472136], 1: [4.123106, 0.000000, 1.414214], 2: [4.000000, 1.414214, 0.000000], } ) cudf.testing.assert_frame_equal(expected, actual)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial/distance/test_haversine_distance.py
# Copyright (c) 2019-2023, NVIDIA CORPORATION. import geopandas as gpd import numpy as np import pandas as pd from shapely.geometry import Point import cuspatial def test_zeros(): distance = cuspatial.haversine_distance( cuspatial.GeoSeries([Point(0, 0)]), cuspatial.GeoSeries([Point(0, 0)]) ) assert np.allclose(distance.to_numpy(), [0.0]) def test_triple(): cities = gpd.GeoSeries( [ Point(-74.0060, 40.7128), Point(2.3522, 48.8566), Point(151.2093, -33.8688), ], index=["New York", "Paris", "Sydney"], ) # Compute all pairs from pairwise cities1 = cuspatial.from_geopandas(cities.repeat(3)) cities2 = cuspatial.from_geopandas(pd.concat([cities] * 3)) distance = cuspatial.haversine_distance( cities1, cities2, ) assert np.allclose( distance.to_numpy(), [ [ 0.0, 5.83724090e03, 1.59887555e04, 5.83724090e03, 0.0, 1.69604974e04, 1.59887555e04, 1.69604974e04, 0.0, ] ], )
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/spatial/indexing/test_indexing.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. import numpy as np import pytest from shapely.geometry import Point import cudf import cuspatial bbox_1 = (0, 1, 0, 1) bbox_2 = (0, 2, 0, 2) def test_empty(): # empty should not throw order, quadtree = cuspatial.quadtree_on_points( cuspatial.GeoSeries([]), *bbox_1, # bbox 1, # scale 1, # max_depth 1, # min_size ) cudf.testing.assert_frame_equal( quadtree, cudf.DataFrame( { "key": cudf.Series([], dtype=np.uint32), "level": cudf.Series([], dtype=np.uint8), "is_internal_node": cudf.Series([], dtype=np.bool_), "length": cudf.Series([], dtype=np.uint32), "offset": cudf.Series([], dtype=np.uint32), } ), ) def test_one_point(): order, quadtree = cuspatial.quadtree_on_points( cuspatial.GeoSeries([Point(0.5, 0.5)]), *bbox_1, # bbox 1, # scale 1, # max_depth 1, # min_size ) cudf.testing.assert_frame_equal( quadtree, cudf.DataFrame( { "key": cudf.Series([0], dtype=np.uint32), "level": cudf.Series([0], dtype=np.uint8), "is_internal_node": cudf.Series([0], dtype=np.bool_), "length": cudf.Series([1], dtype=np.uint32), "offset": cudf.Series([0], dtype=np.uint32), } ), ) def test_two_points(): order, quadtree = cuspatial.quadtree_on_points( cuspatial.GeoSeries([Point(0.5, 0.5), Point(1.5, 1.5)]), *bbox_2, # bbox 1, # scale 1, # max_depth 1, # min_size ) cudf.testing.assert_frame_equal( quadtree, cudf.DataFrame( { "key": cudf.Series([0, 3], dtype=np.uint32), "level": cudf.Series([0, 0], dtype=np.uint8), "is_internal_node": cudf.Series([0, 0], dtype=np.bool_), "length": cudf.Series([1, 1], dtype=np.uint32), "offset": cudf.Series([0, 1], dtype=np.uint32), } ), ) @pytest.mark.parametrize("dtype", ["float32", "float64"]) def test_small_number_of_points(dtype): x = cudf.Series( [ 1.9804558865545805, 0.1895259128530169, 1.2591725716781235, 0.8178039499335275, 0.48171647380517046, 1.3890664414691907, 0.2536015260915061, 3.1907684812039956, 3.028362149164369, 3.918090468102582, 3.710910700915217, 3.0706987088385853, 3.572744183805594, 3.7080407833612004, 3.70669993057843, 3.3588457228653024, 2.0697434332621234, 2.5322042870739683, 2.175448214220591, 2.113652420701984, 2.520755151373394, 2.9909779614491687, 2.4613232527836137, 4.975578758530645, 4.07037627210835, 4.300706849071861, 4.5584381091040616, 4.822583857757069, 4.849847745942472, 4.75489831780737, 4.529792124514895, 4.732546857961497, 3.7622247877537456, 3.2648444465931474, 3.01954722322135, 3.7164018490892348, 3.7002781846945347, 2.493975723955388, 2.1807636574967466, 2.566986568683904, 2.2006520196663066, 2.5104987015171574, 2.8222482218882474, 2.241538022180476, 2.3007438625108882, 6.0821276168848994, 6.291790729917634, 6.109985464455084, 6.101327777646798, 6.325158445513714, 6.6793884701899, 6.4274219368674315, 6.444584786789386, 7.897735998643542, 7.079453687660189, 7.430677191305505, 7.5085184104988, 7.886010001346151, 7.250745898479374, 7.769497359206111, 1.8703303641352362, 1.7015273093278767, 2.7456295127617385, 2.2065031771469, 3.86008672302403, 1.9143371250907073, 3.7176098065039747, 0.059011873032214, 3.1162712022943757, 2.4264509160270813, 3.154282922203257, ] ).astype( dtype ) # x y = cudf.Series( [ 1.3472225743317712, 0.5431061133894604, 0.1448705855995005, 0.8138440641113271, 1.9022922214961997, 1.5177694304735412, 1.8762161698642947, 0.2621847215928189, 0.027638405909631958, 0.3338651960183463, 0.9937713340192049, 0.9376313558467103, 0.33184908855075124, 0.09804238103130436, 0.7485845679979923, 0.2346381514128677, 1.1809465376402173, 1.419555755682142, 1.2372448404986038, 1.2774712415624014, 1.902015274420646, 1.2420487904041893, 1.0484414482621331, 0.9606291981013242, 1.9486902798139454, 0.021365525588281198, 1.8996548860019926, 0.3234041700489503, 1.9531893897409585, 0.7800065259479418, 1.942673409259531, 0.5659923375279095, 2.8709552313924487, 2.693039435509084, 2.57810040095543, 2.4612194182614333, 2.3345952955903906, 3.3999020934055837, 3.2296461832828114, 3.6607732238530897, 3.7672478678985257, 3.0668114607133137, 3.8159308233351266, 3.8812819070357545, 3.6045900851589048, 2.5470532680258002, 2.983311357415729, 2.2235950639628523, 2.5239201807166616, 2.8765450351723674, 2.5605928243991434, 2.9754616970668213, 2.174562817047202, 3.380784914178574, 3.063690547962938, 3.380489849365283, 3.623862886287816, 3.538128217886674, 3.4154469467473447, 3.253257011908445, 4.209727933188015, 7.478882372510933, 7.474216636277054, 6.896038613284851, 7.513564222799629, 6.885401350515916, 6.194330707468438, 5.823535317960799, 6.789029097334483, 5.188939408363776, 5.788316610960881, ] ).astype(dtype) xy = cudf.DataFrame({"x": x, "y": y}).interleave_columns() points = cuspatial.GeoSeries.from_points_xy(xy) order, quadtree = cuspatial.quadtree_on_points( points, 0, # x_min 8, # x_max 0, # y_min 8, # y_max 1, # scale 3, # max_depth 12, # min_size ) cudf.testing.assert_frame_equal( quadtree, cudf.DataFrame( { "key": cudf.Series( [0, 1, 2, 0, 1, 3, 4, 7, 5, 6, 13, 14, 28, 31], dtype=np.uint32, ), "level": cudf.Series( [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], dtype=np.uint8 ), "is_internal_node": cudf.Series( [1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0], dtype=np.bool_ ), "length": cudf.Series( [3, 2, 11, 7, 2, 2, 9, 2, 9, 7, 5, 8, 8, 7], dtype=np.uint32, ), "offset": cudf.Series( [3, 6, 60, 0, 8, 10, 36, 12, 7, 16, 23, 28, 45, 53], dtype=np.uint32, ), } ), )
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/binpreds/test_equals_only_binpreds.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION import geopandas as gpd import pandas as pd import pytest from shapely.geometry import LineString, MultiPoint, Point, Polygon import cuspatial def test_point_geom_equals_point(): gpdpoint1 = gpd.GeoSeries([Point(0, 0)]) gpdpoint2 = gpd.GeoSeries([Point(0, 0)]) point1 = cuspatial.from_geopandas(gpdpoint1) point2 = cuspatial.from_geopandas(gpdpoint2) got = point1.geom_equals(point2) expected = gpdpoint1.geom_equals(gpdpoint2) pd.testing.assert_series_equal(expected, got.to_pandas()) @pytest.mark.parametrize( "lhs", [ [Point(0, 0), Point(0, 0), Point(0, 0)], [Point(1, 1), Point(1, 1), Point(1, 1)], [Point(2, 2), Point(2, 2), Point(2, 2)], ], ) def test_3_points_equals_3_points_one_equal(lhs): gpdpoint1 = gpd.GeoSeries(lhs) gpdpoint2 = gpd.GeoSeries([Point(0, 0), Point(1, 1), Point(2, 2)]) point1 = cuspatial.from_geopandas(gpdpoint1) point2 = cuspatial.from_geopandas(gpdpoint2) got = point1.geom_equals(point2) expected = gpdpoint1.geom_equals(gpdpoint2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_100_points_geom_equals_100_points(point_generator): gpdpoints1 = gpd.GeoSeries([*point_generator(100)]) gpdpoints2 = gpd.GeoSeries([*point_generator(100)]) points1 = cuspatial.from_geopandas(gpdpoints1) points2 = cuspatial.from_geopandas(gpdpoints2) got = points1.geom_equals(points2) expected = gpdpoints1.geom_equals(gpdpoints2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_geom_equals_linestring(): gpdline1 = gpd.GeoSeries([LineString([(0, 0), (1, 1)])]) gpdline2 = gpd.GeoSeries([LineString([(0, 0), (1, 1)])]) line1 = cuspatial.from_geopandas(gpdline1) line2 = cuspatial.from_geopandas(gpdline2) got = line1.geom_equals(line2) expected = gpdline1.geom_equals(gpdline2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_geom_equals_linestring_reversed(): gpdline1 = gpd.GeoSeries([LineString([(0, 0), (1, 1)])]) gpdline2 = gpd.GeoSeries([LineString([(1, 1), (0, 0)])]) line1 = cuspatial.from_geopandas(gpdline1) line2 = cuspatial.from_geopandas(gpdline2) got = line1.geom_equals(line2) expected = gpdline1.geom_equals(gpdline2) pd.testing.assert_series_equal(expected, got.to_pandas()) @pytest.mark.parametrize( "lhs", [ [ LineString([(0, 0), (1, 1)]), LineString([(0, 0), (1, 1)]), LineString([(0, 0), (1, 1)]), ], [ LineString([(1, 1), (2, 2)]), LineString([(1, 1), (2, 2)]), LineString([(1, 1), (2, 2)]), ], [ LineString([(2, 2), (3, 3)]), LineString([(2, 2), (3, 3)]), LineString([(2, 2), (3, 3)]), ], ], ) def test_3_linestrings_equals_3_linestrings_one_equal(lhs): gpdline1 = gpd.GeoSeries(lhs) gpdline2 = gpd.GeoSeries( [ LineString([(0, 0), (1, 1)]), LineString([(1, 1), (2, 2)]), LineString([(2, 2), (3, 3)]), ] ) line1 = cuspatial.from_geopandas(gpdline1) line2 = cuspatial.from_geopandas(gpdline2) got = line1.geom_equals(line2) expected = gpdline1.geom_equals(gpdline2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_10_linestrings_geom_equals_10_linestrings(linestring_generator): gpdlines1 = gpd.GeoSeries([*linestring_generator(10, 5)]) gpdlines2 = gpd.GeoSeries([*linestring_generator(10, 5)]) lines1 = cuspatial.from_geopandas(gpdlines1) lines2 = cuspatial.from_geopandas(gpdlines2) got = lines1.geom_equals(lines2) expected = gpdlines1.geom_equals(gpdlines2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_100_linestrings_geom_equals_100_linestrings(linestring_generator): gpdlines1 = gpd.GeoSeries([*linestring_generator(100, 5)]) gpdlines2 = gpd.GeoSeries([*linestring_generator(100, 5)]) lines1 = cuspatial.from_geopandas(gpdlines1) lines2 = cuspatial.from_geopandas(gpdlines2) got = lines1.geom_equals(lines2) expected = gpdlines1.geom_equals(gpdlines2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_geom_equals_polygon(): gpdline = gpd.GeoSeries([LineString([(0, 0), (1, 1)])]) gpdpolygon = gpd.GeoSeries(Polygon([[0, 0], [1, 0], [1, 1], [0, 0]])) line = cuspatial.from_geopandas(gpdline) polygon = cuspatial.from_geopandas(gpdpolygon) got = line.geom_equals(polygon) expected = gpdline.geom_equals(gpdpolygon) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_100_linestrings_geom_equals_100_polygons( polygon_generator, linestring_generator ): gpdlines = gpd.GeoSeries([*linestring_generator(100, 5)]) gpdpolygons = gpd.GeoSeries([*polygon_generator(100, 0)]) lines = cuspatial.from_geopandas(gpdlines) polygons = cuspatial.from_geopandas(gpdpolygons) got = lines.geom_equals(polygons) expected = gpdlines.geom_equals(gpdpolygons) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_polygon_geom_equals_linestring(): gpdline = gpd.GeoSeries([LineString([(0, 0), (1, 1)])]) gpdpolygon = gpd.GeoSeries(Polygon([[0, 0], [1, 0], [1, 1], [0, 0]])) line = cuspatial.from_geopandas(gpdline) polygon = cuspatial.from_geopandas(gpdpolygon) got = polygon.geom_equals(line) expected = gpdpolygon.geom_equals(gpdline) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_100_polygons_geom_equals_100_linestrings( polygon_generator, linestring_generator ): gpdpolygons = gpd.GeoSeries([*polygon_generator(100, 0)]) gpdlines = gpd.GeoSeries([*linestring_generator(100, 5)]) polygons = cuspatial.from_geopandas(gpdpolygons) lines = cuspatial.from_geopandas(gpdlines) got = polygons.geom_equals(lines) expected = gpdpolygons.geom_equals(gpdlines) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_point_contains_point(): gpdpoint1 = gpd.GeoSeries([Point(0, 0)]) gpdpoint2 = gpd.GeoSeries([Point(0, 0)]) point1 = cuspatial.from_geopandas(gpdpoint1) point2 = cuspatial.from_geopandas(gpdpoint2) got = point1.contains_properly(point2) expected = gpdpoint1.contains(gpdpoint2) assert (got.values_host == expected.values).all() def test_point_not_contains_point(): gpdpoint1 = gpd.GeoSeries([Point(0, 0)]) gpdpoint2 = gpd.GeoSeries([Point(1, 1)]) point1 = cuspatial.from_geopandas(gpdpoint1) point2 = cuspatial.from_geopandas(gpdpoint2) got = point1.contains_properly(point2) expected = gpdpoint1.contains(gpdpoint2) assert (got.values_host == expected.values).all() def test_100_points_contains_100_points(point_generator): gpdpoints1 = gpd.GeoSeries([*point_generator(100)]) gpdpoints2 = gpd.GeoSeries([*point_generator(100)]) points1 = cuspatial.from_geopandas(gpdpoints1) points2 = cuspatial.from_geopandas(gpdpoints2) got = points1.contains_properly(points2) expected = gpdpoints1.contains(gpdpoints2) assert (got.values_host == expected.values).all() def test_point_covers_point(): gpdpoint1 = gpd.GeoSeries([Point(0, 0)]) gpdpoint2 = gpd.GeoSeries([Point(0, 0)]) point1 = cuspatial.from_geopandas(gpdpoint1) point2 = cuspatial.from_geopandas(gpdpoint2) got = point1.covers(point2) expected = gpdpoint1.covers(gpdpoint2) assert (got.values_host == expected.values).all() def test_point_not_covers_point(): gpdpoint1 = gpd.GeoSeries([Point(0, 0)]) gpdpoint2 = gpd.GeoSeries([Point(1, 1)]) point1 = cuspatial.from_geopandas(gpdpoint1) point2 = cuspatial.from_geopandas(gpdpoint2) got = point1.covers(point2) expected = gpdpoint1.covers(gpdpoint2) assert (got.values_host == expected.values).all() def test_100_points_covers_100_points(point_generator): gpdpoints1 = gpd.GeoSeries([*point_generator(100)]) gpdpoints2 = gpd.GeoSeries([*point_generator(100)]) points1 = cuspatial.from_geopandas(gpdpoints1) points2 = cuspatial.from_geopandas(gpdpoints2) got = points1.covers(points2) expected = gpdpoints1.covers(gpdpoints2) assert (got.values_host == expected.values).all() def test_point_intersects_point(): gpdpoint1 = gpd.GeoSeries([Point(0, 0)]) gpdpoint2 = gpd.GeoSeries([Point(0, 0)]) point1 = cuspatial.from_geopandas(gpdpoint1) point2 = cuspatial.from_geopandas(gpdpoint2) got = point1.intersects(point2) expected = gpdpoint1.intersects(gpdpoint2) assert (got.values_host == expected.values).all() def test_point_not_intersects_point(): gpdpoint1 = gpd.GeoSeries([Point(0, 0)]) gpdpoint2 = gpd.GeoSeries([Point(1, 1)]) point1 = cuspatial.from_geopandas(gpdpoint1) point2 = cuspatial.from_geopandas(gpdpoint2) got = point1.intersects(point2) expected = gpdpoint1.intersects(gpdpoint2) assert (got.values_host == expected.values).all() def test_100_points_intersects_100_points(point_generator): gpdpoints1 = gpd.GeoSeries([*point_generator(100)]) gpdpoints2 = gpd.GeoSeries([*point_generator(100)]) points1 = cuspatial.from_geopandas(gpdpoints1) points2 = cuspatial.from_geopandas(gpdpoints2) got = points1.intersects(points2) expected = gpdpoints1.intersects(gpdpoints2) assert (got.values_host == expected.values).all() def test_point_within_point(): gpdpoint1 = gpd.GeoSeries([Point(0, 0)]) gpdpoint2 = gpd.GeoSeries([Point(0, 0)]) point1 = cuspatial.from_geopandas(gpdpoint1) point2 = cuspatial.from_geopandas(gpdpoint2) got = point1.within(point2) expected = gpdpoint1.within(gpdpoint2) assert (got.values_host == expected.values).all() def test_point_not_within_point(): gpdpoint1 = gpd.GeoSeries([Point(0, 0)]) gpdpoint2 = gpd.GeoSeries([Point(1, 1)]) point1 = cuspatial.from_geopandas(gpdpoint1) point2 = cuspatial.from_geopandas(gpdpoint2) got = point1.within(point2) expected = gpdpoint1.within(gpdpoint2) assert (got.values_host == expected.values).all() def test_100_points_within_100_points(point_generator): gpdpoints1 = gpd.GeoSeries(point_generator(100)) gpdpoints2 = gpd.GeoSeries(point_generator(100)) points1 = cuspatial.from_geopandas(gpdpoints1) points2 = cuspatial.from_geopandas(gpdpoints2) got = points1.within(points2).values_host expected = gpdpoints1.within(gpdpoints2).values assert (expected == got).all() def test_point_crosses_point(): gpdpoint1 = gpd.GeoSeries([Point(0, 0)]) gpdpoint2 = gpd.GeoSeries([Point(0, 0)]) point1 = cuspatial.from_geopandas(gpdpoint1) point2 = cuspatial.from_geopandas(gpdpoint2) got = point1.crosses(point2) expected = gpdpoint1.crosses(gpdpoint2) assert (got.values_host == expected.values).all() def test_point_not_crosses_point(): gpdpoint1 = gpd.GeoSeries([Point(0, 0)]) gpdpoint2 = gpd.GeoSeries([Point(1, 1)]) point1 = cuspatial.from_geopandas(gpdpoint1) point2 = cuspatial.from_geopandas(gpdpoint2) got = point1.crosses(point2) expected = gpdpoint1.crosses(gpdpoint2) assert (got.values_host == expected.values).all() @pytest.mark.parametrize( "points", [ [Point(0, 0), Point(3, 3), Point(3, 3)], [Point(3, 3), Point(1, 1), Point(3, 3)], [Point(3, 3), Point(3, 3), Point(2, 2)], ], ) def test_three_points_crosses_three_points(points): gpdpoints1 = gpd.GeoSeries(points) gpdpoints2 = gpd.GeoSeries([Point(0, 0), Point(1, 1), Point(2, 2)]) points1 = cuspatial.from_geopandas(gpdpoints1) points2 = cuspatial.from_geopandas(gpdpoints2) got = points1.crosses(points2) expected = gpdpoints1.crosses(gpdpoints2) assert (got.values_host == expected.values).all() def test_100_points_crosses_100_points(point_generator): gpdpoints1 = gpd.GeoSeries([*point_generator(100)]) gpdpoints2 = gpd.GeoSeries([*point_generator(100)]) points1 = cuspatial.from_geopandas(gpdpoints1) points2 = cuspatial.from_geopandas(gpdpoints2) got = points1.crosses(points2) expected = gpdpoints1.crosses(gpdpoints2) assert (got.values_host == expected.values).all() def test_point_overlaps_point(): gpdpoint1 = gpd.GeoSeries([Point(0, 0)]) gpdpoint2 = gpd.GeoSeries([Point(0, 0)]) point1 = cuspatial.from_geopandas(gpdpoint1) point2 = cuspatial.from_geopandas(gpdpoint2) got = point1.overlaps(point2) expected = gpdpoint1.overlaps(gpdpoint2) assert (got.values_host == expected.values).all() def test_point_not_overlaps_point(): gpdpoint1 = gpd.GeoSeries([Point(0, 0)]) gpdpoint2 = gpd.GeoSeries([Point(1, 1)]) point1 = cuspatial.from_geopandas(gpdpoint1) point2 = cuspatial.from_geopandas(gpdpoint2) got = point1.overlaps(point2) expected = gpdpoint1.overlaps(gpdpoint2) assert (got.values_host == expected.values).all() @pytest.mark.parametrize( "points", [ [Point(0, 0), Point(3, 3), Point(3, 3)], [Point(3, 3), Point(1, 1), Point(3, 3)], [Point(3, 3), Point(3, 3), Point(2, 2)], ], ) def test_three_points_overlaps_three_points(points): gpdpoints1 = gpd.GeoSeries(points) gpdpoints2 = gpd.GeoSeries([Point(0, 0), Point(1, 1), Point(2, 2)]) points1 = cuspatial.from_geopandas(gpdpoints1) points2 = cuspatial.from_geopandas(gpdpoints2) got = points1.overlaps(points2) expected = gpdpoints1.overlaps(gpdpoints2) assert (got.values_host == expected.values).all() def test_100_points_overlaps_100_points(point_generator): gpdpoint1 = gpd.GeoSeries([*point_generator(100)]) gpdpoint2 = gpd.GeoSeries([*point_generator(100)]) point1 = cuspatial.from_geopandas(gpdpoint1) point2 = cuspatial.from_geopandas(gpdpoint2) got = point1.overlaps(point2) expected = gpdpoint1.overlaps(gpdpoint2) assert (got.values_host == expected.values).all() def test_multipoint_geom_equals_multipoint(): gpdpoint1 = gpd.GeoSeries([MultiPoint([(0, 0), (1, 1)])]) gpdpoint2 = gpd.GeoSeries([MultiPoint([(0, 0), (1, 1)])]) point1 = cuspatial.from_geopandas(gpdpoint1) point2 = cuspatial.from_geopandas(gpdpoint2) got = point1.geom_equals(point2) expected = gpdpoint1.geom_equals(gpdpoint2) assert (got.values_host == expected.values).all() def test_multipoint_not_geom_equals_multipoint(): gpdpoint1 = gpd.GeoSeries([MultiPoint([(0, 0), (1, 1)])]) gpdpoint2 = gpd.GeoSeries([MultiPoint([(0, 1), (1, 1)])]) point1 = cuspatial.from_geopandas(gpdpoint1) point2 = cuspatial.from_geopandas(gpdpoint2) got = point1.geom_equals(point2) expected = gpdpoint1.geom_equals(gpdpoint2) assert (got.values_host == expected.values).all() def test_100_multipoints_geom_equals_100_multipoints(multipoint_generator): gpdpoints1 = gpd.GeoSeries([*multipoint_generator(100, 10)]) gpdpoints2 = gpd.GeoSeries([*multipoint_generator(100, 10)]) points1 = cuspatial.from_geopandas(gpdpoints1) points2 = cuspatial.from_geopandas(gpdpoints2) got = points1.geom_equals(points2) expected = gpdpoints1.geom_equals(gpdpoints2) assert (got.values_host == expected.values).all() @pytest.mark.parametrize( "lhs", [ [ MultiPoint([(0, 0), (1, 1)]), MultiPoint([(0, 0), (1, 1)]), MultiPoint([(0, 0), (1, 1)]), ], [ MultiPoint([(0, 0), (1, 1)]), MultiPoint([(0, 1), (1, 1)]), MultiPoint([(0, 0), (1, 1)]), ], [ MultiPoint([(0, 0), (1, 1)]), MultiPoint([(0, 2), (1, 1)]), MultiPoint([(0, 0), (1, 1)]), ], ], ) def test_3_multipoints_geom_equals_3_multipoints_one_equal(lhs): gpdpoints1 = gpd.GeoSeries(lhs) gpdpoints2 = gpd.GeoSeries( [ MultiPoint([(0, 0), (0, 1)]), MultiPoint([(0, 0), (1, 1)]), MultiPoint([(0, 0), (2, 1)]), ] ) points1 = cuspatial.from_geopandas(gpdpoints1) points2 = cuspatial.from_geopandas(gpdpoints2) got = points1.geom_equals(points2) expected = gpdpoints1.geom_equals(gpdpoints2) assert (got.values_host == expected.values).all() def test_3_multipoints_geom_equals_3_multipoints_misordered(): gpdpoints1 = gpd.GeoSeries( [ MultiPoint([(0, 0), (1, 1)]), MultiPoint([(0, 0), (1, 1)]), MultiPoint([(0, 0), (1, 1)]), ] ) gpdpoints2 = gpd.GeoSeries( [ MultiPoint([(1, 1), (0, 0)]), MultiPoint([(1, 1), (0, 0)]), MultiPoint([(1, 1), (0, 0)]), ] ) points1 = cuspatial.from_geopandas(gpdpoints1) points2 = cuspatial.from_geopandas(gpdpoints2) got = points1.geom_equals(points2) expected = gpdpoints1.geom_equals(gpdpoints2) assert (got.values_host == expected.values).all() def test_3_linestrings_geom_equals_3_linestrings_misordered(): gpdline1 = gpd.GeoSeries( [ LineString([(1, 1), (0, 0)]), LineString([(2, 2), (1, 1)]), LineString([(3, 3), (2, 2)]), ] ) gpdline2 = gpd.GeoSeries( [ LineString([(0, 0), (1, 1)]), LineString([(1, 1), (2, 2)]), LineString([(2, 2), (3, 3)]), ] ) line1 = cuspatial.from_geopandas(gpdline1) line2 = cuspatial.from_geopandas(gpdline2) got = line1.geom_equals(line2) expected = gpdline1.geom_equals(gpdline2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_3_linestrings_geom_equals_3_linestrings_longer(): gpdline1 = gpd.GeoSeries( [ LineString([(1, 1), (0, 0), (0, 4)]), LineString([(2, 2), (1, 1), (0, 4)]), LineString([(3, 3), (2, 2), (0, 4)]), ] ) gpdline2 = gpd.GeoSeries( [ LineString([(0, 0), (1, 1), (0, 4)]), LineString([(1, 1), (2, 2), (0, 4)]), LineString([(2, 2), (3, 3), (0, 4)]), ] ) line1 = cuspatial.from_geopandas(gpdline1) line2 = cuspatial.from_geopandas(gpdline2) got = line1.geom_equals(line2) expected = gpdline1.geom_equals(gpdline2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_pair_linestrings_different_last_two(): gpdlinestring1 = gpd.GeoSeries( [ LineString([(0, 0), (1, 1), (2, 1)]), ] ) gpdlinestring2 = gpd.GeoSeries( [ LineString([(0, 0), (2, 1), (1, 1)]), ] ) linestring1 = cuspatial.from_geopandas(gpdlinestring1) linestring2 = cuspatial.from_geopandas(gpdlinestring2) got = linestring1.geom_equals(linestring2) expected = gpdlinestring1.geom_equals(gpdlinestring2) pd.testing.assert_series_equal(expected, got.to_pandas()) @pytest.mark.xfail( reason="""The current implementation of .contains conceals this special case. Unsure of the solution.""" ) def test_pair_polygons_different_ordering(): gpdpoly1 = gpd.GeoSeries( [ Polygon([(0, 0), (1, 0), (1, 1), (0.5, 0.5), (0, 1), (0, 0)]), ] ) gpdpoly2 = gpd.GeoSeries( [ Polygon([(0, 0), (0.5, 0.5), (1, 0), (1, 1), (0, 1), (0, 0)]), ] ) poly1 = cuspatial.from_geopandas(gpdpoly1) poly2 = cuspatial.from_geopandas(gpdpoly2) got = poly1.geom_equals(poly2) expected = gpdpoly1.geom_equals(gpdpoly2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_pair_polygons_different_winding(): gpdpoly1 = gpd.GeoSeries( [ Polygon([(0, 0), (1, 0), (1, 1), (0.5, 0.5), (0, 1), (0, 0)]), ] ) gpdpoly2 = gpd.GeoSeries( [ Polygon([(1, 0), (1, 1), (0.5, 0.5), (0, 1), (0, 0), (1, 0)]), ] ) poly1 = cuspatial.from_geopandas(gpdpoly1) poly2 = cuspatial.from_geopandas(gpdpoly2) got = poly1.geom_equals(poly2) expected = gpdpoly1.geom_equals(gpdpoly2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_3_polygons_geom_equals_3_polygons_misordered_corrected_vertex(): gpdpoly1 = gpd.GeoSeries( [ Polygon([(0, 0), (0, 1), (1, 1), (0, 0)]), Polygon([(0, 0), (0, 1), (1, 1), (0, 0)]), Polygon([(0, 0), (0, 1), (1, 1), (0, 0)]), ] ) gpdpoly2 = gpd.GeoSeries( [ Polygon([(0, 0), (1, 1), (0, 1), (0, 0)]), # Oppositely wound Polygon([(1, 1), (0, 1), (0, 0), (1, 1)]), # Wound by +1 offset Polygon([(0, 1), (0, 0), (1, 1), (0, 1)]), # Wound by -1 offset ] ) poly1 = cuspatial.from_geopandas(gpdpoly1) poly2 = cuspatial.from_geopandas(gpdpoly2) got = poly1.geom_equals(poly2) expected = gpdpoly1.geom_equals(gpdpoly2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_polygon_geom_equals_polygon(): gpdpolygon1 = gpd.GeoSeries(Polygon([[0, 0], [1, 0], [1, 1], [0, 0]])) gpdpolygon2 = gpd.GeoSeries(Polygon([[0, 0], [1, 0], [1, 1], [0, 0]])) polygon1 = cuspatial.from_geopandas(gpdpolygon1) polygon2 = cuspatial.from_geopandas(gpdpolygon2) got = polygon1.geom_equals(polygon2) expected = gpdpolygon1.geom_equals(gpdpolygon2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_polygon_geom_equals_polygon_swap_inner(): gpdpolygon1 = gpd.GeoSeries(Polygon([[0, 0], [1, 0], [1, 1], [0, 0]])) gpdpolygon2 = gpd.GeoSeries(Polygon([[0, 0], [1, 1], [1, 0], [0, 0]])) polygon1 = cuspatial.from_geopandas(gpdpolygon1) polygon2 = cuspatial.from_geopandas(gpdpolygon2) got = polygon1.geom_equals(polygon2) expected = gpdpolygon1.geom_equals(gpdpolygon2) pd.testing.assert_series_equal(expected, got.to_pandas()) @pytest.mark.parametrize( "lhs", [ [ Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), ], [ Polygon([[0, 0], [2, 0], [2, 2], [0, 0]]), Polygon([[0, 0], [2, 0], [2, 2], [0, 0]]), Polygon([[0, 0], [2, 0], [2, 2], [0, 0]]), ], [ Polygon([[0, 0], [3, 0], [3, 3], [0, 0]]), Polygon([[0, 0], [3, 0], [3, 3], [0, 0]]), Polygon([[0, 0], [3, 0], [3, 3], [0, 0]]), ], ], ) def test_3_polygons_geom_equals_3_polygons_one_equal(lhs): gpdpolygons1 = gpd.GeoSeries(lhs) gpdpolygons2 = gpd.GeoSeries( [ Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), Polygon([[0, 0], [2, 0], [2, 2], [0, 0]]), Polygon([[0, 0], [3, 0], [3, 3], [0, 0]]), ] ) polygons1 = cuspatial.from_geopandas(gpdpolygons1) polygons2 = cuspatial.from_geopandas(gpdpolygons2) got = polygons1.geom_equals(polygons2) expected = gpdpolygons1.geom_equals(gpdpolygons2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_100_polygons_geom_equals_100_polygons(polygon_generator): gpdpolygons1 = gpd.GeoSeries([*polygon_generator(100, 0)]) gpdpolygons2 = gpd.GeoSeries([*polygon_generator(100, 0)]) polygons1 = cuspatial.from_geopandas(gpdpolygons1) polygons2 = cuspatial.from_geopandas(gpdpolygons2) got = polygons1.geom_equals(polygons2) expected = gpdpolygons1.geom_equals(gpdpolygons2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_3_polygons_geom_equals_3_polygons_different_sizes(): gpdpoly1 = gpd.GeoSeries( [ Polygon([(0, 0), (0, 1), (1, 1), (1, 0)]), # Length 5 Polygon([(0, 0), (0, 1), (1, 1), (1, 0)]), Polygon([(0, 0), (0, 1), (1, 1), (1, 0)]), ] ) gpdpoly2 = gpd.GeoSeries( [ Polygon( [(0, 0), (1, 1), (1, 0), (0, 0)] ), # Oppositely wound, length 4 Polygon([(1, 1), (1, 0), (0, 0), (1, 1)]), # Wound by +1 offset Polygon([(1, 0), (0, 0), (1, 1), (1, 0)]), # Wound by -1 offset ] ) poly1 = cuspatial.from_geopandas(gpdpoly1) poly2 = cuspatial.from_geopandas(gpdpoly2) got = poly1.geom_equals(poly2) expected = gpdpoly1.geom_equals(gpdpoly2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_3_polygons_geom_equals_3_polygons_misordered(): gpdpoly1 = gpd.GeoSeries( [ Polygon([(0, 0), (0, 1), (1, 1), (0, 0)]), Polygon([(0, 0), (0, 1), (1, 1), (0, 0)]), Polygon([(0, 0), (0, 1), (1, 1), (0, 0)]), ] ) gpdpoly2 = gpd.GeoSeries( [ Polygon([(0, 0), (1, 1), (1, 0), (0, 0)]), # Oppositely wound Polygon([(1, 1), (1, 0), (0, 0), (1, 1)]), # Wound by +1 offset Polygon([(1, 0), (0, 0), (1, 1), (1, 0)]), # Wound by -1 offset ] ) poly1 = cuspatial.from_geopandas(gpdpoly1) poly2 = cuspatial.from_geopandas(gpdpoly2) got = poly1.geom_equals(poly2) expected = gpdpoly1.geom_equals(gpdpoly2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_orders(): gpdlinestring1 = gpd.GeoSeries( [ LineString([(0, 0), (1, 1), (1, 0), (0, 0)]), ] ) gpdlinestring2 = gpd.GeoSeries( [ LineString([(0, 0), (1, 0), (1, 1), (0, 0)]), ] ) linestring1 = cuspatial.from_geopandas(gpdlinestring1) linestring2 = cuspatial.from_geopandas(gpdlinestring2) got = linestring1.geom_equals(linestring2) expected = gpdlinestring1.geom_equals(gpdlinestring2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_indexes(): linestring1 = cuspatial.GeoSeries( [ LineString([(0, 0), (1, 0), (1, 1), (0, 0)]), LineString([(0, 0), (1, 1), (1, 0), (0, 0)]), ] ) linestring2 = cuspatial.GeoSeries( [ LineString([(0, 0), (1, 0), (1, 1), (0, 0)]), LineString([(0, 0), (1, 1), (1, 0), (0, 0)]), ] ) index1 = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1] index2 = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] linestring1 = linestring1[index1].reset_index(drop=True) linestring2 = linestring2[index2].reset_index(drop=True) gpdlinestring1 = linestring1.to_geopandas() gpdlinestring2 = linestring2.to_geopandas() got = linestring1.geom_equals(linestring2) expected = gpdlinestring1.geom_equals(gpdlinestring2) pd.testing.assert_series_equal(expected, got.to_pandas())
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/binpreds/test_binpred_test_dispatch.py
# Copyright (c) 2023, NVIDIA CORPORATION. import os import pandas as pd from binpred_test_dispatch import predicate, simple_test # noqa: F401 # In the below file, all failing tests are recorded with visualizations. LOG_DISPATCHED_PREDICATES = os.environ.get("LOG_DISPATCHED_PREDICATES", False) if LOG_DISPATCHED_PREDICATES: out_file = open("test_binpred_test_dispatch.log", "w") def execute_test(pred, lhs, rhs): gpdlhs = lhs.to_geopandas() gpdrhs = rhs.to_geopandas() # Reverse pred_fn = getattr(rhs, pred) got = pred_fn(lhs) gpd_pred_fn = getattr(gpdrhs, pred) expected = gpd_pred_fn(gpdlhs) assert (got.values_host == expected.values).all() # Forward pred_fn = getattr(lhs, pred) got = pred_fn(rhs) gpd_pred_fn = getattr(gpdlhs, pred) expected = gpd_pred_fn(gpdrhs) assert (got.values_host == expected.values).all() def test_simple_features( predicate, # noqa: F811 simple_test, # noqa: F811 predicate_passes, predicate_fails, feature_passes, feature_fails, request, ): """Parameterized test fixture that runs a binary predicate test for each combination of geometry types and binary predicates. Enable the `LOG_DISPATCHED_PREDICATES` environment variable to log the dispatched predicate results. Uses four fixtures from `conftest.py` to store the number of times each binary predicate has passed and failed, and the number of times each combination of geometry types has passed and failed. These results are saved to CSV files after each test. The result of the tests can be summarized with `tests/binpreds/summarize_binpred_test_dispatch_results.py`. Uses the @xfail_on_exception decorator to mark a test as xfailed if an exception is thrown. This is a temporary measure to allow the test suite to run to completion while we work on fixing the failing tests. Parameters ---------- predicate : str The name of the binary predicate to test. simple_test : tuple A tuple containing the name of the test, a docstring that describes the test, and the left and right geometry objects. predicate_passes : dict A dictionary fixture containing the number of times each binary predicate has passed. predicate_fails : dict A dictionary fixture containing the number of times each binary predicate has failed. feature_passes : dict A dictionary fixture containing the number of times each combination of geometry types has passed. feature_fails : dict A dictionary fixture containing the number of times each combination of geometry types has failed. request : pytest.FixtureRequest The pytest request object. Used to print the test name in diagnostic output. """ if not LOG_DISPATCHED_PREDICATES: (lhs, rhs) = simple_test[2], simple_test[3] execute_test(predicate, lhs, rhs) else: try: execute_test(predicate, lhs, rhs) # The test is complete, the rest is just logging. try: # The test passed, store the results. predicate_passes[predicate] = ( 1 if predicate not in predicate_passes else predicate_passes[predicate] + 1 ) feature_passes[(lhs.column_type, rhs.column_type)] = ( 1 if (lhs.column_type, rhs.column_type) not in feature_passes else feature_passes[(lhs.column_type, rhs.column_type)] + 1 ) passes_df = pd.DataFrame( { "predicate": list(predicate_passes.keys()), "predicate_passes": list(predicate_passes.values()), } ) passes_df.to_csv("predicate_passes.csv", index=False) passes_df = pd.DataFrame( { "feature": list(feature_passes.keys()), "feature_passes": list(feature_passes.values()), } ) passes_df.to_csv("feature_passes.csv", index=False) except Exception as e: raise e except Exception as e: # The test failed, store the results. out_file.write( f"""{predicate}, ------------ {simple_test[0]}\n{simple_test[1]}\nfailed test: {request.node.name}\n\n""" ) predicate_fails[predicate] = ( 1 if predicate not in predicate_fails else predicate_fails[predicate] + 1 ) feature_fails[(lhs.column_type, rhs.column_type)] = ( 1 if (lhs.column_type, rhs.column_type) not in feature_fails else feature_fails[(lhs.column_type, rhs.column_type)] + 1 ) predicate_fails_df = pd.DataFrame( { "predicate": list(predicate_fails.keys()), "predicate_fails": list(predicate_fails.values()), } ) predicate_fails_df.to_csv("predicate_fails.csv", index=False) feature_fails_df = pd.DataFrame( { "feature": list(feature_fails.keys()), "feature_fails": list(feature_fails.values()), } ) feature_fails_df.to_csv("feature_fails.csv", index=False) raise e
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/binpreds/test_intersects_only_binpreds.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION import pandas as pd import pytest from shapely.geometry import ( LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, ) import cuspatial def test_point_intersects_point(): g1 = cuspatial.GeoSeries([Point(0.0, 0.0)]) g2 = cuspatial.GeoSeries([Point(0.0, 0.0)]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_points_intersects_points(): g1 = cuspatial.GeoSeries([Point(0.0, 0.0), Point(0.0, 0.0)]) g2 = cuspatial.GeoSeries([Point(0.0, 0.0), Point(0.0, 1.0)]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_intersects_point(): g1 = cuspatial.GeoSeries([LineString([(0.0, 0.0), (0.0, 1.0)])]) g2 = cuspatial.GeoSeries([Point(0.0, 0.0)]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_extra_linestring_intersects_point(): g1 = cuspatial.GeoSeries([LineString([(0.0, 0.0), (1.0, 1.0)])]) g2 = cuspatial.GeoSeries([Point(1.0, 1.0)]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_extra_linestring_intersects_point_2(): g1 = cuspatial.GeoSeries([LineString([(0.0, 0.0), (1.0, 1.0)])]) g2 = cuspatial.GeoSeries([Point(0.5, 0.5)]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestrings_intersects_points(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), ] ) g2 = cuspatial.GeoSeries([Point(0.0, 0.0), Point(0.0, 0.0)]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestrings_intersects_points_only_one(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), ] ) g2 = cuspatial.GeoSeries([Point(0.0, 0.0), Point(2.0, 2.0)]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestrings_intersects_points_only_one_reversed(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), ] ) g2 = cuspatial.GeoSeries([Point(2.0, 2.0), Point(0.0, 0.0)]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_three_linestrings_intersects_three_points_match_middle(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), ] ) g2 = cuspatial.GeoSeries( [ Point(2.0, 2.0), Point(0.0, 0.0), Point(2.0, 2.0), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_three_linestrings_intersects_three_points_exclude_middle(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), ] ) g2 = cuspatial.GeoSeries( [ Point(0.0, 0.0), Point(2.0, 2.0), Point(0.0, 0.0), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_100_linestrings_intersects_100_points( linestring_generator, point_generator ): g1 = cuspatial.GeoSeries([*linestring_generator(100, 4)]) g2 = cuspatial.GeoSeries([*point_generator(100)]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_intersects_multipoint(): g1 = cuspatial.GeoSeries([LineString([(0.0, 0.0), (1.0, 1.0)])]) g2 = cuspatial.GeoSeries([MultiPoint([(0.0, 0.0), (1.0, 1.0)])]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_intersects_multipoint_midpoint(): g1 = cuspatial.GeoSeries([LineString([(0.0, 0.0), (1.0, 1.0)])]) g2 = cuspatial.GeoSeries([MultiPoint([(0.5, 0.5), (0.5, 0.5)])]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_intersects_multipoint_midpoint_disordered(): g1 = cuspatial.GeoSeries([LineString([(0.0, 0.0), (1.0, 1.0)])]) g2 = cuspatial.GeoSeries([MultiPoint([(0.0, 0.0), (0.5, 0.5)])]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_intersects_multipoint_midpoint_disordered_2(): g1 = cuspatial.GeoSeries([LineString([(0.0, 0.0), (1.0, 1.0)])]) g2 = cuspatial.GeoSeries([MultiPoint([(0.5, 0.5), (0.0, 0.0)])]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_three_linestrings_intersects_middle_multipoint(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), ] ) g2 = cuspatial.GeoSeries( [ MultiPoint([(2.0, 2.0), (3.0, 3.0)]), MultiPoint([(0.0, 0.0), (0.0, 0.0)]), MultiPoint([(2.0, 2.0), (4.0, 4.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_three_linestrings_intersects_not_middle_multipoint(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), ] ) g2 = cuspatial.GeoSeries( [ MultiPoint([(0.0, 0.0), (0.0, 0.0)]), MultiPoint([(2.0, 2.0), (3.0, 3.0)]), MultiPoint([(0.0, 0.0), (0.0, 0.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_intersects_multipoint_cross_intersection(): g1 = cuspatial.GeoSeries([LineString([(0.0, 0.0), (1.0, 1.0)])]) g2 = cuspatial.GeoSeries( [MultiPoint([(0.0, 1.0), (0.5, 0.5), (1.0, 0.0)])] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) @pytest.mark.xfail(reason="Multipoints not supported yet.") def test_linestring_intersects_multipoint_implicit_cross_intersection(): g1 = cuspatial.GeoSeries([LineString([(0.0, 0.0), (1.0, 1.0)])]) g2 = cuspatial.GeoSeries([MultiPoint([(0.0, 1.0), (1.0, 0.0)])]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) @pytest.mark.xfail(reason="Multipoints not supported yet.") def test_100_linestrings_intersects_100_multipoints( linestring_generator, multipoint_generator ): g1 = cuspatial.GeoSeries([*linestring_generator(15, 4)]) g2 = cuspatial.GeoSeries([*multipoint_generator(15, 4)]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_intersects_linestring_crosses(): g1 = cuspatial.GeoSeries([LineString([(0.0, 0.0), (1.0, 1.0)])]) g2 = cuspatial.GeoSeries([LineString([(0.0, 1.0), (1.0, 0.0)])]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestering_intersects_linestring_parallel(): g1 = cuspatial.GeoSeries([LineString([(0.0, 0.0), (0.0, 1.0)])]) g2 = cuspatial.GeoSeries([LineString([(1.0, 0.0), (1.0, 1.0)])]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_intersects_linestring_overlaps(): g1 = cuspatial.GeoSeries([LineString([(0.0, 0.0), (1.0, 1.0)])]) g2 = cuspatial.GeoSeries([LineString([(0.0, 0.0), (0.5, 0.5)])]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_two_linestrings_intersects_two_linestrings_parallel(): g1 = cuspatial.GeoSeries( [ LineString([(1.0, 1.0), (1.0, 2.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), ] ) g2 = cuspatial.GeoSeries( [ LineString([(2.0, 0.0), (2.0, 2.0)]), LineString([(1.0, 0.0), (1.0, 1.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_two_linestrings_intersects_two_linestrings_overlaps(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (1.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), ] ) g2 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.5, 0.5)]), LineString([(0.5, 0.5), (1.0, 1.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_two_linestrings_intersects_two_linestrings_touches(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (1.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), ] ) g2 = cuspatial.GeoSeries( [ LineString([(1.0, 1.0), (2.0, 2.0)]), LineString([(1.0, 0.0), (1.0, 1.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_two_linestrings_intersects_two_linestrings_single(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 1.0), (1.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), ] ) g2 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_two_linestrings_intersects_two_linestrings_single_reversed(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 1.0), (1.0, 1.0)]), ] ) g2 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_three_linestrings_intersects_three_linestrings_middle(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 1.0), (1.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), ] ) g2 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_three_linestrings_intersects_three_linestrings_not_middle(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 1.0), (1.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 1.0), (1.0, 1.0)]), ] ) g2 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (0.0, 1.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_100_linestrings_intersects_100_linestrings(linestring_generator): g1 = cuspatial.GeoSeries([*linestring_generator(100, 5)]) g2 = cuspatial.GeoSeries([*linestring_generator(100, 5)]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_100_linestrings_intersects_100_multilinestrings( linestring_generator, multilinestring_generator ): g1 = cuspatial.GeoSeries([*linestring_generator(100, 5)]) g2 = cuspatial.GeoSeries([*multilinestring_generator(100, 5, 5)]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_100_multilinestrings_intersects_100_linestrings( linestring_generator, multilinestring_generator ): g1 = cuspatial.GeoSeries([*multilinestring_generator(100, 5, 5)]) g2 = cuspatial.GeoSeries([*linestring_generator(100, 5)]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_100_multilinestrings_intersects_100_multilinestrings( multilinestring_generator, ): g1 = cuspatial.GeoSeries([*multilinestring_generator(100, 5, 5)]) g2 = cuspatial.GeoSeries([*multilinestring_generator(100, 5, 5)]) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_intersects_multilinestring(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 1.0), (1.0, 1.0)]), ] ) g2 = cuspatial.GeoSeries( [ MultiLineString( [ [(0.0, 0.0), (0.0, 1.0)], [(0.0, 1.0), (1.0, 1.0)], ] ), MultiLineString( [ [(0.0, 0.0), (0.0, 1.0)], [(0.0, 1.0), (1.0, 1.0)], ] ), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_multilinestring_intersects_linestring(): g1 = cuspatial.GeoSeries( [ MultiLineString( [ [(0.0, 0.0), (0.0, 1.0)], [(0.0, 1.0), (1.0, 1.0)], ] ), MultiLineString( [ [(0.0, 0.0), (0.0, 1.0)], [(0.0, 1.0), (1.0, 1.0)], ] ), ] ) g2 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 1.0), (1.0, 1.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_intersects_polygon(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 1.0), (1.0, 1.0)]), ] ) g2 = cuspatial.GeoSeries( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_polygon_intersects_linestring(): g1 = cuspatial.GeoSeries( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) g2 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 1.0), (1.0, 1.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_multipolygon_intersects_linestring(): g1 = cuspatial.GeoSeries( [ MultiPolygon( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ), MultiPolygon( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ), ] ) g2 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 1.0), (1.0, 1.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_intersects_multipolygon(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 1.0), (1.0, 1.0)]), ] ) g2 = cuspatial.GeoSeries( [ MultiPolygon( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ), MultiPolygon( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_polygon_intersects_multipolygon(): g1 = cuspatial.GeoSeries( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) g2 = cuspatial.GeoSeries( [ MultiPolygon( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ), MultiPolygon( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_multipolygon_intersects_polygon(): g1 = cuspatial.GeoSeries( [ MultiPolygon( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ), MultiPolygon( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ), ] ) g2 = cuspatial.GeoSeries( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_multipolygon_intersects_multipolygon(): g1 = cuspatial.GeoSeries( [ MultiPolygon( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ), MultiPolygon( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ), ] ) g2 = cuspatial.GeoSeries( [ MultiPolygon( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ), MultiPolygon( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.intersects(g2) expected = gpdg1.intersects(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_point_disjoint_linestring(): g1 = cuspatial.GeoSeries( [ Point(0.0, 0.0), Point(0.0, 0.0), ] ) g2 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.disjoint(g2) expected = gpdg1.disjoint(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_disjoint_point(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) g2 = cuspatial.GeoSeries( [ Point(0.0, 0.0), Point(0.0, 0.0), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.disjoint(g2) expected = gpdg1.disjoint(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_disjoint_linestring(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) g2 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.disjoint(g2) expected = gpdg1.disjoint(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_contains_point(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) g2 = cuspatial.GeoSeries( [ Point(0.0, 0.0), Point(0.0, 0.0), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.contains_properly(g2) expected = gpdg1.contains(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_covers_point(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) g2 = cuspatial.GeoSeries( [ Point(0.0, 0.0), Point(0.0, 0.0), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.covers(g2) expected = gpdg1.covers(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_crosses_point(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) g2 = cuspatial.GeoSeries( [ Point(0.0, 0.0), Point(0.0, 0.0), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.crosses(g2) expected = gpdg1.crosses(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def linestring_crosses_linestring(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) g2 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.crosses(g2) expected = gpdg1.crosses(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def linestring_crosses_polygon(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) g2 = cuspatial.GeoSeries( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.crosses(g2) expected = gpdg1.crosses(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_overlaps_point(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) g2 = cuspatial.GeoSeries( [ Point(0.0, 0.0), Point(0.0, 0.0), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.overlaps(g2) expected = gpdg1.overlaps(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_overlaps_linestring(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) g2 = cuspatial.GeoSeries( [ LineString([(0.0, 1.0), (1.0, 1.0)]), LineString([(0.0, 1.0), (1.0, 1.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.overlaps(g2) expected = gpdg1.overlaps(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_linestring_overlaps_polygon(): g1 = cuspatial.GeoSeries( [ LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), LineString([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) g2 = cuspatial.GeoSeries( [ Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (0.0, 0.0)]), ] ) gpdg1 = g1.to_geopandas() gpdg2 = g2.to_geopandas() got = g1.overlaps(g2) expected = gpdg1.overlaps(gpdg2) pd.testing.assert_series_equal(expected, got.to_pandas())
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/binpreds/test_contains_properly.py
# Copyright (c) 2023, NVIDIA CORPORATION import cupy as cp import geopandas as gpd import numpy as np import pytest from shapely.geometry import LineString, MultiPolygon, Point, Polygon import cuspatial def test_manual_polygons(): gpdlhs = gpd.GeoSeries([Polygon(((-8, -8), (-8, 8), (8, 8), (8, -8)))] * 6) gpdrhs = gpd.GeoSeries( [ Polygon(((-8, -8), (-8, 8), (8, 8), (8, -8))), Polygon(((-2, -2), (-2, 2), (2, 2), (2, -2))), Polygon(((-10, -2), (-10, 2), (-6, 2), (-6, -2))), Polygon(((-2, 8), (-2, 12), (2, 12), (2, 8))), Polygon(((6, 0), (8, 2), (10, 0), (8, -2))), Polygon(((-2, -8), (-2, -4), (2, -4), (2, -8))), ] ) rhs = cuspatial.from_geopandas(gpdrhs) lhs = cuspatial.from_geopandas(gpdlhs) got = lhs.contains_properly(rhs).values_host expected = gpdlhs.contains(gpdrhs).values assert (got == np.array([False, True, False, False, False, False])).all() assert ( expected == np.array([True, True, False, False, False, True]) ).all() got = rhs.contains_properly(lhs).values_host expected = gpdrhs.contains(gpdlhs).values assert (got == np.array([False, False, False, False, False, False])).all() assert ( expected == np.array([True, False, False, False, False, False]) ).all() def test_one_polygon_one_linestring_crosses_the_diagonal(linestring_generator): gpdlinestring = gpd.GeoSeries(LineString([[0, 0], [1, 1]])) gpdpolygon = gpd.GeoSeries( Polygon([[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]) ) linestring = cuspatial.from_geopandas(gpdlinestring) polygons = cuspatial.from_geopandas(gpdpolygon) got = polygons.contains_properly(linestring).values_host expected = gpdpolygon.contains(gpdlinestring).values assert not np.any(got) assert np.all(expected) def test_one_polygon_with_hole_one_linestring_crossing_it( linestring_generator, ): gpdlinestring = gpd.GeoSeries(LineString([[0.5, 2.0], [3.5, 2.0]])) gpdpolygon = gpd.GeoSeries( Polygon( ( [0, 0], [0, 4], [4, 4], [4, 0], [0, 0], ), [ ( [1, 1], [1, 3], [3, 3], [3, 1], [1, 1], ) ], ) ) linestring = cuspatial.from_geopandas(gpdlinestring) polygons = cuspatial.from_geopandas(gpdpolygon) got = polygons.contains_properly(linestring).values_host expected = gpdpolygon.contains(gpdlinestring).values assert np.all(got) assert not np.any(expected) @pytest.mark.parametrize( "point, polygon, expects", [ [ Point([0.6, 0.06]), Polygon([[0, 0], [10, 1], [1, 1], [0, 0]]), False, ], [ Point([3.333, 1.111]), Polygon([[6, 2], [3, 1], [3, 4], [6, 2]]), True, ], [Point([3.33, 1.11]), Polygon([[6, 2], [3, 1], [3, 4], [6, 2]]), True], ], ) def test_float_precision_limits_failures(point, polygon, expects): gpdpoint = gpd.GeoSeries(point) gpdpolygon = gpd.GeoSeries(polygon) point = cuspatial.from_geopandas(gpdpoint) polygon = cuspatial.from_geopandas(gpdpolygon) got = polygon.contains_properly(point).values_host # GeoPandas results here are inconsistent. # expected = gpdpolygon.contains(gpdpoint).values # assert expected == True or False assert not np.any(got) @pytest.mark.parametrize( "point, polygon, expects", [ [ Point([0.66, 0.006]), Polygon([[0, 0], [10, 1], [1, 1], [0, 0]]), False, ], [ Point([0.666, 0.0006]), Polygon([[0, 0], [10, 1], [1, 1], [0, 0]]), False, ], ], ) def test_float_precision_limits(point, polygon, expects): """Corner case to test point on edges with floating point precision limits. Unique success cases identified by @mharris. These go in a pair with test_float_precision_limits_failures because these are inconsistent results, where 0.6 fails above (as True, within the polygon) and 0.66 below succeeds, though they are collinear. """ gpdpoint = gpd.GeoSeries(point) gpdpolygon = gpd.GeoSeries(polygon) point = cuspatial.from_geopandas(gpdpoint) polygon = cuspatial.from_geopandas(gpdpolygon) got = polygon.contains_properly(point).values_host expected = gpdpolygon.contains(gpdpoint).values assert got == expected assert got[0] == expects clockwiseTriangle = Polygon([[0, 0], [0, 1], [1, 1], [0, 0]]) clockwiseSquare = Polygon( [[-0.5, -0.5], [-0.5, 0.5], [0.5, 0.5], [0.5, -0.5], [-0.5, -0.5]] ) @pytest.mark.parametrize( "point, polygon, expects", [ [Point([-0.5, -0.5]), clockwiseSquare, False], [Point([-0.5, 0.5]), clockwiseSquare, False], [Point([0.5, 0.5]), clockwiseSquare, False], [Point([0.5, -0.5]), clockwiseSquare, False], # clockwise square, should be true [Point([-0.5, 0.0]), clockwiseSquare, False], [Point([0.0, 0.5]), clockwiseSquare, False], [Point([0.5, 0.0]), clockwiseSquare, False], [Point([0.0, -0.5]), clockwiseSquare, False], # wound clockwise, should be false [Point([0, 0]), clockwiseTriangle, False], [Point([0.0, 1.0]), clockwiseTriangle, False], [Point([1.0, 1.0]), clockwiseTriangle, False], [Point([0.0, 0.5]), clockwiseTriangle, False], [Point([0.5, 0.5]), clockwiseTriangle, False], [Point([0.5, 1]), clockwiseTriangle, False], # wound clockwise, should be true [Point([0.25, 0.5]), clockwiseTriangle, True], [Point([0.75, 0.9]), clockwiseTriangle, True], # wound counter clockwise, should be false [Point([0.0, 0.0]), Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), False], [Point([1.0, 0.0]), Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), False], [Point([1.0, 1.0]), Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), False], [Point([0.5, 0.0]), Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), False], [Point([0.5, 0.5]), Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), False], # wound counter clockwise, should be true [Point([0.5, 0.25]), Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), True], [Point([0.9, 0.75]), Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), True], ], ) def test_point_in_polygon(point, polygon, expects): gpdpoint = gpd.GeoSeries(point) gpdpolygon = gpd.GeoSeries(polygon) point = cuspatial.from_geopandas(gpdpoint) polygon = cuspatial.from_geopandas(gpdpolygon) got = polygon.contains_properly(point).values_host expected = gpdpolygon.contains(gpdpoint).values assert got == expected assert got[0] == expects def test_two_points_one_polygon(): gpdpoint = gpd.GeoSeries([Point(0, 0), Point(0, 0)]) gpdpolygon = gpd.GeoSeries(Polygon([[0, 0], [1, 0], [1, 1], [0, 0]])) point = cuspatial.from_geopandas(gpdpoint) polygon = cuspatial.from_geopandas(gpdpolygon) got = polygon.contains_properly(point).values_host expected = gpdpolygon.contains(gpdpoint).values assert (got == expected).all() def test_one_point_two_polygons(): gpdpoint = gpd.GeoSeries([Point(0, 0)]) gpdpolygon = gpd.GeoSeries( [ Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), Polygon([[-2, -2], [-2, 2], [2, 2], [-2, -2]]), ] ) point = cuspatial.from_geopandas(gpdpoint) polygon = cuspatial.from_geopandas(gpdpolygon) got = polygon.contains_properly(point).values_host expected = gpdpolygon.contains(gpdpoint).values assert (got == expected).all() def test_ten_fixed_points(): gpdpoints = gpd.GeoSeries( [ Point(0, 0), Point(0, 0), Point(0.5, 0.25), Point(0.5, 0.25), Point(0.5, 0.25), Point(0.5, 0.25), Point(0.5, 0.25), Point(0.5, 0.25), Point(0, 0), Point(0, 0), ] ) gpdpolygons = gpd.GeoSeries( [ Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), Polygon([[0, 0], [0, 1], [1, 1], [0, 0]]), Polygon([[0, 0], [0, 1], [1, 1], [0, 0]]), Polygon([[0, 0], [0, 1], [1, 1], [0, 0]]), Polygon([[0, 0], [0, 1], [1, 1], [0, 0]]), Polygon([[0, 0], [0, 1], [1, 1], [0, 0]]), ] ) points = cuspatial.from_geopandas(gpdpoints) polygons = cuspatial.from_geopandas(gpdpolygons) got = polygons.contains_properly(points).values_host expected = gpdpolygons.contains(gpdpoints).values assert (got == expected).all() def test_ten_pair_points(point_generator, polygon_generator): gpdpoints = gpd.GeoSeries([*point_generator(10)]) gpdpolygons = gpd.GeoSeries([*polygon_generator(10, 0)]) points = cuspatial.from_geopandas(gpdpoints) polygons = cuspatial.from_geopandas(gpdpolygons) got = polygons.contains_properly(points).values_host expected = gpdpolygons.contains(gpdpoints).values assert (got == expected).all() def test_one_polygon_with_hole_one_linestring_inside_it(linestring_generator): gpdlinestring = gpd.GeoSeries(LineString([[1.5, 2.0], [2.5, 2.0]])) gpdpolygon = gpd.GeoSeries( Polygon( ( [0, 0], [0, 4], [4, 4], [4, 0], [0, 0], ), [ ( [1, 1], [1, 3], [3, 3], [3, 1], [1, 1], ) ], ) ) linestring = cuspatial.from_geopandas(gpdlinestring) polygons = cuspatial.from_geopandas(gpdpolygon) got = polygons.contains_properly(linestring).values_host expected = gpdpolygon.contains(gpdlinestring).values assert (got == expected).all() def test_one_polygon_one_linestring(linestring_generator): gpdlinestring = gpd.GeoSeries([*linestring_generator(1, 4)]) gpdpolygon = gpd.GeoSeries( Polygon([[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]) ) linestring = cuspatial.from_geopandas(gpdlinestring) polygons = cuspatial.from_geopandas(gpdpolygon) got = polygons.contains_properly(linestring).values_host expected = gpdpolygon.contains(gpdlinestring).values assert (got == expected).all() def test_six_polygons_six_linestrings(linestring_generator): gpdlinestring = gpd.GeoSeries( [ LineString([[1.35, 0.35], [0.35, 0.65]]), LineString([[0.35, 0.35], [0.35, 0.65]]), LineString([[0.25, 0.25], [0.25, 0.75]]), LineString([[0.15, 0.15], [0.15, 0.85]]), LineString([[0.05, 0.05], [0.05, 0.95]]), LineString([[0.05, 0.05], [1.05, 0.95]]), ] ) gpdpolygon = gpd.GeoSeries( [ Polygon([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]), Polygon([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]), Polygon([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]), Polygon([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]), Polygon([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]), Polygon([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]), ] ) linestring = cuspatial.from_geopandas(gpdlinestring) polygons = cuspatial.from_geopandas(gpdpolygon) got = polygons.contains_properly(linestring).values_host expected = gpdpolygon.contains(gpdlinestring).values assert (got == expected).all() def test_max_polygons_max_linestrings(linestring_generator, polygon_generator): gpdlinestring = gpd.GeoSeries([*linestring_generator(31, 3)]) gpdpolygons = gpd.GeoSeries([*polygon_generator(31, 0)]) linestring = cuspatial.from_geopandas(gpdlinestring) polygons = cuspatial.from_geopandas(gpdpolygons) got = polygons.contains_properly(linestring).values_host expected = gpdpolygons.contains(gpdlinestring).values assert (got == expected).all() def test_one_polygon_one_polygon(polygon_generator): gpdlhs = gpd.GeoSeries(Polygon([[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]])) gpdrhs = gpd.GeoSeries([*polygon_generator(1, 0)]) rhs = cuspatial.from_geopandas(gpdrhs) lhs = cuspatial.from_geopandas(gpdlhs) got = lhs.contains_properly(rhs).values_host expected = gpdlhs.contains(gpdrhs).values assert (expected == got).all() got = rhs.contains_properly(lhs).values_host expected = gpdrhs.contains(gpdlhs).values assert (got == expected).all() def test_max_polygons_max_polygons(simple_polygon_generator): gpdlhs = gpd.GeoSeries([*simple_polygon_generator(31, 1, 3)]) gpdrhs = gpd.GeoSeries([*simple_polygon_generator(31, 1.49, 2)]) rhs = cuspatial.from_geopandas(gpdrhs) lhs = cuspatial.from_geopandas(gpdlhs) got = lhs.contains_properly(rhs).values_host expected = gpdlhs.contains(gpdrhs).values assert (expected == got).all() got = rhs.contains_properly(lhs).values_host expected = gpdrhs.contains(gpdlhs).values assert (got == expected).all() def test_one_polygon_one_multipoint(multipoint_generator, polygon_generator): gpdlhs = gpd.GeoSeries([*polygon_generator(1, 0)]) gpdrhs = gpd.GeoSeries([*multipoint_generator(1, 5)]) rhs = cuspatial.from_geopandas(gpdrhs) lhs = cuspatial.from_geopandas(gpdlhs) got = lhs.contains_properly(rhs).values_host expected = gpdlhs.contains(gpdrhs).values assert (got == expected).all() def test_max_polygons_max_multipoints(multipoint_generator, polygon_generator): gpdlhs = gpd.GeoSeries([*polygon_generator(31, 0, 1)]) gpdrhs = gpd.GeoSeries([*multipoint_generator(31, 10)]) rhs = cuspatial.from_geopandas(gpdrhs) lhs = cuspatial.from_geopandas(gpdlhs) got = lhs.contains_properly(rhs).values_host expected = gpdlhs.contains(gpdrhs).values assert (got == expected).all() def test_multi_contains(): lhs = cuspatial.GeoSeries( [ Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), Polygon( ([0, 0], [1, 1], [1, 0], [0, 0]), [([0, 0], [1, 1], [1, 0], [0, 0])], ), MultiPolygon( [ Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), ] ), MultiPolygon( [ Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), Polygon( ([0, 0], [1, 1], [1, 0], [0, 0]), [([0, 0], [1, 1], [1, 0], [0, 0])], ), ] ), ] ) rhs = cuspatial.GeoSeries( [ Point(0.5, 0.25), Point(0.5, 0.25), Point(0.5, 0.25), Point(0.5, 0.25), Point(0.5, 0.25), Point(0.5, 0.25), Point(0.5, 0.25), Point(0.5, 0.25), Point(1.0, 1.0), ] ) gpdlhs = lhs.to_geopandas() gpdrhs = rhs.to_geopandas() expected = gpdlhs.contains(gpdrhs).values got = lhs.contains_properly(rhs).values_host np.testing.assert_array_equal(got, expected) def test_allpairs_with_holes(): lhs = cuspatial.GeoSeries( [ MultiPolygon( [ # Point is in part 0, but not in part 1 Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), Polygon( ([0, 0], [1, 1], [1, 0], [0, 0]), [([0, 0], [1, 1], [1, 0], [0, 0])], ), ] ), MultiPolygon( [ # Point is in part 2 and 3 Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), ] ), Polygon( # Point is not in part 4 because of the hole ([0, 0], [1, 1], [1, 0], [0, 0]), [([0, 0], [1, 1], [1, 0], [0, 0])], ), # Point is in part 5 Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), ] ) rhs = cuspatial.GeoSeries( [ Point(0.5, 0.25), ] ) got = lhs.contains_properly(rhs, allpairs=True).sort_values( "polygon_index" ) assert (got["polygon_index"].values_host == [0, 1, 3]).all() def test_allpairs(): lhs = cuspatial.GeoSeries( [ MultiPolygon( [ Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), Polygon( ([0, 0], [1, 1], [1, 0], [0, 0]), [([0, 0], [1, 1], [0, 1], [0, 0])], ), ] ), MultiPolygon( [ Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), ] ), Polygon( ([0, 0], [1, 1], [1, 0], [0, 0]), [([0, 0], [1, 1], [0, 1], [0, 0])], ), Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), ] ) rhs = cuspatial.GeoSeries( [ Point(0.5, 0.25), ] ) got = lhs.contains_properly(rhs, allpairs=True).sort_values( "polygon_index" ) assert (got["polygon_index"] == cp.arange(4)).all() def test_allpairs_polygon_indices_match_source_index(): lhs = cuspatial.GeoSeries( [ MultiPolygon( [ Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), Polygon( ([0, 0], [1, 1], [1, 0], [0, 0]), [([0, 0], [1, 1], [0, 1], [0, 0])], ), ] ), MultiPolygon( [ Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), ] ), Polygon( ([0, 0], [1, 1], [1, 0], [0, 0]), [([0, 0], [1, 1], [0, 1], [0, 0])], ), Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), ] ) lhs.index = [1, 2, 3, 4] rhs = cuspatial.GeoSeries( [ Point(0.5, 0.25), ] ) got = lhs.contains_properly(rhs, align=False, allpairs=True).sort_values( "polygon_index" ) assert (got["polygon_index"] == cp.arange(1, 5)).all() def test_example_1(): point = cuspatial.GeoSeries( [Point(0.5, 0.5)], ) polygon = cuspatial.GeoSeries( [ Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), ] ) got = polygon.contains_properly(point) assert got.values_host == [False] def test_example_2(): point = cuspatial.GeoSeries( [ Point(0, 0), Point(-1, 0), Point(-2, 0), Point(0, 0), Point(-1, 0), Point(-2, 0), ] ) polygon = cuspatial.GeoSeries( [ Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), Polygon([[-2, -2], [-2, 2], [2, 2], [-2, -2]]), Polygon([[-2, -2], [-2, 2], [2, 2], [-2, -2]]), Polygon([[-2, -2], [-2, 2], [2, 2], [-2, -2]]), ] ) got = polygon.contains_properly(point) assert (got.values_host == [False, False, False, False, True, False]).all()
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/binpreds/test_pip_only_binpreds.py
from shapely.geometry import LineString, Point, Polygon import cuspatial """Overlaps, Within, and Intersects""" def _test(lhs, rhs, predicate): gpdlhs = lhs.to_geopandas() gpdrhs = rhs.to_geopandas() got = getattr(lhs, predicate)(rhs).values_host expected = getattr(gpdlhs, predicate)(gpdrhs).values assert (got == expected).all() def test_polygon_overlaps_point(): lhs = cuspatial.GeoSeries( [Polygon([[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]])] ) rhs = cuspatial.GeoSeries([Point(0.5, 0.5)]) _test(lhs, rhs, "overlaps") def test_max_polygons_overlaps_max_points(polygon_generator, point_generator): lhs = cuspatial.GeoSeries([*polygon_generator(31, 0)]) rhs = cuspatial.GeoSeries([*point_generator(31)]) _test(lhs, rhs, "overlaps") def test_polygon_overlaps_polygon_partially(): lhs = cuspatial.GeoSeries( [Polygon([[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]])] ) rhs = cuspatial.GeoSeries( [Polygon([[0.5, 0.5], [0.5, 1.5], [1.5, 1.5], [1.5, 0.5], [0.5, 0.5]])] ) _test(lhs, rhs, "overlaps") def test_polygon_overlaps_polygon_completely(): lhs = cuspatial.GeoSeries( [Polygon([[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]])] ) rhs = cuspatial.GeoSeries( [ Polygon( [ [0.25, 0.25], [0.25, 0.5], [0.5, 0.5], [0.5, 0.25], [0.25, 0.25], ] ) ] ) _test(lhs, rhs, "overlaps") def test_polygon_overlaps_polygon_no_overlap(): lhs = cuspatial.GeoSeries( [Polygon([[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]])] ) rhs = cuspatial.GeoSeries( [Polygon([[2, 2], [2, 3], [3, 3], [3, 2], [2, 2]])] ) _test(lhs, rhs, "overlaps") def test_max_polygon_overlaps_max_points(polygon_generator, point_generator): lhs = cuspatial.GeoSeries([*polygon_generator(31, 0)]) rhs = cuspatial.GeoSeries([*point_generator(31)]) _test(lhs, rhs, "overlaps") def test_point_intersects_polygon_interior(): lhs = cuspatial.GeoSeries([Point(0.5, 0.5)]) rhs = cuspatial.GeoSeries( [Polygon([[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]])] ) _test(lhs, rhs, "intersects") def test_max_points_intersects_max_polygons_interior( polygon_generator, point_generator ): lhs = cuspatial.GeoSeries([*polygon_generator(31, 0)]) rhs = cuspatial.GeoSeries([*point_generator(31)]) _test(lhs, rhs, "intersects") def test_point_within_polygon(): lhs = cuspatial.GeoSeries([Point(0, 0)]) rhs = cuspatial.GeoSeries([Polygon([[0, 0], [1, 0], [1, 1], [0, 0]])]) _test(lhs, rhs, "within") def test_max_points_within_max_polygons(polygon_generator, point_generator): lhs = cuspatial.GeoSeries([*polygon_generator(31, 0)]) rhs = cuspatial.GeoSeries([*point_generator(31)]) _test(lhs, rhs, "within") def test_linestring_within_polygon(): lhs = cuspatial.GeoSeries([LineString([(0, 0), (1, 1)])]) rhs = cuspatial.GeoSeries([Polygon([[0, 0], [1, 0], [1, 1], [0, 0]])]) _test(lhs, rhs, "within") def test_max_linestring_within_max_polygon( polygon_generator, linestring_generator ): lhs = cuspatial.GeoSeries([*polygon_generator(31, 0)]) rhs = cuspatial.GeoSeries([*linestring_generator(31, 5)]) _test(lhs, rhs, "within") def test_polygon_within_polygon(): lhs = cuspatial.GeoSeries( [Polygon([[0, 0], [-1, 1], [1, 1], [1, -2], [0, 0]])] ) rhs = cuspatial.GeoSeries([Polygon([[-1, -1], [-2, 2], [2, 2], [2, -2]])]) _test(lhs, rhs, "within") def test_max_polygons_within_max_polygons(polygon_generator): lhs = cuspatial.GeoSeries([*polygon_generator(31, 0)]) rhs = cuspatial.GeoSeries([*polygon_generator(31, 1)]) _test(lhs, rhs, "within") def test_polygon_overlaps_linestring(): lhs = cuspatial.GeoSeries( [Polygon([[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]])] ) rhs = cuspatial.GeoSeries([LineString([(0.5, 0.5), (1.5, 1.5)])]) _test(lhs, rhs, "overlaps") def test_max_polygons_overlaps_max_linestrings( polygon_generator, linestring_generator ): lhs = cuspatial.GeoSeries([*polygon_generator(31, 0)]) rhs = cuspatial.GeoSeries([*linestring_generator(31, 5)]) _test(lhs, rhs, "overlaps")
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/binpreds/binpred_test_dispatch.py
# Copyright (c) 2023, NVIDIA CORPORATION. import pytest from shapely.geometry import LineString, Point, Polygon import cuspatial from cuspatial.testing.test_geometries import ( # noqa: F401 features, linestring_linestring_dispatch_list, linestring_polygon_dispatch_list, point_linestring_dispatch_list, point_point_dispatch_list, point_polygon_dispatch_list, polygon_polygon_dispatch_list, ) """Test Dispatch""" """This file is used to generate tests for all possible combinations of geometry types and binary predicates. The tests are generated using the fixtures defined in this file. The fixtures are combined in the test function in `test_binpreds_test_dispatch.py` to make a Tuple: (feature-name, feature-description, feature-lhs, feature-rhs). The feature-name and feature-descriptions are not used in the test but are used for development and debugging. """ @pytest.fixture( params=[ "contains", "geom_equals", "intersects", "covers", "crosses", "disjoint", "overlaps", "touches", "within", ] ) def predicate(request): """The collection of all supported binary predicates""" return request.param def object_dispatch(name_list): """Generate a list of test cases for a given set of test names.""" for name in name_list: yield (name, features[name][0], features[name][1], features[name][2]) type_dispatch = { # A dictionary of test cases for each geometry type combination. # Still needs MultiPoint. (Point, Point): object_dispatch(point_point_dispatch_list), (Point, LineString): object_dispatch(point_linestring_dispatch_list), (Point, Polygon): object_dispatch(point_polygon_dispatch_list), (LineString, LineString): object_dispatch( linestring_linestring_dispatch_list ), (LineString, Polygon): object_dispatch(linestring_polygon_dispatch_list), (Polygon, Polygon): object_dispatch(polygon_polygon_dispatch_list), } def simple_test_dispatch(): """Generates a list of test cases for each geometry type combination. Each dispatched test case is a tuple of the form: (test_name, test_description, lhs, rhs) which is run in `test_binpred_test_dispatch.py`. The test_name is a unique identifier for the test case. The test_description is a string representation of the test case. The lhs and rhs are GeoSeries of the left and right geometries. lhs and rhs are always constructed as a list of 3 geometries since the binpred function is designed to operate primarily on groups of geometries. The first and third feature in the list always match the first geometry specified in `test_description`, and the rhs is always a group of three of the second geometry specified in `test_description`. The second feature in the lhs varies. When the types of the lhs and rhs are equal, the second geometry from `test_description` is substituted for the second geometry in the lhs. This produces a test form of: lhs rhs A B B B A B This decision has two primary benefits: 1. It causes the test to produce varied results (meaning results of the form (True, False, True) or (False, True, False), greatly reducing the likelihood of an "all-False" or "all-True" predicate producing false-positive results. 2. It tests every binary predicate against self, such as A.touches(A) for every predicate and geometry combination. When the types of lhs and rhs are not equal this variation is not performed, since we cannot currently use predicate operations on mixed geometry types. """ for types in type_dispatch: generator = type_dispatch[types] for test_name, test_description, lhs, rhs in generator: yield ( test_name, test_description, cuspatial.GeoSeries( [ lhs, rhs if types[0] == types[1] else lhs, lhs, ] ), cuspatial.GeoSeries( [ rhs, rhs, rhs, ] ), ) @pytest.fixture(params=simple_test_dispatch()) def simple_test(request): """Generates a unique test case for each geometry type combination.""" return request.param
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/binpreds/test_binpred_internals.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION import pandas as pd from shapely.geometry import LineString, MultiPoint, Point, Polygon import cudf import cuspatial from cuspatial.core.binpreds.binpred_dispatch import EQUALS_DISPATCH from cuspatial.utils.binpred_utils import ( _open_polygon_rings, _pli_lines_to_multipoints, _pli_points_to_multipoints, _points_and_lines_to_multipoints, ) def test_internal_reversed_linestrings(): linestring1 = cuspatial.GeoSeries( [ LineString([(0, 0), (1, 1), (1, 0), (0, 0)]), ] ) linestring2 = cuspatial.GeoSeries( [ LineString([(0, 0), (1, 0), (1, 1), (0, 0)]), ] ) predicate = EQUALS_DISPATCH[ (linestring1.column_type, linestring2.column_type) ]() got = predicate._reverse_linestrings( linestring1.lines.xy, linestring1.lines.part_offset ).to_pandas() expected = linestring2.lines.xy.to_pandas() pd.testing.assert_series_equal(got, expected) def test_internal_reversed_linestrings_pair(): linestring1 = cuspatial.GeoSeries( [ LineString([(0, 0), (1, 1), (1, 0), (0, 0)]), LineString([(0, 0), (1, 1), (1, 0)]), ] ) linestring2 = cuspatial.GeoSeries( [ LineString([(0, 0), (1, 0), (1, 1), (0, 0)]), LineString([(1, 0), (1, 1), (0, 0)]), ] ) predicate = EQUALS_DISPATCH[ (linestring1.column_type, linestring2.column_type) ]() got = predicate._reverse_linestrings( linestring1.lines.xy, linestring1.lines.part_offset ).to_pandas() expected = linestring2.lines.xy.to_pandas() pd.testing.assert_series_equal(got, expected) def test_internal_reversed_linestrings_triple(): linestring1 = cuspatial.GeoSeries( [ LineString([(0, 0), (1, 1), (1, 0), (0, 0)]), LineString([(0, 0), (1, 1), (1, 0)]), LineString([(0, 0), (1, 1), (1, 0), (0, 0), (1, 1)]), ] ) linestring2 = cuspatial.GeoSeries( [ LineString([(0, 0), (1, 0), (1, 1), (0, 0)]), LineString([(1, 0), (1, 1), (0, 0)]), LineString([(1, 1), (0, 0), (1, 0), (1, 1), (0, 0)]), ] ) predicate = EQUALS_DISPATCH[ (linestring1.column_type, linestring2.column_type) ]() got = predicate._reverse_linestrings( linestring1.lines.xy, linestring1.lines.part_offset ).to_pandas() expected = linestring2.lines.xy.to_pandas() pd.testing.assert_series_equal(got, expected) def test_open_polygon_rings(): polygon = cuspatial.GeoSeries( [ Polygon([(0, 0), (1, 1), (1, 0), (0, 0)]), ] ) linestring = cuspatial.GeoSeries( [ LineString([(0, 0), (1, 1), (1, 0)]), ] ) got = _open_polygon_rings(polygon) assert (got.lines.xy == linestring.lines.xy).all() def test_open_polygon_rings_two(): polygon = cuspatial.GeoSeries( [ Polygon([(0, 0), (1, 1), (1, 0), (0, 0)]), Polygon([(0, 0), (1, 1), (1, 0), (0, 0)]), ] ) linestring = cuspatial.GeoSeries( [ LineString([(0, 0), (1, 1), (1, 0)]), LineString([(0, 0), (1, 1), (1, 0)]), ] ) got = _open_polygon_rings(polygon) assert (got.lines.xy == linestring.lines.xy).all() def test_open_polygon_rings_three_varying_length(): polygon = cuspatial.GeoSeries( [ Polygon([(0, 0), (1, 1), (0, 1), (0, 0)]), Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]), Polygon([(0, 0), (1, 1), (1, 0), (0, 0)]), ] ) linestring = cuspatial.GeoSeries( [ LineString([(0, 0), (1, 1), (0, 1)]), LineString([(0, 0), (0, 1), (1, 1), (1, 0)]), LineString([(0, 0), (1, 1), (1, 0)]), ] ) got = _open_polygon_rings(polygon) assert (got.lines.xy == linestring.lines.xy).all() def test_points_and_lines_to_multipoints(): mixed = cuspatial.GeoSeries( [ Point(0, 0), LineString([(1, 1), (2, 2)]), ] ) expected = cuspatial.GeoSeries( [ MultiPoint([(0, 0)]), MultiPoint([(1, 1), (2, 2)]), ] ) offsets = [0, 1, 2] got = _points_and_lines_to_multipoints(mixed, offsets) assert (got.multipoints.xy == expected.multipoints.xy).all() def test_points_and_lines_to_multipoints_reverse(): mixed = cuspatial.GeoSeries( [ LineString([(1, 1), (2, 2)]), Point(0, 0), ] ) expected = cuspatial.GeoSeries( [ MultiPoint([(1, 1), (2, 2)]), MultiPoint([(0, 0)]), ] ) offsets = [0, 1, 2] got = _points_and_lines_to_multipoints(mixed, offsets) assert (got.multipoints.xy == expected.multipoints.xy).all() def test_points_and_lines_to_multipoints_two_points_one_linestring(): mixed = cuspatial.GeoSeries( [ Point(0, 0), LineString([(1, 1), (2, 2)]), Point(3, 3), ] ) expected = cuspatial.GeoSeries( [ MultiPoint([(0, 0)]), MultiPoint([(1, 1), (2, 2)]), MultiPoint([(3, 3)]), ] ) offsets = [0, 1, 2, 3] got = _points_and_lines_to_multipoints(mixed, offsets) assert (got.multipoints.xy == expected.multipoints.xy).all() def test_points_and_lines_to_multipoints_two_linestrings_one_point(): mixed = cuspatial.GeoSeries( [ LineString([(0, 0), (1, 1)]), Point(2, 2), LineString([(3, 3), (4, 4)]), ] ) expected = cuspatial.GeoSeries( [ MultiPoint([(0, 0), (1, 1)]), MultiPoint([(2, 2)]), MultiPoint([(3, 3), (4, 4)]), ] ) offsets = [0, 1, 2, 3] got = _points_and_lines_to_multipoints(mixed, offsets) assert (got.multipoints.xy == expected.multipoints.xy).all() def test_points_and_lines_to_multipoints_complex(): mixed = cuspatial.GeoSeries( [ LineString([(0, 0), (1, 1), (2, 2), (3, 3)]), Point(4, 4), LineString([(5, 5), (6, 6)]), Point(7, 7), Point(8, 8), LineString([(9, 9), (10, 10), (11, 11)]), LineString([(12, 12), (13, 13)]), Point(14, 14), ] ) expected = cuspatial.GeoSeries( [ MultiPoint([(0, 0), (1, 1), (2, 2), (3, 3)]), MultiPoint([(4, 4)]), MultiPoint([(5, 5), (6, 6)]), MultiPoint([(7, 7)]), MultiPoint([(8, 8)]), MultiPoint([(9, 9), (10, 10), (11, 11)]), MultiPoint([(12, 12), (13, 13)]), MultiPoint([(14, 14)]), ] ) offsets = [0, 1, 2, 3, 4, 5, 6, 7, 8] got = _points_and_lines_to_multipoints(mixed, offsets) assert (got.multipoints.xy == expected.multipoints.xy).all() def test_points_and_lines_to_multipoints_no_points(): mixed = cuspatial.GeoSeries( [ LineString([(0, 0), (1, 1), (2, 2), (3, 3)]), LineString([(5, 5), (6, 6)]), LineString([(9, 9), (10, 10), (11, 11)]), LineString([(12, 12), (13, 13)]), ] ) expected = cuspatial.GeoSeries( [ MultiPoint([(0, 0), (1, 1), (2, 2), (3, 3)]), MultiPoint([(5, 5), (6, 6)]), MultiPoint([(9, 9), (10, 10), (11, 11)]), MultiPoint([(12, 12), (13, 13)]), ] ) offsets = [0, 1, 2, 3, 4] got = _points_and_lines_to_multipoints(mixed, offsets) assert (got.multipoints.xy == expected.multipoints.xy).all() def test_points_and_lines_to_multipoints_no_linestrings(): mixed = cuspatial.GeoSeries( [ Point(0, 0), Point(4, 4), Point(7, 7), Point(8, 8), Point(14, 14), ] ) expected = cuspatial.GeoSeries( [ MultiPoint([(0, 0)]), MultiPoint([(4, 4)]), MultiPoint([(7, 7)]), MultiPoint([(8, 8)]), MultiPoint([(14, 14)]), ] ) offsets = [0, 1, 2, 3, 4, 5] got = _points_and_lines_to_multipoints(mixed, offsets) assert (got.multipoints.xy == expected.multipoints.xy).all() def test_points_and_lines_to_multipoints_real_example(): mixed = cuspatial.GeoSeries( [ Point(7, 7), Point(4, 4), LineString([(5, 5), (6, 6)]), LineString([(9, 9), (10, 10), (11, 11)]), LineString([(12, 12), (13, 13)]), Point(8, 8), Point(14, 14), ] ) expected = cuspatial.GeoSeries( [ MultiPoint([(7, 7), (4, 4)]), MultiPoint( [ (5, 5), (6, 6), (9, 9), (10, 10), (11, 11), (12, 12), (13, 13), ] ), MultiPoint([(8, 8), (14, 14)]), ] ) offsets = [0, 2, 5, 7] got = _points_and_lines_to_multipoints(mixed, offsets) assert (got.multipoints.xy == expected.multipoints.xy).all() def test_pli_points_to_multipoints_no_points(): points = cuspatial.GeoSeries([]) offsets = cudf.Series([0, 1, 2, 3]) mpoints = _pli_points_to_multipoints((offsets, points)) assert len(mpoints) == 3 def test_pli_points_to_multipoints_first(): points = cuspatial.GeoSeries([Point(1, 2)]) offsets = cudf.Series([0, 1, 1, 1]) mpoints = _pli_points_to_multipoints((offsets, points)) assert (mpoints.sizes.values_host == [1, 0, 0]).all() assert (mpoints.multipoints.xy.values_host == [1, 2]).all() def test_pli_points_to_multipoints_two(): points = cuspatial.GeoSeries( [ Point(1, 2), Point(3, 4), ] ) offsets = cudf.Series([0, 2, 2, 2]) mpoints = _pli_points_to_multipoints((offsets, points)) assert (mpoints.sizes.values_host == [2, 0, 0]).all() assert (mpoints.multipoints.xy.values_host == [1, 2, 3, 4]).all() def test_pli_points_to_multipoints_split(): points = cuspatial.GeoSeries( [ Point(1, 2), Point(3, 4), Point(5, 6), Point(7, 8), ] ) offsets = cudf.Series([0, 2, 2, 4]) mpoints = _pli_points_to_multipoints((offsets, points)) assert (mpoints.sizes.values_host == [2, 0, 2]).all() assert ( mpoints.multipoints.xy.values_host == [1, 2, 3, 4, 5, 6, 7, 8] ).all() def test_pli_points_to_multipoints_drop_linestring(): mixed = cuspatial.GeoSeries( [ Point(1, 2), LineString([(3, 4), (5, 6)]), Point(7, 8), ] ) offsets = cudf.Series([0, 1, 2, 3]) mpoints = _pli_points_to_multipoints((offsets, mixed)) assert (mpoints.sizes.values_host == [1, 0, 1]).all() assert (mpoints.multipoints.xy.values_host == [1, 2, 7, 8]).all() def test_pli_lines_to_multipoints_drop_point(): mixed = cuspatial.GeoSeries( [ Point(1, 2), LineString([(3, 4), (5, 6)]), Point(7, 8), ] ) offsets = cudf.Series([0, 1, 2, 3]) mpoints = _pli_lines_to_multipoints((offsets, mixed)) assert (mpoints.sizes.values_host == [0, 2, 0]).all() assert (mpoints[1:2].multipoints.xy.values_host == [3, 4, 5, 6]).all()
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/binpreds/test_binpred_cartesian_dispatch_list.py
# Copyright (c) 2023, NVIDIA CORPORATION. import geopandas import numpy as np from binpred_test_dispatch import predicate # noqa: F401 import cuspatial from cuspatial.testing.test_geometries import ( features, linestring_linestring_dispatch_list, linestring_polygon_dispatch_list, point_linestring_dispatch_list, point_point_dispatch_list, point_polygon_dispatch_list, polygon_polygon_dispatch_list, ) def sample_test_data(features, dispatch_list, size, lib=cuspatial): """Creates either a cuspatial or geopandas GeoSeries object using the Feature objects in `features`, the list of features to sample from in `dispatch_list`, and the size of the resultant GeoSeries. """ geometry_tuples = [features[key][1:3] for key in dispatch_list] geometries = [ [lhs_geo for lhs_geo, _ in geometry_tuples], [rhs_geo for _, rhs_geo in geometry_tuples], ] lhs = lib.GeoSeries(list(geometries[0])) rhs = lib.GeoSeries(list(geometries[1])) lhs_picks = np.repeat(np.arange(len(lhs)), len(lhs)) rhs_picks = np.tile(np.arange(len(rhs)), len(rhs)) return ( lhs[lhs_picks].reset_index(drop=True), rhs[rhs_picks].reset_index(drop=True), ) def run_test(pred, dispatch_list): size = 10000 lhs, rhs = sample_test_data(features, dispatch_list, size, cuspatial) gpdlhs, gpdrhs = sample_test_data(features, dispatch_list, size, geopandas) # Reverse pred_fn = getattr(rhs, pred) got = pred_fn(lhs) gpd_pred_fn = getattr(gpdrhs, pred) expected = gpd_pred_fn(gpdlhs) assert (got.values_host == expected.values).all() # Forward pred_fn = getattr(lhs, pred) got = pred_fn(rhs) gpd_pred_fn = getattr(gpdlhs, pred) expected = gpd_pred_fn(gpdrhs) assert (got.values_host == expected.values).all() def test_point_point_large_examples(predicate): # noqa: F811 run_test(predicate, point_point_dispatch_list) def test_point_linestring_large_examples(predicate): # noqa: F811 run_test(predicate, point_linestring_dispatch_list) def test_point_polygon_large_examples(predicate): # noqa: F811 run_test(predicate, point_polygon_dispatch_list) def test_linestring_linestring_large_examples(predicate): # noqa: F811 run_test(predicate, linestring_linestring_dispatch_list) def test_linestring_polygon_large_examples(predicate): # noqa: F811 run_test(predicate, linestring_polygon_dispatch_list) def test_polygon_polygon_large_examples(predicate): # noqa: F811 run_test(predicate, polygon_polygon_dispatch_list)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/binpreds/summarize_binpred_test_dispatch_results.py
# Copyright (c) 2023, NVIDIA CORPORATION. """Prints a summary of the results of the binary predicate test dispatch. """ import pandas as pd pp = pd.read_csv("predicate_passes.csv") pf = pd.read_csv("predicate_fails.csv") fp = pd.read_csv("feature_passes.csv") ff = pd.read_csv("feature_fails.csv") print(pp) print(pf) print(fp) print(ff)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/binpreds/test_contains.py
# Copyright (c) 2023, NVIDIA CORPORATION import geopandas as gpd import pandas as pd import pytest from shapely.geometry import MultiPolygon, Polygon import cuspatial def test_manual_polygons(): gpdlhs = gpd.GeoSeries([Polygon(((-8, -8), (-8, 8), (8, 8), (8, -8)))] * 6) gpdrhs = gpd.GeoSeries( [ Polygon(((-8, -8), (-8, 8), (8, 8), (8, -8))), Polygon(((-2, -2), (-2, 2), (2, 2), (2, -2))), Polygon(((-10, -2), (-10, 2), (-6, 2), (-6, -2))), Polygon(((-2, 8), (-2, 12), (2, 12), (2, 8))), Polygon(((6, 0), (8, 2), (10, 0), (8, -2))), Polygon(((-2, -8), (-2, -4), (2, -4), (2, -8))), ] ) rhs = cuspatial.from_geopandas(gpdrhs) lhs = cuspatial.from_geopandas(gpdlhs) got = lhs.contains(rhs).values_host expected = gpdlhs.contains(gpdrhs).values assert (got == expected).all() got = rhs.contains(lhs).values_host expected = gpdrhs.contains(gpdlhs).values assert (got == expected).all() def test_same(): lhs = cuspatial.GeoSeries([Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])]) rhs = cuspatial.GeoSeries([Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])]) gpdlhs = lhs.to_geopandas() gpdrhs = rhs.to_geopandas() got = lhs.contains(rhs) expected = gpdlhs.contains(gpdrhs) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_adjacent(): lhs = cuspatial.GeoSeries([Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])]) rhs = cuspatial.GeoSeries([Polygon([(1, 0), (1, 1), (2, 1), (2, 0)])]) gpdlhs = lhs.to_geopandas() gpdrhs = rhs.to_geopandas() got = lhs.contains(rhs) expected = gpdlhs.contains(gpdrhs) pd.testing.assert_series_equal(expected, got.to_pandas()) def test_interior(): lhs = cuspatial.GeoSeries( [Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)])] ) rhs = cuspatial.GeoSeries( [Polygon([(0, 0), (0, 0.5), (0.5, 0.5), (0.5, 0)])] ) gpdlhs = lhs.to_geopandas() gpdrhs = rhs.to_geopandas() got = lhs.contains(rhs) expected = gpdlhs.contains(gpdrhs) pd.testing.assert_series_equal(expected, got.to_pandas()) @pytest.mark.parametrize( "object", [ Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), MultiPolygon( [ Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), ] ), ], ) def test_self_contains(object): gpdobject = gpd.GeoSeries(object) object = cuspatial.from_geopandas(gpdobject) got = object.contains(object).values_host expected = gpdobject.contains(gpdobject).values assert (got == expected).all() def test_complex_input(): gpdobject = gpd.GeoSeries( [ Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), Polygon( ([0, 0], [1, 1], [1, 0], [0, 0]), [([0, 0], [1, 1], [1, 0], [0, 0])], ), MultiPolygon( [ Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), ] ), MultiPolygon( [ Polygon([[0, 0], [1, 1], [1, 0], [0, 0]]), Polygon( ([0, 0], [1, 1], [1, 0], [0, 0]), [([0, 0], [1, 1], [1, 0], [0, 0])], ), ] ), ] ) object = cuspatial.from_geopandas(gpdobject) got = object.contains(object).values_host expected = gpdobject.contains(gpdobject).values assert (got == expected).all()
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/tests/binpreds/test_binpred_each_dispatch_list.py
# Copyright (c) 2023, NVIDIA CORPORATION. import geopandas from binpred_test_dispatch import predicate # noqa: F401 import cuspatial from cuspatial.testing.test_geometries import ( features, linestring_linestring_dispatch_list, linestring_polygon_dispatch_list, point_linestring_dispatch_list, point_point_dispatch_list, point_polygon_dispatch_list, polygon_polygon_dispatch_list, ) def sample_test_data(features, dispatch_list, lib=cuspatial): """Creates either a cuSpatial or geopandas GeoSeries object using the features in `features` and the list of features to sample from `dispatch_list`. """ geometry_tuples = [features[key][1:3] for key in dispatch_list] geometries = [ [lhs_geo for lhs_geo, _ in geometry_tuples], [rhs_geo for _, rhs_geo in geometry_tuples], ] lhs = lib.GeoSeries(list(geometries[0])) rhs = lib.GeoSeries(list(geometries[1])) return (lhs, rhs) def run_test(pred, dispatch_list): lhs, rhs = sample_test_data(features, dispatch_list, cuspatial) gpdlhs, gpdrhs = sample_test_data(features, dispatch_list, geopandas) # Reverse pred_fn = getattr(rhs, pred) got = pred_fn(lhs) gpd_pred_fn = getattr(gpdrhs, pred) expected = gpd_pred_fn(gpdlhs) assert (got.values_host == expected.values).all() # Forward pred_fn = getattr(lhs, pred) got = pred_fn(rhs) gpd_pred_fn = getattr(gpdlhs, pred) expected = gpd_pred_fn(gpdrhs) assert (got.values_host == expected.values).all() def test_point_point_all_examples(predicate): # noqa: F811 run_test(predicate, point_point_dispatch_list) def test_point_linestring_all_examples(predicate): # noqa: F811 run_test(predicate, point_linestring_dispatch_list) def test_point_polygon_all_examples(predicate): # noqa: F811 run_test(predicate, point_polygon_dispatch_list) def test_linestring_linestring_all_examples(predicate): # noqa: F811 run_test(predicate, linestring_linestring_dispatch_list) def test_linestring_polygon_all_examples(predicate): # noqa: F811 run_test(predicate, linestring_polygon_dispatch_list) def test_polygon_polygon_all_examples(predicate): # noqa: F811 run_test(predicate, polygon_polygon_dispatch_list)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/testing/test_geometries.py
# Copyright (c) 2023, NVIDIA CORPORATION. from shapely.geometry import LineString, Point, Polygon """The fundamental set of tests. This section is dispatched based on the feature type. Each feature pairing has a specific set of comparisons that need to be performed to cover the entire test space. This section contains specific feature representations that cover all possible geometric combinations.""" point_polygon = Polygon([(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)]) features = { "point-point-disjoint": ( """Two points apart.""", Point(0.0, 0.0), Point(1.0, 0.0), ), "point-point-equal": ( """Two points together.""", Point(0.0, 0.0), Point(0.0, 0.0), ), "point-linestring-disjoint": ( """Point and linestring are disjoint.""", Point(0.0, 0.0), LineString([(1.0, 0.0), (2.0, 0.0)]), ), "point-linestring-point": ( """Point and linestring share a point.""", Point(0.0, 0.0), LineString([(0.0, 0.0), (2.0, 0.0)]), ), "point-linestring-edge": ( """Point and linestring intersect.""", Point(0.5, 0.0), LineString([(0.0, 0.0), (1.0, 0.0)]), ), "point-polygon-disjoint": ( """Point and polygon are disjoint.""", Point(-0.5, 0.5), point_polygon, ), "point-polygon-point": ( """Point and polygon share a point.""", Point(0.0, 0.0), point_polygon, ), "point-polygon-edge": ( """Point and polygon intersect.""", Point(0.5, 0.0), point_polygon, ), "point-polygon-in": ( """Point is in polygon interior.""", Point(0.5, 0.5), point_polygon, ), "linestring-linestring-disjoint": ( """ x---x x---x """, LineString([(0.0, 0.0), (1.0, 0.0)]), LineString([(0.0, 1.0), (1.0, 1.0)]), ), "linestring-linestring-same": ( """ x---x """, LineString([(0.0, 0.0), (1.0, 0.0)]), LineString([(0.0, 0.0), (1.0, 0.0)]), ), "linestring-linestring-covers": ( """ x x / x x """, LineString([(0.0, 0.0), (1.0, 1.0)]), LineString([(0.25, 0.25), (0.5, 0.5)]), ), "linestring-linestring-touches": ( """ x | | | x---x """, LineString([(0.0, 0.0), (0.0, 1.0)]), LineString([(0.0, 0.0), (1.0, 0.0)]), ), "linestring-linestring-touch-interior": ( """ x x | / | / |/ x---x """, LineString([(0.0, 1.0), (0.0, 0.0), (1.0, 0.0)]), LineString([(0.0, 0.0), (1.0, 1.0)]), ), "linestring-linestring-touch-edge": ( """ x | | | x-x-x """, LineString([(0.0, 0.0), (1.0, 0.0)]), LineString([(0.5, 0.0), (0.5, 1.0)]), ), "linestring-linestring-touch-edge-twice": ( """ x x / \\ x---x x """, LineString([(0.0, 0.0), (1.0, 1.0), (2.0, 2.0)]), LineString([(0.25, 0.25), (1.0, 0.0), (0.5, 0.5)]), ), "linestring-linestring-crosses": ( """ x | x-|-x | x """, LineString([(0.5, 0.0), (0.5, 1.0)]), LineString([(0.0, 0.5), (1.0, 0.5)]), ), "linestring-linestring-touch-and-cross": ( """ x | x |\\ x---x x """, LineString([(0.0, 0.0), (1.0, 1.0)]), LineString([(0.5, 0.5), (1.0, 0.1), (-1.0, 0.1)]), ), "linestring-polygon-disjoint": ( """ point_polygon above is drawn as ----- | | | | | | ----- and the corresponding linestring is drawn as x---x or x | | | x """ """ x ----- | | | | | | | | | x ----- """, LineString([(-0.5, 0.0), (-0.5, 1.0)]), point_polygon, ), "linestring-polygon-touch-point": ( """ x---x---- | | | | | | ----- """, LineString([(-1.0, 0.0), (0.0, 0.0)]), point_polygon, ), "linestring-polygon-touch-edge": ( """ ----- | | x---x | | | ----- """, LineString([(-1.0, 0.5), (0.0, 0.5)]), point_polygon, ), "linestring-polygon-overlap-edge": ( """ x---- | | | | | | x---- """, LineString([(0.0, 0.0), (0.0, 1.0)]), point_polygon, ), "linestring-polygon-intersect-edge": ( """ ----- | | | | | | x---x-- """, LineString([(-0.5, 0.0), (0.5, 0.0)]), point_polygon, ), "linestring-polygon-intersect-inner-edge": ( """ ----- x | | | x | ----- The linestring in this case is shorter than the corners of the polygon. """, LineString([(0.25, 0.0), (0.75, 0.0)]), point_polygon, ), "linestring-polygon-point-interior": ( """ ----x | /| | / | |/ | x---- """, LineString([(0.0, 0.0), (1.0, 1.0)]), point_polygon, ), "linestring-polygon-edge-interior": ( """ --x-- | | | | | | | | | --x-- """, LineString([(0.5, 0.0), (0.5, 1.0)]), point_polygon, ), "linestring-polygon-in": ( """ ----- | x | | | | | x | ----- """, LineString([(0.5, 0.25), (0.5, 0.75)]), point_polygon, ), "linestring-polygon-in-out": ( """ ----- | | | x | | | | --|-- | x """, LineString([(0.5, 0.5), (0.5, -0.5)]), point_polygon, ), "linestring-polygon-crosses": ( """ x --|-- | | | | | | | | | --|-- x """, LineString([(0.5, 1.25), (0.5, -0.25)]), point_polygon, ), "linestring-polygon-cross-concave-edge": ( """ x x x |\\ | /| | xx- | | | | ---x--- """, LineString([(0.5, 0.0), (0.5, 1.0)]), Polygon([(0, 0), (0, 1), (0.3, 0.4), (1, 1), (1, 0)]), ), "linestring-polygon-half-in": ( """ ----- | | | x | |/ \\| xx-xx """, LineString( [(0.0, 0.0), (0.25, 0.0), (0.5, 0.5), (0.75, 0.0), (1.0, 0.0)] ), point_polygon, ), "linestring-polygon-half-out": ( """ ----- | | | | | | xx-xx \\/ x """, LineString( [(0.0, 0.0), (0.25, 0.0), (0.5, -0.5), (0.75, 0.0), (1.0, 0.0)] ), point_polygon, ), "linestring-polygon-two-edges": ( """ x---- | | | | | | x---x """, LineString([(0.0, 1.0), (0.0, 0.0), (1.0, 0.0)]), point_polygon, ), "linestring-polygon-edge-to-interior": ( """ x---- | | | -x |-/ | x---- """, LineString([(0.0, 1.0), (0.0, 0.0), (1.0, 0.5)]), point_polygon, ), "linestring-polygon-edge-cross-to-exterior": ( """ x------ | | | ---x | --- | x------ """, LineString([(0.0, 1.0), (0.0, 0.0), (1.5, 0.5)]), point_polygon, ), "polygon-polygon-disjoint": ( """ Polygon polygon tests use a triangle for the lhs and a square for the rhs. The triangle is drawn as x---x | / | / |/ x The square is drawn as ----- | | | | | | ----- """, Polygon([(0.0, 2.0), (0.0, 3.0), (1.0, 3.0)]), point_polygon, ), "polygon-polygon-touch-point": ( """ x---x | / | / |/ x---- | | | | | | ----- """, Polygon([(0.0, 1.0), (0.0, 2.0), (1.0, 2.0)]), point_polygon, ), "polygon-polygon-touch-edge": ( """ x---x | / | / |/ -x--x | | | | | | ----- """, Polygon([(0.25, 1.0), (0.25, 2.0), (1.25, 2.0)]), point_polygon, ), "polygon-polygon-overlap-edge": ( """ x |\\ | \\ | \\ x---x | | | | | | ----- """, Polygon([(0.0, 1.0), (0.0, 2.0), (1.0, 2.0)]), point_polygon, ), "polygon-polygon-overlap-inside-edge": ( """ x /| x---x | \\ / | x | / | x-----x """, Polygon([(0, 0), (1, 0), (1, 1), (0, 0)]), Polygon([(0.25, 0.25), (0.5, 0.5), (0, 0.5), (0.25, 0.25)]), ), "polygon-polygon-point-inside": ( """ x---x | / --|-/ | |/| | x | | | ----- """, Polygon([(0.5, 0.5), (0.5, 1.5), (1.5, 1.5)]), point_polygon, ), "polygon-polygon-point-outside": ( """ x -|\\-- |x-x| | | | | ----- """, Polygon([(0.25, 0.75), (0.25, 1.25), (0.75, 0.75)]), point_polygon, ), "polygon-polygon-in-out-point": ( """ x |\\ --|-x | |/| | x | | | x---- """, Polygon([(0.5, 0.5), (0.5, 1.5), (1.0, 1.0)]), point_polygon, ), "polygon-polygon-in-point-point": ( """ x---- |\\ | | x | |/ | x---- """, Polygon([(0.0, 0.0), (0.0, 1.0), (0.5, 0.5)]), point_polygon, ), "polygon-polygon-contained": ( """ ----- | x| | /|| |x-x| ----- """, Polygon([(0.25, 0.25), (0.75, 0.75), (0.75, 0.25)]), point_polygon, ), "polygon-polygon-same": ( """ x---x | | | | | | x---x """, point_polygon, point_polygon, ), } point_point_dispatch_list = [ "point-point-disjoint", "point-point-equal", ] point_linestring_dispatch_list = [ "point-linestring-disjoint", "point-linestring-point", "point-linestring-edge", ] point_polygon_dispatch_list = [ "point-polygon-disjoint", "point-polygon-point", "point-polygon-edge", "point-polygon-in", ] linestring_linestring_dispatch_list = [ "linestring-linestring-disjoint", "linestring-linestring-same", "linestring-linestring-covers", "linestring-linestring-touches", "linestring-linestring-touch-interior", "linestring-linestring-touch-edge", "linestring-linestring-touch-edge-twice", "linestring-linestring-crosses", "linestring-linestring-touch-and-cross", ] linestring_polygon_dispatch_list = [ "linestring-polygon-disjoint", "linestring-polygon-touch-point", "linestring-polygon-touch-edge", "linestring-polygon-overlap-edge", "linestring-polygon-intersect-edge", "linestring-polygon-intersect-inner-edge", "linestring-polygon-point-interior", "linestring-polygon-edge-interior", "linestring-polygon-in", "linestring-polygon-crosses", "linestring-polygon-cross-concave-edge", "linestring-polygon-half-in", "linestring-polygon-half-out", "linestring-polygon-two-edges", "linestring-polygon-edge-to-interior", "linestring-polygon-edge-cross-to-exterior", ] polygon_polygon_dispatch_list = [ "polygon-polygon-disjoint", "polygon-polygon-touch-point", "polygon-polygon-touch-edge", "polygon-polygon-overlap-edge", "polygon-polygon-overlap-inside-edge", "polygon-polygon-point-inside", "polygon-polygon-point-outside", "polygon-polygon-in-out-point", "polygon-polygon-in-point-point", "polygon-polygon-contained", "polygon-polygon-same", ]
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/trajectory.py
# Copyright (c) 2019-2022, NVIDIA CORPORATION. import numpy as np from cudf import DataFrame, Series from cudf.core.column import as_column from cuspatial import GeoSeries from cuspatial._lib.trajectory import ( derive_trajectories as cpp_derive_trajectories, trajectory_bounding_boxes as cpp_trajectory_bounding_boxes, trajectory_distances_and_speeds as cpp_trajectory_distances_and_speeds, ) from cuspatial.utils.column_utils import ( contains_only_points, normalize_timestamp_column, ) def derive_trajectories(object_ids, points: GeoSeries, timestamps): """ Derive trajectories from object ids, points, and timestamps. Parameters ---------- object_ids column of object (e.g., vehicle) ids points : GeoSeries The points of the trajectories timestamps column of timestamps in any resolution Returns ------- result : tuple (objects, traj_offsets) objects : cudf.DataFrame object_ids, xs, ys, and timestamps sorted by ``(object_id, timestamp)``, used by ``trajectory_bounding_boxes`` and ``trajectory_distances_and_speeds`` traj_offsets : cudf.Series offsets of discovered trajectories Examples -------- Compute sorted objects and discovered trajectories >>> objects, traj_offsets = cuspatial.derive_trajectories( [0, 1, 0, 1], # object_id [0, 0, 1, 1], # x [0, 0, 1, 1], # y [0, 10000, 0, 10000] # timestamp ) >>> print(traj_offsets) 0 0 1 2 >>> print(objects) object_id x y timestamp 0 0 0.0 0.0 1970-01-01 00:00:00 1 0 1.0 1.0 1970-01-01 00:00:10 2 1 0.0 0.0 1970-01-01 00:00:00 3 1 1.0 1.0 1970-01-01 00:00:10 """ if len(points) > 0 and not contains_only_points(points): raise ValueError("`points` must only contain point geometries.") object_ids = as_column(object_ids, dtype=np.int32) xs = as_column(points.points.x) ys = as_column(points.points.y) timestamps = normalize_timestamp_column(as_column(timestamps)) objects, traj_offsets = cpp_derive_trajectories( object_ids, xs, ys, timestamps ) return DataFrame._from_data(*objects), Series(data=traj_offsets) def trajectory_bounding_boxes(num_trajectories, object_ids, points: GeoSeries): """Compute the bounding boxes of sets of trajectories. Parameters ---------- num_trajectories number of trajectories (unique object ids) object_ids column of object (e.g., vehicle) ids points: GeoSeries Series of trajectory points Returns ------- result : cudf.DataFrame minimum bounding boxes (in kilometers) for each trajectory x_min : cudf.Series the minimum x-coordinate of each bounding box y_min : cudf.Series the minimum y-coordinate of each bounding box x_max : cudf.Series the maximum x-coordinate of each bounding box y_max : cudf.Series the maximum y-coordinate of each bounding box Examples -------- Compute the minimum bounding boxes of derived trajectories >>> objects, traj_offsets = cuspatial.derive_trajectories( [0, 0, 1, 1], # object_id [0, 1, 2, 3], # x [0, 0, 1, 1], # y [0, 10, 0, 10] # timestamp ) >>> traj_bounding_boxes = cuspatial.trajectory_bounding_boxes( len(traj_offsets), objects['object_id'], objects['x'], objects['y'] ) >>> print(traj_bounding_boxes) x_min y_min x_max y_max 0 0.0 0.0 2.0 2.0 1 1.0 1.0 3.0 3.0 """ if len(points) > 0 and not contains_only_points(points): raise ValueError("`points` must only contain point geometries.") object_ids = as_column(object_ids, dtype=np.int32) xs = as_column(points.points.x) ys = as_column(points.points.y) return DataFrame._from_data( *cpp_trajectory_bounding_boxes(num_trajectories, object_ids, xs, ys) ) def trajectory_distances_and_speeds( num_trajectories, object_ids, points: GeoSeries, timestamps ): """ Compute the distance traveled and speed of sets of trajectories Parameters ---------- num_trajectories number of trajectories (unique object ids) object_ids column of object (e.g., vehicle) ids points: GeoSeries A series of points timestamps column of timestamps in any resolution Returns ------- result : cudf.DataFrame meters : cudf.Series trajectory distance (in kilometers) speed : cudf.Series trajectory speed (in meters/second) Examples -------- Compute the distances and speeds of derived trajectories >>> objects, traj_offsets = cuspatial.derive_trajectories(...) >>> dists_and_speeds = cuspatial.trajectory_distances_and_speeds( len(traj_offsets) objects['object_id'], objects['x'], objects['y'], objects['timestamp'] ) >>> print(dists_and_speeds) distance speed trajectory_id 0 1414.213562 141.421356 1 1414.213562 141.421356 """ if len(points) > 0 and not contains_only_points(points): raise ValueError("`points` must only contain point geometries.") object_ids = as_column(object_ids, dtype=np.int32) xs = as_column(points.points.x) ys = as_column(points.points.y) timestamps = normalize_timestamp_column(as_column(timestamps)) df = DataFrame._from_data( *cpp_trajectory_distances_and_speeds( num_trajectories, object_ids, xs, ys, timestamps ) ) df.index.name = "trajectory_id" return df
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/geoseries.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION from functools import cached_property from numbers import Integral from typing import Optional, Tuple, TypeVar, Union import cupy as cp import geopandas as gpd import numpy as np import pandas as pd import pyarrow as pa from geopandas.geoseries import GeoSeries as gpGeoSeries from shapely.geometry import ( LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, ) from shapely.geometry.base import BaseGeometry, BaseMultipartGeometry import cudf from cudf._typing import ColumnLike from cudf.core.column.column import as_column from cudf.core.copy_types import GatherMap import cuspatial.io.pygeoarrow as pygeoarrow from cuspatial.core._column.geocolumn import ColumnType, GeoColumn from cuspatial.core._column.geometa import Feature_Enum, GeoMeta from cuspatial.core.binops.distance_dispatch import DistanceDispatch from cuspatial.core.binpreds.binpred_dispatch import ( CONTAINS_DISPATCH, CONTAINS_PROPERLY_DISPATCH, COVERS_DISPATCH, CROSSES_DISPATCH, DISJOINT_DISPATCH, EQUALS_DISPATCH, INTERSECTS_DISPATCH, OVERLAPS_DISPATCH, TOUCHES_DISPATCH, WITHIN_DISPATCH, ) from cuspatial.utils.column_utils import ( contains_only_linestrings, contains_only_multipoints, contains_only_points, contains_only_polygons, ) T = TypeVar("T", bound="GeoSeries") class GeoSeries(cudf.Series): """cuspatial.GeoSeries enables GPU-backed storage and computation of shapely-like objects. Our goal is to give feature parity with GeoPandas. At this time, only from_geopandas and to_geopandas are directly supported. cuspatial GIS, indexing, and trajectory functions depend on the arrays stored in the `GeoArrowBuffers` object, accessible with the `points`, `multipoints`, `lines`, and `polygons` accessors. Examples -------- >>> from shapely.geometry import Point import geopandas import cuspatial cuseries = cuspatial.GeoSeries(geopandas.GeoSeries(Point(-1, 0))) cuseries.points.xy 0 -1.0 1 0.0 dtype: float64 """ def __init__( self, data: Optional[ Union[gpd.GeoSeries, Tuple, T, pd.Series, GeoColumn, list] ], index: Union[cudf.Index, pd.Index] = None, dtype=None, name=None, nan_as_null=True, ): # Condition data if data is None or isinstance(data, (pd.Series, list)): data = gpGeoSeries(data) # Create column if isinstance(data, GeoColumn): column = data elif isinstance(data, GeoSeries): column = data._column elif isinstance(data, gpGeoSeries): from cuspatial.io.geopandas_reader import GeoPandasReader adapter = GeoPandasReader(data) pandas_meta = GeoMeta(adapter.get_geopandas_meta()) column = GeoColumn(adapter._get_geotuple(), pandas_meta) else: raise TypeError( f"Incompatible object passed to GeoSeries ctor {type(data)}" ) # Condition index if isinstance(data, (gpGeoSeries, GeoSeries)): if index is None: index = data.index if index is None: index = cudf.RangeIndex(0, len(column)) super().__init__( column, index, dtype=dtype, name=name, nan_as_null=nan_as_null ) @property def feature_types(self): return self._column._meta.input_types.reset_index(drop=True) @property def type(self): gpu_types = cudf.Series(self._column._meta.input_types).astype("str") result = gpu_types.replace( { "0": "Point", "1": "MultiPoint", "2": "Linestring", "3": "Polygon", } ) return result @property def column_type(self): """This is used to determine the type of the GeoColumn. It is a value returning method that produces the same result as the various `contains_only_*` methods, except as an Enum instead of many booleans.""" if contains_only_polygons(self): return ColumnType.POLYGON elif contains_only_linestrings(self): return ColumnType.LINESTRING elif contains_only_multipoints(self): return ColumnType.MULTIPOINT elif contains_only_points(self): return ColumnType.POINT else: return ColumnType.MIXED @property def point_indices(self): if contains_only_polygons(self): return self.polygons.point_indices() elif contains_only_linestrings(self): return self.lines.point_indices() elif contains_only_multipoints(self): return self.multipoints.point_indices() elif contains_only_points(self): return self.points.point_indices() else: if len(self) == 0: return cudf.Series([0], dtype="int32") raise TypeError( "GeoSeries must contain only Points, MultiPoints, Lines, or " "Polygons to return point indices." ) @property def sizes(self): """Returns the number of points of each geometry in the GeoSeries." Returns ------- sizes : cudf.Series The size of each geometry in the GeoSeries. Notes ----- The size of a geometry is the number of points it contains. The size of a polygon is the total number of points in all of its rings. The size of a multipolygon is the sum of the sizes of all of its polygons. The size of a linestring is the number of points in its single line. The size of a multilinestring is the sum of the sizes of all of its linestrings. The size of a multipoint is the number of points in its single point. The size of a point is 1. """ if contains_only_polygons(self): # The size of a polygon is the length of its exterior ring # plus the lengths of its interior rings. # The size of a multipolygon is the sum of all its polygons. full_sizes = self.polygons.ring_offset.take( self.polygons.part_offset.take(self.polygons.geometry_offset) ) return cudf.Series( full_sizes[1:] - full_sizes[:-1], index=self.index ) elif contains_only_linestrings(self): # Not supporting multilinestring yet full_sizes = self.lines.part_offset.take( self.lines.geometry_offset ) return cudf.Series( full_sizes[1:] - full_sizes[:-1], index=self.index ) elif contains_only_multipoints(self): return cudf.Series( self.multipoints.geometry_offset[1:] - self.multipoints.geometry_offset[:-1], index=self.index, ) elif contains_only_points(self): return cudf.Series( cp.repeat(cp.array(1), len(self)), index=self.index ) else: if len(self) == 0: return cudf.Series([0], dtype="int32", index=self.index) raise NotImplementedError( "GeoSeries must contain only Points, MultiPoints, Lines, or " "Polygons to return sizes." ) class GeoColumnAccessor: def __init__(self, list_series, meta): self._series = list_series self._col = self._series._column self._meta = meta self._type = Feature_Enum.POINT @property def x(self): return self.xy[::2].reset_index(drop=True) @property def y(self): return self.xy[1::2].reset_index(drop=True) @property def xy(self): features = self._get_current_features(self._type) if hasattr(features, "leaves"): return cudf.Series(features.leaves().values) else: return cudf.Series() def _get_current_features(self, type): # Resample the existing features so that the offsets returned # by `_offset` methods reflect previous slicing, and match # the values returned by .xy. existing_indices = self._meta.union_offsets[ self._meta.input_types == type.value ] existing_features = self._col.take(existing_indices._column) return existing_features def point_indices(self): # Return a cupy.ndarray containing the index values that each # point belongs to. """ offsets = cp.arange(0, len(self.xy) + 1, 2) sizes = offsets[1:] - offsets[:-1] return cp.repeat(self._series.index, sizes) """ return self._meta.input_types.reset_index(drop=True).index[ self._meta.input_types != -1 ] def column(self): """Return the ListColumn reordered by union offset.""" return self._get_current_features(self._type) class MultiPointGeoColumnAccessor(GeoColumnAccessor): def __init__(self, list_series, meta): super().__init__(list_series, meta) self._type = Feature_Enum.MULTIPOINT @property def geometry_offset(self): return self._get_current_features(self._type).offsets.values def point_indices(self): # Return a cupy.ndarray containing the index values from the # MultiPoint GeoSeries that each individual point is member of. offsets = cp.array(self.geometry_offset) sizes = offsets[1:] - offsets[:-1] return cp.repeat(self._meta.input_types.index, sizes) class LineStringGeoColumnAccessor(GeoColumnAccessor): def __init__(self, list_series, meta): super().__init__(list_series, meta) self._type = Feature_Enum.LINESTRING @property def geometry_offset(self): return self._get_current_features(self._type).offsets.values @property def part_offset(self): return self._get_current_features( self._type ).elements.offsets.values def point_indices(self): # Return a cupy.ndarray containing the index values from the # LineString GeoSeries that each individual point is member of. offsets = cp.array(self.part_offset) sizes = offsets[1:] - offsets[:-1] return cp.repeat(self._meta.input_types.index, sizes) class PolygonGeoColumnAccessor(GeoColumnAccessor): def __init__(self, list_series, meta): super().__init__(list_series, meta) self._type = Feature_Enum.POLYGON @property def geometry_offset(self): return self._get_current_features(self._type).offsets.values @property def part_offset(self): return self._get_current_features( self._type ).elements.offsets.values @property def ring_offset(self): return self._get_current_features( self._type ).elements.elements.offsets.values def point_indices(self): # Return a cupy.ndarray containing the index values from the # Polygon GeoSeries that each individual point is member of. offsets = self.ring_offset.take(self.part_offset).take( self.geometry_offset ) sizes = offsets[1:] - offsets[:-1] return self._meta.input_types.index.repeat(sizes) @property def points(self): """Access the `PointsArray` of the underlying `GeoArrowBuffers`.""" return self.GeoColumnAccessor(self._column.points, self._column._meta) @property def multipoints(self): """Access the `MultiPointArray` of the underlying `GeoArrowBuffers`.""" return self.MultiPointGeoColumnAccessor( self._column.mpoints, self._column._meta ) @property def lines(self): """Access the `LineArray` of the underlying `GeoArrowBuffers`.""" return self.LineStringGeoColumnAccessor( self._column.lines, self._column._meta ) @property def polygons(self): """Access the `PolygonArray` of the underlying `GeoArrowBuffers`.""" return self.PolygonGeoColumnAccessor( self._column.polygons, self._column._meta ) def __repr__(self): # TODO: Implement Iloc with slices so that we can use `Series.__repr__` return self.to_pandas().__repr__() class GeoSeriesLocIndexer: """Map the index to an integer Series and use that.""" def __init__(self, _sr): self._sr = _sr def __getitem__(self, item): booltest = cudf.Series(item) if booltest.dtype in (bool, np.bool_): return self._sr.iloc[item] map_df = cudf.DataFrame( {"map": self._sr.index, "idx": cp.arange(len(self._sr.index))} ) index_df = cudf.DataFrame({"map": item}).reset_index() new_index = index_df.merge( map_df, how="left", sort=False ).sort_values("index") if isinstance(item, Integral): return self._sr.iloc[new_index["idx"][0]] else: result = self._sr.iloc[new_index["idx"]] result.index = item return result class GeoSeriesILocIndexer: """Each row of a GeoSeries is one of the six types: Point, MultiPoint, LineString, MultiLineString, Polygon, or MultiPolygon. """ def __init__(self, sr): self._sr = sr @cached_property def _type_int_to_field(self): return { Feature_Enum.POINT: self._sr.points, Feature_Enum.MULTIPOINT: self._sr.mpoints, Feature_Enum.LINESTRING: self._sr.lines, Feature_Enum.POLYGON: self._sr.polygons, } def __getitem__(self, indexes): # Slice the types and offsets union_offsets = self._sr._column._meta.union_offsets.iloc[indexes] union_types = self._sr._column._meta.input_types.iloc[indexes] # Very important to reset the index if it has been constructed from # a slice. if isinstance(union_offsets, cudf.Series): union_offsets = union_offsets.reset_index(drop=True) if isinstance(union_types, cudf.Series): union_types = union_types.reset_index(drop=True) points = self._sr._column.points mpoints = self._sr._column.mpoints lines = self._sr._column.lines polygons = self._sr._column.polygons column = GeoColumn( (points, mpoints, lines, polygons), { "input_types": union_types, "union_offsets": union_offsets, }, ) if isinstance(indexes, Integral): return GeoSeries(column, name=self._sr.name).to_shapely() else: return GeoSeries( column, index=self._sr.index[indexes], name=self._sr.name ) def from_arrow(union): column = GeoColumn( ( cudf.Series(union.child(0)), cudf.Series(union.child(1)), cudf.Series(union.child(2)), cudf.Series(union.child(3)), ), { "input_types": union.type_codes, "union_offsets": union.offsets, }, ) return GeoSeries(column) @property def loc(self): """Not currently supported.""" return self.GeoSeriesLocIndexer(self) @property def iloc(self): """Return the i-th row of the GeoSeries.""" return self.GeoSeriesILocIndexer(self) def to_geopandas(self, nullable=False): """Returns a new GeoPandas GeoSeries object from the coordinates in the cuspatial GeoSeries. """ if nullable is True: raise ValueError("GeoSeries doesn't support <NA> yet") final_union_slice = self.iloc[0 : len(self._column)] return gpGeoSeries( final_union_slice.to_shapely(), index=self.index.to_pandas(), name=self.name, ) def to_pandas(self): """Treats to_pandas and to_geopandas as the same call, which improves compatibility with pandas. """ return self.to_geopandas() def _linestring_to_shapely(self, geom): if len(geom) == 1: result = [tuple(x) for x in geom[0]] return LineString(result) else: linestrings = [] for linestring in geom: linestrings.append( LineString([tuple(child) for child in linestring]) ) return MultiLineString(linestrings) def _polygon_to_shapely(self, geom): if len(geom) == 1: rings = [] for ring in geom[0]: rings.append(tuple(tuple(point) for point in ring)) return Polygon(rings[0], rings[1:]) else: polygons = [] for p in geom: rings = [] for ring in p: rings.append(tuple([tuple(point) for point in ring])) polygons.append(Polygon(rings[0], rings[1:])) return MultiPolygon(polygons) @cached_property def _arrow_to_shapely(self): type_map = { Feature_Enum.NONE: lambda x: None, Feature_Enum.POINT: Point, Feature_Enum.MULTIPOINT: MultiPoint, Feature_Enum.LINESTRING: self._linestring_to_shapely, Feature_Enum.POLYGON: self._polygon_to_shapely, } return type_map def to_shapely(self): # Copy the GPU data to host for iteration and deserialization result_types = self._column._meta.input_types.to_arrow() # Get the shapely serialization methods we'll use here. shapely_fns = [ self._arrow_to_shapely[Feature_Enum(x)] for x in result_types.to_numpy() ] union = self.to_arrow() # Serialize to Shapely! results = [] for (result_index, shapely_serialization_fn) in zip( range(0, len(self)), shapely_fns ): results.append( shapely_serialization_fn(union[result_index].as_py()) ) # Finally, a slice determines that we return a list, otherwise # an object. if len(results) == 1: return results[0] else: return results def to_arrow(self): """Convert to a GeoArrow Array. Returns ------- result: GeoArrow Union containing GeoArrow Arrays Examples -------- >>> from shapely.geometry import MultiLineString, LineString >>> cugpdf = cuspatial.from_geopandas(geopandas.GeoSeries( MultiLineString( [ [(1, 0), (0, 1)], [(0, 0), (1, 1)] ] ))) >>> cugpdf.to_arrow() <pyarrow.lib.UnionArray object at 0x7f7061c0e0a0> -- is_valid: all not null -- type_ids: [ 2 ] -- value_offsets: [ 0 ] -- child 0 type: list<item: null> [] -- child 1 type: list<item: null> [] -- child 2 type: list<item: list<item: list<item: double>>> [ [ [ [ 1, 0 ], [ 0, 1 ] ], [ [ 0, 0 ], [ 1, 1 ] ] ] ] -- child 3 type: list<item: null> [] """ points = self._column.points mpoints = self._column.mpoints lines = self._column.lines polygons = self._column.polygons arrow_points = ( points.to_arrow().view(pygeoarrow.ArrowPointsType) if len(points) > 0 else points.to_arrow() ) arrow_mpoints = ( mpoints.to_arrow().view(pygeoarrow.ArrowMultiPointsType) if len(mpoints) > 1 else mpoints.to_arrow() ) arrow_lines = ( lines.to_arrow().view(pygeoarrow.ArrowLinestringsType) if len(lines) > 1 else lines.to_arrow() ) arrow_polygons = ( polygons.to_arrow().view(pygeoarrow.ArrowPolygonsType) if len(polygons) > 1 else polygons.to_arrow() ) return pa.UnionArray.from_dense( self._column._meta.input_types.to_arrow(), self._column._meta.union_offsets.to_arrow(), [ arrow_points, arrow_mpoints, arrow_lines, arrow_polygons, ], ) def _align_to_index( self: T, index: ColumnLike, how: str = "outer", sort: bool = True, allow_non_unique: bool = False, ) -> T: """The values in the newly aligned columns will not change, only positions in the union offsets and type codes. """ aligned_union_offsets = ( self._column._meta.union_offsets._align_to_index( index, how, sort, allow_non_unique ) ).astype("int32") aligned_union_offsets[ aligned_union_offsets.isna() ] = Feature_Enum.NONE.value aligned_input_types = self._column._meta.input_types._align_to_index( index, how, sort, allow_non_unique ).astype("int8") aligned_input_types[ aligned_input_types.isna() ] = Feature_Enum.NONE.value column = GeoColumn( ( self._column.points, self._column.mpoints, self._column.lines, self._column.polygons, ), { "input_types": aligned_input_types, "union_offsets": aligned_union_offsets, }, ) return GeoSeries(column) @classmethod def from_points_xy(cls, points_xy): """Construct a GeoSeries of POINTs from an array of interleaved xy coordinates. Parameters ---------- points_xy: array-like Coordinates of the points, interpreted as interlaved x-y coords. Returns ------- GeoSeries: A GeoSeries made of the points. """ return cls(GeoColumn._from_points_xy(as_column(points_xy))) @classmethod def from_multipoints_xy(cls, multipoints_xy, geometry_offset): """Construct a GeoSeries of MULTIPOINTs from an array of interleaved xy coordinates. Parameters ---------- points_xy: array-like Coordinates of the points, interpreted as interleaved x-y coords. geometry_offset: array-like Offsets indicating the starting index of the multipoint. Multiply the index by 2 results in the starting index of the coordinate. See example for detail. Returns ------- GeoSeries: A GeoSeries made of the points. Example ------- >>> import numpy as np >>> cuspatial.GeoSeries.from_multipoints_xy( ... np.array([0, 0, 1, 1, 2, 2, 3, 3], dtype='f8'), ... np.array([0, 2, 4], dtype='i4')) 0 MULTIPOINT (0.00000 0.00000, 1.00000 1.00000) 1 MULTIPOINT (2.00000 2.00000, 3.00000 3.00000) dtype: geometry """ return cls( GeoColumn._from_multipoints_xy( as_column(multipoints_xy), as_column(geometry_offset, dtype="int32"), ) ) @classmethod def from_linestrings_xy( cls, linestrings_xy, part_offset, geometry_offset ) -> T: """Construct a GeoSeries of MULTILINESTRINGs from an array of interleaved xy coordinates. Parameters ---------- linestrings_xy : array-like Coordinates of the points, interpreted as interleaved x-y coords. geometry_offset : array-like Offsets of the first coordinate of each geometry. The length of this array is the number of geometries. Offsets with a difference greater than 1 indicate a MultiLinestring. part_offset : array-like Offsets into the coordinates array indicating the beginning of each part. The length of this array is the number of parts. Returns ------- GeoSeries: A GeoSeries of MULTILINESTRINGs. Example ------- >>> import cudf >>> import cuspatial >>> linestrings_xy = cudf.Series( [0.0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]) >>> part_offset = cudf.Series([0, 6]) >>> geometry_offset = cudf.Series([0, 1]) >>> cuspatial.GeoSeries.from_linestrings_xy( linestrings_xy, part_offset, geometry_offset) 0 LINESTRING (0 0, 1 1, 2 2, 3 3, 4 4, 5 5) dtype: geometry """ return cls( GeoColumn._from_linestrings_xy( as_column(linestrings_xy), as_column(part_offset, dtype="int32"), as_column(geometry_offset, dtype="int32"), ) ) @classmethod def from_polygons_xy( cls, polygons_xy, ring_offset, part_offset, geometry_offset ) -> T: """Construct a GeoSeries of MULTIPOLYGONs from an array of interleaved xy coordinates. Parameters ---------- polygons_xy : array-like Coordinates of the points, interpreted as interleaved x-y coords. geometry_offset : array-like Offsets of the first coordinate of each geometry. The length of this array is the number of geometries. Offsets with a difference greater than 1 indicate a MultiLinestring. part_offset : array-like Offsets into the coordinates array indicating the beginning of each part. The length of this array is the number of parts. rint_offset : array-like Offsets into the part array indicating the beginning of each ring. The length of this array is the number of rings. Returns ------- GeoSeries: A GeoSeries of MULTIPOLYGONs. Example ------- >>> import cudf >>> import cuspatial >>> polygons_xy = cudf.Series( [0.0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5]) >>> ring_offset = cudf.Series([0, 6]) >>> part_offset = cudf.Series([0, 1]) >>> geometry_offset = cudf.Series([0, 1]) >>> cuspatial.GeoSeries.from_polygons_xy( polygons_xy, ring_offset, part_offset, geometry_offset) 0 POLYGON (0 0, 1 1, 2 2, 3 3, 4 4, 5 5) dtype: geometry """ return cls( GeoColumn._from_polygons_xy( as_column(polygons_xy), as_column(ring_offset, dtype="int32"), as_column(part_offset, dtype="int32"), as_column(geometry_offset, dtype="int32"), ) ) def align(self, other): """Align the rows of two GeoSeries using outer join. `align` rearranges two GeoSeries so that their indices match. If one GeoSeries is longer than the other, the shorter GeoSeries will be increased in length and missing index values will be added, inserting `None` when an empty row is created. Alignment involves matching the length of the indices, sorting them, and inserting into the right GeoSeries extra index values that are present in the left GeoSeries. Parameters ---------- other: GeoSeries Returns ------- (left, right) : GeoSeries Pair of aligned GeoSeries Examples -------- >>> points = gpd.GeoSeries([ Point((-8, -8)), Point((-2, -2)), ]) >>> point = gpd.GeoSeries(points[0]) >>> print(points.align(point)) (0 POINT (-8.00000 -8.00000) 1 POINT (-2.00000 -2.00000) dtype: geometry, 0 POINT (-8.00000 -8.00000) 1 None dtype: geometry) >>> points_right = gpd.GeoSeries([ Point((-2, -2)), Point((-8, -8)), ], index=[1,0]) >>> print(points.align(points_right)) (0 POINT (-8.00000 -8.00000) 1 POINT (-2.00000 -2.00000) dtype: geometry, 0 POINT (-8.00000 -8.00000) 1 POINT (-2.00000 -2.00000) dtype: geometry) >>> points_alpha = gpd.GeoSeries([ Point((-1, 1)), Point((1, -1)), ], index=['a', 'b']) >>> print(points.align(points_alpha)) (0 POINT (-8.00000 -8.00000) 1 POINT (-2.00000 -2.00000) a None b None dtype: geometry, 0 None 1 None a POINT (-1.00000 1.00000) b POINT (1.00000 -1.00000) dtype: geometry) """ # Merge the two indices and sort them if ( len(self.index) == len(other.index) and (self.index == other.index).all() ): return self, other idx1 = cudf.DataFrame({"idx": self.index}) idx2 = cudf.DataFrame({"idx": other.index}) index = idx1.merge(idx2, how="outer").sort_values("idx")["idx"] index.name = None # Align the two GeoSeries aligned_left = self._align_to_index(index) aligned_right = other._align_to_index(index) # If the two GeoSeries have the same length, keep the original index # Otherwise, use the union of the two indices if len(other) == len(aligned_right): aligned_right.index = other.index else: aligned_right.index = index if len(self) == len(aligned_left): aligned_left.index = self.index else: aligned_left.index = index # Aligned GeoSeries are sorted by index aligned_right = aligned_right.sort_index() aligned_left = aligned_left.sort_index() return ( aligned_left, aligned_right, ) def _gather(self, gather_map: GatherMap, keep_index=True): # TODO: This could use the information to avoid reprocessing # in iloc return self.iloc[gather_map.column] # def reset_index(self, drop=False, inplace=False, name=None): def reset_index( self, level=None, drop=False, name=None, inplace=False, ): """Reset the index of the GeoSeries. Parameters ---------- level : int, str, tuple, or list, default None Only remove the given levels from the index. Removes all levels by default. drop : bool, default False If drop is False, create a new dataframe with the original index as a column. If drop is True, the original index is dropped. name : object, optional The name to use for the column containing the original Series values. inplace: bool, default False If True, the original GeoSeries is modified. Returns ------- GeoSeries GeoSeries with reset index. Examples -------- >>> points = gpd.GeoSeries([ Point((-8, -8)), Point((-2, -2)), ], index=[1, 0]) >>> print(points.reset_index()) 0 POINT (-8.00000 -8.00000) 1 POINT (-2.00000 -2.00000) dtype: geometry """ geo_series = self.copy(deep=False) # Create a cudf series with the same index as the GeoSeries # and use `cudf` reset_index to identify what our result # should look like. cudf_series = cudf.Series( cp.arange(len(geo_series.index)), index=geo_series.index ) cudf_result = cudf_series.reset_index(level, drop, name, inplace) if not inplace: if isinstance(cudf_result, cudf.Series): geo_series.index = cudf_result.index return geo_series elif isinstance(cudf_result, cudf.DataFrame): # Drop was equal to False, so we need to create a # `GeoDataFrame` from the `GeoSeries` from cuspatial.core.geodataframe import GeoDataFrame # The columns of the `cudf.DataFrame` are the new # columns of the `GeoDataFrame`. columns = { col: cudf_result[col] for col in cudf_result.columns } geo_result = GeoDataFrame(columns) geo_series.index = geo_result.index # Add the original `GeoSeries` as a column. if name: geo_result[name] = geo_series else: geo_result[0] = geo_series return geo_result else: self.index = cudf_series.index return None def contains(self, other, align=False, allpairs=False, mode="full"): """Returns a `Series` of `dtype('bool')` with value `True` for each aligned geometry that contains _other_. An object a is said to contain b if b's boundary and interiors are within those of a and no point of b lies in the exterior of a. If `allpairs=False`, the result will be a `Series` of `dtype('bool')`. If `allpairs=True`, the result will be a `DataFrame` containing two columns, `point_indices` a`nd `polygon_indices`, each of which is a `Series` of `dtype('int32')`. The `point_indices` `Series` contains the indices of the points in the right GeoSeries, and the `polygon_indices` `Series` contains the indices of the polygons in the left GeoSeries. Notes ----- `allpairs=True` excludes geometries that contain points in the boundary of A. Parameters ---------- other : GeoSeries align : bool, default False If True, the two GeoSeries are aligned before performing the operation. If False, the operation is performed on the unaligned GeoSeries. allpairs : bool, default False If True, the result will be a `DataFrame` containing two columns, `point_indices` and `polygon_indices`, each of which is a `Series` of `dtype('int32')`. The `point_indices` `Series` contains the indices of the points in the right GeoSeries, and the `polygon_indices` `Series` contains the indices of the polygons in the left GeoSeries. Excludes boundary points. mode : str, default "full" or "basic_none", "basic_any", "basic_all", or "basic_count". If "full", the result will be a `Series` of `dtype('bool')` with value `True` for each aligned geometry that contains _other_. If "intersects", the result will be a `Series` of `dtype('bool')` with value `True` for each aligned geometry that contains _other_ or intersects _other_. Returns ------- Series or DataFrame A `Series` of `dtype('bool')` with value `True` for each aligned geometry that contains _other_. If `allpairs=True`, the result will be a `DataFrame` containing two columns, `point_indices` and `polygon_indices`, each of which is a `Series` of `dtype('int32')`. """ predicate = CONTAINS_DISPATCH[(self.column_type, other.column_type)]( align=align, allpairs=allpairs, mode=mode ) return predicate(self, other) def contains_properly( self, other, align=False, allpairs=False, mode="full" ): """Returns a `Series` of `dtype('bool')` with value `True` for each aligned geometry that contains _other_. Compute from a GeoSeries of points and a GeoSeries of polygons which points are properly contained within the corresponding polygon. Polygon A contains Point B properly if B intersects the interior of A but not the boundary (or exterior). If `allpairs=False`, the result will be a `Series` of `dtype('bool')`. If `allpairs=True`, the result will be a `DataFrame` containing two columns, `point_indices` and `polygon_indices`, each of which is a `Series` of `dtype('int32')`. The `point_indices` `Series` contains the indices of the points in the right GeoSeries, and the `polygon_indices` `Series` contains the indices of the polygons in the left GeoSeries. Parameters ---------- other a cuspatial.GeoSeries align=True to align the indices before computing .contains or not. If the indices are not aligned, they will be compared based on their implicit row order. allpairs=False True computes the contains for all pairs of geometries between the two GeoSeries. False computes the contains for each geometry in the left GeoSeries against the corresponding geometry in the right GeoSeries. Defaults to False. Examples -------- Test if a polygon is inside another polygon: >>> point = cuspatial.GeoSeries([Point(0.5, 0.5)]) >>> polygon = cuspatial.GeoSeries([ >>> Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), >>> ]) >>> print(polygon.contains(point)) 0 False dtype: bool Test whether three points fall within either of two polygons >>> point = cuspatial.GeoSeries([ >>> Point(0, 0), >>> Point(-1, 0), >>> Point(-2, 0), >>> Point(0, 0), >>> Point(-1, 0), >>> Point(-2, 0), >>> ]) >>> polygon = cuspatial.GeoSeries([ >>> Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), >>> Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), >>> Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), >>> Polygon([[-2, -2], [-2, 2], [2, 2], [-2, -2]]), >>> Polygon([[-2, -2], [-2, 2], [2, 2], [-2, -2]]), >>> Polygon([[-2, -2], [-2, 2], [2, 2], [-2, -2]]), >>> ]) >>> print(polygon.contains(point)) 0 False 1 True 2 False 3 False 4 True 5 False dtype: bool Test whether three points fall within either of two polygons using `allpairs` mode: >>> point = cuspatial.GeoSeries([ >>> Point(0, 0), >>> Point(-1, 0), >>> Point(-2, 0), >>> ]) >>> polygon = cuspatial.GeoSeries([ >>> Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), >>> Polygon([[-2, -2], [-2, 2], [2, 2], [-2, -2]]), >>> ]) >>> print(polygon.contains(point, allpairs=True)) index point_indices polygon_indices 0 2 1 Returns ------- result : cudf.Series or cudf.DataFrame A Series of boolean values indicating whether each point falls within the corresponding polygon in the input in the case of `allpairs=False`. A DataFrame containing two columns, `point_indices` and `polygon_indices`, each of which is a `Series` of `dtype('int32')` in the case of `allpairs=True`. """ predicate = CONTAINS_PROPERLY_DISPATCH[ (self.column_type, other.column_type) ](align=align, allpairs=allpairs, mode=mode) return predicate(self, other) def geom_equals(self, other, align=True): """Compute if a GeoSeries of features A is equal to a GeoSeries of features B. Features are equal if their vertices are equal. An object is equal to other if its set-theoretic boundary, interior, and exterior coincide with those of the other object. Parameters ---------- other a cuspatial.GeoSeries align=True to align the indices before computing .contains or not. If the indices are not aligned, they will be compared based on their implicit row order. Examples -------- Test if two points are equal: >>> point = cuspatial.GeoSeries([Point(0, 0)]) >>> point2 = cuspatial.GeoSeries([Point(0, 0)]) >>> print(point.geom_equals(point2)) 0 True dtype: bool Test if two polygons are equal: >>> polygon = cuspatial.GeoSeries([ >>> Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), >>> ]) >>> polygon2 = cuspatial.GeoSeries([ >>> Polygon([[0, 0], [1, 0], [1, 1], [0, 0]]), >>> ]) >>> print(polygon.geom_equals(polygon2)) 0 True dtype: bool Returns ------- result : cudf.Series A Series of boolean values indicating whether each feature in A is equal to the corresponding feature in B. """ predicate = EQUALS_DISPATCH[(self.column_type, other.column_type)]( align=align ) return predicate(self, other) def covers(self, other, align=True): """Compute if a GeoSeries of features A covers a second GeoSeries of features B. A covers B if no points on B lie in the exterior of A. Parameters ---------- other a cuspatial.GeoSeries align=True align the GeoSeries indexes before calling the binpred Returns ------- result : cudf.Series A Series of boolean values indicating whether each feature in the input GeoSeries covers the corresponding feature in the other GeoSeries. """ predicate = COVERS_DISPATCH[(self.column_type, other.column_type)]( align=align ) return predicate(self, other) def intersects(self, other, align=True): """Returns a `Series` of `dtype('bool')` with value `True` for each aligned geometry that intersects _other_. An object is said to intersect _other_ if its _boundary_ and _interior_ intersects in any way with those of other. Parameters ---------- other a cuspatial.GeoSeries align=True align the GeoSeries indexes before calling the binpred Returns ------- result : cudf.Series A Series of boolean values indicating whether the geometries of each row intersect. """ predicate = INTERSECTS_DISPATCH[(self.column_type, other.column_type)]( align=align ) return predicate(self, other) def within(self, other, align=True): """Returns a `Series` of `dtype('bool')` with value `True` for each aligned geometry that is within _other_. An object is said to be within other if at least one of its points is located in the interior and no points are located in the exterior of the other. Parameters ---------- other a cuspatial.GeoSeries align=True align the GeoSeries indexes before calling the binpred Returns ------- result : cudf.Series A Series of boolean values indicating whether each feature falls within the corresponding polygon in the input. """ predicate = WITHIN_DISPATCH[(self.column_type, other.column_type)]( align=align ) return predicate(self, other) def overlaps(self, other, align=True): """Returns True for all aligned geometries that overlap other, else False. Geometries overlap if they have more than one but not all points in common, have the same dimension, and the intersection of the interiors of the geometries has the same dimension as the geometries themselves. Parameters ---------- other a cuspatial.GeoSeries align=True align the GeoSeries indexes before calling the binpred Returns ------- result : cudf.Series A Series of boolean values indicating whether each geometry overlaps the corresponding geometry in the input.""" predicate = OVERLAPS_DISPATCH[(self.column_type, other.column_type)]( align=align ) return predicate(self, other) def crosses(self, other, align=True): """Returns True for all aligned geometries that cross other, else False. Geometries cross if they have some but not all interior points in common, have the same dimension, and the intersection of the interiors of the geometries has the dimension of the geometries themselves minus one. Parameters ---------- other a cuspatial.GeoSeries align=True align the GeoSeries indexes before calling the binpred Returns ------- result : cudf.Series A Series of boolean values indicating whether each geometry crosses the corresponding geometry in the input.""" predicate = CROSSES_DISPATCH[(self.column_type, other.column_type)]( align=align ) return predicate(self, other) def disjoint(self, other, align=True): """Returns True for all aligned geometries that are disjoint from other, else False. An object is said to be disjoint to other if its boundary and interior does not intersect at all with those of the other. Parameters ---------- other a cuspatial.GeoSeries align=True align the GeoSeries indexes before calling the binpred Returns ------- result : cudf.Series A Series of boolean values indicating whether each pair of corresponding geometries is disjoint. """ predicate = DISJOINT_DISPATCH[(self.column_type, other.column_type)]( align=align ) return predicate(self, other) def touches(self, other, align=True): """Returns True for all aligned geometries that touch other, else False. Geometries touch if they have any coincident edges or share any vertices, and their interiors do not intersect. Parameters ---------- other a cuspatial.GeoSeries align=True align the GeoSeries indexes before calling the binpred Returns ------- result : cudf.Series A Series of boolean values indicating whether each geometry touches the corresponding geometry in the input.""" predicate = TOUCHES_DISPATCH[(self.column_type, other.column_type)]( align=align ) return predicate(self, other) def isna(self): """Detect missing values.""" c = self._column._meta.input_types == Feature_Enum.NONE.value return cudf.Series(c, index=self.index) def notna(self): """Detect non-missing values.""" c = self._column._meta.input_types != Feature_Enum.NONE.value return cudf.Series(c, index=self.index) def distance(self, other, align=True): """Returns a `Series` containing the distance to aligned other. The operation works on a 1-to-1 row-wise manner. See `geopandas.GeoSeries.distance` documentation for details. Parameters ---------- other The GeoSeries (elementwise) or geometric object to find the distance to. align : bool, default True If True, automatically aligns GeoSeries based on their indices. If False, the order of the elements is preserved. Returns ------- Series (float) Notes ----- Unlike GeoPandas, this API currently only supports geoseries that contain only single type geometries. Examples -------- >>> from shapely.geometry import Point >>> point = GeoSeries([Point(0, 0)]) >>> point2 = GeoSeries([Point(1, 1)]) >>> print(point.distance(point2)) 0 1.414214 dtype: float64 By default, geoseries are aligned before computing: >>> from shapely.geometry import Point >>> point = GeoSeries([Point(0, 0)]) >>> point2 = GeoSeries([Point(1, 1), Point(2, 2)]) >>> print(point.distance(point2)) 0 1.414214 1 NaN dtype: float64 This can be overridden by setting `align=False`: >>> lines = GeoSeries([ LineString([(0, 0), (1, 1)]), LineString([(2, 2), (3, 3)])]) >>> polys = GeoSeries([ Polygon([(0, 0), (1, 1), (1, 0)]), Polygon([(2, 2), (3, 3), (3, 2)])], index=[1, 0]) >>> lines.distance(polys), align=False) 0 0.0 1 0.0 dtype: float64 >>> lines.distance(polys, align=True) 0 1.414214 1 1.414214 dtype: float64 """ other_is_scalar = False if issubclass(type(other), (BaseGeometry, BaseMultipartGeometry)): other_is_scalar = True other = GeoSeries([other] * len(self), index=self.index) if not align: if len(self) != len(other): raise ValueError( f"Lengths of inputs do not match. Left: {len(self)}, " f"Right: {len(other)}" ) res = DistanceDispatch(self, other, align)() if other_is_scalar: res.index = self.index return res
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/geodataframe.py
# Copyright (c) 2020-2022, NVIDIA CORPORATION from typing import Dict, Tuple, TypeVar, Union import pandas as pd from geopandas import GeoDataFrame as gpGeoDataFrame from geopandas.geoseries import is_geometry_type as gp_is_geometry_type import cudf from cudf.core.copy_types import BooleanMask, GatherMap from cuspatial.core._column.geocolumn import GeoColumn, GeoMeta from cuspatial.core.geoseries import GeoSeries from cuspatial.io.geopandas_reader import GeoPandasReader T = TypeVar("T", bound="GeoDataFrame") class GeoDataFrame(cudf.DataFrame): """ A GPU GeoDataFrame object. """ def __init__( self, data: Union[Dict, gpGeoDataFrame, cudf.DataFrame] = None ): """ Constructs a GPU GeoDataFrame from a GeoPandas dataframe. Parameters ---------- data : A geopandas.GeoDataFrame object, a cudf.DataFrame object, or a dictionary of objects that can be converted to a GeoDataFrame. """ super().__init__() if isinstance(data, (gpGeoDataFrame, cudf.DataFrame)): self.index = data.index for col in data.columns: if is_geometry_type(data[col]): adapter = GeoPandasReader(data[col]) pandas_meta = GeoMeta(adapter.get_geopandas_meta()) column = GeoColumn(adapter._get_geotuple(), pandas_meta) self._data[col] = column else: self._data[col] = data[col] elif isinstance(data, dict): for key in data.keys(): try: data[key] = GeoSeries(data[key]) except TypeError: pass super()._init_from_dict_like( data, index=self.index if len(self.index) > 0 else None ) elif data is None: pass else: raise ValueError("Invalid type passed to GeoDataFrame ctor") @property def _constructor(self): return GeoDataFrame @property def _constructor_sliced(self): return _GeoSeriesUtility def to_pandas(self, nullable=False): """ Calls `self.to_geopandas`, converting GeoSeries columns into GeoPandas columns and cudf.Series columns into pandas.Series columns, and returning a pandas.DataFrame. Parameters ---------- nullable: matches the cudf `to_pandas` signature, not yet supported. """ return self.to_geopandas(nullable=nullable) def to_geopandas(self, nullable=False): """ Returns a new GeoPandas GeoDataFrame object from the coordinates in the cuspatial GeoDataFrame. Parameters ---------- nullable: matches the cudf `to_pandas` signature, not yet supported. """ if nullable is True: raise ValueError("cuGeoDataFrame doesn't support N/A yet") result = gpGeoDataFrame( dict([(col, self[col].to_pandas()) for col in self.columns]), index=self.index.to_pandas(), ) return result def __repr__(self): return self.to_pandas().__repr__() + "\n" + "(GPU)" + "\n" def _copy_type_metadata( self, other, include_index: bool = True, *, override_dtypes=None ): """ Copy type metadata from each column of `other` to the corresponding column of `self`. See `ColumnBase._with_type_metadata` for more information. """ type_copied = super()._copy_type_metadata( other, include_index=include_index, override_dtypes=override_dtypes ) for name, col, other_col in zip( type_copied._data.keys(), type_copied._data.values(), other._data.values(), ): # A GeoColumn is currently implemented as a NumericalColumn with # several child columns to hold the geometry data. The native # return loop of cudf cython code can only reconstruct the # geocolumn as a NumericalColumn. We can't reconstruct the full # GeoColumn at the column level via _with_type_metadata, because # there is neither a well defined geometry type in cuspatial, # nor we can reconstruct the entire geocolumn data with pure # geometry type. So we need an extra pass here to copy the geometry # data into the type reconstructed dataframe. if isinstance(other_col, GeoColumn): col = GeoColumn( ( other_col.points, other_col.mpoints, other_col.lines, other_col.polygons, ), other_col._meta, cudf.Index(col), ) type_copied._data.set_by_label(name, col, validate=False) return type_copied def _split_out_geometry_columns(self) -> Tuple: """ Break the geometry columns and non-geometry columns into separate dataframes and return them separated. """ columns_mask = pd.Series(self.columns) geocolumn_mask = pd.Series( [isinstance(self[col], GeoSeries) for col in self.columns], dtype="bool", ) geo_columns = self[columns_mask[geocolumn_mask]] # Send the rest of the columns to `cudf` to slice. data_columns = cudf.DataFrame( self[columns_mask[~geocolumn_mask].values] ) return (geo_columns, data_columns) def _recombine_columns(self, geo_columns, data_columns): """ Combine a GeoDataFrame of only geometry columns with a DataFrame of non-geometry columns in the same order as the columns in `self` """ columns_mask = pd.Series(self.columns) geocolumn_mask = pd.Series( [isinstance(self[col], GeoSeries) for col in self.columns] ) return { name: (geo_columns[name] if mask else data_columns[name]) for name, mask in zip(columns_mask.values, geocolumn_mask.values) } def _slice(self: T, arg: slice) -> T: """ Overload the _slice functionality from cudf's frame members. """ geo_columns, data_columns = self._split_out_geometry_columns() sliced_geo_columns = GeoDataFrame( {name: geo_columns[name].iloc[arg] for name in geo_columns.columns} ) sliced_data_columns = data_columns._slice(arg) result = self._recombine_columns( sliced_geo_columns, sliced_data_columns ) return self.__class__(result) def _apply_boolean_mask(self, mask: BooleanMask, keep_index=True) -> T: geo_columns, data_columns = self._split_out_geometry_columns() data = data_columns._apply_boolean_mask(mask, keep_index) geo = GeoDataFrame( {name: geo_columns[name][mask.column] for name in geo_columns} ) res = self.__class__._from_data(self._recombine_columns(geo, data)) if keep_index: res.index = data.index return res def _gather(self, gather_map: GatherMap, keep_index=True): geo_data, cudf_data = self._split_out_geometry_columns() # gather cudf columns df = cudf.DataFrame._from_data(data=cudf_data, index=self.index) cudf_gathered = df._gather(gather_map, keep_index=keep_index) # gather GeoColumns gathered = { geo: geo_data[geo].iloc[gather_map.column] for geo in geo_data.keys() } geo_gathered = GeoDataFrame(gathered) # combine result = GeoDataFrame._from_data( self._recombine_columns(geo_gathered, cudf_gathered) ) result.index = geo_gathered.index # return return result def reset_index( self, level=None, drop=False, inplace=False, col_level=0, col_fill="" ): """Reset the index, or a level of it. Parameters ---------- level : `int`, `str`, `tuple`, or `list`, default `None` Only remove the given levels from the index. Removes all levels by default. drop : `bool`, default `False` Do not try to insert index into dataframe columns. This resets the index to the default integer index. inplace : `bool`, default `False` Modify the GeoDataFrame in place (do not create a new object). col_level : `int` or `str`, default `0` If the columns have multiple levels, determines which level the labels are inserted into. By default it is inserted into the first level. col_fill : `object`, default `""` If the columns have multiple levels, determines how the other levels are named. If None then the index name is repeated. Returns ------- `GeoDataFrame` """ # Split geometry and non-geometry columns geo_data, cudf_data = self._split_out_geometry_columns() # Reset cudf column cudf_reindexed = cudf_data.reset_index( level, drop, inplace, col_level, col_fill ) if inplace: cudf_reindexed = cudf_data # Reset GeoColumns recombiner = self.copy(deep=False) recombiner.index = cudf.RangeIndex(len(recombiner)) # Not a multi-index, and the index was not dropped. if not drop: if not isinstance(cudf_data.index, cudf.MultiIndex): recombiner.insert( loc=0, name="index", value=cudf_reindexed["index"] ) # If the index is a MultiIndex, we need to insert the # individual levels into the GeoDataFrame. elif isinstance(cudf_data.index, cudf.MultiIndex): # If level is not specified, it will be the difference # between the number of columns in reindexed dataframe # and the original. if not level: level = range( len(cudf_reindexed.columns) - len(cudf_data.columns) ) elif not isinstance(level, list): level = [level] levels = ["level_" + str(n) for n in level] for n, name in enumerate(levels): recombiner.insert( loc=n, name=name, value=cudf_reindexed[name].reset_index(drop=True), ) recombiner.index = cudf_reindexed.index if inplace: self.index = cudf_reindexed.index self._data = recombiner._data return None else: # Reset the index of the GeoDataFrame to match the # cudf DataFrame and recombine. geo_data.index = cudf_reindexed.index result = GeoDataFrame._from_data( recombiner._recombine_columns(geo_data, cudf_reindexed) ) result.index = geo_data.index return result class _GeoSeriesUtility: @classmethod def _from_data(cls, new_data, name=None, index=False): new_column = new_data.columns[0] if is_geometry_type(new_column): return GeoSeries(new_column, name=name, index=index) else: return cudf.Series(new_column, name=name, index=index) def is_geometry_type(obj): """ Returns `True` if the column is a `GeoPandas` or `cuspatial.GeoSeries` """ if isinstance(obj, (GeoSeries, GeoColumn)): return True if gp_is_geometry_type(obj): return True return False
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/dtypes.py
# Copyright (c) 2023, NVIDIA CORPORATION. from cudf.core.dtypes import ListDtype def point_dtype(base_dtype): return ListDtype(base_dtype) def multipoint_dtype(base_dtype): return ListDtype(ListDtype(base_dtype)) def linestring_dtype(base_dtype): return ListDtype(ListDtype(ListDtype(base_dtype))) def polygon_dtype(base_dtype): return ListDtype(ListDtype(ListDtype(ListDtype(base_dtype))))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/spatial/projection.py
# Copyright (c) 2022, NVIDIA CORPORATION. from cudf import DataFrame from cuspatial._lib.spatial import ( sinusoidal_projection as cpp_sinusoidal_projection, ) from cuspatial.core.geoseries import GeoSeries from cuspatial.utils.column_utils import ( contain_single_type_geometry, contains_only_multipoints, contains_only_points, ) def sinusoidal_projection(origin_lon, origin_lat, lonlat: GeoSeries): """ Sinusoidal projection of longitude/latitude relative to origin to Cartesian (x/y) coordinates in km. Can be used to approximately convert longitude/latitude coordinates to Cartesian coordinates given that all points are near the origin. Error increases with distance from the origin. Results are scaled relative to the size of the Earth in kilometers. See https://en.wikipedia.org/wiki/Sinusoidal_projection for more detail. Parameters ---------- origin_lon : ``number`` longitude offset (this is subtracted from each input before converting to x,y) origin_lat : ``number`` latitude offset (this is subtracted from each input before converting to x,y) lonlat: GeoSeries A GeoSeries of Points that contains the longitude and latitude to transform Returns ------- result : GeoSeries A GeoSeries that contains the transformed coordinates. """ if contain_single_type_geometry(lonlat): if not contains_only_points(lonlat) or contains_only_multipoints( lonlat ): raise ValueError("`lonlat` must contain only POINTS geometry.") result = cpp_sinusoidal_projection( origin_lon, origin_lat, lonlat.points.x._column, lonlat.points.y._column, ) lonlat_transformed = DataFrame( {"x": result[0], "y": result[1]} ).interleave_columns() return GeoSeries.from_points_xy(lonlat_transformed)
0