# Path: atmos/utils.py
# def print_if(msg, condition, printfunc=None):
#     """ Print msg if condition is True"""
#     if condition:
#         if printfunc is not None:
#             printfunc(msg)
#         else:
#             print(msg)
# 
# Path: atmos/constants.py

# 
# 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


import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import xarray as xray
import statsmodels.api as sm
import scipy.signal as signal
import collections
import atmos.utils as utils
import atmos.plots as ap
import atmos.data as dat
import atmos.variables as av
from mpl_toolkits.basemap import Basemap
from datetime import datetime
from atmos.utils import print_if
from atmos.constants import const as constants
from atmos.data import get_coord
plt.scatter(x, y)
x_in = sm.add_constant(x)
fit = sm.OLS(y, x_in).fit()
ypred = fit.predict(x_in)
plt.plot(x, ypred, 'r')
print fit.summary()

# ----------------------------------------------------------------------
# Multiple linear regression

nobs = 100
x = np.random.random((nobs, 2))
x = sm.add_constant(x)
beta = [1, .1, .5]
e = np.random.random(nobs)
y = np.dot(x, beta) + e
results = sm.OLS(y, x).fit()
print results.summary()
# ----------------------------------------------------------------------
# Read some data from OpenDAP url

url = ('http://goldsmr3.sci.gsfc.nasa.gov/opendap/MERRA_MONTHLY/'
    'MAIMCPASM.5.2.0/1979/MERRA100.prod.assim.instM_3d_asm_Cp.197901.hdf')

ds = xray.open_dataset(url)
T = ds['T']
ps = ds['PS']
q = ds['QV']
plev = get_coord(T, 'plev')
lat = get_coord(T, 'lat')

# Path: atmos/utils.py
# def print_if(msg, condition, printfunc=None):
#     """ Print msg if condition is True"""
#     if condition:
#         if printfunc is not None:
#             printfunc(msg)
#         else:
#             print(msg)
# 
# Path: atmos/constants.py

# 
# 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


# Path: scripts/scratchpad.py
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import xarray as xray
import statsmodels.api as sm
import scipy.signal as signal
import collections
import atmos.utils as utils
import atmos.plots as ap
import atmos.data as dat
import atmos.variables as av
from mpl_toolkits.basemap import Basemap
from datetime import datetime
from atmos.utils import print_if
from atmos.constants import const as constants
from atmos.data import get_coord

plt.scatter(x, y)
x_in = sm.add_constant(x)
fit = sm.OLS(y, x_in).fit()
ypred = fit.predict(x_in)
plt.plot(x, ypred, 'r')
print fit.summary()

# ----------------------------------------------------------------------
# Multiple linear regression

nobs = 100
x = np.random.random((nobs, 2))
x = sm.add_constant(x)
beta = [1, .1, .5]
e = np.random.random(nobs)
y = np.dot(x, beta) + e
results = sm.OLS(y, x).fit()
print results.summary()
# ----------------------------------------------------------------------
# Read some data from OpenDAP url

url = ('http://goldsmr3.sci.gsfc.nasa.gov/opendap/MERRA_MONTHLY/'
    'MAIMCPASM.5.2.0/1979/MERRA100.prod.assim.instM_3d_asm_Cp.197901.hdf')

ds = xray.open_dataset(url)
T = ds['T']
ps = ds['PS']
q = ds['QV']
plev = get_coord(T, 'plev')
lat = get_coord(T, 'lat')

lon = get_coord(T, 'lon')