Example #1
0
def test_plot_topomap_cnorm():
    """Test colormap normalization."""
    if check_version("matplotlib", "3.2.0"):
        from matplotlib.colors import TwoSlopeNorm
    else:
        from matplotlib.colors import DivergingNorm as TwoSlopeNorm

    np.random.seed(42)
    v = np.random.uniform(low=-1, high=2.5, size=64)
    v[:3] = [-1, 0, 2.5]

    montage = make_standard_montage("biosemi64")
    info = create_info(montage.ch_names, 256, "eeg").set_montage("biosemi64")
    cnorm = TwoSlopeNorm(vmin=-1, vcenter=0, vmax=2.5)

    # pass only cnorm, no vmin/vmax
    plot_topomap(v, info, cnorm=cnorm)

    # pass cnorm and vmin
    msg = "vmin=-1.* is implicitly defined by cnorm, ignoring vmin=-10.*"
    with pytest.warns(RuntimeWarning, match=msg):
        plot_topomap(v, info, vmin=-10, cnorm=cnorm)

    # pass cnorm and vmax
    msg = "vmax=2.5 is implicitly defined by cnorm, ignoring vmax=10.*"
    with pytest.warns(RuntimeWarning, match=msg):
        plot_topomap(v, info, vmax=10, cnorm=cnorm)
Example #2
0
def vapour_anomaly(cubes, lat=45, long=0, time_slice=-1):

    for cube in cubes:
        if cube.standard_name == 'specific_humidity':
            vapour = cube.copy()

    mean_vapour = vapour.collapsed('time', iris.analysis.MEAN)
    anomaly = vapour - mean_vapour
    data = vapour.data

    run_length = vapour.shape[0]

    x_axis = vapour.coord('longitude').points
    y_axis = vapour.coord('level_height').points

    plt.contourf(np.arange(0, run_length) * 0.25,
                 y_axis,
                 data[:, :, lat, long].T,
                 bg.N,
                 cmap=bg,
                 norm=TwoSlopeNorm(0))
    plt.title('Water vapour abundance at equator, long=%s' % x_axis[long])
    plt.xlabel('Time [days]')
    plt.ylabel('Height [m]')
    plt.colorbar(pad=0.1)
    plt.show()
Example #3
0
    def redraw(self, event):
        # Only redraw if mouse isn't being held down

        galaxy = self.galaxy
        systems = galaxy.systems

        total = sum([scale.get() for scale in self.scales])
        weights = [scale.get() / total for scale in self.scales]

        for s in systems:
            s.updateScore(weights, galaxy.min_resources, galaxy.max_resources)
        galaxy.calcScoreRange()
        galaxy.calcMedian()
        try:
            norm = TwoSlopeNorm(vmin=galaxy.min_score,
                                vcenter=galaxy.median_score,
                                vmax=galaxy.max_score)
        except:  # Use regular Normalize in the case TwoSlopeNorm fails
            norm = Normalize(vmin=galaxy.min_score, vmax=galaxy.max_score)

        for i in range(len(systems)):
            s = systems[i]

            normed = norm(s.score)
            rgba = self.cmap(normed)
            color = self.convert_to_hex(rgba)

            self.canvas.itemconfig(self.system_to_circ[i], fill=color)
def sphere_qbo(cubes, level=47, time_slice=-1, long=0, lat=0):

    for cube in cubes:
        if cube.standard_name == 'x_wind' or cube.standard_name == 'eastward_wind':
            x_wind = cube.copy()

    longs = np.linspace(-180, 180, 144)
    lats = np.linspace(-90, 90, 90)
    # x_wind = x_wind[:,:,25:65,:]

    ortho = ccrs.Orthographic(central_longitude=long, central_latitude=lat)

    fig = plt.figure()
    # fig, ax0 = plt.subplots(figsize=(5,5))
    # ax0.imshow(image)
    fig.patch.set_facecolor('black')
    ax1 = plt.axes(projection=ortho)
    ax1.set_global()

    # ax.gridlines()
    ax1.contourf(longs,
                 lats,
                 np.roll(x_wind[time_slice, level, :, :].data, 72, axis=1),
                 transform=ccrs.PlateCarree(),
                 cmap=redblu,
                 norm=TwoSlopeNorm(0))
Example #5
0
def plot_divergent_heatmap(df, topics, ordered_topics_dict, colormap):
    """Plot a heat map showing the mean topic distribution per outlet"""
    topic_words = get_top_n_words(ordered_topics_dict)
    num_topics = topics['params']['num_topics']

    fig_width = min(ceil(0.6 * num_topics + 6), 20)
    fig_height = min(ceil(0.65 * num_topics), 20)
    fig = plt.figure(figsize=(fig_width, fig_height))

    sns.set_color_codes("pastel")
    s = sns.heatmap(df,
                    cmap=colormap,
                    norm=TwoSlopeNorm(0),
                    linewidths=2.0,
                    square=True)
    s.set_xticklabels(s.get_xticklabels(), rotation=-45, ha='left')
    s.set_yticklabels(topic_words, rotation=0, fontsize=12)
    s.set_xlabel("")
    st = fig.suptitle("Start Date: {}  End Date: {}  Articles: {}".format(
        topics['params']['begin_date'], topics['params']['end_date'],
        topics['params']['articleCount']),
                      y=0.92)
    fig.savefig(f"fig-{prefix}-divergent-heatmap.png",
                bbox_extra_artists=[st],
                bbox_inches='tight')
Example #6
0
def test_extend_colorbar_customnorm():
    # This was a funny error with TwoSlopeNorm, maybe with other norms,
    # when extend='both'
    fig, (ax0, ax1) = plt.subplots(2, 1)
    pcm = ax0.pcolormesh([[0]], norm=TwoSlopeNorm(vcenter=0., vmin=-2, vmax=1))
    cb = fig.colorbar(pcm, ax=ax0, extend='both')
    np.testing.assert_allclose(cb.ax.get_position().extents,
                               [0.78375, 0.536364, 0.796147, 0.9], rtol=1e-3)
Example #7
0
def colormapAndNorm(p, df, final_df=final_df):
    cc_cmap = returnCMAP(p)
    cmap = ListedColormap(cc_cmap)
    if p != 'pH':
        norm = Normalize(vmin=df[p].min(), vmax=df[p].max())
    else:
        norm = TwoSlopeNorm(vmin=final_df[p].min(),
                            vcenter=7,
                            vmax=final_df[p].max())

    return cmap, norm
Example #8
0
def pcolormesh_dict(vmin, vmax, center=None, cmap=None, norm=None, **kwargs):
    ret = {}
    ret.update(kwargs)
    if center is not None and norm is None:
        assert vmin < center < vmax
        ret.setdefault("norm", TwoSlopeNorm(center, vmin, vmax))

        if cmap is None:
            ret.setdefault("cmap", "crownet_bwr")

    ret.setdefault("norm", Normalize(vmin, vmax))
    ret.setdefault("cmap", t_cmap("Reds", replace_index=(0, 1, 0.0)))

    return ret
Example #9
0
    def visualize_names(self,
                        name: str,
                        people: bool = False,
                        save: str = None):
        """ Visualize the most frequent names and their respective averaged sentiment

        Parameters
        ----------
        name : str
            Name of the movie

        people : bool, default = False
            Whether to only use names with a first and last name

        save : str, default None
            The save prefix name
        """
        if not self.processed_names:
            raise Exception(
                "Please preprocess the names from the reviews first through: \n"
                "character.preprocess_names_and_reviews('reviews.json', 'names.json')"
            )

        if name not in self.processed_names.keys():
            names = list(self.processed_names.keys())
            raise Exception(
                f"Please select one of the following names: {names}")

        df = self.processed_names[name]
        if people:
            df = df.loc[df.Nr_Words > 1, :]

        plt.figure(figsize=(12, 5))
        norm = TwoSlopeNorm(vmin=-1, vcenter=0.0, vmax=1)
        colors = [plt.cm.bwr(norm(c)) for c in df.Sentiment.head(15)]
        ax = sns.barplot(x='Sentiment',
                         y='Word',
                         data=df.head(15),
                         palette=colors,
                         edgecolor='black')
        plt.tight_layout()
        plt.xlabel("Sentiment")
        plt.ylabel("")

        if save:
            plt.savefig(
                f"{self.dir_path}images/characters/{save}_characters.png",
                dpi=300)
        else:
            plt.show()
Example #10
0
def plot_temp_anomaly(cubes, period=(0, 220), lat=45, level=47):
    """ Plot temperature anomaly, temperature minus the local time-averaged temperature
        Default latitude is the equator
        Arguments: CubeList, latitude, and atmospheric level"""

    for cube in cubes:
        if cube.standard_name == 'air_potential_temperature':
            theta = cube[period[0]:period[1], :, lat, :].copy()
        if cube.standard_name == 'air_pressure':
            pressure = cube[period[0]:period[1], :, lat, :].copy()

    run_length, longitudes = theta.shape[0], theta.shape[2] / 2

    for coord in theta.coords():
        if coord.long_name == 'Hybrid height':
            heights = np.round(theta.coord('Hybrid height').points * 1e-03, 0)
        elif coord.long_name == 'level_height':
            heights = np.round(theta.coord('level_height').points * 1e-03, 0)

    p0 = iris.coords.AuxCoord(100000.0,
                              long_name='reference_pressure',
                              units='Pa')
    p0.convert_units(pressure.units)
    # R and cp in J/kgK for 300K
    temperature = theta * ((pressure / p0)**(287.05 / 1005))

    temp_time_mean = temperature.collapsed('time', iris.analysis.MEAN)
    anomaly = temperature - temp_time_mean

    plt.figure(figsize=(10, 5))
    plt.contourf(np.arange(-longitudes, longitudes),
                 np.arange(period[0], period[1]),
                 np.roll(anomaly[:, level, :].data, 72, axis=1),
                 np.arange(-20, 21, 5),
                 cmap=brewer_redblu,
                 norm=TwoSlopeNorm(0))
    plt.title('Temperature Anomaly at Equator, h=%s km' % (heights[level]))
    plt.xlabel('Longitude [degrees]')
    plt.xticks((-144, -120, -96, -72, -48, -24, 0, 24, 48, 72, 96, 120, 144),
               ('180W', '150W', '120W', '90W', '60W', '30W', '0', '30E', '60E',
                '90E', '120E', '150E', '180E'))
    # plt.xticks((-72, -60, -48, -36, -24, -12, 0, 12, 24, 36, 48, 60, 72), ('180W', '150W',
    #            '120W', '90W', '60W', '30W', '0', '30E', '60E', '90E', '120E', '150E', '180E'))
    plt.ylabel('Time [months]')
    cbar = plt.colorbar(pad=0.1)
    cbar.set_ticks(np.arange(-20, 21, 5))
    cbar.ax.set_title('K')
    # plt.savefig('/exports/csce/datastore/geos/users/s1144983/papers/laso/epsfigs/abs_temp_anomaly_%s_new.eps' %(heights[level]), format='eps')
    plt.show()
Example #11
0
def plot_world_var(gdf_world, var):
    vmin = min(gdf_world[var])
    vmax = max(gdf_world[var])
    if vmin < 0:
        norm = TwoSlopeNorm(vmin=vmin, vcenter=0, vmax=vmax)
        gdf_world.plot(
            column=var,
            legend=True,
            cmap=sns.color_palette("vlag", as_cmap=True),
            norm=norm,
        )
    else:
        gdf_world.plot(
            column=var, legend=True, cmap=sns.color_palette("crest", as_cmap=True)
        )
    plt.savefig(cfg.RESULT_PNG_DIR_PATH + "{}_{}".format(cfg.DATE, var))
Example #12
0
    def draw_universe(self, galaxy):
        self.galaxy = galaxy
        systems = galaxy.systems

        #make key for colors
        self.key = tk.Canvas(self.view, height=15, width=385)
        self.key.grid(row=0, column=0, sticky='ne')

        self.key.create_text(0, 0, anchor='nw', text="Worst")
        self.key.create_text(355, 0, anchor='nw', text="Best")

        for s in systems:
            for c in s.hyperlanes:
                p1 = s.pos
                p2 = systems[c].pos
                self.canvas.create_line(p1[0], p1[1], p2[0], p2[1])

        self.system_to_circ = {}

        print(galaxy.min_score, galaxy.max_score, galaxy.avg_score,
              galaxy.median_score)
        try:
            norm = TwoSlopeNorm(vmin=galaxy.min_score,
                                vcenter=galaxy.median_score,
                                vmax=galaxy.max_score)
        except:  # Use regular Normalize in the case TwoSlopeNorm fails
            norm = Normalize(vmin=galaxy.min_score, vmax=galaxy.max_score)
        for i in range(len(systems)):
            s = systems[i]
            p = s.pos
            normed = norm(s.score)
            rgba = self.cmap(normed)
            color = self.convert_to_hex(rgba)

            circ_id = self.canvas.create_circle(p[0],
                                                p[1],
                                                5,
                                                fill=color,
                                                activewidth=4,
                                                tags=i)
            self.system_to_circ[i] = circ_id
            enter_callback = lambda event, tag=i: self.system_enter(event, tag)
            leave_callback = lambda event, tag=i: self.system_exit(event, tag)
            self.canvas.tag_bind(circ_id, "<Enter>", enter_callback)
            self.canvas.tag_bind(circ_id, "<Leave>", leave_callback)
        self.color_key(False)
Example #13
0
def plot_uv(cubes, start=0, end=240, levels=(37, 44, 47, 53)):

    for cube in cubes:
        if cube.standard_name == 'eastward_wind' or cube.standard_name == 'x_wind':
            x_wind = cube[start:end, :, :, :].copy()
        if cube.standard_name == 'northward_wind' or cube.standard_name == 'y_wind':
            y_wind = cube[start:end, :, :, :].copy()

    longitudes, latitudes = x_wind.shape[3] / 2, x_wind.shape[2] / 2

    y_wind = y_wind.regrid(x_wind, iris.analysis.Linear())

    for coord in x_wind.coords():
        if coord.long_name == 'Hybrid height':
            heights = np.round(x_wind.coord('Hybrid height').points * 1e-03, 0)
        elif coord.long_name == 'level_height':
            heights = np.round(x_wind.coord('level_height').points * 1e-03, 0)

    zonal_mean_u = x_wind.collapsed('t', iris.analysis.MEAN)
    u_prime = x_wind - zonal_mean_u
    zonal_mean_v = y_wind.collapsed('t', iris.analysis.MEAN)
    v_prime = y_wind - zonal_mean_v
    cross_term = u_prime * v_prime

    for level in levels:

        plt.figure(figsize=(10, 5))
        plt.contourf(np.arange(-longitudes, longitudes),
                     np.arange(-latitudes, latitudes),
                     np.roll(cross_term[end - 1, level, :, :].data, 72,
                             axis=1),
                     brewer_redblu.N,
                     cmap=brewer_redblu,
                     norm=TwoSlopeNorm(0))
        plt.title('$U^{\prime} \cdot V^{\prime}$ [m2 s-2], h=%s km, day=%s' %
                  (heights[level], end / 4))
        plt.xlabel('Longitude [degrees]')
        plt.xticks((-72, -60, -48, -36, -24, -12, 0, 12, 24, 36, 48, 60, 72),
                   ('180W', '150W', '120W', '90W', '60W', '30W', '0', '30E',
                    '60E', '90E', '120E', '150E', '180E'))
        plt.ylabel('Latitude [degrees]')
        plt.colorbar(pad=0.1)
        plt.show()
Example #14
0
def test_extend_colorbar_customnorm():
    # This was a funny error with TwoSlopeNorm, maybe with other norms,
    # when extend='both'
    N = 100
    X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
    Z1 = np.exp(-X**2 - Y**2)
    Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
    Z = (Z1 - Z2) * 2

    fig, ax = plt.subplots(2, 1)
    pcm = ax[0].pcolormesh(X,
                           Y,
                           Z,
                           norm=TwoSlopeNorm(vcenter=0., vmin=-2, vmax=1),
                           cmap='RdBu_r')
    cb = fig.colorbar(pcm, ax=ax[0], extend='both')
    np.testing.assert_allclose(cb.ax.get_position().extents,
                               [0.78375, 0.536364, 0.796147, 0.9],
                               rtol=1e-3)
Example #15
0
def property_to_color(prop, cmap="viridis", **kwargs):
    """
    Convert a scalar array of property values to colors,
    given a provided color map (or property name).

    Args:
        prop (array_like): the scalar array of property values
        cmap (str): the color map name or property name
        vmin (float): the minimum value of the property color scale
        vmax (float): the maximum value of the property color scale
        kwargs (dict): optional keyword arguments

    Returns:
        array_like: the array of color values for the given property
    """
    from matplotlib.cm import get_cmap

    midpoint = kwargs.get("midpoint",
                          0.0 if cmap in ("d_norm", "esp") else None)
    colormap = get_cmap(
        kwargs.get("colormap", DEFAULT_COLORMAPS.get(cmap, cmap)))
    norm = None
    vmin = kwargs.get("vmin", prop.min())
    vmax = kwargs.get("vmax", prop.max())
    if midpoint is not None:
        try:
            from matplotlib.colors import TwoSlopeNorm
        except ImportError:
            from matplotlib.colors import DivergingNorm as TwoSlopeNorm
        assert vmin <= midpoint
        assert vmax >= midpoint
        norm = TwoSlopeNorm(vmin=vmin, vcenter=midpoint, vmax=vmax)
        prop = norm(prop)
        return colormap(prop)
    else:
        import numpy as np

        prop = np.clip(prop, vmin, vmax) - vmin
        return colormap(prop)
Example #16
0
def main(parser):
    args = parser.parse_args()

    infastx = args.inFastx if args.inFastx else "-"
    motifs = args.motifs.split(',')
    sortedRecs = sorted(list(pysam.FastxFile(infastx, 'r')),
                        key=sortFunc(args.sortCluster))
    if not len(sortedRecs):
        print(f'No records in {infastx}')
        return None

    colors = OrderedDict([(m, COLORMAP.colors[i])
                          for i, m in enumerate(motifs)])
    raster = motifRaster(sortedRecs, motifs, colors)
    patches = [
        mpatches.Patch(color=color, label=motif)
        for motif, color in list(colors.items())
    ]
    f, ax = plotWaterfall(raster, XLABEL, args.ylabel, labels=patches)

    out = args.out if args.out.endswith(
        args.format) else '%s.%s' % (args.out, args.format)
    plt.tight_layout()
    f.savefig(out, dpi=args.dpi, format=args.format)

    if args.plotQV:
        qvraster = qvRaster(sortedRecs, 'Base QV')
        norm = TwoSlopeNorm(CENTERQV, vmin=MINQV, vmax=MAXQV)
        f, ax = plotWaterfall(qvraster,
                              XLABEL,
                              args.ylabel,
                              norm=norm,
                              cmap=QVCOLOR,
                              colorbar='QV')
        name, ext = out.rsplit('.', 1)
        f.savefig(f'{name}.QV.{ext}', format=args.format)

    print('Done')
    return raster
Example #17
0
def irrigated_change_by_county(json_file):
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    import matplotlib

    from matplotlib.colors import TwoSlopeNorm

    unet = prepare_unet_from_json(json_file, 50)
    unet = unet.drop([2002], axis=1)
    unet = unet.T.groupby(np.arange(len(unet.T)) // 5).mean()
    # unet = unet.T.rolling(5).mean()
    u2019 = unet.iloc[-1]
    u2000 = unet.iloc[0]
    diff = u2019 - u2000
    r = '/home/thomas/share/irrigated-training-data-aug21/aux-shapefiles/MontanaCounties_shp/County.shp'
    gdf = gpd.read_file(r)
    gdf['NAME'] = [n.replace(' ', '_') for n in gdf['NAME']]
    diff = diff.loc[gdf['NAME']]
    gdf['diff'] = diff.values

    fig, ax = plt.subplots(1, 1)
    divider = make_axes_locatable(ax)
    vmin, vmax, vcenter = gdf['diff'].min(), gdf['diff'].max(), 0
    norm = TwoSlopeNorm(vmin=vmin, vcenter=vcenter, vmax=vmax)
    cmap = 'coolwarm'
    cbar = plt.cm.ScalarMappable(norm=norm, cmap=cmap)
    cax = divider.append_axes("left", size="5%", pad=0.1)
    gdf.plot(column='diff', ax=ax, cmap='coolwarm')
    cbar = fig.colorbar(cbar, ax=ax, cax=cax)
    cbar.outline.set_visible(False)
    ax.axis('off')
    ax.set_title('Change in irrigated area by county, 2000-2019', fontsize=20)
    fig.text(0.13,
             0.35,
             r'$\Delta$ irrigated area (acres)',
             ha='center',
             rotation='vertical',
             fontsize=20)
    plt.show()
def gravity_wave_drag(cubes, time=-1, level=47):

    for cube in cubes:
        if cube.long_name == 'change_over_time_in_air_temperature_due_to_gravity_wave_drag':
            drag = cube.copy()

    heights = np.round(drag.coord('level_height').points * 1e-03, 0)
    run_length = np.arange(0, drag.shape[0])
    # longitudes = drag.shape[3]
    # latitudes = drag.coord('latitude').points

    plt.figure(figsize=(12, 6))
    iplt.contour(drag[time, level, :, :],
                 brewer_redblu.N,
                 cmap=brewer_redblu,
                 norm=TwoSlopeNorm(0))
    ax = plt.gca()
    ax.gridlines(draw_labels=True)
    plt.title('Temp change due to gravity wave drag [K], month %s, h=%s km' %
              (run_length[time], heights[level]),
              y=1.2)
    plt.colorbar(pad=0.1)
    plt.show()
Example #19
0
def plot_hovmoellerx(cubes, radius=7160000, time='days'):
    """ Plot Hovmoeller diagrams of zonal wind 
        Arguments: CubeList, time (can be '6-hours' or 'days')
        Outputs: 1) Hovmoeller plot of mean equatorial wind between -10 and 10 
                lat, axes time vs. height
                 2) Hovmoeller plot of zonal mean wind at 40 km, axes time vs. 
                latitude (top view) """

    for cube in cubes:
        if cube.standard_name == 'eastward_wind' or cube.standard_name == 'x_wind':
            x_wind = cube.copy()

    x_wind.coord('latitude').coord_system = GeogCS(radius)
    x_wind.coord('longitude').coord_system = GeogCS(radius)

    run_length, lats, longs = x_wind.shape[0], x_wind.coord(
        'latitude'), x_wind.coord('longitude')

    for coord in x_wind.coords():
        if coord.long_name == 'Hybrid height':
            heights = np.round(x_wind.coord('Hybrid height').points * 1e-03, 0)
        elif coord.long_name == 'level_height':
            heights = np.round(x_wind.coord('level_height').points * 1e-03, 0)

    if lats.bounds == None:
        x_wind.coord('latitude').guess_bounds()
    if longs.bounds == None:
        x_wind.coord('longitude').guess_bounds()

    dayside, nightside = x_wind.intersection(
        longitude=(-90, 89),
        latitude=(-10, 10)), x_wind.intersection(longitude=(90, 270),
                                                 latitude=(-10, 10))
    dayside_full, nightside_full = x_wind.intersection(
        longitude=(-90, 89)), x_wind.intersection(longitude=(90, 270))
    day_grid, night_grid = iris.analysis.cartography.area_weights(
        dayside), iris.analysis.cartography.area_weights(nightside)

    dayside_mean = dayside.collapsed(['latitude', 'longitude'],
                                     iris.analysis.MEAN,
                                     weights=day_grid)
    nightside_mean = nightside.collapsed(['latitude', 'longitude'],
                                         iris.analysis.MEAN,
                                         weights=night_grid)

    dayside_zonal_mean = dayside_full.collapsed('longitude',
                                                iris.analysis.MEAN)
    nightside_zonal_mean = nightside_full.collapsed('longitude',
                                                    iris.analysis.MEAN)

    for cube in (dayside_mean, nightside_mean):
        if cube == dayside_mean:
            side = 'Dayside'
        else:
            side = 'Nightside'
        plt.contourf(np.arange(0, run_length) * 0.25,
                     np.array(heights),
                     cube.data.T,
                     levels=np.arange(-120, 121, 20),
                     cmap=brewer_redblu,
                     norm=TwoSlopeNorm(0))
        plt.title('%s Mean Zonal Equatorial Wind' % (side))
        plt.xlabel('Time [%s]' % (time))
        plt.ylabel('Height [km]')
        cbar = plt.colorbar(pad=0.1)
        cbar.set_ticks(np.arange(-120, 121, 20))
        cbar.ax.set_title('m/s')
        # plt.savefig('/exports/csce/datastore/geos/users/s1144983/papers/laso/epsfigs/hovmoeller_%s_new.eps' %(side), format='eps')
        plt.show()

    for cube in (dayside_zonal_mean, nightside_zonal_mean):
        if cube == dayside_zonal_mean:
            side = 'Dayside'
        else:
            side = 'Nightside'
        plt.contourf(np.arange(0, run_length) * 0.25,
                     np.arange(-45, 45),
                     cube[:, 47, :].data.T,
                     np.arange(-120, 121, 20),
                     cmap=brewer_redblu,
                     norm=TwoSlopeNorm(0))
        plt.title('%s Mean Zonal Wind at 41 km' % (side))
        plt.xlabel('Time [%s]' % (time))
        plt.ylabel('Latitude')
        plt.yticks((-45, 0, 45), ('90S', '0', '90N'))
        mbar = plt.colorbar(pad=0.1)
        mbar.set_ticks(np.arange(-120, 121, 20))
        mbar.ax.set_title('m/s')
        # plt.savefig('/exports/csce/datastore/geos/users/s1144983/papers/laso/epsfigs/topview_%s_new.eps' %(side), format='eps')
        plt.show()
Example #20
0
def wave_acceleration(cubes,
                      density,
                      hlevel=47,
                      lat=45,
                      long=0,
                      start=2880,
                      end=3240,
                      plot=False):
    """ This function plots several things:
        1) The high-pass filtered u-prime. We need to filter u-prime because
    the standing Rossby waves create an asymmetrical background flow. Taking
    the zonal anomaly without filtering out long Rossby waves results in a 
    zonal anomaly that represents these waves instead of the transient gravity
    waves we're looking for. We filter out wavelengths of wave number < 5.1.
        2) The time anomaly of the upward wind, w'. We use the time anomaly
    instead of zonal anomaly because the asymmetrical dayside/nightside 
    rising/subsiding air pattern creates the same problem as the standing 
    Rossby waves do for the zonal wind.
        3) The wave momentum flux, calculated by multiplying 1) and 2) and
    differentiating in the vertical direction. We plot the latitudinal 
    cross-section of the zonal mean wave momentum flux together with the change
    in zonal mean zonal wind to see if the direction of acceleration matches the
    change in direction of the zonal wind. We also plot the longitudinal 
    cross-section along the equator (not the meridional mean, just a slice) and
    overlay the longitudinal cross-section of the zonal wind to show that the
    areas of high wave-induced acceleration are collocated with the jet exit region
    at the western terminator and the deep convection zone to the west of the 
    substellar point.
    
    Note: The wave-induced acceleration is calculated ONLY for the resolved,
    larger-than-gridbox gravity waves and does not include the acceleration
    from parameterised gravity waves.
    
    You must use the six-hourly data with this function.
    
    Paper plot time spans: 2880-3240 and 3340-3680"""

    for cube in cubes:
        if cube.standard_name == 'eastward_wind':
            x_wind = cube[start:end, :, :, :].copy()
        if cube.standard_name == 'upward_air_velocity':
            z_wind = cube[start:end, :, :, :].copy()

    z_wind = z_wind.regrid(x_wind, iris.analysis.Linear())

    vertical = [('Hybrid height', x_wind.coord('Hybrid height').points)]
    z_wind = z_wind.interpolate(vertical, iris.analysis.Linear())

    longitudes = x_wind.shape[3] / 2
    latitudes = x_wind.shape[2] / 2
    heights = x_wind.coord('Hybrid height').points
    heights_km = np.round(x_wind.coord('Hybrid height').points * 1e-03, 0)
    """ Filter zonal wind, remove longer wavelengths, calculate u-prime"""

    x_data = x_wind.data

    u_prime_list = []

    for time in range(0, x_wind.shape[0]):
        time_list = []

        for level in range(0, x_wind.shape[1]):
            level_list = []

            for latx in range(0, x_wind.shape[2]):

                u_fft = sp.fftpack.fft(x_data[time, level, latx, :])
                u_psd = np.abs(u_fft)**2
                u_freq = sp.fftpack.fftfreq(len(u_psd), 1. / 144)

                highpass = u_fft.copy()
                highpass[np.abs(u_freq) < 5.1] = 0

                u_cleaned = np.real(sp.fftpack.ifft(highpass))
                u_bar = np.mean(u_cleaned)
                u_prime = u_cleaned - u_bar
                level_list.append(u_prime)

            time_list.append(level_list)
        u_prime_list.append(time_list)

    u_prime = np.array(u_prime_list)
    print(u_prime.shape)

    if plot == True:

        zonal_mean = x_wind.collapsed('longitude', iris.analysis.MEAN)

        fig, (ax1, ax2) = plt.subplots(1,
                                       2,
                                       figsize=(16, 8),
                                       gridspec_kw={'width_ratios': [4, 1]},
                                       sharey=True)
        up = ax1.contourf(np.arange(-longitudes, longitudes),
                          np.array(heights_km),
                          np.roll(u_prime[-1, :, lat, :], 72, axis=1),
                          np.linspace(-35, 35, 70),
                          cmap=brewer_redblu,
                          norm=TwoSlopeNorm(0))
        ax1.set_title('$U^{\prime}$ at Equator, t=%s days' % (end / 4))
        ax1.set_xlabel('Longitude [degrees]')
        ax1.set_xticks((-72, -48, -24, 0, 24, 48, 72),
                       ('180W', '120W', '60W', '0', '60E', '120E', '180E'))
        ax1.set_ylabel('Height [km]')
        # ax1.annotate('', xy=(0.177, 0.55), xytext=(0.11, 0.55), xycoords='figure fraction', arrowprops=dict(facecolor='black',shrink=0.005),
        #              horizontalalignment='left', verticalalignment='top')
        cbar = plt.colorbar(up, pad=0.05, ax=ax1)
        cbar.locator = ticker.AutoLocator()
        cbar.update_ticks()
        cbar.ax.set_title('m/s')

        # plt.figure(figsize=(10, 5))
        # plt.contourf(np.arange(-longitudes, longitudes), np.array(heights_km), np.roll(
        #     u_prime[-1, :, lat, :], 72, axis=1), np.linspace(-35, 35, 70), cmap=brewer_redblu, norm=TwoSlopeNorm(0))
        # plt.title('$U^{\prime}$ at Equator, t=%s days' % (end/4))
        # plt.xlabel('Longitude [degrees]')
        # plt.xticks((-72, -60, -48, -36, -24, -12, 0, 12, 24, 36, 48, 60, 72), ('180W', '150W',
        #            '120W', '90W', '60W', '30W', '0', '30E', '60E', '90E', '120E', '150E', '180E'))
        # plt.ylabel('Height [km]')
        # cbar = plt.colorbar(pad=0.1)
        # cbar.locator = ticker.AutoLocator()
        # cbar.update_ticks()
        # cbar.ax.set_title('m/s')

        # # plt.savefig(
        #     # '/exports/csce/datastore/geos/users/s1144983/papers/laso/epsfigs/uprime_%s_ticks.eps' % (end), format='eps')
        # plt.show()

        # plt.figure(figsize=(2.5, 5))
        zmzw = ax2.contour(np.arange(-latitudes, latitudes) * 2,
                           np.array(heights_km),
                           zonal_mean[-1, :, :].data,
                           np.arange(-80, 81, 20),
                           colors='black',
                           linewidths=2.0)
        ax2.set_title('Zonal Mean Zonal Wind, t=%s days' % (end / 4))
        ax2.set_xlabel('Latitude [degrees]')
        # ax2.set_ylabel('Height [km]')
        ax2.clabel(zmzw, inline=False, colors='k', fmt='%1.1f')
        fig.tight_layout()
        # fig.suptitle('$U^{\prime}$ at Equator and Zonal Mean Zonal Wind, t=%s days' %(end/4), fontsize=18)

        # plt.savefig(
        # '/exports/csce/datastore/geos/users/s1144983/papers/laso/epsfigs/uprime_subplots_%s_right.eps' % (end), format='eps')

        plt.show()
    """ Calculate w-prime"""

    z_mean = z_wind.collapsed('t', iris.analysis.MEAN)
    z_anomaly = z_wind - z_mean

    if plot == True:

        plt.figure(figsize=(10, 5))
        plt.contourf(np.arange(-longitudes, longitudes),
                     np.array(heights_km),
                     np.roll(z_anomaly[-1, :, lat, :].data, 72, axis=1),
                     np.linspace(-0.09, 0.09, 20),
                     cmap=brewer_redblu,
                     norm=TwoSlopeNorm(0))
        plt.title('Vertical Wind Anomaly at Equator [m s-1], t = %s days' %
                  (end / 4))
        plt.xlabel('Longitude [degrees]')
        plt.xticks((-72, -60, -48, -36, -24, -12, 0, 12, 24, 36, 48, 60, 72),
                   ('180W', '150W', '120W', '90W', '60W', '30W', '0', '30E',
                    '60E', '90E', '120E', '150E', '180E'))
        plt.ylabel('Height [km]')
        plt.colorbar(pad=0.1)
        plt.show()
    """ Differentiate wrt height"""

    array = u_prime * z_anomaly.data

    h = np.array([heights])
    h = np.repeat(h[:, np.newaxis], (end - start), axis=0)
    h = np.reshape(h, ((end - start), 60))
    h = np.repeat(h[:, :, np.newaxis], 90, axis=2)
    h = np.repeat(h[:, :, :, np.newaxis], 144, axis=3)

    print(array.shape, h.shape)

    acceleration = array.copy() * density[start:end, :-1, :, :]
    acceleration[:, 0,
                 ...] = (array[:, 1, ...] - array[:, 0, ...]) / (h[:, 1, ...] -
                                                                 h[:, 0, ...])
    acceleration[:, -1,
                 ...] = (array[:, -1, ...] -
                         array[:, -2, ...]) / (h[:, -1, ...] - h[:, -2, ...])
    acceleration[:, 1:-1, ...] = (array[:, 2:, ...] - array[:, 0:-2, ...]) / (
        h[:, 2:, ...] - h[:, 0:-2, ...])
    acceleration = -acceleration
    # Negative because Plumb 1977 paper formula has a negative, just so you don't forget this and freak out
    """ Plot """
    zonal_acc = np.mean(acceleration, axis=3)
    net_acc = np.mean(zonal_acc, axis=0)

    x_mean = x_wind.collapsed('longitude', iris.analysis.MEAN)
    x_avg = x_wind.collapsed('t', iris.analysis.MEAN)
    mean_acc = np.mean(acceleration, axis=0)

    plt.figure(figsize=(10, 5))
    plt.contourf(np.arange(-longitudes, longitudes),
                 np.array(heights_km),
                 np.roll(mean_acc[:, lat, :], 72, axis=1),
                 np.linspace(-8e-05, 8e-05, 20),
                 cmap=brewer_redblu,
                 norm=TwoSlopeNorm(0))
    mbar = plt.colorbar(pad=0.1)
    mbar.locator = ticker.AutoLocator()
    mbar.update_ticks()
    mbar.set_label('$m/s^2$')
    contours = plt.contour(np.arange(-longitudes, longitudes),
                           np.array(heights_km),
                           np.roll(x_avg[:, lat, :].data, 72, axis=1),
                           np.arange(-80, 81, 20),
                           colors='black',
                           linewidths=0.3)
    plt.title('Mean Wave-Induced Acceleration at Equator, t=%s to %s days' %
              (start / 4, end / 4))
    plt.xlabel('Longitude [degrees]')
    plt.xticks((-72, -60, -48, -36, -24, -12, 0, 12, 24, 36, 48, 60, 72),
               ('180W', '150W', '120W', '90W', '60W', '30W', '0', '30E', '60E',
                '90E', '120E', '150E', '180E'))
    plt.ylabel('Height [km]')
    plt.clabel(contours, inline=False, colors='k', fmt='%1.1f')
    # plt.savefig('/exports/csce/datastore/geos/users/s1144983/papers/laso/epsfigs/jetexit_%s_ticks_by20s.eps' %(end), format='eps')
    plt.show()

    x_axis = x_wind.coord('latitude').points
    y_axis = np.round(x_wind.coord('Hybrid height').points * 1e-03, 0)
    plt.figure(figsize=(8, 10))
    plt.contourf(x_axis,
                 y_axis,
                 net_acc,
                 brewer_redblu.N,
                 cmap=brewer_redblu,
                 norm=TwoSlopeNorm(0))
    wbar = plt.colorbar(pad=0.1)
    wbar.locator = ticker.AutoLocator()
    wbar.update_ticks()
    wbar.set_label('$m/s^2$', rotation=90)
    CS = plt.contour(x_axis,
                     y_axis, (x_mean[-1, :, :].data - x_mean[0, :, :].data),
                     colors='black',
                     linewidths=1.5)
    plt.title('Mean Zonal Mean Wave-Induced Acceleration, t=%s to %s days' %
              (start / 4, end / 4))
    plt.xlabel('Latitude [degrees]')
    plt.ylabel('Height [km]')
    plt.clabel(CS, inline=False, colors='k', fmt='%1.1f')
    # plt.savefig('/exports/csce/datastore/geos/users/s1144983/papers/laso/epsfigs/waveinducedacc_%s_ticks.eps' %(end), format='eps')
    plt.show()

    zonal_acc_day = np.mean(zonal_acc[-4:-1, :, :], axis=0)
    latmean = np.mean(zonal_acc_day[:, 40:51], axis=1)
    latwind = x_mean[-4:-1, :, 40:51].collapsed(['latitude', 't'],
                                                iris.analysis.MEAN)

    fig, ax1 = plt.subplots(figsize=(8, 10))
    ax1.set_xlabel('Acceleration [m/s$^2$]')
    ax1.set_ylabel('Height [km]')
    ax1.plot(latmean, y_axis, color='b', label='Acc')
    ax1.tick_params(axis='x', labelcolor='b')

    ax2 = ax1.twiny()
    ax2.set_xlabel('Zonal mean equatorial wind [m/s]')
    ax2.plot(latwind.data, y_axis, color='r', label='Wind')
    ax2.tick_params(axis='x', labelcolor='r')

    plt.title(
        'Mean Zonal Mean Equatorial Wave-Induced Acceleration, t=%s to %s days'
        % (start / 4, end / 4))
    # fig.tight_layout()
    plt.show()
Example #21
0
data = f[1].data

print(type(data))
print(data.shape)
print(data.dtype.name)
print("\nMin:", np.min(data))
print("\nMax:", np.max(data))
print("\nMean:", np.mean(data))
print("\nStd:", np.std(data))

from matplotlib.colors import TwoSlopeNorm

x_ticks = ['-10', '-5', '0', '5', '10']
y_ticks = ['-10', '-5', '0', '5', '10']
t11 = [0, 175, 350, 525, 699]

plt.xticks(ticks=t11, labels=x_ticks, size=7)
plt.yticks(ticks=t11, labels=y_ticks, size=7)

norm = TwoSlopeNorm(vmin=data.min(), vcenter=0, vmax=data.max())
pc = plt.pcolormesh(data, norm=norm, cmap="seismic")
plt.imshow(data, cmap='seismic')
#plt.colorbar(pc)
cbar = plt.colorbar()
for t in cbar.ax.get_yticklabels():
    t.set_fontsize(7)
plt.xlabel("degrees", fontsize=8)
plt.ylabel("degrees", fontsize=8)
#plt.title("MILCA y map of Coma",fontsize=8)
plt.savefig("../images/figure 1.png", dpi=600)
plt.show()
Example #22
0
def meridional_wind(cubes, n=3, time_slice=-1, level=38):

    for cube in cubes:
        if cube.standard_name == 'y_wind':
            y_wind = cube.copy()
        if cube.standard_name == 'air_pressure':
            pressure = cube.copy()

    height = [('level_height', y_wind.coord('level_height').points)]
    pressure = pressure.interpolate(height, iris.analysis.Linear())
    # Regrid so that all three cubes are on the same x, y, z grid. Uses the x_wind as reference for the others

    p_heights = np.round(pressure.data * 1e-05, 4)
    km_heights = np.round(pressure.coord('level_height').points * 1e-03, 1)
    # For labelling the quiver plot

    mean_y = y_wind[time_slice, :, :, :].collapsed('longitude',
                                                   iris.analysis.MEAN)
    y_prime = y_wind - mean_y
    # Zonal mean meridional winds

    y_wind = y_wind[time_slice, level, :, :].data
    x_wind = np.zeros_like(y_wind)

    X, Y = np.meshgrid(np.arange(-72, 72), np.arange(-45, 46))
    fig1, ax1 = plt.subplots(figsize=(10, 5))
    q1 = ax1.quiver(X[::n, ::n],
                    Y[::n, ::n],
                    np.roll(x_wind[::n, ::n], 72, axis=1),
                    np.roll(y_wind[::n, ::n], 72, axis=1),
                    angles='xy',
                    scale_units='xy',
                    scale=3)
    # Create a quiver plot. The np.roll function moves the cube data so the substellar point is centred.
    ax1.quiverkey(q1,
                  X=0.9,
                  Y=1.05,
                  U=3,
                  label='3 m/s',
                  labelpos='E',
                  coordinates='axes')
    # This creates the key with the arrow size. The value of U, the label string, and the value of scale in the previous line should all match.
    plt.title('Meridional wind vectors [m s-1], h=%s bar, %s km' %
              (p_heights[time_slice, level, 0, 0], km_heights[level]))
    plt.xlabel('Longitude')
    plt.ylabel('Latitude')
    plt.xticks((-72, -60, -48, -36, -24, -12, 0, 12, 24, 36, 48, 60, 72),
               ('180W', '150W', '120W', '90W', '60W', '30W', '0', '30E', '60E',
                '90E', '120E', '150E', '180E'))
    plt.yticks((-45, -30, -15, 0, 15, 30, 45),
               ('90S', '60S', '30S', '0', '30N', '60N', '90N'))
    # Labelled the longs and lats manually
    plt.show()

    CS = iplt.contourf(mean_y,
                       brewer_redblu.N,
                       cmap=brewer_redblu,
                       norm=TwoSlopeNorm(0))
    plt.title('Zonal Mean Meridional Wind [m s-1]', y=1.05)
    plt.ylabel('Height [m]')
    plt.xlabel('Latitude [degrees]')
    plt.clabel(CS, inline=False, colors='k', fmt='%1.1f')
    plt.colorbar(pad=0.1)
    plt.show()
Example #23
0
def plot_uw(cubes, start=0, end=120, lat=45, levels=(37, 44, 47, 53)):

    for cube in cubes:
        if cube.standard_name == 'eastward_wind' or cube.standard_name == 'x_wind':
            x_wind = cube[start:end, :, :, :].copy()
        if cube.standard_name == 'northward_wind' or cube.standard_name == 'y_wind':
            y_wind = cube[start:end, :, :, :].copy()
        if cube.standard_name == 'upward_air_velocity':
            z_wind = cube[start:end, :, :, :].copy()

    run_length, longitudes, latitudes = x_wind.shape[
        0], x_wind.shape[3] / 2, x_wind.shape[2] / 2

    y_wind, z_wind = y_wind.regrid(x_wind,
                                   iris.analysis.Linear()), z_wind.regrid(
                                       x_wind, iris.analysis.Linear())

    for coord in x_wind.coords():
        if coord.long_name == 'Hybrid height':
            heights = np.round(x_wind.coord('Hybrid height').points * 1e-03, 0)
            vertical = [('Hybrid height', x_wind.coord('Hybrid height').points)
                        ]
        elif coord.long_name == 'level_height':
            heights = np.round(x_wind.coord('level_height').points * 1e-03, 0)
            vertical = [('level_height', x_wind.coord('level_height').points)]

    z_wind = z_wind.interpolate(vertical, iris.analysis.Linear())

    zonal_mean_u = x_wind.collapsed('t', iris.analysis.MEAN)
    u_prime = x_wind - zonal_mean_u
    zonal_mean_w = z_wind.collapsed('t', iris.analysis.MEAN)
    w_prime = z_wind - zonal_mean_w
    cross_term = u_prime * w_prime

    for level in levels:

        plt.figure(figsize=(10, 5))
        plt.contourf(np.arange(-longitudes, longitudes),
                     np.arange(0, run_length),
                     np.roll(cross_term[:, level, lat, :].data, 72, axis=1),
                     brewer_redblu.N,
                     cmap=brewer_redblu,
                     norm=TwoSlopeNorm(0))
        plt.title(
            '$U^{\prime} \cdot W^{\prime}$ at Equator [m2 s-2], h=%s km, %s to %s days'
            % (heights[level], start / 4, end / 4))
        plt.xlabel('Longitude [degrees]')
        plt.xticks((-72, -60, -48, -36, -24, -12, 0, 12, 24, 36, 48, 60, 72),
                   ('180W', '150W', '120W', '90W', '60W', '30W', '0', '30E',
                    '60E', '90E', '120E', '150E', '180E'))
        plt.ylabel('Time [6-hours]')
        plt.colorbar(pad=0.1)
        plt.show()

        plt.figure(figsize=(10, 5))
        plt.contourf(np.arange(-longitudes, longitudes),
                     np.arange(-latitudes, latitudes),
                     np.roll(cross_term[-1, level, :, :].data, 72, axis=1),
                     brewer_redblu.N,
                     cmap=brewer_redblu,
                     norm=TwoSlopeNorm(0))
        plt.title('$U^{\prime} \cdot W^{\prime}$ [m2 s-2], h=%s km, day=%s' %
                  (heights[level], end / 4))
        plt.xlabel('Longitude [degrees]')
        plt.xticks((-72, -60, -48, -36, -24, -12, 0, 12, 24, 36, 48, 60, 72),
                   ('180W', '150W', '120W', '90W', '60W', '30W', '0', '30E',
                    '60E', '90E', '120E', '150E', '180E'))
        plt.ylabel('Latitude [degrees]')
        plt.colorbar(pad=0.1)
        plt.show()
def NDVI():

    data_path = file_path
    bands_grep = re.compile(".*_(B4|B5)\.(tif|TIF)")

    file_list = glob.glob(data_path + '\*.TIF')
    print(file_list)

    # Filter and keep only useful files (bands 4 and 5 to compute NDVI)
    bands = filter(lambda x: bands_grep.search(x), file_list)
    bands = [s for s in bands]

    #Open and read files
    with rasterio.open(bands[0]) as src:
        b4 = src.read(1).astype('float64')

    with rasterio.open(bands[1]) as src:
        b5 = src.read(1).astype('float64')

    # Allow division by zero
    np.seterr(divide='ignore', invalid='ignore')

    # Calculate NDVI
    ndvi = (b5.astype(float) - b4.astype(float)) / (b4 + b5)

    #No data values
    ndvi = np.where((b5.astype(float) - b4.astype(float)) / (b4 + b5) == 0, 0,
                    (b5.astype(float) - b4.astype(float)) / (b4 + b5))

    # Define spatial characteristics of output object (basically they are analog to the input)
    kwargs = src.meta

    # Update kwargs (change in data type)
    kwargs.update(dtype=rasterio.float64, count=1)

    with rasterio.open(output_path + '/NDVI.tif', 'w', **kwargs) as dst:
        dst.write_band(1, ndvi.astype(rasterio.float64))

    src = rasterio.open(output_path + '/NDVI.tif')

    # Render with colormap and colorbar
    z = np.linspace(-1, 1, 50 * 50)

    norm = TwoSlopeNorm(vmin=z.min(), vcenter=0, vmax=z.max())
    pc = plt.imshow(src.read(1).astype('float64'), norm=norm, cmap='RdBu_r')
    plt.colorbar(pc)

    plt.show()

    # geotiff kaydetme
    naip_data_path = output_path + '/NDVI.tif'

    with rasterio.open(naip_data_path) as src:
        naip_data = src.read()
        naip_meta = src.profile

    naip_transform = naip_meta["transform"]
    naip_crs = naip_meta["crs"]

    w, h = ndvi.shape

    customized_cmap = {}
    a = float(255 / 2)

    print(a)
    print(customized_cmap)

    for s in range(-1, 2):
        s = s * (255 / 2)
        print(s)

    a = 0
    b = 255
    for s in range(0, 256):
        s_color = (a, 0, b, 0)
        customized_cmap[s] = s_color
        a += 1
        b -= 1

    print(customized_cmap)

    ndvi = cv2.normalize(ndvi,
                         None,
                         alpha=0,
                         beta=255,
                         norm_type=cv2.NORM_MINMAX,
                         dtype=cv2.CV_32F)

    with rasterio.open((output_path + '/NDVI.tif'),
                       'w',
                       driver='GTiff',
                       width=w,
                       height=h,
                       count=1,
                       dtype=rasterio.uint8,
                       crs=naip_crs,
                       transform=naip_transform) as dst:
        dst.write(ndvi.astype(rasterio.uint8), indexes=1)
        dst.write_colormap(1, customized_cmap)
Example #25
0
def wave_acceleration(cubes, lat=45, long=0, start=0, end=240):

    for cube in cubes:
        if cube.standard_name == 'eastward_wind':
            x_wind = cube[start:end, :, :, :].copy()
        if cube.standard_name == 'northward_wind':
            y_wind = cube[start:end, :, :, :].copy()
        if cube.standard_name == 'upward_air_velocity':
            z_wind = cube[start:end, :, :, :].copy()
        if cube.standard_name == 'air_pressure':
            pressure = cube[start:end, :, :, :].copy()

    y_wind = y_wind.regrid(x_wind, iris.analysis.Linear())
    z_wind = z_wind.regrid(x_wind, iris.analysis.Linear())
    z_wind = -1 * z_wind
    pressure = pressure.regrid(x_wind, iris.analysis.Linear())

    heights = pressure.coord('Hybrid height').points

    height = [('Hybrid height', pressure.coord('Hybrid height').points)]
    x_wind, y_wind = x_wind.interpolate(
        height,
        iris.analysis.Linear()), y_wind.interpolate(height,
                                                    iris.analysis.Linear())

    longitudes = x_wind.shape[3] / 2
    # x_zonal_mean = x_wind.collapsed('longitude', iris.analysis.MEAN)
    # avg_zonal_mean = x_zonal_mean.collapsed('t', iris.analysis.MEAN)

    x_mean = x_wind.collapsed('t', iris.analysis.MEAN)
    z_mean = z_wind.collapsed('t', iris.analysis.MEAN)

    x_anomaly = x_wind - x_mean
    z_anomaly = z_wind - z_mean

    result = x_wind.copy()
    result.data = x_anomaly.data * z_anomaly.data
    array = result.data
    # h = np.log(pressure.data)
    h = np.array([heights])
    h = np.repeat(h[:, np.newaxis], (end - start), axis=0)
    h = np.reshape(h, ((end - start), 61))
    h = np.repeat(h[:, :, np.newaxis], 90, axis=2)
    h = np.repeat(h[:, :, :, np.newaxis], 144, axis=3)

    print(h.shape)

    acceleration = array.copy()
    acceleration[:, 0,
                 ...] = (array[:, 1, ...] - array[:, 0, ...]) / (h[:, 1, ...] -
                                                                 h[:, 0, ...])
    acceleration[:, -1,
                 ...] = (array[:, -1, ...] -
                         array[:, -2, ...]) / (h[:, -1, ...] - h[:, -2, ...])
    acceleration[:, 1:-1, ...] = (array[:, 2:, ...] - array[:, 0:-2, ...]) / (
        h[:, 2:, ...] - h[:, 0:-2, ...])

    # acceleration = array.copy()
    # acceleration[:,0,...] = (array[:,1,...]-array[:,0,...])/(h[1]-h[0])
    # acceleration[:,-1,...] = (array[:,-1,...]-array[:,-2,...])/(h[-1]-h[-2])
    # acceleration[:,1:-1,...] = (array[:,2:,...]-array[:,0:-2,...])/(h[2:]-h[0:-2])

    # zonal_acc = np.mean(acceleration, axis=3)
    # net_acc = np.sum(acceleration, axis=3)
    # net_acc_total = np.mean(zonal_acc, axis=0)

    substellar = acceleration[:, :, 31:59:, long]
    net_acc = np.mean(substellar, axis=0)  # + x_wind[start,:,31:59,long].data

    plt.figure(figsize=(10, 5))
    plt.contourf(np.arange(-longitudes, longitudes),
                 np.array(heights),
                 np.roll(x_anomaly[end - start - 1, :, lat, :].data,
                         72,
                         axis=1),
                 brewer_redblu.N,
                 cmap=brewer_redblu,
                 norm=TwoSlopeNorm(0))
    plt.title('Zonal Wind Anomaly at Equator [m s-1], t = %s days' % (end / 4))
    plt.xlabel('Longitude [degrees]')
    plt.xticks((-72, -60, -48, -36, -24, -12, 0, 12, 24, 36, 48, 60, 72),
               ('180W', '150W', '120W', '90W', '60W', '30W', '0', '30E', '60E',
                '90E', '120E', '150E', '180E'))
    plt.ylabel('Height [m]')
    plt.colorbar(pad=0.1)
    plt.show()

    plt.figure(figsize=(10, 5))
    plt.contourf(np.arange(-longitudes, longitudes),
                 np.array(heights),
                 np.roll(z_anomaly[end - start - 1, :, lat, :].data,
                         72,
                         axis=1),
                 np.linspace(-0.05, 0.05, 20),
                 cmap=brewer_redblu,
                 norm=TwoSlopeNorm(0))
    plt.title('Vertical Wind Anomaly at Equator [m s-1], t = %s days' %
              (end / 4))
    plt.xlabel('Longitude [degrees]')
    plt.xticks((-72, -60, -48, -36, -24, -12, 0, 12, 24, 36, 48, 60, 72),
               ('180W', '150W', '120W', '90W', '60W', '30W', '0', '30E', '60E',
                '90E', '120E', '150E', '180E'))
    plt.ylabel('Height [m]')
    plt.colorbar(pad=0.1)
    plt.show()

    plt.figure(figsize=(10, 5))
    plt.contourf(np.arange(-longitudes, longitudes),
                 np.array(heights),
                 np.roll(acceleration[end - start - 1, :, lat, :], 72, axis=1),
                 np.linspace(-0.0024, 0.0024, 20),
                 cmap=brewer_redblu,
                 norm=TwoSlopeNorm(0))
    plt.title('Wave-Induced Acceleration at Equator [m s-2], t = %s days' %
              (end / 4))
    plt.xlabel('Longitude [degrees]')
    plt.xticks((-72, -60, -48, -36, -24, -12, 0, 12, 24, 36, 48, 60, 72),
               ('180W', '150W', '120W', '90W', '60W', '30W', '0', '30E', '60E',
                '90E', '120E', '150E', '180E'))
    plt.ylabel('Height [m]')
    plt.colorbar(pad=0.1)
    plt.show()

    x_axis = pressure.coord('latitude').points
    y_axis = pressure.coord('Hybrid height').points
    plt.figure(figsize=(6, 10))
    plt.contourf(x_axis[31:59],
                 y_axis,
                 net_acc,
                 brewer_redblu.N,
                 cmap=brewer_redblu,
                 norm=TwoSlopeNorm(0))
    plt.colorbar(pad=0.1)
    CS = plt.contour(x_axis[31:59],
                     y_axis,
                     x_anomaly[end - start - 1, :, 31:59, long].data,
                     colors='black',
                     linewidths=0.5)
    plt.title('Mean acceleration at long %s from day=%s to %s' %
              (long * 2.5, start / 4, end / 4))
    plt.xlabel('Latitude [degrees]')
    plt.ylabel('Height [m]')
    plt.clabel(CS, inline=False, colors='k', fmt='%1.1f')
    plt.show()
            # For each laguerre filter
            for j1 in range(L):
                for j2 in range(L):
                    sum_filters += W[h][j1] * W[h][j2] * laguerre_bank[j1, m1] * laguerre_bank[j2, m2]
            
            sum_units += C[h, 1] * sum_filters
        
        kernel_2[m1, m2] = sum_units
        
print("[2nd order Volterra kernel]")    
print(kernel_2)

fig = plt.figure(figsize=(10,10))

# 3D plot
# ax = fig.gca(projection='3d')
# x = y = np.arange(0, memory, 1)
# X, Y = np.meshgrid(x, y)
# ax.plot_surface(X, Y, kernel_2, cmap='inferno', antialiased=False, alpha=0.27)
# # Customize the z axis.
# ax.set_zlim(-1.01, 1.01)
# ax.zaxis.set_major_locator(LinearLocator(10))
# ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

# Heatmap plot
norm = TwoSlopeNorm(vmin=kernel_2.min(), vmax = kernel_2.max(), vcenter=0)
plt.imshow(kernel_2, cmap='RdBu', interpolation='nearest', norm=norm)
plt.xticks(np.arange(0, memory, 1))
plt.yticks(np.arange(0, memory, 1))
plt.colorbar()
plt.show()
Example #27
0
def ep_flux(cubes, omega=0.64617667e-05, start=0, end=240):

    for cube in cubes:
        if cube.standard_name == 'air_potential_temperature':
            theta = cube[start:end, :, :, :].copy()
        if cube.standard_name == 'eastward_wind':
            x_wind = cube[start:end, :, :, :].copy()
        if cube.standard_name == 'northward_wind':
            y_wind = cube[start:end, :, :, :].copy()
        if cube.standard_name == 'air_pressure':
            pressure = cube[start:end, :, :, :].copy()

    heights, longitudes, longs = np.round(
        pressure.coord('Hybrid height').points * 1e-03,
        0), pressure.coord('longitude').points, pressure.shape[3] / 2

    y_wind, x_wind = y_wind.regrid(pressure,
                                   iris.analysis.Linear()), x_wind.regrid(
                                       pressure, iris.analysis.Linear())

    vertical = [('Hybrid height', pressure.coord('Hybrid height').points)]
    x_wind, y_wind = x_wind.interpolate(
        vertical,
        iris.analysis.Linear()), y_wind.interpolate(vertical,
                                                    iris.analysis.Linear())

    theta_data = theta.data
    x_wind_data = x_wind.data
    y_wind_data = y_wind.data
    pressure_data = pressure.data
    logpressure = np.log(pressure_data)

    theta_zonal_mean = theta.collapsed('t', iris.analysis.MEAN)
    theta_zonal_mean_data = theta_zonal_mean.data
    logpressure_zonal_mean = np.mean(logpressure, axis=2)
    pressure_zonal_mean = np.mean(pressure_data, axis=2)

    THETAp = ep_zderivative(theta_zonal_mean_data, logpressure_zonal_mean)
    THETAp /= pressure_zonal_mean

    # u_prime_lats = []

    # for level in range(0,61):
    #     u_prime_heights = []

    #     for lat in range(0,90):

    #         u_fft = sp.fftpack.fft(x_wind_data[level,lat,:])
    #         u_psd = np.abs(u_fft)**2
    #         u_freq = sp.fftpack.fftfreq(len(u_psd), 1./144)

    #         highpass = u_fft.copy()
    #         highpass[np.abs(u_freq) < 1.1] = 0

    #         u_cleaned = np.real(sp.fftpack.ifft(highpass))
    #         u_bar = np.mean(u_cleaned)
    #         u_prime = u_cleaned - u_bar

    #         u_prime_heights.append(u_prime)

    #     u_prime_lats.append(u_prime_heights)

    y_zonal_mean = y_wind.collapsed('t', iris.analysis.MEAN)
    x_zonal_mean = x_wind.collapsed('t', iris.analysis.MEAN)
    # x_anomaly_data = np.array(u_prime_lats)
    x_anomaly = x_wind - x_zonal_mean
    y_anomaly = y_wind - y_zonal_mean
    theta_anomaly = theta - theta_zonal_mean

    y_anomaly_data = y_anomaly.data
    theta_anomaly_data = theta_anomaly.data
    x_anomaly_data = x_anomaly.data

    XY_anomaly = x_anomaly_data * y_anomaly_data
    YTH_anomaly = y_anomaly_data * theta_anomaly_data
    XY_anomaly_zonal_mean = np.mean(XY_anomaly, axis=2)
    YTH_anomaly_zonal_mean = np.mean(YTH_anomaly, axis=2)

    lats = (pressure.coord('latitude').points) * (np.pi / 180
                                                  )  # Latitudes in radians
    coriolis = 2 * omega * np.sin(lats)  # Coriolis force
    radius = 7160000  # radius of ProxB in meters
    rcosphi = radius * np.cos(lats)
    rsinphi = radius * np.sin(lats)
    latfac = rcosphi * np.cos(lats)

    EP_phi = -XY_anomaly_zonal_mean * latfac
    EP_up = (coriolis * rcosphi * YTH_anomaly_zonal_mean) / THETAp

    EP_phi_div = ep_latderivative(EP_phi, rsinphi)
    EP_up_div = ep_zderivative(EP_up, pressure_zonal_mean)
    EP_div = (EP_phi_div + EP_up_div)

    # x_zonal_mean = x_wind.collapsed('longitude', iris.analysis.MEAN)
    x_mean = x_wind.collapsed('longitude', iris.analysis.MEAN)

    x_axis = pressure.coord('latitude').points
    # y_axis = pressure_zonal_mean
    y_axis = pressure.coord('Hybrid height').points
    plt.contourf(x_axis,
                 y_axis[35:59],
                 EP_div[35:59, :],
                 brewer_redblu.N,
                 cmap=brewer_redblu,
                 norm=TwoSlopeNorm(0))
    plt.colorbar(pad=0.1)
    CS = plt.contour(x_axis,
                     y_axis[35:59],
                     x_mean[35:59, :].data,
                     colors='black',
                     linewidths=0.5)
    plt.title('EP flux divergence for day=%s, long=%s to %s' %
              (time_slice / 4, longitudes[0], longitudes[-1]))
    plt.xlabel('Latitude [degrees]')
    plt.ylabel('Height [m]')
    plt.clabel(CS, inline=False, colors='k', fmt='%1.1f')
    plt.show()
Example #28
0
def create_xsection(cubes, time_slice=1780, lat=45):

    for cube in cubes:
        if cube.standard_name == 'eastward_wind' or cube.standard_name == 'x_wind':
            x_wind = cube[time_slice, :, :, :].copy()
        if cube.standard_name == 'air_pressure':
            pressure = cube[time_slice, :, :, :].copy()

    longitudes, heights = x_wind.shape[2] / 2, np.round(
        x_wind.coord('Hybrid height').points * 1e-03, 0)
    pressure = pressure.regrid(x_wind, iris.analysis.Linear())

    height = [('Hybrid height', x_wind.coord('Hybrid height').points)]
    pressure = pressure.interpolate(height, iris.analysis.Linear())

    pressure = pressure.extract(iris.Constraint(latitude=45))
    h = np.log(pressure.data)

    u_prime_array = []
    xterm_array = []

    for level in range(0, 60):

        u_prime, cross_term = plot_uwprime(cubes=cubes,
                                           time_slice=time_slice,
                                           lat=lat,
                                           level=level,
                                           plots=False)

        u_prime_array.append(u_prime)
        xterm_array.append(cross_term)

    u_prime_array = np.array(u_prime_array)
    xterm_array = np.array(xterm_array)

    array = xterm_array.copy()
    acceleration = array.copy()
    acceleration[0, :] = (array[1, :] - array[0, :]) / (h[1, :] - h[0, :])
    acceleration[-1, :] = (array[-1, :] - array[-2, :]) / (h[-1, :] - h[-2, :])
    acceleration[1:-1, :] = (array[2:, :] - array[0:-2, :]) / (h[2:, :] -
                                                               h[0:-2, :])

    plt.figure(figsize=(10, 5))
    plt.contourf(np.arange(-longitudes, longitudes),
                 np.array(heights),
                 np.roll(u_prime_array, 72, axis=1),
                 brewer_redblu.N,
                 cmap=brewer_redblu,
                 norm=TwoSlopeNorm(0))
    plt.title('$U^{\prime}$ at Equator, t=%s days' % (time_slice / 4))
    plt.xlabel('Longitude [degrees]')
    plt.xticks((-72, -60, -48, -36, -24, -12, 0, 12, 24, 36, 48, 60, 72),
               ('180W', '150W', '120W', '90W', '60W', '30W', '0', '30E', '60E',
                '90E', '120E', '150E', '180E'))
    plt.ylabel('Height [km]')
    plt.colorbar(pad=0.1)
    plt.show()

    plt.figure(figsize=(10, 5))
    plt.contourf(np.arange(-longitudes, longitudes),
                 np.array(heights),
                 np.roll(xterm_array, 72, axis=1),
                 brewer_redblu.N,
                 cmap=brewer_redblu,
                 norm=TwoSlopeNorm(0))
    plt.title('$U^{\prime} \cdot W^{\prime}$ at Equator, t=%s days' %
              (time_slice / 4))
    plt.xlabel('Longitude [degrees]')
    plt.xticks((-72, -60, -48, -36, -24, -12, 0, 12, 24, 36, 48, 60, 72),
               ('180W', '150W', '120W', '90W', '60W', '30W', '0', '30E', '60E',
                '90E', '120E', '150E', '180E'))
    plt.ylabel('Height [km]')
    plt.colorbar(pad=0.1)
    plt.show()

    plt.figure(figsize=(10, 5))
    plt.contourf(np.arange(-longitudes, longitudes),
                 np.array(heights[33:42]),
                 np.roll(u_prime_array[33:42], 72, axis=1),
                 np.linspace(-5, 5, 80),
                 cmap=brewer_redblu,
                 norm=TwoSlopeNorm(0))
    plt.title('$U^{\prime}$ at Equator, t=%s days' % (time_slice / 4))
    plt.xlabel('Longitude [degrees]')
    plt.xticks((-72, -60, -48, -36, -24, -12, 0, 12, 24, 36, 48, 60, 72),
               ('180W', '150W', '120W', '90W', '60W', '30W', '0', '30E', '60E',
                '90E', '120E', '150E', '180E'))
    plt.ylabel('Height [km]')
    plt.colorbar(pad=0.1)
    plt.show()

    plt.figure(figsize=(10, 5))
    plt.contourf(np.arange(-longitudes, longitudes),
                 np.array(heights),
                 np.roll(acceleration, 72, axis=1),
                 np.linspace(-0.5, 0.5, 10),
                 cmap=brewer_redblu,
                 norm=TwoSlopeNorm(0))
    plt.title('Wave-Induced Acceleration at Equator (filtered), t=%s days' %
              (time_slice / 4))
    plt.xlabel('Longitude [degrees]')
    plt.xticks((-72, -60, -48, -36, -24, -12, 0, 12, 24, 36, 48, 60, 72),
               ('180W', '150W', '120W', '90W', '60W', '30W', '0', '30E', '60E',
                '90E', '120E', '150E', '180E'))
    plt.ylabel('Height [km]')
    plt.colorbar(pad=0.1)
    plt.show()
Example #29
0
dist = int((len(y_fluc) / 2.) / 4)
NGC4839 = [345, 381]

print("\nLength of y fluctuation matrix =", len(y_fluc))

from matplotlib.colors import TwoSlopeNorm  #Needed in plotting diverging colormaps

x_ticks = ['-2', '-1', '0', '1', '2']
y_ticks = ['-2', '-1', '0', '1', '2']
t11 = [0, 35, 70, 105, 138]

plt.figure()
plt.xticks(ticks=t11, labels=x_ticks, size='small')
plt.yticks(ticks=t11, labels=y_ticks, size='small')

norm = TwoSlopeNorm(vmin=y_fluc.min(), vcenter=0, vmax=y_fluc.max())
pc = plt.pcolormesh(y_fluc, norm=norm, cmap="seismic")
plt.imshow(y_fluc, cmap='seismic')
ax = plt.gca()
rect = patches.Rectangle((mid - dist, mid - dist),
                         2 * dist,
                         2 * dist,
                         linewidth=2,
                         edgecolor='black',
                         facecolor="none")
ax.add_patch(rect)
circ = patches.Circle((NGC4839[0] - x_ind[0][0], NGC4839[1] - y_ind[0][0]),
                      15 / pixsize,
                      linewidth=2,
                      edgecolor='green',
                      facecolor="none")
def MSI():

    data_path = file_path
    bands_grep = re.compile(".*_(B5|B6)\.(tif|TIF)")

    file_list = glob.glob(data_path + '\*.TIF')

    # Filter and keep only useful files (bands 4 and 5 to compute NDVI)
    bands = filter(lambda x: bands_grep.search(x), file_list)
    bands = [s for s in bands]

    with rasterio.open(bands[0]) as src:
        b5 = src.read(1).astype('float64')

    with rasterio.open(bands[1]) as src:
        b6 = src.read(1).astype('float64')

    # Allow division by zero
    np.seterr(divide='ignore', invalid='ignore')

    msi_temp = np.where(b5 == 0, 0, b6 / b5)

    max = msi_temp.astype(float).max()

    msi = np.where(b6 / b5 >= max, max, b6 / b5)

    # Define spatial characteristics of output object (basically they are analog to the input)
    kwargs = src.meta

    # Update kwargs (change in data type)
    kwargs.update(dtype=rasterio.float64, count=1)

    with rasterio.open(output_path + '/MSI.tif', 'w', **kwargs) as dst:
        dst.write_band(1, msi.astype(rasterio.float64))

    src = rasterio.open(output_path + '/MSI.tif')

    # matplotlib ile görsel ve colorbar ayrı ayrı
    z = np.linspace(0, max, 50 * 50)

    norm = TwoSlopeNorm(vmin=z.min(), vcenter=max / 2, vmax=z.max())
    pc = plt.imshow(src.read(1).astype('float64'), norm=norm, cmap='RdBu_r')
    plt.colorbar(pc)

    plt.show()

    # geotiff kaydetme
    naip_data_path = output_path + '/MSI.tif'

    with rasterio.open(naip_data_path) as src:
        naip_data = src.read()
        naip_meta = src.profile

    naip_transform = naip_meta["transform"]
    naip_crs = naip_meta["crs"]

    w, h = msi.shape

    customized_cmap = {}
    a = float(255 / (max + 2))

    for s in range(0, int(max + 2)):
        s_color = (0 + a, 0, 255 - a, 0)
        customized_cmap[s] = s_color
        s += 1
        a += float(255 / (max + 2))

    with rasterio.open(output_path + '/MSI.tif',
                       'w',
                       driver='GTiff',
                       width=w,
                       height=h,
                       count=1,
                       dtype=rasterio.uint8,
                       crs=naip_crs,
                       transform=naip_transform) as dst:
        dst.write(msi.astype(rasterio.uint8), indexes=1)
        dst.write_colormap(1, customized_cmap)