Exemple #1
0
def _plot(df):
    import matplotlib.pyplot as plt
    plt.figure(figsize=(10,10))
    romspy.basemap()
    df2 = df['2012-08-01']
    ax = plt.gca()
    ax.quiver(df2.lon.values, df2.lat.values, df2.u.values, df2.v.values)
    plt.show()
def _plot(df):
    import matplotlib.pyplot as plt
    plt.figure(figsize=(10, 10))
    romspy.basemap()
    df2 = df['2012-08-01']
    ax = plt.gca()
    ax.quiver(df2.lon.values, df2.lat.values, df2.u.values, df2.v.values)
    plt.show()
Exemple #3
0
    def hview(self,
              vname,
              time=-1,
              k=20,
              fmt='%i',
              cff=None,
              unit='g',
              cblabel=None,
              levels=None,
              step=3,
              scale=5,
              method='pcolor'):
        """
        2015-11-08 ベクトルに対応させるために ax_heatmap と ax_vecmap を追加
        """
        print '{}, time={}, k={}, fmt={},'.format(vname, time, k, fmt),

        if cff is None:
            cff = romspy.unit2cff(vname, unit)
        if levels is None:
            levels = romspy.levels(vname, unit)
        if cblabel is None:
            cblabel = vname
        print 'cff={}'.format(cff)

        if vname == 'velocity':
            var = self.nc.variables['u']
        else:
            var = self.nc.variables[vname]

        if var.ndim > 2:
            t, dtime = self.get_time(time)

        if vname == 'velocity':
            self.add_quiver(vname, t, k, cff, step, scale)
        else:
            if 'pcolor' in method:
                self.add_pcolor(vname, t, k, cff, levels, cblabel, fmt)
            if 'contour' in method:
                self.add_contour(vname, t, k, cff, levels, cblabel, fmt)
            if 'fill' in method:
                self.add_contourf(vname, t, k, cff, levels, cblabel, fmt)

        # basemap
        if self.mapfile is not None:
            romspy.basemap(self.mapfile)

        # finalize
        if var.ndim == 2:
            plt.title('Model domein & bathymetry')
        elif ('avg' in self.ncfile) or ('dia' in self.ncfile):
            time_string = datetime.datetime.strftime(dtime, '%Y-%m')
            plt.title('Average ({})'.format(time_string))
        else:
            plt.title(datetime.datetime.strftime(dtime, '%Y-%m-%d %H:%M:%S'))

        return plt.gca()
Exemple #4
0
    def hview(self, vname, **kw):
        """
        2015-11-08 ベクトルに対応させるために ax_heatmap と ax_vecmap を追加
        """
        time = kw.pop('time', -1)
        k = kw.pop('k', 20)
        cff = kw.pop('cff', None)
        method = kw.pop('method', 'pcolor')
        unit = kw.pop('unit', 'g')
        levels = kw.pop('levels', None)

        if cff is None:
            cff = romspy.unit2cff(vname, unit)
        if levels is None:
            levels = romspy.levels(vname, unit)
        print 'cff={}'.format(cff)

        if vname == 'velocity':
            var = self.nc.variables['u']
        else:
            var = self.nc.variables[vname]

        if var.ndim > 2:
            t, dtime = self.get_time(time)

        if vname == 'velocity':
            self.add_quiver(vname, t, k, **kw)
        elif method == 'limit':
            self.add_pcolor_limit(vname, t, k, **kw)
        else:
            if 'rbf' in method:
                self.add_contourf_rbf(vname, t, k, cff, levels, **kw)
            if 'pcolor' in method:
                self.add_pcolor(vname, t, k, cff, levels, **kw)
            if 'contour' in method:
                self.add_contour(vname, t, k, cff, levels, **kw)
            if 'fill' in method:
                self.add_contourf(vname, t, k, cff, levels, **kw)

        if self.mapfile is not None:
            romspy.basemap(self.mapfile)

        if k == 20:
            plt.text(135.25, 34.25, 'surface layer')
        elif k == 1:
            plt.text(135.25, 34.25, 'bottom layer')

        if var.ndim == 2:
            plt.title('Model domein & bathymetry')
        elif ('avg' in self.ncfile) or ('dia' in self.ncfile):
            time_string = datetime.datetime.strftime(dtime,'%Y-%m')
            plt.title('Average ({})'.format(time_string))
        else:
            plt.title(datetime.datetime.strftime(dtime,'%Y-%m-%d %H:%M:%S'))

        return plt.gca()
Exemple #5
0
    def hview(self, vname, time=-1, k=20, fmt='%i', cff=None, unit='g', 
              cblabel=None, levels=None, step=3, scale=5, method='pcolor'):
        """
        2015-11-08 ベクトルに対応させるために ax_heatmap と ax_vecmap を追加
        """
        print '{}, time={}, k={}, fmt={},'.format(vname, time, k, fmt),

        if cff is None:
            cff = romspy.unit2cff(vname, unit)
        if levels is None:
            levels = romspy.levels(vname, unit)
        if cblabel is None:
            cblabel = vname
        print 'cff={}'.format(cff)

        if vname == 'velocity':
            var = self.nc.variables['u']
        else:
            var = self.nc.variables[vname]

        if var.ndim > 2:
            t, dtime = self.get_time(time)

        if vname == 'velocity':
            self.add_quiver(vname, t, k, cff, step, scale)
        else:
            if 'pcolor' in method:
                self.add_pcolor(vname, t, k, cff, levels, cblabel, fmt)
            if 'contour' in method:
                self.add_contour(vname, t, k, cff, levels, cblabel, fmt)
            if 'fill' in method:
                self.add_contourf(vname, t, k, cff, levels, cblabel, fmt)

        # basemap
        if self.mapfile is not None:
            romspy.basemap(self.mapfile)

        # print layer
        if k == 20:
            plt.text(135.25, 34.25, 'surface layer')
        elif k == 1:
            plt.text(135.25, 34.25, 'bottom layer')

        # finalize
        if var.ndim == 2:
            plt.title('Model domein & bathymetry')
        elif ('avg' in self.ncfile) or ('dia' in self.ncfile):
            time_string = datetime.datetime.strftime(dtime,'%Y-%m')
            plt.title('Average ({})'.format(time_string))
        else:
            plt.title(datetime.datetime.strftime(dtime,'%Y-%m-%d %H:%M:%S'))

        return plt.gca()
Exemple #6
0
def plot_stations(stafile):
    df = _read_stations(stafile)
    plt.figure(figsize=(8,8))
    plt.scatter(df.lon.values, df.lat.values)
    for i in df.index:
        #plt.text(df.lon[i], df.lat[i], df.id[i], backgroundcolor='w')
        plt.annotate(str(df.id[i]), xy=(df.lon[i], df.lat[i]), 
                xycoords='data',
                xytext=(df.lon[i]-0.025, df.lat[i]+0.015), 
                #textcoords='offset points',
                arrowprops=dict(arrowstyle="-")
                )
    romspy.basemap(mapfile)
    plt.gca().patch.set_facecolor('gray')
    plt.gca().patch.set_alpha(0.2)
    pngfile = stafile.replace('csv', 'png')
    romspy.savefig(pngfile)
    plt.show()
Exemple #7
0
def plot_stations(stafile):
    df = _read_stations(stafile)
    plt.figure(figsize=(8, 8))
    plt.scatter(df.lon.values, df.lat.values)
    for i in df.index:
        #plt.text(df.lon[i], df.lat[i], df.id[i], backgroundcolor='w')
        plt.annotate(
            str(df.id[i]),
            xy=(df.lon[i], df.lat[i]),
            xycoords='data',
            xytext=(df.lon[i] - 0.025, df.lat[i] + 0.015),
            #textcoords='offset points',
            arrowprops=dict(arrowstyle="-"))
    romspy.basemap(mapfile)
    plt.gca().patch.set_facecolor('gray')
    plt.gca().patch.set_alpha(0.2)
    pngfile = stafile.replace('csv', 'png')
    romspy.savefig(pngfile)
    plt.show()
Exemple #8
0
 def hview(self, var2d, vname, t, title, **kw):
     alpha = kw.pop('alpha', 0.5)
     fmt = kw.pop('fmt', '%i')  # %.1f
     label = kw.pop('label', None)
     contour = kw.pop('contour', True)
     contourf = kw.pop('contourf', True)
     clabel = kw.pop('clabel', True)
     linewidths = kw.pop('linewiths', 0.5)
     kw['extend'] = kw.pop('extend', 'both')
     
     ax = plt.gca()
     if contourf:
         CF = ax.contourf(self.X, self.Y, var2d, alpha=alpha, **kw)
         CB = plt.colorbar(CF)
     if contour:
         C = ax.contour(self.X, self.Y, var2d, colors='k', linewidths=linewidths, **kw)
     if clabel:
         C.clabel(colors='k', fmt=fmt)
     if label is not None:
         CB.ax.set_ylabel(label)
         title = label + title
     ax.set_title(title)
     romspy.basemap(self.mapfile)
Exemple #9
0
def _plot_map(ts, post_tmp, *args, **kw):
    """
    plot for "ts" dataframe

    ts: input DataFrame
    post_tmp: output file
    """
    start, end, vname, layer, stafile = args
    sta = _read_stations(stafile)
    if vname == 'DO':
        vmin, vmax = 0, 10
    elif vname == 'COD':
        vmin, vmax = 0, 8
    elif vname == 'temp':
        vmin, vmax = 10, 30

    for t in ts.index:
        time_str = datetime.datetime.strftime(t, '%Y-%m')
        s2 = pd.concat([sta, ts[time_str].T], axis=1).dropna()
        if len(s2) > 0:
            xs = s2.lon.values
            ys = s2.lat.values
            zs = s2.ix[:,-1].values
            x, y, z = _rbf(xs, ys, zs, **kw)
            #x, y, z = _grid(xs, ys, zs, bin=50)
            plt.pcolor(x, y, z, vmin=vmin, vmax=vmax)
            plt.colorbar()
            romspy.basemap(mapfile)
            plt.scatter(xs, ys, c=zs, s=30, vmin=vmin, vmax=vmax)
        else:
            romspy.basemap(mapfile)
        figfile = post_tmp.format(**locals())
        _mkdir(figfile)
        plt.title('{vname} (layer={layer}) {time_str}'.format(**locals()))
        plt.savefig(figfile, bbox_inches='tight')
        plt.clf()
Exemple #10
0
import numpy as np
import matplotlib.pyplot as plt
import romspy

inifile = '/home/okada/Data/ob500_ini_param6-ini_20120101.nc'
grdfile = '/home/okada/Data/ob500_grd-11_3.nc'

ini = netCDF4.Dataset(inifile, 'r')
grd = netCDF4.Dataset(grdfile, 'r')

h = grd['h'][:]
cs_r = grd['Cs_r'][:]
x_rho = grd['lon_rho'][0, :]
y_rho = grd['lat_rho'][:, 0]
X, Y = np.meshgrid(x_rho, y_rho)

zeta = ini['zeta'][0, :, :]
temp = ini['temp'][0, :, :, :]
N, M, L = temp.shape

depth = np.zeros_like(temp)
for n in range(N):
    depth[n, :, :] = cs_r[n] * (zeta + h)

temp10 = romspy.zslice(temp, depth, -1)

fig, ax = plt.subplots(1, 1, figsize=(6, 5))
romspy.basemap()
C = ax.contourf(X, Y, temp10)
#C.label()
CB = plt.colorbar(C)
Exemple #11
0
def reshape_wind(windfiles,
                 stafiles,
                 grdfile,
                 method='kriging',
                 smooth=1,
                 plot=False):
    u, v = {}, {}
    timedelta = datetime.timedelta(hours=3)
    for windfile in windfiles:
        print windfile
        if 'mp' in windfile:
            names = ['name', 'date', 'direction', 'wind']
            df = pd.read_csv(windfile,
                             encoding='Shift_JIS',
                             names=names,
                             skiprows=1,
                             na_values='*',
                             index_col='date')
            df['u'] = -np.sin(math.pi * df.direction / 180.0) * df.wind
            df['v'] = -np.cos(math.pi * df.direction / 180.0) * df.wind
            df.index = df.index.map(
                lambda t: datetime.datetime.strptime(t, '%Y/%m/%d %H:%M'))
            df = df.resample('12H', how='mean', loffset=timedelta)
            #df = df.resample('H', how='mean')
            station = int(windfile[-26:-24])
            u[station] = df.u.dropna()
            v[station] = df.v.dropna()
        elif 'jma' in windfile:
            df = pd.read_csv(windfile,
                             encoding='Shift_JIS',
                             na_values='--',
                             index_col='id')
            df['u'] = -np.sin(
                math.pi * df.wind_direction / 180.0) * df.wind_velocity
            df['v'] = -np.cos(
                math.pi * df.wind_direction / 180.0) * df.wind_velocity
            df.index = df.index.map(
                lambda t: datetime.datetime.strptime(t, '%Y/%m/%d %H:%M'))
            df = df.resample('12H', how='mean', loffset=timedelta)
            #df = df.resample('H', how='mean')
            station = windfile[windfile.find('jma_') + 4:-22]
            u[station] = df.u.dropna()
            v[station] = df.v.dropna()

    sta_mp = pd.read_csv(stafiles['mp'], index_col='station')
    sta_jma = pd.read_csv(stafiles['jma'], index_col='station')

    grd = netCDF4.Dataset(grdfile, 'r')
    xmesh = grd.variables['lon_rho'][:, :]
    ymesh = grd.variables['lat_rho'][:, :]
    grd.close()

    xgrid = xmesh[0, :]
    ygrid = ymesh[:, 0]

    td = len(df)
    xd = len(xgrid)
    yd = len(ygrid)
    u3d = np.zeros(shape=[td, yd, xd])
    v3d = np.zeros_like(u3d)
    time_wind = np.zeros(shape=[td])

    for i, t in enumerate(df.index):
        X, Y, U, V = [], [], [], []
        for station in u.keys():
            try:
                U.append(u[station][t])
                V.append(v[station][t])
                if type(station) == int:
                    X.append(sta_mp.lon[station])
                    Y.append(sta_mp.lat[station])
                elif type(station) == str:
                    X.append(sta_jma.x[station])
                    Y.append(sta_jma.y[station])
            except:
                pass
        print i, t, len(Y)

        if method == 'kriging_gaussian':
            ukrig = OrdinaryKriging(X,
                                    Y,
                                    U,
                                    variogram_model='gaussian',
                                    verbose=False,
                                    enable_plotting=False)
            vkrig = OrdinaryKriging(X,
                                    Y,
                                    V,
                                    variogram_model='gaussian',
                                    verbose=False,
                                    enable_plotting=False)
            umesh, ss = ukrig.execute('grid', xgrid, ygrid)
            vmesh, ss = vkrig.execute('grid', xgrid, ygrid)

        elif method == 'kriging_linear':
            ukrig = OrdinaryKriging(X,
                                    Y,
                                    U,
                                    variogram_model='linear',
                                    verbose=False,
                                    enable_plotting=False)
            vkrig = OrdinaryKriging(X,
                                    Y,
                                    V,
                                    variogram_model='linear',
                                    verbose=False,
                                    enable_plotting=False)
            umesh, ss = ukrig.execute('grid', xgrid, ygrid)
            vmesh, ss = vkrig.execute('grid', xgrid, ygrid)

        elif method == 'rbf':
            urbf = Rbf(X, Y, U)
            vrbf = Rbf(X, Y, V)
            umesh = urbf(xmesh, ymesh)
            vmesh = vrbf(xmesh, ymesh)

        elif method == 'rbf_gaussian':
            urbf = Rbf(X, Y, U, function='inverse')
            vrbf = Rbf(X, Y, V, function='inverse')
            umesh = urbf(xmesh, ymesh)
            vmesh = vrbf(xmesh, ymesh)

        elif method == 'rbf_linear':
            urbf = Rbf(X, Y, U, function='inverse')
            vrbf = Rbf(X, Y, V, function='inverse')
            umesh = urbf(xmesh, ymesh)
            vmesh = vrbf(xmesh, ymesh)

        elif method == 'rbf_inverse':
            urbf = Rbf(X, Y, U, function='inverse')
            vrbf = Rbf(X, Y, V, function='inverse')
            umesh = urbf(xmesh, ymesh)
            vmesh = vrbf(xmesh, ymesh)

        elif method == 'rbf_inverse_smooth':
            urbf = Rbf(X, Y, U, function='inverse', smooth=smooth)
            vrbf = Rbf(X, Y, V, function='inverse', smooth=smooth)
            umesh = urbf(xmesh, ymesh)
            vmesh = vrbf(xmesh, ymesh)

        if plot == 'pcolor' and i == 0:
            plt.figure(figsize=[15, 5])
            plt.subplot(1, 2, 1)
            plt.pcolor(xmesh, ymesh, umesh, vmin=-1, vmax=1)
            plt.colorbar()
            plt.subplot(1, 2, 2)
            plt.pcolor(xmesh, ymesh, vmesh, vmin=-1, vmax=1)
            plt.colorbar()
            plt.show()

        elif plot == 'quiver' and i == 0:
            plt.figure(figsize=[10, 10])
            romspy.basemap('F:/okada/notebook/deg_OsakaBayMap_okada.bln')
            plt.quiver(xmesh[::3, ::3],
                       ymesh[::3, ::3],
                       umesh[::3, ::3],
                       vmesh[::3, ::3],
                       units='width',
                       angles='xy',
                       scale=100)
            plt.quiver(X,
                       Y,
                       U,
                       V,
                       color='r',
                       units='xy',
                       angles='xy',
                       scale=100)
            plt.show()

        u3d[i, :, :] = umesh
        v3d[i, :, :] = vmesh
        time_wind[i] = netCDF4.date2num(t, romspy.JST_days)

    return u3d, v3d, time_wind
Exemple #12
0
            lon, lat = x, y
        except:
            lon, lat = xy2lonlat(x, y, grdfile)
        if type == varid:
            if not lon in check.keys():
                print i, t, x, y, z, type, v
                check[lon] = z
                sc = ax.scatter(lon, lat, c=v*cff, vmin=vmin, vmax=vmax, s=200)
                #plt.text(lon-0.01, lat-0.02, str(round(v,1)))
            elif z < check[lon]:
                print i, t, x, y, z, type, v
                check[lon] = z
                sc = ax.scatter(lon, lat, c=v*cff, vmin=vmin, vmax=vmax, s=200)

    return sc


if __name__ == '__main__':
    import datetime
    romspy.cmap('jet')
    obsfile = '/home/okada/Data/ob500_obs_2012_mp-2.nc'
    varid = 15
    plotdate = datetime.datetime(2012,8,3,0)
    vmin = 0
    vmax = 10
    cff = romspy.mol2g_O2
    romspy.basemap()
    sc = hplot_values(obsfile, varid, plotdate, vmin=vmin, vmax=vmax, cff=cff)
    plt.colorbar(sc)
    plt.show()