# Path: atmos/data.py
# def get_coord(data, coord_name, return_type='values'):
#     """Return values, name or dimension of coordinate in DataArray.
# 
#     Parameters
#     ----------
#     data : xray.DataArray
#         Data array to search for latitude coords.
#     coord_name : str
#         Coordinate to extract.  Can be the exact ID of the variable or
#         a generic ID ('lat', 'lon', 'plev', 'time', 'day', 'year').
#         If a generic ID is provided then lists of common names for that ID
#         will be searched for a match.
#     return_type : {'values', 'name', 'dim'}, optional
#         'values' : Return an array of coordinate values.
#         'name' : Return the name of the coordinate.
#         'dim' : Return the dimension of the coordinate.
# 
#     Returns
#     -------
#     output : ndarray, string or int
# 
#     The generic coordinate names searched through are:
#     'lat' : ['lats', 'latitude', 'YDim','Y', 'y']
#     'lon' : ['long', 'lons', 'longitude', 'XDim', 'X', 'x']
#     'plev' : ['plevel', 'plevels', 'lev', 'level',
#               'levels', 'Height']
#     as well as capitalization options for coord_name (.upper(),
#     .lower(), .capitalize())
#     """
# 
#     def name_options(nm):
#         opts = {'lat' : ['lats', 'latitude', 'YDim','Y', 'y'],
#                 'lon' : ['long', 'lons', 'longitude', 'XDim', 'X', 'x'],
#                 'plev' : ['plevel', 'plevels', 'lev', 'level', 'levels',
#                           'Height']}
# 
#         nms = list(set([nm, nm.lower(), nm.upper(), nm.capitalize()]))
#         if opts.get(nm) is not None:
#             nms = list(nms) + opts[nm]
#         return nms
# 
#     names = name_options(coord_name)
# 
#     # Look in list of common coordinate names
#     if coord_name not in data.coords:
#         found = [i for i, s in enumerate(names) if s in data.coords]
# 
#         if len(found) == 0:
#             raise ValueError("Can't find coordinate name in data coords %s" %
#                              data.coords.keys())
#         if len(found) > 1:
#             raise ValueError('Conflicting possible coord names in coords %s'
#                 % data.coords.keys())
#         else:
#             coord_name = names[found[0]]
# 
#     if return_type == 'values':
#         output = data[coord_name].values.copy()
#     elif return_type == 'name':
#         output = coord_name
#     elif return_type == 'dim':
#         output = data.dims.index(coord_name)
#     else:
#         raise ValueError('Invalid return_type ' + return_type)
# 
#     return output
# 
# def latlon_equal(data1, data2, latname1=None, lonname1=None,
#                  latname2=None, lonname2=None):
#     """Return True if input DataArrays have the same lat-lon coordinates."""
# 
#     lat1 = get_coord(data1, 'lat', coord_name=latname1)
#     lon1 = get_coord(data1, 'lon', coord_name=lonname1)
#     lat2 = get_coord(data2, 'lat', coord_name=latname2)
#     lon2 = get_coord(data2, 'lon', coord_name=lonname2)
# 
#     is_equal = np.array_equal(lat1, lat2) and np.array_equal(lon1, lon2)
#     return is_equal
# 
# def lon_convention(lon):
#     """Return 360 if longitudes are 0-360E, 180 if 180W-180E.
# 
#     The output of this function can be used in the set_lon() function
#     to make two data arrays use a consistent longitude convention.
#     """
#     if lon.min() < 0:
#         return 180
#     else:
#         return 360
# 
# def set_lon(data, lonmax=360, lon=None, lonname=None):
#     """Set data longitudes to 0-360E or 180W-180E convention.
# 
#     Parameters
#     ----------
#     data : ndarray or xray.DataArray
#         Input data array with longitude as the last dimension
#     lonmax : int, optional
#         Maximum longitude for output data.  Set to 360 for 0-360E,
#         or set to 180 for 180W-180E.
#     lon : 1-D ndarray or list, optional
#         Longitudes of input data. Only used if data is an ndarray.
#         If data is an xray.DataArray, then lon = data['lon']
#     lonname : string, optional
#         Name of longitude coordinate in data, if data is a DataArray
# 
#     Returns
#     -------
#     If argument data is an ndarray:
#         data_out, lon_out : ndarray
#             The data and longitude arrays shifted to the selected
#             convention.
#     If argument data is an xray.DataArray:
#         data_out : xray.DataArray
#             DataArray object with data and longitude values shifted to
#             the selected convention.
#     """
# 
#     if isinstance(data, xray.DataArray):
#         lon = get_coord(data, 'lon')
#         if lonname is None:
#             lonname = get_coord(data, 'lon', 'name')
#         name, attrs, coords, dims_list = xr.meta(data)
#         vals = data.values
#     else:
#         vals = data
# 
#     lonmin = lonmax - 360
#     if lonmin >= lon.min() and lonmin <= lon.max():
#         lon0 = lonmin
#         start = True
#     else:
#         lon0 = lonmax
#         start = False
# 
#     vals_out, lon_out = basemap.shiftgrid(lon0, vals, lon, start=start)
# 
#     if isinstance(data, xray.DataArray):
#         coords[lonname].values = lon_out
#         data_out = xray.DataArray(vals_out, name=name, dims=dims_list,
#                                   coords=coords, attrs=attrs)
#         return data_out
#     else:
#         return vals_out, lon_out


import numpy as np
import matplotlib.pyplot as plt
import xray
import atmos.utils as utils
import atmos.plots as ap
import atmos.data as dat
from atmos.data import get_coord, latlon_equal, lon_convention, set_lon


# ----------------------------------------------------------------------
# NCEP2
# ----------------------------------------------------------------------

filename = 'data/more/ncep2_climatology_monthly.nc'
ds = dat.ncload(filename)
mon = ds['mon'].values
u = ds['u']

# Path: atmos/data.py
# def get_coord(data, coord_name, return_type='values'):
#     """Return values, name or dimension of coordinate in DataArray.
# 
#     Parameters
#     ----------
#     data : xray.DataArray
#         Data array to search for latitude coords.
#     coord_name : str
#         Coordinate to extract.  Can be the exact ID of the variable or
#         a generic ID ('lat', 'lon', 'plev', 'time', 'day', 'year').
#         If a generic ID is provided then lists of common names for that ID
#         will be searched for a match.
#     return_type : {'values', 'name', 'dim'}, optional
#         'values' : Return an array of coordinate values.
#         'name' : Return the name of the coordinate.
#         'dim' : Return the dimension of the coordinate.
# 
#     Returns
#     -------
#     output : ndarray, string or int
# 
#     The generic coordinate names searched through are:
#     'lat' : ['lats', 'latitude', 'YDim','Y', 'y']
#     'lon' : ['long', 'lons', 'longitude', 'XDim', 'X', 'x']
#     'plev' : ['plevel', 'plevels', 'lev', 'level',
#               'levels', 'Height']
#     as well as capitalization options for coord_name (.upper(),
#     .lower(), .capitalize())
#     """
# 
#     def name_options(nm):
#         opts = {'lat' : ['lats', 'latitude', 'YDim','Y', 'y'],
#                 'lon' : ['long', 'lons', 'longitude', 'XDim', 'X', 'x'],
#                 'plev' : ['plevel', 'plevels', 'lev', 'level', 'levels',
#                           'Height']}
# 
#         nms = list(set([nm, nm.lower(), nm.upper(), nm.capitalize()]))
#         if opts.get(nm) is not None:
#             nms = list(nms) + opts[nm]
#         return nms
# 
#     names = name_options(coord_name)
# 
#     # Look in list of common coordinate names
#     if coord_name not in data.coords:
#         found = [i for i, s in enumerate(names) if s in data.coords]
# 
#         if len(found) == 0:
#             raise ValueError("Can't find coordinate name in data coords %s" %
#                              data.coords.keys())
#         if len(found) > 1:
#             raise ValueError('Conflicting possible coord names in coords %s'
#                 % data.coords.keys())
#         else:
#             coord_name = names[found[0]]
# 
#     if return_type == 'values':
#         output = data[coord_name].values.copy()
#     elif return_type == 'name':
#         output = coord_name
#     elif return_type == 'dim':
#         output = data.dims.index(coord_name)
#     else:
#         raise ValueError('Invalid return_type ' + return_type)
# 
#     return output
# 
# def latlon_equal(data1, data2, latname1=None, lonname1=None,
#                  latname2=None, lonname2=None):
#     """Return True if input DataArrays have the same lat-lon coordinates."""
# 
#     lat1 = get_coord(data1, 'lat', coord_name=latname1)
#     lon1 = get_coord(data1, 'lon', coord_name=lonname1)
#     lat2 = get_coord(data2, 'lat', coord_name=latname2)
#     lon2 = get_coord(data2, 'lon', coord_name=lonname2)
# 
#     is_equal = np.array_equal(lat1, lat2) and np.array_equal(lon1, lon2)
#     return is_equal
# 
# def lon_convention(lon):
#     """Return 360 if longitudes are 0-360E, 180 if 180W-180E.
# 
#     The output of this function can be used in the set_lon() function
#     to make two data arrays use a consistent longitude convention.
#     """
#     if lon.min() < 0:
#         return 180
#     else:
#         return 360
# 
# def set_lon(data, lonmax=360, lon=None, lonname=None):
#     """Set data longitudes to 0-360E or 180W-180E convention.
# 
#     Parameters
#     ----------
#     data : ndarray or xray.DataArray
#         Input data array with longitude as the last dimension
#     lonmax : int, optional
#         Maximum longitude for output data.  Set to 360 for 0-360E,
#         or set to 180 for 180W-180E.
#     lon : 1-D ndarray or list, optional
#         Longitudes of input data. Only used if data is an ndarray.
#         If data is an xray.DataArray, then lon = data['lon']
#     lonname : string, optional
#         Name of longitude coordinate in data, if data is a DataArray
# 
#     Returns
#     -------
#     If argument data is an ndarray:
#         data_out, lon_out : ndarray
#             The data and longitude arrays shifted to the selected
#             convention.
#     If argument data is an xray.DataArray:
#         data_out : xray.DataArray
#             DataArray object with data and longitude values shifted to
#             the selected convention.
#     """
# 
#     if isinstance(data, xray.DataArray):
#         lon = get_coord(data, 'lon')
#         if lonname is None:
#             lonname = get_coord(data, 'lon', 'name')
#         name, attrs, coords, dims_list = xr.meta(data)
#         vals = data.values
#     else:
#         vals = data
# 
#     lonmin = lonmax - 360
#     if lonmin >= lon.min() and lonmin <= lon.max():
#         lon0 = lonmin
#         start = True
#     else:
#         lon0 = lonmax
#         start = False
# 
#     vals_out, lon_out = basemap.shiftgrid(lon0, vals, lon, start=start)
# 
#     if isinstance(data, xray.DataArray):
#         coords[lonname].values = lon_out
#         data_out = xray.DataArray(vals_out, name=name, dims=dims_list,
#                                   coords=coords, attrs=attrs)
#         return data_out
#     else:
#         return vals_out, lon_out


# Path: testing/testing-data-20150918.py
import numpy as np
import matplotlib.pyplot as plt
import xray
import atmos.utils as utils
import atmos.plots as ap
import atmos.data as dat
from atmos.data import get_coord, latlon_equal, lon_convention, set_lon



# ----------------------------------------------------------------------
# NCEP2
# ----------------------------------------------------------------------

filename = 'data/more/ncep2_climatology_monthly.nc'
ds = dat.ncload(filename)
mon = ds['mon'].values
u = ds['u']

v = ds['v']