def plot_temperature_biases():

    seasons = ["(a) Annual", " (b) Winter (DJF)", "(c) Spring (MAM)", "(d) Summer (JJA)", "(e) Fall (SON)"]
    months =  [range(1, 13), [12, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]  ]
    season_to_months = dict(zip(seasons, months))

    cru_var_name = "tmp"
    cru_data_store, crcm4_data_store = _get_comparison_data(cru_var_name= cru_var_name,
        season_to_months=season_to_months)

    x, y = polar_stereographic.xs, polar_stereographic.ys
    i_array, j_array = _get_routing_indices()
    x_min, x_max, y_min, y_max = plot_utils.get_ranges(x[i_array, j_array], y[i_array, j_array])



    plot_utils.apply_plot_params(width_pt= None, font_size=9, aspect_ratio=2.5)
    fig = plt.figure()
    assert isinstance(fig, Figure)

    basemap = polar_stereographic.basemap
    assert isinstance(basemap, Basemap)
    gs = gridspec.GridSpec(3,2)

    color_map = my_cm.get_red_blue_colormap(ncolors = 14, reversed=True)
    clevels = xrange(-8, 9, 2)
    all_plot_axes = []
    for i, season in enumerate(seasons):
        if not i:
            ax = fig.add_subplot(gs[0,:])
        else:
            row, col = (i - 1)  // 2 + 1, (i - 1) % 2
            ax = fig.add_subplot(gs[row, col])
        all_plot_axes.append(ax)
        assert isinstance(ax, Axes)
        delta = crcm4_data_store[season] - cru_data_store[season]
        if cru_var_name == "tmp": delta -= 273.15
        #delta = maskoceans(polar_stereographic.lons, polar_stereographic.lats, delta)
        save = delta[i_array, j_array]
        delta[:, :] = np.ma.masked
        delta[i_array, j_array] = save
        img = basemap.pcolormesh(x, y, delta, cmap = color_map, vmin = -7, vmax = 7)
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", "8%", pad="3%")
        int_ticker = LinearLocator(numticks = color_map.N + 1)
        fig.colorbar(img, cax = cax, ticks = MultipleLocator(base = 2))
        ax.set_title(season)

    for the_ax in all_plot_axes:
        the_ax.set_xlim(x_min, x_max)
        the_ax.set_ylim(y_min, y_max)
        basemap.drawcoastlines(ax = the_ax, linewidth = 0.1)
        plot_utils.draw_meridians_and_parallels(basemap, step_degrees=30.0, ax = the_ax)
        plot_basin_boundaries_from_shape(basemap, axes = the_ax, linewidth=0.4)
        put_selected_stations(the_ax, basemap, i_array, j_array)

    #gs.tight_layout(fig)
    fig.suptitle("T(2m), degrees, CRCM4 - CRU")
    fig.savefig("seasonal_{0}_ccc.png".format(cru_var_name))
示例#2
0
def plot_data(data, i_array, j_array, name='AEX', title = None, digits = 1,
                                      color_map = mpl.cm.get_cmap('RdBu'),
                                      minmax = (None, None),
                                      units = '%',
                                      colorbar_orientation = 'vertical'
                                      ):



    if name != None:
        plt.figure()

    to_plot = np.ma.masked_all(xs.shape)
    for index, i, j in zip( range(len(data)), i_array, j_array):
        to_plot[i, j] = data[index]


    print np.ma.min(data), np.ma.max(data)

  #  m.pcolor(xs, ys, to_plot, cmap = mpl.cm.get_cmap('RdBu_r'))

    extent = [np.min(xs), np.max(xs), np.min(ys), np.max(ys)]
    plt.imshow(to_plot.transpose().copy(), interpolation = 'nearest' ,
                                    extent = extent,
                                    origin = 'lower',
                                    cmap = color_map,
                                    vmin = minmax[0],
                                    vmax = minmax[1]
                                    )


    plot_basin_boundaries_from_shape(m, linewidth = 1)
    m.drawrivers()
    m.drawcoastlines()
    draw_meridians_and_parallels(m, step_degrees = 30)

    int_ticker = LinearLocator()
    cb = plt.colorbar(ticks = int_ticker, orientation = colorbar_orientation)
    cb.ax.set_ylabel(units)

    override = {'fontsize': 20,
                  'verticalalignment': 'baseline',
                  'horizontalalignment': 'center'}


    plt.title(title if title != None else name, override)

    ymin, ymax = plt.ylim()
    plt.ylim(ymin + 0.12 * (ymax - ymin), ymax * 0.32)

    xmin, xmax = plt.xlim()
    plt.xlim(xmin + (xmax - xmin) * 0.65, 0.85*xmax)

    if name != None:
        plt.savefig(name + '.png', bbox_inches = 'tight')
def plot_forcing_error(errors_map, i_list, j_list):
    pylab.rcParams.update(params)
    to_plot = ma.masked_all(xs.shape)

    err = None
    for id, error in errors_map.iteritems():
        if err == None:
            err = np.zeros(error.shape)
        err += error

    err = err / len(errors_map)

    for i, j, er in zip(i_list, j_list, err):
        to_plot[i,j] = er



    n_levels = 20
    plt.imshow(to_plot.transpose().copy(), extent = [np.min(xs), np.max(xs), ys.min(), ys.max()],
                                        origin = 'lower',
                                        interpolation = 'bilinear' ,
                                        cmap = mpl.cm.get_cmap('RdBu_r', n_levels),
                                        vmin = -30, vmax = 30)

    int_ticker = MaxNLocator(nbins=n_levels, integer=True)
    cb = plt.colorbar(ticks = int_ticker)
    cb.ax.set_ylabel('%')

    basemap.drawcoastlines()
    print np.min(lons), np.max(lons), lats.min(), lats.max()

    plot_basin_boundaries_from_shape(basemap, linewidth = 0.5)

    ymin, ymax = plt.ylim()
    plt.ylim(ymin + 0.12 * (ymax - ymin), ymax * 0.32)

    xmin, xmax = plt.xlim()
    plt.xlim(xmin + (xmax - xmin) * 0.65, 0.85*xmax)
    draw_meridians_and_parallels(basemap, 10)
    plt.savefig("forcing_errors.png")
示例#4
0
def test_interpolation():
    lons, lats, interpolated = get_topography_interpolated_to_graham_grid(
                                        grid_lower_left = GeoPoint(-85.0, 40.0),
                                        grid_shape = (380, 280)
                                        )

    print lons.shape
    print lats.shape
    print interpolated.shape
    print 'done interpolating'


    m = Basemap(llcrnrlon=-85, llcrnrlat=40,
                urcrnrlon=-53, urcrnrlat=65)
    lons, lats = m(lons, lats)
    m.contourf(lons, lats, interpolated)
    m.drawcoastlines()
    draw_meridians_and_parallels(m)
    plt.colorbar()

    plt.savefig('interpolated_topo.png')

    pass
def default_basemap_scatter():
#    m = Basemap()
#    m.drawcoastlines(linewidth = 0.5)
#    longitudes_array  = np.arange(-85, -55, 5.0 / MINUTES_PER_DEGREE)
#    latitudes_array = np.arange(70, 40, - 5.0 / MINUTES_PER_DEGREE)
#    X, Y = pylab.meshgrid(longitudes_array, latitudes_array)
#    longitudes_array, latitudes_array = m(X, Y)
#    m.contourf(longitudes_array, latitudes_array, longitudes_array)
    

#    plt.figure()
#    m = Basemap(boundinglat = 40, projection = 'npstere', lat_0=60, lon_0=0)
#    m.drawcoastlines()
#    draw_meridians_and_parallels(m, 25)

    plt.figure()
    m = Basemap(projection = 'npstere',
                        lat_ts = 60, lat_0 = 60, lon_0 = -115, boundinglat = 40, resolution='i')
    m.drawcoastlines()

    m.drawrivers(color = 'blue', linewidth = 1)


    dx = 45000.0

    [px, py] = m(-61.5*dx, -179.8*dx)
    m.scatter(px, py , c="red")
    draw_meridians_and_parallels(m, 25)

    [ymin, ymax] = plt.ylim()
    plt.ylim(ymin + 0.12 * (ymax - ymin), ymax * 0.32)

    [xmin, xmax] = plt.xlim()
    plt.xlim(xmin + (xmax - xmin) * 0.65, 0.85*xmax)


    plt.show()
def plot_temp():
    seasons = ["(a) Annual", " (b) Winter (DJF)", "(c) Spring (MAM)", "(d) Summer (JJA)", "(e) Fall (SON)"]
    months =  [range(1, 13), [12, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]  ]
    season_to_months = dict(zip(seasons, months))

    #take out annual
    seasons.pop(0)
    #put new numbering for the subplots
    new_numbering = ["a", "b", "c", "d"]


    var_name = "st"
    year_range_c = xrange(1970,2000)
    year_range_f = xrange(2041,2071)
    x, y = polar_stereographic.xs, polar_stereographic.ys
    i_array, j_array = _get_routing_indices()
    x_min, x_max, y_min, y_max = plot_utils.get_ranges(x[i_array, j_array], y[i_array, j_array])



    plot_utils.apply_plot_params(width_pt= None, font_size=9, aspect_ratio=2.5)
    fig = plt.figure()
    assert isinstance(fig, Figure)

    basemap = polar_stereographic.basemap
    assert isinstance(basemap, Basemap)
    gs = gridspec.GridSpec(3,2)

    #color_map = mpl.cm.get_cmap(name="jet", lut=10)
    clevels = xrange(-8, 9, 2)
    all_plot_axes = []
    
    
    
    #determine min an max for color scales
    min_val = np.inf
    max_val = -np.inf
    for season in seasons:
        current = _get_data(v_name=var_name, months = season_to_months[season],
                    member_list=members.current_ids, year_range=year_range_c)
        future = _get_data(v_name=var_name, months = season_to_months[season],
                    member_list=members.future_ids, year_range=year_range_f)

        current_m = np.mean(current, axis=0)
        future_m = np.mean(future, axis= 0)


        delta = future_m[i_array, j_array] - current_m[i_array, j_array]

        the_min = delta.min()
        the_max = delta.max()

        min_val = min(min_val, the_min)
        max_val = max(max_val, the_max)

    min_val = np.floor(min_val)
    max_val = np.ceil(max_val)

    color_map = my_cm.get_red_blue_colormap(ncolors = 10, reversed=True)
    if min_val >= 0:
        color_map = my_cm.get_red_colormap(ncolors=10)
    
    for i, season in enumerate(seasons):
        row, col = i // 2, i % 2
        ax = fig.add_subplot(gs[row, col ])
        all_plot_axes.append(ax)


        current = _get_data(v_name=var_name, months = season_to_months[season],
                    member_list=members.current_ids, year_range=year_range_c)
        future = _get_data(v_name=var_name, months = season_to_months[season],
                    member_list=members.future_ids, year_range=year_range_f)


#        t, p = stats.ttest_ind(current, future, axis=0)

#        significant = np.array(p <= 0.05)

        significant = calculate_significance_using_bootstrap(current, future)
        assert not np.all(~significant)
        assert not np.all(significant)

        current_m = np.mean(current, axis=0)
        future_m = np.mean(future, axis= 0)

        delta = (future_m - current_m)

        assert isinstance(ax, Axes)

        #delta = maskoceans(polar_stereographic.lons, polar_stereographic.lats, delta)
        save = delta[i_array, j_array]
        delta = np.ma.masked_all(delta.shape)
        delta[i_array, j_array] = save
        d_min = np.floor( np.min(save) )
        d_max = np.ceil( np.max(save) )

        img = basemap.pcolormesh(x, y, delta, cmap = color_map, vmin = min_val, vmax = max_val)
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", "8%", pad="3%")
        assert isinstance(cax, Axes)

        int_ticker = LinearLocator(numticks = color_map.N + 1)
        cb = fig.colorbar(img, cax = cax, ticks = int_ticker)
        cax.set_title("$^{\\circ}{\\rm C}$")



        where_significant = significant
        significant = np.ma.masked_all(significant.shape)

        significant[~where_significant] = 0
        basemap.pcolormesh( x, y, significant , cmap = mpl.cm.get_cmap(name = "gray", lut = 3),
                           vmin = -1, vmax = 1, ax = ax)
        ax.set_title( season.replace( re.findall( "([a-z])", season)[0], new_numbering[i]) )

    for the_ax in all_plot_axes:
        the_ax.set_xlim(x_min, x_max)
        the_ax.set_ylim(y_min, y_max)
        basemap.drawcoastlines(ax = the_ax, linewidth = 0.1)
        plot_utils.draw_meridians_and_parallels(basemap, step_degrees=30.0, ax = the_ax)
        plot_basin_boundaries_from_shape(basemap, axes = the_ax, linewidth=0.4)


    #gs.update(wspace=0.5)
    fig.tight_layout()
    #fig.suptitle("Projected changes, T(2m), degrees, CRCM4")
    fig.savefig("proj_change_{0}_ccc.png".format(var_name))
def plot_swe():
    seasons = ["(a) Annual", " (b) Winter (DJF)", "(c) Spring (MAM)", "(d) Summer (JJA)", "(e) Fall (SON)"]
    months =  [range(1, 13), [12, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]  ]
    season_to_months = dict(zip(seasons, months))

    var_name = "sno"
    year_range_c = xrange(1970,2000)
    year_range_f = xrange(2041,2071)
    x, y = polar_stereographic.xs, polar_stereographic.ys
    i_array, j_array = _get_routing_indices()
    x_min, x_max, y_min, y_max = plot_utils.get_ranges(x[i_array, j_array], y[i_array, j_array])

    _generate_mask_of_domain_of_interest(i_array, j_array)
    if True: return

    plot_utils.apply_plot_params(width_pt= None, font_size=9, aspect_ratio=2.5)
    fig = plt.figure()
    assert isinstance(fig, Figure)

    basemap = polar_stereographic.basemap
    assert isinstance(basemap, Basemap)
    gs = gridspec.GridSpec(3,4, height_ratios=[1,1,1], width_ratios=[1,1,1,1])


    #color_map = my_cm.get_
    color_map = my_cm.get_red_blue_colormap(ncolors = 10, reversed=True)
    #color_map = mpl.cm.get_cmap(name="jet_r", lut=10)
    clevels = xrange(-8, 9, 2)
    all_plot_axes = []
    for i, season in enumerate(seasons):
        if not i:
            ax = fig.add_subplot(gs[0,1:3])
        else:
            row, col = (i - 1)  // 2 + 1, (i - 1) % 2
            ax = fig.add_subplot(gs[row, col * 2 : col * 2 + 2 ])
        all_plot_axes.append(ax)


        current = _get_data(v_name=var_name, months = season_to_months[season],
                    member_list=members.current_ids, year_range=year_range_c)
        future = _get_data(v_name=var_name, months = season_to_months[season],
                    member_list=members.future_ids, year_range=year_range_f)


        t, p = stats.ttest_ind(current, future, axis=0)
        #TODO: change it back to p <= 0.05 wheen doing real sign test
        significant = np.array(p <= 1)

        assert not np.all(~significant)
        assert not np.all(significant)

        current_m = np.mean(current, axis=0)
        future_m = np.mean(future, axis= 0)


        delta = (future_m - current_m)
        delta = np.array(delta)

        assert isinstance(ax, Axes)

        #delta = maskoceans(polar_stereographic.lons, polar_stereographic.lats, delta)
        save = delta[i_array, j_array]
        delta = np.ma.masked_all(delta.shape)
        delta[i_array, j_array] = save
        d_min = np.floor( np.min(save)  )
        d_max = np.ceil( np.max(save)  )


        bounds = plot_utils.get_boundaries_for_colobar(d_min, d_max, color_map.N, lambda x: np.round(x, decimals=10))
        print bounds

        bn = BoundaryNorm(bounds, color_map.N)

        d = np.max( np.abs([d_min, d_max]) )

        print season, np.min(delta), np.max(delta)

        #delta = np.ma.masked_where(delta < 0, delta )
        img = basemap.pcolormesh(x, y, delta, cmap = color_map, norm = bn, vmin = bounds[0], vmax = bounds[-1])
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", "8%", pad="3%")
        assert isinstance(cax, Axes)

        int_ticker = LinearLocator(numticks = color_map.N + 1)

        cb = fig.colorbar(img, cax = cax, ticks = bounds, boundaries = bounds)





        where_significant = significant
        significant = np.ma.masked_all(significant.shape)

        significant[(~where_significant)] = 0
        save = significant[i_array, j_array]
        significant = np.ma.masked_all(significant.shape)
        significant[i_array, j_array] = save

        basemap.pcolormesh( x, y, significant , cmap = mpl.cm.get_cmap(name = "gray", lut = 3),
                           vmin = -1, vmax = 1, ax = ax)

        ax.set_title(season)

    for the_ax in all_plot_axes:
        the_ax.set_xlim(x_min, x_max)
        the_ax.set_ylim(y_min, y_max)
        basemap.drawcoastlines(ax = the_ax, linewidth = 0.1)
        plot_utils.draw_meridians_and_parallels(basemap, step_degrees=30.0, ax = the_ax)
        plot_basin_boundaries_from_shape(basemap, axes = the_ax, linewidth=0.4)


    gs.update(wspace=0.5)

    #gs.tight_layout(fig)
    fig.suptitle("Projected changes, SWE, mm, CRCM4")
    fig.savefig("proj_change_{0}_ccc.png".format(var_name))

    pass
def plot_precip(data_path = "/home/huziy/skynet1_rech3/crcm4_data"):
    seasons = ["(a) Annual", " (b) Winter (DJF)", "(c) Spring (MAM)", "(d) Summer (JJA)", "(e) Fall (SON)"]
    months =  [range(1, 13), [12, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]  ]
    season_to_months = dict(zip(seasons, months))


    #remove annual
    seasons.pop(0)
    #put new numbering for the subplots
    new_numbering = ["a", "b", "c", "d"]


    var_name = "pcp"
    year_range_c = xrange(1970,2000)
    year_range_f = xrange(2041,2071)
    x, y = polar_stereographic.xs, polar_stereographic.ys
    i_array, j_array = _get_routing_indices()
    x_min, x_max, y_min, y_max = plot_utils.get_ranges(x[i_array, j_array], y[i_array, j_array])



    plot_utils.apply_plot_params(width_pt= None, font_size=9, aspect_ratio=2.5)
    fig = plt.figure()
    assert isinstance(fig, Figure)

    basemap = polar_stereographic.basemap
    assert isinstance(basemap, Basemap)
    gs = gridspec.GridSpec(3,2, height_ratios=[1,1,1], width_ratios=[1,1])



    #determine min an max for color scales
    min_val = np.inf
    max_val = -np.inf
    for season in seasons:
        current = _get_data(v_name=var_name, months = season_to_months[season],
                    member_list=members.current_ids, year_range=year_range_c)
        future = _get_data(v_name=var_name, months = season_to_months[season],
                    member_list=members.future_ids, year_range=year_range_f)

        current_m = np.mean(current, axis=0)
        future_m = np.mean(future, axis= 0)


        delta = future_m[i_array, j_array] - current_m[i_array, j_array]

        the_min = delta.min()
        the_max = delta.max()

        min_val = min(min_val, the_min)
        max_val = max(max_val, the_max)

    min_val = np.floor(min_val)
    max_val = np.ceil(max_val)




    color_map = my_cm.get_red_blue_colormap(ncolors = 10, reversed=False)
    #color_map = mpl.cm.get_cmap(name="jet_r", lut=10)
    clevels = xrange(-8, 9, 2)
    all_plot_axes = []
    for i, season in enumerate(seasons):
        row, col = i // 2, i % 2
        ax = fig.add_subplot(gs[row, col ])
        all_plot_axes.append(ax)


        current = _get_data(data_folder=data_path, v_name=var_name, months = season_to_months[season],
                    member_list=members.current_ids, year_range=year_range_c)
        future = _get_data(data_folder=data_path, v_name=var_name, months = season_to_months[season],
                    member_list=members.future_ids, year_range=year_range_f)


        #t, p = stats.ttest_ind(current, future, axis=0)

        #significant = np.array(p <= 0.05)
        significant = calculate_significance_using_bootstrap(current, future)
        assert not np.all(~significant)
        assert not np.all(significant)

        current_m = np.mean(current, axis=0)
        future_m = np.mean(future, axis= 0)

        seconds_per_day = 24 * 60 * 60
        delta = (future_m - current_m) * seconds_per_day
        delta = np.array(delta)

        assert isinstance(ax, Axes)

        #delta = maskoceans(polar_stereographic.lons, polar_stereographic.lats, delta)
        save = delta[i_array, j_array]
        delta = np.ma.masked_all(delta.shape)
        delta[i_array, j_array] = save
        d_min = np.floor( min_val * 10 ) / 10.0
        d_max = np.ceil( max_val *10 ) / 10.0

        if d_min  > 0: color_map = my_cm.get_blue_colormap(ncolors=10)

        img = basemap.pcolormesh(x, y, delta, cmap = color_map, vmin = d_min, vmax = d_max)
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", "8%", pad="3%")
        assert isinstance(cax, Axes)

        int_ticker = LinearLocator(numticks = color_map.N + 1)

        cb = fig.colorbar(img, cax = cax, ticks = int_ticker)
        cax.set_title("mm/d")

        where_significant = significant
        significant = np.ma.masked_all(significant.shape)

        significant[(~where_significant)] = 0
        save = significant[i_array, j_array]
        significant = np.ma.masked_all(significant.shape)
        significant[i_array, j_array] = save

        basemap.pcolormesh( x, y, significant , cmap = mpl.cm.get_cmap(name = "gray", lut = 3),
                           vmin = -1, vmax = 1, ax = ax)

        ax.set_title( season.replace( re.findall( "([a-z])", season)[0], new_numbering[i]) )


    #plot djf swe change
    season = " (b) Winter (DJF)"
    ax = fig.add_subplot(gs[2, : ])
    all_plot_axes.append(ax)
    var_name = "sno"

    current = _get_data(data_folder=data_path, v_name=var_name, months = season_to_months[season],
                    member_list=members.current_ids, year_range=year_range_c)
    future = _get_data(data_folder=data_path, v_name=var_name, months = season_to_months[season],
                    member_list=members.future_ids, year_range=year_range_f)


    #t, p = stats.ttest_ind(current, future, axis=0)

    #significant = np.array(p <= 0.05)
    significant = calculate_significance_using_bootstrap(current, future)

    assert not np.all(~significant)
    assert not np.all(significant)

    current_m = np.mean(current, axis=0)
    future_m = np.mean(future, axis= 0)


    delta = future_m - current_m
    delta = np.array(delta)

    assert isinstance(ax, Axes)

    #delta = maskoceans(polar_stereographic.lons, polar_stereographic.lats, delta)
    save = delta[i_array, j_array]
    delta = np.ma.masked_all(delta.shape)
    delta[i_array, j_array] = save
    d_min = np.floor( np.min(save) * 10 ) / 10.0
    d_max = np.ceil( np.max(save) *10 ) / 10.0

    if d_min >= 0: color_map = my_cm.get_blue_colormap(ncolors=10)

    bounds = plot_utils.get_boundaries_for_colobar(d_min, d_max, color_map.N, lambda x: np.round(x, decimals=0))

    bn = BoundaryNorm(bounds, color_map.N)


    img = basemap.pcolormesh(x, y, delta, cmap = color_map, vmin = bounds[0], vmax = bounds[-1], norm = bn)
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", "8%", pad="3%")
    assert isinstance(cax, Axes)

    int_ticker = LinearLocator(numticks = color_map.N + 1)

    cb = fig.colorbar(img, cax = cax, ticks = bounds)
    cax.set_title("mm")

    where_significant = significant
    significant = np.ma.masked_all(significant.shape)

    significant[(~where_significant)] = 0
    save = significant[i_array, j_array]
    significant = np.ma.masked_all(significant.shape)
    significant[i_array, j_array] = save

    basemap.pcolormesh( x, y, significant , cmap = mpl.cm.get_cmap(name = "gray", lut = 3),
                        vmin = -1, vmax = 1, ax = ax)

    ax.set_title( season.replace( re.findall( "([a-z])", season)[0], "e"))
    #finish swe djf



    for the_ax in all_plot_axes:
        the_ax.set_xlim(x_min, x_max)
        the_ax.set_ylim(y_min, y_max)
        basemap.drawcoastlines(ax = the_ax, linewidth = 0.1)
        plot_utils.draw_meridians_and_parallels(basemap, step_degrees=30.0, ax = the_ax)
        plot_basin_boundaries_from_shape(basemap, axes = the_ax, linewidth=0.4)


    #gs.update(wspace=0.5)

    #gs.tight_layout(fig)
    #fig.suptitle("Projected changes, total precip (mm/day), CRCM4")
    fig.tight_layout()
    fig.savefig("proj_change_{0}_ccc.png".format(var_name))

    pass
def plot_swe_biases():

    seasons = ["(a) Annual", " (b) Winter (DJF)", "(c) Spring (MAM)", "(d) Summer (JJA)", "(e) Fall (SON)"]
    months =  [range(1, 13), [12, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]  ]
    season_to_months = dict(zip(seasons, months))

    swe_obs_name = "swe"
    cru_data_store, crcm4_data_store = _get_comparison_data_swe(swe_var_name= swe_obs_name,
        season_to_months=season_to_months, start_date=datetime(1980,1,1), end_date=datetime(1996, 12, 31))

    x, y = polar_stereographic.xs, polar_stereographic.ys
    i_array, j_array = _get_routing_indices()
    x_min, x_max, y_min, y_max = plot_utils.get_ranges(x[i_array, j_array], y[i_array, j_array])



    plot_utils.apply_plot_params(width_pt= None, font_size=9, aspect_ratio=2.5)
    fig = plt.figure()
    assert isinstance(fig, Figure)

    basemap = polar_stereographic.basemap
    assert isinstance(basemap, Basemap)
    gs = gridspec.GridSpec(3,2)

    color_map = my_cm.get_red_blue_colormap(ncolors = 14, reversed=True)
    clevels = xrange(-8, 9, 2)
    all_plot_axes = []
    for i, season in enumerate(seasons):
        if not i:
            ax = fig.add_subplot(gs[0,:])
        else:
            row, col = (i - 1)  // 2 + 1, (i -1) % 2
            ax = fig.add_subplot(gs[row, col])
        all_plot_axes.append(ax)
        assert isinstance(ax, Axes)
        delta = crcm4_data_store[season] - cru_data_store[season]

        #delta = maskoceans(polar_stereographic.lons, polar_stereographic.lats, delta)
        save = delta[i_array, j_array]
        delta = np.ma.masked_all(delta.shape)
        delta[i_array, j_array] = save


        vmax = np.ceil( np.max(save) / 10.0) * 10
        vmin = np.floor( np.min(save) / 10.0) * 10

        bounds = plot_utils.get_boundaries_for_colobar(vmin, vmax, color_map.N, lambda x: np.round(x, decimals = 1))
        bn = BoundaryNorm(bounds, color_map.N)
        img = basemap.pcolormesh(x, y, delta, cmap = color_map, vmin = vmin, vmax = vmax, norm = bn)
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", "8%", pad="3%")
        int_ticker = LinearLocator(numticks = color_map.N + 1)





        fig.colorbar(img, cax = cax, ticks = bounds, boundaries = bounds)
        ax.set_title(season)

    for the_ax in all_plot_axes:
        the_ax.set_xlim(x_min, x_max)
        the_ax.set_ylim(y_min, y_max)
        basemap.drawcoastlines(ax = the_ax, linewidth = 0.1)
        plot_utils.draw_meridians_and_parallels(basemap, step_degrees=30.0, ax = the_ax)
        plot_basin_boundaries_from_shape(basemap, axes = the_ax, linewidth=0.4)
#        put_selected_stations(the_ax, basemap, i_array, j_array)


    #gs.tight_layout(fig)
    fig.suptitle("SWE (mm), CRCM4 - Ross Brown dataset (1981-1997)")
    fig.savefig("seasonal_{0}_ccc.png".format(swe_obs_name))
def plot_precip_biases():
    seasons = ["(a) Annual", " (b) Winter (DJF)", "(c) Spring (MAM)", "(d) Summer (JJA)", "(e) Fall (SON)"]
    months =  [range(1, 13), [12, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]  ]
    season_to_months = dict(zip(seasons, months))
    cru_var_name = "pre"
    cru_data_store, crcm4_data_store = _get_comparison_data(
        crcm4_data_folder="/home/huziy/skynet1_rech3/crcm4_data/aex_p1pcp",
        cru_data_path = "data/cru_data/CRUTS3.1/cru_ts_3_10.1901.2009.pre.dat.nc",
        cru_var_name=cru_var_name, season_to_months=season_to_months
    )

    x, y = polar_stereographic.xs, polar_stereographic.ys
    i_array, j_array = _get_routing_indices()
    x_min, x_max, y_min, y_max = plot_utils.get_ranges(x[i_array, j_array], y[i_array, j_array])



    plot_utils.apply_plot_params(width_pt= None, font_size=9, aspect_ratio=2.5)

    fig = plt.figure()
    assert isinstance(fig, Figure)

    basemap = polar_stereographic.basemap
    assert isinstance(basemap, Basemap)
    gs = gridspec.GridSpec(3,2, width_ratios=[1,1], height_ratios=[1, 1, 1])

    color_map = my_cm.get_red_blue_colormap(ncolors = 16, reversed=False)
    color_map.set_over("k")
    color_map.set_under("k")
    all_plot_axes = []
    img = None
    for i, season in enumerate(seasons):
        if not i:
            ax = fig.add_subplot(gs[0,:])
        else:
            row, col = (i - 1)  // 2 + 1, (i - 1) % 2
            ax = fig.add_subplot(gs[row, col])
        all_plot_axes.append(ax)
        assert isinstance(ax, Axes)

        delta = crcm4_data_store[season] - cru_data_store[season]
        save = delta[i_array, j_array]
        delta[:, :] = np.ma.masked
        delta[i_array, j_array] = save
        img = basemap.pcolormesh(x, y, delta, cmap = color_map, vmin = -2, vmax = 2)
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", "8%", pad="3%")
        int_ticker = LinearLocator(numticks = color_map.N + 1)
        fig.colorbar(img, cax = cax, ticks = MultipleLocator(base = 0.5))
        ax.set_title(season)

    for the_ax in all_plot_axes:
        assert isinstance(the_ax, Axes)
        the_ax.set_xlim(x_min, x_max)
        the_ax.set_ylim(y_min, y_max)
        the_ax.set_xmargin(0)
        the_ax.set_ymargin(0)
        basemap.drawcoastlines(ax = the_ax, linewidth = 0.1)
        plot_utils.draw_meridians_and_parallels(basemap, step_degrees=30.0, ax = the_ax)
        plot_basin_boundaries_from_shape(basemap, axes = the_ax, linewidth=0.4)
#        put_selected_stations(the_ax, basemap, i_array, j_array)

#    ax = fig.add_subplot(gs[3,:])
#    assert isinstance(ax, Axes)
#    fig.colorbar(img, cax = ax, orientation = "horizontal", ticks = MultipleLocator(base = 0.5))

    #gs.tight_layout(fig)
    fig.suptitle("Total precip, mm/day, CRCM4 - CRU")
    fig.savefig("seasonal_{0}_ccc.png".format(cru_var_name))
def plot_swe_and_temp_on_one_plot():
    seasons = ["(a) Annual", " (b) Winter (DJF)", "(c) Spring (MAM)", "(d) Summer (JJA)", "(e) Fall (SON)"]
    months =  [range(1, 13), [12, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]  ]
    season_to_months = dict(zip(seasons, months))
    cru_var_name = "tmp"

    temp_obs_data_store, temp_crcm4_data_store = _get_comparison_data(cru_var_name= cru_var_name,
        season_to_months=season_to_months)

    x, y = polar_stereographic.xs, polar_stereographic.ys
    i_array, j_array = _get_routing_indices()
    x_min, x_max, y_min, y_max = plot_utils.get_ranges(x[i_array, j_array], y[i_array, j_array])

    #get swe data
    swe_obs_name = "swe"
    swe_obs_data_store, swe_crcm4_data_store = _get_comparison_data_swe(swe_var_name= swe_obs_name,
        season_to_months=season_to_months, start_date=datetime(1980,1,1), end_date=datetime(1997, 1, 1))



    plot_utils.apply_plot_params(width_pt= None, font_size=9, aspect_ratio=2.5)

    fig = plt.figure()
    assert isinstance(fig, Figure)
    gs = gridspec.GridSpec(2, 1)

    basemap = polar_stereographic.basemap
    swe_season = seasons[1]
    temp_season = seasons[2]

    var_names = [ "swe", cru_var_name]
    the_seasons = [ swe_season, temp_season ]

    labels = [ "(a) Winter (DJF)", "(b) Sping (MAM)"]
    units = [ "mm", "$^{\\circ}{\\rm C}$" ]

    data_stores = [
        [swe_obs_data_store, swe_crcm4_data_store],
        [temp_obs_data_store, temp_crcm4_data_store]
    ]



    all_plot_axes = []
    for i, season, var_name, store, label, unit in zip(xrange(len(seasons)), the_seasons, var_names, data_stores,
            labels, units):
        ax = fig.add_subplot(gs[i, 0])
        all_plot_axes.append(ax)
        assert isinstance(ax, Axes)

        crcm4 = store[1][season]
        obs = store[0][season]

        delta = crcm4 - obs
        if var_name == "tmp": delta -= 273.15

        if var_name == "swe":
            ax.annotate("(1979-1997)", (0.1, 0.1), xycoords = "axes fraction",
                font_properties = FontProperties(weight = "bold"))
        elif var_name == "tmp":
            ax.annotate("(1970-1999)", (0.1, 0.1), xycoords = "axes fraction",
                font_properties = FontProperties(weight = "bold"))


        color_map = my_cm.get_red_blue_colormap(ncolors = 16, reversed=(var_name == "tmp"))
        color_map.set_over("k")
        color_map.set_under("k")



        #delta = maskoceans(polar_stereographic.lons, polar_stereographic.lats, delta)
        save = delta[i_array, j_array]
        delta = np.ma.masked_all(delta.shape)
        delta[i_array, j_array] = save



        vmin = np.floor( np.min(save)  )
        vmax = np.ceil( np.max(save)  )

        decimals = 0 if var_name == "swe" else 1
        round_func = lambda x: np.round(x, decimals= decimals)
        bounds = plot_utils.get_boundaries_for_colobar(vmin, vmax, color_map.N, round_func= round_func)
        bn = BoundaryNorm( bounds, color_map.N )

        img = basemap.pcolormesh(x, y, delta, cmap = color_map, norm = bn)
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", "8%", pad="3%")
        fig.colorbar(img, cax = cax, boundaries = bounds, ticks = bounds)
        ax.set_title(label)
        cax.set_title(unit)




    for the_ax in all_plot_axes:
        the_ax.set_xlim(x_min, x_max)
        the_ax.set_ylim(y_min, y_max)
        basemap.drawcoastlines(ax = the_ax, linewidth = 0.1)
        plot_utils.draw_meridians_and_parallels(basemap, step_degrees=30.0, ax = the_ax)
        plot_basin_boundaries_from_shape(basemap, axes = the_ax, linewidth=0.4)
        put_selected_stations(the_ax, basemap, i_array, j_array)

    fig.tight_layout()
    fig.savefig("swe_temp_biases.png")
def plot_data(data, i_array, j_array, name='AEX', title = None, digits = 1,
                                      color_map = mpl.cm.get_cmap('RdBu_r'), 
                                      minmax = (None, None),
                                      units = '%',
                                      colorbar_orientation = 'vertical',
                                      draw_colorbar = True,
                                      basemap = None, axes = None,
                                      impose_lower_limit = None, upper_limited = False

                                      ):



    if name is not None:
        plt.figure()

    to_plot = np.ma.masked_all((n_cols, n_rows))
    for index, i, j in zip( range(len(data)), i_array, j_array):
        to_plot[i, j] = data[index]


    print np.ma.min(data), np.ma.max(data)
    
  #  m.pcolor(xs, ys, to_plot, cmap = mpl.cm.get_cmap('RdBu_r'))

    if basemap is None:
        the_basemap = m
    else:
        the_basemap = basemap

    image = the_basemap.pcolormesh(xs, ys, to_plot.copy(), cmap = color_map,
                                          vmin = minmax[0],
                                          vmax = minmax[1], ax = axes)



    #ads to m fields basins and basins_info which contain shapes and information
 #   m.readshapefile('data/shape/contour_bv_MRCC/Bassins_MRCC_utm18', 'basins')
 #   m.scatter(xs, ys, c=to_plot)
    plot_basin_boundaries_from_shape(m, axes=axes, linewidth = 2.1)
    #the_basemap.drawrivers(linewidth = 0.5, ax = axes)
    the_basemap.drawcoastlines(linewidth = 0.5, ax = axes)
    plot_utils.draw_meridians_and_parallels(the_basemap, step_degrees = 30)



    axes.set_title(title if title is not None else name)

    #zoom_to_qc()
    x_min, x_max, y_min, y_max = plot_utils.get_ranges(xs[i_array, j_array], ys[i_array, j_array])
    axes.set_xlim(x_min, x_max)
    axes.set_ylim(y_min, y_max)


    if draw_colorbar:
        from mpl_toolkits.axes_grid1 import make_axes_locatable

        divider = make_axes_locatable(axes)
        cax = divider.append_axes("right", "8%", pad="3%")
        int_ticker = LinearLocator(numticks = color_map.N + 1)
        cb = axes.figure.colorbar(image, ticks = int_ticker,
                          orientation = colorbar_orientation,
                          format = '%d', cax = cax, ax=axes, drawedges = True)

        cb.ax.set_title(units)
        #cb.outline.remove()
        bottom, top = cb.ax.get_ylim()
        left, right = cb.ax.get_xlim()
        print bottom, top, left, right


        if impose_lower_limit is None:
            new_bottom = min( np.min(data), 0 )
        else:
            new_bottom = impose_lower_limit
        #new_bottom = np.floor( new_bottom / 10.0 ) * 10.0


        new_bottom = np.abs((new_bottom - minmax[0]) / (float(minmax[1] - minmax[0])))

        new_bottom = plot_utils.get_closest_tick_value(color_map.N + 1, new_bottom) - 1.0e-4



        print new_bottom
        cb.ax.set_ylim(bottom = new_bottom)
        left, right = cb.ax.get_xlim()
        bottom, top = cb.ax.get_ylim()

        #cb.ax.set_xlim(left = 0, right = 0.8)
        cb.outline.set_visible( False )

        if upper_limited:
            cl = cb.ax.get_yticklabels()
            labels = []
            for text in cl:
                labels.append(text.get_text())

            labels[-1] = '$\\geq$' + labels[-1]
            cb.ax.set_yticklabels(labels)