Exemplo n.º 1
0
def run():
    input_dir = get_dir('hycom_input')
    output_dir = get_dir('xpresspearl_output')
    output_name = 'pts_parcels_2008-2009'
    time0, lon0, lat0 = get_release_time_lon_lat()
    start_date = datetime(2008, 5, 22)
    end_date = datetime(2010, 5, 22)
    indices = _get_io_indices_from_netcdf()
    kh = get_kh_value_from_grid_size(lat0[0])
    interp_method = 'linear'
    # get paths
    ncfiles = get_daily_ncfiles_in_time_range(input_dir, start_date, end_date)
    output_path = output_dir + output_name
    # create fieldset
    filenames = [input_dir + ncfile for ncfile in ncfiles]
    variables = {'U': 'u', 'V': 'v'}
    dimensions = {'lat': 'lat', 'lon': 'lon', 'time': 'time'}
    fset = FieldSet.from_netcdf(filenames,
                                variables,
                                dimensions,
                                indices=indices)
    # add constant horizontal diffusivity (zero on land)
    lm = LandMask.read_from_netcdf()
    kh2D = kh * np.ones(lm.mask.shape)
    kh2D[lm.mask.astype('bool')] = 0.0  # diffusion zero on land
    kh2D_subset = kh2D[indices['lat'], :][:, indices['lon']]
    fset.add_field(
        Field('Kh_zonal',
              data=kh2D_subset,
              lon=fset.U.grid.lon,
              lat=fset.U.grid.lat,
              mesh='spherical',
              interp_method=interp_method))
    fset.add_field(
        Field('Kh_meridional',
              data=kh2D_subset,
              lon=fset.U.grid.lon,
              lat=fset.U.grid.lat,
              mesh='spherical',
              interp_method=interp_method))
    # montly release
    pset = ParticleSet(fieldset=fset,
                       pclass=JITParticle,
                       lon=lon0,
                       lat=lat0,
                       time=time0)
    # execute
    run_time = timedelta(days=(end_date - start_date).days)
    dt = timedelta(hours=1)
    output_interval = 24
    kernel = pset.Kernel(AdvectionRK4) + pset.Kernel(DiffusionUniformKh)
    output_file = pset.ParticleFile(name=output_path,
                                    outputdt=dt * output_interval)
    pset.execute(kernel,
                 runtime=run_time,
                 dt=dt,
                 output_file=output_file,
                 verbose_progress=True,
                 recovery={ErrorCode.ErrorOutOfBounds: delete_particle})
Exemplo n.º 2
0
def run_neutral_iod_2009_with_wind(
        output_name='neutral_iod_2009_with_3p-wind'):
    output_dir = get_dir('pts_output')
    restart_path = get_dir('pts_output') + 'neutral_iod_2008_with_3p-wind.nc'
    restart = RestartParticles(restart_path)
    start_date = restart.time0[0]
    end_date = datetime(2009, 12, 31)
    run_hycom_cfsr_subset_monthly_release(output_dir, output_name,
                                          restart.time0, restart.lon0,
                                          restart.lat0, start_date, end_date)
Exemplo n.º 3
0
def run_neutral_iod(output_name='neutral_iod_2008-2009',
                    constant_release=False):
    input_dir = get_dir('hycom_input')
    output_dir = get_dir('pts_output')
    start_date = datetime(2008, 1, 1, 12, 0)
    end_date = datetime(2009, 12, 31)
    io_sources = IORiverParticles.get_from_netcdf(
        start_date, constant_release=constant_release)
    run_hycom_subset_monthly_release(input_dir, output_dir, output_name,
                                     io_sources.time0, io_sources.lon0,
                                     io_sources.lat0, start_date, end_date)
Exemplo n.º 4
0
def christmas_island_animation():
    particles = BeachingParticles.read_from_netcdf(
        get_dir('christmas_island_input'))

    lon_range = [100, 115]
    lat_range = [-12, -5]
    output_name = 'plastic_waste_christmas_island'
    logo_extent = (lon_range[1] - 2, lon_range[1] - 0.1, lat_range[0] + 0.2,
                   lat_range[0] + 2)
    create_animation_beached(particles.time,
                             particles.lon,
                             particles.lat,
                             None,
                             None,
                             output_name=output_name,
                             lon_range=lon_range,
                             lat_range=lat_range,
                             text='Christmas Island',
                             text_lon=105.6,
                             text_lat=-11.,
                             dpi=300,
                             fps=2,
                             title_style='month',
                             add_uwa_logo=True,
                             logo_extent=logo_extent)
Exemplo n.º 5
0
 def add_eke(self,input_path_mean_currents=get_dir('mean_ocean_surface_currents')):
     if getattr(self,'u') is not None and getattr(self,'v') is not None:
         netcdf = Dataset(input_path_mean_currents)
         u_mean = netcdf['u'][:]
         v_mean = netcdf['v'][:]
         eke_values = 0.5*((self.u.values-u_mean)**2+(self.v.values-v_mean)**2)
         self.eke = Quantity4D('eke',eke_values,units='m2/s2')
Exemplo n.º 6
0
def get_iot_plastic_measurements(input_path=get_dir('iot_measurements')):
    df = pd.read_excel(input_path, sheet_name='Event_details', skiprows=5)
    time = np.array([d.to_pydatetime() for d in df['Date']])
    lon = np.array(df['Longitude'])
    lat = np.array(df['Latitude'])
    n_plastic = np.array(df['Total'])
    kg_plastic = np.array(df['Weight Kg'])
    return time, lon, lat, n_plastic, kg_plastic
Exemplo n.º 7
0
def get_christmas_plastic_measurements(input_path=get_dir('iot_measurements')):
    time, lon, lat, n_plastic, kg_plastic = get_iot_plastic_measurements(
        input_path=input_path)
    lon_range, lat_range = get_christmas_box_lon_lat_range()
    l_lon = np.logical_and(lon_range[0] <= lon, lon <= lon_range[1])
    l_lat = np.logical_and(lat_range[0] <= lat, lat <= lat_range[1])
    l_ci = np.logical_and(l_lon, l_lat)
    return time[l_ci], lon[l_ci], lat[l_ci], n_plastic[l_ci], kg_plastic[l_ci]
Exemplo n.º 8
0
def _get_parcels_particles_path(file_description,
                                year=None,
                                dir_description='pts_output'):
    parcels_dir = get_dir(dir_description)
    if year is None:
        parcels_path = f'{parcels_dir}{file_description}.nc'
        return parcels_path
    parcels_path = f'{parcels_dir}{file_description}{year}.nc'
    return parcels_path
Exemplo n.º 9
0
def _get_non_beaching_path(basin_name,
                           description,
                           extra_description=None,
                           dir_description='pts_processed'):
    processed_dir = get_dir(dir_description)
    if extra_description is None:
        non_beached_path = f'{processed_dir}{basin_name}_{description}.nc'
    else:
        non_beached_path = f'{processed_dir}{basin_name}_{extra_description}_{description}.nc'
    return non_beached_path
Exemplo n.º 10
0
def _get_beaching_path(basin_name,
                       dx,
                       p,
                       description,
                       extra_description=None,
                       dir_description='pts_processed'):
    processed_dir = get_dir(dir_description)
    p_str = str(p).replace('.', '')
    if extra_description is None:
        beached_path = f'{processed_dir}{basin_name}_{description}_{dx}km_p{p_str}.nc'
    else:
        beached_path = f'{processed_dir}{basin_name}_{description}_{dx}km_p{p_str}_{extra_description}.nc'
    return beached_path
Exemplo n.º 11
0
def get_output_path(basin_name,
                    dx,
                    p,
                    description,
                    file_format,
                    extra_description=None,
                    dir_description='pts_postprocessed'):
    output_dir = get_dir(dir_description)
    p_str = str(p).replace('.', '')
    if extra_description is None:
        output_path = f'{output_dir}{basin_name}_{description}_{dx}km_p{p_str}.{file_format}'
    else:
        output_path = f'{output_dir}{basin_name}_{description}_{dx}km_p{p_str}_{extra_description}.{file_format}'
    return output_path
Exemplo n.º 12
0
def figure4_seasonal_density(input_path=get_dir('iot_input_density'),
                             output_path=None,
                             plot_style='plot_tools/plot.mplstyle'):
    lon_range_cki, lat_range_cki = get_cki_box_lon_lat_range()
    lon_range_ci, lat_range_ci = get_christmas_box_lon_lat_range()
    plt.style.use(plot_style)
    fig = plt.figure(figsize=(6, 6))
    for i in range(12):
        start_date = datetime(2008, i + 1, 1)
        end_date = add_month_to_timestamp(start_date, 1)
        density = Density.read_from_netcdf(input_path,
                                           time_start=start_date,
                                           time_end=end_date)
        z = np.mean(density.density, axis=0)
        z[z == 0] = np.nan
        lon = density.grid.lon
        lat = density.grid.lat
        ax = plt.subplot(4, 3, i + 1, projection=ccrs.PlateCarree())
        if i in [0, 3, 6]:
            mplot = _iot_basic_map(ax, xmarkers='off')
            ax.tick_params(axis='both', which='both', length=0)
            ax.set_xticklabels([])
        elif i in [10, 11]:
            mplot = _iot_basic_map(ax, ymarkers='off')
            ax.tick_params(axis='both', which='both', length=0)
            ax.set_yticklabels([])
        elif i == 9:
            mplot = _iot_basic_map(ax)
            ax.tick_params(axis='both', which='both', length=0)
        else:
            mplot = _iot_basic_map(ax, xmarkers='off', ymarkers='off')
            ax.tick_params(axis='both', which='both', length=0)
            ax.set_xticklabels([])
            ax.set_yticklabels([])
        c, ranges = mplot.pcolormesh(lon,
                                     lat,
                                     z,
                                     ranges=[1, 10, 100, 10**3, 10**4],
                                     show_cbar=False)
        mplot.box(lon_range_cki, lat_range_cki, linewidth=0.5)
        mplot.box(lon_range_ci, lat_range_ci, linewidth=0.5)
        if i == 9:
            _add_horizontal_colorbar(fig, ax, c, ranges, scale_width=3.3)
        mplot.add_subtitle(
            f'({string.ascii_lowercase[i]}) {start_date.strftime("%b")}')
    # save
    if output_path:
        plt.savefig(output_path, bbox_inches='tight', dpi=300)
    plt.show()
Exemplo n.º 13
0
def calculate_mean_hycom_data(months, lon_range, lat_range, input_dir=get_dir('hycom_input')):
    u_all = []
    v_all = []
    for month in months:
        start_date = datetime(2008, month, 1)
        end_date = add_month_to_timestamp(start_date, 1)
        n_days = (end_date-start_date).days
        for i in range(n_days):
            date = start_date+timedelta(days=i)
            input_path = f'{input_dir}{date.strftime("%Y%m%d")}.nc'
            log.info(None, f'Reading data from: {input_path}')
            lon, lat, u, v = _read_hycom_data(input_path, lon_range, lat_range)
            u_all.append(u)
            v_all.append(v)
    u_all = np.array(u_all)
    v_all = np.array(v_all)
    log.info(None, f'Calculating mean u and v')
    u_mean = np.nanmean(u_all, axis=0)
    v_mean = np.nanmean(v_all, axis=0)
    return lon, lat, u_mean, v_mean
Exemplo n.º 14
0
def xpresspearl_animation():
    particles = BeachingParticles.read_from_netcdf(
        get_dir('xpresspearl_output') + 'particles_2008-2009.nc')
    output_name = 'xpresspearl'
    lon_range = [40, 120]
    lat_range = [-20, 40]
    _, lon0, lat0 = get_xpresspearl_release_time_lon_lat()
    create_animation_beached(particles.time,
                             particles.lon,
                             particles.lat,
                             None,
                             None,
                             lon_range=lon_range,
                             lat_range=lat_range,
                             output_name=output_name,
                             point=True,
                             point_lon=lon0,
                             point_lat=lat0,
                             dpi=300,
                             fps=5,
                             title_style='time_passed_simple')
Exemplo n.º 15
0
def daily_date_range_from_irds_server(output_dir,
                                      date_range,
                                      lon_range=None,
                                      lat_range=None,
                                      variables=['u', 'v'],
                                      i_depths=[0],
                                      irds_mount=get_dir('ozroms_daily_input'),
                                      log_file='dl/ozroms_daily.log'):
    log.info(log_file, f'Accessing IRDS: {irds_mount}')
    ncfiles = get_ozroms_daily_ncfiles_from_irds(irds_mount, date_range[0],
                                                 date_range[1])
    log.info(log_file, f'Found daily ncfiles: {ncfiles[0:5]}')
    for ncfile in ncfiles:
        input_path = f'{irds_mount}{ncfile}'
        file_from_opendap_server(output_dir,
                                 input_path,
                                 lon_range=lon_range,
                                 lat_range=lat_range,
                                 variables=variables,
                                 i_depths=i_depths,
                                 log_file=log_file)
Exemplo n.º 16
0
def cocos_keeling_islands_animation():
    particles = BeachingParticles.read_from_netcdf(get_dir('iot_input_2008'))

    lon_range = [90., 128.]
    lat_range = [-20., 6.]
    output_name = 'plastic_waste_cki_2008'
    create_animation_beached(particles.time,
                             particles.lon,
                             particles.lat,
                             None,
                             None,
                             output_name=output_name,
                             lon_range=lon_range,
                             lat_range=lat_range,
                             text='Cocos Keeling\nIslands',
                             text_lon=97.,
                             text_lat=-13.,
                             point=True,
                             point_lon=96.86,
                             point_lat=-12.14,
                             dpi=150,
                             fps=4,
                             title_style='month')
Exemplo n.º 17
0
def figure3_release_arrival_histograms(
        input_path=get_dir('iot_input'),
        output_path=None,
        plot_style='plot_tools/plot.mplstyle',
        river_names=['Serayu', 'Progo', 'Tanduy', 'Wulan', 'Bogowonto'],
        river_lons=[109.1125, 110.2125, 108.7958333, 108.1458333, 110.0291667],
        river_lats=[
            -7.679166667, -7.979166667, -7.670833333, -7.779166667,
            -7.895833333
        ],
        river_styles=['-', '-.', ':', '--', '-'],
        river_colors=['k', 'k', 'k', 'k', '#bfbfbf']):
    particles = BeachingParticles.read_from_netcdf(input_path)
    cki_n_release, _, cki_n_entry = get_n_particles_per_month_release_arrival(
        particles, 'cki')
    ci_n_release, _, ci_n_entry = get_n_particles_per_month_release_arrival(
        particles, 'christmas')
    all_sources = RiverSources.read_from_shapefile()
    river_waste = []
    for i in range(len(river_names)):
        i_river = np.where(
            np.logical_and(all_sources.lon == river_lons[i],
                           all_sources.lat == river_lats[i]))
        river_waste.append(np.squeeze(all_sources.waste[i_river]))

    plt.style.use(plot_style)
    fig = plt.figure(figsize=(5, 4))
    plt.rcParams['font.size'] = 5
    plt.rcParams['axes.labelsize'] = 5

    ax1 = plt.subplot(2, 2, (1, 2))
    for i in range(len(river_names)):
        ax1.plot(all_sources.time,
                 river_waste[i],
                 label=river_names[i],
                 color=river_colors[i],
                 linestyle=river_styles[i])
    ax1.set_xticks(all_sources.time)
    ax1.set_xticklabels([
        'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
        'Nov', 'Dec'
    ])
    ax1.set_xlim(1, 12)
    ax1.set_yticks(np.arange(0, 3000, 500))
    ax1.set_ylim(0, 3000)
    ax1.set_ylabel('[# particles]')
    ax1.legend(loc='upper right', bbox_to_anchor=(1.18, 1.0))
    anchored_text1 = AnchoredText(
        f'(a) Seasonal input of plastic waste from {int(len(river_names))} main polluting rivers',
        loc='upper left',
        borderpad=0.0)
    ax1.add_artist(anchored_text1)

    ax2 = plt.subplot(2, 2, 3)
    _histogram_release_arrival(ax2, cki_n_release, cki_n_entry)
    anchored_text2 = AnchoredText(
        f'(b) Seasonality of particles reaching Cocos Keeling Islands',
        loc='upper left',
        borderpad=0.0)
    ax2.add_artist(anchored_text2)
    # legend
    legend_elements = [
        Patch(facecolor='w', edgecolor='k', hatch='//////', label='Release'),
        Patch(facecolor='w', edgecolor='k', label='Arrival')
    ]
    ax2.legend(handles=legend_elements,
               loc='upper left',
               bbox_to_anchor=(0.0, 0.91))

    ax3 = plt.subplot(2, 2, 4)
    _histogram_release_arrival(ax3, ci_n_release, ci_n_entry)
    ax3.yaxis.set_label_position('right')
    ax3.yaxis.tick_right()
    anchored_text3 = AnchoredText(
        f'(c) Seasonality of particles reaching Christmas Island',
        loc='upper left',
        borderpad=0.0)
    ax3.add_artist(anchored_text3)
    if output_path:
        plt.savefig(output_path, bbox_inches='tight', dpi=300)
    plt.show()
Exemplo n.º 18
0
def figure2_main_sources(input_path=get_dir('iot_input'),
                         river_names_cki=[],
                         river_names_ci=[],
                         ylim_cki=[0, 45],
                         ylim_ci=[0, 45],
                         output_path=None,
                         plot_style='plot_tools/plot.mplstyle'):
    particles = BeachingParticles.read_from_netcdf(input_path)
    box_lon_cki, box_lat_cki = get_cki_box_lon_lat_range()
    box_lon_ci, box_lat_ci = get_christmas_box_lon_lat_range()
    l_box_cki = get_l_particles_in_box(particles, 'cki')
    l_box_ci = get_l_particles_in_box(particles, 'christmas')
    lon_main_cki, lat_main_cki, waste_main_cki = get_main_sources_lon_lat_n_particles(
        particles, 'cki')
    lon_main_ci, lat_main_ci, waste_main_ci = get_main_sources_lon_lat_n_particles(
        particles, 'christmas')
    (main_colors_cki, main_sizes_cki, main_edgewidths_cki
     ) = _get_marker_colors_sizes_edgewidths_for_main_sources(waste_main_cki)
    (main_colors_ci, main_sizes_ci, main_edgewidths_ci
     ) = _get_marker_colors_sizes_edgewidths_for_main_sources(waste_main_ci)
    x_cki, waste_big_cki, colors_big_cki = _get_sorted_river_contribution_info(
        lon_main_cki, lat_main_cki, waste_main_cki, main_colors_cki,
        river_names_cki, 'CKI')
    x_ci, waste_big_ci, colors_big_ci = _get_sorted_river_contribution_info(
        lon_main_ci, lat_main_ci, waste_main_ci, main_colors_ci,
        river_names_ci, 'CI')

    plt.style.use(plot_style)
    fig = plt.figure(figsize=(6, 4))
    plt.rcParams['font.size'] = 5
    plt.rcParams['axes.labelsize'] = 5
    plt.subplots_adjust(wspace=0.0)
    plt.subplots_adjust(hspace=0.35)
    land_color = '#cfcfcf'
    in_box_color = '#2e4999'
    # (a) main sources CKI
    ax1 = plt.subplot(2, 3, (1, 2), projection=ccrs.PlateCarree())
    mplot1 = _iot_basic_map(ax1)
    plt.rcParams['font.size'] = 5
    mplot1.ax.set_xticklabels([])
    mplot1.tracks(particles.lon[l_box_cki, :],
                  particles.lat[l_box_cki, :],
                  color=in_box_color,
                  linewidth=0.2)
    mplot1.box(box_lon_cki, box_lat_cki, linewidth=0.8, color='w')
    mplot1.box(box_lon_cki, box_lat_cki, linewidth=0.5)
    ax1.add_feature(cftr.LAND, facecolor=land_color, edgecolor='k', zorder=5)
    mplot1.points(lon_main_cki,
                  lat_main_cki,
                  marker='o',
                  facecolor=main_colors_cki,
                  markersize=np.array(main_sizes_cki) * 5,
                  edgewidth=main_edgewidths_cki)
    mplot1.add_subtitle(
        f'(a) Source locations and tracks of particles reaching\n     Cocos Keeling Islands (CKI)'
    )
    ax1.set_anchor('W')
    # (c) main sources CI
    ax2 = plt.subplot(2, 3, (4, 5), projection=ccrs.PlateCarree())
    mplot2 = _iot_basic_map(ax2)
    plt.rcParams['font.size'] = 5
    mplot2.tracks(particles.lon[l_box_ci, :],
                  particles.lat[l_box_ci, :],
                  color=in_box_color,
                  linewidth=0.2)
    mplot2.box(box_lon_ci, box_lat_ci, linewidth=0.8, color='w')
    mplot2.box(box_lon_ci, box_lat_ci, linewidth=0.5)
    ax2.add_feature(cftr.LAND, facecolor=land_color, edgecolor='k', zorder=5)
    mplot2.points(lon_main_ci,
                  lat_main_ci,
                  marker='o',
                  facecolor=main_colors_ci,
                  markersize=np.array(main_sizes_ci) * 5,
                  edgewidth=main_edgewidths_ci)
    mplot2.add_subtitle(
        f'(c) Source locations and tracks of particles reaching\n     Christmas Island (CI)'
    )
    # sources legend
    legend_entries = _get_legend_entries_for_main_sources()
    ax2.set_anchor('W')
    ax2.legend(handles=legend_entries,
               title='[# particles]',
               loc='upper right',
               bbox_to_anchor=(1.3, 1.0))
    # (b) river contributions CKI
    ax3 = plt.subplot(2, 3, 3)
    ax3.bar(x_cki, waste_big_cki, color=colors_big_cki, zorder=5)
    ax3.set_ylabel('[% particles arriving]')
    ax3.set_ylim(ylim_cki)
    yticks = np.arange(0, ylim_cki[1], 5)
    yticks[0] = ylim_cki[0]
    ax3.set_yticks(yticks)
    xticks = np.arange(0, len(river_names_cki))
    ax3.set_xticks(xticks)
    ax3.set_xticklabels(river_names_cki, rotation='vertical')
    ax3.grid(False, axis='x')
    anchored_text1 = AnchoredText(
        f'(b) Contributions of rivers to particles\n     reaching the CKI',
        loc='upper left',
        borderpad=0.0)
    ax3.add_artist(anchored_text1)
    ax3.set_anchor('W')
    # (d) river contributions CI
    ax4 = plt.subplot(2, 3, 6)
    ax4.bar(x_ci, waste_big_ci, color=colors_big_ci, zorder=5)
    ax4.set_ylim(ylim_ci)
    yticks2 = np.arange(0, ylim_ci[1], 5)
    yticks2[0] = ylim_ci[0]
    ax4.set_yticks(yticks2)
    ax4.set_ylabel('[% particles arriving]')
    xticks = np.arange(0, len(river_names_ci))
    ax4.set_xticks(xticks)
    ax4.set_xticklabels(river_names_ci, rotation='vertical')
    ax4.grid(False, axis='x')
    anchored_text2 = AnchoredText(
        f'(d) Contributions of rivers to particles\n     reaching CI',
        loc='upper left',
        borderpad=0.0)
    ax4.add_artist(anchored_text2)
    ax4.set_anchor('W')
    if output_path:
        plt.savefig(output_path, bbox_inches='tight', dpi=300)
    plt.show()
Exemplo n.º 19
0
def figure1_overview(output_path=None,
                     river_dir=get_dir('indonesia_rivers'),
                     river_filenames=[
                         'progo.shp', 'bogowonto.shp', 'serayu.shp',
                         'tanduy.shp', 'wulan.shp'
                     ],
                     river_color='#002eb5',
                     linewidth=1.5,
                     plot_style='plot_tools/plot.mplstyle'):
    # boxes IOT
    lon_range_cki, lat_range_cki = get_cki_box_lon_lat_range()
    lon_range_ci, lat_range_ci = get_christmas_box_lon_lat_range()
    # box Java:
    lon_range_java = [105., 115.6]
    lat_range_java = [-9., -5.]
    meridians_java = [105, 110, 115]
    parallels_java = np.arange(lat_range_java[0], lat_range_java[1] + 1, 1)
    # box zoom Java:
    lon_range = [107.5, 111.]
    lat_range = [-8.2, -6.]
    meridians = [108, 109, 110]
    parallels = [-8, -7, -6]
    # cities
    city_names = [
        'Tasikmalaya', 'Purwokerto', 'Wonosobo', 'Purworejo', 'Magelang',
        'Yogyakarta'
    ]
    city_lons = [108.22, 109.25, 109.90, 110.01, 110.22, 110.37]
    city_lats = [-7.35, -7.42, -7.37, -7.71, -7.49, -7.80]

    plt.style.use(plot_style)
    fig = plt.figure(figsize=(8, 6))
    plt.rcParams['font.size'] = 8
    plt.rcParams['axes.labelsize'] = 6
    # (a) Overview NE monsoon
    ax1 = plt.subplot(2, 2, 1, projection=ccrs.PlateCarree())
    mplot1 = _iot_basic_map(ax1)
    plt.rcParams['font.size'] = 8
    plt.rcParams['axes.labelsize'] = 6
    mplot1.box(lon_range_cki, lat_range_cki, linewidth=0.5)
    mplot1.box(lon_range_ci, lat_range_ci, linewidth=0.5)
    mplot1.box(lon_range, lat_range, linewidth=1, color='#d00d20')
    mplot1.add_subtitle(
        '(a) Region overview and main NE monsoon ocean currents')
    # (b) Overview SW monsoon
    ax3 = plt.subplot(2, 2, 3, projection=ccrs.PlateCarree())
    mplot3 = _iot_basic_map(ax3)
    plt.rcParams['font.size'] = 8
    plt.rcParams['axes.labelsize'] = 6
    mplot3.box(lon_range_cki, lat_range_cki, linewidth=0.5)
    mplot3.box(lon_range_ci, lat_range_ci, linewidth=0.5)
    mplot3.box(lon_range, lat_range, linewidth=1, color='#d00d20')
    mplot3.add_subtitle(
        '(b) Region overview and main SW monsoon ocean currents')
    # (c) zoom Java
    ax2 = plt.subplot(2, 2, (2, 4), projection=ccrs.PlateCarree())
    mplot2 = MapPlot(ax2,
                     lon_range,
                     lat_range,
                     meridians=meridians,
                     parallels=parallels,
                     ymarkers='right')
    plt.rcParams['font.size'] = 8
    plt.rcParams['axes.labelsize'] = 6
    for river_file in river_filenames:
        reader = shpreader.Reader(river_dir + river_file)
        rivers = reader.records()
        for river in rivers:
            ax2.add_geometries([river.geometry],
                               ccrs.PlateCarree(),
                               edgecolor=river_color,
                               facecolor='None',
                               zorder=5,
                               linewidth=linewidth)
    mplot2.points(city_lons,
                  city_lats,
                  marker='o',
                  edgecolor='k',
                  facecolor='#d00d20',
                  markersize=5)
    mplot2.add_subtitle(
        '(c) Main Javanese rivers contributing to IOT plastic waste')
    if output_path:
        plt.savefig(output_path, bbox_inches='tight', dpi=300)
    plt.show()
Exemplo n.º 20
0
    lon_range_ci, lat_range_ci = get_christmas_box_lon_lat_range()

    plt.style.use(plot_style)
    fig = plt.figure()
    ax = plt.gca(projection=ccrs.PlateCarree())
    mplot = _iot_basic_map(ax)
    mplot.quiver(lon, lat, u, v, thin=thin, scale=scale)
    mplot.box(lon_range_cki, lat_range_cki, linewidth=0.5, color='r')
    mplot.box(lon_range_ci, lat_range_ci, linewidth=0.5, color='r')
    if output_path:
        plt.savefig(output_path, bbox_inches='tight', dpi=300)
    plt.show()


if __name__ == '__main__':
    figure1_overview(output_path=get_dir('iot_plots') + 'fig1.jpg')
    river_names_cki = ['Serayu', 'Bogowonto', 'Tanduy', 'Progo']
    river_names_ci = ['Tanduy', 'Serayu', 'Wulan', 'Bogowonto']
    figure2_main_sources(river_names_cki=river_names_cki,
                         river_names_ci=river_names_ci,
                         output_path=get_dir('iot_plots') + 'fig2.jpg')
    figure3_release_arrival_histograms(output_path=get_dir('iot_plots') +
                                       'fig3.jpg')
    figure4_seasonal_density(output_path=get_dir('iot_plots') + 'fig4.jpg')
    # plastic_measurements(plastic_type='count', output_path=get_dir('iot_plots')+'samples_count.jpg')
    # plastic_measurements(plastic_type='mass', output_path=get_dir('iot_plots')+'samples_mass.jpg')

    # --- plots with 3% wind added ---
    # river_names_cki_wind = ['Tanduy', 'Bogowonto']
    # river_names_ci_wind = ['Bogowonto', 'Progo', 'Tanduy']
    # figure2_main_sources(river_names_cki=river_names_cki_wind, river_names_ci=river_names_ci_wind,
Exemplo n.º 21
0
    output_interval = 24
    kernel = pset.Kernel(AdvectionRK4) + pset.Kernel(DiffusionUniformKh)
    output_file = pset.ParticleFile(name=output_path,
                                    outputdt=dt * output_interval)
    pset.execute(kernel,
                 runtime=run_time,
                 dt=dt,
                 output_file=output_file,
                 verbose_progress=True,
                 recovery={ErrorCode.ErrorOutOfBounds: delete_particle})


if __name__ == '__main__':
    # use "main_run_pts_parcels.sh" bash script to run simulations
    year = int(sys.argv[1])
    input_dir = get_dir('hycom_input')
    output_dir = get_dir('pts_output')
    if year == 1995:
        # --- first run ---
        start_date = datetime(1995, 1, 1, 12, 0)
        end_date = datetime(1995, 12, 31)
        output_name = 'constant_io_river_sources_1995'
        io_sources = IORiverParticles.get_from_netcdf(start_date)
        run_hycom_subset_monthly_release(input_dir, output_dir, output_name,
                                         io_sources.time0, io_sources.lon0,
                                         io_sources.lat0, start_date, end_date)
    else:
        # --- consecutive runs ---
        restart_path = get_dir(
            'hycom_output'
        ) + 'hycom_currents/' + 'constant_io_river_sources_' + str(year -
Exemplo n.º 22
0
def run_hycom_cfsr_subset_monthly_release(
        output_dir,
        output_name,
        time0,
        lon0,
        lat0,
        start_date,
        end_date,
        windage=0.03,
        input_dir_hycom=get_dir('hycom_input'),
        input_dir_cfsr=get_dir('cfsr_input'),
        indices_hycom=_get_io_indices_from_netcdf(),
        indices_cfsr=_get_io_indices_from_netcdf(
            input_path=get_dir('cfsr_indices_input')),
        kh=10.,
        interp_method='linear'):
    # get paths
    ncfiles_hycom = get_daily_ncfiles_in_time_range(input_dir_hycom,
                                                    start_date, end_date)
    ncfiles_cfsr = get_daily_ncfiles_in_time_range(input_dir_cfsr, start_date,
                                                   end_date)
    output_path = output_dir + output_name
    # create fieldset
    filenames_hycom = [input_dir_hycom + ncfile for ncfile in ncfiles_hycom]
    filenames_cfsr = [input_dir_cfsr + ncfile for ncfile in ncfiles_cfsr]
    variables_hycom = {'U': 'u', 'V': 'v'}
    variables_cfsr = {'U': 'u', 'V': 'v'}
    dimensions_hycom = {'lat': 'lat', 'lon': 'lon', 'time': 'time'}
    dimensions_cfsr = {'lat': 'lat', 'lon': 'lon', 'time': 'time'}
    fset_hycom = FieldSet.from_netcdf(filenames_hycom,
                                      variables_hycom,
                                      dimensions_hycom,
                                      indices=indices_hycom)
    fset_cfsr = FieldSet.from_netcdf(filenames_cfsr,
                                     variables_cfsr,
                                     dimensions_cfsr,
                                     indices=indices_cfsr)
    fset_cfsr.U.set_scaling_factor(windage)
    fset_cfsr.V.set_scaling_factor(windage)
    fset = FieldSet(U=fset_hycom.U + fset_cfsr.U, V=fset_hycom.V + fset_cfsr.V)
    # add constant horizontal diffusivity (zero on land)
    lm = LandMask.read_from_netcdf()
    kh2D = kh * np.ones(lm.mask.shape)
    kh2D[lm.mask.astype('bool')] = 0.0  # diffusion zero on land
    kh2D_subset = kh2D[indices_hycom['lat'], :][:, indices_hycom['lon']]
    fset.add_field(
        Field('Kh_zonal',
              data=kh2D_subset,
              lon=fset_hycom.U.grid.lon,
              lat=fset_hycom.U.grid.lat,
              mesh='spherical',
              interp_method=interp_method))
    fset.add_field(
        Field('Kh_meridional',
              data=kh2D_subset,
              lon=fset_hycom.U.grid.lon,
              lat=fset_hycom.U.grid.lat,
              mesh='spherical',
              interp_method=interp_method))
    # monthly release
    pset = ParticleSet(fieldset=fset,
                       pclass=JITParticle,
                       lon=lon0,
                       lat=lat0,
                       time=time0)
    # execute
    run_time = timedelta(days=(end_date - start_date).days)
    dt = timedelta(hours=1)
    output_interval = 24
    kernel = pset.Kernel(AdvectionRK4) + pset.Kernel(DiffusionUniformKh)
    output_file = pset.ParticleFile(name=output_path,
                                    outputdt=dt * output_interval)
    pset.execute(kernel,
                 runtime=run_time,
                 dt=dt,
                 output_file=output_file,
                 verbose_progress=True,
                 recovery={ErrorCode.ErrorOutOfBounds: delete_particle})
Exemplo n.º 23
0
import os
from utilities import get_dir, combine_left_right
root_dir = get_dir()
import sys
print(os.path.join(root_dir, "vtk_robot/project_module/"))
sys.path.insert(0, os.path.join(root_dir, "vtk_robot/project_module/"))
from project_main import projector as projector_class
import numpy as np
import pickle as pkl
from PIL import Image
import matplotlib.pyplot as plt
import cProfile
import pstats
from pstats import SortKey
from PIL import Image

data_path = os.path.join(root_dir, "data")
save_path = os.path.join(root_dir, "results")
if not os.path.isdir(save_path): os.makedirs(save_path)

kine_file = os.path.join(data_path, "kine.pkl")
with open(kine_file, "rb") as f:
    kine = pkl.load(f)

kine_i = kine[0]

projector = projector_class(root_dir)

points_l = projector.get_3Dshape(kine_i, "L")
points_r = projector.get_3Dshape(kine_i, "R")
Exemplo n.º 24
0
    _pcolormesh_and_colorbar(fig,
                             ax,
                             lon,
                             lat,
                             variable_values,
                             cbar_label,
                             cmap=cmap)
    _add_text_watermark(ax)
    if output_path is not None:
        plt.savefig(output_path, bbox_inches='tight', dpi=300)
    plt.show()


if __name__ == '__main__':
    cmap_style = 'normal'
    output_dir = get_dir('plot_output')
    modeldata = from_local_file(get_dir('plot_input'))
    lon = modeldata.lon.values
    lat = modeldata.lat.values
    # 2D variables
    variables = ['sst', 'temp2m', 'mld', 'o2', 'salinity', 'sea_ice_cover']
    cbar_labels = [
        'SST [$\degree$C]', 'Air temperature [$\degree$C]',
        'Mixed layer depth [m]', 'Oxygen concentration [mmol/m$^3$]',
        'Salinity [10$^{-3}^]', 'Sea-ice cover [fraction]'
    ]
    cmaps = [
        cmo.thermal, cmo.thermal, cmo.deep, cmo.tempo, cmo.haline, cmo.ice_r
    ]
    for i in range(len(variables)):
        if len(getattr(modeldata, variables[i]).dimensions) == 3: