コード例 #1
0
def write_initial_positions(index, drifter, grid):
    bathy, nav_lon, nav_lat = tidetools.get_bathy_data(grid)
    xind, yind = tidetools.find_closest_model_point(drifter['lon'][index],
                                                    drifter['lat'][index],
                                                    nav_lon,
                                                    nav_lat,
                                                    bathy,
                                                    allow_land=True)
    xp, yp = find_start_point(nav_lon, nav_lat, xind, yind, drifter, index)
    initial_conditions = np.ones((81, 5))
    # longitude index
    initial_conditions[0:-1:3, 0] = yp
    initial_conditions[1:-1:3, 0] = yp - 2.5
    initial_conditions[2:81:3, 0] = yp + 2.5
    # latitude index
    for i in range(0, 81, 9):
        initial_conditions[0 + i:3 + i, 1] = xp + 0.5
        initial_conditions[0 + 3 + i:3 + 3 + i, 1] = xp - 2
        initial_conditions[0 + 6 + i:3 + 6 + i, 1] = xp + 3
    # depth
    initial_conditions[0:27, 2] = -1.5
    initial_conditions[27:54, 2] = -2.5
    initial_conditions[54:81, 2] = -3.5
    # time
    tp = (drifter['time'][index].hour + drifter['time'][index].minute / 60. +
          drifter['time'][index].second / 3600.)
    for i in range(0, 81, 27):
        initial_conditions[0 + i:9 + i, 3] = tp
        initial_conditions[0 + 9 + i:9 + 9 + i, 3] = tp + 0.5
        initial_conditions[0 + 18 + i:9 + 18 + i, 3] = tp - 0.5

    np.savetxt('initial_positions.txt', initial_conditions, fmt='%10.5f')
コード例 #2
0
def retrieve_nowcast_data(lon, lat, date, obs_depth, field, grid_B, mesh_mask):
    """Gather nowcast field daily mean, min and max at lat, lon on date,
    interpolated to obs_depth.

    :arg lon: longitude point
    :type lon: real number

    :arg lat: latitude point
    :type lat: real number

    :arg date: simulation date
    :type date: datetime

    :arg obs_depth: array of depths to be interpolated to
    :type obs_depth: numpy array

    :arg field: name of variable to load, e.g 'vosaline' or 'votemper'
    :type field: string

    :arg grid_B: model bathymetry
    :type grid_B: netCDF4 object

    :arg mesh_mask: model mesh mask
    :type mesh_mask: netCDF4 object

    :returns: model_d_interp, model_max, model_min - numpy arrays
    """
    # look up model grid point
    bathy, lons, lats = tidetools.get_bathy_data(grid_B)
    j, i = tidetools.find_closest_model_point(lon, lat, lons, lats, bathy)
    # loading
    grid_d = results_dataset('1d', 'grid_T', date)
    grid_h = results_dataset('1h', 'grid_T', date)
    model_d = grid_d.variables[field][0, :, j, i]
    model_h = grid_h.variables[field][:, :, j, i]
    gdep = mesh_mask.variables['gdept'][0, :, j, i]
    # masking
    tmask = mesh_mask.variables['tmask'][:, :, j, i]
    tmask = 1 - tmask + np.zeros(model_h.shape)
    model_d = np.ma.array(model_d, mask=tmask[0, :])
    gdep_mask = np.ma.array(gdep, mask=tmask[0, :])
    model_h = np.ma.array(model_h, mask=tmask)
    # interpolate to observed depth
    model_d_interp = comparisons.interpolate_depth(model_d, gdep_mask,
                                                   obs_depth)
    model_h_interp = np.zeros((model_h.shape[0], len(obs_depth)))
    for t in np.arange(model_h.shape[0]):
        model_h_interp[t, :] = comparisons.interpolate_depth(
            model_h[t, :], gdep_mask, obs_depth)
    # daily max and min
    model_max = np.max(model_h_interp, axis=0)
    model_min = np.min(model_h_interp, axis=0)

    return model_d_interp, model_max, model_min
コード例 #3
0
ファイル: JEMS.py プロジェクト: SalishSeaCast/analysis-nancy
def compare_JEMS_model(stn, sdt, edt, grid_B, results_home,
                       smin=5, smax=31, tmin=8, tmax=12):
    """Comparison between all JEMS T+S data in a date range and model nowcasts.

    :arg stn: The JEMS station name
    :type stn: string

    :arg sdt: the start date of the date range
    :type sdt: datetime object

    :arg edt: the end date of the date range
    :type edt: datetime object

    :arg grid_B: the model bathymetry
    :type grid_B: netCDF handle

    :arg results_home: the path to the model results
    :type results_home: string

    :arg smin: minimum salinity for axis
    :type smin: float

    :arg smax: maximum salinity for axis
    :type smax: float

    :arg tmin: minimum temperature for axis
    :type tmin: float

    :arg tmax: maximum salinity for axis
    :type tmax: float

    :returns: figmap, fig - figure objects for the map and comaprisons plots
    """

    # Observations
    lat = SITES[stn]['lat']
    lon = SITES[stn]['lon']
    data = load_JEMS_csv(stn)
    data = isolate_dates(data, sdt, edt)
    data = data.groupby('date')

    # Model grid
    X = grid_B.variables['nav_lon'][:]
    Y = grid_B.variables['nav_lat'][:]
    bathy = grid_B.variables['Bathymetry'][:]
    [j, i] = tidetools.find_closest_model_point(lon, lat, X, Y, bathy)

    # Set up loop and figure
    num = data.ngroups
    fig, axs = plt.subplots(num, 2, figsize=(10, 4*num))
    try:
        for day, axS, axT in zip(data.groups, axs[:, 0], axs[:, 1]):
            plot_comparisons(day, axS, axT, results_home, data, stn, j, i)
            axS.set_xlim([smin, smax])
            axS.set_ylim([SITES[stn]['depth'], 0])
            axT.set_xlim([tmin, tmax])
            axT.set_ylim([SITES[stn]['depth'], 0])
        axS.set_xlabel('Salinity (psu)')
        axT.set_xlabel('Temperature (deg C)')
    except IndexError:
        day = data.groups.keys()[0]
        axS = axs[0]
        axT = axs[1]
        plot_comparisons(day, axS, axT, results_home, data, stn, j, i)
        axS.set_xlim([smin, smax])
        axS.set_ylim([SITES[stn]['depth'], 0])
        axT.set_xlim([tmin, tmax])
        axT.set_ylim([SITES[stn]['depth'], 0])
        axS.set_xlabel('Salinity (psu)')
        axT.set_xlabel('Temperature (deg C)')

    # map
    figmap, ax = plt.subplots(1, 1)
    viz_tools.plot_coastline(ax, grid_B, coords='map')
    ax.plot(lon, lat, 'o')
    ax.set_title(stn)

    return figmap, fig
コード例 #4
0
def compare_cast_hourly(month,
                        model_year,
                        field,
                        data_obs,
                        model_path,
                        xmin=-124,
                        xmax=-122,
                        ymin=48,
                        ymax=50,
                        zmin=0,
                        zmax=300,
                        vmin=10,
                        vmax=32):
    """Comparison between model and observations at every cast in a given month
    Model daily average is compared witth houlry std errors
    """
    # Load model grid
    grid = '/data/nsoontie/MEOPAR/NEMO-forcing/grid/bathy_meter_SalishSea2.nc'
    f = nc.Dataset(grid)
    bathy = f.variables['Bathymetry'][:]
    X = f.variables['nav_lon'][:]
    Y = f.variables['nav_lat'][:]
    mesh = '/data/nsoontie/MEOPAR/NEMO-forcing/grid/mesh_mask_SalishSea2.nc'
    g = nc.Dataset(mesh)
    depth_mod = g.variables['gdept_0'][0, :]

    # Model variables
    if field == 'Salinity':
        model_field = 'vosaline'
    elif field == 'Temperature':
        model_field = 'votemper'

    # plot obs and model
    data_m = data_obs[data_obs['Month'] == month]
    num_casts = len(data_m.index)
    fig, axs = plt.subplots(num_casts, 2, figsize=(10, 3.5 * num_casts))
    cast = 0
    for dep_obs, var_obs, lon, lat, day, year in zip(
            data_m['Depth'], data_m[field], data_m['Longitude'],
            data_m['Latitude'], data_m['Day'], data_m['Year']):
        # model grid points
        try:
            ax = axs[cast, 0]
            axm = axs[cast, 1]
        except IndexError:
            ax = axs[0]
            axm = axs[1]
        j, i = tidetools.find_closest_model_point(lon, lat, X, Y, bathy)
        date = datetime.datetime(year, month, day)
        if date >= FIRST_NOWCAST:
            hourly_grid = get_hourly_grid(date, model_path)
            depth_mod = hourly_grid.variables['deptht'][:]
            max_h, min_h, var_plot = calculate_hourly_ext(
                model_field, hourly_grid, j, i)
        else:
            var_model = early_model_data(date, j, i, '1h', 'grid_T',
                                         model_field, model_path)
            var_plot = np.mean(var_model, axis=0)
            min_h = np.min(var_model, axis=0)
            max_h = np.max(var_model, axis=0)

        # plot model
        ax.plot(var_plot, depth_mod, '-b', label='daily mean', alpha=0.5)
        ax.plot(max_h, depth_mod, 'k--', label='daily max')
        ax.plot(min_h, depth_mod, 'k:', label='daily min')
        # plot observations and location on map
        ax.plot(var_obs, dep_obs, '-*r', label='obs')
        axm.plot(lon, lat, '*r')
        # Set plot axis and labels
        ax.set_ylim([zmax, zmin])
        ax.set_xlim([vmin, vmax])
        ax.set_ylabel('Depth [m]')
        ax.set_xlabel(field)
        # plot mode coastline
        viz_tools.plot_coastline(axm, f, coords='map')
        axm.set_ylim([ymin, ymax])
        axm.set_xlim([xmin, xmax])
        axm.set_title('{}-{}-{}'.format(year, month, day))
        # legend
        ax.legend(loc=0)
        cast = cast + 1

    return fig
コード例 #5
0
def compare_cast_model(month,
                       model_year,
                       field,
                       data_obs,
                       model_path,
                       xmin=-124,
                       xmax=-122,
                       ymin=48,
                       ymax=50,
                       zmin=0,
                       zmax=300,
                       vmin=10,
                       vmax=32,
                       x=7):
    """Comparison between model and observations at every cast in a given month
    Model is compared x days before and after cast date
    """
    # Load model grid
    grid = '/data/nsoontie/MEOPAR/NEMO-forcing/grid/bathy_meter_SalishSea2.nc'
    f = nc.Dataset(grid)
    bathy = f.variables['Bathymetry'][:]
    X = f.variables['nav_lon'][:]
    Y = f.variables['nav_lat'][:]

    # date ranges based on month and model_year
    date = datetime.datetime(model_year, month, 1)
    sdt = date - datetime.timedelta(days=31)
    edt = date + datetime.timedelta(days=60)

    # Model variables and nowcast/spinup?
    if field == 'Salinity':
        model_field = 'vosaline'
    elif field == 'Temperatute':
        model_field = 'votemper'
    # Is this a nowcast?
    if model_year == 2014 or model_year == 2015:
        nowcast_flag = True
    else:
        nowcast_flag = False

    # load model variables
    depth_mod, var_mod, dates_mod = load_model(model_path,
                                               sdt,
                                               edt,
                                               model_field,
                                               nowcast_flag=nowcast_flag)
    # plot obs and model
    data_m = data_obs[data_obs['Month'] == month]
    num_casts = len(data_m.index)
    fig, axs = plt.subplots(num_casts, 2, figsize=(10, 3.5 * num_casts))
    cast = 0
    for dep_obs, var_obs, lon, lat, day, year in zip(
            data_m['Depth'], data_m[field], data_m['Longitude'],
            data_m['Latitude'], data_m['Day'], data_m['Year']):
        # model grid points
        try:
            ax = axs[cast, 0]
            axm = axs[cast, 1]
        except IndexError:
            ax = axs[0]
            axm = axs[1]
        [j, i] = tidetools.find_closest_model_point(lon, lat, X, Y, bathy)
        # model time index
        t_ind = []
        for count, date in enumerate(dates_mod):
            if date.day == day:
                if date.month == month:
                    t_ind.append(count)
                    t_ind.append(count - x)  # x days earlier
                    t_ind.append(count + x)  # x days later
        labels = [
            'same day', '{} days earlier'.format(x), '{} days later'.format(x)
        ]
        colors = ['b', 'g', 'k']
        for ii, t in enumerate(t_ind):
            try:
                var_plot = var_mod[t, :, j, i]
                var_plot = np.ma.masked_values(var_plot, 0)
                if j:
                    ax.plot(var_plot,
                            depth_mod,
                            '-b',
                            color=colors[ii],
                            label=labels[ii],
                            alpha=0.5)
            except IndexError:
                print('No model data for {}/{}, '
                      '{}'.format(day, month, labels[ii]))
        # plot observations and location on map
        ax.plot(var_obs, dep_obs, '-*r', label='obs')
        axm.plot(lon, lat, '*r')
        # Set plot axis and labels
        ax.set_ylim([zmax, zmin])
        ax.set_xlim([vmin, vmax])
        ax.set_ylabel('Depth [m]')
        ax.set_xlabel(field)

        # plot mode coastline
        viz_tools.plot_coastline(axm, f, coords='map')
        axm.set_ylim([ymin, ymax])
        axm.set_xlim([xmin, xmax])
        axm.set_title('{}-{}-{}'.format(year, month, day))

        # legend
        ax.legend(loc=0)
        cast = cast + 1

    return fig
コード例 #6
0
def compare_model_obs(month,
                      model_year,
                      field,
                      data_obs,
                      model_path,
                      xmin=-124,
                      xmax=-122,
                      ymin=48,
                      ymax=50,
                      zmin=0,
                      zmax=300,
                      vmin=10,
                      vmax=32):
    """Compares the observations from WOD with model output on the same day
    and at a close grid point.
    Comparisons are during single month.
    field is compared ('Temperature' or 'Salinity' )
    Observations stored in data_obs (DataFrame)
    Model_path defines where the model data is stored(can be nowcast or spinup)
    """
    # Load model grid
    grid = '/data/nsoontie/MEOPAR/NEMO-forcing/grid/bathy_meter_SalishSea2.nc'
    f = nc.Dataset(grid)
    bathy = f.variables['Bathymetry'][:]
    X = f.variables['nav_lon'][:]
    Y = f.variables['nav_lat'][:]

    fig, [ax, axm] = plt.subplots(1, 2, figsize=(10, 3))

    # date ranges based on month and model_year
    sdt = datetime.datetime(model_year, month, 1)
    edt = sdt + datetime.timedelta(days=31)

    # Model variables and nowcast/spinup?
    if field == 'Salinity':
        model_field = 'vosaline'
    elif field == 'Temperatute':
        model_field = 'votemper'
    # Is this a nowcast?
    if model_year == 2014 or model_year == 2015:
        nowcast_flag = True
        title = 'Nowcast'
    else:
        nowcast_flag = False
        title = 'Spinup'

    # load model variables
    depth_mod, var_mod, dates_mod = load_model(model_path,
                                               sdt,
                                               edt,
                                               model_field,
                                               nowcast_flag=nowcast_flag)

    # plot obs and model
    data_m = data_obs[data_obs['Month'] == month]
    for dep_obs, var_obs, lon, lat, day in zip(data_m['Depth'], data_m[field],
                                               data_m['Longitude'],
                                               data_m['Latitude'],
                                               data_m['Day']):
        # model grid points
        [j, i] = tidetools.find_closest_model_point(lon, lat, X, Y, bathy)
        # model time index
        t_ind = []
        for count, date in enumerate(dates_mod):
            if date.month == month:
                if date.day == day:
                    t_ind = count
        var_plot = var_mod[t_ind, :, j, i]
        var_plot = np.ma.masked_values(var_plot, 0)

        ax.plot(var_obs, dep_obs, '-*r', label='obs', alpha=0.5)
        if j:
            try:
                ax.plot(var_plot, depth_mod, '-ob', label='model', alpha=0.5)
            except ValueError:
                print('No model data for {}/{}'.format(day, month))
        # plot location on map
        axm.plot(lon, lat, '*r')

    # Set plot axis and labels
    ax.set_ylim([zmax, zmin])
    ax.set_xlim([vmin, vmax])
    ax.set_title(title)
    ax.set_ylabel('Depth [m]')
    ax.set_xlabel(field)

    # plot mode coastline
    viz_tools.plot_coastline(axm, f, coords='map')
    axm.set_ylim([ymin, ymax])
    axm.set_xlim([xmin, xmax])
    axm.set_title('Month {}'.format(month))

    # fake the legend
    simObs, = ax.plot(-1, 0, 'r*')
    simMod, = ax.plot(-1, 0, 'bo')
    ax.legend([simObs, simMod], ['obs', 'model'], loc=0)

    return fig