# Path: gridded/pyugrid/uvar.py
# class UVar(object):
#     """
#     A class to hold a variable associated with the UGrid. Data can be on the
#     nodes, edges, etc. -- "UGrid Variable"
# 
#     It holds an array of the data, as well as the attributes associated
#     with that data  -- this is mapped to a netcdf variable with
#     attributes(attributes get stored in the netcdf file)
#     """
# 
#     def __init__(self, name, location, data=None, attributes=None):
#         """
#         create a UVar object
#         :param name: the name of the variable (depth, u_velocity, etc.)
#         :type name: string
# 
#         :param location: the type of grid element the data is associated with:
#                          'node', 'edge', or 'face'
# 
#         :param data: The data itself
#         :type data: 1-d numpy array or array-like object ().
#                     If you have a list or tuple, it should be something that can be
#                     converted to a numpy array (list, etc.)
#         """
#         self.name = name
# 
#         if location not in ['node', 'edge', 'face', 'boundary']:
#             raise ValueError("location must be one of: "
#                              "'node', 'edge', 'face', 'boundary'")
# 
#         self.location = location
# 
#         if data is None:
#             # Could be any data type, but we'll default to float
#             self._data = np.zeros((0,), dtype=np.float64)
#         else:
#             self._data = asarraylike(data)
# 
#         # FixMe: we need a separate attribute dict -- we really do'nt want all this
#         #        getting mixed up with the python object attributes
#         self.attributes = {} if attributes is None else attributes
#         # if the data is a netcdf variable, pull the attributes from there
#         try:
#             for attr in data.ncattrs():
#                 self.attributes[attr] = data.getncattr(attr)
#         except AttributeError:  # must not be a netcdf variable
#             pass
# 
#         self._cache = OrderedDict()
# 
#     # def update_attrs(self, attrs):
#     #     """
#     #     update the attributes of the UVar object
# 
#     #     :param attr: Dict containing attributes to be added to the object
#     #     """
#     #     for key, val in attrs.items():
#     #         setattr(self, key, val)
# 
#     @property
#     def data(self):
#         """
#         The data associated with the UVar -- a numpy array-like object with the actual data
#         """
#         return self._data
# 
#     @data.setter
#     def data(self, data):
#         self._data = asarraylike(data)
# 
#     @data.deleter
#     def data(self):
#         self._data = self._data = np.zeros((0,), dtype=np.float64)
# 
#     @property
#     def shape(self):
#         """
#         The shape of the data array associated with the UVar.
#         """
#         return self.data.shape
# 
#     @property
#     def max(self):
#         """ maximum value of the variable """
#         return np.max(self._data)
# 
#     @property
#     def min(self):
#         """ minimum value of the variable """
#         return np.min(self._data)
# 
#     @property
#     def dtype(self):
#         """ data type of the variable """
#         return self.data.dtype
# 
#     @property
#     def ndim(self):
#         """ number of dimensions of the variable """
#         return self.data.ndim
# 
#     def __getitem__(self, item):
#         """
#         Transfers responsibility to the data's __getitem__ if not cached
#         """
#         rv = None
#         if str(item) in self._cache:
#             rv = self._cache[str(item)]
#         else:
#             rv = self._data.__getitem__(item)
#             self._cache[str(item)] = rv
#             if len(self._cache) > 3:
#                 self._cache.popitem(last=False)
#         return rv
# 
#     def __str__(self):
#         print("in __str__, data is:", self.data)
#         msg = ("UVar object: {0:s}, on the {1:s}s, and {2:d} data "
#                "points\nAttributes: {3}").format
#         return msg(self.name, self.location, len(self.data), self.attributes)
# 
#     def __len__(self):
#         return len(self.data)
# 
# Path: gridded/tests/test_ugrid/utilities.py
# @contextlib.contextmanager
# def chdir(dirname=None):
#     curdir = os.getcwd()
#     try:
#         if dirname is not None:
#             os.chdir(dirname)
#         yield
#     finally:
#         os.chdir(curdir)


import os
import numpy as np
import pytest
    import netCDF4
from gridded.pyugrid.uvar import UVar
from .utilities import chdir
test_files = os.path.join(os.path.dirname(__file__), 'files')


def test_init():
    d = UVar('depth', location='node', data=[1.0, 2.0, 3.0, 4.0])

    assert d.name == 'depth'
    assert np.array_equal(d.data, [1.0, 2.0, 3.0, 4.0])
    assert d.location == 'node'
    assert d.attributes == {}

    with pytest.raises(ValueError):
        d = UVar('depth', location='nodes')


def test_add_data():
    d = UVar('depth', location='node')
    assert d.name == 'depth'
    assert np.array_equal(d.data, [])

    # Add the data:
    d.data = [1.0, 2.0, 3.0, 4.0]

    assert np.array_equal(d.data, [1.0, 2.0, 3.0, 4.0])
    # Duck type check of nd.ndarray.
    d.data *= 2
    assert np.array_equal(d.data, [2.0, 4.0, 6.0, 8.0])


def test_delete_data():

# Path: gridded/pyugrid/uvar.py
# class UVar(object):
#     """
#     A class to hold a variable associated with the UGrid. Data can be on the
#     nodes, edges, etc. -- "UGrid Variable"
# 
#     It holds an array of the data, as well as the attributes associated
#     with that data  -- this is mapped to a netcdf variable with
#     attributes(attributes get stored in the netcdf file)
#     """
# 
#     def __init__(self, name, location, data=None, attributes=None):
#         """
#         create a UVar object
#         :param name: the name of the variable (depth, u_velocity, etc.)
#         :type name: string
# 
#         :param location: the type of grid element the data is associated with:
#                          'node', 'edge', or 'face'
# 
#         :param data: The data itself
#         :type data: 1-d numpy array or array-like object ().
#                     If you have a list or tuple, it should be something that can be
#                     converted to a numpy array (list, etc.)
#         """
#         self.name = name
# 
#         if location not in ['node', 'edge', 'face', 'boundary']:
#             raise ValueError("location must be one of: "
#                              "'node', 'edge', 'face', 'boundary'")
# 
#         self.location = location
# 
#         if data is None:
#             # Could be any data type, but we'll default to float
#             self._data = np.zeros((0,), dtype=np.float64)
#         else:
#             self._data = asarraylike(data)
# 
#         # FixMe: we need a separate attribute dict -- we really do'nt want all this
#         #        getting mixed up with the python object attributes
#         self.attributes = {} if attributes is None else attributes
#         # if the data is a netcdf variable, pull the attributes from there
#         try:
#             for attr in data.ncattrs():
#                 self.attributes[attr] = data.getncattr(attr)
#         except AttributeError:  # must not be a netcdf variable
#             pass
# 
#         self._cache = OrderedDict()
# 
#     # def update_attrs(self, attrs):
#     #     """
#     #     update the attributes of the UVar object
# 
#     #     :param attr: Dict containing attributes to be added to the object
#     #     """
#     #     for key, val in attrs.items():
#     #         setattr(self, key, val)
# 
#     @property
#     def data(self):
#         """
#         The data associated with the UVar -- a numpy array-like object with the actual data
#         """
#         return self._data
# 
#     @data.setter
#     def data(self, data):
#         self._data = asarraylike(data)
# 
#     @data.deleter
#     def data(self):
#         self._data = self._data = np.zeros((0,), dtype=np.float64)
# 
#     @property
#     def shape(self):
#         """
#         The shape of the data array associated with the UVar.
#         """
#         return self.data.shape
# 
#     @property
#     def max(self):
#         """ maximum value of the variable """
#         return np.max(self._data)
# 
#     @property
#     def min(self):
#         """ minimum value of the variable """
#         return np.min(self._data)
# 
#     @property
#     def dtype(self):
#         """ data type of the variable """
#         return self.data.dtype
# 
#     @property
#     def ndim(self):
#         """ number of dimensions of the variable """
#         return self.data.ndim
# 
#     def __getitem__(self, item):
#         """
#         Transfers responsibility to the data's __getitem__ if not cached
#         """
#         rv = None
#         if str(item) in self._cache:
#             rv = self._cache[str(item)]
#         else:
#             rv = self._data.__getitem__(item)
#             self._cache[str(item)] = rv
#             if len(self._cache) > 3:
#                 self._cache.popitem(last=False)
#         return rv
# 
#     def __str__(self):
#         print("in __str__, data is:", self.data)
#         msg = ("UVar object: {0:s}, on the {1:s}s, and {2:d} data "
#                "points\nAttributes: {3}").format
#         return msg(self.name, self.location, len(self.data), self.attributes)
# 
#     def __len__(self):
#         return len(self.data)
# 
# Path: gridded/tests/test_ugrid/utilities.py
# @contextlib.contextmanager
# def chdir(dirname=None):
#     curdir = os.getcwd()
#     try:
#         if dirname is not None:
#             os.chdir(dirname)
#         yield
#     finally:
#         os.chdir(curdir)


# Path: gridded/tests/test_ugrid/test_uvar.py
import os
import numpy as np
import pytest
    import netCDF4
from gridded.pyugrid.uvar import UVar
from .utilities import chdir

test_files = os.path.join(os.path.dirname(__file__), 'files')


def test_init():
    d = UVar('depth', location='node', data=[1.0, 2.0, 3.0, 4.0])

    assert d.name == 'depth'
    assert np.array_equal(d.data, [1.0, 2.0, 3.0, 4.0])
    assert d.location == 'node'
    assert d.attributes == {}

    with pytest.raises(ValueError):
        d = UVar('depth', location='nodes')


def test_add_data():
    d = UVar('depth', location='node')
    assert d.name == 'depth'
    assert np.array_equal(d.data, [])

    # Add the data:
    d.data = [1.0, 2.0, 3.0, 4.0]

    assert np.array_equal(d.data, [1.0, 2.0, 3.0, 4.0])
    # Duck type check of nd.ndarray.
    d.data *= 2
    assert np.array_equal(d.data, [2.0, 4.0, 6.0, 8.0])


def test_delete_data():

    d = UVar('depth', location='node', data=[1.0, 2.0, 3.0, 4.0])