def test_single_boxcar(target_point, tmpfile, source_data_function):
    '''Smooth a single point'''
    
    import iris.quickplot as qplt, matplotlib.pyplot as plt
    from gridsmoother import GridSmoother
    
    import os

    #lat,lon = target_point

    dlat = 180. / 1#CUBE_SHAPE[0]
    dlon = 360. / 1#CUBE_SHAPE[1]

    print "point lat = %s, lon = %s" % target_point

    assert int(target_point[0] / dlat) - target_point[0] / dlat < SMALL_NUMBER
    assert int(target_point[1] / dlon) - target_point[1] / dlon < SMALL_NUMBER
    
    print "dlat = %s, dlon = %s" % (dlat, dlon)
    
    #centre = (lat,lon)#(dlat / 2., dlon / 2.)
    source_cube = gen_or_load_2D(tmpfile , [source_data_function], ["unsmoothed data"], {"GS_centre_lat":target_point[0], 'GS_centre_lon':target_point[1]},nlat=180, nlon=360)[0]
    
    lat_width = 6.
    lon_width = 18.
    
    print "box car parameters: lat_width %s, lon_width %s" % (lat_width, lon_width)
    
    gs = GridSmoother()
    filename= "boxcar_%s_x_%s.json.gz" % (lon_width,lat_width)
    if os.path.exists(filename):
        gs.load(filename)
    else:
        gs.build_boxcar_lat_lon(source_cube, lat_width, lon_width)
        gs.save(filename)
    
    smoothed_cube = gs.smooth_2d_cube(source_cube)
               
    if PLOT:
        import cartopy.crs as ccrs
        fig = plt.figure()
        subpl = fig.add_subplot(111, projection=ccrs.PlateCarree())
    
        qplt.pcolormesh(smoothed_cube, cmap='Reds')
        qplt.outline(smoothed_cube)
#        subpl.add_artist(plt.Circle(target_point, smoothing_width, edgecolor='blue', facecolor='none', transform=ccrs.PlateCarree()))
        
        for i, lat in enumerate(smoothed_cube.coord('latitude').points):
            for j, lon in enumerate(smoothed_cube.coord('longitude').points):
                if smoothed_cube.data[i, j] > 0:
                    plt.text(lon, lat, smoothed_cube.data[i, j] ** -1, transform=ccrs.PlateCarree(), ha='center', va='center')
        
        qplt.plt.gca().coastlines()
        qplt.show()
Beispiel #2
0
 def test_xaxis_labels(self):
     qplt.outline(self.cube, coords=('str_coord', 'bar'))
     self.assertBoundsTickLabels('xaxis')
Beispiel #3
0
 def test_xaxis_labels(self):
     qplt.outline(self.cube, coords=("str_coord", "bar"))
     self.assertBoundsTickLabels("xaxis")
def test_single_point(target_point, tmpfile, source_data_function, num_expected_distinct_values=2):
    '''Smooth a single point'''
    
    import iris.quickplot as qplt, matplotlib.pyplot as plt
    from gridsmoother import GridSmoother
    
    import os

    #lat,lon = target_point

    dlat = 180. / CUBE_SHAPE[0]
    dlon = 360. / CUBE_SHAPE[1]

    print "point lat = %s, lon = %s" % target_point

    assert int(target_point[0] / dlat) - target_point[0] / dlat < SMALL_NUMBER
    assert int(target_point[1] / dlon) - target_point[1] / dlon < SMALL_NUMBER
    
    print "dlat = %s, dlon = %s" % (dlat, dlon)
    
    #centre = (lat,lon)#(dlat / 2., dlon / 2.)
    source_cube = gen_or_load_2D(tmpfile , [source_data_function], ["unsmoothed data"], {"GS_centre_lat":target_point[0], 'GS_centre_lon':target_point[1]})[0]
    
    for smoothing_width in np.arange(2.0, 5, 0.5) * dlat:
        print "smoothing_width: ", smoothing_width
        
        gs = GridSmoother()
        filename = 'smoothing_%s.json.gz' % smoothing_width
        
        smoothing_function = lambda s: (s <= smoothing_width) * 1.0
        if os.path.exists(filename):
            gs.load(filename)
        else:
            gs.build(source_cube, smoothing_function)
            gs.save('smoothing_%s.json.gz' % smoothing_width)

        smoothed_cube = gs.smooth_2d_cube(source_cube)
        
        assert np.isclose(smoothed_cube.data.sum(), source_cube.data.sum(), atol=SMALL_NUMBER)

        #will fail for smoothing functions other than a hard cut off:
        if num_expected_distinct_values is not None:
            assert len(set(smoothed_cube.data.ravel().tolist())) == num_expected_distinct_values
        
        for i, j in zip(*np.where(smoothed_cube.data > 0.0)):
            assert smoothing_function(angular_separation(source_cube.coord('latitude').points[i],
                                                         source_cube.coord('longitude').points[j],
                                                         *target_point)
                                      ) > 0.
        
        for i, j in zip(*np.where(smoothed_cube.data == 0.0)):
            assert smoothing_function(angular_separation(source_cube.coord('latitude').points[i],
                                                         source_cube.coord('longitude').points[j],
                                                         *target_point)
                                      ) == 0.
        
        if PLOT:
            import cartopy.crs as ccrs
            fig = plt.figure()
            subpl = fig.add_subplot(111, projection=ccrs.PlateCarree())
        
            qplt.pcolormesh(smoothed_cube, cmap='Reds')
            qplt.outline(smoothed_cube)
            subpl.add_artist(plt.Circle(target_point, smoothing_width, edgecolor='blue', facecolor='none', transform=ccrs.PlateCarree()))
            
            for i, lat in enumerate(smoothed_cube.coord('latitude').points):
                for j, lon in enumerate(smoothed_cube.coord('longitude').points):
                    if smoothed_cube.data[i, j] > 0:
                        plt.text(lon, lat, smoothed_cube.data[i, j] ** -1, transform=ccrs.PlateCarree(), ha='center', va='center')
            
            qplt.plt.gca().coastlines()
            qplt.show()
Beispiel #5
0
def plot_driftMap(um, glm, ifs, ship_data):

    import iris.plot as iplt
    import iris.quickplot as qplt
    import iris.analysis.cartography
    import cartopy.crs as ccrs
    import cartopy
    import matplotlib.path as mpath
    from matplotlib.patches import Polygon

    ###################################
    ## PLOT MAP
    ###################################

    print('******')
    print('')
    print('Plotting cartopy map:')
    print('')

    ##################################################
    ##################################################
    #### 	CARTOPY
    ##################################################
    ##################################################

    SMALL_SIZE = 12
    MED_SIZE = 14
    LARGE_SIZE = 16

    plt.rc('font', size=MED_SIZE)
    plt.rc('axes', titlesize=MED_SIZE)
    plt.rc('axes', labelsize=MED_SIZE)
    plt.rc('xtick', labelsize=MED_SIZE)
    plt.rc('ytick', labelsize=MED_SIZE)
    plt.rc('legend', fontsize=MED_SIZE)
    # plt.rc('figure',titlesize=LARGE_SIZE)

    #################################################################
    ## create figure and axes instances
    #################################################################
    plt.figure(figsize=(5, 6))  #, dpi=300)
    # ax = plt.axes(projection=ccrs.Orthographic(30, 70))    # NP Stereo
    ax = plt.axes(projection=ccrs.NorthPolarStereo(central_longitude=30))

    ### set size
    ax.set_extent([20, 50, 88.35, 89.95], crs=ccrs.PlateCarree())  ### SWATH

    ### DON'T USE: PLATECARREE, NORTHPOLARSTEREO (on it's own), LAMBERT

    #################################################################
    ## add geographic features/guides for reference
    #################################################################
    ax.add_feature(cartopy.feature.OCEAN, color='lightcyan', zorder=0)
    ax.add_feature(cartopy.feature.LAND,
                   color='lightgrey',
                   zorder=0,
                   edgecolor='black')
    ax.add_feature(cartopy.feature.COASTLINE)
    ax.gridlines(color='black', linestyle='--')

    #################################################################
    ## plot UM data
    ################################################################
    # iplt.pcolormesh(um[diag][290:370,150:230])

    #################################################################
    ## plot UM nest
    #################################################################
    ### draw outline of grid
    # qplt.outline(um[0][0,:,:])          ### original swath
    # qplt.outline(cube[diag][hour,386:479,211:305])          ### redesigned swath (>13th)
    # qplt.outline(cube[hour,471:495,240:264])          ### 12-13th Aug swath
    # qplt.outline(cube[diag][hour,386:495,211:305])          ### misc
    # qplt.outline(cube[diag][290:370,150:230])

    ### Plot um grid centres
    # plt.plot(um[0].dim_coords[2], um[0].dim_coords[1], '.',
    #          color = 'k', linewidth = 2,
    #          transform = ccrs.PlateCarree(), label = 'Whole',
    #          )

    ###---------------------------------------------------------------------------------
    ### Plot um grid centres
    ###---------------------------------------------------------------------------------
    # plt.scatter(um[0].dim_coords[2], um[0].dim_coords[1], s = 9, c = 'steelblue')#,
    # label = 'UM_RA2M/CASIM-100',
    # alpha = 0.8,
    # edgecolor = 'midnightblue'
    # # transform = ccrs.PlateCarree()
    # )
    # qplt.scatter(um[0].dim_coords[2], um[0].dim_coords[1], s = 9, c = 'steelblue')
    qplt.outline(um[2][0, 300:, 100:400], color='steelblue')
    # qplt.outline(glm[1][0,:,:],
    #         color = 'lightgrey')

    ###---------------------------------------------------------------------------------
    ### Plot ifs grid centres
    ###---------------------------------------------------------------------------------
    plt.scatter(
        ifs['lons'][:],
        ifs['lats'][:],
        s=120,
        c='gold',
        label='IFS_midpoints',
        marker='x',
        # alpha = 0.5,
        linewidth=3,
        edgecolor='saddlebrown',
        transform=ccrs.PlateCarree())

    #################################################################
    ## plot ship track
    #################################################################
    ### DEFINE DRIFT + IN_ICE PERIODS
    drift_index = iceDrift(ship_data)
    inIce_index = inIce(ship_data)
    trackShip_index = trackShip(ship_data)

    ### Plot full track as line plot
    # plt.plot(ship_data.values[:,6], ship_data.values[:,7], '--',
    #          color = 'pink', linewidth = 2,
    #          transform = ccrs.PlateCarree(), label = 'Whole',
    #          )
    # plt.plot(ship_data.values[inIce_index,6], ship_data.values[inIce_index,7],
    #          color = 'palevioletred', linewidth = 3,
    #          transform = ccrs.PlateCarree(), label = 'In Ice',
    #          )
    # plt.plot(ship_data.values[inIce_index[0],6], ship_data.values[inIce_index[0],7],
    #          'k^', markerfacecolor = 'palevioletred', linewidth = 3,
    #          transform = ccrs.PlateCarree(),
    #          )
    # plt.plot(ship_data.values[inIce_index[-1],6], ship_data.values[inIce_index[-1],7],
    #          'kv', markerfacecolor = 'palevioletred', linewidth = 3,
    #          transform = ccrs.PlateCarree(),
    #          )
    plt.plot(
        ship_data.values[drift_index, 6],
        ship_data.values[drift_index, 7],
        color='firebrick',
        linewidth=3,
        transform=ccrs.PlateCarree(),
        label='AO2018 drift',
    )

    plt.title('Grid setup')

    plt.legend(bbox_to_anchor=(-0.05, 0.835, 1., .102), loc=4, ncol=1)

    print('******')
    print('')
    print('Finished plotting cartopy map! :)')
    print('')

    plt.savefig('../FIGS/Drift_UM_IFS_grids_v4.png', dpi=300)
    # plt.show()
    plt.close()