NCAS-CMS / cf-python

A CF-compliant Earth Science data analysis library
http://ncas-cms.github.io/cf-python
MIT License
120 stars 19 forks source link

coordinate equality raises a stack trace instead of a False #806

Open bnlawrence opened 2 weeks ago

bnlawrence commented 2 weeks ago

I am comparing coordinates for equality (don't ask why).

MWE of the problem, given a field with Z and Y dimensions:

zz = f.dimension_coordinate('Z')
yy = f.dimension_coordiante('Y')
zz == yy # raises an error instead of simply raising False:
               # ValueError: Can't compare <Units: m> to <Units: degrees_north>

Platform: Linux-3.10.0-1160.119.1.el7.x86_64-x86_64-with-glibc2.17 HDF5 library: 1.14.3 netcdf library: 4.9.2 udunits2 library: /home/users/lawrence/.conda/envs/mampy24b/lib/libudunits2.so.0 esmpy/ESMF: not available Python: 3.12.4 dask: 2024.7.0 netCDF4: 1.7.1 h5netcdf: 1.3.0 h5py: 3.11.0 s3fs: 2024.6.1 psutil: 6.0.0 packaging: 24.1 numpy: 2.0.0 scipy: 1.14.0 matplotlib: 3.9.1 cftime: 1.6.4 cfunits: 3.3.7 cfplot: 3.3.0 cfdm: 1.11.2.0 cf: 3.17.0

davidhassell commented 2 weeks ago

Hi Bryan (not spam!),

== is for array equality (a la numpy). For "overall" equality use the equals method, which always returns a Boolean:

zz = f.dimension_coordinate('Z')
yy = f.dimension_coordinate('Y')
if zz.equals(yy):
   print("oops")
if not zz.equals('something completely different'):
    print("as expected")

In addition, if you want to know why they weren't equal, you can use the verbose keyword to tell you, with varying levels of detail.

The overall equality includes an array equality component, but it only bothers to check that if all of the properties, units, shape, etc, have already found to be the same.

They docs describe how "equality" is defined: https://ncas-cms.github.io/cf-python/method/cf.DimensionCoordinate.equals.html

All cf-python constructs (field, coordinate, cell method, cell measures, etc.) have an equals method.