repo_id
stringlengths
21
96
file_path
stringlengths
31
155
content
stringlengths
1
92.9M
__index_level_0__
int64
0
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/spatial/join.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. import warnings from cudf import DataFrame from cudf.core.column import as_column from cuspatial import GeoSeries from cuspatial._lib import spatial_join from cuspatial._lib.point_in_polygon import ( point_in_polygon as cpp_point_in_polygon, ) from cuspatial.utils.column_utils import ( contains_only_linestrings, contains_only_points, contains_only_polygons, ) from cuspatial.utils.join_utils import pip_bitmap_column_to_binary_array def point_in_polygon(points: GeoSeries, polygons: GeoSeries): """Compute from a set of points and a set of polygons which points fall within which polygons. Note that `polygons_(x,y)` must be specified as closed polygons: the first and last coordinate of each polygon must be the same. Parameters ---------- points : GeoSeries A Series of points to test polygons: GeoSeries A Series of polygons to test Examples -------- Test whether 3 points fall within either of two polygons >>> result = cuspatial.point_in_polygon( GeoSeries([Point(0, 0), Point(-8, -8), Point(6, 6)]), GeoSeries([ Polygon([(-10, -10), (5, -10), (5, 5), (-10, 5), (-10, -10)]), Polygon([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]) ], index=['nyc', 'hudson river']) ) # The result of point_in_polygon is a DataFrame of Boolean # values indicating whether each point (rows) falls within # each polygon (columns). >>> print(result) nyc hudson river 0 True True 1 True False 2 False True # Point 0: (0, 0) falls in both polygons # Point 1: (-8, -8) falls in the first polygon # Point 2: (6.0, 6.0) falls in the second polygon Returns ------- result : cudf.DataFrame A DataFrame of boolean values indicating whether each point falls within each polygon. """ if len(polygons) == 0: return DataFrame() # The C++ API only supports single-polygon, reject if input has # multipolygons if len(polygons.polygons.part_offset) != len( polygons.polygons.geometry_offset ): raise ValueError("GeoSeries cannot contain multipolygon.") x = as_column(points.points.x) y = as_column(points.points.y) poly_offsets = as_column(polygons.polygons.part_offset) ring_offsets = as_column(polygons.polygons.ring_offset) px = as_column(polygons.polygons.x) py = as_column(polygons.polygons.y) result = cpp_point_in_polygon(x, y, poly_offsets, ring_offsets, px, py) result = DataFrame( pip_bitmap_column_to_binary_array( polygon_bitmap_column=result, width=len(poly_offsets) - 1 ) ) result.columns = polygons.index[::-1] return DataFrame._from_data( { name: result[name].astype("bool") for name in reversed(result.columns) } ) def join_quadtree_and_bounding_boxes( quadtree, bounding_boxes, x_min, x_max, y_min, y_max, scale, max_depth ): """Search a quadtree for polygon or linestring bounding box intersections. Parameters ---------- quadtree : cudf.DataFrame A complete quadtree for a given area-of-interest bounding box. bounding_boxes : cudf.DataFrame Minimum bounding boxes for a set of polygons or linestrings x_min The lower-left x-coordinate of the area of interest bounding box x_max The upper-right x-coordinate of the area of interest bounding box min_y The lower-left y-coordinate of the area of interest bounding box max_y The upper-right y-coordinate of the area of interest bounding box scale Scale to apply to each point's distance from ``(x_min, y_min)`` max_depth Maximum quadtree depth at which to stop testing for intersections Returns ------- result : cudf.DataFrame Indices for each intersecting bounding box and leaf quadrant. bbox_offset : cudf.Series Indices for each bbox that intersects with the quadtree. quad_offset : cudf.Series Indices for each leaf quadrant intersecting with a poly bbox. Notes ----- * Swaps ``min_x`` and ``max_x`` if ``min_x > max_x`` * Swaps ``min_y`` and ``max_y`` if ``min_y > max_y`` """ x_min, x_max, y_min, y_max = ( min(x_min, x_max), max(x_min, x_max), min(y_min, y_max), max(y_min, y_max), ) min_scale = max(x_max - x_min, y_max - y_min) / ((1 << max_depth) + 2) if scale < min_scale: warnings.warn( "scale {} is less than required minimum ".format(scale) + "scale {}. Clamping to minimum scale".format(min_scale) ) return DataFrame._from_data( *spatial_join.join_quadtree_and_bounding_boxes( quadtree, bounding_boxes, x_min, x_max, y_min, y_max, max(scale, min_scale), max_depth, ) ) def quadtree_point_in_polygon( poly_quad_pairs, quadtree, point_indices, points: GeoSeries, polygons: GeoSeries, ): """Test whether the specified points are inside any of the specified polygons. Uses the table of (polygon, quadrant) pairs returned by ``cuspatial.join_quadtree_and_bounding_boxes`` to ensure only the points in the same quadrant as each polygon are tested for intersection. This pre-filtering can dramatically reduce number of points tested per polygon, enabling faster intersection-testing at the expense of extra memory allocated to store the quadtree and sorted point_indices. Parameters ---------- poly_quad_pairs: cudf.DataFrame Table of (polygon, quadrant) index pairs returned by ``cuspatial.join_quadtree_and_bounding_boxes``. quadtree : cudf.DataFrame A complete quadtree for a given area-of-interest bounding box. point_indices : cudf.Series Sorted point indices returned by ``cuspatial.quadtree_on_points`` points: GeoSeries Points used to build the quadtree polygons: GeoSeries Polygons to test against Returns ------- result : cudf.DataFrame Indices for each intersecting point and polygon pair. polygon_index : cudf.Series Index of containing polygon. point_index : cudf.Series Index of contained point. This index refers to ``point_indices``, so it is an index to an index. """ if not contains_only_points(points): raise ValueError( "`point` Geoseries must contains only point geometries." ) if not contains_only_polygons(polygons): raise ValueError( "`polygons` Geoseries must contains only polygons geometries." ) points_x = as_column(points.points.x) points_y = as_column(points.points.y) poly_offsets = as_column(polygons.polygons.part_offset) ring_offsets = as_column(polygons.polygons.ring_offset) poly_points_x = as_column(polygons.polygons.x) poly_points_y = as_column(polygons.polygons.y) return DataFrame._from_data( *spatial_join.quadtree_point_in_polygon( poly_quad_pairs, quadtree, point_indices._column, points_x, points_y, poly_offsets, ring_offsets, poly_points_x, poly_points_y, ) ) def quadtree_point_to_nearest_linestring( linestring_quad_pairs, quadtree, point_indices, points: GeoSeries, linestrings: GeoSeries, ): """Finds the nearest linestring to each point in a quadrant, and computes the distances between each point and linestring. Uses the table of (linestring, quadrant) pairs returned by ``cuspatial.join_quadtree_and_bounding_boxes`` to ensure distances are computed only for the points in the same quadrant as each linestring. Parameters ---------- linestring_quad_pairs: cudf.DataFrame Table of (linestring, quadrant) index pairs returned by ``cuspatial.join_quadtree_and_bounding_boxes``. quadtree : cudf.DataFrame A complete quadtree for a given area-of-interest bounding box. point_indices : cudf.Series Sorted point indices returned by ``cuspatial.quadtree_on_points`` points: GeoSeries Points to find nearest linestring for linestrings: GeoSeries Linestrings to test for Returns ------- result : cudf.DataFrame Indices for each point and its nearest linestring, and the distance between the two. point_index : cudf.Series Index of point. This index refers to ``point_indices``, so it is an index to an index. linestring_index : cudf.Series Index of the nearest linestring to the point. distance : cudf.Series Distance between point and its nearest linestring. """ if not contains_only_points(points): raise ValueError( "`point` Geoseries must contains only point geometries." ) if not contains_only_linestrings(linestrings): raise ValueError( "`linestrings` Geoseries must contains only linestring geometries." ) if len(linestrings.lines.part_offset) != len( linestrings.lines.geometry_offset ): raise ValueError("GeoSeries cannot contain multilinestrings.") points_x = as_column(points.points.x) points_y = as_column(points.points.y) linestring_points_x = as_column(linestrings.lines.x) linestring_points_y = as_column(linestrings.lines.y) linestring_offsets = as_column(linestrings.lines.part_offset) return DataFrame._from_data( *spatial_join.quadtree_point_to_nearest_linestring( linestring_quad_pairs, quadtree, as_column(point_indices, dtype="uint32"), points_x, points_y, as_column(linestring_offsets, dtype="uint32"), linestring_points_x, linestring_points_y, ) )
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/spatial/nearest_points.py
import cupy as cp from cudf.core.column import as_column import cuspatial._lib.nearest_points as nearest_points from cuspatial.core._column.geocolumn import GeoColumn from cuspatial.core.geodataframe import GeoDataFrame from cuspatial.core.geoseries import GeoSeries from cuspatial.utils.column_utils import ( contains_only_linestrings, contains_only_points, ) def pairwise_point_linestring_nearest_points( points: GeoSeries, linestrings: GeoSeries ) -> GeoDataFrame: """Returns the nearest points between two GeoSeries of points and linestrings. Multipoints and Multilinestrings are also supported. With restriction that the `points` series must contain either only points or only multipoints. Parameters ---------- points : GeoSeries A GeoSeries of points. Currently either only a series of points or a series of multipoints is supported. linestrings : GeoSeries A GeoSeries of linestrings or multilinestrings. Returns ------- GeoDataFrame A GeoDataFrame with four columns. - "point_geometry_id" contains index of the nearest point in the row. If `points` consists of single-points, it is always 0. - "linestring_geometry_id" contains the index of the linestring in the multilinestring that contains the nearest point. - "segment_id" contains the index of the segment in the linestring that contains the nearest point. - "geometry" contains the points of the nearest point on the linestring. """ if len(points) != len(linestrings): raise ValueError( "The inputs should have the same number of geometries" ) if len(points) == 0: data = { "point_geometry_id": [], "linestring_geometry_id": [], "segment_id": [], "geometry": GeoSeries([]), } return GeoDataFrame._from_data(data) if not contains_only_points(points): raise ValueError("`points` must contain only point geometries.") if not contains_only_linestrings(linestrings): raise ValueError( "`linestrings` must contain only linestring geometries." ) if len(points.points.xy) > 0 and len(points.multipoints.xy) > 0: raise NotImplementedError( "Mixing points and multipoint geometries in `points` is not yet " "supported." ) points_xy = ( points.points.xy if len(points.points.xy) > 0 else points.multipoints.xy ) points_geometry_offset = ( None if len(points.points.xy) > 0 else as_column(points.multipoints.geometry_offset) ) ( point_geometry_id, linestring_geometry_id, segment_id, point_on_linestring_xy, ) = nearest_points.pairwise_point_linestring_nearest_points( points_xy._column, as_column(linestrings.lines.part_offset), linestrings.lines.xy._column, points_geometry_offset, as_column(linestrings.lines.geometry_offset), ) point_on_linestring = GeoColumn._from_points_xy(point_on_linestring_xy) nearest_points_on_linestring = GeoSeries(point_on_linestring) if not point_geometry_id: point_geometry_id = cp.zeros(len(points), dtype=cp.int32) data = { "point_geometry_id": point_geometry_id, "linestring_geometry_id": linestring_geometry_id, "segment_id": segment_id, "geometry": nearest_points_on_linestring, } return GeoDataFrame._from_data(data)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/spatial/indexing.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. import warnings from cudf import DataFrame, Series from cudf.core.column import as_column from cuspatial import GeoSeries from cuspatial._lib.quadtree import ( quadtree_on_points as cpp_quadtree_on_points, ) from cuspatial.utils.column_utils import contains_only_points def quadtree_on_points( points: GeoSeries, x_min, x_max, y_min, y_max, scale, max_depth, max_size ): """ Construct a quadtree from a set of points for a given area-of-interest bounding box. Parameters ---------- points Series of points. x_min The lower-left x-coordinate of the area of interest bounding box. x_max The upper-right x-coordinate of the area of interest bounding box. y_min The lower-left y-coordinate of the area of interest bounding box. y_max The upper-right y-coordinate of the area of interest bounding box. scale Scale to apply to each point's distance from ``(x_min, y_min)``. max_depth Maximum quadtree depth. max_size Maximum number of points allowed in a node before it's split into 4 leaf nodes. Returns ------- result : tuple (cudf.Series, cudf.DataFrame) keys_to_points : cudf.Series(dtype=np.int32) A column of sorted keys to original point indices quadtree : cudf.DataFrame A complete quadtree for the set of input points key : cudf.Series(dtype=np.int32) An int32 column of quadrant keys level : cudf.Series(dtype=np.int8) An int8 column of quadtree levels is_internal_node : cudf.Series(dtype=np.bool_) A boolean column indicating whether the node is a quad or leaf length : cudf.Series(dtype=np.int32) If this is a non-leaf quadrant (i.e. ``is_internal_node`` is ``True``), this column's value is the number of children in the non-leaf quadrant. Otherwise this column's value is the number of points contained in the leaf quadrant. offset : cudf.Series(dtype=np.int32) If this is a non-leaf quadrant (i.e. ``is_internal_node`` is ``True``), this column's value is the position of the non-leaf quadrant's first child. Otherwise this column's value is the position of the leaf quadrant's first point. Notes ----- * Swaps ``min_x`` and ``max_x`` if ``min_x > max_x`` * Swaps ``min_y`` and ``max_y`` if ``min_y > max_y`` * 2D coordinates are converted into a 1D Morton code by dividing each x/y by the ``scale``: (``(x - min_x) / scale`` and ``(y - min_y) / scale``). * `max_depth` should be less than 16, since Morton codes are represented as `uint32_t`. The eventual number of levels may be less than `max_depth` if the number of points is small or `max_size` is large. * All intermediate quadtree nodes will have fewer than `max_size` number of points. Leaf nodes are permitted (but not guaranteed) to have >= `max_size` number of points. Examples -------- An example of selecting the ``max_size`` and ``scale`` based on input:: >>> np.random.seed(0) >>> points = cudf.DataFrame({ "x": cudf.Series(np.random.normal(size=120)) * 500, "y": cudf.Series(np.random.normal(size=120)) * 500, }) >>> max_depth = 3 >>> max_size = 50 >>> min_x, min_y, max_x, max_y = (points["x"].min(), points["y"].min(), points["x"].max(), points["y"].max()) >>> scale = max(max_x - min_x, max_y - min_y) // (1 << max_depth) >>> print( "max_size: " + str(max_size) + "\\n" "num_points: " + str(len(points)) + "\\n" "min_x: " + str(min_x) + "\\n" "max_x: " + str(max_x) + "\\n" "min_y: " + str(min_y) + "\\n" "max_y: " + str(max_y) + "\\n" "scale: " + str(scale) + "\\n" ) max_size: 50 num_points: 120 min_x: -1577.4949079170394 max_x: 1435.877311993804 min_y: -1412.7015761122134 max_y: 1492.572387431971 scale: 301.0 >>> key_to_point, quadtree = cuspatial.quadtree_on_points( points["x"], points["y"], min_x, max_x, min_y, max_y, scale, max_depth, max_size ) >>> print(quadtree) key level is_internal_node length offset 0 0 0 False 15 0 1 1 0 False 27 15 2 2 0 False 12 42 3 3 0 True 4 8 4 4 0 False 5 106 5 6 0 False 6 111 6 9 0 False 2 117 7 12 0 False 1 119 8 12 1 False 22 54 9 13 1 False 18 76 10 14 1 False 9 94 11 15 1 False 3 103 >>> print(key_to_point) 0 63 1 20 2 33 3 66 4 19 ... 115 113 116 3 117 78 118 98 119 24 Length: 120, dtype: int32 """ if not len(points) == 0 and not contains_only_points(points): raise ValueError("GeoSeries must contain only points.") xs = as_column(points.points.x) ys = as_column(points.points.y) x_min, x_max, y_min, y_max = ( min(x_min, x_max), max(x_min, x_max), min(y_min, y_max), max(y_min, y_max), ) min_scale = max(x_max - x_min, y_max - y_min) / ((1 << max_depth) + 2) if scale < min_scale: warnings.warn( "scale {} is less than required minimum ".format(scale) + "scale {}. Clamping to minimum scale".format(min_scale) ) key_to_point, quadtree = cpp_quadtree_on_points( xs, ys, x_min, x_max, y_min, y_max, max(scale, min_scale), max_depth, max_size, ) return Series(key_to_point), DataFrame._from_data(*quadtree)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/spatial/bounding.py
# Copyright (c) 2022, NVIDIA CORPORATION. from cudf import DataFrame from cudf.core.column import as_column from cuspatial._lib.linestring_bounding_boxes import ( linestring_bounding_boxes as cpp_linestring_bounding_boxes, ) from cuspatial._lib.polygon_bounding_boxes import ( polygon_bounding_boxes as cpp_polygon_bounding_boxes, ) from cuspatial.core.geoseries import GeoSeries from cuspatial.utils.column_utils import ( contains_only_linestrings, contains_only_polygons, ) def polygon_bounding_boxes(polygons: GeoSeries): """Compute the minimum bounding-boxes for a set of polygons. Parameters ---------- polygons: GeoSeries A series of polygons Returns ------- result : cudf.DataFrame minimum bounding boxes for each polygon minx : cudf.Series the minimum x-coordinate of each bounding box miny : cudf.Series the minimum y-coordinate of each bounding box maxx : cudf.Series the maximum x-coordinate of each bounding box maxy : cudf.Series the maximum y-coordinate of each bounding box Notes ----- Has no notion of multipolygons. If a multipolygon is passed, the bounding boxes for each polygon will be computed and returned. The user is responsible for handling the multipolygon case. """ column_names = ["minx", "miny", "maxx", "maxy"] if len(polygons) == 0: return DataFrame(columns=column_names, dtype="f8") if not contains_only_polygons(polygons): raise ValueError("Geoseries must contain only polygons.") # `cpp_polygon_bounding_boxes` computes bbox with all points supplied, # but only supports single-polygon input. We compute the polygon offset # by combining the geometry offset and parts offset of the multipolygon # array. poly_offsets = polygons.polygons.part_offset ring_offsets = polygons.polygons.ring_offset x = polygons.polygons.x y = polygons.polygons.y return DataFrame._from_data( dict( zip( column_names, cpp_polygon_bounding_boxes( as_column(poly_offsets), as_column(ring_offsets), as_column(x), as_column(y), ), ) ) ) def linestring_bounding_boxes(linestrings: GeoSeries, expansion_radius: float): """Compute the minimum bounding boxes for a set of linestrings. Parameters ---------- linestrings: GeoSeries A series of linestrings expansion_radius radius of each linestring point Returns ------- result : cudf.DataFrame minimum bounding boxes for each linestring minx : cudf.Series the minimum x-coordinate of each bounding box miny : cudf.Series the minimum y-coordinate of each bounding box maxx : cudf.Series the maximum x-coordinate of each bounding box maxy : cudf.Series the maximum y-coordinate of each bounding box """ column_names = ["minx", "miny", "maxx", "maxy"] if len(linestrings) == 0: return DataFrame(columns=column_names, dtype="f8") if not contains_only_linestrings(linestrings): raise ValueError("Geoseries must contain only linestrings.") # `cpp_linestring_bounding_boxes` computes bbox with all points supplied, # but only supports single-linestring input. We compute the linestring # offset by combining the geometry offset and parts offset of the # multilinestring array. line_offsets = linestrings.lines.part_offset.take( linestrings.lines.geometry_offset ) x = linestrings.lines.x y = linestrings.lines.y results = cpp_linestring_bounding_boxes( as_column(line_offsets), as_column(x), as_column(y), expansion_radius ) return DataFrame._from_data(dict(zip(column_names, results)))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/spatial/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. from .bounding import linestring_bounding_boxes, polygon_bounding_boxes from .distance import ( directed_hausdorff_distance, haversine_distance, pairwise_linestring_distance, pairwise_linestring_polygon_distance, pairwise_point_distance, pairwise_point_linestring_distance, pairwise_point_polygon_distance, pairwise_polygon_distance, ) from .filtering import points_in_spatial_window from .indexing import quadtree_on_points from .join import ( join_quadtree_and_bounding_boxes, point_in_polygon, quadtree_point_in_polygon, quadtree_point_to_nearest_linestring, ) from .nearest_points import pairwise_point_linestring_nearest_points from .projection import sinusoidal_projection __all__ = [ "directed_hausdorff_distance", "haversine_distance", "join_quadtree_and_bounding_boxes", "sinusoidal_projection", "pairwise_point_distance", "pairwise_linestring_distance", "pairwise_linestring_polygon_distance", "pairwise_point_polygon_distance", "pairwise_point_linestring_distance", "pairwise_point_linestring_nearest_points", "pairwise_polygon_distance", "polygon_bounding_boxes", "linestring_bounding_boxes", "point_in_polygon", "points_in_spatial_window", "quadtree_on_points", "quadtree_point_in_polygon", "quadtree_point_to_nearest_linestring", ]
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/spatial/distance.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. import cudf from cudf import DataFrame, Series from cudf.core.column import as_column from cuspatial._lib.distance import ( directed_hausdorff_distance as cpp_directed_hausdorff_distance, haversine_distance as cpp_haversine_distance, pairwise_linestring_distance as cpp_pairwise_linestring_distance, pairwise_linestring_polygon_distance as c_pairwise_line_poly_dist, pairwise_point_distance as cpp_pairwise_point_distance, pairwise_point_linestring_distance as c_pairwise_point_linestring_distance, pairwise_point_polygon_distance as c_pairwise_point_polygon_distance, pairwise_polygon_distance as c_pairwise_polygon_distance, ) from cuspatial._lib.types import CollectionType from cuspatial.core.geoseries import GeoSeries from cuspatial.utils.column_utils import ( contains_only_linestrings, contains_only_multipoints, contains_only_points, contains_only_polygons, ) def directed_hausdorff_distance(multipoints: GeoSeries): """Compute the directed Hausdorff distances between all pairs of spaces. Parameters ---------- multipoints: GeoSeries A column of multipoint, where each multipoint indicates an input space to compute its hausdorff distance to the rest of input spaces. Returns ------- result : cudf.DataFrame result[i, j] indicates the hausdorff distance between multipoints[i] and multipoint[j]. Examples -------- The directed Hausdorff distance from one space to another is the greatest of all the distances between any point in the first space to the closest point in the second. `Wikipedia <https://en.wikipedia.org/wiki/Hausdorff_distance>`_ Consider a pair of lines on a grid:: : x -----xyy--- : : x\\ :sub:`0` = (0, 0), x\\ :sub:`1` = (0, 1) y\\ :sub:`0` = (1, 0), y\\ :sub:`1` = (2, 0) x\\ :sub:`0` is the closest point in ``x`` to ``y``. The distance from x\\ :sub:`0` to the farthest point in ``y`` is 2. y\\ :sub:`0` is the closest point in ``y`` to ``x``. The distance from y\\ :sub:`0` to the farthest point in ``x`` is 1.414. Compute the directed hausdorff distances between a set of spaces >>> pts = cuspatial.GeoSeries([ ... MultiPoint([(0, 0), (1, 0)]), ... MultiPoint([(0, 1), (0, 2)]) ... ]) >>> cuspatial.directed_hausdorff_distance(pts) 0 1 0 0.0 1.414214 1 2.0 0.000000 """ num_spaces = len(multipoints) if num_spaces == 0: return DataFrame([]) if not contains_only_multipoints(multipoints): raise ValueError("Input must be a series of multipoints.") result = cpp_directed_hausdorff_distance( multipoints.multipoints.x._column, multipoints.multipoints.y._column, as_column(multipoints.multipoints.geometry_offset[:-1]), ) return DataFrame._from_columns(result, range(num_spaces)) def haversine_distance(p1: GeoSeries, p2: GeoSeries): """Compute the haversine distances in kilometers between an arbitrary list of lon/lat pairs Parameters ---------- p1: GeoSeries Series of points as floats p2: GeoSeries Series of points as floats Returns ------- result : cudf.Series The distance between pairs of points between `p1` and `p2` >>> import cudf >>> import cuspatial >>> a = {"latitude":[0.0,0.0,1.0,1.0], ... "longitude": [0.0,1.0,0.0,1.0]} >>> df = cudf.DataFrame(data=a) >>> # Create cuSpatial GeoSeries from cuDF Dataframe >>> gs = cuspatial.GeoSeries.from_points_xy( ... df[['longitude', 'latitude']].interleave_columns() ... ) >>> # Create Comparator cuSpatial GeoSeries from a comparator point >>> df['compare_lat'] = 2.0 # this will broadcast the value to all rows >>> df['compare_lng'] = 2.0 >>> cmp_gs = cuspatial.GeoSeries.from_points_xy( ... df[['compare_lat', 'compare_lng']].interleave_columns() ... ) >>> # Calculate Haversine Distance of cuDF dataframe to comparator point >>> df['compare_dist'] = cuspatial.haversine_distance(gs, cmp_gs) >>> df.head() latitude longitude compare_lat compare_lng compare_dist 0 0.0 0.0 2.0 2.0 314.474805 1 0.0 1.0 2.0 2.0 248.629315 2 1.0 0.0 2.0 2.0 248.568719 3 1.0 1.0 2.0 2.0 157.225432 """ if any([not contains_only_points(p1), not contains_only_points(p2)]): raise ValueError("Input muist be two series of points.") if len(p1) != len(p2): raise ValueError("Mismatch length of inputs.") p1_lon = p1.points.x._column p1_lat = p1.points.y._column p2_lon = p2.points.x._column p2_lat = p2.points.y._column return cudf.Series._from_data( {"None": cpp_haversine_distance(p1_lon, p1_lat, p2_lon, p2_lat)} ) def pairwise_point_distance(points1: GeoSeries, points2: GeoSeries): """Compute distance between (multi)points-(multi)points pairs Currently `points1` and `points2` must contain either only points or multipoints. Mixing points and multipoints in the same series is unsupported. Parameters ---------- points1 : GeoSeries A GeoSeries of (multi)points points2 : GeoSeries A GeoSeries of (multi)points Returns ------- distance : cudf.Series the distance between each pair of (multi)points Examples -------- >>> from shapely.geometry import Point, MultiPoint >>> p1 = cuspatial.GeoSeries([ ... MultiPoint([(0.0, 0.0), (1.0, 0.0)]), ... MultiPoint([(0.0, 1.0), (1.0, 0.0)]) ... ]) >>> p2 = cuspatial.GeoSeries([ ... Point(2.0, 2.0), Point(0.0, 0.5) ... ]) >>> cuspatial.pairwise_point_distance(p1, p2) 0 2.236068 1 0.500000 dtype: float64 """ if not len(points1) == len(points2): raise ValueError("`points1` and `points2` must have the same length") if len(points1) == 0: return cudf.Series(dtype="float64") if not contains_only_points(points1): raise ValueError("`points1` array must contain only points") if not contains_only_points(points2): raise ValueError("`points2` array must contain only points") if (len(points1.points.xy) > 0 and len(points1.multipoints.xy) > 0) or ( len(points2.points.xy) > 0 and len(points2.multipoints.xy) > 0 ): raise NotImplementedError( "Mixing point and multipoint geometries is not supported" ) ( lhs_column, lhs_point_collection_type, ) = _extract_point_column_and_collection_type(points1) ( rhs_column, rhs_point_collection_type, ) = _extract_point_column_and_collection_type(points2) return Series._from_data( { None: cpp_pairwise_point_distance( lhs_point_collection_type, rhs_point_collection_type, lhs_column, rhs_column, ) } ) def pairwise_linestring_distance( multilinestrings1: GeoSeries, multilinestrings2: GeoSeries ): """Compute distance between (multi)linestring-(multi)linestring pairs The shortest distance between two linestrings is defined as the shortest distance between all pairs of segments of the two linestrings. If any of the segments intersect, the distance is 0. Parameters ---------- multilinestrings1 : GeoSeries A GeoSeries of (multi)linestrings multilinestrings2 : GeoSeries A GeoSeries of (multi)linestrings Returns ------- distance : cudf.Series the distance between each pair of linestrings Examples -------- >>> from shapely.geometry import LineString, MultiLineString >>> ls1 = cuspatial.GeoSeries([ ... LineString([(0, 0), (1, 1)]), ... LineString([(1, 0), (2, 1)]) ... ]) >>> ls2 = cuspatial.GeoSeries([ ... MultiLineString([ ... LineString([(-1, 0), (-2, -1)]), ... LineString([(-2, -1), (-3, -2)]) ... ]), ... MultiLineString([ ... LineString([(0, -1), (0, -2), (0, -3)]), ... LineString([(0, -3), (-1, -3), (-2, -3)]) ... ]) ... ]) >>> cuspatial.pairwise_linestring_distance(ls1, ls2) 0 1.000000 1 1.414214 dtype: float64 """ if not len(multilinestrings1) == len(multilinestrings2): raise ValueError( "`multilinestrings1` and `multilinestrings2` must have the same " "length" ) if len(multilinestrings1) == 0: return cudf.Series(dtype="float64") if not contains_only_linestrings( multilinestrings1 ) or not contains_only_linestrings(multilinestrings2): raise ValueError( "`multilinestrings1` and `multilinestrings2` must contain only " "linestrings" ) if len(multilinestrings1) == 0: return cudf.Series(dtype="float64") return Series._from_data( { None: cpp_pairwise_linestring_distance( multilinestrings1.lines.column(), multilinestrings2.lines.column(), ) } ) def pairwise_point_linestring_distance( points: GeoSeries, linestrings: GeoSeries ): """Compute distance between (multi)points-(multi)linestrings pairs The distance between a (multi)point and a (multi)linestring is defined as the shortest distance between every point in the multipoint and every line segment in the multilinestring. This algorithm computes distance pairwise. The ith row in the result is the distance between the ith (multi)point in `points` and the ith (multi)linestring in `linestrings`. Parameters ---------- points : GeoSeries The (multi)points to compute the distance from. linestrings : GeoSeries The (multi)linestrings to compute the distance from. Returns ------- distance : cudf.Series Notes ----- The input `GeoSeries` must contain a single type geometry. For example, `points` series cannot contain both points and polygons. Currently, it is unsupported that `points` contains both points and multipoints. Examples -------- **Compute distances between point array to linestring arrays** >>> from shapely.geometry import ( ... Point, MultiPoint, LineString, MultiLineString ... ) >>> import geopandas as gpd, cuspatial >>> pts = cuspatial.from_geopandas(gpd.GeoSeries([ ... Point(0.0, 0.0), Point(1.0, 1.0), Point(2.0, 2.0) ... ])) >>> mlines = cuspatial.from_geopandas(gpd.GeoSeries( ... [ ... LineString([Point(-1.0, 0.0), ... Point(-0.5, -0.5), ... Point(-1.0, -0.5), ... Point(-0.5, -1.0)]), ... LineString([Point(8.0, 10.0), ... Point(11.21, 9.48), ... Point(7.1, 12.5)]), ... LineString([Point(1.0, 0.0), Point(0.0, 1.0)]), ... ])) >>> cuspatial.pairwise_point_linestring_distance(pts, mlines) 0 0.707107 1 11.401754 2 2.121320 dtype: float64 **Compute distances between multipoint to multilinestring arrays** >>> # 3 pairs of multi points containing 3 points each >>> ptsdata = [ ... [[9, 7], [0, 6], [7, 2]], ... [[5, 8], [5, 7], [6, 0]], ... [[8, 8], [6, 7], [4, 1]], ... ] >>> # 3 pairs of multi linestrings containing 2 linestrings each >>> linesdata = [ ... [ ... [[86, 47], [31, 17], [84, 16], [14, 63]], ... [[14, 36], [90, 73], [72, 66], [0, 5]], ... ], ... [ ... [[36, 90], [29, 31], [91, 70], [25, 78]], ... [[61, 64], [89, 20], [94, 46], [37, 44]], ... ], ... [ ... [[60, 76], [29, 60], [53, 87], [8, 18]], ... [[0, 16], [79, 14], [3, 6], [98, 89]], ... ], ... ] >>> pts = cuspatial.from_geopandas( ... gpd.GeoSeries(map(MultiPoint, ptsdata)) ... ) >>> lines = cuspatial.from_geopandas( ... gpd.GeoSeries(map(MultiLineString, linesdata)) ... ) >>> cuspatial.pairwise_point_linestring_distance(pts, lines) 0 0.762984 1 33.241540 2 0.680451 dtype: float64 """ if not contains_only_points(points): raise ValueError("`points` array must contain only points") if not contains_only_linestrings(linestrings): raise ValueError("`linestrings` array must contain only linestrings") if len(points.points.xy) > 0 and len(points.multipoints.xy) > 0: raise NotImplementedError( "Mixing point and multipoint geometries is not supported" ) ( point_column, point_collection_type, ) = _extract_point_column_and_collection_type(points) return Series._from_data( { None: c_pairwise_point_linestring_distance( point_collection_type, point_column, linestrings.lines.column(), ) } ) def pairwise_point_polygon_distance(points: GeoSeries, polygons: GeoSeries): """Compute distance between (multi)points-(multi)polygons pairs The distance between a (multi)point and a (multi)polygon is defined as the shortest distance between every point in the multipoint and every edge of the (multi)polygon. If the multipoint and multipolygon intersects, the distance is 0. This algorithm computes distance pairwise. The ith row in the result is the distance between the ith (multi)point in `points` and the ith (multi)polygon in `polygons`. Parameters ---------- points : GeoSeries The (multi)points to compute the distance from. polygons : GeoSeries The (multi)polygons to compute the distance from. Returns ------- distance : cudf.Series Notes ----- The input `GeoSeries` must contain a single type geometry. For example, `points` series cannot contain both points and polygons. Currently, it is unsupported that `points` contains both points and multipoints. Examples -------- Compute distance between a point and a polygon: >>> from shapely.geometry import Point >>> points = cuspatial.GeoSeries([Point(0, 0)]) >>> polygons = cuspatial.GeoSeries([Point(1, 1).buffer(0.5)]) >>> cuspatial.pairwise_point_polygon_distance(points, polygons) 0 0.914214 dtype: float64 Compute distance between a multipoint and a multipolygon >>> from shapely.geometry import MultiPoint >>> mpoints = cuspatial.GeoSeries([MultiPoint([Point(0, 0), Point(1, 1)])]) >>> mpolys = cuspatial.GeoSeries([ ... MultiPoint([Point(2, 2), Point(1, 2)]).buffer(0.5)]) >>> cuspatial.pairwise_point_polygon_distance(mpoints, mpolys) 0 0.5 dtype: float64 """ if len(points) != len(polygons): raise ValueError("Unmatched input geoseries length.") if len(points) == 0: return cudf.Series(dtype=points.points.xy.dtype) if not contains_only_points(points): raise ValueError("`points` array must contain only points") if not contains_only_polygons(polygons): raise ValueError("`polygons` array must contain only polygons") if len(points.points.xy) > 0 and len(points.multipoints.xy) > 0: raise NotImplementedError( "Mixing point and multipoint geometries is not supported" ) ( points_column, point_collection_type, ) = _extract_point_column_and_collection_type(points) polygon_column = polygons.polygons.column() return Series._from_data( { None: c_pairwise_point_polygon_distance( point_collection_type, points_column, polygon_column ) } ) def pairwise_linestring_polygon_distance( linestrings: GeoSeries, polygons: GeoSeries ): """Compute distance between (multi)linestrings-(multi)polygons pairs. The distance between a (multi)linestrings and a (multi)polygon is defined as the shortest distance between every segment in the multilinestring and every edge of the (multi)polygon. If the multilinestring and multipolygon intersect, the distance is 0. This algorithm computes distance pairwise. The ith row in the result is the distance between the ith (multi)linestring in `linestrings` and the ith (multi)polygon in `polygons`. Parameters ---------- linestrings : GeoSeries The (multi)linestrings to compute the distance from. polygons : GeoSeries The (multi)polygons to compute the distance from. Returns ------- distance : cudf.Series Notes ----- The input `GeoSeries` must contain a single type geometry. For example, `linestrings` series cannot contain both linestrings and polygons. Examples -------- Compute distance between a linestring and a polygon: >>> from shapely.geometry import LineString, Polygon >>> lines = cuspatial.GeoSeries([ ... LineString([(0, 0), (1, 1)])]) >>> polys = cuspatial.GeoSeries([ ... Polygon([(-1, -1), (-1, 0), (-2, 0), (-1, -1)]) ... ]) >>> cuspatial.pairwise_linestring_polygon_distance(lines, polys) 0 1.0 dtype: float64 Compute distance between a multipoint and a multipolygon >>> from shapely.geometry import MultiLineString, MultiPolygon >>> lines = cuspatial.GeoSeries([ ... MultiLineString([ ... LineString([(0, 0), (1, 1)]), ... LineString([(1, 1), (2, 2)])]) ... ]) >>> polys = cuspatial.GeoSeries([ ... MultiPolygon([ ... Polygon([(-1, -1), (-1, 0), (-2, 0), (-1, -1)]), ... Polygon([(-2, 0), (-3, 0), (-3, -1), (-2, 0)])]) ... ]) >>> cuspatial.pairwise_linestring_polygon_distance(lines, polys) 0 1.0 dtype: float64 """ if len(linestrings) != len(polygons): raise ValueError("Unmatched input geoseries length.") if len(linestrings) == 0: return cudf.Series(dtype=linestrings.lines.xy.dtype) if not contains_only_linestrings(linestrings): raise ValueError("`linestrings` array must contain only linestrings") if not contains_only_polygons(polygons): raise ValueError("`polygon` array must contain only polygons") linestrings_column = linestrings.lines.column() polygon_column = polygons.polygons.column() return Series._from_data( {None: c_pairwise_line_poly_dist(linestrings_column, polygon_column)} ) def pairwise_polygon_distance(polygons1: GeoSeries, polygons2: GeoSeries): """Compute distance between (multi)polygon-(multi)polygon pairs. The distance between two (multi)polygons is defined as the shortest distance between any edge of the first (multi)polygon and any edge of the second (multi)polygon. If two (multi)polygons intersect, the distance is 0. This algorithm computes distance pairwise. The ith row in the result is the distance between the ith (multi)polygon in `polygons1` and the ith (multi)polygon in `polygons2`. Parameters ---------- polygons1 : GeoSeries The (multi)polygons to compute the distance from. polygons2 : GeoSeries The (multi)polygons to compute the distance from. Returns ------- distance : cudf.Series Notes ----- `polygons1` and `polygons2` must contain only polygons. Examples -------- Compute distance between polygons: >>> from shapely.geometry import Polygon, MultiPolygon >>> s0 = cuspatial.GeoSeries([ ... Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)])]) >>> s1 = cuspatial.GeoSeries([ ... Polygon([(2, 2), (3, 2), (3, 3), (2, 2)])]) >>> cuspatial.pairwise_polygon_distance(s0, s1) 0 1.414214 dtype: float64 Compute distance between multipolygons: >>> s0 = cuspatial.GeoSeries([ ... MultiPolygon([ ... Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]), ... Polygon([(2, 0), (3, 0), (3, 1), (2, 0)])])]) >>> s1 = cuspatial.GeoSeries([ ... MultiPolygon([ ... Polygon([(-1, 0), (-2, 0), (-2, -1), (-1, -1), (-1, 0)]), ... Polygon([(0, -1), (1, -1), (1, -2), (0, -2), (0, -1)])])]) >>> cuspatial.pairwise_polygon_distance(s0, s1) 0 1.0 dtype: float64 """ if len(polygons1) != len(polygons2): raise ValueError("Unmatched input geoseries length.") if len(polygons1) == 0: return cudf.Series(dtype=polygons1.lines.xy.dtype) if not contains_only_polygons(polygons1): raise ValueError("`polygons1` array must contain only polygons") if not contains_only_polygons(polygons2): raise ValueError("`polygons2` array must contain only polygons") polygon1_column = polygons1.polygons.column() polygon2_column = polygons2.polygons.column() return Series._from_data( {None: c_pairwise_polygon_distance(polygon1_column, polygon2_column)} ) def _extract_point_column_and_collection_type(s: GeoSeries): """Given a GeoSeries that contains only points or multipoints, return the point or multipoint column and the collection type of the GeoSeries. """ point_collection_type = ( CollectionType.SINGLE if len(s.points.xy > 0) else CollectionType.MULTI ) if point_collection_type == CollectionType.SINGLE: return s.points.column(), point_collection_type else: return s.multipoints.column(), point_collection_type
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/spatial/filtering.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. from cudf import DataFrame from cudf.core.column import as_column from cuspatial._lib import points_in_range from cuspatial.core.geoseries import GeoSeries from cuspatial.utils.column_utils import contains_only_points def points_in_spatial_window(points: GeoSeries, min_x, max_x, min_y, max_y): """Return only the subset of coordinates that fall within a rectangular window. A point `(x, y)` is inside the query window if and only if ``min_x < x < max_x AND min_y < y < max_y`` The window is specified by minimum and maximum x and y coordinates. Parameters ---------- points: GeoSeries A geoseries of points min_x: float lower x-coordinate of the query window max_x: float upper x-coordinate of the query window min_y: float lower y-coordinate of the query window max_y: float upper y-coordinate of the query window Returns ------- result : GeoSeries subset of `points` above that fall within the window Notes ----- * Swaps ``min_x`` and ``max_x`` if ``min_x > max_x`` * Swaps ``min_y`` and ``max_y`` if ``min_y > max_y`` """ if len(points) == 0: return GeoSeries([]) if not contains_only_points(points): raise ValueError("GeoSeries must contain only points.") xs = as_column(points.points.x) ys = as_column(points.points.y) res_xy = DataFrame._from_data( *points_in_range.points_in_range(min_x, max_x, min_y, max_y, xs, ys) ).interleave_columns() return GeoSeries.from_points_xy(res_xy)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binpreds/feature_intersects.py
# Copyright (c) 2023, NVIDIA CORPORATION. import cupy as cp import cudf from cuspatial.core.binops.intersection import pairwise_linestring_intersection from cuspatial.core.binpreds.basic_predicates import ( _basic_contains_any, _basic_intersects, ) from cuspatial.core.binpreds.binpred_interface import ( BinPred, IntersectsOpResult, NotImplementedPredicate, PreprocessorResult, ) from cuspatial.core.binpreds.feature_equals import EqualsPredicateBase from cuspatial.utils.binpred_utils import ( LineString, MultiPoint, Point, Polygon, _false_series, ) class IntersectsPredicateBase(BinPred): """Base class for binary predicates that are defined in terms of the intersection primitive. """ def _preprocess(self, lhs, rhs): """Convert input lhs and rhs into LineStrings. The intersection basic predicate requires that the input geometries be LineStrings or MultiLineStrings. This function converts the input geometries into LineStrings and stores them in the PreprocessorResult object that is passed into _compute_predicate. Parameters ---------- lhs : GeoSeries The left hand side of the binary predicate. rhs : GeoSeries The right hand side of the binary predicate. Returns ------- GeoSeries A boolean Series containing the computed result of the final binary predicate operation, """ return self._compute_predicate(lhs, rhs, PreprocessorResult(lhs, rhs)) def _compute_predicate(self, lhs, rhs, preprocessor_result): """Compute the predicate using the intersects basic predicate. lhs and rhs must both be LineStrings or MultiLineStrings. """ basic_result = pairwise_linestring_intersection( preprocessor_result.lhs, preprocessor_result.rhs ) computed_result = IntersectsOpResult(basic_result) return self._postprocess(lhs, rhs, computed_result) def _get_intersecting_geometry_indices(self, lhs, op_result): """Naively computes the indices of matches by constructing a set of lengths from the returned offsets buffer, then returns an integer index for all of the offset sizes that are larger than 0.""" is_offsets = cudf.Series(op_result.result[0]) is_sizes = is_offsets[1:].reset_index(drop=True) - is_offsets[ :-1 ].reset_index(drop=True) return cp.arange(len(lhs))[is_sizes > 0] def _postprocess(self, lhs, rhs, op_result): """Postprocess the output GeoSeries to ensure that they are of the correct type for the predicate.""" match_indices = self._get_intersecting_geometry_indices(lhs, op_result) result = _false_series(len(lhs)) if len(op_result.result[1]) > 0: result[match_indices] = True return result class IntersectsByEquals(EqualsPredicateBase): pass class PolygonPointIntersects(BinPred): def _preprocess(self, lhs, rhs): return _basic_contains_any(lhs, rhs) class PointPolygonIntersects(BinPred): def _preprocess(self, lhs, rhs): return _basic_contains_any(rhs, lhs) class LineStringPointIntersects(IntersectsPredicateBase): def _preprocess(self, lhs, rhs): return _basic_intersects(lhs, rhs) class PointLineStringIntersects(LineStringPointIntersects): def _preprocess(self, lhs, rhs): """Swap LHS and RHS and call the normal contains processing.""" return super()._preprocess(rhs, lhs) class LineStringPolygonIntersects(BinPred): def _preprocess(self, lhs, rhs): return _basic_contains_any(rhs, lhs) class PolygonLineStringIntersects(BinPred): def _preprocess(self, lhs, rhs): return _basic_contains_any(lhs, rhs) class PolygonPolygonIntersects(BinPred): def _preprocess(self, lhs, rhs): contains_rhs = _basic_contains_any(rhs, lhs) contains_lhs = _basic_contains_any(lhs, rhs) return contains_rhs | contains_lhs """ Type dispatch dictionary for intersects binary predicates. """ DispatchDict = { (Point, Point): IntersectsByEquals, (Point, MultiPoint): NotImplementedPredicate, (Point, LineString): PointLineStringIntersects, (Point, Polygon): PointPolygonIntersects, (MultiPoint, Point): NotImplementedPredicate, (MultiPoint, MultiPoint): NotImplementedPredicate, (MultiPoint, LineString): NotImplementedPredicate, (MultiPoint, Polygon): NotImplementedPredicate, (LineString, Point): LineStringPointIntersects, (LineString, MultiPoint): LineStringPointIntersects, (LineString, LineString): IntersectsPredicateBase, (LineString, Polygon): LineStringPolygonIntersects, (Polygon, Point): PolygonPointIntersects, (Polygon, MultiPoint): NotImplementedPredicate, (Polygon, LineString): PolygonLineStringIntersects, (Polygon, Polygon): PolygonPolygonIntersects, }
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binpreds/feature_covers.py
# Copyright (c) 2023, NVIDIA CORPORATION. from cuspatial.core.binpreds.basic_predicates import ( _basic_contains_any, _basic_contains_count, _basic_equals_count, _basic_intersects_pli, ) from cuspatial.core.binpreds.binpred_interface import ( BinPred, ImpossiblePredicate, NotImplementedPredicate, ) from cuspatial.core.binpreds.feature_equals import EqualsPredicateBase from cuspatial.core.binpreds.feature_intersects import ( LineStringPointIntersects, ) from cuspatial.utils.binpred_utils import ( LineString, MultiPoint, Point, Polygon, _points_and_lines_to_multipoints, _zero_series, ) class CoversPredicateBase(EqualsPredicateBase): """Implements the covers predicate across different combinations of geometry types. For example, a Point-Polygon covers predicate is defined in terms of a Point-Polygon equals predicate. Point.covers(Point) LineString.covers(Polygon) """ pass class LineStringLineStringCovers(BinPred): def _preprocess(self, lhs, rhs): # A linestring A covers another linestring B iff # no point in B is outside of A. pli = _basic_intersects_pli(lhs, rhs) points = _points_and_lines_to_multipoints(pli[1], pli[0]) # Every point in B must be in the intersection equals = _basic_equals_count(rhs, points) == rhs.sizes return equals class PolygonPointCovers(BinPred): def _preprocess(self, lhs, rhs): return _basic_contains_any(lhs, rhs) class PolygonLineStringCovers(BinPred): def _preprocess(self, lhs, rhs): # A polygon covers a linestring if all of the points in the linestring # are in the interior or exterior of the polygon. This differs from # a polygon that contains a linestring in that some point of the # linestring must be in the interior of the polygon. # Count the number of points from rhs in the interior of lhs contains_count = _basic_contains_count(lhs, rhs) # Now count the number of points from rhs in the boundary of lhs pli = _basic_intersects_pli(lhs, rhs) intersections = pli[1] # There may be no intersection, so start with _zero_series equality = _zero_series(len(rhs)) if len(intersections) > 0: matching_length_multipoints = _points_and_lines_to_multipoints( intersections, pli[0] ) equality = _basic_equals_count(matching_length_multipoints, rhs) covers = contains_count + equality >= rhs.sizes return covers class PolygonPolygonCovers(BinPred): def _preprocess(self, lhs, rhs): contains = lhs.contains(rhs) return contains DispatchDict = { (Point, Point): CoversPredicateBase, (Point, MultiPoint): NotImplementedPredicate, (Point, LineString): ImpossiblePredicate, (Point, Polygon): ImpossiblePredicate, (MultiPoint, Point): NotImplementedPredicate, (MultiPoint, MultiPoint): NotImplementedPredicate, (MultiPoint, LineString): NotImplementedPredicate, (MultiPoint, Polygon): NotImplementedPredicate, (LineString, Point): LineStringPointIntersects, (LineString, MultiPoint): NotImplementedPredicate, (LineString, LineString): LineStringLineStringCovers, (LineString, Polygon): CoversPredicateBase, (Polygon, Point): PolygonPointCovers, (Polygon, MultiPoint): CoversPredicateBase, (Polygon, LineString): PolygonLineStringCovers, (Polygon, Polygon): PolygonPolygonCovers, }
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binpreds/contains_geometry_processor.py
# Copyright (c) 2023, NVIDIA CORPORATION. import cupy as cp import cudf from cudf.core.dataframe import DataFrame from cudf.core.series import Series from cuspatial.core._column.geocolumn import GeoColumn from cuspatial.core.binpreds.binpred_interface import ( BinPred, PreprocessorResult, ) from cuspatial.utils.binpred_utils import ( _count_results_in_multipoint_geometries, _false_series, _true_series, ) from cuspatial.utils.column_utils import ( contains_only_linestrings, contains_only_multipoints, contains_only_polygons, ) class ContainsGeometryProcessor(BinPred): def _preprocess_multipoint_rhs(self, lhs, rhs): """Flatten any rhs into only its points xy array. This is necessary because the basic predicate for contains, point-in-polygon, only accepts points. Parameters ---------- lhs : GeoSeries The left-hand GeoSeries. rhs : GeoSeries The right-hand GeoSeries. Returns ------- result : PreprocessorResult A PreprocessorResult object containing the original lhs and rhs, the rhs with only its points, and the indices of the points in the original rhs. """ # RHS conditioning: point_indices = None # point in polygon if contains_only_linestrings(rhs): # condition for linestrings geom = rhs.lines elif contains_only_polygons(rhs): # polygon in polygon geom = rhs.polygons elif contains_only_multipoints(rhs): # mpoint in polygon geom = rhs.multipoints else: # no conditioning is required geom = rhs.points xy_points = geom.xy # Arrange into shape for calling point-in-polygon point_indices = geom.point_indices() from cuspatial.core.geoseries import GeoSeries final_rhs = GeoSeries(GeoColumn._from_points_xy(xy_points._column)) preprocess_result = PreprocessorResult( lhs, rhs, final_rhs, point_indices ) return preprocess_result def _convert_quadtree_result_from_part_to_polygon_indices( self, lhs, point_result ): """Convert the result of a quadtree contains_properly call from part indices to polygon indices. Parameters ---------- point_result : cudf.Series The result of a quadtree contains_properly call. This result contains the `part_index` of the polygon that contains the point, not the polygon index. Returns ------- cudf.Series The result of a quadtree contains_properly call. This result contains the `polygon_index` of the polygon that contains the point, not the part index. """ # Get the length of each part, map it to indices, and store # the result in a dataframe. rings_to_parts = cp.array(lhs.polygons.part_offset) part_sizes = rings_to_parts[1:] - rings_to_parts[:-1] parts_map = cudf.Series( cp.arange(len(part_sizes)), name="part_index" ).repeat(part_sizes) parts_index_mapping_df = parts_map.reset_index(drop=True).reset_index() # Map the length of each polygon in a similar fashion, then # join them below. parts_to_geoms = cp.array(lhs.polygons.geometry_offset) geometry_sizes = parts_to_geoms[1:] - parts_to_geoms[:-1] geometry_map = cudf.Series( cp.arange(len(geometry_sizes)), name="polygon_index" ).repeat(geometry_sizes) geom_index_mapping_df = geometry_map.reset_index(drop=True) geom_index_mapping_df.index.name = "part_index" geom_index_mapping_df = geom_index_mapping_df.reset_index() # Replace the part index with the polygon index by join part_result = parts_index_mapping_df.merge( point_result, on="part_index" ) # Replace the polygon index with the row index by join return geom_index_mapping_df.merge(part_result, on="part_index")[ ["polygon_index", "point_index"] ] def _reindex_allpairs(self, lhs, op_result) -> DataFrame: """Prepare the allpairs result of a contains_properly call as the first step of postprocessing. An allpairs result is reindexed by replacing the polygon index with the original index of the polygon from the lhs. Parameters ---------- lhs : GeoSeries The left-hand side of the binary predicate. op_result : ContainsProperlyOpResult The result of the contains_properly call. Returns ------- cudf.DataFrame A cudf.DataFrame with two columns: `polygon_index` and `point_index`. The `polygon_index` column contains the index of the polygon from the original lhs that contains the point, and the `point_index` column contains the index of the point from the preprocessor final_rhs input to point-in-polygon. """ # Convert the quadtree part indices df into a polygon indices df polygon_indices = ( self._convert_quadtree_result_from_part_to_polygon_indices( lhs, op_result.pip_result ) ) # Because the quadtree contains_properly call returns a list of # points that are contained in each part, parts can be duplicated # once their index is converted to a polygon index. allpairs_result = polygon_indices.drop_duplicates() # TODO: This is slow and needs optimization # Replace the polygon index with the original index allpairs_result["polygon_index"] = allpairs_result[ "polygon_index" ].replace(Series(lhs.index, index=cp.arange(len(lhs.index)))) return allpairs_result def _postprocess_multipoint_rhs( self, lhs, rhs, preprocessor_result, op_result, mode ): """Reconstruct the original geometry from the result of the contains_properly call. Parameters ---------- lhs : GeoSeries The left-hand side of the binary predicate. rhs : GeoSeries The right-hand side of the binary predicate. preprocessor_result : PreprocessorResult The result of the preprocessor. op_result : ContainsProperlyOpResult The result of the contains_properly call. mode : str The mode of the predicate. Various mode options are available to support binary predicates. The mode options are `full`, `basic_none`, `basic_any`, and `basic_count`. If the default option `full` is specified, `.contains` or .contains_properly` will return a boolean series indicating whether each feature in the right-hand GeoSeries is contained by the corresponding feature in the left-hand GeoSeries. If `basic_none` is specified, `.contains` or .contains_properly` returns the negation of `basic_any`.`. If `basic_any` is specified, `.contains` or `.contains_properly` returns a boolean series indicating whether any point in the right-hand GeoSeries is contained by the corresponding feature in the left-hand GeoSeries. If the `basic_count` option is specified, `.contains` or .contains_properly` returns a Series of integers indicating the number of points in the right-hand GeoSeries that are contained by the corresponding feature in the left-hand GeoSeries. Returns ------- cudf.Series A boolean series indicating whether each feature in the right-hand GeoSeries satisfies the requirements of the point- in-polygon basic predicate with its corresponding feature in the left-hand GeoSeries.""" point_indices = preprocessor_result.point_indices allpairs_result = self._reindex_allpairs(lhs, op_result) if isinstance(allpairs_result, Series): return allpairs_result # Hits is the number of calculated points in each polygon # Expected count is the sizes of the features in the right-hand # GeoSeries (hits, expected_count,) = _count_results_in_multipoint_geometries( point_indices, allpairs_result ) result_df = hits.reset_index().merge( expected_count.reset_index(), on="rhs_index" ) # Handling for the basic predicates if mode == "basic_none": none_result = _true_series(len(rhs)) if len(result_df) == 0: return none_result none_result.loc[result_df["point_index_x"] > 0] = False return none_result elif mode == "basic_any": any_result = _false_series(len(rhs)) if len(result_df) == 0: return any_result indexes = result_df["rhs_index"][result_df["point_index_x"] > 0] any_result.iloc[indexes] = True return any_result elif mode == "basic_count": count_result = cudf.Series(cp.zeros(len(rhs)), dtype="int32") if len(result_df) == 0: return count_result hits = result_df["point_index_x"] hits.index = count_result.iloc[result_df["rhs_index"]].index count_result.iloc[result_df["rhs_index"]] = hits return count_result # Handling for full contains (equivalent to basic predicate all) # for each input pair i: result[i] =  true iff point[i] is # contained in at least one polygon of multipolygon[i]. result_df["feature_in_polygon"] = ( result_df["point_index_x"] >= result_df["point_index_y"] ) final_result = _false_series(len(rhs)) final_result.loc[ result_df["rhs_index"][result_df["feature_in_polygon"]] ] = True return final_result def _postprocess_points(self, lhs, rhs, preprocessor_result, op_result): """Used when the rhs is naturally points. Instead of reconstructing the original geometry, this method applies the `point_index` results to the original rhs points and returns a boolean series reflecting which `point_index`es were found. """ allpairs_result = self._reindex_allpairs(lhs, op_result) if self.config.allpairs: return allpairs_result final_result = _false_series(len(rhs)) if len(lhs) == len(rhs): matches = ( allpairs_result["polygon_index"] == allpairs_result["point_index"] ) polygon_indexes = allpairs_result["polygon_index"][matches] final_result.loc[ preprocessor_result.point_indices[polygon_indexes] ] = True return final_result else: final_result.loc[allpairs_result["polygon_index"]] = True return final_result
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binpreds/feature_touches.py
# Copyright (c) 2023, NVIDIA CORPORATION. import cupy as cp import cudf from cuspatial.core.binpreds.basic_predicates import ( _basic_contains_count, _basic_contains_properly_any, _basic_equals_all, _basic_equals_any, _basic_equals_count, _basic_intersects, _basic_intersects_count, _basic_intersects_pli, ) from cuspatial.core.binpreds.binpred_interface import ( BinPred, ImpossiblePredicate, ) from cuspatial.core.binpreds.feature_contains import ContainsPredicate from cuspatial.utils.binpred_utils import ( LineString, MultiPoint, Point, Polygon, _false_series, _pli_points_to_multipoints, _points_and_lines_to_multipoints, ) class TouchesPredicateBase(ContainsPredicate): """ If any point is shared between the following geometry types, they touch: Used by: (Point, MultiPoint) (Point, LineString) (MultiPoint, Point) (MultiPoint, MultiPoint) (MultiPoint, LineString) (MultiPoint, Polygon) (LineString, Point) (LineString, MultiPoint) (Polygon, MultiPoint) """ def _preprocess(self, lhs, rhs): return _basic_equals_any(lhs, rhs) class PointPolygonTouches(ContainsPredicate): def _preprocess(self, lhs, rhs): # Reverse argument order. equals_all = _basic_equals_all(rhs, lhs) touches = _basic_intersects(rhs, lhs) return ~equals_all & touches class LineStringLineStringTouches(BinPred): def _preprocess(self, lhs, rhs): """A and B have at least one point in common, and the common points lie in at least one boundary""" # First compute pli which will contain points for line crossings and # linestrings for overlapping segments. pli = _basic_intersects_pli(lhs, rhs) offsets = cudf.Series(pli[0]) pli_geometry_count = offsets[1:].reset_index(drop=True) - offsets[ :-1 ].reset_index(drop=True) indices = ( cudf.Series(cp.arange(len(pli_geometry_count))) .repeat(pli_geometry_count) .reset_index(drop=True) ) # In order to be a touch, all of the intersecting geometries # for a particular row must be points. pli_types = pli[1]._column._meta.input_types point_intersection = _false_series(len(lhs)) only_points_in_intersection = ( pli_types.groupby(indices).sum().sort_index() == 0 ) point_intersection.iloc[ only_points_in_intersection.index ] = only_points_in_intersection # Finally, we need to check if the points in the intersection # are equal to endpoints of either linestring. points = _points_and_lines_to_multipoints(pli[1], pli[0]) equals_lhs = _basic_equals_count(points, lhs) > 0 equals_rhs = _basic_equals_count(points, rhs) > 0 touches = point_intersection & (equals_lhs | equals_rhs) return touches & ~lhs.crosses(rhs) class LineStringPolygonTouches(BinPred): def _preprocess(self, lhs, rhs): intersects = _basic_intersects_count(lhs, rhs) > 0 contains = rhs.contains(lhs) contains_any = _basic_contains_properly_any(rhs, lhs) pli = _basic_intersects_pli(lhs, rhs) if len(pli[1]) == 0: return _false_series(len(lhs)) points = _pli_points_to_multipoints(pli) # A touch can only occur if the point in the intersection # is equal to a point in the linestring: it must # terminate in the boundary of the polygon. equals = _basic_equals_count(points, lhs) == points.sizes return equals & intersects & ~contains & ~contains_any class PolygonPointTouches(BinPred): def _preprocess(self, lhs, rhs): intersects = _basic_intersects(lhs, rhs) return intersects class PolygonLineStringTouches(LineStringPolygonTouches): def _preprocess(self, lhs, rhs): return super()._preprocess(rhs, lhs) class PolygonPolygonTouches(BinPred): def _preprocess(self, lhs, rhs): contains_lhs_none = _basic_contains_count(lhs, rhs) == 0 contains_rhs_none = _basic_contains_count(rhs, lhs) == 0 contains_lhs = lhs.contains(rhs) contains_rhs = rhs.contains(lhs) equals = lhs.geom_equals(rhs) intersect_count = _basic_intersects_count(lhs, rhs) intersects = (intersect_count > 0) & (intersect_count < rhs.sizes - 1) result = ( ~equals & contains_lhs_none & contains_rhs_none & ~contains_lhs & ~contains_rhs & intersects ) return result DispatchDict = { (Point, Point): ImpossiblePredicate, (Point, MultiPoint): TouchesPredicateBase, (Point, LineString): TouchesPredicateBase, (Point, Polygon): PointPolygonTouches, (MultiPoint, Point): TouchesPredicateBase, (MultiPoint, MultiPoint): TouchesPredicateBase, (MultiPoint, LineString): TouchesPredicateBase, (MultiPoint, Polygon): TouchesPredicateBase, (LineString, Point): TouchesPredicateBase, (LineString, MultiPoint): TouchesPredicateBase, (LineString, LineString): LineStringLineStringTouches, (LineString, Polygon): LineStringPolygonTouches, (Polygon, Point): PolygonPointTouches, (Polygon, MultiPoint): TouchesPredicateBase, (Polygon, LineString): PolygonLineStringTouches, (Polygon, Polygon): PolygonPolygonTouches, }
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binpreds/feature_within.py
# Copyright (c) 2023, NVIDIA CORPORATION. from cuspatial.core.binpreds.basic_predicates import ( _basic_equals_all, _basic_equals_any, _basic_intersects, ) from cuspatial.core.binpreds.binpred_interface import ( BinPred, ImpossiblePredicate, NotImplementedPredicate, ) from cuspatial.utils.binpred_utils import ( LineString, MultiPoint, Point, Polygon, ) class WithinPredicateBase(BinPred): def _preprocess(self, lhs, rhs): return _basic_equals_all(lhs, rhs) class WithinIntersectsPredicate(BinPred): def _preprocess(self, lhs, rhs): intersects = _basic_intersects(rhs, lhs) equals = _basic_equals_any(rhs, lhs) return intersects & ~equals class PointLineStringWithin(BinPred): def _preprocess(self, lhs, rhs): intersects = lhs.intersects(rhs) equals = _basic_equals_any(lhs, rhs) return intersects & ~equals class PointPolygonWithin(BinPred): def _preprocess(self, lhs, rhs): return rhs.contains_properly(lhs) class LineStringLineStringWithin(BinPred): def _preprocess(self, lhs, rhs): contains = rhs.contains(lhs) return contains class LineStringPolygonWithin(BinPred): def _preprocess(self, lhs, rhs): return rhs.contains(lhs) class PolygonPolygonWithin(BinPred): def _preprocess(self, lhs, rhs): return rhs.contains(lhs) DispatchDict = { (Point, Point): WithinPredicateBase, (Point, MultiPoint): WithinIntersectsPredicate, (Point, LineString): PointLineStringWithin, (Point, Polygon): PointPolygonWithin, (MultiPoint, Point): NotImplementedPredicate, (MultiPoint, MultiPoint): NotImplementedPredicate, (MultiPoint, LineString): WithinIntersectsPredicate, (MultiPoint, Polygon): PolygonPolygonWithin, (LineString, Point): ImpossiblePredicate, (LineString, MultiPoint): WithinIntersectsPredicate, (LineString, LineString): LineStringLineStringWithin, (LineString, Polygon): LineStringPolygonWithin, (Polygon, Point): WithinPredicateBase, (Polygon, MultiPoint): WithinPredicateBase, (Polygon, LineString): WithinPredicateBase, (Polygon, Polygon): PolygonPolygonWithin, }
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binpreds/binpred_dispatch.py
# Copyright (c) 2023, NVIDIA CORPORATION. """`binpred_dispatch.py` contains a collection of dictionaries that are used to dispatch binary predicate functions to the correct implementation. The dictionaries are collected here to make using the dispatch functionality easier. """ from cuspatial.core.binpreds.feature_contains import ( # NOQA F401 DispatchDict as CONTAINS_DISPATCH, ) from cuspatial.core.binpreds.feature_contains_properly import ( # NOQA F401 DispatchDict as CONTAINS_PROPERLY_DISPATCH, ) from cuspatial.core.binpreds.feature_covers import ( # NOQA F401 DispatchDict as COVERS_DISPATCH, ) from cuspatial.core.binpreds.feature_crosses import ( # NOQA F401 DispatchDict as CROSSES_DISPATCH, ) from cuspatial.core.binpreds.feature_disjoint import ( # NOQA F401 DispatchDict as DISJOINT_DISPATCH, ) from cuspatial.core.binpreds.feature_equals import ( # NOQA F401 DispatchDict as EQUALS_DISPATCH, ) from cuspatial.core.binpreds.feature_intersects import ( # NOQA F401 DispatchDict as INTERSECTS_DISPATCH, ) from cuspatial.core.binpreds.feature_overlaps import ( # NOQA F401 DispatchDict as OVERLAPS_DISPATCH, ) from cuspatial.core.binpreds.feature_touches import ( # NOQA F401 DispatchDict as TOUCHES_DISPATCH, ) from cuspatial.core.binpreds.feature_within import ( # NOQA F401 DispatchDict as WITHIN_DISPATCH, )
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binpreds/feature_overlaps.py
# Copyright (c) 2023, NVIDIA CORPORATION. import cudf from cuspatial.core.binpreds.basic_predicates import ( _basic_contains_properly_any, ) from cuspatial.core.binpreds.binpred_interface import ( BinPred, ImpossiblePredicate, ) from cuspatial.core.binpreds.feature_contains import ContainsPredicate from cuspatial.core.binpreds.feature_equals import EqualsPredicateBase from cuspatial.utils.binpred_utils import ( LineString, MultiPoint, Point, Polygon, _false_series, ) from cuspatial.utils.column_utils import has_same_geometry class OverlapsPredicateBase(EqualsPredicateBase): """Base class for overlaps binary predicate. Depends on the equals predicate for all implementations up to this point in time. For example, a Point-Point Overlaps predicate is defined in terms of a Point-Point Equals predicate. Used by: (Point, Polygon) (Polygon, Point) (Polygon, MultiPoint) (Polygon, LineString) (Polygon, Polygon) """ pass class PolygonPolygonOverlaps(BinPred): def _preprocess(self, lhs, rhs): contains_lhs = lhs.contains(rhs) contains_rhs = rhs.contains(lhs) contains_properly_lhs = _basic_contains_properly_any(lhs, rhs) contains_properly_rhs = _basic_contains_properly_any(rhs, lhs) return ~(contains_lhs | contains_rhs) & ( contains_properly_lhs | contains_properly_rhs ) class PolygonPointOverlaps(ContainsPredicate): def _postprocess(self, lhs, rhs, op_result): if not has_same_geometry(lhs, rhs) or len(op_result.point_result) == 0: return _false_series(len(lhs)) polygon_indices = ( self._convert_quadtree_result_from_part_to_polygon_indices( op_result.point_result ) ) group_counts = polygon_indices.groupby("polygon_index").count() point_counts = ( cudf.DataFrame( {"point_indices": op_result.point_indices, "input_size": True} ) .groupby("point_indices") .count() ) result = (group_counts["point_index"] > 0) & ( group_counts["point_index"] < point_counts["input_size"] ) return result """Dispatch table for overlaps binary predicate.""" DispatchDict = { (Point, Point): ImpossiblePredicate, (Point, MultiPoint): ImpossiblePredicate, (Point, LineString): ImpossiblePredicate, (Point, Polygon): OverlapsPredicateBase, (MultiPoint, Point): ImpossiblePredicate, (MultiPoint, MultiPoint): ImpossiblePredicate, (MultiPoint, LineString): ImpossiblePredicate, (MultiPoint, Polygon): ImpossiblePredicate, (LineString, Point): ImpossiblePredicate, (LineString, MultiPoint): ImpossiblePredicate, (LineString, LineString): ImpossiblePredicate, (LineString, Polygon): ImpossiblePredicate, (Polygon, Point): OverlapsPredicateBase, (Polygon, MultiPoint): OverlapsPredicateBase, (Polygon, LineString): OverlapsPredicateBase, (Polygon, Polygon): PolygonPolygonOverlaps, }
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binpreds/feature_crosses.py
# Copyright (c) 2023, NVIDIA CORPORATION. from cuspatial.core.binpreds.basic_predicates import ( _basic_equals_count, _basic_intersects_count, _basic_intersects_pli, ) from cuspatial.core.binpreds.binpred_interface import ( BinPred, ImpossiblePredicate, ) from cuspatial.core.binpreds.feature_equals import EqualsPredicateBase from cuspatial.core.binpreds.feature_intersects import IntersectsPredicateBase from cuspatial.utils.binpred_utils import ( LineString, MultiPoint, Point, Polygon, _false_series, _points_and_lines_to_multipoints, ) class CrossesPredicateBase(EqualsPredicateBase): """Base class for binary predicates that are defined in terms of a the equals binary predicate. For example, a Point-Point Crosses predicate is defined in terms of a Point-Point Equals predicate. Used by: (Point, Polygon) (Polygon, Point) (Polygon, MultiPoint) (Polygon, LineString) (Polygon, Polygon) """ pass class LineStringLineStringCrosses(IntersectsPredicateBase): def _compute_predicate(self, lhs, rhs, preprocessor_result): # A linestring crosses another linestring iff # they intersect, and none of the points of the # intersection are in the boundary of the other pli = _basic_intersects_pli(rhs, lhs) intersections = _points_and_lines_to_multipoints(pli[1], pli[0]) equals_lhs_count = _basic_equals_count(intersections, lhs) equals_rhs_count = _basic_equals_count(intersections, rhs) equals_lhs = equals_lhs_count != intersections.sizes equals_rhs = equals_rhs_count != intersections.sizes equals = equals_lhs & equals_rhs return equals class LineStringPolygonCrosses(BinPred): def _preprocess(self, lhs, rhs): intersects = _basic_intersects_count(rhs, lhs) > 0 touches = rhs.touches(lhs) contains = rhs.contains(lhs) return ~touches & intersects & ~contains class PolygonLineStringCrosses(LineStringPolygonCrosses): def _preprocess(self, lhs, rhs): return super()._preprocess(rhs, lhs) class PointPointCrosses(CrossesPredicateBase): def _preprocess(self, lhs, rhs): """Points can't cross other points, so we return False.""" return _false_series(len(lhs)) DispatchDict = { (Point, Point): PointPointCrosses, (Point, MultiPoint): ImpossiblePredicate, (Point, LineString): ImpossiblePredicate, (Point, Polygon): CrossesPredicateBase, (MultiPoint, Point): ImpossiblePredicate, (MultiPoint, MultiPoint): ImpossiblePredicate, (MultiPoint, LineString): ImpossiblePredicate, (MultiPoint, Polygon): ImpossiblePredicate, (LineString, Point): ImpossiblePredicate, (LineString, MultiPoint): ImpossiblePredicate, (LineString, LineString): LineStringLineStringCrosses, (LineString, Polygon): LineStringPolygonCrosses, (Polygon, Point): CrossesPredicateBase, (Polygon, MultiPoint): CrossesPredicateBase, (Polygon, LineString): PolygonLineStringCrosses, (Polygon, Polygon): ImpossiblePredicate, }
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binpreds/feature_contains_properly.py
# Copyright (c) 2023, NVIDIA CORPORATION. from typing import TypeVar import cupy as cp import cudf from cuspatial.core.binpreds.basic_predicates import ( _basic_equals_all, _basic_intersects, ) from cuspatial.core.binpreds.binpred_interface import ( BinPred, ContainsOpResult, ImpossiblePredicate, NotImplementedPredicate, PreprocessorResult, ) from cuspatial.core.binpreds.contains import contains_properly from cuspatial.core.binpreds.contains_geometry_processor import ( ContainsGeometryProcessor, ) from cuspatial.utils.binpred_utils import ( LineString, MultiPoint, Point, Polygon, _is_complex, ) from cuspatial.utils.column_utils import ( contains_only_polygons, has_multipolygons, ) GeoSeries = TypeVar("GeoSeries") class ContainsProperlyPredicate(ContainsGeometryProcessor): def __init__(self, **kwargs): """Base class for binary predicates that are defined in terms of `contains_properly`. Subclasses are selected using the `DispatchDict` located at the end of this file. Parameters ---------- allpairs: bool Whether to compute all pairs of features in the left-hand and right-hand GeoSeries. If False, the feature will be compared in a 1:1 fashion with the corresponding feature in the other GeoSeries. mode: str The mode to use for computing the predicate. The default is "full", which computes true or false if the `.contains_properly` predicate is satisfied. Other options include "basic_none", "basic_any", "basic_all", and "basic_count". """ super().__init__(**kwargs) self.config.allpairs = kwargs.get("allpairs", False) self.config.mode = kwargs.get("mode", "full") def _preprocess(self, lhs, rhs): preprocessor_result = super()._preprocess_multipoint_rhs(lhs, rhs) return self._compute_predicate(lhs, rhs, preprocessor_result) def _pip_mode(self, lhs, rhs): """Determine if the quadtree should be used for the binary predicate. Returns ------- bool True if the quadtree should be used, False otherwise. Notes ----- 1. If the number of polygons in the lhs is less than 32, we use the brute-force algorithm because it is faster and has less memory overhead. 2. If the lhs contains multipolygons, or `allpairs=True` is specified, we use quadtree because the quadtree code path already handles multipolygons. 3. Otherwise default to pairwise to match the default GeoPandas behavior. """ if len(lhs) <= 31: return "brute_force" elif self.config.allpairs or has_multipolygons(lhs): return "quadtree" else: return "pairwise" def _compute_predicate( self, lhs: "GeoSeries", rhs: "GeoSeries", preprocessor_result: PreprocessorResult, ): """Compute the contains_properly relationship between two GeoSeries. A feature A contains another feature B if no points of B lie in the exterior of A, and at least one point of the interior of B lies in the interior of A. This is the inverse of `within`.""" if not contains_only_polygons(lhs): raise TypeError( "`.contains` can only be called with polygon series." ) mode = self._pip_mode(lhs, preprocessor_result.final_rhs) lhs_indices = lhs.index # Duplicates the lhs polygon for each point in the final_rhs result # that was computed by _preprocess. Will always ensure that the # number of points in the rhs is equal to the number of polygons in the # lhs. if mode == "pairwise": lhs_indices = preprocessor_result.point_indices pip_result = contains_properly( lhs[lhs_indices], preprocessor_result.final_rhs, mode=mode ) # If the mode is pairwise or brute_force, we need to replace the # `pairwise_index` of each repeated polygon with the `part_index` # from the preprocessor result. if "pairwise_index" in pip_result.columns: pairwise_index_df = cudf.DataFrame( { "pairwise_index": cp.arange(len(lhs_indices)), "part_index": rhs.point_indices, } ) pip_result = pip_result.merge( pairwise_index_df, on="pairwise_index" )[["part_index", "point_index"]] op_result = ContainsOpResult(pip_result, preprocessor_result) return self._postprocess(lhs, rhs, preprocessor_result, op_result) def _postprocess(self, lhs, rhs, preprocessor_result, op_result): """Postprocess the output GeoSeries to ensure that they are of the correct type for the predicate. Postprocess for contains_properly has to handle multiple input and output configurations. The input to postprocess is `point_indices`, which can be either a cudf.DataFrame with one row per point and one column per polygon or a cudf.DataFrame containing the point index and the part index for each point in the polygon. Parameters ---------- lhs : GeoSeries The left-hand side of the binary predicate. rhs : GeoSeries The right-hand side of the binary predicate. preprocessor_output : ContainsOpResult The result of the contains_properly call. Returns ------- cudf.Series or cudf.DataFrame A Series of boolean values indicating whether each feature in the rhs GeoSeries is contained in the lhs GeoSeries in the case of allpairs=False. Otherwise, a DataFrame containing the point index and the polygon index for each point in the polygon. """ if _is_complex(rhs): return super()._postprocess_multipoint_rhs( lhs, rhs, preprocessor_result, op_result, mode=self.config.mode ) else: return super()._postprocess_points( lhs, rhs, preprocessor_result, op_result ) class ContainsProperlyByIntersection(BinPred): """Point types are contained only by an intersection test. Used by: (Point, Point) (LineString, Point) """ def _preprocess(self, lhs, rhs): return _basic_intersects(lhs, rhs) class LineStringLineStringContainsProperly(BinPred): def _preprocess(self, lhs, rhs): count = _basic_equals_all(lhs, rhs) return count """DispatchDict listing the classes to use for each combination of left and right hand side types. """ DispatchDict = { (Point, Point): ContainsProperlyByIntersection, (Point, MultiPoint): ContainsProperlyByIntersection, (Point, LineString): ImpossiblePredicate, (Point, Polygon): ImpossiblePredicate, (MultiPoint, Point): NotImplementedPredicate, (MultiPoint, MultiPoint): NotImplementedPredicate, (MultiPoint, LineString): NotImplementedPredicate, (MultiPoint, Polygon): NotImplementedPredicate, (LineString, Point): ContainsProperlyByIntersection, (LineString, MultiPoint): ContainsProperlyPredicate, (LineString, LineString): LineStringLineStringContainsProperly, (LineString, Polygon): ImpossiblePredicate, (Polygon, Point): ContainsProperlyPredicate, (Polygon, MultiPoint): ContainsProperlyPredicate, (Polygon, LineString): ContainsProperlyPredicate, (Polygon, Polygon): ContainsProperlyPredicate, }
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binpreds/feature_equals.py
# Copyright (c) 2023, NVIDIA CORPORATION. from __future__ import annotations from typing import Generic, TypeVar import cupy as cp import cudf from cudf import Series import cuspatial from cuspatial.core.binpreds.binpred_interface import ( BinPred, EqualsOpResult, ImpossiblePredicate, NotImplementedPredicate, PreprocessorResult, ) from cuspatial.utils.binpred_utils import ( LineString, MultiPoint, Point, Polygon, _false_series, ) GeoSeries = TypeVar("GeoSeries") class EqualsPredicateBase(BinPred, Generic[GeoSeries]): """Base class for binary predicates that are defined in terms of the equals basic predicate. `EqualsPredicateBase` implements utility functions that are used within many equals-related binary predicates. Used by: (Point, Point) (Point, Polygon) (LineString, Polygon) (Polygon, Point) (Polygon, MultiPoint) (Polygon, LineString) (Polygon, Polygon) """ def _offset_equals(self, lhs, rhs): """Compute the pairwise length equality of two offset arrays. Consider the following example: lhs = [0, 3, 5, 7] rhs = [0, 2, 4, 6] _offset_equals(lhs, rhs) returns [False, True, True, True]. The first element is False because the first object in lhs has 3 points, while the first object in rhs has 2 points. The remaining elements are True because the remaining objects in lhs and rhs have the same number of points. Parameters ---------- lhs : cudf.Series left-hand-side offset array rhs : cudf.Series right-hand-side offset array Returns ------- cudf.Series pairwise length equality """ lhs_lengths = lhs[:-1] - lhs[1:] rhs_lengths = rhs[:-1] - rhs[1:] return lhs_lengths == rhs_lengths def _sort_interleaved_points_by_offset(self, coords, offsets, sort_order): """Sort xy according to bins defined by offset. Sort order is a list of column names to sort by. `_sort_interleaved_points_by_offset` creates a dataframe with the following columns: "sizes": an index for each object represented in `coords`. "points": an index for each point in `coords`. "xy_key": an index that maintains x/y ordering. "xy": the x/y coordinates in `coords`. The dataframe is sorted according to keys passed in by the caller. For sorting multipoints, the keys in order are "object_key", "xy", "xy_key". This sorts the points in each multipoint into the same bin defined by "object_key", then sorts the points in each bin by x/y coordinates, and finally sorts the points in each bin by the `xy_key` which maintains that the x coordinate precedes the y coordinate. For sorting linestrings, the keys in order are "object_key", "point_key", "xy_key". This sorts the points in each linestring into the same bin defined by "object_key", then sorts the points in each bin by point ordering, and finally sorts the points in each bin by x/y ordering. Parameters ---------- coords : cudf.Series interleaved x,y coordinates offsets : cudf.Series offsets into coords sort_order : list list of column names to sort by. One of "object_key", "point_key", "xy_key", and "xy". Returns ------- cudf.Series sorted interleaved x,y coordinates """ sizes = offsets[1:] - offsets[:-1] object_key = ( cudf.Series(cp.arange(len(sizes))) .repeat(sizes * 2) .reset_index(drop=True) ) point_key = cp.arange(len(coords) // 2).repeat(2)[::-1] xy_key = cp.tile([0, 1], len(coords) // 2) sorting_df = cudf.DataFrame( { "object_key": object_key, "point_key": point_key, "xy_key": xy_key, "xy": coords, } ) sorted_df = sorting_df.sort_values(by=sort_order).reset_index( drop=True ) return sorted_df["xy"] def _sort_multipoint_series(self, coords, offsets): """Sort xy according to bins defined by offset. Consider an xy buffer of 20 values and an offset buffer [0, 5]. This means that the first multipoint has 5 points and the second multipoint has 5 points. The first multipoint is sorted by x/y coordinates and the second multipoint is sorted by x/y coordinates. The resultant sorted values are stored in the same offset region, or bin, as the original unsorted values. Parameters ---------- coords : cudf.Series interleaved x,y coordinates offsets : cudf.Series offsets into coords Returns ------- cudf.Series Coordinates sorted according to the bins defined by offsets. """ result = self._sort_interleaved_points_by_offset( coords, offsets, ["object_key", "xy", "xy_key"] ) result.name = None return result def _sort_multipoints(self, lhs, rhs): """Sort the coordinates of the multipoints in the left-hand and right-hand GeoSeries. Parameters ---------- lhs : GeoSeries The left-hand GeoSeries. rhs : GeoSeries The right-hand GeoSeries. Returns ------- lhs_result : Tuple A tuple containing the sorted left-hand GeoSeries and the sorted right-hand GeoSeries. """ lhs_sorted = self._sort_multipoint_series( lhs.multipoints.xy, lhs.multipoints.geometry_offset ) rhs_sorted = self._sort_multipoint_series( rhs.multipoints.xy, rhs.multipoints.geometry_offset ) lhs_result = cuspatial.core.geoseries.GeoSeries.from_multipoints_xy( lhs_sorted, lhs.multipoints.geometry_offset ) rhs_result = cuspatial.core.geoseries.GeoSeries.from_multipoints_xy( rhs_sorted, rhs.multipoints.geometry_offset ) lhs_result.index = lhs.index rhs_result.index = rhs.index return ( lhs_result, rhs_result, ) def _reverse_linestrings(self, coords, offsets): """Reverse the order of coordinates in a Arrow buffer of coordinates and offsets.""" result = self._sort_interleaved_points_by_offset( coords, offsets, ["object_key", "point_key", "xy_key"] ) result.name = None return result def _preprocess(self, lhs: "GeoSeries", rhs: "GeoSeries"): """Convert the input geometry types into buffers of points that can then be compared with the equals basic predicate. The equals basic predicate is simply the value-equality operation on the coordinates of the points in the geometries. This means that we can convert any geometry type into a buffer of points and then compare the buffers with the equals basic predicate. Parameters ---------- lhs : GeoSeries The left-hand GeoSeries. rhs : GeoSeries The right-hand GeoSeries. Returns ------- result : GeoSeries A GeoSeries of boolean values indicating whether each feature in the right-hand GeoSeries satisfies the requirements of a binary predicate with its corresponding feature in the left-hand GeoSeries. """ # Any unmatched type is not equal if (lhs.feature_types != rhs.feature_types).any(): return _false_series(len(lhs)) return self._compute_predicate( lhs, rhs, PreprocessorResult(None, rhs.point_indices) ) def _vertices_equals(self, lhs: Series, rhs: Series): """Compute the equals relationship between interleaved xy coordinate buffers.""" if not isinstance(lhs, Series): raise TypeError("lhs must be a cudf.Series") if not isinstance(rhs, Series): raise TypeError("rhs must be a cudf.Series") length = min(len(lhs), len(rhs)) a = lhs[:length:2]._column == rhs[:length:2]._column b = rhs[1:length:2]._column == lhs[1:length:2]._column return a & b def _compute_predicate(self, lhs, rhs, preprocessor_result): """Perform the binary predicate operation on the input GeoSeries. The lhs and rhs are `GeoSeries` of points, and the point_indices are the indices of the points in the rhs GeoSeries that correspond to each feature in the rhs GeoSeries. """ result = self._vertices_equals(lhs.points.xy, rhs.points.xy) return self._postprocess( lhs, rhs, EqualsOpResult(result, preprocessor_result.point_indices) ) def _postprocess(self, lhs, rhs, op_result): """Postprocess the output GeoSeries to combine the resulting comparisons into a single boolean value for each feature in the rhs GeoSeries. """ return cudf.Series(op_result.result, dtype="bool") class PolygonComplexEquals(EqualsPredicateBase): def _postprocess(self, lhs, rhs, op_result): """Postprocess the output GeoSeries to combine the resulting comparisons into a single boolean value for each feature in the rhs GeoSeries. """ if len(op_result.result) == 0: return _false_series(len(lhs)) result_df = cudf.DataFrame( {"idx": op_result.point_indices, "equals": op_result.result} ) gb_idx = result_df.groupby("idx") feature_equals_linestring = ( gb_idx.sum().sort_index() == gb_idx.count().sort_index() )["equals"] result = _false_series(len(lhs)) result[ feature_equals_linestring.index ] = feature_equals_linestring.values return result class MultiPointMultiPointEquals(PolygonComplexEquals): def _compute_predicate(self, lhs, rhs, point_indices): lengths_equal = self._offset_equals( lhs.multipoints.geometry_offset, rhs.multipoints.geometry_offset ) (lhs_sorted, rhs_sorted) = self._sort_multipoints( lhs[lengths_equal], rhs[lengths_equal] ) result = self._vertices_equals( lhs_sorted.multipoints.xy, rhs_sorted.multipoints.xy ) return self._postprocess( lhs, rhs, EqualsOpResult(result, rhs_sorted.point_indices) ) class LineStringLineStringEquals(PolygonComplexEquals): def _compute_predicate(self, lhs, rhs, preprocessor_result): """Linestrings can be compared either forward or reversed. We need to compare both directions.""" lengths_equal = self._offset_equals( lhs.lines.part_offset, rhs.lines.part_offset ) lhs_lengths_equal = lhs[lengths_equal] rhs_lengths_equal = rhs[lengths_equal] lhs_reversed = self._reverse_linestrings( lhs_lengths_equal.lines.xy, lhs_lengths_equal.lines.part_offset ) forward_result = self._vertices_equals( lhs_lengths_equal.lines.xy, rhs_lengths_equal.lines.xy ) reverse_result = self._vertices_equals( lhs_reversed, rhs_lengths_equal.lines.xy ) result = forward_result | reverse_result original_point_indices = cudf.Series( lhs_lengths_equal.point_indices ).replace(cudf.Series(lhs_lengths_equal.index)) return self._postprocess( lhs, rhs, EqualsOpResult(result, original_point_indices) ) class LineStringPointEquals(EqualsPredicateBase): def _preprocess(self, lhs, rhs): """A LineString cannot be equal to a point. So, return False.""" return _false_series(len(lhs)) class PolygonPolygonEquals(BinPred): def _preprocess(self, lhs, rhs): """Two polygons are equal if they contain each other.""" lhs_contains_rhs = lhs.contains(rhs) rhs_contains_lhs = rhs.contains(lhs) return lhs_contains_rhs & rhs_contains_lhs """DispatchDict for Equals operations.""" DispatchDict = { (Point, Point): EqualsPredicateBase, (Point, MultiPoint): NotImplementedPredicate, (Point, LineString): ImpossiblePredicate, (Point, Polygon): EqualsPredicateBase, (MultiPoint, Point): NotImplementedPredicate, (MultiPoint, MultiPoint): MultiPointMultiPointEquals, (MultiPoint, LineString): NotImplementedPredicate, (MultiPoint, Polygon): NotImplementedPredicate, (LineString, Point): LineStringPointEquals, (LineString, MultiPoint): NotImplementedPredicate, (LineString, LineString): LineStringLineStringEquals, (LineString, Polygon): EqualsPredicateBase, (Polygon, Point): EqualsPredicateBase, (Polygon, MultiPoint): EqualsPredicateBase, (Polygon, LineString): EqualsPredicateBase, (Polygon, Polygon): PolygonPolygonEquals, }
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binpreds/feature_disjoint.py
# Copyright (c) 2023, NVIDIA CORPORATION. from cuspatial.core.binpreds.basic_predicates import ( _basic_contains_any, _basic_equals_any, _basic_intersects, ) from cuspatial.core.binpreds.binpred_interface import ( BinPred, NotImplementedPredicate, ) from cuspatial.core.binpreds.feature_intersects import IntersectsPredicateBase from cuspatial.utils.binpred_utils import ( LineString, MultiPoint, Point, Polygon, ) class DisjointByWayOfContains(BinPred): def _preprocess(self, lhs, rhs): """Disjoint is the opposite of contains, so just implement contains and then negate the result. Used by: (Point, Polygon) (Polygon, Point) """ return ~_basic_contains_any(lhs, rhs) class PointPointDisjoint(BinPred): def _preprocess(self, lhs, rhs): return ~_basic_equals_any(lhs, rhs) class PointLineStringDisjoint(BinPred): def _preprocess(self, lhs, rhs): """Disjoint is the opposite of intersects, so just implement intersects and then negate the result.""" intersects = _basic_intersects(lhs, rhs) return ~intersects class PointPolygonDisjoint(BinPred): def _preprocess(self, lhs, rhs): return ~_basic_contains_any(lhs, rhs) class LineStringPointDisjoint(PointLineStringDisjoint): def _preprocess(self, lhs, rhs): """Swap ordering for Intersects.""" return super()._preprocess(rhs, lhs) class LineStringLineStringDisjoint(IntersectsPredicateBase): def _postprocess(self, lhs, rhs, op_result): """Disjoint is the opposite of intersects, so just implement intersects and then negate the result.""" result = super()._postprocess(lhs, rhs, op_result) return ~result class LineStringPolygonDisjoint(BinPred): def _preprocess(self, lhs, rhs): return ~_basic_contains_any(rhs, lhs) class PolygonPolygonDisjoint(BinPred): def _preprocess(self, lhs, rhs): return ~_basic_contains_any(lhs, rhs) & ~_basic_contains_any(rhs, lhs) DispatchDict = { (Point, Point): PointPointDisjoint, (Point, MultiPoint): NotImplementedPredicate, (Point, LineString): PointLineStringDisjoint, (Point, Polygon): PointPolygonDisjoint, (MultiPoint, Point): NotImplementedPredicate, (MultiPoint, MultiPoint): NotImplementedPredicate, (MultiPoint, LineString): NotImplementedPredicate, (MultiPoint, Polygon): LineStringPolygonDisjoint, (LineString, Point): LineStringPointDisjoint, (LineString, MultiPoint): NotImplementedPredicate, (LineString, LineString): LineStringLineStringDisjoint, (LineString, Polygon): LineStringPolygonDisjoint, (Polygon, Point): DisjointByWayOfContains, (Polygon, MultiPoint): NotImplementedPredicate, (Polygon, LineString): DisjointByWayOfContains, (Polygon, Polygon): PolygonPolygonDisjoint, }
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binpreds/feature_contains.py
# Copyright (c) 2023, NVIDIA CORPORATION. from typing import TypeVar import cudf from cuspatial.core.binpreds.basic_predicates import ( _basic_contains_count, _basic_equals_any, _basic_equals_count, _basic_intersects, _basic_intersects_pli, ) from cuspatial.core.binpreds.binpred_interface import ( BinPred, ImpossiblePredicate, NotImplementedPredicate, ) from cuspatial.core.binpreds.contains_geometry_processor import ( ContainsGeometryProcessor, ) from cuspatial.utils.binpred_utils import ( LineString, MultiPoint, Point, Polygon, _open_polygon_rings, _pli_lines_to_multipoints, _pli_points_to_multipoints, _points_and_lines_to_multipoints, _zero_series, ) from cuspatial.utils.column_utils import ( contains_only_linestrings, contains_only_points, contains_only_polygons, ) GeoSeries = TypeVar("GeoSeries") class ContainsPredicate(ContainsGeometryProcessor): def __init__(self, **kwargs): super().__init__(**kwargs) self.config.allpairs = kwargs.get("allpairs", False) self.config.mode = kwargs.get("mode", "full") def _preprocess(self, lhs, rhs): preprocessor_result = super()._preprocess_multipoint_rhs(lhs, rhs) return self._compute_predicate(lhs, rhs, preprocessor_result) def _intersection_results_for_contains_linestring(self, lhs, rhs): pli = _basic_intersects_pli(lhs, rhs) # Convert the pli into points and multipoint intersections. multipoint_points = _pli_points_to_multipoints(pli) multipoint_lines = _pli_lines_to_multipoints(pli) # Count the point intersections that are equal to points in the # LineString # Count the linestring intersections that are equal to points in # the LineString return ( _basic_equals_count(rhs, multipoint_points), _basic_equals_count(rhs, multipoint_lines), ) def _intersection_results_for_contains_polygon(self, lhs, rhs): pli = _basic_intersects_pli(lhs, rhs) pli_features = pli[1] if len(pli_features) == 0: return _zero_series(len(lhs)) pli_offsets = cudf.Series(pli[0]) # Convert the pli to multipoints for equality checking multipoints = _points_and_lines_to_multipoints( pli_features, pli_offsets ) intersect_equals_count = _basic_equals_count(rhs, multipoints) return intersect_equals_count def _compute_polygon_polygon_contains(self, lhs, rhs, preprocessor_result): lines_rhs = _open_polygon_rings(rhs) contains = _basic_contains_count(lhs, lines_rhs).reset_index(drop=True) intersects = self._intersection_results_for_contains_polygon( lhs, lines_rhs ) # A closed polygon has an extra line segment that is not used in # counting the number of points. We need to subtract this from the # number of points in the polygon. multipolygon_part_offset = rhs.polygons.part_offset.take( rhs.polygons.geometry_offset ) polygon_size_reduction = ( multipolygon_part_offset[1:] - multipolygon_part_offset[:-1] ) result = contains + intersects >= rhs.sizes - polygon_size_reduction return result def _compute_polygon_linestring_contains( self, lhs, rhs, preprocessor_result ): # Count the number of points in lhs that are properly contained by # rhs contains = _basic_contains_count(lhs, rhs).reset_index(drop=True) # Count the number of point intersections (line crossings) between # lhs and rhs. # Also count the number of perfectly overlapping linestring sections. # Each linestring overlap counts as two point overlaps. ( point_intersects_count, linestring_intersects_count, ) = self._intersection_results_for_contains_linestring(lhs, rhs) # Subtract the length of the linestring intersections from the length # of the rhs linestring, then test that the sum of contained points # is equal to that adjusted rhs length. rhs_sizes_less_line_intersection_size = ( rhs.sizes - linestring_intersects_count ) rhs_sizes_less_line_intersection_size[ rhs_sizes_less_line_intersection_size <= 0 ] = 1 final_result = contains + point_intersects_count == ( rhs_sizes_less_line_intersection_size ) return final_result def _compute_predicate(self, lhs, rhs, preprocessor_result): if contains_only_points(rhs): # Special case in GeoPandas, points are not contained # in the boundary of a polygon, so only return true if # the points are contained_properly. contains = _basic_contains_count(lhs, rhs).reset_index(drop=True) return contains > 0 elif contains_only_linestrings(rhs): return self._compute_polygon_linestring_contains( lhs, rhs, preprocessor_result ) elif contains_only_polygons(rhs): return self._compute_polygon_polygon_contains( lhs, rhs, preprocessor_result ) else: raise NotImplementedError("Invalid rhs for contains operation") class PointPointContains(BinPred): def _preprocess(self, lhs, rhs): return _basic_equals_any(lhs, rhs) class LineStringPointContains(BinPred): def _preprocess(self, lhs, rhs): intersects = _basic_intersects(lhs, rhs) equals = _basic_equals_any(lhs, rhs) return intersects & ~equals class LineStringLineStringContainsPredicate(BinPred): def _preprocess(self, lhs, rhs): pli = _basic_intersects_pli(lhs, rhs) points = _points_and_lines_to_multipoints(pli[1], pli[0]) # Every point in B must be in the intersection equals = _basic_equals_count(rhs, points) == rhs.sizes return equals """DispatchDict listing the classes to use for each combination of left and right hand side types. """ DispatchDict = { (Point, Point): PointPointContains, (Point, MultiPoint): ImpossiblePredicate, (Point, LineString): ImpossiblePredicate, (Point, Polygon): ImpossiblePredicate, (MultiPoint, Point): NotImplementedPredicate, (MultiPoint, MultiPoint): NotImplementedPredicate, (MultiPoint, LineString): NotImplementedPredicate, (MultiPoint, Polygon): NotImplementedPredicate, (LineString, Point): LineStringPointContains, (LineString, MultiPoint): NotImplementedPredicate, (LineString, LineString): LineStringLineStringContainsPredicate, (LineString, Polygon): ImpossiblePredicate, (Polygon, Point): ContainsPredicate, (Polygon, MultiPoint): ContainsPredicate, (Polygon, LineString): ContainsPredicate, (Polygon, Polygon): ContainsPredicate, }
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binpreds/binpred_interface.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. from typing import TYPE_CHECKING, Tuple from cudf import Series from cuspatial.utils.binpred_utils import _false_series if TYPE_CHECKING: from cuspatial.core.geoseries import GeoSeries class BinPredConfig: """Configuration for a binary predicate. Parameters ---------- align : bool Whether to align the left-hand and right-hand GeoSeries before computing the binary predicate. Defaults to True. allpairs : bool Whether to compute the binary predicate between all pairs of features in the left-hand and right-hand GeoSeries. Defaults to False. Only available with the contains predicate. mode: str The mode to use when computing the binary predicate. Defaults to "full". Only available with the contains predicate and used for internal operations. """ def __init__(self, **kwargs): self.align = kwargs.get("align", True) self.kwargs = kwargs def __repr__(self): return f"BinPredConfig(align={self.align}, kwargs={self.kwargs})" def __str__(self): return self.__repr__() class PreprocessorResult: """Result of a binary predicate preprocessor. The following classes are used to give all implementors of `BinaryItf` a common interface for preprocessor results. Parameters ---------- lhs : GeoSeries The left-hand GeoSeries. rhs : GeoSeries The right-hand GeoSeries. final_rhs : GeoSeries The rhs GeoSeries, if modified by the preprocessor. For example the contains preprocessor converts any complex feature type into a collection of points. point_indices : cudf.Series A cudf.Series of indices that map each point in `points` to its corresponding feature in the right-hand GeoSeries. """ def __init__( self, lhs: "GeoSeries", rhs: "GeoSeries", final_rhs: "GeoSeries" = None, point_indices: Series = None, ): self.lhs = lhs self.rhs = rhs self.final_rhs = final_rhs self.point_indices = point_indices def __repr__(self): return f"PreprocessorResult(lhs={self.lhs}, rhs={self.rhs}, \ points={self.final_rhs}, point_indices={self.point_indices})" def __str__(self): return self.__repr__() class OpResult: """Result of a binary predicate operation.""" pass class ContainsOpResult(OpResult): """Result of a Contains binary predicate operation. Parameters ---------- pip_result : cudf.DataFrame A cudf.DataFrame containing two columns: "polygon_index" and Point_index". The "polygon_index" column contains the index of the polygon that contains each point. The "point_index" column contains the index of each point that is contained by a polygon. intersection_result: Tuple (optional) A tuple containing the result of the intersection operation between the left-hand GeoSeries and the right-hand GeoSeries. Used in .contains_properly. """ def __init__( self, pip_result: Series, preprocessor_result: PreprocessorResult, intersection_result: Tuple = None, ): self.pip_result = pip_result self.preprocessor_result = preprocessor_result self.intersection_result = intersection_result def __repr__(self): return f"OpResult(pip_result={self.pip_result},\n \ preprocessor_result={self.preprocessor_result},\n \ intersection_result={self.intersection_result})\n" def __str__(self): return self.__repr__() class EqualsOpResult(OpResult): """Result of an Equals binary predicate operation. Parameters ---------- result : cudf.Series A cudf.Series of boolean values indicating whether each feature in the right-hand GeoSeries is equal to the point in the left-hand GeoSeries. point_indices: cudf.Series A cudf.Series of indices that map each point in `points` to its corresponding feature in the right-hand GeoSeries. """ def __init__(self, result: Series, point_indices: Series): self.result = result self.point_indices = point_indices def __repr__(self): return f"OpResult(result={self.result}) \ point_indices={self.point_indices}" def __str__(self): return self.__repr__() class IntersectsOpResult(OpResult): """Result of an Intersection binary predicate operation.""" def __init__(self, result: Tuple): self.result = result def __repr__(self): return f"OpResult(result={self.result})" def __str__(self): return self.__repr__() class BinPred: """Base class for binary predicates. This class is an abstract base class and can not be instantiated directly. `BinPred` is the base class that implements this interface in the most general case. Child classes exist for each combination of left-hand and right-hand GeoSeries types and binary predicates. For example, a `PointPointContains` predicate is a child class of `BinPred` that implements the `contains_properly` predicate for two `Point` GeoSeries. These classes are found in the `feature_<predicateName>` files found in this directory. Notes ----- BinPred classes are selected using the appropriate dispatch function. For example, the `contains_properly` predicate is selected using the `CONTAINS_DISPATCH` dispatch function from `binpred_dispatch.py`. The dispatch function selects the appropriate BinPred class based on the left-hand and right-hand GeoSeries types. This enables customized behavior for each combination of left-hand and right-hand GeoSeries types and binary predicates. For example, the `contains_properly` predicate for two `Point` GeoSeries is implemented using a `PointPointContains` BinPred class. The `contains_properly` predicate for a `Point` GeoSeries and a `Polygon` GeoSeries is implemented using a `PointPolygonContains` BinPred class. Most subclasses will be able to use all or 2/3rds of the methods defined in the `RootContains(BinPred) class`. The `RootContains` class implements the `contains_properly` predicate for the most common combination of left-hand and right-hand GeoSeries types. The `RootContains` class can be used as a template for implementing the `contains_properly` predicate for other combinations of left-hand and right-hand GeoSeries types. Examples -------- >>> from cuspatial.core.binpreds.binpred_dispatch import CONTAINS_DISPATCH >>> from cuspatial.core.geoseries import GeoSeries >>> from shapely.geometry import Point, Polygon >>> predicate = CONTAINS_DISPATCH[( ... lhs.column_type, rhs.column_type ... )](align=True, allpairs=False) >>> lhs = GeoSeries([Polygon([(0, 0), (1, 1), (1, 0)])]) >>> rhs = GeoSeries([Point(0, 0), Point(1, 1)]) >>> print(predicate(lhs, rhs)) 0 False dtype: bool """ def __init__(self, **kwargs): """Initialize a binary predicate. Collects any arguments passed to the binary predicate to be used at runtime. This class stores the config object that can be passed to the binary predicate at runtime. The lhs and rhs are set at runtime using the __call__ method so that the same binary predicate can be used for multiple left-hand and right-hand GeoSeries. Parameters ---------- **kwargs Any additional arguments to be used at runtime. Attributes ---------- kwargs : dict Any additional arguments to be used at runtime. Methods ------- __call__(self, lhs, rhs) System call for the binary predicate. Calls the _call method, which is implemented by the subclass. _call(self, lhs, rhs) Call the binary predicate. This method is implemented by the subclass. _preprocess(self, lhs, rhs) Preprocess the left-hand and right-hand GeoSeries. This method is implemented by the subclass. _compute_predicate(self, lhs, rhs) Compute the binary predicate between two GeoSeries. This method is implemented by the subclass. _postprocess(self, lhs, rhs, point_indices, op_result) Postprocess the output GeoSeries to ensure that they are of the correct type for the predicate. This method is implemented by the subclass. Examples -------- >>> from cuspatial.core.binpreds.binpred_dispatch import ( ... CONTAINS_DISPATCH ... ) >>> from cuspatial.core.geoseries import GeoSeries >>> from shapely.geometry import Point, Polygon >>> predicate = CONTAINS_DISPATCH[( ... lhs.column_type, rhs.column_type ... )](align=True, allpairs=False) >>> lhs = GeoSeries([Polygon([(0, 0), (1, 1), (1, 0)])]) >>> rhs = GeoSeries([Point(0, 0), Point(1, 1)]) >>> print(predicate(lhs, rhs)) 0 False dtype: bool """ self.config = BinPredConfig(**kwargs) def __call__(self, lhs: "GeoSeries", rhs: "GeoSeries") -> Series: """System call for the binary predicate. Calls the _call method, which is implemented by the subclass. Executing the binary predicate returns the results of the binary predicate as a GeoSeries. Parameters ---------- lhs : GeoSeries The left-hand GeoSeries. rhs : GeoSeries The right-hand GeoSeries. Returns ------- result : Series The results of the binary predicate. Examples -------- >>> from cuspatial.core.binpreds.binpred_dispatch import ( ... CONTAINS_DISPATCH ... ) >>> from cuspatial.core.geoseries import GeoSeries >>> from shapely.geometry import Point, Polygon >>> predicate = CONTAINS_DISPATCH[( ... lhs.column_type, rhs.column_type ... )](align=True, allpairs=False) >>> lhs = GeoSeries([Polygon([(0, 0), (1, 1), (1, 0)])]) >>> rhs = GeoSeries([Point(0, 0), Point(1, 1)]) >>> print(predicate(lhs, rhs)) 0 False dtype: bool """ return self._call(lhs, rhs) def _call(self, lhs: "GeoSeries", rhs: "GeoSeries") -> Series: """Call the binary predicate. This method is implemented by the subclass. Parameters ---------- lhs : GeoSeries The left-hand GeoSeries. rhs : GeoSeries The right-hand GeoSeries. Returns ------- result : Series A cudf.Series of boolean values indicating whether each feature in the right-hand GeoSeries satisfies the requirements of a binary predicate with its corresponding feature in the left-hand GeoSeries. """ return self._preprocess(lhs, rhs) def _preprocess(self, lhs: "GeoSeries", rhs: "GeoSeries") -> Series: """Preprocess the left-hand and right-hand GeoSeries. This method is implemented by the subclass. Preprocessing is used to ensure that the left-hand and right-hand GeoSeries are of the correct type for each of the three basic predicates: 'contains', 'intersects', and 'equals'. For example, `contains` requires that the left-hand GeoSeries be polygons or multipolygons and the right-hand GeoSeries be points or multipoints. `intersects` requires that the left-hand GeoSeries be linestrings or points and the right-hand GeoSeries be linestrings or points. `equals` requires that the left-hand and right-hand GeoSeries be points. Subclasses that implement `_preprocess` are responsible for calling `_compute_predicate` to continue the execution of the binary predicate. The last line of `_preprocess` as implemented by any subclass should be return self._compute_predicate(lhs, rhs, points, point_indices) Parameters ---------- lhs : GeoSeries The original left-hand GeoSeries. rhs : GeoSeries The original right-hand GeoSeries. Returns ------- result : Series A cudf.Series of boolean values indicating whether each feature in the right-hand GeoSeries satisfies the requirements of a binary predicate with its corresponding feature in the left-hand GeoSeries. """ raise NotImplementedError def _compute_predicate( self, lhs: "GeoSeries", rhs: "GeoSeries", preprocessor_result: PreprocessorResult, ) -> Series: """Compute the binary predicate between two GeoSeries. This method is implemented by the subclass. This method is called by `_preprocess` to continue the execution of the binary predicate. `_compute_predicate` is responsible for calling `_postprocess` to complete the execution of the binary predicate. `compute_predicate` is used to compute the binary predicate, or composition of binary predicates, between two GeoSeries. The left-hand GeoSeries is considered the "base" GeoSeries and the right-hand GeoSeries is considered the "other" GeoSeries. The binary predicate is computed between each feature in the base GeoSeries and the other GeoSeries. The result is a GeoSeries of boolean values indicating whether each feature in the other GeoSeries satisfies the requirements of a binary predicate with its corresponding feature in the base GeoSeries. Subclasses that implement `_compute_predicate` are responsible for calling `_postprocess` to complete the execution of the binary predicate. The last line of `_compute_predicate` should be return self._postprocess( lhs, rhs, OpResult(modified_rhs, point_indices) ) where `modified_rhs` is a GeoSeries of points and `point_indices` is a cudf.Series of indices that map each point in `points` to its corresponding feature in the right-hand GeoSeries. Parameters ---------- lhs : GeoSeries The left-hand GeoSeries. rhs : GeoSeries The right-hand GeoSeries. preprocessor_result : PreprocessorResult The result of the preprocessing step. """ raise NotImplementedError def _postprocess( self, lhs: "GeoSeries", rhs: "GeoSeries", op_result: OpResult, ) -> Series: """Postprocess the output GeoSeries to ensure that they are of the correct return type for the predicate. This method is implemented by the subclass. Postprocessing is used to convert the results of the `_compute_predicate` call into countable values. This step converts the results of one of the three binary predicates `contains`, `intersects`, or `equals` into a `Series` of boolean values. When the `rhs` is a non-point type, `_postprocess` is responsible for aggregating the results of the `_compute_predicate` call into a single boolean value for each feature in the `lhs`. Parameters ---------- lhs : GeoSeries The left-hand GeoSeries. rhs : GeoSeries The right-hand GeoSeries. op_result : cudf.Series The result of the `_compute_predicate` call. Returns ------- result : Series A Series of boolean values indicating whether each feature in the right-hand GeoSeries satisfies the requirements of a binary predicate with its corresponding feature in the left-hand GeoSeries. Notes ----- Arithmetic rules incorporated into `_postprocess` classes: (a, b) -> a contains b iff for all points p in b, p is in a (a, b) -> a intersects b iff for any point p in b, p is in a I'm currently looking into refactoring these arithmetics into a syntax that more closely resembles it. """ raise NotImplementedError class NotImplementedPredicate(BinPred): """A class that is used to raise an error when a binary predicate is not implemented for a given combination of left-hand and right-hand GeoSeries types. This is useful for delineating which binary predicates are implemented for which GeoSeries types in their appropriate `DispatchDict`. """ def __init__(self, *args, **kwargs): raise NotImplementedError class ImpossiblePredicate(BinPred): """There are many combinations that are impossible. This is the base class to simply return a series of False values for these cases. """ def _preprocess(self, lhs, rhs): return _false_series(len(lhs))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binpreds/basic_predicates.py
# Copyright (c) 2023, NVIDIA CORPORATION. import cudf from cuspatial.core.binops.equals_count import pairwise_multipoint_equals_count from cuspatial.utils.binpred_utils import ( _linestrings_from_geometry, _multipoints_from_geometry, _multipoints_is_degenerate, _points_and_lines_to_multipoints, _zero_series, ) def _basic_equals_any(lhs, rhs): """Utility method that returns True if any point in the lhs geometry is equal to a point in the rhs geometry.""" lhs = _multipoints_from_geometry(lhs) rhs = _multipoints_from_geometry(rhs) result = pairwise_multipoint_equals_count(lhs, rhs) return result > 0 def _basic_equals_all(lhs, rhs): """Utility method that returns True if all points in the lhs geometry are equal to points in the rhs geometry.""" lhs = _multipoints_from_geometry(lhs) rhs = _multipoints_from_geometry(rhs) result = pairwise_multipoint_equals_count(lhs, rhs) sizes = ( lhs.multipoints.geometry_offset[1:] - lhs.multipoints.geometry_offset[:-1] ) return result == sizes def _basic_equals_count(lhs, rhs): """Utility method that returns the number of points in the lhs geometry that are equal to a point in the rhs geometry.""" lhs = _multipoints_from_geometry(lhs) rhs = _multipoints_from_geometry(rhs) result = pairwise_multipoint_equals_count(lhs, rhs) return result def _basic_intersects_pli(lhs, rhs): """Utility method that returns the original results of `pairwise_linestring_intersection` (pli).""" from cuspatial.core.binops.intersection import ( pairwise_linestring_intersection, ) lhs = _linestrings_from_geometry(lhs) rhs = _linestrings_from_geometry(rhs) return pairwise_linestring_intersection(lhs, rhs) def _basic_intersects_count(lhs, rhs): """Utility method that returns the number of points in the lhs geometry that intersect with the rhs geometry.""" pli = _basic_intersects_pli(lhs, rhs) if len(pli[1]) == 0: return _zero_series(len(rhs)) intersections = _points_and_lines_to_multipoints(pli[1], pli[0]) sizes = cudf.Series(intersections.sizes) # If the result is degenerate is_degenerate = _multipoints_is_degenerate(intersections) # If all the points in the intersection are in the rhs if len(is_degenerate) > 0: sizes[is_degenerate] = 1 return sizes def _basic_intersects(lhs, rhs): """Utility method that returns True if any point in the lhs geometry intersects with the rhs geometry.""" is_sizes = _basic_intersects_count(lhs, rhs) return is_sizes > 0 def _basic_contains_count(lhs, rhs): """Utility method that returns the number of points in the lhs geometry that are contained_properly in the rhs geometry. """ lhs = lhs rhs = _multipoints_from_geometry(rhs) contains = lhs.contains_properly(rhs, mode="basic_count") return contains def _basic_contains_any(lhs, rhs): """Utility method that returns True if any point in the lhs geometry is contained_properly in the rhs geometry.""" lhs = lhs rhs = _multipoints_from_geometry(rhs) contains = lhs.contains_properly(rhs, mode="basic_any") intersects = _basic_intersects(lhs, rhs) return contains | intersects def _basic_contains_properly_any(lhs, rhs): """Utility method that returns True if any point in the lhs geometry is contained_properly in the rhs geometry.""" lhs = lhs rhs = _multipoints_from_geometry(rhs) contains = lhs.contains_properly(rhs, mode="basic_any") return contains
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binpreds/contains.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. from math import ceil, sqrt import cudf from cudf import DataFrame, Series from cudf.core.column import as_column import cuspatial from cuspatial._lib.pairwise_point_in_polygon import ( pairwise_point_in_polygon as cpp_pairwise_point_in_polygon, ) from cuspatial._lib.point_in_polygon import ( point_in_polygon as cpp_byte_point_in_polygon, ) from cuspatial.utils.join_utils import pip_bitmap_column_to_binary_array def _quadtree_contains_properly(points, polygons): """Compute from a series of points and a series 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). Note that polygons must be closed: the first and last vertex of each polygon must be the same. Parameters ---------- points : GeoSeries A GeoSeries of points. polygons : GeoSeries A GeoSeries of polygons. Returns ------- result : cudf.Series A Series of boolean values indicating whether each point falls within its corresponding polygon. """ # Set the scale to the default minimum scale without triggering a warning. max_depth = 15 min_size = ceil(sqrt(len(points))) if len(polygons) == 0: return Series() x_max = polygons.polygons.x.max() x_min = polygons.polygons.x.min() y_max = polygons.polygons.y.max() y_min = polygons.polygons.y.min() scale = max(x_max - x_min, y_max - y_min) / ((1 << max_depth) + 2) point_indices, quadtree = cuspatial.quadtree_on_points( points, x_min, x_max, y_min, y_max, scale, max_depth, min_size, ) 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 ) polygons_and_points["point_index"] = point_indices.iloc[ polygons_and_points["point_index"] ].reset_index(drop=True) polygons_and_points["part_index"] = polygons_and_points["polygon_index"] polygons_and_points.drop("polygon_index", axis=1, inplace=True) return polygons_and_points def _brute_force_contains_properly(points, polygons): """Compute from a series of points and a series 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). Note that polygons must be closed: the first and last vertex of each polygon must be the same. Parameters ---------- points : GeoSeries A GeoSeries of points. polygons : GeoSeries A GeoSeries of polygons. Returns ------- result : cudf.DataFrame A DataFrame of boolean values indicating whether each point falls within its corresponding polygon. """ pip_result = cpp_byte_point_in_polygon( as_column(points.points.x), as_column(points.points.y), as_column(polygons.polygons.part_offset), as_column(polygons.polygons.ring_offset), as_column(polygons.polygons.x), as_column(polygons.polygons.y), ) result = DataFrame( pip_bitmap_column_to_binary_array( polygon_bitmap_column=pip_result, width=len(polygons.polygons.part_offset) - 1, ) ) final_result = DataFrame._from_data( { name: result[name].astype("bool") for name in reversed(result.columns) } ) final_result.columns = range(len(final_result.columns)) return final_result def _pairwise_contains_properly(points, polygons): """Compute from a series of polygons and an equal-length series of points 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). Note that polygons must be closed: the first and last vertex of each polygon must be the same. Parameters ---------- points : GeoSeries A GeoSeries of points. polygons : GeoSeries A GeoSeries of polygons. Returns ------- result : cudf.DataFrame A DataFrame of boolean values indicating whether each point falls within its corresponding polygon. """ result_column = cpp_pairwise_point_in_polygon( as_column(points.points.x), as_column(points.points.y), as_column(polygons.polygons.part_offset), as_column(polygons.polygons.ring_offset), as_column(polygons.polygons.x), as_column(polygons.polygons.y), ) # Pairwise returns a boolean column with a True value for each (polygon, # point) pair where the point is contained properly by the polygon. We can # use this to create a dataframe with only (polygon, point) pairs that # satisfy the relationship. pip_result = cudf.Series(result_column, dtype="bool") trues = pip_result[pip_result].index true_pairs = cudf.DataFrame( { "pairwise_index": trues, "point_index": trues, "result": True, } ) return true_pairs def contains_properly(polygons, points, mode="pairwise"): if mode == "quadtree": return _quadtree_contains_properly(points, polygons) elif mode == "pairwise": return _pairwise_contains_properly(points, polygons) else: # Use stack to convert the result to the same shape as quadtree's # result, name the columns appropriately, and return the # two-column DataFrame. bitmask_result = _brute_force_contains_properly(points, polygons) bitmask_result_df = bitmask_result.stack().reset_index() trues = bitmask_result_df[bitmask_result_df[0]] trues.columns = ["point_index", "part_index", "result"] return trues
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/_column/geometa.py
# Copyright (c) 2021-2022 NVIDIA CORPORATION # This allows GeoMeta as its own init type from __future__ import annotations from enum import Enum from typing import Union import cudf # This causes arrow to encode NONE as =255, which I'll accept now # in order to keep the rest of the enums the same. class Feature_Enum(Enum): NONE = -1 POINT = 0 MULTIPOINT = 1 LINESTRING = 2 POLYGON = 3 class GeoMeta: """ Creates input_types and union_offsets for GeoColumns that are created using native GeoArrowBuffers. These will be used to convert to GeoPandas GeoSeries if necessary. """ def __init__(self, meta: Union[GeoMeta, dict]): if isinstance(meta, dict): self.input_types = cudf.Series(meta["input_types"], dtype="int8") self.union_offsets = cudf.Series( meta["union_offsets"], dtype="int32" ) else: self.input_types = cudf.Series(meta.input_types, dtype="int8") self.union_offsets = cudf.Series(meta.union_offsets, dtype="int32") def copy(self): return self.__class__( { "input_types": self.input_types.copy(), "union_offsets": self.union_offsets.copy(), } )
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/_column/__init__.py
# Copyright (c) 2022, NVIDIA CORPORATION
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/_column/geocolumn.py
# Copyright (c) 2021-2023 NVIDIA CORPORATION from enum import Enum from functools import cached_property from typing import Tuple, TypeVar import cupy as cp import pyarrow as pa import cudf from cudf.core.column import ColumnBase, arange, as_column, build_list_column from cuspatial.core._column.geometa import Feature_Enum, GeoMeta from cuspatial.utils.column_utils import empty_geometry_column class ColumnType(Enum): MIXED = 0 POINT = 1 MULTIPOINT = 2 LINESTRING = 3 POLYGON = 4 T = TypeVar("T", bound="GeoColumn") class GeoColumn(ColumnBase): """ Parameters ---------- data : A tuple of four cudf.Series of list dtype meta : A GeoMeta object (optional) Notes ----- The GeoColumn class subclasses `NumericalColumn`. Combined with `_copy_type_metadata`, this assures support for sort, groupby, and potential other `cudf` algorithms. """ def __init__( self, data: Tuple, meta: GeoMeta = None, shuffle_order: cudf.Index = None, ): if ( isinstance(data[0], cudf.Series) and isinstance(data[1], cudf.Series) and isinstance(data[2], cudf.Series) and isinstance(data[3], cudf.Series) ): self._meta = GeoMeta(meta) self.points = data[0] self.points.name = "points" self.mpoints = data[1] self.mpoints.name = "mpoints" self.lines = data[2] self.lines.name = "lines" self.polygons = data[3] self.polygons.name = "polygons" else: raise TypeError("All four Tuple arguments must be cudf.ListSeries") super().__init__(None, size=len(self), dtype="geometry") def to_arrow(self): return pa.UnionArray.from_dense( self._meta.input_types.to_arrow(), self._meta.union_offsets.to_arrow(), [ self.points.to_arrow(), self.mpoints.to_arrow(), self.lines.to_arrow(), self.polygons.to_arrow(), ], ) def __len__(self): """ Returns the number of unique geometries stored in this GeoColumn. """ return len(self._meta.input_types) def _dump(self): return ( f"POINTS\n" f"{self.points._repr__()}\n" f"MULTIPOINTS\n" f"{self.multipoints._repr__()}\n" f"LINES\n" f"{self.lines._repr__()}\n" f"POLYGONS\n" f"{self.polygons._repr__()}\n" ) def copy(self, deep=True): """ Create a copy of all of the GPU-backed data structures in this GeoColumn. """ result = GeoColumn( ( self.points.copy(deep), self.mpoints.copy(deep), self.lines.copy(deep), self.polygons.copy(deep), ), self._meta.copy(), ) return result @property def valid_count(self) -> int: """ Arrow's UnionArray does not support nulls, so this is always equal to the length of the GeoColumn. """ return self._meta.input_types.valid_count def has_nulls(self) -> bool: """ Arrow's UnionArray does not support nulls, so this is always False. """ return self._meta.input_types.has_nulls @classmethod def _from_points_xy(cls, points_xy: ColumnBase): """ Create a GeoColumn of only single points from a cudf Series with interleaved xy coordinates. """ if not points_xy.dtype.kind == "f": raise ValueError("Coordinates must be floating point numbers.") point_col = _xy_as_variable_sized_list(points_xy) num_points = len(point_col) meta = GeoMeta( { "input_types": as_column( cp.full( num_points, Feature_Enum.POINT.value, dtype=cp.int8 ) ), "union_offsets": as_column( cp.arange(num_points, dtype=cp.int32) ), } ) coord_dtype = points_xy.dtype return cls( ( cudf.Series(point_col), cudf.Series( empty_geometry_column(Feature_Enum.MULTIPOINT, coord_dtype) ), cudf.Series( empty_geometry_column(Feature_Enum.LINESTRING, coord_dtype) ), cudf.Series( empty_geometry_column(Feature_Enum.POLYGON, coord_dtype) ), ), meta, ) @classmethod def _from_multipoints_xy( cls, multipoints_xy: ColumnBase, geometry_offsets: ColumnBase ): """ Create a GeoColumn of multipoints from a cudf Series with interleaved xy coordinates. """ if not multipoints_xy.dtype.kind == "f": raise ValueError("Coordinates must be floating point numbers.") multipoint_col = build_list_column( indices=geometry_offsets, elements=_xy_as_variable_sized_list(multipoints_xy), size=len(geometry_offsets) - 1, ) num_multipoints = len(multipoint_col) meta = GeoMeta( { "input_types": as_column( cp.full( num_multipoints, Feature_Enum.MULTIPOINT.value, dtype=cp.int8, ) ), "union_offsets": as_column( cp.arange(num_multipoints, dtype=cp.int32) ), } ) coord_dtype = multipoints_xy.dtype return cls( ( cudf.Series( empty_geometry_column(Feature_Enum.POINT, coord_dtype) ), cudf.Series(multipoint_col), cudf.Series( empty_geometry_column(Feature_Enum.LINESTRING, coord_dtype) ), cudf.Series( empty_geometry_column(Feature_Enum.POLYGON, coord_dtype) ), ), meta, ) @classmethod def _from_linestrings_xy( cls, linestrings_xy: ColumnBase, part_offsets: ColumnBase, geometry_offsets: ColumnBase, ): """ Create a GeoColumn of multilinestrings from a cudf Series with interleaved xy coordinates. """ if not linestrings_xy.dtype.kind == "f": raise ValueError("Coordinates must be floating point numbers.") parts_col = build_list_column( indices=part_offsets, elements=_xy_as_variable_sized_list(linestrings_xy), size=len(part_offsets) - 1, ) linestrings_col = build_list_column( indices=geometry_offsets, elements=parts_col, size=len(geometry_offsets) - 1, ) num_linestrings = len(linestrings_col) meta = GeoMeta( { "input_types": as_column( cp.full( num_linestrings, Feature_Enum.LINESTRING.value, dtype=cp.int8, ) ), "union_offsets": as_column( cp.arange(num_linestrings, dtype=cp.int32) ), } ) coord_dtype = linestrings_xy.dtype return cls( ( cudf.Series( empty_geometry_column(Feature_Enum.POINT, coord_dtype) ), cudf.Series( empty_geometry_column(Feature_Enum.MULTIPOINT, coord_dtype) ), cudf.Series(linestrings_col), cudf.Series( empty_geometry_column(Feature_Enum.POLYGON, coord_dtype) ), ), meta, ) @classmethod def _from_polygons_xy( cls, polygons_xy: ColumnBase, ring_offsets: ColumnBase, part_offsets: ColumnBase, geometry_offsets: ColumnBase, ): """ Create a GeoColumn of multipolygons from a cudf Series with interleaved xy coordinates. """ if not polygons_xy.dtype.kind == "f": raise ValueError("Coordinates must be floating point numbers.") rings_col = build_list_column( indices=ring_offsets, elements=_xy_as_variable_sized_list(polygons_xy), size=len(ring_offsets) - 1, ) parts_col = build_list_column( indices=part_offsets, elements=rings_col, size=len(part_offsets) - 1, ) polygons_col = build_list_column( indices=geometry_offsets, elements=parts_col, size=len(geometry_offsets) - 1, ) num_polygons = len(polygons_col) meta = GeoMeta( { "input_types": as_column( cp.full( num_polygons, Feature_Enum.POLYGON.value, dtype=cp.int8, ) ), "union_offsets": as_column( cp.arange(num_polygons, dtype=cp.int32) ), } ) coord_dtype = polygons_xy.dtype return cls( ( cudf.Series( empty_geometry_column(Feature_Enum.POINT, coord_dtype) ), cudf.Series( empty_geometry_column(Feature_Enum.MULTIPOINT, coord_dtype) ), cudf.Series( empty_geometry_column(Feature_Enum.LINESTRING, coord_dtype) ), cudf.Series(polygons_col), ), meta, ) @cached_property def memory_usage(self) -> int: """ Outputs how much memory is used by the underlying geometries. """ final_size = self._meta.input_types.memory_usage() final_size = final_size + self._meta.union_offsets.memory_usage() final_size = final_size + self.points._column.memory_usage final_size = final_size + self.mpoints._column.memory_usage final_size = final_size + self.lines._column.memory_usage final_size = final_size + self.polygons._column.memory_usage return final_size def _xy_as_variable_sized_list(xy: ColumnBase): """Given an array of interleaved x-y coordinate, construct a cuDF ListDtype type array, where each row is the coordinate. """ if len(xy) % 2 != 0: raise ValueError("xy must have an even number of elements") num_points = len(xy) // 2 indices = arange(0, num_points * 2 + 1, 2, dtype="int32") return build_list_column(indices=indices, elements=xy, size=num_points)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binops/intersection.py
# Copyright (c) 2023, NVIDIA CORPORATION. from typing import TYPE_CHECKING import cudf from cudf.core.column import arange, build_list_column from cuspatial._lib.intersection import ( pairwise_linestring_intersection as c_pairwise_linestring_intersection, ) from cuspatial.core._column.geocolumn import GeoColumn from cuspatial.core._column.geometa import Feature_Enum, GeoMeta from cuspatial.utils.column_utils import ( contains_only_linestrings, empty_geometry_column, ) if TYPE_CHECKING: from cuspatial.core.geoseries import GeoSeries def pairwise_linestring_intersection( linestrings1: "GeoSeries", linestrings2: "GeoSeries" ): """ Compute the intersection of two GeoSeries of linestrings. Note ---- The result contains an index list and a GeoSeries and is interpreted as `List<Union>`. This is a temporary workaround until cuDF supports union column. Parameters ---------- linestrings1 : GeoSeries A GeoSeries of linestrings. linestrings2 : GeoSeries A GeoSeries of linestrings. Returns ------- Tuple[cudf.Series, GeoSeries, DataFrame] A tuple of three elements: - An integral cuDF series of offsets to each intersection result in the GeoSeries. - A Geoseries of the results of the intersection. - A DataFrame of the ids of the linestrings and segments that the intersection results came from. """ from cuspatial.core.geoseries import GeoSeries if len(linestrings1) == 0 and len(linestrings2) == 0: return ( cudf.Series([0]), GeoSeries([]), cudf.DataFrame( { "lhs_linestring_id": [], "lhs_segment_id": [], "rhs_linestring_id": [], "rhs_segment_id": [], } ), ) if any( not contains_only_linestrings(s) for s in [linestrings1, linestrings2] ): raise ValueError("Input GeoSeries must contain only linestrings.") geoms, look_back_ids = c_pairwise_linestring_intersection( linestrings1.lines.column(), linestrings2.lines.column() ) ( geometry_collection_offset, types_buffer, offset_buffer, points, segments, ) = geoms # Organize the look back ids into list column (lhs_linestring_id, lhs_segment_id, rhs_linestring_id, rhs_segment_id,) = [ build_list_column( indices=geometry_collection_offset, elements=id_, size=len(geometry_collection_offset) - 1, ) for id_ in look_back_ids ] linestring_column = build_list_column( indices=arange(0, len(segments) + 1, dtype="int32"), elements=segments, size=len(segments), ) coord_dtype = points.dtype.leaf_type meta = GeoMeta( {"input_types": types_buffer, "union_offsets": offset_buffer} ) from cuspatial.core.geoseries import GeoSeries geometries = GeoSeries( GeoColumn( ( cudf.Series(points), cudf.Series( empty_geometry_column(Feature_Enum.MULTIPOINT, coord_dtype) ), cudf.Series(linestring_column), cudf.Series( empty_geometry_column(Feature_Enum.POLYGON, coord_dtype) ), ), meta, ) ) ids = cudf.DataFrame( { "lhs_linestring_id": lhs_linestring_id, "lhs_segment_id": lhs_segment_id, "rhs_linestring_id": rhs_linestring_id, "rhs_segment_id": rhs_segment_id, } ) return geometry_collection_offset, geometries, ids
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binops/distance_dispatch.py
import cudf from cudf.core.column import arange, full from cuspatial._lib.distance import ( pairwise_linestring_distance, pairwise_linestring_polygon_distance, pairwise_point_distance, pairwise_point_linestring_distance, pairwise_point_polygon_distance, pairwise_polygon_distance, ) from cuspatial._lib.types import CollectionType from cuspatial.core._column.geometa import Feature_Enum from cuspatial.utils.column_utils import ( contains_only_linestrings, contains_only_multipoints, contains_only_points, contains_only_polygons, ) # Maps from type combinations to a tuple of (function, reverse, # point_collection_types). # # If reverse is True, the arguments need to be swapped. # Due to the way the functions are written, certain combinations of types # requires that the arguments be swapped. For example, # `point_linestring_distance` requires that the first argument be a point and # the second argument be a linestring. In this case, when lhs is a linestring # and rhs is a point, the arguments need to be swapped. The results holds true # thanks to that cartesian distance is symmetric. # # `point_collection_types` is a tuple of the types of the point column type. # For example, if the first argument is a `MultiPoint` and the second is a # `Point`, then the `point_collection_types` is (`CollectionType.MULTI`, # `CollectionType.SINGLE`). They are only needed for point/multipoint columns, # because the cython APIs are designed to handle both point and multipoint # columns based on their collection types. type_to_func = { (Feature_Enum.POINT, Feature_Enum.POINT): ( pairwise_point_distance, False, (CollectionType.SINGLE, CollectionType.SINGLE), ), (Feature_Enum.POINT, Feature_Enum.MULTIPOINT): ( pairwise_point_distance, False, (CollectionType.SINGLE, CollectionType.MULTI), ), (Feature_Enum.POINT, Feature_Enum.LINESTRING): ( pairwise_point_linestring_distance, False, (CollectionType.SINGLE,), ), (Feature_Enum.POINT, Feature_Enum.POLYGON): ( pairwise_point_polygon_distance, False, (CollectionType.SINGLE,), ), (Feature_Enum.LINESTRING, Feature_Enum.POINT): ( pairwise_point_linestring_distance, True, (CollectionType.SINGLE,), ), (Feature_Enum.LINESTRING, Feature_Enum.MULTIPOINT): ( pairwise_point_linestring_distance, True, (CollectionType.MULTI,), ), (Feature_Enum.LINESTRING, Feature_Enum.LINESTRING): ( pairwise_linestring_distance, False, (), ), (Feature_Enum.LINESTRING, Feature_Enum.POLYGON): ( pairwise_linestring_polygon_distance, False, (), ), (Feature_Enum.POLYGON, Feature_Enum.POINT): ( pairwise_point_polygon_distance, True, (CollectionType.SINGLE,), ), (Feature_Enum.POLYGON, Feature_Enum.MULTIPOINT): ( pairwise_point_polygon_distance, True, (CollectionType.MULTI,), ), (Feature_Enum.POLYGON, Feature_Enum.LINESTRING): ( pairwise_linestring_polygon_distance, True, (), ), (Feature_Enum.POLYGON, Feature_Enum.POLYGON): ( pairwise_polygon_distance, False, (), ), (Feature_Enum.MULTIPOINT, Feature_Enum.POINT): ( pairwise_point_distance, False, (CollectionType.MULTI, CollectionType.SINGLE), ), (Feature_Enum.MULTIPOINT, Feature_Enum.MULTIPOINT): ( pairwise_point_distance, False, (CollectionType.MULTI, CollectionType.MULTI), ), (Feature_Enum.MULTIPOINT, Feature_Enum.LINESTRING): ( pairwise_point_linestring_distance, False, (CollectionType.MULTI,), ), (Feature_Enum.MULTIPOINT, Feature_Enum.POLYGON): ( pairwise_point_polygon_distance, False, (CollectionType.MULTI,), ), } class DistanceDispatch: """Dispatches distance operations between two GeoSeries""" def __init__(self, lhs, rhs, align): if align: self._lhs, self._rhs = lhs.align(rhs) else: self._lhs, self._rhs = lhs, rhs self._align = align self._res_index = lhs.index self._non_null_mask = self._lhs.notna() & self._rhs.notna() self._lhs = self._lhs[self._non_null_mask] self._rhs = self._rhs[self._non_null_mask] # TODO: This test is expensive, so would be nice if we can cache it self._lhs_type = self._determine_series_type(self._lhs) self._rhs_type = self._determine_series_type(self._rhs) def _determine_series_type(self, s): """Check single geometry type of `s`.""" if contains_only_multipoints(s): typ = Feature_Enum.MULTIPOINT elif contains_only_points(s): typ = Feature_Enum.POINT elif contains_only_linestrings(s): typ = Feature_Enum.LINESTRING elif contains_only_polygons(s): typ = Feature_Enum.POLYGON else: raise NotImplementedError( "Geoseries with mixed geometry types are not supported" ) return typ def _column(self, s, typ): """Get column of `s` based on `typ`.""" if typ == Feature_Enum.POINT: return s.points.column() elif typ == Feature_Enum.MULTIPOINT: return s.multipoints.column() elif typ == Feature_Enum.LINESTRING: return s.lines.column() elif typ == Feature_Enum.POLYGON: return s.polygons.column() @property def _lhs_column(self): return self._column(self._lhs, self._lhs_type) @property def _rhs_column(self): return self._column(self._rhs, self._rhs_type) def __call__(self): func, reverse, collection_types = type_to_func[ (self._lhs_type, self._rhs_type) ] if reverse: dist = func(*collection_types, self._rhs_column, self._lhs_column) else: dist = func(*collection_types, self._lhs_column, self._rhs_column) # Rows with misaligned indices contains nan. Here we scatter the # distance values to the correct indices. result = full( len(self._res_index), float("nan"), dtype="float64", ) scatter_map = arange( len(self._res_index), dtype="int32" ).apply_boolean_mask(self._non_null_mask) result[scatter_map] = dist # If `align==False`, geopandas preserves lhs index. index = None if self._align else self._res_index return cudf.Series(result, index=index, nan_as_null=False)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/core/binops/equals_count.py
# Copyright (c) 2023, NVIDIA CORPORATION. import cudf from cuspatial._lib.pairwise_multipoint_equals_count import ( pairwise_multipoint_equals_count as c_pairwise_multipoint_equals_count, ) from cuspatial.utils.column_utils import contains_only_multipoints def pairwise_multipoint_equals_count(lhs, rhs): """Compute the number of points in each multipoint in the lhs that exist in the corresponding multipoint in the rhs. For each point in a multipoint in the lhs, search the corresponding multipoint in the rhs for a point that is equal to the point in the lhs. If a point is found, increment the count for that multipoint in the lhs. Parameters ---------- lhs : GeoSeries A GeoSeries of multipoints. rhs : GeoSeries A GeoSeries of multipoints. Examples -------- >>> import cuspatial >>> from shapely.geometry import MultiPoint >>> p1 = cuspatial.GeoSeries([MultiPoint([Point(0, 0)])]) >>> p2 = cuspatial.GeoSeries([MultiPoint([Point(0, 0)])]) >>> cuspatial.pairwise_multipoint_equals_count(p1, p2) 0 1 dtype: uint32 >>> p1 = cuspatial.GeoSeries([MultiPoint([Point(0, 0)])]) >>> p2 = cuspatial.GeoSeries([MultiPoint([Point(1, 1)])]) >>> cuspatial.pairwise_multipoint_equals_count(p1, p2) 0 0 dtype: uint32 >>> 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)]), ... ] ... ) >>> cuspatial.pairwise_multipoint_equals_count(p1, p2) 0 1 1 0 2 1 dtype: uint32 Returns ------- count : cudf.Series A Series of the number of points in each multipoint in the lhs that are equal to points in the corresponding multipoint in the rhs. """ if len(lhs) == 0: return cudf.Series([]) if any(not contains_only_multipoints(s) for s in [lhs, rhs]): raise ValueError("Input GeoSeries must contain only multipoints.") lhs_column = lhs._column.mpoints._column rhs_column = rhs._column.mpoints._column result = c_pairwise_multipoint_equals_count(lhs_column, rhs_column) return cudf.Series(result)
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/distance.pyx
# Copyright (c) 2022-2023, NVIDIA CORPORATION. from libcpp.memory cimport make_shared, shared_ptr, unique_ptr from libcpp.utility cimport move, pair from cudf._lib.column cimport Column from cudf._lib.cpp.column.column cimport column from cudf._lib.cpp.column.column_view cimport column_view from cudf._lib.cpp.table.table_view cimport table_view from cudf._lib.utils cimport columns_from_table_view from cuspatial._lib.cpp.column.geometry_column_view cimport ( geometry_column_view, ) from cuspatial._lib.cpp.distance cimport ( directed_hausdorff_distance as directed_cpp_hausdorff_distance, haversine_distance as cpp_haversine_distance, pairwise_linestring_distance as c_pairwise_linestring_distance, pairwise_linestring_polygon_distance as c_pairwise_line_poly_dist, pairwise_point_distance as c_pairwise_point_distance, pairwise_point_linestring_distance as c_pairwise_point_linestring_distance, pairwise_point_polygon_distance as c_pairwise_point_polygon_distance, pairwise_polygon_distance as c_pairwise_polygon_distance, ) from cuspatial._lib.cpp.types cimport collection_type_id, geometry_type_id from cuspatial._lib.types cimport collection_type_py_to_c cpdef haversine_distance(Column x1, Column y1, Column x2, Column y2): cdef column_view c_x1 = x1.view() cdef column_view c_y1 = y1.view() cdef column_view c_x2 = x2.view() cdef column_view c_y2 = y2.view() cdef unique_ptr[column] c_result with nogil: c_result = move(cpp_haversine_distance(c_x1, c_y1, c_x2, c_y2)) return Column.from_unique_ptr(move(c_result)) def directed_hausdorff_distance( Column xs, Column ys, Column space_offsets, ): cdef column_view c_xs = xs.view() cdef column_view c_ys = ys.view() cdef column_view c_shape_offsets = space_offsets.view() cdef pair[unique_ptr[column], table_view] result with nogil: result = move( directed_cpp_hausdorff_distance( c_xs, c_ys, c_shape_offsets, ) ) owner = Column.from_unique_ptr(move(result.first), data_ptr_exposed=True) return columns_from_table_view( result.second, owners=[owner] * result.second.num_columns() ) def pairwise_point_distance( lhs_point_collection_type, rhs_point_collection_type, Column points1, Column points2, ): cdef collection_type_id lhs_point_multi_type = collection_type_py_to_c( lhs_point_collection_type ) cdef collection_type_id rhs_point_multi_type = collection_type_py_to_c( rhs_point_collection_type ) cdef shared_ptr[geometry_column_view] c_multipoints_lhs = \ make_shared[geometry_column_view]( points1.view(), lhs_point_multi_type, geometry_type_id.POINT) cdef shared_ptr[geometry_column_view] c_multipoints_rhs = \ make_shared[geometry_column_view]( points2.view(), rhs_point_multi_type, geometry_type_id.POINT) cdef unique_ptr[column] c_result with nogil: c_result = move(c_pairwise_point_distance( c_multipoints_lhs.get()[0], c_multipoints_rhs.get()[0], )) return Column.from_unique_ptr(move(c_result)) def pairwise_linestring_distance( Column multilinestrings1, Column multilinestrings2 ): cdef shared_ptr[geometry_column_view] c_multilinestring_lhs = \ make_shared[geometry_column_view]( multilinestrings1.view(), collection_type_id.MULTI, geometry_type_id.LINESTRING) cdef shared_ptr[geometry_column_view] c_multilinestring_rhs = \ make_shared[geometry_column_view]( multilinestrings2.view(), collection_type_id.MULTI, geometry_type_id.LINESTRING) cdef unique_ptr[column] c_result with nogil: c_result = move(c_pairwise_linestring_distance( c_multilinestring_lhs.get()[0], c_multilinestring_rhs.get()[0], )) return Column.from_unique_ptr(move(c_result)) def pairwise_point_linestring_distance( point_collection_type, Column points, Column linestrings, ): cdef collection_type_id points_multi_type = collection_type_py_to_c( point_collection_type ) cdef shared_ptr[geometry_column_view] c_points = \ make_shared[geometry_column_view]( points.view(), points_multi_type, geometry_type_id.POINT) cdef shared_ptr[geometry_column_view] c_multilinestrings = \ make_shared[geometry_column_view]( linestrings.view(), collection_type_id.MULTI, geometry_type_id.LINESTRING) cdef unique_ptr[column] c_result with nogil: c_result = move(c_pairwise_point_linestring_distance( c_points.get()[0], c_multilinestrings.get()[0], )) return Column.from_unique_ptr(move(c_result)) def pairwise_point_polygon_distance( point_collection_type, Column multipoints, Column multipolygons ): cdef collection_type_id points_multi_type = collection_type_py_to_c( point_collection_type ) cdef shared_ptr[geometry_column_view] c_multipoints = \ make_shared[geometry_column_view]( multipoints.view(), points_multi_type, geometry_type_id.POINT) cdef shared_ptr[geometry_column_view] c_multipolygons = \ make_shared[geometry_column_view]( multipolygons.view(), collection_type_id.MULTI, geometry_type_id.POLYGON) cdef unique_ptr[column] c_result with nogil: c_result = move(c_pairwise_point_polygon_distance( c_multipoints.get()[0], c_multipolygons.get()[0] )) return Column.from_unique_ptr(move(c_result)) def pairwise_linestring_polygon_distance( Column multilinestrings, Column multipolygons ): cdef shared_ptr[geometry_column_view] c_multilinestrings = \ make_shared[geometry_column_view]( multilinestrings.view(), collection_type_id.MULTI, geometry_type_id.LINESTRING) cdef shared_ptr[geometry_column_view] c_multipolygons = \ make_shared[geometry_column_view]( multipolygons.view(), collection_type_id.MULTI, geometry_type_id.POLYGON) cdef unique_ptr[column] c_result with nogil: c_result = move(c_pairwise_line_poly_dist( c_multilinestrings.get()[0], c_multipolygons.get()[0] )) return Column.from_unique_ptr(move(c_result)) def pairwise_polygon_distance(Column lhs, Column rhs): cdef shared_ptr[geometry_column_view] c_lhs = \ make_shared[geometry_column_view]( lhs.view(), collection_type_id.MULTI, geometry_type_id.POLYGON) cdef shared_ptr[geometry_column_view] c_rhs = \ make_shared[geometry_column_view]( rhs.view(), collection_type_id.MULTI, geometry_type_id.POLYGON) cdef unique_ptr[column] c_result with nogil: c_result = move(c_pairwise_polygon_distance( c_lhs.get()[0], c_rhs.get()[0] )) return Column.from_unique_ptr(move(c_result))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/point_in_polygon.pyx
# Copyright (c) 2020, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from libcpp.utility cimport move from cudf._lib.column cimport Column, column, column_view from cuspatial._lib.cpp.point_in_polygon cimport ( point_in_polygon as cpp_point_in_polygon, ) def point_in_polygon( Column test_points_x, Column test_points_y, Column poly_offsets, Column poly_ring_offsets, Column poly_points_x, Column poly_points_y ): cdef column_view c_test_points_x = test_points_x.view() cdef column_view c_test_points_y = test_points_y.view() cdef column_view c_poly_offsets = poly_offsets.view() cdef column_view c_poly_ring_offsets = poly_ring_offsets.view() cdef column_view c_poly_points_x = poly_points_x.view() cdef column_view c_poly_points_y = poly_points_y.view() cdef unique_ptr[column] result with nogil: result = move( cpp_point_in_polygon( c_test_points_x, c_test_points_y, c_poly_offsets, c_poly_ring_offsets, c_poly_points_x, c_poly_points_y ) ) return Column.from_unique_ptr(move(result))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/utils.pxd
# Copyright (c) 2022, NVIDIA CORPORATION. from cudf._lib.cpp.column.column_view cimport column_view from cuspatial._lib.cpp.optional cimport nullopt, optional cdef optional[column_view] unwrap_pyoptcol(object pyoptcol) except*
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/types.pxd
# Copyright (c) 2023, NVIDIA CORPORATION. from libc.stdint cimport uint8_t from cuspatial._lib.cpp.types cimport collection_type_id, geometry_type_id ctypedef uint8_t underlying_geometry_type_id_t ctypedef uint8_t underlying_collection_type_id_t cdef geometry_type_id geometry_type_py_to_c(typ) except* cdef collection_type_id collection_type_py_to_c(typ) except*
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/pairwise_point_in_polygon.pyx
# Copyright (c) 2022, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from libcpp.utility cimport move from cudf._lib.column cimport Column, column, column_view from cuspatial._lib.cpp.pairwise_point_in_polygon cimport ( pairwise_point_in_polygon as cpp_pairwise_point_in_polygon, ) def pairwise_point_in_polygon( Column test_points_x, Column test_points_y, Column poly_offsets, Column poly_ring_offsets, Column poly_points_x, Column poly_points_y ): cdef column_view c_test_points_x = test_points_x.view() cdef column_view c_test_points_y = test_points_y.view() cdef column_view c_poly_offsets = poly_offsets.view() cdef column_view c_poly_ring_offsets = poly_ring_offsets.view() cdef column_view c_poly_points_x = poly_points_x.view() cdef column_view c_poly_points_y = poly_points_y.view() cdef unique_ptr[column] result with nogil: result = move( cpp_pairwise_point_in_polygon( c_test_points_x, c_test_points_y, c_poly_offsets, c_poly_ring_offsets, c_poly_points_x, c_poly_points_y ) ) return Column.from_unique_ptr(move(result))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/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. # ============================================================================= set(cython_sources distance.pyx intersection.pyx nearest_points.pyx point_in_polygon.pyx points_in_range.pyx pairwise_multipoint_equals_count.pyx pairwise_point_in_polygon.pyx polygon_bounding_boxes.pyx linestring_bounding_boxes.pyx quadtree.pyx spatial.pyx spatial_join.pyx trajectory.pyx types.pyx utils.pyx ) set(linked_libraries cuspatial::cuspatial) rapids_cython_create_modules( CXX ASSOCIATED_TARGETS cuspatial SOURCE_FILES "${cython_sources}" LINKED_LIBRARIES "${linked_libraries}" )
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/types.pyx
# Copyright (c) 2022, NVIDIA CORPORATION. from enum import IntEnum from cuspatial._lib.cpp.types cimport collection_type_id, geometry_type_id from cuspatial._lib.types cimport ( underlying_collection_type_id_t, underlying_geometry_type_id_t, ) class GeometryType(IntEnum): POINT = ( <underlying_geometry_type_id_t> geometry_type_id.POINT ) LINESTRING = ( <underlying_geometry_type_id_t> geometry_type_id.LINESTRING ) POLYGON = ( <underlying_geometry_type_id_t> geometry_type_id.POLYGON ) class CollectionType(IntEnum): SINGLE = ( <underlying_collection_type_id_t> collection_type_id.SINGLE ) MULTI = ( <underlying_collection_type_id_t> collection_type_id.MULTI ) cdef geometry_type_id geometry_type_py_to_c(typ : GeometryType): return <geometry_type_id>(<underlying_collection_type_id_t> (typ.value)) cdef collection_type_id collection_type_py_to_c(typ : CollectionType): return <collection_type_id>(<underlying_collection_type_id_t> (typ.value))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/intersection.pyx
# Copyright (c) 2023, NVIDIA CORPORATION. from libcpp.memory cimport make_shared, shared_ptr from libcpp.utility cimport move from cudf._lib.column cimport Column from cuspatial._lib.types import CollectionType, GeometryType from cuspatial._lib.cpp.column.geometry_column_view cimport ( geometry_column_view, ) from cuspatial._lib.cpp.linestring_intersection cimport ( linestring_intersection_column_result, pairwise_linestring_intersection as cpp_pairwise_linestring_intersection, ) from cuspatial._lib.cpp.types cimport collection_type_id, geometry_type_id from cuspatial._lib.types cimport ( underlying_collection_type_id_t, underlying_geometry_type_id_t, ) def pairwise_linestring_intersection(Column lhs, Column rhs): """ Compute the intersection of two (multi)linestrings. """ from cuspatial.core._column.geometa import Feature_Enum cdef linestring_intersection_column_result c_result cdef collection_type_id multi_type = <collection_type_id>( <underlying_collection_type_id_t>(CollectionType.MULTI.value) ) cdef geometry_type_id linestring_type = <geometry_type_id>( <underlying_geometry_type_id_t>(GeometryType.LINESTRING.value) ) cdef shared_ptr[geometry_column_view] c_lhs = \ make_shared[geometry_column_view]( lhs.view(), multi_type, linestring_type) cdef shared_ptr[geometry_column_view] c_rhs = \ make_shared[geometry_column_view]( rhs.view(), multi_type, linestring_type) with nogil: c_result = move(cpp_pairwise_linestring_intersection( c_lhs.get()[0], c_rhs.get()[0] )) geometry_collection_offset = Column.from_unique_ptr( move(c_result.geometry_collection_offset) ) types_buffer = Column.from_unique_ptr(move(c_result.types_buffer)) offset_buffer = Column.from_unique_ptr(move(c_result.offset_buffer)) points = Column.from_unique_ptr(move(c_result.points)) segments = Column.from_unique_ptr(move(c_result.segments)) lhs_linestring_id = Column.from_unique_ptr( move(c_result.lhs_linestring_id) ) lhs_segment_id = Column.from_unique_ptr(move(c_result.lhs_segment_id)) rhs_linestring_id = Column.from_unique_ptr( move(c_result.rhs_linestring_id) ) rhs_segment_id = Column.from_unique_ptr(move(c_result.rhs_segment_id)) # Map linestring type codes from libcuspatial to cuspatial types_buffer[types_buffer == GeometryType.LINESTRING.value] = ( Feature_Enum.LINESTRING.value ) return ((geometry_collection_offset, types_buffer, offset_buffer, points, segments), (lhs_linestring_id, lhs_segment_id, rhs_linestring_id, rhs_segment_id))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/trajectory.pyx
# Copyright (c) 2019-2020, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from libcpp.pair cimport pair from libcpp.utility cimport move from cudf._lib.column cimport Column from cudf._lib.cpp.column.column cimport column from cudf._lib.cpp.column.column_view cimport column_view from cudf._lib.cpp.table.table cimport table from cudf._lib.cpp.types cimport size_type from cudf._lib.utils cimport data_from_unique_ptr from cuspatial._lib.cpp.trajectory cimport ( derive_trajectories as cpp_derive_trajectories, trajectory_bounding_boxes as cpp_trajectory_bounding_boxes, trajectory_distances_and_speeds as cpp_trajectory_distances_and_speeds, ) cpdef derive_trajectories(Column object_id, Column x, Column y, Column timestamp): cdef column_view c_id = object_id.view() cdef column_view c_x = x.view() cdef column_view c_y = y.view() cdef column_view c_ts = timestamp.view() cdef pair[unique_ptr[table], unique_ptr[column]] result with nogil: result = move(cpp_derive_trajectories(c_id, c_x, c_y, c_ts)) return data_from_unique_ptr( move(result.first), column_names=["object_id", "x", "y", "timestamp"] ), Column.from_unique_ptr(move(result.second)) cpdef trajectory_bounding_boxes(size_type num_trajectories, Column object_id, Column x, Column y): cdef column_view c_id = object_id.view() cdef column_view c_x = x.view() cdef column_view c_y = y.view() cdef unique_ptr[table] result with nogil: result = move(cpp_trajectory_bounding_boxes( num_trajectories, c_id, c_x, c_y )) return data_from_unique_ptr( move(result), column_names=["x_min", "y_min", "x_max", "y_max"] ) cpdef trajectory_distances_and_speeds(size_type num_trajectories, Column object_id, Column x, Column y, Column timestamp): cdef column_view c_id = object_id.view() cdef column_view c_x = x.view() cdef column_view c_y = y.view() cdef column_view c_ts = timestamp.view() cdef unique_ptr[table] result with nogil: result = move(cpp_trajectory_distances_and_speeds( num_trajectories, c_id, c_x, c_y, c_ts )) return data_from_unique_ptr( move(result), column_names=["distance", "speed"] )
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/quadtree.pyx
# Copyright (c) 2020, NVIDIA CORPORATION. from libc.stdint cimport int8_t from libcpp.memory cimport unique_ptr from libcpp.pair cimport pair from libcpp.utility cimport move from cudf._lib.column cimport Column from cudf._lib.cpp.column.column cimport column from cudf._lib.cpp.column.column_view cimport column_view from cudf._lib.cpp.table.table cimport table from cudf._lib.cpp.types cimport size_type from cudf._lib.utils cimport data_from_unique_ptr from cuspatial._lib.cpp.quadtree cimport ( quadtree_on_points as cpp_quadtree_on_points, ) cpdef quadtree_on_points(Column x, Column y, double x_min, double x_max, double y_min, double y_max, double scale, int8_t max_depth, size_type min_size): cdef column_view c_x = x.view() cdef column_view c_y = y.view() cdef pair[unique_ptr[column], unique_ptr[table]] result with nogil: result = move(cpp_quadtree_on_points( c_x, c_y, x_min, x_max, y_min, y_max, scale, max_depth, min_size )) return ( Column.from_unique_ptr(move(result.first)), data_from_unique_ptr( move(result.second), column_names=[ "key", "level", "is_internal_node", "length", "offset" ] ) )
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/spatial.pyx
# Copyright (c) 2019, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from libcpp.pair cimport pair from libcpp.utility cimport move from cudf._lib.column cimport Column from cudf._lib.cpp.column.column cimport column from cudf._lib.cpp.column.column_view cimport column_view from cuspatial._lib.cpp.projection cimport ( sinusoidal_projection as cpp_sinusoidal_projection, ) def sinusoidal_projection( double origin_lon, double origin_lat, Column input_lon, Column input_lat ): cdef column_view c_input_lon = input_lon.view() cdef column_view c_input_lat = input_lat.view() cdef pair[unique_ptr[column], unique_ptr[column]] result with nogil: result = move( cpp_sinusoidal_projection( origin_lon, origin_lat, c_input_lon, c_input_lat ) ) return (Column.from_unique_ptr(move(result.first)), Column.from_unique_ptr(move(result.second)))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/utils.pyx
# Copyright (c) 2022, NVIDIA CORPORATION. from cudf._lib.column cimport Column from cudf._lib.cpp.column.column_view cimport column_view from cuspatial._lib.cpp.optional cimport nullopt, optional cdef optional[column_view] unwrap_pyoptcol(pyoptcol) except *: # Unwrap python optional Column arg to c optional[column_view] cdef Column pycol cdef optional[column_view] c_opt if isinstance(pyoptcol, Column): pycol = pyoptcol c_opt = pycol.view() elif pyoptcol is None: c_opt = nullopt else: raise ValueError("pyoptcol must be either Column or None.") return c_opt
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/polygon_bounding_boxes.pyx
# Copyright (c) 2020-2023, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from libcpp.utility cimport move from cudf._lib.column cimport Column from cudf._lib.cpp.column.column_view cimport column_view from cudf._lib.cpp.table.table cimport table from cudf._lib.utils cimport columns_from_unique_ptr from cuspatial._lib.cpp.polygon_bounding_boxes cimport ( polygon_bounding_boxes as cpp_polygon_bounding_boxes, ) cpdef polygon_bounding_boxes(Column poly_offsets, Column ring_offsets, Column x, Column y): cdef column_view c_poly_offsets = poly_offsets.view() cdef column_view c_ring_offsets = ring_offsets.view() cdef column_view c_x = x.view() cdef column_view c_y = y.view() cdef unique_ptr[table] result with nogil: result = move(cpp_polygon_bounding_boxes( c_poly_offsets, c_ring_offsets, c_x, c_y )) return columns_from_unique_ptr(move(result))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/nearest_points.pyx
# Copyright (c) 2022-2023, NVIDIA CORPORATION. from libcpp.utility cimport move from cudf._lib.column cimport Column from cudf._lib.cpp.column.column_view cimport column_view from cuspatial._lib.cpp.nearest_points cimport ( pairwise_point_linestring_nearest_points as c_func, point_linestring_nearest_points_result, ) from cuspatial._lib.cpp.optional cimport optional from cuspatial._lib.utils cimport unwrap_pyoptcol def pairwise_point_linestring_nearest_points( Column points_xy, Column linestring_part_offsets, Column linestring_points_xy, multipoint_geometry_offset=None, multilinestring_geometry_offset=None, ): cdef optional[column_view] c_multipoint_geometry_offset = unwrap_pyoptcol( multipoint_geometry_offset) cdef optional[column_view] c_multilinestring_geometry_offset = ( unwrap_pyoptcol(multilinestring_geometry_offset)) cdef column_view c_points_xy = points_xy.view() cdef column_view c_linestring_offsets = linestring_part_offsets.view() cdef column_view c_linestring_points_xy = linestring_points_xy.view() cdef point_linestring_nearest_points_result c_result with nogil: c_result = move(c_func( c_multipoint_geometry_offset, c_points_xy, c_multilinestring_geometry_offset, c_linestring_offsets, c_linestring_points_xy, )) multipoint_geometry_id = None if multipoint_geometry_offset is not None: multipoint_geometry_id = Column.from_unique_ptr( move(c_result.nearest_point_geometry_id.value())) multilinestring_geometry_id = None if multilinestring_geometry_offset is not None: multilinestring_geometry_id = Column.from_unique_ptr( move(c_result.nearest_linestring_geometry_id.value())) segment_id = Column.from_unique_ptr(move(c_result.nearest_segment_id)) point_on_linestring_xy = Column.from_unique_ptr( move(c_result.nearest_point_on_linestring_xy)) return ( multipoint_geometry_id, multilinestring_geometry_id, segment_id, point_on_linestring_xy )
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/points_in_range.pyx
# Copyright (c) 2020-2023, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from libcpp.utility cimport move from cudf._lib.column cimport Column, column_view from cudf._lib.cpp.table.table cimport table from cudf._lib.utils cimport data_from_unique_ptr from cuspatial._lib.cpp.points_in_range cimport ( points_in_range as cpp_points_in_range, ) cpdef points_in_range( double range_min_x, double range_max_x, double range_min_y, double range_max_y, Column x, Column y ): cdef column_view x_v = x.view() cdef column_view y_v = y.view() cdef unique_ptr[table] c_result with nogil: c_result = move( cpp_points_in_range( range_min_x, range_max_x, range_min_y, range_max_y, x_v, y_v ) ) return data_from_unique_ptr(move(c_result), column_names=["x", "y"])
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/spatial_join.pyx
# Copyright (c) 2020-2022, NVIDIA CORPORATION. from libc.stdint cimport int8_t from libcpp.memory cimport unique_ptr from libcpp.utility cimport move from cudf._lib.column cimport Column, column_view from cudf._lib.cpp.table.table cimport table, table_view from cudf._lib.utils cimport data_from_unique_ptr, table_view_from_table from cuspatial._lib.cpp.spatial_join cimport ( join_quadtree_and_bounding_boxes as cpp_join_quadtree_and_bounding_boxes, quadtree_point_in_polygon as cpp_quadtree_pip, quadtree_point_to_nearest_linestring as cpp_quadtree_p2p, ) cpdef join_quadtree_and_bounding_boxes(object quadtree, object bounding_boxes, double x_min, double x_max, double y_min, double y_max, double scale, int8_t max_depth): cdef table_view c_quadtree = table_view_from_table( quadtree, ignore_index=True) cdef table_view c_bounding_boxes = table_view_from_table( bounding_boxes, ignore_index=True) cdef unique_ptr[table] result with nogil: result = move(cpp_join_quadtree_and_bounding_boxes( c_quadtree, c_bounding_boxes, x_min, x_max, y_min, y_max, scale, max_depth )) return data_from_unique_ptr( move(result), column_names=["bbox_offset", "quad_offset"] ) cpdef quadtree_point_in_polygon(object poly_quad_pairs, object quadtree, Column point_indices, Column points_x, Column points_y, Column poly_offsets, Column ring_offsets, Column poly_points_x, Column poly_points_y): cdef table_view c_poly_quad_pairs = table_view_from_table( poly_quad_pairs, ignore_index=True) cdef table_view c_quadtree = table_view_from_table( quadtree, ignore_index=True) cdef column_view c_point_indices = point_indices.view() cdef column_view c_points_x = points_x.view() cdef column_view c_points_y = points_y.view() cdef column_view c_poly_offsets = poly_offsets.view() cdef column_view c_ring_offsets = ring_offsets.view() cdef column_view c_poly_points_x = poly_points_x.view() cdef column_view c_poly_points_y = poly_points_y.view() cdef unique_ptr[table] result with nogil: result = move(cpp_quadtree_pip( c_poly_quad_pairs, c_quadtree, c_point_indices, c_points_x, c_points_y, c_poly_offsets, c_ring_offsets, c_poly_points_x, c_poly_points_y )) return data_from_unique_ptr( move(result), column_names=["polygon_index", "point_index"] ) cpdef quadtree_point_to_nearest_linestring(object linestring_quad_pairs, object quadtree, Column point_indices, Column points_x, Column points_y, Column linestring_offsets, Column linestring_points_x, Column linestring_points_y): cdef table_view c_linestring_quad_pairs = table_view_from_table( linestring_quad_pairs, ignore_index=True) cdef table_view c_quadtree = table_view_from_table( quadtree, ignore_index=True) cdef column_view c_point_indices = point_indices.view() cdef column_view c_points_x = points_x.view() cdef column_view c_points_y = points_y.view() cdef column_view c_linestring_offsets = linestring_offsets.view() cdef column_view c_linestring_points_x = linestring_points_x.view() cdef column_view c_linestring_points_y = linestring_points_y.view() cdef unique_ptr[table] result with nogil: result = move(cpp_quadtree_p2p( c_linestring_quad_pairs, c_quadtree, c_point_indices, c_points_x, c_points_y, c_linestring_offsets, c_linestring_points_x, c_linestring_points_y )) return data_from_unique_ptr( move(result), column_names=["point_index", "linestring_index", "distance"] )
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/pairwise_multipoint_equals_count.pyx
# Copyright (c) 2023, NVIDIA CORPORATION. from libcpp.memory cimport make_shared, shared_ptr, unique_ptr from libcpp.utility cimport move from cudf._lib.column cimport Column, column from cuspatial._lib.cpp.column.geometry_column_view cimport ( geometry_column_view, ) from cuspatial._lib.cpp.pairwise_multipoint_equals_count cimport ( pairwise_multipoint_equals_count as cpp_pairwise_multipoint_equals_count, ) from cuspatial._lib.cpp.types cimport collection_type_id, geometry_type_id def pairwise_multipoint_equals_count( Column _lhs, Column _rhs, ): cdef shared_ptr[geometry_column_view] lhs = \ make_shared[geometry_column_view]( _lhs.view(), collection_type_id.MULTI, geometry_type_id.POINT) cdef shared_ptr[geometry_column_view] rhs = \ make_shared[geometry_column_view]( _rhs.view(), collection_type_id.MULTI, geometry_type_id.POINT) cdef unique_ptr[column] result with nogil: result = move( cpp_pairwise_multipoint_equals_count( lhs.get()[0], rhs.get()[0], ) ) return Column.from_unique_ptr(move(result))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/linestring_bounding_boxes.pyx
# Copyright (c) 2020-2023, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from libcpp.utility cimport move from cudf._lib.column cimport Column from cudf._lib.cpp.column.column_view cimport column_view from cudf._lib.cpp.table.table cimport table from cudf._lib.utils cimport columns_from_unique_ptr from cuspatial._lib.cpp.linestring_bounding_boxes cimport ( linestring_bounding_boxes as cpp_linestring_bounding_boxes, ) cpdef linestring_bounding_boxes(Column poly_offsets, Column x, Column y, double R): cdef column_view c_poly_offsets = poly_offsets.view() cdef column_view c_x = x.view() cdef column_view c_y = y.view() cdef unique_ptr[table] result with nogil: result = move(cpp_linestring_bounding_boxes( c_poly_offsets, c_x, c_y, R )) return columns_from_unique_ptr(move(result))
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp/nearest_points.pxd
# Copyright (c) 2022-2023, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from cudf._lib.column cimport column, column_view from cuspatial._lib.cpp.optional cimport optional cdef extern from "cuspatial/nearest_points.hpp" \ namespace "cuspatial" nogil: cdef struct point_linestring_nearest_points_result: optional[unique_ptr[column]] nearest_point_geometry_id optional[unique_ptr[column]] nearest_linestring_geometry_id unique_ptr[column] nearest_segment_id unique_ptr[column] nearest_point_on_linestring_xy cdef point_linestring_nearest_points_result \ pairwise_point_linestring_nearest_points( const optional[column_view] multipoint_geometry_offsets, const column_view points_xy, const optional[column_view] multilinestring_geometry_offsets, const column_view linestring_part_offsets, const column_view linestring_points_xy, ) except +
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp/types.pxd
# Copyright (c) 2023, NVIDIA CORPORATION. cdef extern from "cuspatial/types.hpp" namespace "cuspatial" nogil: cdef enum geometry_type_id: POINT "cuspatial::geometry_type_id::POINT" LINESTRING "cuspatial::geometry_type_id::LINESTRING" POLYGON "cuspatial::geometry_type_id::POLYGON" ctypedef enum collection_type_id: SINGLE "cuspatial::collection_type_id::SINGLE" MULTI "cuspatial::collection_type_id::MULTI"
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp/quadtree.pxd
# Copyright (c) 2020, NVIDIA CORPORATION. from libc.stdint cimport int8_t from libcpp.memory cimport unique_ptr from libcpp.pair cimport pair from cudf._lib.cpp.column.column cimport column from cudf._lib.cpp.column.column_view cimport column_view from cudf._lib.cpp.table.table cimport table from cudf._lib.cpp.types cimport size_type cdef extern from "cuspatial/point_quadtree.hpp" namespace "cuspatial" nogil: cdef pair[unique_ptr[column], unique_ptr[table]] quadtree_on_points( column_view x, column_view y, double x_min, double x_max, double y_min, double y_max, double scale, int8_t max_depth, size_type min_size ) except +
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp/polygon_bounding_boxes.pxd
# Copyright (c) 2020-2023, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from cudf._lib.cpp.column.column_view cimport column_view from cudf._lib.cpp.table.table cimport table cdef extern from "cuspatial/bounding_boxes.hpp" \ namespace "cuspatial" nogil: cdef unique_ptr[table] polygon_bounding_boxes( const column_view & poly_offsets, const column_view & ring_offsets, const column_view & x, const column_view & y ) except +
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp/projection.pxd
# Copyright (c) 2020-2023, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from libcpp.pair cimport pair from cudf._lib.cpp.column.column cimport column from cudf._lib.cpp.column.column_view cimport column_view cdef extern from "cuspatial/projection.hpp" namespace "cuspatial" \ nogil: cdef pair[unique_ptr[column], unique_ptr[column]] sinusoidal_projection( const double origin_lon, const double origin_lat, const column_view& input_lon, const column_view& input_lat ) except +
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp/pairwise_point_in_polygon.pxd
# Copyright (c) 2022-2023, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from cudf._lib.column cimport column, column_view cdef extern from "cuspatial/point_in_polygon.hpp" \ namespace "cuspatial" nogil: cdef unique_ptr[column] pairwise_point_in_polygon( const column_view & test_points_x, const column_view & test_points_y, const column_view & poly_offsets, const column_view & poly_ring_offsets, const column_view & poly_points_x, const column_view & poly_points_y ) except +
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp/pairwise_multipoint_equals_count.pxd
# Copyright (c) 2023, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from cudf._lib.column cimport column, column_view from cuspatial._lib.cpp.column.geometry_column_view cimport ( geometry_column_view, ) cdef extern from "cuspatial/pairwise_multipoint_equals_count.hpp" \ namespace "cuspatial" nogil: cdef unique_ptr[column] pairwise_multipoint_equals_count( const geometry_column_view lhs, const geometry_column_view rhs, ) except +
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp/distance.pxd
# Copyright (c) 2023, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from libcpp.utility cimport pair from cudf._lib.cpp.column.column cimport column from cudf._lib.cpp.column.column_view cimport column_view from cudf._lib.cpp.table.table_view cimport table_view from cuspatial._lib.cpp.column.geometry_column_view cimport ( geometry_column_view, ) cdef extern from "cuspatial/distance.hpp" \ namespace "cuspatial" nogil: cdef pair[unique_ptr[column], table_view] directed_hausdorff_distance( const column_view& xs, const column_view& ys, const column_view& space_offsets ) except + cdef unique_ptr[column] haversine_distance( const column_view& a_lon, const column_view& a_lat, const column_view& b_lon, const column_view& b_lat ) except + cdef unique_ptr[column] pairwise_point_distance( const geometry_column_view & multipoints1, const geometry_column_view & multipoints2 ) except + cdef unique_ptr[column] pairwise_point_linestring_distance( const geometry_column_view & multipoints, const geometry_column_view & multilinestrings ) except + cdef unique_ptr[column] pairwise_point_polygon_distance( const geometry_column_view & multipoints, const geometry_column_view & multipolygons ) except + cdef unique_ptr[column] pairwise_linestring_distance( const geometry_column_view & multilinestrings1, const geometry_column_view & multilinestrings2 ) except + cdef unique_ptr[column] pairwise_linestring_polygon_distance( const geometry_column_view & multilinestrings, const geometry_column_view & multipolygons ) except + cdef unique_ptr[column] pairwise_polygon_distance( const geometry_column_view & multipolygons1, const geometry_column_view & multipolygons2 ) except +
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp/linestring_intersection.pxd
# Copyright (c) 2023, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from cudf._lib.column cimport column, column_view from cuspatial._lib.cpp.column.geometry_column_view cimport ( geometry_column_view, ) cdef extern from "cuspatial/intersection.hpp" \ namespace "cuspatial" nogil: struct linestring_intersection_column_result: unique_ptr[column] geometry_collection_offset unique_ptr[column] types_buffer unique_ptr[column] offset_buffer unique_ptr[column] points unique_ptr[column] segments unique_ptr[column] lhs_linestring_id unique_ptr[column] lhs_segment_id unique_ptr[column] rhs_linestring_id unique_ptr[column] rhs_segment_id cdef linestring_intersection_column_result \ pairwise_linestring_intersection( const geometry_column_view & multilinestring_lhs, const geometry_column_view & multilinestring_rhs, ) except +
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp/points_in_range.pxd
# Copyright (c) 2020-2023, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from cudf._lib.column cimport column, column_view from cudf._lib.cpp.table.table cimport table, table_view cdef extern from "cuspatial/points_in_range.hpp" namespace "cuspatial" nogil: cdef unique_ptr[table] points_in_range \ "cuspatial::points_in_range" ( double range_min_x, double range_max_x, double range_min_y, double range_max_y, const column_view & x, const column_view & y ) except +
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp/point_in_polygon.pxd
# Copyright (c) 2020, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from cudf._lib.column cimport column, column_view cdef extern from "cuspatial/point_in_polygon.hpp" namespace "cuspatial" nogil: cdef unique_ptr[column] point_in_polygon( const column_view & test_points_x, const column_view & test_points_y, const column_view & poly_offsets, const column_view & poly_ring_offsets, const column_view & poly_points_x, const column_view & poly_points_y ) except +
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp/trajectory.pxd
# Copyright (c) 2020, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from libcpp.pair cimport pair from cudf._lib.cpp.column.column cimport column from cudf._lib.cpp.column.column_view cimport column_view from cudf._lib.cpp.table.table cimport table from cudf._lib.cpp.types cimport size_type cdef extern from "cuspatial/trajectory.hpp" namespace "cuspatial" nogil: cdef pair[unique_ptr[table], unique_ptr[column]] derive_trajectories( const column_view& object_id, const column_view& x, const column_view& y, const column_view& timestamp ) except + cdef unique_ptr[table] trajectory_bounding_boxes( size_type num_trajectories, const column_view& object_id, const column_view& x, const column_view& y ) except + cdef unique_ptr[table] trajectory_distances_and_speeds( size_type num_trajectories, const column_view& object_id, const column_view& x, const column_view& y, const column_view& timestamp ) except +
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp/spatial_join.pxd
# Copyright (c) 2020-2022, NVIDIA CORPORATION. from libc.stdint cimport int8_t from libcpp.memory cimport unique_ptr from cudf._lib.column cimport column_view from cudf._lib.cpp.table.table cimport table, table_view cdef extern from "cuspatial/spatial_join.hpp" namespace "cuspatial" nogil: cdef unique_ptr[table] join_quadtree_and_bounding_boxes \ "cuspatial::join_quadtree_and_bounding_boxes" ( const table_view & quadtree, const table_view & bboxes, double x_min, double x_max, double y_min, double y_max, double scale, int8_t max_depth ) except + cdef unique_ptr[table] quadtree_point_in_polygon \ "cuspatial::quadtree_point_in_polygon" ( const table_view & poly_quad_pairs, const table_view & quadtree, const column_view & point_indices, const column_view & points_x, const column_view & points_y, const column_view & poly_offsets, const column_view & ring_offsets, const column_view & poly_points_x, const column_view & poly_points_y ) except + cdef unique_ptr[table] quadtree_point_to_nearest_linestring \ "cuspatial::quadtree_point_to_nearest_linestring" ( const table_view & linestring_quad_pairs, const table_view & quadtree, const column_view & point_indices, const column_view & points_x, const column_view & points_y, const column_view & linestring_offsets, const column_view & linestring_points_x, const column_view & linestring_points_y ) except +
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp/optional.pxd
from libcpp cimport bool # Backported to cython 0.29 from https://github.com/cython/cython/pull/3294 cdef extern from "<optional>" namespace "std" nogil: cdef cppclass nullopt_t: nullopt_t() cdef nullopt_t nullopt cdef cppclass optional[T]: ctypedef T value_type optional() optional(nullopt_t) optional(optional&) except + optional(T&) except + bool has_value() T& value() T& value_or[U](U& default_value) void swap(optional&) void reset() T& emplace(...) T& operator*() # T* operator->() Not Supported optional& operator=(optional&) optional& operator=[U](U&) optional& operator=(nullopt) bool operator bool() bool operator!() bool operator==[U](optional&, U&) bool operator!=[U](optional&, U&) bool operator<[U](optional&, U&) bool operator>[U](optional&, U&) bool operator<=[U](optional&, U&) bool operator>=[U](optional&, U&) optional[T] make_optional[T](...) except +
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp/linestring_bounding_boxes.pxd
# Copyright (c) 2020-2023, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from cudf._lib.cpp.column.column_view cimport column_view from cudf._lib.cpp.table.table cimport table cdef extern from "cuspatial/bounding_boxes.hpp" \ namespace "cuspatial" nogil: cdef unique_ptr[table] linestring_bounding_boxes( const column_view & linestring_offsets, const column_view & x, const column_view & y, double R ) except +
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp/distance/polygon_distance.pxd
# Copyright (c) 2023, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from cudf._lib.cpp.column.column cimport column from cuspatial._lib.cpp.column.geometry_column_view cimport ( geometry_column_view, ) cdef extern from "cuspatial/distance.hpp" \ namespace "cuspatial" nogil: cdef unique_ptr[column] pairwise_polygon_distance( const geometry_column_view & lhs, const geometry_column_view & rhs ) except +
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/_lib/cpp/column/geometry_column_view.pxd
# Copyright (c) 2023, NVIDIA CORPORATION. from libcpp.memory cimport unique_ptr from cudf._lib.column cimport column, column_view from cuspatial._lib.cpp.types cimport collection_type_id, geometry_type_id cdef extern from "cuspatial/column/geometry_column_view.hpp" \ namespace "cuspatial" nogil: cdef cppclass geometry_column_view: geometry_column_view() except + geometry_column_view( const column_view& column, collection_type_id collection_type, geometry_type_id geometry_type ) except +
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/io/geopandas_reader.py
# Copyright (c) 2020-2022 NVIDIA CORPORATION. from geopandas import GeoSeries as gpGeoSeries from shapely.geometry import ( LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, mapping, ) import cudf from cuspatial.core._column.geometa import Feature_Enum from cuspatial.io import pygeoarrow NONE_OFFSET = -1 def parse_geometries(geoseries: gpGeoSeries) -> tuple: point_coords = [] mpoint_coords = [] line_coords = [] polygon_coords = [] all_offsets = [] type_buffer = [] point_offsets = [0] mpoint_offsets = [0] line_offsets = [0] polygon_offsets = [0] for geom in geoseries: if geom is None: all_offsets.append(NONE_OFFSET) type_buffer.append(Feature_Enum.NONE.value) continue coords = mapping(geom)["coordinates"] if isinstance(geom, Point): point_coords.append(coords) all_offsets.append(point_offsets[-1]) point_offsets.append(point_offsets[-1] + 1) type_buffer.append(Feature_Enum.POINT.value) elif isinstance(geom, MultiPoint): mpoint_coords.append(coords) all_offsets.append(mpoint_offsets[-1]) mpoint_offsets.append(mpoint_offsets[-1] + 1) type_buffer.append(Feature_Enum.MULTIPOINT.value) elif isinstance(geom, LineString): line_coords.append([coords]) all_offsets.append(line_offsets[-1]) line_offsets.append(line_offsets[-1] + 1) type_buffer.append(Feature_Enum.LINESTRING.value) elif isinstance(geom, MultiLineString): line_coords.append(coords) all_offsets.append(line_offsets[-1]) line_offsets.append(line_offsets[-1] + 1) type_buffer.append(Feature_Enum.LINESTRING.value) elif isinstance(geom, Polygon): polygon_coords.append([coords]) all_offsets.append(polygon_offsets[-1]) polygon_offsets.append(polygon_offsets[-1] + 1) type_buffer.append(Feature_Enum.POLYGON.value) elif isinstance(geom, MultiPolygon): polygon_coords.append(coords) all_offsets.append(polygon_offsets[-1]) polygon_offsets.append(polygon_offsets[-1] + 1) type_buffer.append(Feature_Enum.POLYGON.value) else: raise TypeError(type(geom)) return ( type_buffer, all_offsets, point_coords, mpoint_coords, line_coords, polygon_coords, ) class GeoPandasReader: buffers = None source = None def __init__(self, geoseries: gpGeoSeries): """ GeoPandasReader copies a GeoPandas GeoSeries object iteratively into a set of arrays: points, multipoints, lines, and polygons. Parameters ---------- geoseries : A GeoPandas GeoSeries """ self.buffers = pygeoarrow.from_lists(*parse_geometries(geoseries)) def _get_geotuple(self) -> cudf.Series: """ TODO: Returns the four basic cudf.ListSeries objects for points, mpoints, lines, and polygons """ points = cudf.Series.from_arrow( self.buffers.field(Feature_Enum.POINT.value) ) mpoints = cudf.Series.from_arrow( self.buffers.field(Feature_Enum.MULTIPOINT.value) ) lines = cudf.Series.from_arrow( self.buffers.field(Feature_Enum.LINESTRING.value) ) polygons = cudf.Series.from_arrow( self.buffers.field(Feature_Enum.POLYGON.value) ) return ( points, mpoints, lines, polygons, ) def get_geopandas_meta(self) -> dict: """ Returns the metadata that was created converting the GeoSeries into GeoArrow format. The metadata essentially contains the object order in the GeoSeries format. GeoArrow doesn't support custom orderings, every GeoArrow data store contains points, multipoints, lines, and polygons in an arbitrary order. """ buffers = self.buffers return { "input_types": buffers.type_codes, "union_offsets": buffers.offsets, }
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/io/pygeoarrow.py
# Copyright (c) 2022, NVIDIA CORPORATION from typing import List import pyarrow as pa ArrowPolygonsType: pa.ListType = pa.list_( pa.list_(pa.list_(pa.list_(pa.float64()))) ) ArrowLinestringsType: pa.ListType = pa.list_(pa.list_(pa.list_(pa.float64()))) ArrowMultiPointsType: pa.ListType = pa.list_(pa.list_(pa.float64())) ArrowPointsType: pa.ListType = pa.list_(pa.float64()) def getGeoArrowUnionRootType() -> pa.union: return pa.union( [ ArrowPointsType, ArrowMultiPointsType, ArrowLinestringsType, ArrowPolygonsType, ], mode="dense", ) def from_pyarrow_lists( type_buffer: pa.ListArray, all_offsets: pa.ListArray, point_coords: pa.ListArray, mpoint_coords: pa.ListArray, line_coords: pa.ListArray, polygon_coords: pa.ListArray, ) -> pa.lib.UnionArray: type_buffer = type_buffer all_offsets = all_offsets children = [ point_coords, mpoint_coords, line_coords, polygon_coords, ] return pa.UnionArray.from_dense( type_buffer, all_offsets, children, ["points", "mpoints", "lines", "polygons"], ) def from_lists( type_buffer: List, all_offsets: List, point_coords: List, mpoint_coords: List, line_coords: List, polygon_coords: List, ) -> pa.lib.UnionArray: return from_pyarrow_lists( pa.array(type_buffer).cast(pa.int8()), pa.array(all_offsets).cast(pa.int32()), pa.array(point_coords, type=ArrowPointsType), pa.array(mpoint_coords, type=ArrowMultiPointsType), pa.array(line_coords, type=ArrowLinestringsType), pa.array(polygon_coords, type=ArrowPolygonsType), )
0
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/cuspatial/io/geopandas.py
# Copyright (c) 2020-2022, NVIDIA CORPORATION. import pandas as pd from geopandas import GeoDataFrame as gpGeoDataFrame from geopandas.geoseries import GeoSeries as gpGeoSeries from cuspatial import GeoDataFrame, GeoSeries def from_geopandas(gpdf): """ Converts a geopandas mixed geometry dataframe into a cuspatial geometry dataframe. Possible inputs: - :class:`geopandas.GeoSeries` - :class:`geopandas.GeoDataFrame` """ if isinstance(gpdf, gpGeoSeries): return GeoSeries(gpdf) elif isinstance(gpdf, gpGeoDataFrame): return GeoDataFrame(gpdf) elif isinstance(gpdf, pd.Series): raise TypeError("Mixed pandas/geometry types not supported yet.") else: raise TypeError
0
rapidsai_public_repos/cuspatial/python/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/benchmarks/conftest.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. """Defines pytest fixtures for all benchmarks. The cuspatial fixture is a single randomly generated GeoDataframe, containing 4 columns: 1 GeoSeries column, an int column, a float column, and a string column. """ import cupy as cp import geopandas as gpd import numpy as np import pandas as pd import pytest import pytest_cases from numba import cuda from shapely.geometry import ( LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, ) import cudf import cuspatial @pytest_cases.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_cases.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_cases.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) def make_geopandas_dataframe_from_naturalearth_lowres(nr): source_df = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres")) result_df = gpd.GeoDataFrame() for i in range((nr // len(source_df)) + 1): scramble_df = source_df.iloc[ np.random.choice(len(source_df), len(source_df)), : ] result_df = pd.concat([scramble_df, result_df]).reset_index(drop=True) return result_df @pytest_cases.fixture() def host_dataframe(): return gpd.read_file(gpd.datasets.get_path("naturalearth_lowres")) @pytest_cases.fixture() def gpu_dataframe(host_dataframe): return cuspatial.from_geopandas(host_dataframe) @pytest_cases.fixture() def polygons(host_dataframe): return cuspatial.from_geopandas( host_dataframe[host_dataframe["geometry"].type == "Polygon"] ) @pytest_cases.fixture() def sorted_trajectories(): ids = cp.random.randint(1, 400, 10000) timestamps = cp.random.random(10000) * 10000 x = cp.random.random(10000) y = cp.random.random(10000) xy = cudf.DataFrame({"x": x, "y": y}).interleave_columns() points = cuspatial.GeoSeries.from_points_xy(xy) return cuspatial.derive_trajectories(ids, points, timestamps) @pytest_cases.fixture() def gpdf_100(request): return make_geopandas_dataframe_from_naturalearth_lowres(100) @pytest_cases.fixture() def gpdf_1000(request): return make_geopandas_dataframe_from_naturalearth_lowres(1000) @pytest_cases.fixture() def gpdf_10000(request): return make_geopandas_dataframe_from_naturalearth_lowres(10000) @pytest_cases.fixture() def cugpdf_100(gpdf_100): return cuspatial.from_geopandas(gpdf_100) @pytest_cases.fixture() def shapefile(tmp_path, gpdf_100): d = tmp_path / "shp" d.mkdir() p = d / "read_polygon_shapefile" gpdf_100.to_file(p) return p @pytest.fixture() def point_generator_device(): def generator(n): coords = cp.random.random(n * 2, dtype="f8") return cuspatial.GeoSeries.from_points_xy(coords) return generator # Numba kernel to generate a closed ring for each polygon @cuda.jit def generate_polygon_coordinates( coordinate_array, centroids, radius, num_vertices ): i = cuda.grid(1) if i >= coordinate_array.size: return point_idx = i // 2 geometry_idx = point_idx // (num_vertices + 1) # The last index should wrap around to 0 intra_point_idx = point_idx % (num_vertices + 1) centroid = centroids[geometry_idx] angle = 2 * np.pi * intra_point_idx / num_vertices if i % 2 == 0: coordinate_array[i] = centroid[0] + radius * np.cos(angle) else: coordinate_array[i] = centroid[1] + radius * np.sin(angle) @pytest.fixture() def polygon_generator_device(): def generator(n, num_vertices, radius=1.0, all_concentric=False): geometry_offsets = cp.arange(n + 1) part_offsets = cp.arange(n + 1) # Each polygon has a closed ring, so we need to add an extra point ring_offsets = cp.arange( (n + 1) * (num_vertices + 1), step=(num_vertices + 1) ) num_points = int(ring_offsets[-1].get()) if not all_concentric: centroids = cp.random.random((n, 2)) else: centroids = cp.zeros((n, 2)) coords = cp.ndarray((num_points * 2,), dtype="f8") generate_polygon_coordinates.forall(len(coords))( coords, centroids, radius, num_vertices ) return cuspatial.GeoSeries.from_polygons_xy( coords, ring_offsets, part_offsets, geometry_offsets ) return generator @pytest.fixture() def linestring_generator_device(polygon_generator_device): """Reusing polygon_generator_device, treating the rings of the generated polygons as linestrings. This is to gain locality to the generated linestrings. """ def generator(n, segment_per_linestring): polygons = polygon_generator_device( n, segment_per_linestring, all_concentric=False ) return cuspatial.GeoSeries.from_linestrings_xy( polygons.polygons.xy, polygons.polygons.ring_offset, polygons.polygons.geometry_offset, ) return generator
0
rapidsai_public_repos/cuspatial/python/cuspatial
rapidsai_public_repos/cuspatial/python/cuspatial/benchmarks/pytest.ini
# Copyright (c) 2022, NVIDIA CORPORATION. [pytest] python_files = bench_*.py python_classes = Bench python_functions = bench_*
0
rapidsai_public_repos/cuspatial/python/cuspatial/benchmarks
rapidsai_public_repos/cuspatial/python/cuspatial/benchmarks/api/bench_api.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. import cupy import geopandas import pytest import cudf import cuspatial def bench_io_from_geopandas(benchmark, host_dataframe): benchmark(cuspatial.from_geopandas, host_dataframe) def bench_io_to_geopandas(benchmark, gpu_dataframe): benchmark( gpu_dataframe.to_geopandas, ) def bench_derive_trajectories(benchmark, sorted_trajectories): ids = cupy.random.randint(1, 400, 10000) timestamps = cupy.random.random(10000) * 10000 x = cupy.random.random(10000) y = cupy.random.random(10000) points = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame({"x": x, "y": y}).interleave_columns() ) benchmark(cuspatial.derive_trajectories, ids, points, timestamps) def bench_trajectory_distances_and_speeds(benchmark, sorted_trajectories): length = len(cudf.Series(sorted_trajectories[1]).unique()) points = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame( { "x": sorted_trajectories[0]["x"], "y": sorted_trajectories[0]["y"], } ).interleave_columns() ) benchmark( cuspatial.trajectory_distances_and_speeds, length, sorted_trajectories[0]["object_id"], points, sorted_trajectories[0]["timestamp"], ) def bench_trajectory_bounding_boxes(benchmark, sorted_trajectories): length = len(cudf.Series(sorted_trajectories[1]).unique()) points = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame( { "x": sorted_trajectories[0]["x"], "y": sorted_trajectories[0]["y"], } ).interleave_columns() ) benchmark( cuspatial.trajectory_bounding_boxes, length, sorted_trajectories[0]["object_id"], points, ) def bench_polygon_bounding_boxes(benchmark, polygons): benchmark(cuspatial.polygon_bounding_boxes, polygons) def bench_linestring_bounding_boxes(benchmark, sorted_trajectories): xy = sorted_trajectories[0][["x", "y"]].interleave_columns() lines = cuspatial.GeoSeries.from_linestrings_xy( xy, sorted_trajectories[1], cupy.arange(len(sorted_trajectories)) ) benchmark( cuspatial.linestring_bounding_boxes, lines, 0.0001, ) def bench_sinusoidal_projection(benchmark, gpu_dataframe): afghanistan = gpu_dataframe["geometry"][ gpu_dataframe["name"] == "Afghanistan" ] lonlat = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame( {"lon": afghanistan.polygons.y, "lat": afghanistan.polygons.x} ).interleave_columns() ) benchmark( cuspatial.sinusoidal_projection, afghanistan.polygons.y.mean(), afghanistan.polygons.x.mean(), lonlat, ) def bench_directed_hausdorff_distance(benchmark, sorted_trajectories): coords = sorted_trajectories[0][["x", "y"]].interleave_columns() offsets = sorted_trajectories[1] s = cuspatial.GeoSeries.from_multipoints_xy(coords, offsets) benchmark(cuspatial.directed_hausdorff_distance, s) def bench_directed_hausdorff_distance_many_spaces(benchmark): spaces = 10000 coords = cupy.zeros((spaces * 2,)) offsets = cupy.arange(spaces + 1, dtype="int32") s = cuspatial.GeoSeries.from_multipoints_xy(coords, offsets) benchmark(cuspatial.directed_hausdorff_distance, s) def bench_haversine_distance(benchmark, gpu_dataframe): coords_first = gpu_dataframe["geometry"][0:10].polygons.xy[0:1000] coords_second = gpu_dataframe["geometry"][10:20].polygons.xy[0:1000] points_first = cuspatial.GeoSeries.from_points_xy(coords_first) points_second = cuspatial.GeoSeries.from_points_xy(coords_second) benchmark(cuspatial.haversine_distance, points_first, points_second) def bench_distance_pairwise_linestring(benchmark, gpu_dataframe): geometry = gpu_dataframe["geometry"] benchmark( cuspatial.pairwise_linestring_distance, geometry, geometry, ) def bench_points_in_spatial_window(benchmark, gpu_dataframe): geometry = gpu_dataframe["geometry"] mean_x, std_x = (geometry.polygons.x.mean(), geometry.polygons.x.std()) mean_y, std_y = (geometry.polygons.y.mean(), geometry.polygons.y.std()) points = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame( {"x": geometry.polygons.x, "y": geometry.polygons.y} ).interleave_columns() ) benchmark( cuspatial.points_in_spatial_window, points, mean_x - std_x, mean_x + std_x, mean_y - std_y, mean_y + std_y, ) def bench_quadtree_on_points(benchmark, gpu_dataframe): polygons = gpu_dataframe["geometry"].polygons x_points = (cupy.random.random(10000000) - 0.5) * 360 y_points = (cupy.random.random(10000000) - 0.5) * 180 points = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame({"x": x_points, "y": y_points}).interleave_columns() ) scale = 5 max_depth = 7 min_size = 125 benchmark( cuspatial.quadtree_on_points, points, polygons.x.min(), polygons.x.max(), polygons.y.min(), polygons.y.max(), scale, max_depth, min_size, ) def bench_quadtree_point_in_polygon(benchmark, polygons): df = polygons polygons = polygons["geometry"].polygons x_points = (cupy.random.random(50000000) - 0.5) * 360 y_points = (cupy.random.random(50000000) - 0.5) * 180 scale = 5 max_depth = 7 min_size = 125 points = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame({"x": x_points, "y": y_points}).interleave_columns() ) point_indices, quadtree = cuspatial.quadtree_on_points( points, polygons.x.min(), polygons.x.max(), polygons.y.min(), polygons.y.max(), scale, max_depth, min_size, ) poly_bboxes = cuspatial.polygon_bounding_boxes(df["geometry"]) intersections = cuspatial.join_quadtree_and_bounding_boxes( quadtree, poly_bboxes, polygons.x.min(), polygons.x.max(), polygons.y.min(), polygons.y.max(), scale, max_depth, ) benchmark( cuspatial.quadtree_point_in_polygon, intersections, quadtree, point_indices, points, df["geometry"], ) def bench_quadtree_point_to_nearest_linestring(benchmark): SCALE = 3 MAX_DEPTH = 7 MIN_SIZE = 125 host_countries = geopandas.read_file( geopandas.datasets.get_path("naturalearth_lowres") ) host_cities = geopandas.read_file( geopandas.datasets.get_path("naturalearth_cities") ) gpu_countries = cuspatial.from_geopandas( host_countries[host_countries["geometry"].type == "Polygon"] ) gpu_cities = cuspatial.from_geopandas(host_cities) polygons = gpu_countries["geometry"].polygons points_x = gpu_cities["geometry"].points.x points_y = gpu_cities["geometry"].points.y points = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame({"x": points_x, "y": points_y}).interleave_columns() ) linestrings = cuspatial.GeoSeries.from_linestrings_xy( cudf.DataFrame( {"x": polygons.x, "y": polygons.y} ).interleave_columns(), polygons.ring_offset, cupy.arange(len(polygons.ring_offset)), ) point_indices, quadtree = cuspatial.quadtree_on_points( points, polygons.x.min(), polygons.x.max(), polygons.y.min(), polygons.y.max(), SCALE, MAX_DEPTH, MIN_SIZE, ) xy = cudf.DataFrame( {"x": polygons.x, "y": polygons.y} ).interleave_columns() lines = cuspatial.GeoSeries.from_linestrings_xy( xy, polygons.ring_offset, cupy.arange(len(polygons.ring_offset)) ) linestring_bboxes = cuspatial.linestring_bounding_boxes(lines, 2.0) intersections = cuspatial.join_quadtree_and_bounding_boxes( quadtree, linestring_bboxes, polygons.x.min(), polygons.x.max(), polygons.y.min(), polygons.y.max(), SCALE, MAX_DEPTH, ) benchmark( cuspatial.quadtree_point_to_nearest_linestring, intersections, quadtree, point_indices, points, linestrings, ) def bench_point_in_polygon(benchmark, polygons): x_points = (cupy.random.random(5000) - 0.5) * 360 y_points = (cupy.random.random(5000) - 0.5) * 180 points = cuspatial.GeoSeries.from_points_xy( cudf.DataFrame({"x": x_points, "y": y_points}).interleave_columns() ) short_dataframe = polygons.iloc[0:31] geometry = short_dataframe["geometry"] benchmark(cuspatial.point_in_polygon, points, geometry) # GeoSeries.distance benchmarking. @pytest.mark.parametrize("align", [True, False]) @pytest.mark.parametrize("n", [1e3, 1e4, 1e5, 1e6, 1e7]) @pytest.mark.parametrize("lib", ["cuspatial", "geopandas"]) def bench_distance_point(benchmark, lib, point_generator_device, n, align): points = point_generator_device(int(n)) other_points = point_generator_device(int(n)) index = cudf.Index(cupy.arange(len(other_points) - 1, -1, -1)) if lib == "geopandas": points = points.to_geopandas() other_points = other_points.to_geopandas() index = index.to_pandas() other_points.index = index benchmark(points.distance, other_points, align) @pytest.mark.parametrize("align", [True, False]) @pytest.mark.parametrize("n", [1e3, 1e4, 1e5, 1e6, 1e7]) @pytest.mark.parametrize("lib", ["cuspatial", "geopandas"]) def bench_distance_point_linestring( benchmark, point_generator_device, linestring_generator_device, lib, n, align, ): points = point_generator_device(int(n)) linestrings = linestring_generator_device(int(n), 20) index = cudf.Index(cupy.arange(len(linestrings) - 1, -1, -1)) if lib == "geopandas": points = points.to_geopandas() linestrings = linestrings.to_geopandas() index = index.to_pandas() linestrings.index = index benchmark(points.distance, linestrings, align) @pytest.mark.parametrize("align", [True, False]) @pytest.mark.parametrize("n", [1e3, 1e4, 1e5, 1e6, 1e7]) @pytest.mark.parametrize("lib", ["cuspatial", "geopandas"]) def bench_distance_point_polygon( benchmark, point_generator_device, polygon_generator_device, lib, n, align ): points = point_generator_device(int(n)) polygons = polygon_generator_device(int(n), 38) index = cudf.Index(cupy.arange(len(polygons) - 1, -1, -1)) if lib == "geopandas": points = points.to_geopandas() polygons = polygons.to_geopandas() index = index.to_pandas() polygons.index = index benchmark(points.distance, polygons, align) @pytest.mark.parametrize("align", [True, False]) @pytest.mark.parametrize("n", [1e3, 1e4, 1e5, 1e6, 1e7]) @pytest.mark.parametrize("lib", ["cuspatial", "geopandas"]) def bench_distance_linestring_linestring( benchmark, linestring_generator_device, lib, n, align ): lines1 = linestring_generator_device(int(n), 20) lines2 = linestring_generator_device(int(n), 20) index = cudf.Index(cupy.arange(len(lines1) - 1, -1, -1)) if lib == "geopandas": lines1 = lines1.to_geopandas() lines2 = lines2.to_geopandas() index = index.to_pandas() lines1.index = index benchmark(lines1.distance, lines2, align) @pytest.mark.parametrize("align", [True, False]) @pytest.mark.parametrize("n", [1e3, 1e4, 1e5, 1e6, 1e7]) @pytest.mark.parametrize("lib", ["cuspatial", "geopandas"]) @pytest.mark.parametrize( "num_segments, num_sides", [(5, 5), (20, 38), (100, 100), (1000, 1000)] ) def bench_distance_linestring_polygon( benchmark, lib, linestring_generator_device, polygon_generator_device, n, align, num_segments, num_sides, ): lines = linestring_generator_device(int(n), num_segments) polygons = polygon_generator_device(int(n), num_sides) index = cudf.Index(cupy.arange(len(lines) - 1, -1, -1)) if lib == "geopandas": lines = lines.to_geopandas() polygons = polygons.to_geopandas() index = index.to_pandas() lines.index = index benchmark(lines.distance, polygons, align) @pytest.mark.parametrize("align", [True, False]) @pytest.mark.parametrize("n", [1e3, 1e4, 1e5, 1e6, 1e7]) @pytest.mark.parametrize("lib", ["cuspatial", "geopandas"]) @pytest.mark.parametrize("intersects", [True, False]) def bench_distance_polygon( benchmark, lib, polygon_generator_device, n, align, intersects ): polygons1 = polygon_generator_device( int(n), 38, radius=1.0, all_concentric=True ) polygons2 = polygon_generator_device( int(n), 38, radius=0.5, all_concentric=True ) index = cudf.Index(cupy.arange(len(polygons1) - 1, -1, -1)) if lib == "geopandas": polygons1 = polygons1.to_geopandas() polygons2 = polygons2.to_geopandas() index = index.to_pandas() polygons1.index = index benchmark(polygons1.distance, polygons2, align)
0
rapidsai_public_repos/cuspatial/python/cuspatial/benchmarks
rapidsai_public_repos/cuspatial/python/cuspatial/benchmarks/io/bench_geoseries.py
# Copyright (c) 2022, NVIDIA CORPORATION. """Benchmarks of GeoSeries methods.""" import cuspatial def bench_from_geoseries_100(benchmark, gpdf_100): benchmark(cuspatial.from_geopandas, gpdf_100["geometry"]) def bench_from_geoseries_1000(benchmark, gpdf_1000): benchmark(cuspatial.from_geopandas, gpdf_1000["geometry"]) def bench_from_geoseries_10000(benchmark, gpdf_10000): benchmark(cuspatial.from_geopandas, gpdf_10000["geometry"])
0
rapidsai_public_repos/cuspatial/python/cuspatial/cmake
rapidsai_public_repos/cuspatial/python/cuspatial/cmake/Modules/WheelHelpers.cmake
# ============================================================================= # 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_guard(GLOBAL) # Making libraries available inside wheels by installing the associated targets. function(add_target_libs_to_wheel) list(APPEND CMAKE_MESSAGE_CONTEXT "add_target_libs_to_wheel") set(options "") set(one_value "LIB_DIR") set(multi_value "TARGETS") cmake_parse_arguments(_ "${options}" "${one_value}" "${multi_value}" ${ARGN}) message(VERBOSE "Installing targets '${__TARGETS}' into lib_dir '${__LIB_DIR}'") foreach(target IN LISTS __TARGETS) if(NOT TARGET ${target}) message(VERBOSE "No target named ${target}") continue() endif() get_target_property(alias_target ${target} ALIASED_TARGET) if(alias_target) set(target ${alias_target}) endif() get_target_property(is_imported ${target} IMPORTED) if(NOT is_imported) # If the target isn't imported, install it into the the wheel install(TARGETS ${target} DESTINATION ${__LIB_DIR}) message(VERBOSE "install(TARGETS ${target} DESTINATION ${__LIB_DIR})") else() # If the target is imported, make sure it's global get_target_property(already_global ${target} IMPORTED_GLOBAL) if(NOT already_global) set_target_properties(${target} PROPERTIES IMPORTED_GLOBAL TRUE) endif() # Find the imported target's library so we can copy it into the wheel set(lib_loc) foreach(prop IN ITEMS IMPORTED_LOCATION IMPORTED_LOCATION_RELEASE IMPORTED_LOCATION_DEBUG) get_target_property(lib_loc ${target} ${prop}) if(lib_loc) message(VERBOSE "Found ${prop} for ${target}: ${lib_loc}") break() endif() message(VERBOSE "${target} has no value for property ${prop}") endforeach() if(NOT lib_loc) message(FATAL_ERROR "Found no libs to install for target ${target}") endif() # Copy the imported library into the wheel install(FILES ${lib_loc} DESTINATION ${__LIB_DIR}) message(VERBOSE "install(FILES ${lib_loc} DESTINATION ${__LIB_DIR})") endif() endforeach() endfunction()
0
rapidsai_public_repos/cuspatial
rapidsai_public_repos/cuspatial/java/LICENSE-bundled
The binary distribution of this product bundles binaries of Boost which are available under the following license: Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
0
rapidsai_public_repos/cuspatial
rapidsai_public_repos/cuspatial/java/README.md
# Java Bindings for Cuspatial This project is a Java layer bridging Java user and libcuspatial.so Follow these instructions to create local builds and installation of librmm, libcudf and cudf-java, and libcuspatial ## Build and Install Dependencies: ### 1. libcudf and cudf-java 1.1) Follow instructions on this page for libcudf: `https://github.com/rapidsai/cudf/blob/branch-0.11/CONTRIBUTING.md#script-to-build-cudf-from-source`, but append two more cmake config flags `-DARROW_STATIC_LIB=ON -DBoost_USE_STATIC_LIBS=ON`, changing ```xml $ cmake .. -DCMAKE_INSTALL_PREFIX=$CONDA_PREFIX -DCMAKE_CXX11_ABI=ON ``` to ```xml $ cmake .. -DCMAKE_INSTALL_PREFIX=$CONDA_PREFIX -DCMAKE_CXX11_ABI=ON -DARROW_STATIC_LIB=ON -DBoost_USE_STATIC_LIBS=ON ``` Make sure to `make install` after `make`. DO NOT use the `build.sh` script to build `libcudf.so` 1.2) Follow the instructions in `${CUDF_HOME}/java/README.md` to build and install cuDF product JAR and test JAR ```xml $ cd ${CUDF_HOME}/java $ mvn clean install ``` NOTE: 1. Following above steps you will have conda env `cudf_dev` which is required for subsequent builds. 2. libcudf.so will be installed under conda env `cudf_dev`. 3. libcudfJni.so will be built by maven pom. 4. cuDF JARs will be installed to maven local. ### 2. librmm (header-only) `export RMM_HOME=${pwd}/rmm` and `git clone` source into `$RMM_HOME`. Follow instructions on this page: `https://github.com/rapidsai/rmm`, section `Script to build RMM from source` ```xml $ cd ${RMM_HOME}/ $ ./build.sh librmm ``` NOTE: 1. The build.sh script does installation by default. 2. The destination is conda env `cudf_dev`. ### 3. libcuspatial Follow the instructions on this page for libcuspatial: https://github.com/rapidsai/cuspatial ```xml $ cd ${CUSPATIAL_HOME}/ $ ./build.sh libcuspatial tests ``` NOTE: 1. Require env `RMM_HOME`, `CUDF_HOME`, `CUSPATIAL_HOME`, and conda env `cudf_dev`. ## Build cuspatial-java ```xml $ cd ${CUSPATIAL_HOME}/java $ mvn clean install ``` NOTE: 1. cuspatialJni.so will be built by maven pom. 2. Unit tests of Cuspatial-java will run during the JAR build.
0
rapidsai_public_repos/cuspatial
rapidsai_public_repos/cuspatial/java/pom.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (c) 2020, 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>ai.rapids</groupId> <artifactId>cuspatial</artifactId> <version>0.16-SNAPSHOT</version> <name>cuspatialjni</name> <description> This project provides java bindings for cuspatial, to be able to process large amounts of data on a GPU. </description> <url>http://ai.rapids</url> <licenses> <license> <name>Apache License, Version 2.0</name> <url>https://www.apache.org/licenses/LICENSE-2.0.txt</url> <distribution>repo</distribution> <comments>A business-friendly OSS license</comments> </license> </licenses> <scm> <connection>scm:git:https://github.com/rapidsai/cuspatial.git</connection> <developerConnection>scm:git:git@github.com:rapidsai/cuspatial.git</developerConnection> <tag>HEAD</tag> <url>https://github.com/rapidsai/cuspatial</url> </scm> <developers> <developer> <id>byin</id> <name>Beixing Yin</name> <email>byin@nvidia.com</email> <roles> <role>Committer</role> </roles> <timezone>-8</timezone> </developer> </developers> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <junit.version>5.4.2</junit.version> <ai.rapids.refcount.debug>false</ai.rapids.refcount.debug> <native.build.path>${basedir}/target/cmake-build</native.build.path> <skipNativeCopy>false</skipNativeCopy> <cxx11.abi.value>ON</cxx11.abi.value> <cxx.flags/> <CUDA_STATIC_RUNTIME>OFF</CUDA_STATIC_RUNTIME> <PER_THREAD_DEFAULT_STREAM>OFF</PER_THREAD_DEFAULT_STREAM> <cudf.classifier.cuda>cuda10-2</cudf.classifier.cuda> </properties> <dependencies> <dependency> <groupId>ai.rapids</groupId> <artifactId>cudf</artifactId> <classifier>${cudf.classifier.cuda}</classifier> <version>${project.version}</version> </dependency> <dependency> <groupId>ai.rapids</groupId> <artifactId>cudf</artifactId> <classifier>tests</classifier> <version>${project.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.9</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-params</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.9</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.25.0</version> <scope>test</scope> </dependency> </dependencies> <profiles> <profile> <id>abiOff</id> <properties> <cxx11.abi.value>OFF</cxx11.abi.value> </properties> </profile> <profile> <id>no-cxx-deprecation-warnings</id> <properties> <cxx.flags>-Wno-deprecated-declarations</cxx.flags> </properties> </profile> <profile> <id>release</id> <distributionManagement> <snapshotRepository> <id>ossrh</id> <url>https://oss.sonatype.org/content/repositories/snapshots</url> </snapshotRepository> </distributionManagement> <properties> <gpg.passphrase>${GPG_PASSPHRASE}</gpg.passphrase> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>2.2.1</version> <executions> <execution> <id>attach-sources</id> <goals> <goal>jar-no-fork</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.9.1</version> <executions> <execution> <id>attach-javadocs</id> <goals> <goal>jar</goal> </goals> <configuration> <additionalparam>-Xdoclint:none</additionalparam> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-gpg-plugin</artifactId> <version>1.5</version> <executions> <execution> <id>sign-artifacts</id> <phase>verify</phase> <goals> <goal>sign</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.sonatype.plugins</groupId> <artifactId>nexus-staging-maven-plugin</artifactId> <version>1.6.7</version> <extensions>true</extensions> <configuration> <serverId>ossrh</serverId> <nexusUrl>https://oss.sonatype.org/</nexusUrl> <autoReleaseAfterClose>false</autoReleaseAfterClose> </configuration> </plugin> </plugins> </build> </profile> </profiles> <build> <resources> <resource> <!-- Include the properties file to provide the build information. --> <directory>${project.build.directory}/extra-resources</directory> <filtering>true</filtering> </resource> <resource> <directory>${basedir}/..</directory> <targetPath>META-INF</targetPath> <includes> <include>LICENSE</include> </includes> </resource> <resource> <directory>${basedir}</directory> <targetPath>META-INF</targetPath> <includes> <include>LICENSE-bundled</include> </includes> </resource> <resource> <directory>${basedir}/target/native-deps/</directory> </resource> </resources> <pluginManagement> <plugins> <plugin> <groupId>org.codehaus.gmaven</groupId> <artifactId>gmaven-plugin</artifactId> <version>1.5</version> </plugin> <plugin> <artifactId>maven-exec-plugin</artifactId> <version>1.6.0</version> </plugin> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <plugin> <artifactId>maven-resources-plugin</artifactId> <!-- downgrade version so symlinks are followed --> <version>2.6</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.0</version> <dependencies> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-surefire-provider</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.2.0</version> </dependency> </dependencies> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>2.22.0</version> </plugin> <plugin> <artifactId>maven-jar-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> <plugin> <artifactId>maven-site-plugin</artifactId> <version>3.7.1</version> </plugin> <plugin> <artifactId>maven-project-info-reports-plugin</artifactId> <version>3.0.0</version> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <artifactId>maven-antrun-plugin</artifactId> <executions> <execution> <id>cmake</id> <phase>validate</phase> <configuration> <tasks> <mkdir dir="${native.build.path}"/> <exec dir="${native.build.path}" failonerror="true" executable="cmake"> <arg value="${basedir}/src/main/native"/> <arg value="-DCUDA_STATIC_RUNTIME=${CUDA_STATIC_RUNTIME}" /> <arg value="-DPER_THREAD_DEFAULT_STREAM=${PER_THREAD_DEFAULT_STREAM}" /> <arg value="-DCMAKE_CXX11_ABI=${cxx11.abi.value}"/> <arg value="-DCMAKE_CXX_FLAGS=${cxx.flags}"/> </exec> <exec dir="${native.build.path}" failonerror="true" executable="make"> <arg value="-j16"/> </exec> <mkdir dir="${project.build.directory}/extra-resources"/> <exec executable="bash" output="${project.build.directory}/extra-resources/cuspatial-java-version-info.properties"> <arg value="${project.basedir}/buildscripts/build-info"/> <arg value="${project.version}"/> </exec> </tasks> </configuration> <goals> <goal>run</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.gmaven</groupId> <artifactId>gmaven-plugin</artifactId> <executions> <execution> <id>setproperty</id> <phase>validate</phase> <goals> <goal>execute</goal> </goals> <configuration> <source> def sout = new StringBuffer(), serr = new StringBuffer() //This only works on linux def proc = 'ldd ${native.build.path}/libcuspatialjni.so'.execute() proc.consumeProcessOutput(sout, serr) proc.waitForOrKill(10000) def libcuspatial = ~/libcuspatial\\.so\\s+=>\\s+(.*)libcuspatial.*\\.so\\s+.*/ def cuspatialm = libcuspatial.matcher(sout) if (cuspatialm.find()) { pom.properties['native.cuspatial.path'] = cuspatialm.group(1) } else { fail("Could not find cuspatial as a dependency of libcuspatialjni out> $sout err> $serr") } def libcudart = ~/libcudart\\.so\\.(.*)\\s+=>.*/ def cm = libcudart.matcher(sout) if (cm.find()) { if (pom.properties['CUDA_STATIC_RUNTIME'] == 'ON') { fail("found libcudart when we expect to be statically linked to it") } def classifier = 'cuda' + cm.group(1) .replaceFirst(/\\./, '-') // First . becomes a - .replaceAll(/\\..*$/, '') // Drop all of the subversions from cuda .replaceAll(/-0$/, '') // If it is a X.0 version, like 10.0 drop the .0 pom.properties['cuda.classifier'] = classifier println 'WARNING FOUND libcudart this means your jar will only work against a single version of the cuda runtime ' + classifier } else if (pom.properties['CUDA_STATIC_RUNTIME'] == 'OFF') { fail('could not find libcudart when we expect to be dynamically linked to it') } else { pom.properties['cuda.classifier'] = '' } if (pom.properties['CUDA_STATIC_RUNTIME'] == 'ON') { println 'WARNING RUNNING WITH STATIC LINKING DOES NOT FULLY WORK. USE WITH CAUTION.' } </source> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <!--Set by groovy script--> <classifier>${cuda.classifier}</classifier> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <!-- you can turn this off, by passing -DtrimStackTrace=true when running tests --> <trimStackTrace>false</trimStackTrace> <redirectTestOutputToFile>true</redirectTestOutputToFile> <systemPropertyVariables> <ai.rapids.refcount.debug>${ai.rapids.refcount.debug}</ai.rapids.refcount.debug> </systemPropertyVariables> </configuration> </plugin> <plugin> <artifactId>maven-resources-plugin</artifactId> <executions> <execution> <id>copy-native-libs</id> <phase>validate</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <overwrite>true</overwrite> <skip>${skipNativeCopy}</skip> <outputDirectory>${basedir}/target/native-deps/${os.arch}/${os.name}</outputDirectory> <resources> <resource> <directory>${native.build.path}</directory> <includes> <include>libcuspatialjni.so</include> </includes> </resource> <resource> <!--Set by groovy script--> <directory>${native.cuspatial.path}</directory> <includes> <include>libcuspatial.so</include> </includes> </resource> </resources> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>
0
rapidsai_public_repos/cuspatial/java
rapidsai_public_repos/cuspatial/java/dev/cudf_java_styles.xml
<code_scheme name="cudf_java" version="173"> <JavaCodeStyleSettings> <option name="JD_ADD_BLANK_AFTER_DESCRIPTION" value="false" /> </JavaCodeStyleSettings> <codeStyleSettings language="JAVA"> <option name="RIGHT_MARGIN" value="100" /> <option name="KEEP_SIMPLE_BLOCKS_IN_ONE_LINE" value="true" /> <option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" /> <option name="KEEP_SIMPLE_LAMBDAS_IN_ONE_LINE" value="true" /> <option name="KEEP_SIMPLE_CLASSES_IN_ONE_LINE" value="true" /> <option name="KEEP_MULTIPLE_EXPRESSIONS_IN_ONE_LINE" value="true" /> <option name="WRAP_LONG_LINES" value="true" /> <indentOptions> <option name="INDENT_SIZE" value="2" /> <option name="CONTINUATION_INDENT_SIZE" value="4" /> <option name="TAB_SIZE" value="2" /> </indentOptions> <arrangement> <groups /> </arrangement> </codeStyleSettings> </code_scheme>
0
rapidsai_public_repos/cuspatial/java/src/main/java/ai/rapids
rapidsai_public_repos/cuspatial/java/src/main/java/ai/rapids/cuspatial/CuSpatialNativeDepsLoader.java
/* * Copyright (c) 2020, 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. */ package ai.rapids.cuspatial; import ai.rapids.cudf.NativeDepsLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class will load the native dependencies. */ public class CuSpatialNativeDepsLoader extends NativeDepsLoader { private static final Logger log = LoggerFactory.getLogger(CuSpatialNativeDepsLoader.class); private static boolean loaded = false; private static final String[] loadOrder = new String[] { "cuspatial", "cuspatialjni" }; static synchronized void loadCuSpatialNativeDeps() { if (!loaded) { try { loadNativeDeps(); loadNativeDeps(loadOrder); loaded = true; } catch (Throwable t) { log.error("Could not load ...", t); } } } }
0
rapidsai_public_repos/cuspatial/java/src/main/java/ai/rapids
rapidsai_public_repos/cuspatial/java/src/main/java/ai/rapids/cuspatial/CuSpatialException.java
/* * Copyright (c) 2020, 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. */ package ai.rapids.cuspatial; /** * Exception thrown by cuspatial itself. */ public class CuSpatialException extends RuntimeException { CuSpatialException(String message) { super(message); } CuSpatialException(String message, Throwable cause) { super(message, cause); } }
0
rapidsai_public_repos/cuspatial/java/src/main/java/ai/rapids
rapidsai_public_repos/cuspatial/java/src/main/java/ai/rapids/cuspatial/Pair.java
/* * * Copyright (c) 2020, 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. * */ package ai.rapids.cuspatial; import java.util.AbstractMap; public class Pair<T1 extends AutoCloseable, T2 extends AutoCloseable> extends AbstractMap.SimpleEntry<T1, T2> implements AutoCloseable { public Pair(T1 l, T2 r) { super(l, r); } public T1 getLeft() { return getKey(); } public T2 getRight() { return getValue(); } @Override public synchronized void close() throws Exception { this.getLeft().close(); this.getRight().close(); } }
0
rapidsai_public_repos/cuspatial/java/src/main/java/ai/rapids
rapidsai_public_repos/cuspatial/java/src/main/java/ai/rapids/cuspatial/CuSpatial.java
/* * * Copyright (c) 2020, 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. * */ package ai.rapids.cuspatial; import ai.rapids.cudf.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; public final class CuSpatial { private static final Logger log = LoggerFactory.getLogger(CuSpatial.class); static { CuSpatialNativeDepsLoader.loadCuSpatialNativeDeps(); } /** * Compute haversine distances between points in set A to the corresponding points in set B. * * https://en.wikipedia.org/wiki/Haversine_formula * * @param aLon: longitude of points in set A * @param aLat: latitude of points in set A * @param bLon: longitude of points in set B * @param bLat: latitude of points in set B * NOTE: As for radius of the sphere on which the points reside, default value 6371.0 is used (aprx. radius * of earth in km) * NOTE: Default `device_memory_resource` is used for allocating the output ColumnVector * * @return array of distances for all (aLon[i], aLat[i]) and (bLon[i], bLat[i]) point pairs */ public static ColumnVector haversineDistance(ColumnVector aLon, ColumnVector aLat, ColumnVector bLon, ColumnVector bLat) { return new ColumnVector(haversineDistanceImpl(aLon.getNativeView(), aLat.getNativeView(), bLon.getNativeView(), bLat.getNativeView())); } /** * Find all points (x,y) that fall within a rectangular query window. * * A point (x, y) is in the window if `x > window_min_x && x < window_min_y && y > window_min_y && y * < window_max_y`. * * Swaps `window_min_x` and `window_max_x` if `window_min_x > window_max_x`. * Swaps `window_min_y` and `window_max_y` if `window_min_y > window_max_y`. * * @param windowMinX lower x-coordinate of the query window * @param windowMaxX upper x-coordinate of the query window * @param windowMinY lower y-coordinate of the query window * @param windowMaxY upper y-coordinate of the query window * @param x x-coordinates of points to be queried * @param y y-coordinates of points to be queried * NOTE: Default `device_memory_resource` is used for allocating the output table * * @return A table with two columns of the same type as the input columns. Columns 0, 1 are the * (x, y) coordinates of the points in the input that fall within the query window. */ public static Table pointsInSpatialWindow(double windowMinX, double windowMaxX, double windowMinY, double windowMaxY, ColumnVector x, ColumnVector y) { return new Table(pointsInSpatialWindowImpl(windowMinX, windowMaxX, windowMinY, windowMaxY, x.getNativeView(), y.getNativeView())); } /** * Derive trajectories from object ids, points, and timestamps. * * Groups the input object ids to determine unique trajectories. Returns a * table with the trajectory ids, the number of objects in each trajectory, * and the offset position of the first object for each trajectory in the * input object ids column. * * @param objectId column of object (e.g., vehicle) ids * @param x coordinates (in kilometers) * @param y coordinates (in kilometers) * @param timestamp column of timestamps in any resolution * NOTE: Default `device_memory_resource` is used for allocating the output * * @throws CuSpatialException containing cuspatial::logic_error If objectId isn't cudf::type_id::INT32 * @throws CuSpatialException containing cuspatial::logic_error If x and y are different types * @throws CuSpatialException containing cuspatial::logic_error If timestamp isn't a cudf::TIMESTAMP type * @throws CuSpatialException containing cuspatial::logic_error If objectId, x, y, or timestamp contain nulls * @throws CuSpatialException containing cuspatial::logic_error If objectId, x, y, and timestamp are different * sizes * * @return a Pair<ai.rapids.cudf.Table, ai.rapids.cudf.ColumnVector>. * 1. Pair.left is a table of these columns (object_id, x, y, timestamp) sorted by (object_id, timestamp) * 2. Pair.right is a column of type int32 for start positions for each trajectory's first object */ public static Pair<Table, ColumnVector> deriveTrajectories(ColumnVector objectId, ColumnVector x, ColumnVector y, ColumnVector timestamp) { long[] columnAddressArray = deriveTrajectoriesImpl(objectId.getNativeView(), x.getNativeView(), y.getNativeView(), timestamp.getNativeView()); long[] tableColumns = Arrays.copyOfRange(columnAddressArray, 0, columnAddressArray.length - 1); long indexColumn = columnAddressArray[columnAddressArray.length - 1]; return new Pair<>(new Table(tableColumns), new ColumnVector(indexColumn)); } /** * Compute the distance and speed of objects in a trajectory. Groups the * timestamp, x, and y, columns by object id to determine unique trajectories, * then computes the average distance and speed for all routes in each * trajectory. * NOTE: Assumes objectId, timestamp, x, y presorted by (objectId, timestamp). * * @param numTrajectories number of trajectories (unique object ids) * @param objectId column of object (e.g., vehicle) ids * @param x coordinates (in kilometers) * @param y coordinates (in kilometers) * @param timestamp column of timestamps in any resolution * NOTE: Default `device_memory_resource` is used for allocating the output table * * @throws CuSpatialException containing cuspatial::logic_error If objectId isn't cudf::type_id::INT32 * @throws CuSpatialException containing cuspatial::logic_error If x and y are different types * @throws CuSpatialException containing cuspatial::logic_error If timestamp isn't a cudf::TIMESTAMP type * @throws CuSpatialException containing cuspatial::logic_error If objectId, x, y, or timestamp contain nulls * @throws CuSpatialException containing cuspatial::logic_error If objectId, x, y, and timestamp are different * sizes * * @return a table of distances (meters) and speeds (meters/second) whose * length is `numTrajectories`, sorted by objectId. */ public static Table trajectoryDistancesAndSpeeds(int numTrajectories, ColumnVector objectId, ColumnVector x, ColumnVector y, ColumnVector timestamp) { long[] columnAddressArray = trajectoryDistancesAndSpeedsImpl(numTrajectories, objectId.getNativeView(), x.getNativeView(), y.getNativeView(), timestamp.getNativeView()); return new Table(columnAddressArray); } /** * Compute the spatial bounding boxes of trajectories. Groups the x, y, * and timestamp columns by object id to determine unique trajectories, then * computes the minimum bounding box to contain all routes in each trajectory. * * NOTE: Assumes objectId, timestamp, x, y presorted by (objectId, timestamp). * * @param numTrajectories number of trajectories (unique object ids) * @param objectId column of object (e.g., vehicle) ids * @param x coordinates (in kilometers) * @param y coordinates (in kilometers) * NOTE: Default `device_memory_resource` is used for allocating the output table * * @throws CuSpatialException containing cuspatial::logic_error If objectId isn't cudf::type_id::INT32 * @throws CuSpatialException containing cuspatial::logic_error If x and y are different types * @throws CuSpatialException containing cuspatial::logic_error If objectId, x, or y contain nulls * @throws CuSpatialException containing cuspatial::logic_error If objectId, x, and y are different sizes * * @return a table of bounding boxes with length `numTrajectories` and * four columns: * xMin - the minimum x-coordinate of each bounding box in kilometers * yMin - the minimum y-coordinate of each bounding box in kilometers * xMax - the maximum x-coordinate of each bounding box in kilometers * yMax - the maximum y-coordinate of each bounding box in kilometers */ public static Table trajectoryBoundingBoxes(int numTrajectories, ColumnVector objectId, ColumnVector x, ColumnVector y) { long[] columnAddressArray = trajectoryBoundingBoxesImpl(numTrajectories, objectId.getNativeView(), x.getNativeView(), y.getNativeView()); return new Table(columnAddressArray); } /** * Tests whether the specified points are inside any of the specified polygons. * * Tests whether points are inside at most 31 polygons. Polygons are a collection of one or more * rings. Rings are a collection of three or more vertices. * * @param testPointsX: x-coordinates of points to test * @param testPointsY: y-coordinates of points to test * @param polyOffsets: beginning index of the first ring in each polygon * @param polyRingOffsets: beginning index of the first point in each ring * @param polyPointsX: x-coordinates of polygon points * @param polyPointsY: y-coordinates of polygon points * * @return A column of INT32 containing one element per input point. Each bit (except the sign bit) * represents a hit or miss for each of the input polygons in least-significant-bit order. i.e. * `output[3] & 0b0010` indicates a hit or miss for the 3rd point against the 2nd polygon. * * NOTE: Limit 31 polygons per call. Polygons may contain multiple rings. * * NOTE: Direction of rings does not matter. * * NOTE: This algorithm supports the ESRI shapefile format, but assumes all polygons are "clean" (as * defined by the format), and does _not_ verify whether the input adheres to the shapefile format. * * NOTE: Overlapping rings negate each other. This behavior is not limited to a single negation, * allowing for "islands" within the same polygon. * * poly w/two rings poly w/four rings * +-----------+ +------------------------+ * :███████████: :████████████████████████: * :███████████: :██+------------------+██: * :██████+----:------+ :██: +----+ +----+ :██: * :██████: :██████: :██: :████: :████: :██: * +------;----+██████: :██: :----: :----: :██: * :███████████: :██+------------------+██: * :███████████: :████████████████████████: * +-----------+ +------------------------+ */ public static ColumnVector pointInPolygon(ColumnVector testPointsX, ColumnVector testPointsY, ColumnVector polyOffsets, ColumnVector polyRingOffsets, ColumnVector polyPointsX, ColumnVector polyPointsY) { return new ColumnVector(pointInPolygonImpl(testPointsX.getNativeView(), testPointsY.getNativeView(), polyOffsets.getNativeView(), polyRingOffsets.getNativeView(), polyPointsX.getNativeView(), polyPointsY.getNativeView())); } /** * Translates lon/lat relative to origin and converts to cartesian (x/y) coordinates. * * @param originLon: longitude of origin * @param originLat: latitude of origin * @param inputLon: longitudes to transform * @param inputLat: latitudes to transform * * @return a pair of columns containing cartesian coordinates in kilometers */ public static Pair<ColumnVector, ColumnVector> lonlatToCartesian(double originLon, double originLat, ColumnVector inputLon, ColumnVector inputLat) { long[] columnAddressArray = lonlatToCartesianImpl(originLon, originLat, inputLon.getNativeView(), inputLat.getNativeView()); long left = columnAddressArray[0]; long right = columnAddressArray[1]; return new Pair<>(new ColumnVector(left), new ColumnVector(right)); } ///////////////////////////////////////////////////////////////////////////// // NATIVE APIs ///////////////////////////////////////////////////////////////////////////// private static native long haversineDistanceImpl(long aLonViewHandle, long aLatViewHandle, long bLonViewHandle, long bLatViewHandle); private static native long[] pointsInSpatialWindowImpl(double windowMinX, double windowMaxX, double windowMinY, double windowMaxY, long xViewHandle, long yViewHandle); private static native long[] deriveTrajectoriesImpl(long objectIdViewHandle, long xViewHandle, long yViewHandle, long timestampViewHandle); private static native long[] trajectoryDistancesAndSpeedsImpl(int numTrajectories, long objectIdViewHandle, long xViewHandle, long yViewHandle, long timestampViewHandle); private static native long[] trajectoryBoundingBoxesImpl(int numTrajectories, long objectIdViewHandle, long xViewHandle, long yViewHandle); private static native long pointInPolygonImpl(long testPointsXViewHandle, long testPointsYViewHandle, long polyOffsetsViewHandle, long polyRingOffsetsViewHandle, long polyPointsXViewHandle, long polyPointsYViewHandle); private static native long[] lonlatToCartesianImpl(double originLon, double originLat, long inputLonViewHandle, long inputLatViewHandle); }
0
rapidsai_public_repos/cuspatial/java/src/main
rapidsai_public_repos/cuspatial/java/src/main/native/CMakeLists.txt
#============================================================================= # Copyright (c) 2019-2020, 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) include(../../../../fetch_rapids.cmake) # TODO: The logic for setting the architectures was previously not here. Was # that just an oversight, or is there a reason not to include this here? rapids_cuda_init_architectures(CUSPATIAL_JNI) project(CUDF_JNI VERSION 0.7.0 LANGUAGES C CXX CUDA) ################################################################################################### # - build type ------------------------------------------------------------------------------------ # Set a default build type if none was specified rapids_cmake_build_type("Release") ################################################################################################### # - compiler options ------------------------------------------------------------------------------ set(CMAKE_CXX_STANDARD 17) set(CMAKE_C_COMPILER $ENV{CC}) set(CMAKE_CXX_COMPILER $ENV{CXX}) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CUDA_STANDARD 17) set(CMAKE_CUDA_STANDARD_REQUIRED ON) if(CMAKE_COMPILER_IS_GNUCXX) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror -Wno-error=deprecated-declarations") option(CMAKE_CXX11_ABI "Enable the GLIBCXX11 ABI" ON) if(CMAKE_CXX11_ABI) message(STATUS "CUDF: Enabling the GLIBCXX11 ABI") else() message(STATUS "CUDF: Disabling the GLIBCXX11 ABI") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D_GLIBCXX_USE_CXX11_ABI=0") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D_GLIBCXX_USE_CXX11_ABI=0") set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Xcompiler -D_GLIBCXX_USE_CXX11_ABI=0") endif() endif() #set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -gencode=arch=compute_60,code=sm_60 -gencode=arch=compute_61,code=sm_61") set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -gencode=arch=compute_60,code=sm_60") set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -gencode=arch=compute_70,code=sm_70 -gencode=arch=compute_70,code=compute_70") set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} --expt-extended-lambda --expt-relaxed-constexpr") # set warnings as errors # TODO: remove `no-maybe-uninitialized` used to suppress warnings in rmm::exec_policy set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -Werror cross-execution-space-call -Xcompiler -Wall,-Werror,-Wno-error=deprecated-declarations") # Option to enable line info in CUDA device compilation to allow introspection when profiling / memchecking option(CMAKE_CUDA_LINEINFO "Enable the -lineinfo option for nvcc (useful for cuda-memcheck / profiler" OFF) if (CMAKE_CUDA_LINEINFO) set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -lineinfo") endif() # Debug options if(CMAKE_BUILD_TYPE MATCHES Debug) message(STATUS "Building with debugging flags") set(CMAKE_CUDA_FLAGS "${CMAKE_CUDA_FLAGS} -G -Xcompiler -rdynamic") endif() option(BUILD_TESTS "Configure CMake to build tests" ON) ################################################################################################### # - cudart options -------------------------------------------------------------------------------- # cudart can be statically linked or dynamically linked. The python ecosystem wants dynamic linking option(CUDA_STATIC_RUNTIME "Statically link the CUDA runtime" OFF) if(CUDA_STATIC_RUNTIME) message(STATUS "Enabling static linking of cudart") set(CUDART_LIBRARY "cudart_static") else() set(CUDART_LIBRARY "cudart") endif() ################################################################################################### # - cmake modules --------------------------------------------------------------------------------- set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules/" ${CMAKE_MODULE_PATH}) include(FeatureSummary) include(CheckIncludeFiles) include(CheckLibraryExists) ################################################################################################### # - Thrust/CUB/libcudacxx ------------------------------------------------------------------------------------ find_path(LIBCUDACXX_INCLUDE "simt" HINTS "$ENV{CONDA_PREFIX}/include/libcudf/libcudacxx" "$ENV{CUDF_HOME}/cpp/build/_deps/libcudacxx-src/include") message(STATUS "CUDACXX: LIBCUDACXX_INCLUDE set to ${LIBCUDACXX_INCLUDE}") ################################################################################################### # - RMM ------------------------------------------------------------------------------------------- find_path(RMM_INCLUDE "rmm" HINTS "$ENV{CONDA_PREFIX}/include" "$ENV{CONDA_PREFIX}/include/rmm" "$ENV{RMM_HOME}/include") find_library(RMM_LIBRARY "rmm" HINTS "$ENV{CONDA_PREFIX}/lib" "$ENV{RMM_HOME}/build") message(STATUS "RMM: RMM_INCLUDE set to ${RMM_INCLUDE}") message(STATUS "RMM: RMM_LIBRARY set to ${RMM_LIBRARY}") add_library(rmm SHARED IMPORTED ${RMM_LIBRARY}) if (RMM_INCLUDE AND RMM_LIBRARY) set_target_properties(rmm PROPERTIES IMPORTED_LOCATION ${RMM_LIBRARY}) endif (RMM_INCLUDE AND RMM_LIBRARY) ################################################################################################### # - CUDF ------------------------------------------------------------------------------------------ set(CUDF_INCLUDE "$ENV{CONDA_PREFIX}/include" "$ENV{CUDF_HOME}/java/src/main/native/include") find_library(CUDF_LIBRARY "cudf" HINTS "$ENV{CONDA_PREFIX}/lib" "$ENV{CUDF_HOME}/cpp/build") message(STATUS "CUDF: CUDF_INCLUDE set to ${CUDF_INCLUDE}") message(STATUS "CUDF: CUDF_LIBRARY set to ${CUDF_LIBRARY}") add_library(cudf SHARED IMPORTED ${CUDF_LIBRARY}) if (CUDF_INCLUDE AND CUDF_LIBRARY) set_target_properties(cudf PROPERTIES IMPORTED_LOCATION ${CUDF_LIBRARY}) endif (CUDF_INCLUDE AND CUDF_LIBRARY) ################################################################################################### # - CUSPATIAL ------------------------------------------------------------------------------------------ set(CUSPATIAL_INCLUDE "$ENV{CUSPATIAL_HOME}/cpp/include") find_library(CUSPATIAL_LIBRARY "cuspatial" HINTS "$ENV{CUSPATIAL_HOME}/cpp/build") message(STATUS "CUSPATIAL: CUSPATIAL_INCLUDE set to ${CUSPATIAL_INCLUDE}") message(STATUS "CUSPATIAL: CUSPATIAL_LIBRARY set to ${CUSPATIAL_LIBRARY}") add_library(cuspatial SHARED IMPORTED ${CUSPATIAL_LIBRARY}) if (CUSPATIAL_INCLUDE AND CUSPATIAL_LIBRARY) set_target_properties(cuspatial PROPERTIES IMPORTED_LOCATION ${CUSPATIAL_LIBRARY}) endif (CUSPATIAL_INCLUDE AND CUSPATIAL_LIBRARY) ################################################################################################### # - find JNI ------------------------------------------------------------------------------------- find_package(JNI REQUIRED) if(JNI_FOUND) message(STATUS "JDK with JNI in ${JNI_INCLUDE_DIRS}") else() message(FATAL_ERROR "JDK with JNI not found, please check your settings.") endif() ################################################################################################### # - include paths --------------------------------------------------------------------------------- include_directories("${CMAKE_SOURCE_DIR}/include" "${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES}" "${LIBCUDACXX_INCLUDE}" "${RMM_INCLUDE}" "${CUDF_INCLUDE}" "${CUSPATIAL_INCLUDE}" "${JNI_INCLUDE_DIRS}") ################################################################################################### # - library paths --------------------------------------------------------------------------------- link_directories("${CMAKE_BINARY_DIR}/lib" "${CUSPATIAL_LIBRARY}") ################################################################################################### # - library targets ------------------------------------------------------------------------------- set(SOURCE_FILES "src/cuSpatialJni.cpp") add_library(cuspatialjni SHARED ${SOURCE_FILES}) #Override RPATH for cuspatialjni SET_TARGET_PROPERTIES(cuspatialjni PROPERTIES BUILD_RPATH "\$ORIGIN") ################################################################################################### # - build options --------------------------------------------------------------------------------- option(USE_NVTX "Build with NVTX support" ON) if(USE_NVTX) message(STATUS "Using Nvidia Tools Extension") find_library(NVTX_LIBRARY nvToolsExt PATH ${CMAKE_CUDA_IMPLICIT_LINK_DIRECTORIES}) target_link_libraries(cuspatialjni ${NVTX_LIBRARY}) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DUSE_NVTX") endif() option(PER_THREAD_DEFAULT_STREAM "Build with per-thread default stream" OFF) if(PER_THREAD_DEFAULT_STREAM) message(STATUS "Using per-thread default stream") add_compile_definitions(CUDA_API_PER_THREAD_DEFAULT_STREAM) endif() ################################################################################################### # - link libraries -------------------------------------------------------------------------------- target_link_libraries(cuspatialjni cuspatial)
0
rapidsai_public_repos/cuspatial/java/src/main
rapidsai_public_repos/cuspatial/java/src/main/native/clang-format.README
README ====== To apply code formatting to a file you are working on, currently you can do this manually using clang-format-7: This will edit the file, and print to stdout: clang-format [file] This will edit the file in place, do this if you are sure of what you are doing: clang-format -i [file]
0
rapidsai_public_repos/cuspatial/java/src/main
rapidsai_public_repos/cuspatial/java/src/main/native/.clang-format
--- # Reference: https://clang.llvm.org/docs/ClangFormatStyleOptions.html Language: Cpp # BasedOnStyle: LLVM # no indentation (-2 from indent, which is 2) AccessModifierOffset: -2 AlignAfterOpenBracket: Align # int aaaa = 12; # int b = 23; # int ccc = 23; # leaving OFF AlignConsecutiveAssignments: false # int aaaa = 12; # float b = 23; # std::string ccc = 23; # leaving OFF AlignConsecutiveDeclarations: false ##define A \ # int aaaa; \ # int b; \ # int dddddddddd; # leaving ON AlignEscapedNewlines: Right # int aaa = bbbbbbbbbbbbbbb + # ccccccccccccccc; # leaving ON AlignOperands: true # true: false: # int a; // My comment a vs. int a; // My comment a # int b = 2; // comment b int b = 2; // comment about b # leaving ON AlignTrailingComments: true # squeezes a long declaration's arguments to the next line: #true: #void myFunction( # int a, int b, int c, int d, int e); # #false: #void myFunction(int a, # int b, # int c, # int d, # int e); # leaving ON AllowAllParametersOfDeclarationOnNextLine: true # changed to ON, as we use short blocks on same lines AllowShortBlocksOnASingleLine: true # set this to ON, we use this in a few places AllowShortCaseLabelsOnASingleLine: true # set this to ON AllowShortFunctionsOnASingleLine: Inline AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false # Deprecated option. # PenaltyReturnTypeOnItsOwnLine applies, as we set this to None, # where it tries to break after the return type automatically AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false AlwaysBreakTemplateDeclarations: MultiLine # if all the arguments for a function don't fit in a single line, # with a value of "false", it'll split each argument into different lines BinPackArguments: true BinPackParameters: true # if this is set to Custom, the BraceWrapping flags apply BreakBeforeBraces: Custom BraceWrapping: AfterClass: false AfterControlStatement: false AfterEnum: false AfterFunction: false AfterNamespace: false AfterObjCDeclaration: false AfterStruct: false AfterUnion: false AfterExternBlock: false BeforeCatch: false BeforeElse: false IndentBraces: false SplitEmptyFunction: false SplitEmptyRecord: false SplitEmptyNamespace: false # will break after operators when a line is too long BreakBeforeBinaryOperators: None # not in docs.. so that's nice BreakBeforeInheritanceComma: false # This will break inheritance list and align on colon, # it also places each inherited class in a different line. # Leaving ON BreakInheritanceList: BeforeColon # #true: #veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription # ? firstValue # : SecondValueVeryVeryVeryVeryLong; # #false: #veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ? # firstValue : # SecondValueVeryVeryVeryVeryLong; BreakBeforeTernaryOperators: false BreakConstructorInitializersBeforeComma: false BreakConstructorInitializers: BeforeColon BreakAfterJavaFieldAnnotations: true BreakStringLiterals: true # So the line lengths in cudf are not following a limit, at the moment. # Usually it's a long comment that makes the line length inconsistent. # Command I used to find max line lengths (from cpp directory): # find include src tests|grep "\." |xargs -I{} bash -c "awk '{print length}' {} | sort -rn | head -1"|sort -n # I picked 100, as it seemed somewhere around median ColumnLimit: 100 # TODO: not aware of any of these at this time CommentPragmas: '^ IWYU pragma:' # So it doesn't put subsequent namespaces in the same line CompactNamespaces: false ConstructorInitializerAllOnOneLineOrOnePerLine: false ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 # TODO: adds spaces around the element list # in initializer: vector<T> x{ {}, ..., {} } Cpp11BracedListStyle: true DerivePointerAlignment: false DisableFormat: false ExperimentalAutoDetectBinPacking: false # } // namespace a => useful FixNamespaceComments: true ForEachMacros: - foreach - Q_FOREACH - BOOST_FOREACH IncludeBlocks: Regroup IncludeCategories: - Regex: '<[[:alnum:]]+>' Priority: 0 - Regex: '<[[:alnum:].]+>' Priority: 1 - Regex: '<.*>' Priority: 2 - Regex: '.*/.*' Priority: 3 - Regex: '.*' Priority: 4 # if a header matches this in an include group, it will be moved up to the # top of the group. IncludeIsMainRegex: '(Test)?$' IndentCaseLabels: true IndentPPDirectives: None IndentWidth: 2 IndentWrappedFunctionNames: false JavaScriptQuotes: Leave JavaScriptWrapImports: true KeepEmptyLinesAtTheStartOfBlocks: true MacroBlockBegin: '' MacroBlockEnd: '' MaxEmptyLinesToKeep: 1 NamespaceIndentation: None ObjCBinPackProtocolList: Auto ObjCBlockIndentWidth: 2 ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: true # Penalties: leaving unchanged for now # https://stackoverflow.com/questions/26635370/in-clang-format-what-do-the-penalties-do PenaltyBreakAssignment: 2 PenaltyBreakBeforeFirstCallParameter: 19 PenaltyBreakComment: 300 PenaltyBreakFirstLessLess: 120 PenaltyBreakString: 1000 PenaltyBreakTemplateDeclaration: 10 PenaltyExcessCharacter: 1000000 # As currently set, we don't see return types being # left on their own line, leaving at 60 PenaltyReturnTypeOnItsOwnLine: 60 # char* foo vs char *foo, picking Right aligned PointerAlignment: Right ReflowComments: true # leaving ON, but this could be something to turn OFF SortIncludes: true SortUsingDeclarations: true SpaceAfterCStyleCast: false SpaceAfterTemplateKeyword: true SpaceBeforeAssignmentOperators: true SpaceBeforeCpp11BracedList: false SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true SpaceBeforeParens: ControlStatements SpaceBeforeRangeBasedForLoopColon: true SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 1 SpacesInAngles: false SpacesInContainerLiterals: true SpacesInCStyleCastParentheses: false SpacesInParentheses: false SpacesInSquareBrackets: false Standard: Cpp11 TabWidth: 8 UseTab: Never ...
0
rapidsai_public_repos/cuspatial/java/src/main/native
rapidsai_public_repos/cuspatial/java/src/main/native/src/cuSpatialJni.cpp
/* * Copyright (c) 2020, 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 <cudf/table/table.hpp> #include "cuspatial/coordinate_transform.hpp" #include "cuspatial/hausdorff.hpp" #include "cuspatial/haversine.hpp" #include "cuspatial/point_in_polygon.hpp" #include "cuspatial/spatial_window.hpp" #include "cuspatial/trajectory.hpp" #include "jni_utils.hpp" constexpr char const *CUSPATIAL_ERROR_CLASS = "ai/rapids/cuspatial/CuSpatialException"; // java class package path #define CATCH_STD_CUSPATIAL(env, ret_val) CATCH_STD_CLASS(env, CUSPATIAL_ERROR_CLASS, ret_val) /** * Take a table returned by some operation and turn it into an array of column* so we can track them * ourselves in java instead of having their life tied to the table. * @param table_result the table to convert for return * @param extra_columns columns not in the table that will be added to the result at the end. */ static jlongArray convert_table_for_return(JNIEnv *env, std::unique_ptr<cudf::table> &table_result, std::vector<std::unique_ptr<cudf::column>> &extra_columns) { std::vector<std::unique_ptr<cudf::column>> ret = table_result->release(); int table_cols = ret.size(); int num_columns = table_cols + extra_columns.size(); cudf::jni::native_jlongArray outcol_handles(env, num_columns); for (int i = 0; i < table_cols; i++) { outcol_handles[i] = reinterpret_cast<jlong>(ret[i].release()); } for (int i = 0; i < extra_columns.size(); i++) { outcol_handles[i + table_cols] = reinterpret_cast<jlong>(extra_columns[i].release()); } return outcol_handles.get_jArray(); } namespace { jlongArray convert_table_for_return(JNIEnv *env, std::unique_ptr<cudf::table> &table_result) { std::vector<std::unique_ptr<cudf::column>> extra; return convert_table_for_return(env, table_result, extra); } jlongArray convert_columns_for_return(JNIEnv *env, std::vector<std::unique_ptr<cudf::column>> &columns) { int num_columns = columns.size(); cudf::jni::native_jlongArray outcol_handles(env, num_columns); for (int i = 0; i < num_columns; i++) { outcol_handles[i] = reinterpret_cast<jlong>(columns[i].release()); } return outcol_handles.get_jArray(); } } // anonymous namespace extern "C" { //////// // Native methods for cuspatial/haversine.hpp //////// JNIEXPORT jlong JNICALL Java_ai_rapids_cuspatial_CuSpatial_haversineDistanceImpl( JNIEnv *env, jclass clazz, jlong a_lon_view_handle, jlong a_lat_view_handle, jlong b_lon_view_handle, jlong b_lat_view_handle) { JNI_NULL_CHECK(env, a_lon_view_handle, "input column_view a_lon is null", 0); JNI_NULL_CHECK(env, a_lat_view_handle, "input column_view a_lat is null", 0); JNI_NULL_CHECK(env, b_lon_view_handle, "input column_view b_lon is null", 0); JNI_NULL_CHECK(env, b_lat_view_handle, "input column_view b_lat is null", 0); using cudf::column; using cudf::column_view; try { column_view *a_lon_column_view = reinterpret_cast<column_view *>(a_lon_view_handle); column_view *a_lat_column_view = reinterpret_cast<column_view *>(a_lat_view_handle); column_view *b_lon_column_view = reinterpret_cast<column_view *>(b_lon_view_handle); column_view *b_lat_column_view = reinterpret_cast<column_view *>(b_lat_view_handle); std::unique_ptr<column> result = cuspatial::haversine_distance( *a_lon_column_view, *a_lat_column_view, *b_lon_column_view, *b_lat_column_view); return reinterpret_cast<jlong>(result.release()); } CATCH_STD_CUSPATIAL(env, 0); } //////// // Native methods for cuspatial/hausdorff.hpp //////// JNIEXPORT jlong JNICALL Java_ai_rapids_cuspatial_CuSpatial_directedHausdorffDistanceImpl( JNIEnv *env, jclass clazz, jlong xs_view_handle, jlong ys_view_handle, jlong points_per_space_view_handle) { JNI_NULL_CHECK(env, xs_view_handle, "input column_view xs is null", 0); JNI_NULL_CHECK(env, ys_view_handle, "input column_view ys is null", 0); JNI_NULL_CHECK(env, points_per_space_view_handle, "input column_view points_per_space is null", 0); using cudf::column; using cudf::column_view; try { column_view *xs_column_view = reinterpret_cast<column_view *>(xs_view_handle); column_view *ys_column_view = reinterpret_cast<column_view *>(ys_view_handle); column_view *points_per_space_column_view = reinterpret_cast<column_view *>(points_per_space_view_handle); std::unique_ptr<column> result = cuspatial::directed_hausdorff_distance( *xs_column_view, *ys_column_view, *points_per_space_column_view); return reinterpret_cast<jlong>(result.release()); } CATCH_STD_CUSPATIAL(env, 0); } //////// // Native methods for cuspatial/spatial_window.hpp //////// JNIEXPORT jlongArray JNICALL Java_ai_rapids_cuspatial_CuSpatial_pointsInSpatialWindowImpl( JNIEnv *env, jclass clazz, jdouble window_min_x, jdouble window_max_x, jdouble window_min_y, jdouble window_max_y, jlong x_view_handle, jlong y_view_handle) { JNI_NULL_CHECK(env, x_view_handle, "input column_view points_x is null", 0); JNI_NULL_CHECK(env, y_view_handle, "input column_view points_y is null", 0); using cudf::column; using cudf::column_view; using cudf::table; try { column_view *x_column_view = reinterpret_cast<column_view *>(x_view_handle); column_view *y_column_view = reinterpret_cast<column_view *>(y_view_handle); std::unique_ptr<table> result = cuspatial::points_in_spatial_window( window_min_x, window_max_x, window_min_y, window_max_y, *x_column_view, *y_column_view); return convert_table_for_return(env, result); } CATCH_STD_CUSPATIAL(env, NULL); } //////// // Native methods for cuspatial/trajectory.hpp //////// JNIEXPORT jlongArray JNICALL Java_ai_rapids_cuspatial_CuSpatial_deriveTrajectoriesImpl( JNIEnv *env, jclass clazz, jlong object_id_view_handle, jlong x_view_handle, jlong y_view_handle, jlong timestamp_view_handle) { JNI_NULL_CHECK(env, object_id_view_handle, "input column_view object_id is null", 0); JNI_NULL_CHECK(env, x_view_handle, "input column_view x is null", 0); JNI_NULL_CHECK(env, y_view_handle, "input column_view y is null", 0); JNI_NULL_CHECK(env, timestamp_view_handle, "input column_view timestamp is null", 0); using cudf::column; using cudf::column_view; try { column_view *object_id_column_view = reinterpret_cast<column_view *>(object_id_view_handle); column_view *x_column_view = reinterpret_cast<column_view *>(x_view_handle); column_view *y_column_view = reinterpret_cast<column_view *>(y_view_handle); column_view *timestamp_column_view = reinterpret_cast<column_view *>(timestamp_view_handle); std::pair<std::unique_ptr<cudf::table>, std::unique_ptr<cudf::column>> result = cuspatial::derive_trajectories(*object_id_column_view, *x_column_view, *y_column_view, *timestamp_column_view); std::vector<std::unique_ptr<cudf::column>> extra; extra.emplace_back(std::move(result.second)); return convert_table_for_return(env, result.first, extra); } CATCH_STD_CUSPATIAL(env, 0); } JNIEXPORT jlongArray JNICALL Java_ai_rapids_cuspatial_CuSpatial_trajectoryDistancesAndSpeedsImpl( JNIEnv *env, jclass clazz, jint num_trajectories, jlong object_id_view_handle, jlong x_view_handle, jlong y_view_handle, jlong timestamp_view_handle) { JNI_NULL_CHECK(env, object_id_view_handle, "input column_view object_id is null", 0); JNI_NULL_CHECK(env, x_view_handle, "input column_view x is null", 0); JNI_NULL_CHECK(env, y_view_handle, "input column_view y is null", 0); JNI_NULL_CHECK(env, timestamp_view_handle, "input column_view timestamp is null", 0); using cudf::column; using cudf::column_view; using cudf::table; try { cudf::size_type num_trajectories_int32 = reinterpret_cast<cudf::size_type>(num_trajectories); column_view *object_id_column_view = reinterpret_cast<column_view *>(object_id_view_handle); column_view *x_column_view = reinterpret_cast<column_view *>(x_view_handle); column_view *y_column_view = reinterpret_cast<column_view *>(y_view_handle); column_view *timestamp_column_view = reinterpret_cast<column_view *>(timestamp_view_handle); std::unique_ptr<table> result = cuspatial::trajectory_distances_and_speeds( num_trajectories_int32, *object_id_column_view, *x_column_view, *y_column_view, *timestamp_column_view); return convert_table_for_return(env, result); } CATCH_STD_CUSPATIAL(env, NULL); } JNIEXPORT jlongArray JNICALL Java_ai_rapids_cuspatial_CuSpatial_trajectoryBoundingBoxesImpl( JNIEnv *env, jclass clazz, jint num_trajectories, jlong object_id_view_handle, jlong x_view_handle, jlong y_view_handle) { JNI_NULL_CHECK(env, object_id_view_handle, "input column_view object_id is null", 0); JNI_NULL_CHECK(env, x_view_handle, "input column_view x is null", 0); JNI_NULL_CHECK(env, y_view_handle, "input column_view y is null", 0); using cudf::column; using cudf::column_view; using cudf::table; try { cudf::size_type num_trajectories_int32 = reinterpret_cast<cudf::size_type>(num_trajectories); column_view *object_id_column_view = reinterpret_cast<column_view *>(object_id_view_handle); column_view *x_column_view = reinterpret_cast<column_view *>(x_view_handle); column_view *y_column_view = reinterpret_cast<column_view *>(y_view_handle); std::unique_ptr<table> result = cuspatial::trajectory_bounding_boxes( num_trajectories_int32, *object_id_column_view, *x_column_view, *y_column_view); return convert_table_for_return(env, result); } CATCH_STD_CUSPATIAL(env, NULL); } //////// // Native methods for cuspatial/point_in_polygon.hpp //////// JNIEXPORT jlong JNICALL Java_ai_rapids_cuspatial_CuSpatial_pointInPolygonImpl( JNIEnv *env, jclass clazz, jlong test_points_x_view_handle, jlong test_points_y_view_handle, jlong poly_offsets_view_handle, jlong poly_ring_offsets_view_handle, jlong poly_points_x_view_handle, jlong poly_points_y_view_handle) { JNI_NULL_CHECK(env, test_points_x_view_handle, "input column_view test_points_x is null", 0); JNI_NULL_CHECK(env, test_points_y_view_handle, "input column_view test_points_y is null", 0); JNI_NULL_CHECK(env, poly_offsets_view_handle, "input column_view poly_offsets is null", 0); JNI_NULL_CHECK(env, poly_ring_offsets_view_handle, "input column_view poly_ring_offsets is null", 0); JNI_NULL_CHECK(env, poly_points_x_view_handle, "input column_view poly_points_x is null", 0); JNI_NULL_CHECK(env, poly_points_y_view_handle, "input column_view poly_points_y is null", 0); using cudf::column; using cudf::column_view; try { column_view *test_points_x_column_view = reinterpret_cast<column_view *>(test_points_x_view_handle); column_view *test_points_y_column_view = reinterpret_cast<column_view *>(test_points_y_view_handle); column_view *poly_offsets_column_view = reinterpret_cast<column_view *>(poly_offsets_view_handle); column_view *poly_ring_offsets_column_view = reinterpret_cast<column_view *>(poly_ring_offsets_view_handle); column_view *poly_points_x_column_view = reinterpret_cast<column_view *>(poly_points_x_view_handle); column_view *poly_points_y_column_view = reinterpret_cast<column_view *>(poly_points_y_view_handle); std::unique_ptr<column> result = cuspatial::point_in_polygon( *test_points_x_column_view, *test_points_y_column_view, *poly_offsets_column_view, *poly_ring_offsets_column_view, *poly_points_x_column_view, *poly_points_y_column_view); return reinterpret_cast<jlong>(result.release()); } CATCH_STD_CUSPATIAL(env, 0); } //////// // Native methods for cuspatial/coordinate_transform.hpp //////// JNIEXPORT jlongArray JNICALL Java_ai_rapids_cuspatial_CuSpatial_lonlatToCartesianImpl( JNIEnv *env, jclass clazz, jdouble origin_lon, jdouble origin_lat, jlong input_lon_view_handle, jlong input_lat_view_handle) { JNI_NULL_CHECK(env, input_lon_view_handle, "input column_view input_lon is null", 0); JNI_NULL_CHECK(env, input_lat_view_handle, "input column_view input_lat is null", 0); using cudf::column; using cudf::column_view; try { column_view *input_lon_column_view = reinterpret_cast<column_view *>(input_lon_view_handle); column_view *input_lat_column_view = reinterpret_cast<column_view *>(input_lat_view_handle); std::pair<std::unique_ptr<cudf::column>, std::unique_ptr<cudf::column>> result = cuspatial::sinusoidal_projection(origin_lon, origin_lat, *input_lon_column_view, *input_lat_column_view); std::vector<std::unique_ptr<cudf::column>> columns; columns.emplace_back(std::move(result.first)); columns.emplace_back(std::move(result.second)); return convert_columns_for_return(env, columns); } CATCH_STD_CUSPATIAL(env, NULL); } } // extern "C"
0
rapidsai_public_repos/cuspatial/java/src/test/java/ai/rapids
rapidsai_public_repos/cuspatial/java/src/test/java/ai/rapids/cuspatial/CuSpatialTest.java
/* * * Copyright (c) 2020, 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. * */ package ai.rapids.cuspatial; import ai.rapids.cudf.*; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.function.Supplier; import java.util.stream.IntStream; import static ai.rapids.cudf.QuantileMethod.HIGHER; import static ai.rapids.cudf.QuantileMethod.LINEAR; import static ai.rapids.cudf.QuantileMethod.LOWER; import static ai.rapids.cudf.QuantileMethod.MIDPOINT; import static ai.rapids.cudf.QuantileMethod.NEAREST; import static ai.rapids.cudf.TableTest.assertColumnsAreEqual; import static ai.rapids.cudf.TableTest.assertTablesAreEqual; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; public class CuSpatialTest extends CudfTestBase { @Test void testHaversine() { try ( ColumnVector aLon = ColumnVector.fromDoubles(-180, 180); ColumnVector aLat = ColumnVector.fromDoubles(0, 30); ColumnVector bLon = ColumnVector.fromDoubles(180, -180); ColumnVector bLat = ColumnVector.fromDoubles(0, 30); ColumnVector result = CuSpatial.haversineDistance(aLon, aLat, bLon, bLat); ColumnVector expected = ColumnVector.fromDoubles(1.5604449514735574e-12, 1.3513849691832763e-12) ) { assertColumnsAreEqual(expected, result); } } @Test void testPointsInSpatialWindow() { double windowMinX = 1.5; double windowMaxX = 5.5; double windowMinY = 1.5; double windowMaxY = 5.5; try ( ColumnVector pointsX = ColumnVector.fromDoubles(1.0, 2.0, 3.0, 5.0, 7.0, 1.0, 2.0, 3.0, 6.0, 0.0, 3.0, 6.0); ColumnVector pointsY = ColumnVector.fromDoubles(0.0, 1.0, 2.0, 3.0, 1.0, 3.0, 5.0, 6.0, 5.0, 4.0, 7.0, 4.0); Table result = CuSpatial.pointsInSpatialWindow(windowMinX, windowMaxX, windowMinY, windowMaxY, pointsX, pointsY); ColumnVector expectedPointsX = ColumnVector.fromDoubles(3.0, 5.0, 2.0); ColumnVector expectedPointsY = ColumnVector.fromDoubles(2.0, 3.0, 5.0); ) { assertColumnsAreEqual(expectedPointsX, result.getColumn(0)); assertColumnsAreEqual(expectedPointsY, result.getColumn(1)); } } @Test void testDeriveTrajectories() throws Exception { try ( ColumnVector objectId = ColumnVector.fromInts(1, 2, 3, 4); ColumnVector timestamp = ColumnVector.timestampSecondsFromLongs(0000000000001L, 2000000000000L, 2000000000001L, 2000000000002L); ColumnVector pointsX = ColumnVector.fromDoubles(1.0, 2.0, 3.0, 5.0); ColumnVector pointsY = ColumnVector.fromDoubles(0.0, 1.0, 2.0, 3.0); Pair<Table, ColumnVector> result = CuSpatial.deriveTrajectories(objectId, pointsX, pointsY, timestamp) ) { Table resultTable = result.getLeft(); ColumnVector resultColumn = result.getRight(); } } @Test void testDeriveTrajectoriesThrowsException() { assertThrows(CuSpatialException.class, () -> { try ( ColumnVector objectId = ColumnVector.fromInts(1, 2, 3, 4); ColumnVector timestamp = ColumnVector.timestampSecondsFromLongs(0000000000001L, 2000000000000L, 2000000000001L, 2000000000002L); ColumnVector pointsX = ColumnVector.fromDoubles(1.0, 2.0, 3.0, 5.0, 3.0);//size mismatch ColumnVector pointsY = ColumnVector.fromDoubles(0.0, 1.0, 2.0, 3.0); Pair<Table, ColumnVector> result = CuSpatial.deriveTrajectories(objectId, pointsX, pointsY, timestamp) ) {} }); } @Test void testTrajectoryDistancesAndSpeeds() { int numTrajectories = 4; try ( ColumnVector objectId = ColumnVector.fromInts(1, 2, 3, 4); ColumnVector timestamp = ColumnVector.timestampSecondsFromLongs(0000000000001L, 2000000000000L, 2000000000001L, 2000000000002L); ColumnVector pointsX = ColumnVector.fromDoubles(1.0, 2.0, 3.0, 5.0); ColumnVector pointsY = ColumnVector.fromDoubles(0.0, 1.0, 2.0, 3.0); Table result = CuSpatial.trajectoryDistancesAndSpeeds(numTrajectories, objectId, pointsX, pointsY, timestamp) ) { } } @Test void testTrajectoryBoundingBoxes() { int numTrajectories = 4; try ( ColumnVector objectId = ColumnVector.fromInts(1, 2, 3, 4); ColumnVector pointsX = ColumnVector.fromDoubles(1.0, 2.0, 3.0, 5.0); ColumnVector pointsY = ColumnVector.fromDoubles(0.0, 1.0, 2.0, 3.0); Table result = CuSpatial.trajectoryBoundingBoxes(numTrajectories, objectId, pointsX, pointsY) ) { } } @Test void testPointInPolygonOnePolygonOneRing() { try ( ColumnVector testPointX = ColumnVector.fromDoubles(-2.0, 2.0, 0.0, 0.0, -0.5, 0.5, 0.0, 0.0); ColumnVector testPointY = ColumnVector.fromDoubles(0.0, 0.0, -2.0, 2.0, 0.0, 0.0, -0.5, 0.5); ColumnVector polyOffsets = ColumnVector.fromInts(0); ColumnVector polyRingOffsets = ColumnVector.fromInts(0); ColumnVector polyPointX = ColumnVector.fromDoubles(-1.0, -1.0, 1.0, 1.0, -1.0); ColumnVector polyPointY = ColumnVector.fromDoubles(-1.0, 1.0, 1.0, -1.0, -1.0); ColumnVector result = CuSpatial.pointInPolygon(testPointX, testPointY, polyOffsets, polyRingOffsets, polyPointX, polyPointY); ColumnVector expected = ColumnVector.fromInts(0, 0, 0, 0, 1, 1, 1, 1) ) { assertColumnsAreEqual(expected, result); } } @Test void testPointInPolygonTwoPolygonsOneRingEach() { try ( ColumnVector testPointX = ColumnVector.fromDoubles(-2.0, 2.0, 0.0, 0.0, -0.5, 0.5, 0.0, 0.0); ColumnVector testPointY = ColumnVector.fromDoubles(0.0, 0.0, -2.0, 2.0, 0.0, 0.0, -0.5, 0.5); ColumnVector polyOffsets = ColumnVector.fromInts(0, 1); ColumnVector polyRingOffsets = ColumnVector.fromInts(0, 5); ColumnVector polyPointX = ColumnVector.fromDoubles(-1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 0.0, -1.0, 0.0, 1.0); ColumnVector polyPointY = ColumnVector.fromDoubles(-1.0, -1.0, 1.0, 1.0, -1.0, 0.0, 1.0, 0.0, -1.0, 0.0); ColumnVector result = CuSpatial.pointInPolygon(testPointX, testPointY, polyOffsets, polyRingOffsets, polyPointX, polyPointY); ColumnVector expected = ColumnVector.fromInts(0b00, 0b00, 0b00, 0b00, 0b11, 0b11, 0b11, 0b11) ) { assertColumnsAreEqual(expected, result); } } @Test void testLonlatToCartesianMultiple() { double cameraLon = -90.66511046; double cameraLat = 42.49197018; try { try ( ColumnVector pointLon = ColumnVector.fromDoubles(-90.664973, -90.665393, -90.664976, -90.664537); ColumnVector pointLat = ColumnVector.fromDoubles(42.493894, 42.491520, 42.491420, 42.493823); Pair<ColumnVector, ColumnVector> result = CuSpatial.lonlatToCartesian(cameraLon, cameraLat, pointLon, pointLat); ColumnVector expectedPointsX = ColumnVector.fromDoubles(-0.01126195531216838, 0.02314864865181343, -0.01101638630252916, -0.04698301003584082); ColumnVector expectedPointsY = ColumnVector.fromDoubles(-0.21375777777718794, 0.05002000000015667, 0.06113111111163663, -0.20586888888847929); ) { assertColumnsAreEqual(expectedPointsX, result.getLeft()); assertColumnsAreEqual(expectedPointsY, result.getRight()); } } catch (Exception e) { e.printStackTrace(); } } }
0
rapidsai_public_repos/cuspatial/java/src/test/java/ai/rapids
rapidsai_public_repos/cuspatial/java/src/test/java/ai/rapids/cuspatial/CuSpatialTestNativeDepsLoader.java
/* * Copyright (c) 2020, 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. */ package ai.rapids.cuspatial; import ai.rapids.cudf.NativeDepsLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class will load the native dependencies. */ public class CuSpatialTestNativeDepsLoader extends NativeDepsLoader { private static final Logger log = LoggerFactory.getLogger(CuSpatialTestNativeDepsLoader.class); private static boolean loaded = false; private static final String[] loadOrder = new String[] { "cuspatialtestutils" }; static synchronized void loadCuSpatialTestNativeDeps() { if (!loaded) { try { loadNativeDeps(loadOrder); loaded = true; } catch (Throwable t) { log.error("Could not load ...", t); } } } }
0
rapidsai_public_repos/cuspatial/java
rapidsai_public_repos/cuspatial/java/buildscripts/build-info
#!/usr/bin/env bash # # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # 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. # # This script generates the build info. # Arguments: # version - The current version of cudf java code echo_build_properties() { echo version=$1 echo user=$USER echo revision=$(git rev-parse HEAD) echo branch=$(git rev-parse --abbrev-ref HEAD) echo date=$(date -u +%Y-%m-%dT%H:%M:%SZ) echo url=$(git config --get remote.origin.url) } echo_build_properties $1
0
rapidsai_public_repos/cuspatial/conda
rapidsai_public_repos/cuspatial/conda/environments/all_cuda-120_arch-x86_64.yaml
# This file is generated by `rapids-dependency-file-generator`. # To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. channels: - rapidsai - rapidsai-nightly - conda-forge - nvidia dependencies: - c-compiler - clang-tools=16.0.6 - cmake>=3.26.4 - cuda-cudart-dev - cuda-cupti-dev - cuda-nvcc - cuda-nvrtc-dev - cuda-version=12.0 - cudf==23.12.* - cuml==23.12.* - cupy>=12.0.0 - curl - cxx-compiler - cython>=3.0.0 - doxygen - gcc_linux-64=11.* - geopandas>=0.11.0 - gmock>=1.13.0 - gtest>=1.13.0 - ipython - ipywidgets - libcudf==23.12.* - librmm==23.12.* - myst-parser - nbsphinx - ninja - notebook - numpydoc - pre-commit - proj - pydata-sphinx-theme!=0.14.2 - pydeck - pytest - pytest-cov - pytest-xdist - python>=3.9,<3.11 - rmm==23.12.* - scikit-build>=0.13.1 - scikit-image - setuptools - shapely - sphinx<6 - sqlite - sysroot_linux-64==2.17 name: all_cuda-120_arch-x86_64
0
rapidsai_public_repos/cuspatial/conda
rapidsai_public_repos/cuspatial/conda/environments/all_cuda-118_arch-x86_64.yaml
# This file is generated by `rapids-dependency-file-generator`. # To make changes, edit ../../dependencies.yaml and run `rapids-dependency-file-generator`. channels: - rapidsai - rapidsai-nightly - conda-forge - nvidia dependencies: - c-compiler - clang-tools=16.0.6 - cmake>=3.26.4 - cuda-version=11.8 - cudatoolkit - cudf==23.12.* - cuml==23.12.* - cupy>=12.0.0 - curl - cxx-compiler - cython>=3.0.0 - doxygen - gcc_linux-64=11.* - geopandas>=0.11.0 - gmock>=1.13.0 - gtest>=1.13.0 - ipython - ipywidgets - libcudf==23.12.* - librmm==23.12.* - myst-parser - nbsphinx - ninja - notebook - numpydoc - nvcc_linux-64=11.8 - pre-commit - proj - pydata-sphinx-theme!=0.14.2 - pydeck - pytest - pytest-cov - pytest-xdist - python>=3.9,<3.11 - rmm==23.12.* - scikit-build>=0.13.1 - scikit-image - setuptools - shapely - sphinx<6 - sqlite - sysroot_linux-64==2.17 name: all_cuda-118_arch-x86_64
0
rapidsai_public_repos/cuspatial/conda/recipes
rapidsai_public_repos/cuspatial/conda/recipes/cuproj/conda_build_config.yaml
c_compiler_version: - 11 cxx_compiler_version: - 11 cuda_compiler: - cuda-nvcc cuda11_compiler: - nvcc sysroot_version: - "2.17" cmake_version: - ">=3.26.4"
0
rapidsai_public_repos/cuspatial/conda/recipes
rapidsai_public_repos/cuspatial/conda/recipes/cuproj/build.sh
# Copyright (c) 2023, NVIDIA CORPORATION. # This assumes the script is executed from the root of the repo directory ./build.sh cuproj
0
rapidsai_public_repos/cuspatial/conda/recipes
rapidsai_public_repos/cuspatial/conda/recipes/cuproj/meta.yaml
# Copyright (c) 2018-2023, NVIDIA CORPORATION. {% set version = environ['RAPIDS_PACKAGE_VERSION'].lstrip('v') %} {% set minor_version = version.split('.')[0] + '.' + version.split('.')[1] %} {% set cuda_version = '.'.join(environ['RAPIDS_CUDA_VERSION'].split('.')[:2]) %} {% set cuda_major = cuda_version.split('.')[0] %} {% set py_version = environ['CONDA_PY'] %} {% set date_string = environ['RAPIDS_DATE_STRING'] %} package: name: cuproj version: {{ version }} source: path: ../../.. build: number: {{ GIT_DESCRIBE_NUMBER }} string: cuda{{ cuda_major }}_py{{ py_version }}_{{ date_string }}_{{ GIT_DESCRIBE_HASH }}_{{ GIT_DESCRIBE_NUMBER }} script_env: - AWS_ACCESS_KEY_ID - AWS_SECRET_ACCESS_KEY - AWS_SESSION_TOKEN - CMAKE_C_COMPILER_LAUNCHER - CMAKE_CUDA_COMPILER_LAUNCHER - CMAKE_CXX_COMPILER_LAUNCHER - CMAKE_GENERATOR - PARALLEL_LEVEL - SCCACHE_BUCKET - SCCACHE_IDLE_TIMEOUT - SCCACHE_REGION - SCCACHE_S3_KEY_PREFIX=cuproj-aarch64 # [aarch64] - SCCACHE_S3_KEY_PREFIX=cuproj-linux64 # [linux64] - SCCACHE_S3_USE_SSL - SCCACHE_S3_NO_CREDENTIALS ignore_run_exports_from: {% if cuda_major == "11" %} - {{ compiler('cuda11') }} {% endif %} requirements: build: - {{ compiler('c') }} - {{ compiler('cxx') }} {% if cuda_major == "11" %} - {{ compiler('cuda11') }} ={{ cuda_version }} {% else %} - {{ compiler('cuda') }} {% endif %} - cuda-version ={{ cuda_version }} - ninja - sysroot_{{ target_platform }} {{ sysroot_version }} host: - cuda-version ={{ cuda_version }} - cmake {{ cmake_version }} - cython >=0.29,<0.30 - python - rmm ={{ minor_version }} - scikit-build >=0.13.1 - setuptools - proj - sqlite run: {% if cuda_major == "11" %} - cudatoolkit {% endif %} - {{ pin_compatible('cuda-version', max_pin='x', min_pin='x') }} - python - rmm ={{ minor_version }} - cupy>=12.0.0 test: # [linux64] imports: # [linux64] - cuproj # [linux64] requires: - cupy>=12.0.0 - cuspatial ={{ minor_version }} - rmm ={{ minor_version }} about: home: https://rapids.ai/ license: Apache-2.0 license_family: Apache license_file: LICENSE summary: cuProj GPU Geographic Projection Library for Python
0
rapidsai_public_repos/cuspatial/conda/recipes
rapidsai_public_repos/cuspatial/conda/recipes/libcuspatial/conda_build_config.yaml
c_compiler_version: - 11 cxx_compiler_version: - 11 cuda_compiler: - cuda-nvcc cuda11_compiler: - nvcc cmake_version: - ">=3.26.4" gtest_version: - ">=1.13.0" sysroot_version: - "2.17"
0
rapidsai_public_repos/cuspatial/conda/recipes
rapidsai_public_repos/cuspatial/conda/recipes/libcuspatial/install_libcuspatial.sh
#!/bin/bash # Copyright (c) 2022, NVIDIA CORPORATION. cmake --install cpp/build
0
rapidsai_public_repos/cuspatial/conda/recipes
rapidsai_public_repos/cuspatial/conda/recipes/libcuspatial/build.sh
# Copyright (c) 2018-2023, NVIDIA CORPORATION. # build cuspatial with verbose output ./build.sh -v libcuspatial tests benchmarks --allgpuarch -n \ --cmake-args=\"-DNVBench_ENABLE_CUPTI=OFF\"
0
rapidsai_public_repos/cuspatial/conda/recipes
rapidsai_public_repos/cuspatial/conda/recipes/libcuspatial/meta.yaml
# Copyright (c) 2018-2023, NVIDIA CORPORATION. {% set version = environ['RAPIDS_PACKAGE_VERSION'].lstrip('v') %} {% set minor_version = version.split('.')[0] + '.' + version.split('.')[1] %} {% set cuda_version = '.'.join(environ['RAPIDS_CUDA_VERSION'].split('.')[:2]) %} {% set cuda_major = cuda_version.split('.')[0] %} {% set date_string = environ['RAPIDS_DATE_STRING'] %} package: name: libcuspatial-split source: path: ../../.. build: script_env: - AWS_ACCESS_KEY_ID - AWS_SECRET_ACCESS_KEY - AWS_SESSION_TOKEN - CMAKE_C_COMPILER_LAUNCHER - CMAKE_CUDA_COMPILER_LAUNCHER - CMAKE_CXX_COMPILER_LAUNCHER - CMAKE_GENERATOR - PARALLEL_LEVEL - SCCACHE_BUCKET - SCCACHE_IDLE_TIMEOUT - SCCACHE_REGION - SCCACHE_S3_KEY_PREFIX=libcuspatial-aarch64 # [aarch64] - SCCACHE_S3_KEY_PREFIX=libcuspatial-linux64 # [linux64] - SCCACHE_S3_USE_SSL - SCCACHE_S3_NO_CREDENTIALS requirements: build: - {{ compiler('c') }} - {{ compiler('cxx') }} {% if cuda_major == "11" %} - {{ compiler('cuda11') }} ={{ cuda_version }} {% else %} - {{ compiler('cuda') }} {% endif %} - cuda-version ={{ cuda_version }} - cmake {{ cmake_version }} - ninja - sysroot_{{ target_platform }} {{ sysroot_version }} host: - cuda-version ={{ cuda_version }} - doxygen - gmock {{ gtest_version }} - gtest {{ gtest_version }} - libcudf ={{ minor_version }} - librmm ={{ minor_version }} - sqlite - proj outputs: - name: libcuspatial version: {{ version }} script: install_libcuspatial.sh build: number: {{ GIT_DESCRIBE_NUMBER }} string: cuda{{ cuda_major }}_{{ date_string }}_{{ GIT_DESCRIBE_HASH }}_{{ GIT_DESCRIBE_NUMBER }} run_exports: - {{ pin_subpackage("libcuspatial", max_pin="x.x") }} requirements: build: - cmake {{ cmake_version }} host: - cuda-version ={{ cuda_version }} {% if cuda_major == "11" %} - cudatoolkit {% else %} - cuda-cudart-dev {% endif %} run: - {{ pin_compatible('cuda-version', max_pin='x', min_pin='x') }} {% if cuda_major == "11" %} - cudatoolkit {% endif %} - libcudf ={{ minor_version }} - librmm ={{ minor_version }} - sqlite - proj test: commands: - test -f $PREFIX/lib/libcuspatial.so about: home: https://rapids.ai/ license: Apache-2.0 license_family: Apache license_file: LICENSE summary: libcuspatial library - name: libcuspatial-tests version: {{ version }} script: install_libcuspatial_tests.sh build: number: {{ GIT_DESCRIBE_NUMBER }} string: cuda{{ cuda_major }}_{{ date_string }}_{{ GIT_DESCRIBE_HASH }}_{{ GIT_DESCRIBE_NUMBER }} requirements: build: - cmake {{ cmake_version }} host: - cuda-version ={{ cuda_version }} {% if cuda_major == "11" %} - cudatoolkit {% else %} - cuda-cudart-dev {% endif %} run: - {{ pin_subpackage('libcuspatial', exact=True) }} {% if cuda_major == "11" %} - cudatoolkit {% endif %} - {{ pin_compatible('cuda-version', max_pin='x', min_pin='x') }} - gmock {{ gtest_version }} - gtest {{ gtest_version }}
0
rapidsai_public_repos/cuspatial/conda/recipes
rapidsai_public_repos/cuspatial/conda/recipes/libcuspatial/install_libcuspatial_tests.sh
#!/bin/bash # Copyright (c) 2022, NVIDIA CORPORATION. cmake --install cpp/build --component testing
0
rapidsai_public_repos/cuspatial/conda/recipes
rapidsai_public_repos/cuspatial/conda/recipes/cuspatial/conda_build_config.yaml
c_compiler_version: - 11 cxx_compiler_version: - 11 cuda_compiler: - cuda-nvcc cuda11_compiler: - nvcc sysroot_version: - "2.17" cmake_version: - ">=3.26.4"
0
rapidsai_public_repos/cuspatial/conda/recipes
rapidsai_public_repos/cuspatial/conda/recipes/cuspatial/build.sh
# Copyright (c) 2018-2019, NVIDIA CORPORATION. # Ignore conda-provided CMAKE_ARGS for the Python build. unset CMAKE_ARGS # This assumes the script is executed from the root of the repo directory ./build.sh cuspatial
0
rapidsai_public_repos/cuspatial/conda/recipes
rapidsai_public_repos/cuspatial/conda/recipes/cuspatial/meta.yaml
# Copyright (c) 2018-2023, NVIDIA CORPORATION. {% set version = environ['RAPIDS_PACKAGE_VERSION'].lstrip('v') %} {% set minor_version = version.split('.')[0] + '.' + version.split('.')[1] %} {% set cuda_version = '.'.join(environ['RAPIDS_CUDA_VERSION'].split('.')[:2]) %} {% set cuda_major = cuda_version.split('.')[0] %} {% set py_version = environ['CONDA_PY'] %} {% set date_string = environ['RAPIDS_DATE_STRING'] %} package: name: cuspatial version: {{ version }} source: path: ../../.. build: number: {{ GIT_DESCRIBE_NUMBER }} string: cuda{{ cuda_major }}_py{{ py_version }}_{{ date_string }}_{{ GIT_DESCRIBE_HASH }}_{{ GIT_DESCRIBE_NUMBER }} script_env: - AWS_ACCESS_KEY_ID - AWS_SECRET_ACCESS_KEY - AWS_SESSION_TOKEN - CMAKE_C_COMPILER_LAUNCHER - CMAKE_CUDA_COMPILER_LAUNCHER - CMAKE_CXX_COMPILER_LAUNCHER - CMAKE_GENERATOR - PARALLEL_LEVEL - SCCACHE_BUCKET - SCCACHE_IDLE_TIMEOUT - SCCACHE_REGION - SCCACHE_S3_KEY_PREFIX=cuspatial-aarch64 # [aarch64] - SCCACHE_S3_KEY_PREFIX=cuspatial-linux64 # [linux64] - SCCACHE_S3_USE_SSL - SCCACHE_S3_NO_CREDENTIALS ignore_run_exports_from: {% if cuda_major == "11" %} - {{ compiler('cuda11') }} {% endif %} requirements: build: - {{ compiler('c') }} - {{ compiler('cxx') }} {% if cuda_major == "11" %} - {{ compiler('cuda11') }} ={{ cuda_version }} {% else %} - {{ compiler('cuda') }} {% endif %} - cuda-version ={{ cuda_version }} - ninja - sysroot_{{ target_platform }} {{ sysroot_version }} host: - cuda-version ={{ cuda_version }} - cmake {{ cmake_version }} - cudf ={{ minor_version }} - cython >=3.0.0 - libcuspatial ={{ version }} - python - rmm ={{ minor_version }} - scikit-build >=0.13.1 - setuptools run: {% if cuda_major == "11" %} - cudatoolkit {% endif %} - {{ pin_compatible('cuda-version', max_pin='x', min_pin='x') }} - cudf ={{ minor_version }} - geopandas >=0.11.0 - python - rmm ={{ minor_version }} test: # [linux64] imports: # [linux64] - cuspatial # [linux64] about: home: https://rapids.ai/ license: Apache-2.0 license_family: Apache license_file: LICENSE summary: cuSpatial GPU Spatial and Trajectory Data Management and Analytics Library
0
rapidsai_public_repos/cuspatial
rapidsai_public_repos/cuspatial/cpp/.clangd
# https://clangd.llvm.org/config # Apply a config conditionally to all C files If: PathMatch: .*\.(c|h)$ --- # Apply a config conditionally to all C++ files If: PathMatch: .*\.(c|h)pp --- # Apply a config conditionally to all CUDA files If: PathMatch: .*\.cuh? CompileFlags: Add: - "-x" - "cuda" # No error on unknown CUDA versions - "-Wno-unknown-cuda-version" # Allow variadic CUDA functions - "-Xclang=-fcuda-allow-variadic-functions" Diagnostics: Suppress: - "variadic_device_fn" - "attributes_not_allowed" --- # Tweak the clangd parse settings for all files CompileFlags: Add: # report all errors - "-ferror-limit=0" - "-fmacro-backtrace-limit=0" - "-ftemplate-backtrace-limit=0" # Skip the CUDA version check - "--no-cuda-version-check" Remove: # remove gcc's -fcoroutines - -fcoroutines # remove nvc++ flags unknown to clang - "-gpu=*" - "-stdpar*" # remove nvcc flags unknown to clang - "-arch*" - "-gencode*" - "--generate-code*" - "-ccbin*" - "-t=*" - "--threads*" - "-Xptxas*" - "-Xcudafe*" - "-Xfatbin*" - "-Xcompiler*" - "--diag-suppress*" - "--diag_suppress*" - "--compiler-options*" - "--expt-extended-lambda" - "--expt-relaxed-constexpr" - "-forward-unknown-to-host-compiler" - "-Werror=cross-execution-space-call"
0