diff --git a/ci/release/update-version.sh b/ci/release/update-version.sh index 0dc29801..cb1020ff 100755 --- a/ci/release/update-version.sh +++ b/ci/release/update-version.sh @@ -45,7 +45,6 @@ DEPENDENCIES=( dask-cuda dask-cudf cugraph - cuspatial ) for DEP in "${DEPENDENCIES[@]}"; do for FILE in dependencies.yaml conda/environments/*.yaml; do diff --git a/conda/environments/all_cuda-118_arch-aarch64.yaml b/conda/environments/all_cuda-118_arch-aarch64.yaml index 23f180aa..a2bd1994 100644 --- a/conda/environments/all_cuda-118_arch-aarch64.yaml +++ b/conda/environments/all_cuda-118_arch-aarch64.yaml @@ -13,7 +13,6 @@ dependencies: - cudf==25.6.*,>=0.0.0a0 - cugraph==25.6.*,>=0.0.0a0 - cupy>=12.0.0 -- cuspatial==25.6.*,>=0.0.0a0 - dask-cuda==25.6.*,>=0.0.0a0 - dask-cudf==25.6.*,>=0.0.0a0 - datashader>=0.15 diff --git a/conda/environments/all_cuda-118_arch-x86_64.yaml b/conda/environments/all_cuda-118_arch-x86_64.yaml index 766b12f9..e25d62ec 100644 --- a/conda/environments/all_cuda-118_arch-x86_64.yaml +++ b/conda/environments/all_cuda-118_arch-x86_64.yaml @@ -13,7 +13,6 @@ dependencies: - cudf==25.6.*,>=0.0.0a0 - cugraph==25.6.*,>=0.0.0a0 - cupy>=12.0.0 -- cuspatial==25.6.*,>=0.0.0a0 - dask-cuda==25.6.*,>=0.0.0a0 - dask-cudf==25.6.*,>=0.0.0a0 - datashader>=0.15 diff --git a/conda/environments/all_cuda-128_arch-aarch64.yaml b/conda/environments/all_cuda-128_arch-aarch64.yaml index 8106fc11..941e0566 100644 --- a/conda/environments/all_cuda-128_arch-aarch64.yaml +++ b/conda/environments/all_cuda-128_arch-aarch64.yaml @@ -12,7 +12,6 @@ dependencies: - cudf==25.6.*,>=0.0.0a0 - cugraph==25.6.*,>=0.0.0a0 - cupy>=12.0.0 -- cuspatial==25.6.*,>=0.0.0a0 - dask-cuda==25.6.*,>=0.0.0a0 - dask-cudf==25.6.*,>=0.0.0a0 - datashader>=0.15 diff --git a/conda/environments/all_cuda-128_arch-x86_64.yaml b/conda/environments/all_cuda-128_arch-x86_64.yaml index 22114330..70908541 100644 --- a/conda/environments/all_cuda-128_arch-x86_64.yaml +++ b/conda/environments/all_cuda-128_arch-x86_64.yaml @@ -12,7 +12,6 @@ dependencies: - cudf==25.6.*,>=0.0.0a0 - cugraph==25.6.*,>=0.0.0a0 - cupy>=12.0.0 -- cuspatial==25.6.*,>=0.0.0a0 - dask-cuda==25.6.*,>=0.0.0a0 - dask-cudf==25.6.*,>=0.0.0a0 - datashader>=0.15 diff --git a/conda/recipes/cuxfilter/recipe.yaml b/conda/recipes/cuxfilter/recipe.yaml index 527ba41d..0fb8d621 100644 --- a/conda/recipes/cuxfilter/recipe.yaml +++ b/conda/recipes/cuxfilter/recipe.yaml @@ -34,7 +34,6 @@ requirements: - ${{ pin_compatible("cuda-version", upper_bound="x", lower_bound="x") }} - cudf =${{ minor_version }} - cupy >=12.0.0 - - cuspatial =${{ minor_version }} - dask-cudf =${{ minor_version }} - datashader >=0.15 - geopandas >=0.11.0 diff --git a/dependencies.yaml b/dependencies.yaml index 27e795b0..225033b4 100644 --- a/dependencies.yaml +++ b/dependencies.yaml @@ -219,7 +219,6 @@ dependencies: packages: - &cudf_unsuffixed cudf==25.6.*,>=0.0.0a0 - cupy>=12.0.0 - - &cuspatial_unsuffixed cuspatial==25.6.*,>=0.0.0a0 - &dask_cudf_unsuffixed dask-cudf==25.6.*,>=0.0.0a0 - nodejs>=18 - libwebp-base @@ -232,7 +231,6 @@ dependencies: packages: - cudf-cu12==25.6.*,>=0.0.0a0 - &cupy_cu12 cupy-cuda12x>=12.0.0 - - cuspatial-cu12==25.6.*,>=0.0.0a0 - dask-cudf-cu12==25.6.*,>=0.0.0a0 - matrix: cuda: "12.*" @@ -242,7 +240,6 @@ dependencies: # NOTE: cupy still has a "-cuda12x" suffix here, because it's suffixed # in DLFW builds - *cupy_cu12 - - *cuspatial_unsuffixed - *dask_cudf_unsuffixed - matrix: cuda: "11.*" @@ -250,7 +247,6 @@ dependencies: packages: - cudf-cu11==25.6.*,>=0.0.0a0 - &cupy_cu11 cupy-cuda11x>=12.0.0 - - cuspatial-cu11==25.6.*,>=0.0.0a0 - dask-cudf-cu11==25.6.*,>=0.0.0a0 - matrix: cuda: "11.*" @@ -260,13 +256,11 @@ dependencies: # NOTE: cupy still has a "-cuda11x" suffix here, because it's suffixed # in DLFW builds - *cupy_cu11 - - *cuspatial_unsuffixed - *dask_cudf_unsuffixed - matrix: packages: - *cudf_unsuffixed - *cupy_cu11 - - *cuspatial_unsuffixed - *dask_cudf_unsuffixed test_python: common: @@ -283,7 +277,6 @@ dependencies: - coverage - *cudf_unsuffixed - cupy>=12.0.0 - - *cuspatial_unsuffixed - *dask_cudf_unsuffixed - cuxfilter==25.6.*,>=0.0.0a0 - python>=3.10,<3.13 diff --git a/notebooks/RAPIDS Visualization Guide/RAPIDS Viz Catalog.ipynb b/notebooks/RAPIDS Visualization Guide/RAPIDS Viz Catalog.ipynb index 32b627c0..f21dd33e 100644 --- a/notebooks/RAPIDS Visualization Guide/RAPIDS Viz Catalog.ipynb +++ b/notebooks/RAPIDS Visualization Guide/RAPIDS Viz Catalog.ipynb @@ -46,7 +46,7 @@ "source": [ "### GPU Accelerated Interaction\n", "\n", - "The below libraries directly use RAPIDS cuDF/Dask-cuDF and/or cuSpatial to create charts that support accelerated crossfiltering or rendering:\n", + "The below libraries directly use RAPIDS cuDF/Dask-cuDF to create charts that support accelerated crossfiltering or rendering:\n", "- **[Holoviews with Linked Brushing](https://holoviews.org/user_guide/Linked_Brushing.html?highlight=linked%20brushing)**\n", "- **[Datashader](https://datashader.org/user_guide/Performance.html)**\n", "- **[Plotly Dash with Holoviews](https://dash.plotly.com/holoviews#gpu-accelerating-datashader-and-linked-selections-with-rapids)**\n", diff --git a/notebooks/RAPIDS Visualization Guide/RAPIDS Viz Guide Notebook.ipynb b/notebooks/RAPIDS Visualization Guide/RAPIDS Viz Guide Notebook.ipynb index 0941fb67..b9710875 100644 --- a/notebooks/RAPIDS Visualization Guide/RAPIDS Viz Guide Notebook.ipynb +++ b/notebooks/RAPIDS Visualization Guide/RAPIDS Viz Guide Notebook.ipynb @@ -15,7 +15,7 @@ "source": [ "# RAPIDS Visualization Guide Notebook\n", "### A Streamlined Guide to RAPIDS Accelerated Visualization and Visual Analtyics\n", - "The guide will walk through using RAPIDS [cuDF](https://github.com/rapidsai/cudf), [cuSpatial](https://github.com/rapidsai/cuspatial), [cuML](https://github.com/rapidsai/cuml), [cuGraph](https://github.com/rapidsai/cugraph) and [cuxfilter](https://github.com/rapidsai/cuxfilter), with [hvPlot](https://hvplot.holoviz.org/), [Datashader](https://datashader.org/), and [Plotly Dash](https://github.com/plotly/dash) with the publicly available [Divvy Bike share dataset](https://divvybikes.com/system-data)." + "The guide will walk through using RAPIDS [cuDF](https://github.com/rapidsai/cudf), [cuML](https://github.com/rapidsai/cuml), [cuGraph](https://github.com/rapidsai/cugraph) and [cuxfilter](https://github.com/rapidsai/cuxfilter), with [hvPlot](https://hvplot.holoviz.org/), [Datashader](https://datashader.org/), and [Plotly Dash](https://github.com/plotly/dash) with the publicly available [Divvy Bike share dataset](https://divvybikes.com/system-data)." ] }, { @@ -69,7 +69,6 @@ " - cudf >= 23.06\n", " - cuml >= 23.06\n", " - cugraph >= 23.06\n", - " - cuspatial >= 23.06\n", " - cuxfilter >= 23.06\n", " - geoviews <= 1.9.6\n", " - cupy\n", @@ -103,7 +102,6 @@ "\n", "# rapids etc\n", "import cudf\n", - "import cuspatial\n", "import cugraph\n", "import cuml\n", "import cuxfilter\n", @@ -594,7 +592,7 @@ "id": "b04800a0-a1fc-443f-87a2-332e2b0ca6b7", "metadata": {}, "source": [ - "### Using cuSpatial" + "### Using cupy to calculate Haversine distance" ] }, { @@ -606,14 +604,29 @@ }, "outputs": [], "source": [ - "# Using cuSpatial, we can calculate distances from two points\n", - "# Create a cuSpatial GeoSeries from the latitude and longitude columns\n", - "start_points = cuspatial.GeoSeries.from_points_xy(df[['start_lng','start_lat']].interleave_columns().astype(\"float64\"))\n", - "end_points = cuspatial.GeoSeries.from_points_xy(df[['end_lng','end_lat']].interleave_columns().astype(\"float64\"))\n", + "def haversine_distance_cupy(lon1, lat1, lon2, lat2, earth_radius_km=6371.0):\n", + " \"\"\"\n", + " Calculate the Haversine distance between two sets of points.\n", + " \"\"\"\n", + " # Convert degrees to radians\n", + " lon1_rad = cupy.radians(lon1.values)\n", + " lat1_rad = cupy.radians(lat1.values)\n", + " lon2_rad = cupy.radians(lon2.values)\n", + " lat2_rad = cupy.radians(lat2.values)\n", + "\n", + " # Differences\n", + " dlon = lon2_rad - lon1_rad\n", + " dlat = lat2_rad - lat1_rad\n", + "\n", + " # Haversine formula\n", + " a = cupy.sin(dlat / 2)**2 + cupy.cos(lat1_rad) * cupy.cos(lat2_rad) * cupy.sin(dlon / 2)**2\n", + " c = 2 * cupy.arcsin(cupy.sqrt(a)) # Alternatively: 2 * cupy.arctan2(cupy.sqrt(a), cupy.sqrt(1 - a))\n", + " \n", + " distances_km = earth_radius_km * c\n", + " return distances_km\n", "\n", "# Calculate distance\n", - "distances_in_km = cuspatial.haversine_distance(start_points, end_points)\n", - "\n", + "distances_in_km = haversine_distance_cupy(df.start_lng, df.start_lat, df.end_lng, df.end_lat)\n", "# Add the distances back into the dataframe, convert from KM to M, and rounding values to make it more obvious if the stopped at the same place it started\n", "dist_m = cudf.Series(distances_in_km).values * 1000\n", "df['dist_m'] = dist_m.round().astype('int32')\n", diff --git a/notebooks/RAPIDS Visualization Guide/README.md b/notebooks/RAPIDS Visualization Guide/README.md index bc458d8e..93a77e3c 100644 --- a/notebooks/RAPIDS Visualization Guide/README.md +++ b/notebooks/RAPIDS Visualization Guide/README.md @@ -5,7 +5,7 @@ Try a user guide notebook of an end-to-end RAPIDS visualization integrated workf ### The workflow includes integrated examples that use: - cuDF for EDA - cuML for KDE and Kmeans -- cuSpatial for Haversine Distance +- cupy for Haversine Distance - cuGraph for FA2 - cuxfilter for cross-filtered bars, graph, and geospatial scatter charts - hvPlot with bokeh, datashader, and panel for multiple chart types diff --git a/python/cuxfilter/charts/core/non_aggregate/utils.py b/python/cuxfilter/charts/core/non_aggregate/utils.py index ca090476..7b96ff57 100644 --- a/python/cuxfilter/charts/core/non_aggregate/utils.py +++ b/python/cuxfilter/charts/core/non_aggregate/utils.py @@ -1,13 +1,177 @@ -import cuspatial -from shapely.geometry import Polygon -import geopandas as gpd - - -def point_in_polygon(df, x, y, polygons): - points = cuspatial.GeoSeries.from_points_xy( - df[[x, y]].interleave_columns().astype("float64") - ) - polygons = cuspatial.GeoSeries( - gpd.GeoSeries(Polygon(polygons)), index=["selection"] - ) - return cuspatial.point_in_polygon(points, polygons).selection +from numba import cuda +from numba.core.errors import NumbaPerformanceWarning +import cupy as cp +import cudf +import warnings + + +# Define the CUDA kernel using numba.cuda.jit +# This kernel implements the ray casting algorithm +@cuda.jit(device=True) +def point_in_polygon_ray_cast(px, py, polygon_xy, num_vertices): + """ + Check if a single point (px, py) is inside a polygon using ray casting. + + This is a device function intended to be called from a CUDA kernel. + + Parameters + ---------- + px : float + X-coordinate of the point. + py : float + Y-coordinate of the point. + polygon_xy : cupy.ndarray + Flat array of polygon vertices, interleaved [x0, y0, x1, y1, ...]. + num_vertices : int + Number of vertices in the polygon. + + Returns + ------- + bool + True if the point is inside the polygon, False otherwise. + """ + intersections = 0 + for j in range(num_vertices): + vjx = polygon_xy[2 * j] + vjy = polygon_xy[2 * j + 1] + # Get next vertex, wrapping around + j_plus_1 = (j + 1) % num_vertices + vj1x = polygon_xy[2 * j_plus_1] + vj1y = polygon_xy[2 * j_plus_1 + 1] + + # Check if the horizontal ray crosses the edge (vj, vj1) + # Condition 1: Is the point's y-coordinate within the edge's y-range? + if (vjy <= py < vj1y) or (vj1y <= py < vjy): + # Condition 2: Is the edge not horizontal? + if vjy != vj1y: + # Calculate the x-coordinate of the intersection + x_intersection = vjx + (py - vjy) * (vj1x - vjx) / (vj1y - vjy) + # Condition 3: Is the intersection point to the right of + # the point? + if px < x_intersection: + intersections += 1 + + # Point is inside if the number of intersections is odd + return intersections % 2 == 1 + + +@cuda.jit +def point_in_polygon_kernel(points_xy, polygon_xy, num_vertices, out): + """ + CUDA kernel to check an array of points against a single polygon. + + Each thread checks one point. + + Parameters + ---------- + points_xy : cupy.ndarray + Flat array of point coordinates, interleaved [px0, py0, px1, py1, ...]. + polygon_xy : cupy.ndarray + Flat array of polygon vertices, interleaved [vx0, vy0, vx1, vy1, ...]. + num_vertices : int + Number of vertices in the polygon. + out : cupy.ndarray + Output boolean array. out[i] is True if points_xy[2*i:2*i+2] is + inside the polygon. + """ + i = cuda.grid(1) # Global thread index + + # Check if index is within bounds (number of points) + if i < points_xy.shape[0] // 2: + px = points_xy[2 * i] + py = points_xy[2 * i + 1] + + # Call the device function for the actual check + out[i] = point_in_polygon_ray_cast(px, py, polygon_xy, num_vertices) + + +def point_in_polygon(df, x, y, polygon_coords): + """ + Checks which points in a DataFrame are inside a given polygon using a CUDA + kernel. + + Parameters + ---------- + df : cudf.DataFrame + DataFrame containing the points. + x : str + Column name for the x-coordinates of the points. + y : str + Column name for the y-coordinates of the points. + polygon_coords : list of tuples or similar array-like + Coordinates of the polygon vertices, e.g., [(x1, y1), (x2, y2), ...]. + The polygon should be closed. + + Returns + ------- + cudf.Series + A boolean Series indicating whether each point is inside the polygon. + """ + if not isinstance(df, cudf.DataFrame): + raise TypeError("Input 'df' must be a cudf.DataFrame") + + # 1. Prepare point data + num_points = len(df) + if num_points == 0: + return cudf.Series([], dtype="bool", index=df.index) + + # Interleave columns directly using cudf and get cupy array + # .values returns a cupy array for cudf Series/DataFrame + points_xy_cp = df[[x, y]].astype(cp.float64).interleave_columns().values + + # 2. Prepare polygon data + try: + # Directly create cupy array from polygon_coords + polygon_xy_cp = cp.array(polygon_coords, dtype=cp.float64) + + # Flatten if it's a list of pairs (N, 2) + if polygon_xy_cp.ndim == 2 and polygon_xy_cp.shape[1] == 2: + polygon_xy_cp = polygon_xy_cp.flatten() + elif polygon_xy_cp.ndim != 1: + raise ValueError( + "Polygon coordinates must be list of pairs or flat list." + ) + + # Validate size + if polygon_xy_cp.size % 2 != 0: + raise ValueError( + "Polygon coordinates must have an even number of elements." + ) + + num_vertices = polygon_xy_cp.size // 2 + + if num_vertices < 3: + raise ValueError("Polygon must have at least 3 vertices.") + + except (ValueError, TypeError): + # Handle invalid polygon formats or insufficient vertices + # Return all False as per the check at the start + if isinstance(df.index, cudf.MultiIndex): + idx = cudf.RangeIndex(len(df)) + else: + idx = df.index + return cudf.Series(cp.zeros(len(df), dtype=cp.bool_), index=idx) + + # 3. Prepare output array + out_gpu = cp.zeros(num_points, dtype=cp.bool_) + + # 4. Configure and launch kernel + threads_per_block = 256 + blocks_per_grid = ( + num_points + (threads_per_block - 1) + ) // threads_per_block + + if blocks_per_grid > 0: + # Suppress NumbaPerformanceWarning for low grid size in tests + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + category=NumbaPerformanceWarning, + message="Grid size.*result in GPU under-utilization", + ) + point_in_polygon_kernel[blocks_per_grid, threads_per_block]( + points_xy_cp, polygon_xy_cp, num_vertices, out_gpu + ) + + # 5. Return result as cudf.Series, preserving original index + return cudf.Series(out_gpu, index=df.index) diff --git a/python/cuxfilter/tests/charts/core/non_aggregate/test_utils.py b/python/cuxfilter/tests/charts/core/non_aggregate/test_utils.py new file mode 100644 index 00000000..88b79cd3 --- /dev/null +++ b/python/cuxfilter/tests/charts/core/non_aggregate/test_utils.py @@ -0,0 +1,114 @@ +import pytest +import cudf +import numpy as np +from cudf.testing import assert_series_equal + +# Assume the function is in this path relative to the tests +from cuxfilter.charts.core.non_aggregate.utils import point_in_polygon + + +@pytest.fixture +def sample_points_df(): + """Create a sample cudf DataFrame for testing.""" + # Points relative to polygon (0,0)-(1,1): + # (0.5, 0.5) -> Inside + # (1.5, 0.5) -> Outside + # (0.5, 1.5) -> Outside + # (1.5, 1.5) -> Outside + data = { + "x": [0.5, 1.5, 0.5, 1.5], + "y": [0.5, 0.5, 1.5, 1.5], + "val": [1, 2, 3, 4], # Corresponds to original vals for these points + } + return cudf.DataFrame(data) + + +@pytest.fixture +def simple_polygon_list(): + """A simple square polygon as a list of tuples.""" + # Square from (0,0) to (1,1) + return [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)] + + +@pytest.fixture +def simple_polygon_numpy(simple_polygon_list): + """The same simple square polygon as a NumPy array.""" + return np.array(simple_polygon_list, dtype=np.float64) + + +def test_point_in_polygon_basic(sample_points_df, simple_polygon_list): + """Test basic point in polygon functionality with list polygon.""" + result = point_in_polygon(sample_points_df, "x", "y", simple_polygon_list) + # Points: Inside(T), Outside(F), Outside(F), Outside(F) + expected = cudf.Series( + [True, False, False, False], + index=sample_points_df.index, + ) + assert_series_equal(result, expected) + + +def test_point_in_polygon_numpy_poly(sample_points_df, simple_polygon_numpy): + """Test point in polygon functionality with NumPy polygon.""" + result = point_in_polygon(sample_points_df, "x", "y", simple_polygon_numpy) + # Expect the same result as with the list polygon + expected = cudf.Series( + [True, False, False, False], + index=sample_points_df.index, + ) + assert_series_equal(result, expected) + + +def test_point_in_polygon_empty_df(): + """Test with an empty DataFrame.""" + empty_df = cudf.DataFrame({"x": [], "y": []}) + polygon = [(0, 0), (1, 0), (1, 1), (0, 1)] + result = point_in_polygon(empty_df, "x", "y", polygon) + expected = cudf.Series([], dtype="bool", index=empty_df.index) + assert_series_equal(result, expected) + + +def test_point_in_polygon_invalid_polygon(sample_points_df): + """Test with an invalid polygon (less than 3 vertices).""" + invalid_poly = [(0, 0), (1, 1)] # Only two vertices + result = point_in_polygon(sample_points_df, "x", "y", invalid_poly) + # Expect all False as the function should handle invalid polygons + # gracefully + expected = cudf.Series( + [False] * len(sample_points_df), + index=sample_points_df.index, + dtype="bool", + ) + assert_series_equal(result, expected) + + +def test_point_in_polygon_flat_polygon(sample_points_df): + """Test with polygon coordinates provided as a flat list.""" + flat_poly = [0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0] # Square + result = point_in_polygon(sample_points_df, "x", "y", flat_poly) + # Expect the same result + expected = cudf.Series( + [True, False, False, False], + index=sample_points_df.index, + ) + assert_series_equal(result, expected) + + +def test_point_in_polygon_no_points_inside(sample_points_df): + """Test case where no points are inside the polygon.""" + # Polygon shifted away from all points + shifted_polygon = [(10.0, 10.0), (11.0, 10.0), (11.0, 11.0), (10.0, 11.0)] + result = point_in_polygon(sample_points_df, "x", "y", shifted_polygon) + expected = cudf.Series( + [False] * len(sample_points_df), index=sample_points_df.index + ) + assert_series_equal(result, expected) + + +def test_point_in_polygon_all_points_inside(): + """Test case where all points are inside the polygon.""" + points_df = cudf.DataFrame({"x": [0.2, 0.5, 0.8], "y": [0.2, 0.5, 0.8]}) + # Polygon encompassing all points + large_polygon = [(-1, -1), (2, -1), (2, 2), (-1, 2)] + result = point_in_polygon(points_df, "x", "y", large_polygon) + expected = cudf.Series([True, True, True], index=points_df.index) + assert_series_equal(result, expected) diff --git a/python/cuxfilter/tests/charts/core/test_core_graph.py b/python/cuxfilter/tests/charts/core/test_core_graph.py index c60c61b4..1c6ca1df 100644 --- a/python/cuxfilter/tests/charts/core/test_core_graph.py +++ b/python/cuxfilter/tests/charts/core/test_core_graph.py @@ -149,39 +149,77 @@ class evt: def test_lasso_selection_callback(self, df_type): nodes = initialize_df( df_type, - {"vertex": [0, 1, 2, 3], "x": [0, 1, 1, 2], "y": [0, 1, 2, 0]}, + { + "vertex": [0, 1, 2, 3], + "x": [0.5, 1.5, 0.5, 2.5], + "y": [0.5, 1.5, 1.5, 0.5], + }, ) edges = initialize_df( - df_type, {"source": [1, 1, 1, 1], "target": [0, 1, 2, 3]} + df_type, {"source": [0, 2], "target": [2, 3]} # Simplified edges ) dashboard = DashBoard(dataframe=DataFrame.load_graph((nodes, edges))) bg = BaseGraph() - bg.chart_type = "temp" - bg.nodes = nodes + bg.chart_type = "graph_lasso_test" + bg.nodes = nodes # Make sure BaseGraph instance knows the nodes bg.edges = edges bg.inspect_neighbors = CustomInspectTool(_active=False) + self.result = None # Reset result for the test + def t_function(data, edges=None, patch_update=False): - self.result = data + # Store the result sorted by vertex for consistent comparison + # Handle empty DataFrame case + if data is not None and len(data) > 0: + self.result = data.sort_values(by="vertex").reset_index( + drop=True + ) + elif data is not None: # Empty dataframe + self.result = data + else: # data is None + self.result = None bg.reload_chart = t_function - # Add the last point to close the shape - geometry = np.array([[1, 1], [1, 2], [2, 2], [2, 1], [1, 1]]) - - t = bg.get_lasso_select_callback(dashboard) - with mock.patch("cuspatial.point_in_polygon") as pip: - if isinstance(nodes, dask_cudf.DataFrame): - # point in polygon is called per partition, - # in this case 2 partitions of length 2 each - pip.return_value = cudf.DataFrame({"selection": [True, False]}) - else: - pip.return_value = cudf.DataFrame( - {"selection": [True, False, True, False]} - ) - t(geometry) - assert pip.called - assert isinstance(self.result, df_type) + # Define the lasso polygon - square from (1,1) to (2,2) + geometry = np.array( + [[1.0, 1.0], [1.0, 2.0], [2.0, 2.0], [2.0, 1.0], [1.0, 1.0]], + dtype=np.float64, + ) + + # Get the callback function + lasso_callback = bg.get_lasso_select_callback(dashboard) + # Execute the callback with the geometry + lasso_callback(geometry=geometry) + + # --- Expected Result Definition --- + # Node 2 (vertex=2, x=1.5, y=1.5) should be selected. + expected_nodes_data = { + "vertex": [1], + "x": [1.5], + "y": [1.5], + } + # Always create the expected result as a cudf.DataFrame + expected_cudf_df = cudf.DataFrame(expected_nodes_data) + + # --- Comparison Logic --- + assert self.result is not None + + # Compute the result if it's a Dask DataFrame + if isinstance(self.result, dask_cudf.DataFrame): + result_to_compare = self.result.compute() + else: + result_to_compare = self.result + + # Ensure result is sorted and indexed like the expected one + if result_to_compare is not None and len(result_to_compare) > 0: + result_to_compare = result_to_compare.sort_values( + by="vertex" + ).reset_index(drop=True) + + # Assert the content matches the expected selected nodes + # df_equals likely uses cudf.testing.assert_frame_equal internally + assert df_equals(result_to_compare, expected_cudf_df) @pytest.mark.parametrize("df_type", df_types) @pytest.mark.parametrize( diff --git a/python/cuxfilter/tests/charts/core/test_core_non_aggregate.py b/python/cuxfilter/tests/charts/core/test_core_non_aggregate.py index f236d672..b329d6bc 100644 --- a/python/cuxfilter/tests/charts/core/test_core_non_aggregate.py +++ b/python/cuxfilter/tests/charts/core/test_core_non_aggregate.py @@ -123,30 +123,63 @@ def test_lasso_selection_callback(self, df_type): bnac = BaseNonAggregate() bnac.x = "a" bnac.y = "b" - bnac.chart_type = "temp" + bnac.chart_type = "non_agg_lasso_test" - df = initialize_df(df_type, {"a": [0, 1, 1, 2], "b": [0, 1, 2, 0]}) - expected_df = initialize_df(df_type, {"a": [0, 1], "b": [0, 2]}) + df = initialize_df( + df_type, {"a": [0.5, 1.5, 0.5, 2.5], "b": [0.5, 1.5, 1.5, 0.5]} + ) dashboard = DashBoard(dataframe=DataFrame.from_dataframe(df)) - # Add the last point to close the shape - geometry = np.array([[1, 1], [1, 2], [2, 2], [2, 1], [1, 1]]) - - t = bnac.get_lasso_select_callback(dashboard) - with mock.patch("cuspatial.point_in_polygon") as pip: - if isinstance(df, dask_cudf.DataFrame): - # point in polygon is called per partition, - # in this case 2 partitions of length 2 each - pip.return_value = cudf.DataFrame({"selection": [True, False]}) - else: - pip.return_value = cudf.DataFrame( - {"selection": [True, False, True, False]} - ) - t(geometry) - assert pip.called - result_df = dashboard._query(dashboard._generate_query_str()) - assert isinstance(result_df, df_type) - assert df_equals(result_df, expected_df) + # Define the lasso polygon - square from (1,1) to (2,2) + geometry = np.array( + [[1.0, 1.0], [1.0, 2.0], [2.0, 2.0], [2.0, 1.0], [1.0, 1.0]], + dtype=np.float64, + ) + + # Get the callback function + lasso_callback = bnac.get_lasso_select_callback(dashboard) + + # Execute the callback + lasso_callback(geometry=geometry) + + # --- Expected Result Definition --- + # Point (a=1.5, b=1.5) should be selected. + expected_nodes_data = { + "a": [1.5], + "b": [1.5], + } + # Always create the expected result as a cudf.DataFrame + expected_cudf_df = cudf.DataFrame(expected_nodes_data) + # Ensure dtypes match the original for robust comparison + expected_cudf_df["a"] = expected_cudf_df["a"].astype(df["a"].dtype) + expected_cudf_df["b"] = expected_cudf_df["b"].astype(df["b"].dtype) + + # --- Comparison Logic --- + # The callback updates the dashboard's query dictionary + # We need to execute the query to get the selected data + result_df = dashboard._query(dashboard._generate_query_str()) + + assert result_df is not None + + # Compute the result if it's a Dask DataFrame + if isinstance(result_df, dask_cudf.DataFrame): + result_to_compare = result_df.compute() + else: + result_to_compare = result_df + + # Ensure result is sorted and indexed like the expected one + if result_to_compare is not None and len(result_to_compare) > 0: + result_to_compare = result_to_compare.sort_values( + by=["a", "b"] + ).reset_index(drop=True) + + expected_cudf_df = expected_cudf_df.sort_values( + by=["a", "b"] + ).reset_index(drop=True) + + # Assert the content matches the expected selected nodes + assert isinstance(result_to_compare, cudf.DataFrame) + assert df_equals(result_to_compare, expected_cudf_df) @pytest.mark.parametrize( "data, _data", diff --git a/python/pyproject.toml b/python/pyproject.toml index ab76d1f1..674fa361 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -21,7 +21,6 @@ dependencies = [ "bokeh>=3.1,<=3.6.3", "cudf==25.6.*,>=0.0.0a0", "cupy-cuda11x>=12.0.0", - "cuspatial==25.6.*,>=0.0.0a0", "dask-cudf==25.6.*,>=0.0.0a0", "datashader>=0.15", "geopandas>=0.11.0",