Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ Version NEXTVERSION

**2026-11-??**

* New package-level functions to convert from and to `iris`:
`cf.from_iris` and `cf.to_iris`
(https://github.com/NCAS-CMS/cf-python/issues/979)
* New package-level functions to convert from and to `xarray`:
`cf.from_xarray` and `cf.to_xarray`
(https://github.com/NCAS-CMS/cf-python/issues/978)
Expand All @@ -13,6 +16,7 @@ Version NEXTVERSION
aggregation-promoted field ancillaries
(https://github.com/NCAS-CMS/cf-python/issues/971)
* Changed dependency: ``Python>=3.11.0``
* New optional dependency: ``ncdata>=0.4.0``

----

Expand Down
1 change: 1 addition & 0 deletions cf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@
from .regrid import RegridOperator

from .xarray_utils import from_xarray, to_xarray
from .iris_utils import from_iris, to_iris

# Set up basic logging for the full project with a root logger
import logging
Expand Down
54 changes: 54 additions & 0 deletions cf/iris_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""Utilities for conversion to and from iris."""

import cfdm


def from_iris(c):
"""Convert an `iris` dataset to CF field or domain constructs."""
try:
import ncdata # noqa: F401
except ImportError as e:
raise ImportError(
f"{e}. Must install ncdata (https://pypi.org/project/ncdata) "
"to allow conversions to and from iris cubes"
)

try:
from ncdata.iris import from_iris
except ImportError as e:
raise ImportError(
f"{e}. Must install scitools-iris "
"(https://pypi.org/project/scitools-iris/) "
"to allow conversions to and from iris cubes"
)

try:
from ncdata.xarray import to_xarray
except ImportError as e:
raise ImportError(
f"{e}. Must install xarray "
"to allow conversions to and from iris cubes"
)

from cf import from_xarray

n = from_iris(c)
ds = to_xarray(n)
return from_xarray(ds)


# Reset the docstring from cfdm
from_iris.__doc__ = cfdm.from_iris.__doc__.replace("cfdm.", "cf.").replace(
"<Field", "<CF Field"
)


def to_iris(f):
"""Convert CF field or domain constructs to an `iris` dataset."""
return cfdm.to_iris(f)


# Reset the docstring from cfdm
to_iris.__doc__ = cfdm.to_iris.__doc__.replace("cfdm.", "cf.").replace(
"<Field", "<CF Field"
)
97 changes: 97 additions & 0 deletions cf/test/test_iris.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import datetime
import faulthandler
import unittest

faulthandler.enable() # to debug seg faults and timeouts

ok = True
try:
import iris # noqa: F401
import ncdata # noqa: F401
import xarray # noqa: F401
except ImportError:
ok = False

import cf


class irisTest(unittest.TestCase):
"""Unit test for converting to and from iris."""

def setUp(self):
"""Preparations called immediately before each test method."""
# Disable log messages to silence expected warnings
cf.log_level("DISABLE")
# Note: to enable all messages for given methods, lines or
# calls (those without a 'verbose' option to do the same)
# e.g. to debug them, wrap them (for methods, start-to-end
# internally) as follows:
#
# cf.LOG_LEVEL('DEBUG')
# < ... test code ... >
# cf.log_level('DISABLE')

@unittest.skipIf(not ok, "requires iris, xarray, and ncdata")
def test_to_iris(self):
"""Test cf.to_iris."""
fields = cf.example_fields()

# Write each field to a different xarray dataset
for f in fields:
c = cf.to_iris(f)
self.assertIsInstance(c, iris.cube.CubeList)
self.assertIn("Conventions", c[0].attributes)
str(c)

# All fields
c = cf.to_iris(fields)
self.assertIsInstance(c, iris.cube.CubeList)
str(c)

@unittest.skipIf(not ok, "requires iris, xarray, and ncdata")
def test_to_iris_from_disk(self):
"""Test cf.to_iris on datasets read from disk."""
for dataset in (
"example_field_0.nc",
"example_field_0.zarr2",
"example_field_0.zarr3",
"gathered.nc",
"DSG_timeSeries_contiguous.nc",
"DSG_timeSeries_indexed.nc",
"DSG_timeSeriesProfile_indexed_contiguous.nc",
"parent.nc",
"external.nc",
"external_missing.nc",
"combined.nc",
"geometry_1.nc",
"geometry_2.nc",
"geometry_3.nc",
"geometry_interior_ring.nc",
"geometry_interior_ring_2.nc",
"string_char.nc",
"subsampled_2.nc",
"ugrid_1.nc",
"ugrid_2.nc",
"ugrid_3.nc",
"test_file.nc",
):
f = cf.read(dataset)
c = cf.to_iris(f)
self.assertIsInstance(c, iris.cube.CubeList)
str(c)

@unittest.skipIf(not ok, "requires iris, xarray, and ncdata")
def test_from_iris(self):
"""Test cf.from_iris."""
# These fields round trip OK!
f = cf.example_fields(0, 2, 5, 7, 12, 13)
ds = cf.to_iris(f)
g = cf.from_iris(ds)
self.assertEqual(len(f), len(g))


if __name__ == "__main__":
print("Run date:", datetime.datetime.now())
cf.environment()
print("")
unittest.main(verbosity=2)
6 changes: 4 additions & 2 deletions docs/source/function.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ Aggregation
cf.aggregate
cf.climatology_cells

Conversion from and to xarray
-----------------------------
Conversion from and to xarray and iris
--------------------------------------

.. autosummary::
:nosignatures:
Expand All @@ -42,6 +42,8 @@ Conversion from and to xarray

cf.from_xarray
cf.to_xarray
cf.from_iris
cf.to_iris

.. _functions-mathematical-operations:

Expand Down
7 changes: 7 additions & 0 deletions docs/source/function/cf.from_iris.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
cf.from_iris
=============

.. currentmodule:: cf
.. default-role:: obj

.. autofunction:: cf.from_iris
7 changes: 7 additions & 0 deletions docs/source/function/cf.to_iris.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
cf.to_iris
==========

.. currentmodule:: cf
.. default-role:: obj

.. autofunction:: cf.to_iris
1 change: 0 additions & 1 deletion docs/source/installation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,6 @@ environments for which these features are not required.
newer. This package is required to create 2-d latitude and longitude
coordinates from grid mappings.


----

.. _Tests:
Expand Down