def to_cdms2(dataarray, copy=True):
    """Convert a DataArray into a cdms2 variable
    """
    # we don't want cdms2 to be a hard dependency
    import cdms2

    def set_cdms2_attrs(var, attrs):
        for k, v in attrs.items():
            setattr(var, k, v)

    # 1D axes
    axes = []
    for dim in dataarray.dims:
        coord = encode(dataarray.coords[dim])
        axis = cdms2.createAxis(coord.values, id=dim)
        set_cdms2_attrs(axis, coord.attrs)
        axes.append(axis)

    # Data
    var = encode(dataarray)
    cdms2_var = cdms2.createVariable(var.values, axes=axes, id=dataarray.name,
                                     mask=pd.isnull(var.values), copy=copy)

    # Attributes
    set_cdms2_attrs(cdms2_var, var.attrs)

    # Curvilinear and unstructured grids
    if dataarray.name not in dataarray.coords:

        cdms2_axes = OrderedDict()
        for coord_name in set(dataarray.coords.keys()) - set(dataarray.dims):

            coord_array = dataarray.coords[coord_name].to_cdms2()

            cdms2_axis_cls = (cdms2.coord.TransientAxis2D
                              if coord_array.ndim else
                              cdms2.auxcoord.TransientAuxAxis1D)
            cdms2_axis = cdms2_axis_cls(coord_array)
            if cdms2_axis.isLongitude():
                cdms2_axes['lon'] = cdms2_axis
            elif cdms2_axis.isLatitude():
                cdms2_axes['lat'] = cdms2_axis

        if 'lon' in cdms2_axes and 'lat' in cdms2_axes:
            if len(cdms2_axes['lon'].shape) == 2:
                cdms2_grid = cdms2.hgrid.TransientCurveGrid(
                    cdms2_axes['lat'], cdms2_axes['lon'])
            else:
                cdms2_grid = cdms2.gengrid.AbstractGenericGrid(
                    cdms2_axes['lat'], cdms2_axes['lon'])
            for axis in cdms2_grid.getAxisList():
                cdms2_var.setAxis(cdms2_var.getAxisIds().index(axis.id), axis)
            cdms2_var.setGrid(cdms2_grid)

    return cdms2_var
Convert a DataArray into a cdms2 variable