Skip to content

Coordinate identification for 2d latitude/longitude fails in presence of similarly named auxilliary variables #3860

@ljoakim

Description

@ljoakim

What went wrong?

I work with data that have x, y dimension coordinates as well as auxiliary 2d latitude and longitude coordinates. In the data arrays, there are additional auxiliary variables that conflict with the latitude/longitude coordinates when trying to use the accessor, e.g. da.metpy.latitude.

This seems to stem from the non-CF failsafe regex fallback in the check_axis function, when called from _generate_coordinate_map(), which marks all auxiliary variables with names starting with e.g. y, x, lat or lon as candidates for the accessor.

For y and x, this is resolved later because they match dimension names, but not for latitude and longitude, which causes the access to fail. Not sure precisely how to fix it, but would it maybe be possible to defer the regex fallback and use it only if no "CF-compliant" coordinate were found?

I've created a pytest test that reproduces the issue.

Thanks,

Operating System

Linux

Version

1.7.0.post81+g9f59838062

Python Version

3.13.3

Code to Reproduce

# Added in tests/test_xarray.py
#
def test_coord_identification_with_other_namelike_vars(test_var_multidim_full):
    """Test coord identification works in presence of vars with similar names."""
    test_da = test_var_multidim_full.assign_coords(
        ylike=('y', [0, 0]),
        latlike=(('y', 'x'), [[0, 0], [0, 0]]),
        xlike=('x', [0, 0]),
        lonlike=(('y', 'x'), [[0, 0], [0, 0]]),
    )
    assert test_da['y'].identical(test_da.metpy.y)
    assert test_da['lat'].identical(test_da.metpy.latitude)
    assert test_da['x'].identical(test_da.metpy.x)
    assert test_da['lon'].identical(test_da.metpy.longitude)

Errors, Traceback, and Logs

src/metpy/_warnings.py:29: UserWarning
___________ test_coord_identification_with_other_namelike_vars[all] ____________

test_var_multidim_full = <xarray.DataArray 'Temperature' (isobaric: 2, y: 2, x: 2)> Size: 32B
[8 values with dtype=float32]
Coordinates:
    ti...e:  Initialized analysis product
    GRIB_level_type:               100
    GRIB_VectorComponentFlag:      gridRelative

    def test_coord_identification_with_other_namelike_vars(test_var_multidim_full):
        """Test coord identification works in presence of vars with similar names."""
        test_da = test_var_multidim_full.assign_coords(
            ylike=('y', [0, 0]),
            latlike=(('y', 'x'), [[0, 0], [0, 0]]),
            xlike=('x', [0, 0]),
            lonlike=(('y', 'x'), [[0, 0], [0, 0]]),
        )
>       assert test_da['y'].identical(test_da.metpy.y)
                                      ^^^^^^^^^^^^^^^

tests/test_xarray.py:1521: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
src/metpy/xarray.py:492: in y
    return self._axis('y')
           ^^^^^^^^^^^^^^^
src/metpy/xarray.py:417: in _axis
    coord_var = self._metpy_axis_search(axis)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
src/metpy/xarray.py:400: in _metpy_axis_search
    coord_map = self._generate_coordinate_map()
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
src/metpy/xarray.py:365: in _generate_coordinate_map
    self._resolve_axis_duplicates(axis, coord_lists)
src/metpy/xarray.py:383: in _resolve_axis_duplicates
    _warnings.warn(f'More than one {axis} coordinate present for variable {varname}.')
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

args = ('More than one longitude coordinate present for variable  "Temperature".',)
kwargs = {}, level = 7

    def warn(*args, **kwargs):
        """Wrap `warnings.warn` and automatically set the stack level if not given."""
        level = kwargs.get('stacklevel')
        if level is None:
            level = _find_stack_level()
>       warnings.warn(*args, **kwargs, stacklevel=level)
E       UserWarning: More than one longitude coordinate present for variable  "Temperature".

src/metpy/_warnings.py:29: UserWarning
=========================== short test summary info ============================
FAILED tests/test_xarray.py::test_coord_identification_with_other_namelike_vars[True]
FAILED tests/test_xarray.py::test_coord_identification_with_other_namelike_vars[all]
============================== 2 failed in 0.51s ===============================

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area: XarrayPertains to xarray integrationType: BugSomething is not working like it should

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions