Skip to content

Consistent coordinates for pre-compute and 1d profile generation - #50

Merged
sungeunbae merged 2 commits into
mainfrom
1d_profile_fix
Feb 25, 2026
Merged

sungeunbae merged 2 commits into
mainfrom
1d_profile_fix

Conversation

@sungeunbae

Copy link
Copy Markdown
Member

This PR fixes a ValueError crash ("Basin point lies outside of the extent of the basin surface") occurring during 1D profile generation for points situated extremely close to basin boundaries.

  File "C:\Users\ara299\python_venv\venv_312\Lib\site-packages\velocity_modelling\basin_model.py", line 801, in determine_basin_surface_depths
    adjacent_points = AdjacentPoints.find_basin_adjacent_points(
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ara299\python_venv\venv_312\Lib\site-packages\velocity_modelling\geometry.py", line 782, in find_basin_adjacent_points
    raise ValueError(
ValueError: Basin point lies outside of the extent of the basin surface . 172.72931463769967 -42.99999463769967

From inspection, the location that caused this was (172.72932, -43.0)

  1. Fix: Coordinate Consistency in generate_1d_profiles.py

The root cause of the crash was a discrepancy between the coordinates used for basin membership checks and those used for velocity interpolation:

  • Previously: Basin membership was pre-computed using the raw input coordinates from the CSV file.
  • The Issue: When generating the 1D profile, the model grid generation snaps the input coordinates to the nearest grid point (e.g., -43.0 becoming -42.99999...). For edge cases, a point could be technically "inside" the basin based on raw coordinates, but the snapped mesh point would fall slightly "outside" the valid basin grid. This inconsistency caused the interpolation logic to fail when it attempted to query a point it believed was inside the basin.
  • The Fix: We now pre-calculate the exact mesh coordinates for all profiles before performing the basin membership check. By using the snapped mesh coordinates for the check, we ensure consistency: if a point snaps outside the basin grid, it is correctly classified as "outside," preventing the crash. This approach retains the performance benefits of vectorized basin checks.
  1. Defensive Change: Floating Point Tolerance in geometry.py

Added a tolerance (tol=1e-07) to floating-point comparisons in the geometry logic (specifically find_basin_adjacent_points and related Numba functions).

  • Reasoning: Previously, the code relied on strict equality checks or strict inequality for boundary detection.
  • Change: Replaced strict checks with tolerance-based comparisons (e.g., abs(a - b) <= tol). While this was not the primary fix for the reported crash, it makes the geometry calculations more robust against minor floating-point inaccuracies inherent in grid generation and projection.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @sungeunbae, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a critical ValueError that occurred when generating 1D profiles for points extremely close to basin boundaries. The core issue stemmed from inconsistent coordinate handling between basin membership determination and velocity interpolation. By standardizing the coordinates used for basin checks to match the snapped mesh coordinates, the system now accurately identifies points as inside or outside the basin, preventing crashes. Additionally, the changes enhance the overall robustness of geometric calculations by incorporating floating-point tolerances, mitigating potential issues from numerical precision.

Highlights

  • Coordinate Consistency for 1D Profile Generation: Resolved a ValueError crash during 1D profile generation by ensuring that basin membership checks use the same snapped mesh coordinates as velocity interpolation. Previously, a discrepancy between raw input coordinates (for basin checks) and snapped grid coordinates (for interpolation) could cause points near basin boundaries to be incorrectly classified, leading to failures.
  • Improved Floating-Point Robustness: Introduced a floating-point tolerance (defaulting to 1e-07) to comparisons in geometry.py functions. This change replaces strict equality checks with tolerance-based comparisons, making the geometry calculations more robust against minor floating-point inaccuracies inherent in grid generation and projection, although it was not the primary fix for the reported crash.
Changelog
  • velocity_modelling/geometry.py
    • Added a tol parameter with a default value of 1e-07 to point_on_vertex, find_corner_inds, and find_basin_adjacent_points_numba functions.
    • Updated docstrings for these functions to include the new tol parameter.
    • Replaced hardcoded 1e-07 and strict equality comparisons (==) with np.abs(a - b) <= tol for floating-point comparisons within these functions.
  • velocity_modelling/scripts/generate_1d_profiles.py
    • Refactored the profile generation loop to first pre-compute all mesh coordinates and store global_mesh objects, then perform basin membership checks using these consistent mesh coordinates.
    • Introduced mesh_lats and mesh_lons arrays to store the snapped coordinates for basin membership checks.
    • Extracted DataFrame columns (lat, lon, zmin, zmax, spacing) into NumPy arrays for improved performance.
    • Used a silent_logger during the initial mesh generation phase to reduce log verbosity.
    • Adjusted the setting of global_mesh.nz and global_mesh.z to occur during the initial mesh pre-computation.
Activity
  • No human activity has been recorded on this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request correctly addresses a crash related to coordinate inconsistencies during 1D profile generation by pre-calculating mesh coordinates before checking for basin membership. The changes look solid and effectively fix the reported bug. Additionally, the defensive change to use a tolerance for floating-point comparisons in the geometry module improves the robustness of the code.

I've added a couple of suggestions to improve code clarity and remove minor redundancies in the profile generation script. Overall, this is a good set of changes.

Comment thread velocity_modelling/scripts/generate_1d_profiles.py Outdated
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>

@lispandfound lispandfound left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just minor improvement suggestions. Provided they past tests I'm happy for you to merge after considering the changes without requiring another review.

Comment on lines -364 to 387
if np.abs(lat - lats[0]) <= 1e-07:
if np.abs(lat - lats[0]) <= tol:
corner_lat_ind = 0
elif np.abs(lat - lats[-1]) <= 1e-07:
elif np.abs(lat - lats[-1]) <= tol:
corner_lat_ind = nlat - 1
else:
raise ValueError(
f"Point lies outside of surface bounds. Lat {lat} outside [{lats[0]} {lats[-1]}]"
)

if np.abs(lon - lons[0]) <= 1e-07:
if np.abs(lon - lons[0]) <= tol:
corner_lon_ind = 0
elif np.abs(lon - lons[-1]) <= 1e-07:
elif np.abs(lon - lons[-1]) <= tol:
corner_lon_ind = nlon - 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similarly here you should use np.isclose

Comment on lines 225 to 261
@@ -239,17 +243,20 @@ def point_on_vertex(
Latitude of the point to check.
lon : float
Longitude of the point to check.
tol : float
Tolerance for floating point equality test, default: 1e-07


Returns
-------
bool
True if the point matches a boundary vertex within tolerance (1e-07), otherwise False.
True if the point matches a boundary vertex within tolerance, otherwise False.
"""
# Vectorized comparison using NumPy with tolerance
lat_matches = (
np.abs(boundary_lats - lat) <= 1e-07
np.abs(boundary_lats - lat) <= tol
) # np.isclose is not supported by njit
lon_matches = np.abs(boundary_lons - lon) <= 1e-07
lon_matches = np.abs(boundary_lons - lon) <= tol

matches = np.logical_and(lat_matches, lon_matches)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is just np.isclose. both np.isclose and np.allclose have been supported by numba since four years ago, also here.

lat_close = np.isclose(lat, boundary_lats, rtol=0.0, atol=tol)
lon_close = np.isclose(lon, boundary_lons, rtol=0.0, atol=tol)
return np.any(lat_close & lon_close)
>>> @numba.njit
... def test(lat, lon, boundary_lats, boundary_lons, tol=1e-7):
...     lat_close = np.isclose(lat, boundary_lats, rtol=0.0, atol=tol)
...     lon_close = np.isclose(lon, boundary_lons, rtol=0.0, atol=tol)
...     return np.any(lat_close & lon_close)
...
>>> test(-43.0, 172.64, np.array([-43.0, -44.0]), np.array([172.0, 172.65]))
False
>>> test(-43.0, 172.64, np.array([-43.0, -44.0]), np.array([172.0, 172.65]))
False
>>> test(-43.0, 172.64, np.array([-43.0, -44.0]), np.array([172.0, 172.65]))
False
>>> test(-43.0, 172.64, np.array([-43.0, -44.0]), np.array([172.0, 172.64]))
False
>>> test(-43.0, 172.64, np.array([-43.0, -43.0]), np.array([172.0, 172.64]))
True

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lispandfound Thanks for the update regarding np.isclose() support in Numba—I wasn't aware it was supported now.However, after reviewing the documentation, I prefer to stick with np.abs(a - b) <= tol for this specific case.

np.isclose uses a relative tolerance by default (rtol=1e-05)

numpy.isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)

and internally checks

 absolute(a - b) <= (atol + rtol * absolute(b))

For geographic coordinates, we need a fixed spatial tolerance (e.g., 1e-7 degrees) regardless of the coordinate magnitude (e.g., relative error at 170° is much larger than at 1°). To achieve this with np.isclose(), I would have to explicitly disable the relative tolerance

np.isclose(a, b, rtol=0, atol=tol)

This is more verbose, and less readable than the direct comparision.. Also inside @njit, direct subtraction is the most efficient primitive operation avoiding the extra overheads of np.isclose() (eg. internal handing of NaN, infinites etc).

https://numpy.org/doc/stable/reference/generated/numpy.isclose.html

@sungeunbae sungeunbae Feb 24, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Based on my observation, I even feel like to replace the 2 uses of "np.isclose()" with np.abs() <=tol

Line 1032-1040

    lat = np.where(
        np.isclose(zg, 0),
        0,
        90 - np.arctan(np.sqrt(xg**2 + yg**2) / zg) / RPERD - np.where(zg < 0, 180, 0),
    )

    lon = np.where(
        np.isclose(xg, 0), 0, np.arctan(yg / xg) / RPERD - np.where(xg < 0, 180, 0)
    )

Perhaps this is not critical as it is comparing with 0, and np.isclose(x,0) is abs(x-0) <= atol + rtol*0, effectively `abs(x)<=atol (which is 1e-8)

But for the consistency, I feel like to go ahead. Thought? @lispandfound

@sungeunbae
sungeunbae merged commit 8ea0fa5 into main Feb 25, 2026
4 checks passed
@sungeunbae
sungeunbae deleted the 1d_profile_fix branch February 25, 2026 03:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants