Exemple #1
0
                                        N=cmap.shape[0])

figure(6)
clf()
levs = arange(0, 1.0570833e-07, 1e-8)
levs = [
    -0.125e-8, 0., 0.125e-8, 0.25e-8, 0.625e-8, 1e-8, 2e-8, 3e-8, 4e-8, 5e-8,
    6e-8, 7e-8, 7.5e-8, 8e-8, 9e-8, 1.0570833e-07
]
subplot(111, projection=proj())
pactive, lon = add_cyclic_point(pactive, lon)
#contourf(lon,lat,pactive,cmap=get_cmap('jet'),levels=levs,extend='both')
contourf(lon, lat, pactive, cmap=cmap, levels=levs)
cmap.set_under('w')
gca().coastlines('50m')
gca().xlocator = mticker.FixedLocator([-180, -45, 0, 45, 180])
xformatter = LONGITUDE_FORMATTER
title('Observation-based species dist. model')
letter_label(ypos=1.05)
cb = colorbar()
cb.set_label('More AM $\longleftarrow \longrightarrow$ More ECM')

tight_layout()
savefig('test_sulman.png', dpi=300)
sys.exit()

figure(4)
clf()
subplot(223, projection=proj())
Eobs, lon = add_cyclic_point(ECM_obs.isel(band=0).values, ECM_obs.x)
contourf(lon, ECM_obs.y, Eobs, vmin=0.0, vmax=1.0, cmap=get_cmap('YlGn'))
Exemple #2
0
    def peek(self, title="GOES Xray Flux", **kwargs):
        """
        Plots GOES XRS light curve is the usual manner. An example is shown
        below:

        .. plot::

            import sunpy.timeseries
            import sunpy.data.sample
            ts_goes = sunpy.timeseries.TimeSeries(sunpy.data.sample.GOES_XRS_TIMESERIES, source='XRS')
            ts_goes.peek()

        Parameters
        ----------
        title : `str`. optional
            The title of the plot. Defaults to "GOES Xray Flux".
        **kwargs : `dict`
            Additional plot keyword arguments that are handed to `axes.plot` functions
        """
        # Check we have a timeseries valid for plotting
        self._validate_data_for_plotting()

        fig, ax = plt.subplots()

        dates = matplotlib.dates.date2num(
            parse_time(self.to_dataframe().index).datetime)

        ax.plot_date(dates,
                     self.to_dataframe()['xrsa'],
                     '-',
                     label=r'0.5--4.0 $\AA$',
                     color='blue',
                     lw=2,
                     **kwargs)
        ax.plot_date(dates,
                     self.to_dataframe()['xrsb'],
                     '-',
                     label=r'1.0--8.0 $\AA$',
                     color='red',
                     lw=2,
                     **kwargs)

        ax.set_yscale("log")
        ax.set_ylim(1e-9, 1e-2)
        ax.set_title(title)
        ax.set_ylabel('Watts m$^{-2}$')
        ax.set_xlabel(
            datetime.datetime.isoformat(self.to_dataframe().index[0])[0:10])

        ax2 = ax.twinx()
        ax2.set_yscale("log")
        ax2.set_ylim(1e-9, 1e-2)
        labels = ['A', 'B', 'C', 'M', 'X']
        centers = np.logspace(-7.5, -3.5, len(labels))
        ax2.yaxis.set_minor_locator(mticker.FixedLocator(centers))
        ax2.set_yticklabels(labels, minor=True)
        ax2.set_yticklabels([])

        ax.yaxis.grid(True, 'major')
        ax.xaxis.grid(False, 'major')
        ax.legend()

        # TODO: display better tick labels for date range (e.g. 06/01 - 06/05)
        formatter = matplotlib.dates.DateFormatter('%H:%M')
        ax.xaxis.set_major_formatter(formatter)

        ax.fmt_xdata = matplotlib.dates.DateFormatter('%H:%M')
        fig.autofmt_xdate()

        return fig
Exemple #3
0
def execute(context):
    plotting.setup()
    hts_name = context.config("hts")

    df_census = context.stage("census")
    df_hts, df_correction = context.stage("hts")

    # PLOT: Work / education flows
    plt.figure(figsize=plotting.WIDE_FIGSIZE)

    figures = [{
        "slot": "work",
        "title": "Work",
        "top": 12
    }, {
        "slot": "education",
        "title": "Education",
        "top": 12,
        "factor": 0.7
    }]

    for index, figure in enumerate(figures):
        plt.subplot(1, 2, index + 1)
        slot = figure["slot"]

        df = context.stage("data")[slot]
        df = pd.merge(df,
                      df_census[slot].rename(columns={"weight": "reference"}),
                      on=["home", slot])
        df = pd.merge(df, df_correction[slot], on="home")
        df["scaled_reference"] = df["reference"] * (
            figure["factor"] if "factor" in figure else df["factor"])

        count = figure["top"]
        df = df.sort_values(by="scaled_reference", ascending=False).head(count)

        plt.bar(np.arange(count),
                df["reference"],
                width=0.4,
                align="edge",
                linewidth=0.5,
                edgecolor="white",
                color=plotting.COLORS["census"],
                alpha=0.25)
        plt.bar(np.arange(count),
                df["scaled_reference"],
                width=0.4,
                label="Census",
                align="edge",
                linewidth=0.5,
                edgecolor="white",
                color=plotting.COLORS["census"])
        plt.bar(np.arange(count) + 0.4,
                df["mean"] / SAMPLING_RATE,
                width=0.4,
                label="Synthetic",
                align="edge",
                linewidth=0.5,
                edgecolor="white",
                color=plotting.COLORS["synthetic"])

        for index, (min,
                    max) in enumerate(zip(df["min"].values, df["max"].values)):
            index += 0.4 + 0.2
            plt.plot([index, index],
                     [min / SAMPLING_RATE, max / SAMPLING_RATE],
                     color='k',
                     linewidth=1.0)

        plt.grid()
        plt.gca().set_axisbelow(True)
        plt.gca().xaxis.grid(alpha=0.0)

        plt.gca().yaxis.set_major_locator(
            tck.FixedLocator(np.arange(100) * 1e5))
        plt.gca().yaxis.set_major_formatter(
            tck.FuncFormatter(lambda x, p: "%d" % (x * 1e-3, )))

        origins, destinations = df["home"].values, df[figure["slot"]].values

        plt.gca().xaxis.set_major_locator(
            tck.FixedLocator(np.arange(count) + 0.4))
        plt.gca().xaxis.set_major_formatter(
            tck.FixedFormatter(
                ["%s\n%s" % item for item in zip(origins, destinations)]))

        plt.ylabel("Commuters [x1000]")
        plt.legend(loc="best")
        plt.title(figure["title"])

    plt.tight_layout()
    plt.savefig("%s/commute_flows.pdf" % context.path())
    plt.close()

    # PLOT: Scatter
    plt.figure(figsize=plotting.SHORT_FIGSIZE)

    parts = [{
        "slot": "work",
        "title": "Work",
        "marker": ".",
        "color": "k"
    }, {
        "slot": "education",
        "title": "Education",
        "factor": 0.7,
        "marker": ".",
        "color": plotting.COLORS[hts_name]
    }]

    minimum = np.inf
    maximum = -np.inf

    for part in parts:
        slot = part["slot"]

        df = context.stage("data")[slot]
        df = pd.merge(df,
                      df_census[slot].rename(columns={"weight": "reference"}),
                      on=["home", slot])
        df = pd.merge(df, df_correction[slot], on="home")
        df["scaled_reference"] = df["reference"] * (part["factor"] if "factor"
                                                    in part else df["factor"])

        plt.loglog(df["scaled_reference"],
                   df["mean"] / SAMPLING_RATE,
                   markersize=2,
                   marker=part["marker"],
                   color=part["color"],
                   linestyle="none",
                   label=part["title"])

        minimum = np.minimum(minimum, df["scaled_reference"].min() * 0.9)
        maximum = np.maximum(maximum, df["scaled_reference"].max() * 1.1)

    x = np.linspace(minimum, maximum, 100)
    plt.fill_between(x,
                     x * 0.8,
                     x * 1.2,
                     color="k",
                     alpha=0.2,
                     linewidth=0.0,
                     label=r"20% Error")

    plt.xlim([minimum, maximum])
    plt.ylim([minimum, maximum])

    plt.grid()
    plt.gca().set_axisbelow(True)
    plt.legend()

    plt.xlabel("Reference flow")
    plt.ylabel("Synthetic flow")

    plt.tight_layout()
    plt.savefig("%s/commute_scatter.pdf" % context.path())
    plt.close()

    # PLOT: Histogram
    plt.figure(figsize=plotting.SHORT_FIGSIZE)

    parts = [{
        "slot": "work",
        "title": "Work"
    }, {
        "slot": "education",
        "title": "Education",
        "factor": 0.7
    }]

    for index, part in enumerate(parts):
        slot = part["slot"]

        df = context.stage("data")[slot]
        df = pd.merge(df,
                      df_census[slot].rename(columns={"weight": "reference"}),
                      on=["home", slot])
        df = pd.merge(df, df_correction[slot], on="home")
        df["scaled_reference"] = df["reference"] * (part["factor"] if "factor"
                                                    in part else df["factor"])

        df["difference"] = 100 * (
            df["mean"] / SAMPLING_RATE -
            df["scaled_reference"]) / df["scaled_reference"]

        min = df["difference"].min()
        max = df["difference"].max()
        mean = df["difference"].mean()

        values = df["difference"].values
        outliers = values  # values[(values < min) | (values > max)]

        plt.plot([index - 0.2, index + 0.2], [min, min],
                 color="k",
                 linewidth=1.0)
        plt.plot([index - 0.2, index + 0.2], [max, max],
                 color="k",
                 linewidth=1.0)
        plt.plot([index - 0.2, index + 0.2], [mean, mean],
                 color="k",
                 linewidth=1.0,
                 linestyle=":")
        plt.plot([index - 0.2, index - 0.2], [min, max],
                 color="k",
                 linewidth=1.0)
        plt.plot([index + 0.2, index + 0.2], [min, max],
                 color="k",
                 linewidth=1.0)

        plt.plot([index] * len(outliers),
                 outliers,
                 color="k",
                 marker=".",
                 markersize=2,
                 linestyle="none")

    plt.gca().xaxis.set_major_locator(tck.FixedLocator([0, 1]))
    plt.gca().xaxis.set_major_formatter(
        tck.FixedFormatter(["Work", "Education"]))

    plt.ylabel("Error [%]")

    plt.xlim([-0.5, 1.5])
    plt.grid()
    plt.gca().set_axisbelow(True)
    plt.gca().xaxis.grid(alpha=0.0)

    plt.bar([np.nan], [np.nan],
            color="none",
            edgecolor="k",
            linewidth=1.0,
            label="5% - 95%")
    plt.plot([np.nan], color="k", linestyle=":", label="Mean")

    plt.legend(loc="best")

    plt.tight_layout()
    plt.savefig("%s/commute_flow_boxplot.pdf" % context.path())
    plt.close()
Exemple #4
0
def plot_on_map_L3(data,
                   lat,
                   lon,
                   cmapt,
                   cbartitle=None,
                   title=None,
                   centrelon=None):

    import numpy as np
    import numpy.ma as ma
    import matplotlib.pyplot as plt
    plt.switch_backend('agg')
    import matplotlib.ticker as mticker
    import cartopy.crs as ccrs
    from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
    from cartopy.feature import LAND
    #Get relative path to subroutines
    import os
    import sys
    dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
    os.environ[
        "CARTOPY_USER_BACKGROUNDS"] = dirname + '/Blue_marble_data/BlueMarbleNG-TB/'

    proj = ccrs.Stereographic(central_latitude=90.0)
    ax = plt.axes(projection=proj)
    ax.coastlines()

    gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True)
    gl.top_labels = False
    gl.left_labels = False
    gl.xlocator = mticker.FixedLocator([-180, -120, -60, 0, 60, 120, 180])
    gl.ylocator = mticker.FixedLocator([-90, -60, -30, 0, 30, 60, 90])
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER

    mi = data.min()
    ma = data.max()

    mapped = plt.pcolormesh(lon,
                            lat,
                            data,
                            cmap=cmapt,
                            vmin=mi,
                            vmax=ma,
                            transform=ccrs.PlateCarree())
    cbar = plt.colorbar(mapped,
                        ax=ax,
                        orientation='horizontal',
                        pad=0.05,
                        extend='both')

    if cbartitle is not None:
        cbar.set_label(cbartitle)

    #Maximize and save PNG file
    if title is not None:
        plt.title(title)
        ax.xaxis.labelpad = 20
        plt.gcf().subplots_adjust(bottom=0.00)

    fig = plt.gcf()
    return fig
Exemple #5
0
extent = [73.5,140,14,53.6]

# <codecell>

fig = plt.figure(figsize=(20,13))
gs = gridspec.GridSpec(3, 3)

#############--------------################-------------#############--------------################-------------

# PLOT TOP LEFT
ax1 = fig.add_subplot(gs[0,0], projection=ccrs.AlbersEqualArea(central_longitude=105, central_latitude=15))
ax1.set_extent(extent)
ax1.coastlines(resolution='110m')

gl1 = ax1.gridlines()
gl1.xlocator = mticker.FixedLocator([50, 70,90,110,130,150,170])
gl1.ylocator = mticker.FixedLocator([10,  20,  30,  40,  50, 60])
gl1.xformatter = LONGITUDE_FORMATTER
gl1.yformatter = LATITUDE_FORMATTER

ax1.add_feature(cfeature.LAND, facecolor='0.85')

# # classify each county based on column ID_3
# for record, county in zip(china_adm3_shp.records(), china_adm3_shp.geometries()): 
#     # extract for each row the value corresponding to the column header 
#     ID = record.attributes['ID_3']    
#     # Classify the records in to groups
#     if ID <= 500:
#         facecolor = 'k'
#         edgecolor = 'k'
#     if (ID > 500) and (x <= 1000):
Exemple #6
0
}

obs_tracks = da.read_nc(
    'detection/JRA55/JRA55_all_tracks_knutson2007.nc')['all_tracks']
nc = da.read_nc('data/JRA55/atl_2010_MSLP.nc')
lons, lats = nc.lon, nc.lat
lons[lons > 180] -= 360

# sparial stuff
plt.close('all')
plt.figure(figsize=(10, 5))
ax = plt.axes(projection=rot_pole)
ax.set_global()
ax.coastlines()
gl = ax.gridlines(color='#8470ff', linewidth=1)
gl.ylocator = mticker.FixedLocator(np.arange(-20, 60, 10))
gl.xlocator = mticker.FixedLocator(np.arange(-120, 20, 10))
for yy in np.arange(-10, 40, 10):
    ax.text(-15, yy, str(yy), color='#8470ff', transform=plate_carree)
for xx in np.arange(-100, 0, 10):
    ax.text(xx, 8, str(xx), color='#8470ff', transform=plate_carree)
ax.add_feature(cartopy.feature.LAND, facecolor='darkgreen')
ax.add_feature(cartopy.feature.OCEAN, facecolor='darkblue')
ax.set_xlim(np.min(grid_lons) - 5, np.max(grid_lons) + 20)
ax.set_ylim(np.min(grid_lats) - 5, np.max(grid_lats) + 5)
reg = Polygon([(grid_lons[0], grid_lats[0]), (grid_lons[-1], grid_lats[0]),
               (grid_lons[-1], grid_lats[-1]), (grid_lons[0], grid_lats[-1]),
               (grid_lons[0], grid_lats[0])])
ax.add_geometries([reg],
                  rot_pole,
                  color='lightgreen',
def make_plot(fnum, all_data, ylab, ylab2, xlim=None):

    
    major_locator = ticker.FixedLocator([1, 8, 15, 22, 29])
    minor_locator = ticker.MultipleLocator(1)
 
    f,ax1 = plt.subplots(num=fnum, clear=True)

    f.set_size_inches(10, 6)

    present_year = datetime.datetime.now().year
    x_max = 1
    for data in all_data:
        # Calculate difference to current year:
        this_year = data['datetime'][0].astype(object).year
        this_month = data['datetime'][0].astype(object).month
        month_start_dt64 = np.datetime64(f"{this_year}-{this_month:02d}-01", 'ms')
        # Flesh out the year from this
        years_ago = present_year - this_year
        
        x = (data['datetime'] - month_start_dt64) / np.timedelta64(1,'D') + 1.0 # +1, because May 0 looks a bit weird
        # Add that amount of years to offset:
        years_ago = data
        
        # Averate the two channels
        y = np.nanmean( np.append(data['pool1'][:, None], data['pool2'][:, None], axis=1), axis=1 )
        
        ax1.plot(x, y, label=f"{this_year}")
        
        x_max = max(x_max, x[-1])
        
    ax1.set_ylabel(ylab)

    l = ax1.legend()

    ax1.spines['top'].set_visible(False)
    ax1.spines['right'].set_visible(False)

    # format the ticks
    ax1.xaxis.set_major_locator(major_locator)
#    ax1.xaxis.set_major_formatter(x_major_fmt)
    ax1.xaxis.set_minor_locator(minor_locator)
#    ax1.xaxis.set_minor_formatter(x_minor_fmt)
    #f.autofmt_xdate()

    ax2 = ax1.twinx()
    ax2.set_ylabel(ylab2)
    plt.setp(ax1.xaxis.get_majorticklabels(), rotation=0, horizontalalignment='center' )
    plt.setp(ax1.xaxis.get_minorticklabels(), rotation=0, horizontalalignment='center', fontsize=9 )

    #ax1.set_xlabel("Day of month")
    ax1.set_title(data['datetime'][0].astype(object).strftime("%b"))
    
    # Adjust x range
    x_min = 1
    ax1.set_xlim(x_min, x_max)

    # Round the y axis similarly
    y_min, y_max = ax1.get_ylim()
    yt = ax1.get_yticks()
    ax1.set_ylim(yt[0], yt[-1])
    
    # ax2 is empty, so the default y range is 0.0 to 1.0.
    # Set it to match such that the ticks line up:
    ax2.set_ylim(yt[0], yt[-1])

    # Overwrite the tick decorator to convert C to F dynamically:
    ax2.yaxis.set_major_formatter(c2f_formatter)

    ax1.grid(b=True, which='major', color=(0.75,0.75,0.75), linestyle='-')
    ax1.grid(b=True, which='minor', color=(0.8,0.8,0.8), linestyle=':')


    #f.tight_layout()
    return f, ax1
    ax.yaxis.set_major_formatter(ticker.ScalarFormatter())
    ax.axhline(96**2, ls='--', c='blue')
    ax.axhline(32**2, ls='--', c='orange')
    plt.xticks(rotation=40, ha="right")
    # plt.legend(bbox_to_anchor=(1.01, 1), borderaxespad=0)
    plt.xlabel('Klasse')
    plt.ylabel('Fläche in Pixelanzahl')
    plt.savefig(os.path.join(output_directory, 'box_area.png'), bbox_inches='tight')

    # Seitenverhältnisse der Boxen
    plt.figure(figsize=(9,8))
    ax = sns.boxenplot(data=object_dataframe, x='class', y='ratio')
    ax.set_yscale('log')
    # sns.move_legend(ax, loc='upper left', bbox_to_anchor=(1, 1))
    locs = [0.3, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2, 2.5, 3, 3.5, 4, 4.5, 5]
    ax.yaxis.set_major_locator(ticker.FixedLocator(locs))
    ax.yaxis.set_major_formatter(ticker.ScalarFormatter())
    plt.xticks(rotation=40, ha="right")
    # plt.legend(bbox_to_anchor=(1.01, 1), borderaxespad=0)
    plt.xlabel('Klasse')
    plt.ylabel('Seitenverhältnis Weite / Höhe')
    plt.savefig(os.path.join(output_directory, 'box_ratio.png'), bbox_inches='tight')

    # Gewicht in Abhängigkeit von Anzahl der Objekte
    plt.figure(figsize=(8,8))
    g = sns.catplot(data=file_dataframe, y='weight', x='objects', hue='objects', col='class', col_wrap=4, jitter=0.4, alpha=0.8)
    for ax in g.axes.flat:
        ax.yaxis.set_major_locator(ticker.MultipleLocator(500))
        ax.yaxis.set_major_formatter(ticker.ScalarFormatter())
    # sns.move_legend(ax, loc='upper left', bbox_to_anchor=(1, 1))
    g.set_ylabels('Gewicht in Gramm', fontsize=15)  # not set_label
Exemple #9
0
def _plot_scalings_multiple(
    scalings,
    x_key,
    y_key,
    x_label,
    y_label,
    series_labels,
    title,
):

    # Wrap single instance in list if needed
    if isinstance(scalings, (pandas.DataFrame, TraceSet, MetricSet)):
        scalings = [scalings]

    # Make sure we are dealing with all pd.Dataframe
    scalings = [_get_dataframe(dataset) for dataset in scalings]

    # Sort out labels as needed
    if x_label is None:
        x_label = x_key

    if y_label is None:
        y_label = y_key

    if series_labels is None:
        if len(scalings) == 1:
            series_labels = [y_label]
        else:
            series_labels = range(len(scalings))

    # Calculate x and y ranges
    cores_min = numpy.nan
    cores_max = numpy.nan
    y_max = numpy.nan

    for dataset in scalings:
        cores_min = numpy.nanmin([cores_min, dataset[x_key].min()])
        cores_max = numpy.nanmax([cores_max, dataset[x_key].max()])
        y_max = numpy.nanmax((y_max, dataset[y_key].max()))

    # And pad appropriately
    y_max *= 1.2
    x_margin = 0.02 * cores_max

    # Calculate ideal scalings
    ideal_scaling_cores = numpy.linspace(cores_min - x_margin,
                                         cores_max + x_margin)
    ideal_scaling = ideal_scaling_cores / cores_min
    ideal_scaling_80pc = 0.2 + 0.8 * ideal_scaling

    # Finally, plot
    fig = plt.figure(figsize=figparams["single.figsize"])
    ax = fig.add_axes(figparams["single.axlayout"][0])

    ax.fill_between(
        ideal_scaling_cores,
        0,
        ideal_scaling_80pc,
        label="80% Scaling",
        alpha=0.1,
        color="g",
        linestyle="-",
    )
    ax.fill_between(
        ideal_scaling_cores,
        ideal_scaling_80pc,
        ideal_scaling,
        label="Ideal Scaling",
        alpha=0.2,
        color="g",
        linestyle="-",
    )

    for dataset, label in zip(scalings, series_labels):
        ax.plot(
            dataset[x_key],
            dataset[y_key],
            label=label,
            marker="x",
            linestyle="-",
            alpha=0.8,
        )

    ax.set_xlim(ideal_scaling_cores.min(), ideal_scaling_cores.max())
    ax.set_ylim(0, y_max)
    ax.set_xlabel(x_label)
    ax.set_ylabel(y_label)
    ax.xaxis.set_major_locator(mtick.FixedLocator(scalings[0][x_key], 6))
    ax.legend()

    if title:
        ax.set_title(title)

    return fig
Exemple #10
0
def parallel_coordinates(df, target_column, lower_is_better=True, **kwds):
    minimum_target = df[target_column].min()
    maximum_target = df[target_column].max()

    # process target column for plotting
    target_colors = df[target_column]
    target_colors = np.true_divide(target_colors - target_colors.min(),
                                   np.ptp(target_colors))
    if lower_is_better:
        target_colors = (target_colors - 1) * (-1)
    # sort df such that during plotting the better ones are drawn over the others
    df = df.sort_values(target_column, ascending=not lower_is_better)
    df = df.drop(columns=target_column)

    cols = df.columns

    x_ticks = list(range(len(cols)))

    # Create (X-1) sublots along x axis
    fig, axes = plt.subplots(1,
                             len(x_ticks) - 1,
                             sharey=False,
                             figsize=(15, 5))
    # handle case X-1 == 1, in which case axes is not a list
    if len(x_ticks) - 1 == 1:
        axes = [axes]

    # Get min, max and range for each column
    # Normalize the data for each column
    tick_dict = {}
    for col in cols:
        tick_dict[col] = {}
        if type(df[col]
                [0]) is str:  # treat variables of type string as categorical
            df[col] = df[col].astype('category')
            codes = df[col].cat.codes.copy()
            codes = np.true_divide(codes - codes.min(), np.ptp(codes))
            # Save the ticks and ticklabels
            # I assume that unique() returns the values in the order that they appear in the Series
            tick_dict[col]['ticks'] = codes.unique()
            tick_dict[col]['tick_labels'] = df[col].unique()
            # replace the categories with the computed codes
            df[col] = codes
        else:  # not categorical
            tick_dict[col]['tick_labels'] = df[col].unique()
            df[col] = np.true_divide(df[col] - df[col].min(), np.ptp(df[col]))
            tick_dict[col]['ticks'] = df[col].unique()
        df[col] = df[col] + np.random.normal(size=len(df), scale=0.02)

    # Loop over horizontally stacked subplots
    for i, ax in enumerate(axes):
        # loop over lines
        for idx in df.index:
            y = target_colors[idx]
            ax.plot(x_ticks,
                    df.loc[idx, cols],
                    color=cm.viridis(y),
                    linewidth=3)
        ax.set_xlim([x_ticks[i], x_ticks[i + 1]])

    norm = mpl.colors.Normalize(vmin=minimum_target, vmax=maximum_target)
    cmap = mpl.cm.ScalarMappable(
        norm=norm,
        cmap=mpl.cm.viridis_r if lower_is_better else mpl.cm.viridis)
    cmap.set_array([])
    fig.subplots_adjust(right=0.8)
    cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
    fig.colorbar(cmap, cax=cbar_ax)

    # Set the tick positions and labels on y axis for each plot
    # Tick positions based on normalised data
    # Tick labels are based on original data
    for idx, ax in enumerate(axes):
        ax.yaxis.set_ticks(tick_dict[cols[idx]]['ticks'])
        ax.set_yticklabels(tick_dict[cols[idx]]['tick_labels'])
        ax.xaxis.set_major_locator(ticker.FixedLocator([idx]))
        ax.set_xticklabels([cols[idx]])

    # Move the final axis' ticks to the right-hand side
    ax = plt.twinx(axes[-1])
    idx = len(axes)
    ax.yaxis.set_ticks(tick_dict[cols[idx]]['ticks'])
    ax.set_yticklabels(tick_dict[cols[idx]]['tick_labels'])
    ax.xaxis.set_major_locator(ticker.FixedLocator([x_ticks[-2], x_ticks[-1]]))
    ax.set_xticklabels([cols[-2], cols[-1]])
    # Remove space between subplots
    plt.subplots_adjust(wspace=0)
Exemple #11
0
    def __init__(
        self,
        ax,
        cmap=None,
        norm=None,
        alpha=None,
        values=None,
        boundaries=None,
        orientation='vertical',
        ticklocation='auto',
        extend='neither',
        spacing='uniform',  # uniform or proportional
        ticks=None,
        format=None,
        drawedges=False,
        filled=True,
        extendfrac=None,
        extendrect=False,
        label='',
    ):
        #: The axes that this colorbar lives in.
        self.ax = ax
        self._patch_ax()
        if cmap is None:
            cmap = cm.get_cmap()
        if norm is None:
            norm = colors.Normalize()
        self.alpha = alpha
        cm.ScalarMappable.__init__(self, cmap=cmap, norm=norm)
        self.values = values
        self.boundaries = boundaries
        self.extend = extend
        self._inside = self._slice_dict[extend]
        self.spacing = spacing
        self.orientation = orientation
        self.drawedges = drawedges
        self.filled = filled
        self.extendfrac = extendfrac
        self.extendrect = extendrect
        self.solids = None
        self.lines = list()
        self.outline = None
        self.patch = None
        self.dividers = None

        if ticklocation == 'auto':
            ticklocation = 'bottom' if orientation == 'horizontal' else 'right'
        self.ticklocation = ticklocation

        self.set_label(label)
        if cbook.iterable(ticks):
            self.locator = ticker.FixedLocator(ticks, nbins=len(ticks))
        else:
            self.locator = ticks  # Handle default in _ticker()
        if format is None:
            if isinstance(self.norm, colors.LogNorm):
                self.formatter = ticker.LogFormatterSciNotation()
            elif isinstance(self.norm, colors.SymLogNorm):
                self.formatter = ticker.LogFormatterSciNotation(
                    linthresh=self.norm.linthresh)
            else:
                self.formatter = ticker.ScalarFormatter()
        elif isinstance(format, six.string_types):
            self.formatter = ticker.FormatStrFormatter(format)
        else:
            self.formatter = format  # Assume it is a Formatter
        # The rest is in a method so we can recalculate when clim changes.
        self.config_axis()
        self.draw_all()
Exemple #12
0
def main():

    for p_level in plot_levels:

        # Set pressure height contour min/max
        if p_level == 925:
            clev_min = 660.
            clev_max = 810.
        elif p_level == 850:
            clev_min = 1435.
            clev_max = 1530.
        elif p_level == 700:
            clev_min = 3090.
            clev_max = 3155.
        elif p_level == 500:
            clev_min = 5800.
            clev_max = 5890.
        else:
            print 'Contour min/max not set for this pressure level'

# Set potential temperature min/max
        if p_level == 925:
            clevpt_min = 300.
            clevpt_max = 312.
        elif p_level == 850:
            clevpt_min = 302.
            clevpt_max = 310.
        elif p_level == 700:
            clevpt_min = 312.
            clevpt_max = 320.
        elif p_level == 500:
            clevpt_min = 325.
            clevpt_max = 332.
        else:
            print 'Potential temperature min/max not set for this pressure level'

# Set specific humidity min/max
        if p_level == 925:
            clevsh_min = 0.012
            clevsh_max = 0.020
        elif p_level == 850:
            clevsh_min = 0.007
            clevsh_max = 0.017
        elif p_level == 700:
            clevsh_min = 0.002
            clevsh_max = 0.010
        elif p_level == 500:
            clevsh_min = 0.001
            clevsh_max = 0.005
        else:
            print 'Specific humidity min/max not set for this pressure level'

        #clevs_col = np.arange(clev_min, clev_max)
        clevs_lin = np.arange(clev_min, clev_max, 5)

        p_level_constraint = iris.Constraint(pressure=p_level)

        for plot_diag in plot_diags:

            for experiment_id in experiment_ids:

                expmin1 = experiment_id[:-1]

                # For each day in cube

                height_pp_file = '%s_408_on_p_levs_mean_by_day.pp' % (
                    experiment_id)
                height_pfile = '%s%s/%s/%s' % (pp_file_path, expmin1,
                                               experiment_id, height_pp_file)
                cube = iris.load_cube(height_pfile, p_level_constraint)

                #print pcube
                #print height_cube

                time_coords = cube.coord('time')
                #add_hour_of_day(pcube, pcube.coord('time'))

                #add_hour_of_day(height_cube, height_cube.coord('time'))

                iris.coord_categorisation.add_day_of_year(cube,
                                                          time_coords,
                                                          name='day_of_year')

                #pcube.remove_coord('time')
                #cube_diff.remove_coord('time')
                #height_cube.remove_coord('time')
                #height_cube_diff.remove_coord('time')

                #p_cube_difference = iris.analysis.maths.subtract(pcube, cube_diff, dim='hour')
                #height_cube_difference = iris.analysis.maths.subtract(height_cube, height_cube_diff, dim='hour')

                #pdb.set_trace()

                #del height_cube, pcube, height_cube_diff, cube_diff

                for t, time_cube in enumerate(
                        cube.slices(['grid_latitude', 'grid_longitude'])):

                    #pdb.set_trace()

                    # Get  time of averagesfor plot title

                    h = u.num2date(
                        np.array(time_cube.coord('time').points,
                                 dtype=float)[0]).strftime('%d%b')

                    #Convert to India time

                    from_zone = tz.gettz('UTC')
                    to_zone = tz.gettz('Asia/Kolkata')

                    h_utc = u.num2date(
                        np.array(time_cube.coord('day_of_year').points,
                                 dtype=float)[0]).replace(tzinfo=from_zone)

                    h_local = h_utc.astimezone(to_zone).strftime('%H%M')

                    fig = plt.figure(**figprops)

                    cmap = plt.cm.RdBu_r

                    ax = plt.axes(projection=ccrs.PlateCarree(),
                                  extent=(lon_low, lon_high,
                                          lat_low + degs_crop_bottom,
                                          lat_high - degs_crop_top))

                    m =\
                        Basemap(llcrnrlon=lon_low,llcrnrlat=lat_low,urcrnrlon=lon_high,urcrnrlat=lat_high, rsphere = 6371229)
                    #pdb.set_trace()
                    lat = cube.coord('grid_latitude').points
                    lon = cube.coord('grid_longitude').points

                    cs = cube.coord_system('CoordSystem')

                    lons, lats = np.meshgrid(lon, lat)
                    lons, lats = iris.analysis.cartography.unrotate_pole\
                                (lons,lats, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude)

                    x, y = m(lons, lats)

                    # if plot_diag=='temp':
                    #     min_contour = clevpt_min
                    #     max_contour = clevpt_max
                    #     cb_label='K'
                    #     main_title='8km  Explicit model (dklyu) minus 8km parametrised model geopotential height (grey contours), potential temperature (colours),\
                    #                       and wind (vectors) %s UTC    %s IST' % (h, h_local)
                    #     tick_interval=2
                    #     clev_number=max_contour-min_contour+1
                    # elif plot_diag=='sp_hum':
                    #     min_contour = clevsh_min
                    #     max_contour = clevsh_max
                    #     cb_label='kg/kg'
                    #     main_title='8km  Explicit model (dklyu) minus 8km parametrised model geopotential height (grey contours), specific humidity (colours),\
                    #                      and wind (vectors) %s UTC    %s IST' % (h, h_local)
                    #     tick_interval=0.002
                    #     clev_number=max_contour-min_contour+0.001

                    # clevs = np.linspace(min_contour, max_contour, clev_number)
                    # #clevs = np.linspace(-3, 3, 32)
                    # cont = plt.contourf(x,y,time_cube.data, clevs, cmap=cmap, extend='both')

                    #cont = iplt.contourf(time_cube, clevs, cmap=cmap, extend='both')

                    cs_lin = iplt.contour(time_cube,
                                          clevs_lin,
                                          colors='#262626',
                                          linewidths=1.)
                    plt.clabel(cs_lin, fontsize=14, fmt='%d', color='black')

                    #del time_cube

                    #plt.clabel(cont, fmt='%d')
                    #ax.stock_img()
                    ax.coastlines(resolution='110m', color='#262626')

                    gl = ax.gridlines(draw_labels=True,
                                      linewidth=0.5,
                                      color='#262626',
                                      alpha=0.5,
                                      linestyle='--')
                    gl.xlabels_top = False
                    gl.ylabels_right = False
                    #gl.xlines = False
                    dx, dy = 10, 10

                    gl.xlocator = mticker.FixedLocator(
                        range(int(lon_low_tick),
                              int(lon_high_tick) + dx, dx))
                    gl.ylocator = mticker.FixedLocator(
                        range(int(lat_low_tick),
                              int(lat_high_tick) + dy, dy))
                    gl.xformatter = LONGITUDE_FORMATTER
                    gl.yformatter = LATITUDE_FORMATTER

                    gl.xlabel_style = {'size': 12, 'color': '#262626'}
                    #gl.xlabel_style = {'color': '#262626', 'weight': 'bold'}
                    gl.ylabel_style = {'size': 12, 'color': '#262626'}

                    # cbar = fig.colorbar(cont, orientation='horizontal', pad=0.05, extend='both')
                    # cbar.set_label('%s' % cb_label, fontsize=10, color='#262626')
                    # #cbar.set_label(time_cube.units, fontsize=10, color='#262626')
                    # cbar.set_ticks(np.arange(min_contour, max_contour+tick_interval,tick_interval))
                    # ticks = (np.arange(min_contour, max_contour+tick_interval,tick_interval))
                    # cbar.set_ticklabels(['${%.1f}$' % i for i in ticks])

                    # cbar.ax.tick_params(labelsize=10, color='#262626')

                    #main_title='Mean Rainfall for EMBRACE Period -%s UTC (%s IST)' % (h, h_local)
                    #main_title=time_cube.standard_name.title().replace('_',' ')
                    #model_info = re.sub(r'[(\']', ' ', model_info)
                    #model_info = re.sub(r'[\',)]', ' ', model_info)
                    #print model_info

                    file_save_name = '%s_%s_%s_hPa_and_geop_height_%s' % (
                        experiment_id, plot_diag, p_level, h)
                    save_dir = '%s%s/%s' % (save_path, experiment_id,
                                            plot_diag)
                    if not os.path.exists('%s' % save_dir):
                        os.makedirs('%s' % (save_dir))

                    #plt.show()

                    #fig.savefig('%s/%s_notitle.png' % (save_dir, file_save_name), format='png', bbox_inches='tight')

                    plt.title('%s UTC' % (h))
                    fig.savefig('%s/%s_short_title.png' %
                                (save_dir, file_save_name),
                                format='png',
                                bbox_inches='tight')

                    #model_info=re.sub('(.{68} )', '\\1\n', str(model_name_convert_title.main(experiment_id)), 0, re.DOTALL)
                    #plt.title('\n'.join(wrap('%s\n%s' % (main_title, model_info), 1000,replace_whitespace=False)), fontsize=16)
                    #fig.savefig('%s/%s.png' % (save_dir, file_save_name), format='png', bbox_inches='tight')

                    fig.clf()
                    plt.close()
                    #del time_cube
                    gc.collect()
ax.set_yticklabels(['i', 't', 'c'])
ax.xaxis.set_major_locator(plt.NullLocator())

belief_pack[0, 0] = 1.0

ax = plt.subplot(313)
ax.set_yticks([0., 4., 8.])
cnt = plt.contourf(belief_time, torch.arange(pomdp.n_actions), adv_vals.T, 40)
for c in cnt.collections:
    c.set_edgecolor("face")
plt.step(belief_time, belief_actions, color='k')
if colorbar:
    heatmap = plt.pcolor(belief_pack)
    cb = plt.colorbar(heatmap, aspect=colorbar_aspect)
    cb.set_label('Advantage values')
    tick_locator = ticker.FixedLocator([0.0, 0.5, 1.0])
    cb.locator = tick_locator
    cb.update_ticks()
ax.set_ylabel('Action')
ax.set_xlabel('Time')
plt.savefig('aloha_' + str(int(colorbar)))
plt.show()

# extra plot for heatmap
plt.figure()

heatmap = plt.pcolor(belief_pack)
plt.gca().set_xlabel('time')

cb = plt.colorbar(heatmap, aspect=25)
tick_locator = ticker.FixedLocator([0.0, 0.5, 1.0])
def main():

 def draw_screen_poly_iris( lats, lons):
    #x, y = m( lons, lats )
    xy = zip(lons,lats)
    poly = Polygon( xy, edgecolor='#262626', facecolor='none', alpha=1, linewidth=2 )
    if (plot_coords[2]=='Southern Indian Ocean'):
       poly = Polygon( xy, edgecolor='red', facecolor='none', alpha=0.4, linewidth=5, label=l+1 ) 

    plt.gca().add_patch(poly)

    legendEntries.append(l+1)
    legendtext.append(plot_coords[2])

 def label(lats, lons,  text):
    #y = xy[1] - 0.15 # shift y-value for label so that it's below the artist   
    lons_label = (np.max(lons)+np.min(lons)) / 2
    lats_label = (np.max(lats) + np.min(lats)) / 2
    x, y = (lons_label, lats_label ) 
    #plt.text(x, y, text, color='#262626', ha="center", va="center", size=32, backgroundcolor='white', alpha=0.4 )
    font0 = FontProperties()
    font0.set_family('sans-serif')
   
    plt.text(x, y, text, color='black', ha="center", va="center", size=64 , fontweight='bold', fontproperties=font0)
    if (plot_coords[2]=='Southern Indian Ocean'):
       plt.text(x, y, text, color='red', ha="center", va="center", size=64, fontproperties=font0)

#experiment_ids = ['djzny', 'djzns', 'djznw', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq' ] 
 #experiment_ids = ['djznq', 'djzny', 'djzns', 'djznu', 'dkbhu', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq', 'dkhgu'] 
 experiment_ids = ['djznq' ] 
 #experiment_ids = ['dkhgu','dkjxq']
# Bit above Western Ghats
 lats_1 = [20, 28, 28, 20]
 lons_1 = [67, 67, 71, 71]
 label_1 = 'Bit above Western Ghats'

# Western Ghats
#lats_2 = [8, 21, 21, 8]
#lons_2 = [72, 72, 77, 77]
#label_2 = 'Western Ghats'

# Western Ghats
 lats_2 = [8.75, 22., 22., 8.75]
 lons_2 = [73.75, 70., 73.75, 77.75]
 label_2 = 'Western Ghats'

# Bay of Bengal
 lats_3 = [10, 25, 25, 10]
 lons_3 = [80, 80, 100, 100]
 label_3 = 'Bay of Bengal'

# Southern , western Indian Ocean
 lats_4 = [-10, 5, 5, -10]
 lons_4 = [64.12, 64.12, 80, 80]
 label_4 = 'Southern, western Indian Ocean'

# Southern , western Indian Ocean
 lats_5 = [-10, 5, 5, -10]
 lons_5 = [80, 80, 101.87, 101.87]
 label_5 = 'Southern, eastern Indian Ocean'

# Southern Indian Ocean
 lats_6 = [-10, 5, 5, -10]
 lons_6 = [64.12, 64.12, 101.87, 101.87]
 label_6 = 'Southern Indian Ocean'

# Monsoon Trough
 lats_7 = [21., 16., 22., 27]
 lons_7 = [73., 83., 87., 75]
 label_7 = 'Monsoon Trough'

 # Himalayas
 lats_8 = [25.8, 26.3, 30., 30., 28.5, 27.8, 27.8, 25.8]
 lons_8 = [90., 83., 76.3, 82.7, 86.3, 90., 95., 95.]
 label_8 = 'Himalayas'

#Ganga Basin
 lats_9 = [22, 27., 30., 26.2, 25.8, 22]
 lons_9 = [87, 75, 76.3, 83, 90., 90.]
 label_9 = 'Ganga Basin'

 lats_poly = lats_1, lats_2, lats_3, lats_4, lats_5, lats_6, lats_7, lats_8, lats_9
 lons_poly = lons_1, lons_2, lons_3, lons_4, lons_5, lons_6, lons_7, lons_8, lons_9
 labels = label_1, label_2, label_3, label_4, label_5, label_6, label_7, label_8, label_9
 for experiment_id in experiment_ids:

  expmin1 = experiment_id[:-1]
  pfile = '/nfs/a90/eepdw/Data/EMBRACE/Mean_State/pp_files/%s/%s/%s.pp' % (expmin1, experiment_id, pp_file)
  if (experiment_id=='djznq'):
     pfile = '/nfs/a90/eepdw/Data/EMBRACE/Mean_State/pp_files/%s/%s/rain_mean.pp' % (expmin1, experiment_id)

  legendEntries=[]
  legendtext=[]

  #pc =  iris(pfile)
  pcube = iris.load_cube(pfile)
  print pcube
     #print pc
 
 # Get min and max latitude/longitude and unrotate  to get min/max corners to crop plot automatically - otherwise end with blank bits on the edges 
  if (experiment_id=='djznq'):
   lats = pcube.coord('grid_latitude').points
   lons = pcube.coord('grid_longitude').points
  else:
   lats = pcube.coord('latitude').points
   lons = pcube.coord('longitude').points
  
  cs = pcube.coord_system('CoordSystem')
  if isinstance(cs, iris.coord_systems.RotatedGeogCS):

      print 'Rotated CS %s' % cs
     
      lon_low= np.min(lons)
      lon_high = np.max(lons)
      lat_low = np.min(lats)
      lat_high = np.max(lats)

      lon_corners, lat_corners = np.meshgrid((lon_low, lon_high), (lat_low, lat_high))
      
      lon_corner_u,lat_corner_u = unrotate.unrotate_pole(lon_corners, lat_corners, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude)
      lon_low = lon_corner_u[0,0]
      lon_high = lon_corner_u[0,1]
      lat_low = lat_corner_u[0,0]
      lat_high = lat_corner_u[1,0]

  else: 
      lon_low= np.min(lons)
      lon_high = np.max(lons)
      lat_low = np.min(lats)
      lat_high = np.max(lats)

  #lon_low= 62
  #lon_high = 102
  #lat_low = -7
  #lat_high = 33

  #lon_high_box = 101.866 
  #lon_low_box = 64.115
  #lat_high_box = 33.
  #lat_low_box =-6.79

  #lon_high = 101.866 
  #lon_low = 64.115
  #lat_high = 33.
  #lat_low =-6.79

  lon_low_tick=lon_low -(lon_low%divisor)
  lon_high_tick=math.ceil(lon_high/divisor)*divisor

  lat_low_tick=lat_low - (lat_low%divisor)
  lat_high_tick=math.ceil(lat_high/divisor)*divisor
 
  print lat_high_tick
  print lat_low_tick
  plt.figure(figsize=(8,8))
         
  cmap=cm.s3pcpn_l
    
  ax = plt.axes(projection=ccrs.PlateCarree(), extent=(lon_low,lon_high,lat_low+degs_crop_bottom,lat_high-degs_crop_top))
  
  #ax = plt.axes(projection=ccrs.PlateCarree(), extent=(lon_low,lon_high,lat_low,lat_high))

  #ax = plt.axes(projection=ccrs.PlateCarree())

  clevs = np.linspace(min_contour, max_contour,256)

  pcubeplot=iris.analysis.maths.multiply(pcube,3600)

  cont = iplt.contourf(pcubeplot, clevs, cmap=cmap, extend='both')
                     
  #plt.clabel(cont, fmt='%d')
  #ax.stock_img()
  ax.coastlines(resolution='110m', color='#262626') 
                     
  gl = ax.gridlines(draw_labels=True,linewidth=0.5, color='#262626', alpha=0.5, linestyle='--')
  gl.xlabels_top = False
  gl.ylabels_right = False
            #gl.xlines = False
  dx, dy = 10, 10

  gl.xlocator = mticker.FixedLocator(range(int(lon_low_tick),int(lon_high_tick)+dx,dx))
  gl.ylocator = mticker.FixedLocator(range(int(lat_low_tick),int(lat_high_tick)+dy,dy))
  gl.xformatter = LONGITUDE_FORMATTER
  gl.yformatter = LATITUDE_FORMATTER
  
  gl.xlabel_style = {'size': 12, 'color':'#262626'}
  #gl.xlabel_style = {'color': '#262626', 'weight': 'bold'}
  gl.ylabel_style = {'size': 12, 'color':'#262626'}         

  cbar = plt.colorbar(cont, orientation='horizontal', pad=0.05, extend='both')
  cbar.set_label('mm/h', fontsize=10, color='#262626') 
  #cbar.set_label(pcube.units, fontsize=10, color='#262626')
  cbar.set_ticks(np.arange(min_contour, max_contour+tick_interval,tick_interval))
  ticks = (np.arange(min_contour, max_contour+tick_interval,tick_interval))
  cbar.set_ticklabels(['%.1f' % i for i in ticks])
  cbar.ax.tick_params(labelsize=10, color='#262626')
  
  main_title='Mean Rainfall for EMBRACE Period (smoothed to 24km)'
  #main_title=pcube.standard_name.title().replace('_',' ')
  model_info=re.sub('(.{68} )', '\\1\n', str(model_name_convert_title.main(experiment_id)), 0, re.DOTALL)
  #model_info = re.sub(r'[(\']', ' ', model_info)
  #model_info = re.sub(r'[\',)]', ' ', model_info)
  #print model_info
  for l,plot_coords in enumerate(zip(lats_poly,lons_poly, labels)):
    #colour = cmap(1.*(l*2)/(NUM_COLOURS*2))
    draw_screen_poly_iris( plot_coords[0], plot_coords[1])
    label(plot_coords[0], plot_coords[1], l+1)

  if not os.path.exists('%s%s/%s' % (save_path, experiment_id, pp_file)): os.makedirs('%s%s/%s' % (save_path, experiment_id, pp_file))

  plt.savefig('%s%s/%s/%s_%s_area_boxes_notitle.png' % (save_path, experiment_id, pp_file, experiment_id, pp_file), format='png', bbox_inches='tight')

  plt.title('\n'.join(wrap('%s\n%s' % (main_title, model_info), 1000,replace_whitespace=False)), fontsize=16)
 
  #plt.show()
 
  plt.savefig('%s%s/%s/%s_%s_area_boxes.png' % (save_path, experiment_id, pp_file, experiment_id, pp_file), format='png', bbox_inches='tight')
  
  plt.close()
Exemple #15
0
    def __call__(self,
                 field,
                 ct=False,
                 logscale=True,
                 log=False,
                 ax=None,
                 bnds=[0, 360, -90, 90],
                 title='',
                 units='',
                 cbfrac=0.11,
                 projection_name='PlateCarree',
                 **plt_kwargs):

        # Central longitude must be between -180 and 180 (greenwich meridian is 0)
        #lon_0 = (bnds[0] + bnds[1])/2 - 360
        lon_0 = (bnds[0] + bnds[1]) / 2

        #print('lon_0', lon_0)

        if projection_name == 'PlateCarree':
            proj = cart.crs.PlateCarree(central_longitude=lon_0)
        elif projection_name == 'Robinson':
            proj = cart.crs.Robinson(central_longitude=lon_0)
        elif projection_name == 'AlbersEqualArea':
            proj = cart.crs.AlbersEqualArea(central_longitude=lon_0)
        else:
            print('Projection name is invalid.')

        if projection_name == 'PlateCarree':
            proj2 = cart.crs.PlateCarree()
        elif projection_name == 'Robinson':
            proj2 = cart.crs.Robinson()
        elif projection_name == 'AlbersEqualArea':
            proj2 = cart.crs.AlbersEqualArea()
        else:
            print('Projection name is invalid.')

        if ax is None:
            fig, ax = plt.subplots(figsize=(12, 6))

        #print(self.orig_grid.shape)
        #print(da.values.shape)
        #print(self.new_grid.shape)

        vmax = plt_kwargs.pop('vmax', field.max())
        vmin = plt_kwargs.pop('vmin', field.min())

        m = plt.axes(projection=proj)
        x, y = field.lon, field.lat

        #ax= plt.gca()

        pardiff = 30.
        merdiff = 60.

        if np.abs(bnds[1] - bnds[0]) < 180:
            merdiff = 30.
        #if np.abs(bnds[1] - bnds[0]) < 90:
        #    merdiff = 15.
        #if np.abs(bnds[3]- bnds[2]) < 90:
        #    pardiff = 15.

        par = np.arange(-90., 90. + pardiff, pardiff)
        mer = np.arange(-180., 180. + merdiff, merdiff)

        ax = plt.gca()
        ax.set_xticks(mer, crs=proj2)
        ax.set_yticks(par, crs=proj2)
        lon_formatter = LongitudeFormatter(zero_direction_label=True)
        lat_formatter = LatitudeFormatter()
        ax.xaxis.set_major_formatter(lon_formatter)
        ax.yaxis.set_major_formatter(lat_formatter)
        ax.get_yaxis().set_tick_params(direction='out')
        ax.get_xaxis().set_tick_params(direction='out')

        ax.set_extent((bnds[0], bnds[1], bnds[2], bnds[3]), crs=proj2)

        # Find index where data is splitted for mapping
        #split_lon_idx = round(x.shape[1]/(360/(lon_0 if lon_0>0 else lon_0+360)))
        #norm=LogNorm(vmin=vmin, vmax=vmax)

        lognorm = LogNorm(vmin=vmin, vmax=vmax)

        if log:
            p = m.pcolormesh(x,
                             y,
                             field,
                             vmax=vmax,
                             vmin=vmin,
                             norm=lognorm,
                             transform=proj2,
                             zorder=1,
                             **plt_kwargs)
        else:
            p = m.pcolormesh(x,
                             y,
                             field,
                             vmax=vmax,
                             vmin=vmin,
                             transform=proj2,
                             zorder=1,
                             **plt_kwargs)
        #p = m.pcolormesh(x[:,split_lon_idx:], y[:,split_lon_idx:], field[:,split_lon_idx:],
        #                 vmax=vmax, vmin=vmin, transform=cart.crs.PlateCarree(), zorder=2, **plt_kwargs)

        if ct:
            ctstep = np.abs(vmax - vmin) / 20
            ctlevels = np.arange(vmin, vmax + ctstep, ctstep)
            ct = plt.contour(x,
                             y,
                             field,
                             colors='k',
                             levels=ctlevels,
                             linewidths=1,
                             transform=proj2)
            if np.any(np.round(ct.levels, 5) == 0):
                ct.collections[np.where(
                    np.round(ct.levels, 5) == 0)[0][0]].set_linewidth(0)
                #ax.clabel(ct, fontsize=9, inline=1, fmt='%1.1f')
                for line in ct.collections:
                    if line.get_linestyle() != [(None, None)]:
                        line.set_linestyle([(0, (8.0, 8.0))])

        gl = ax.gridlines(crs=proj2,
                          linewidth=0.5,
                          color='black',
                          alpha=0.6,
                          linestyle='-.',
                          zorder=10)
        gl.xlocator = mticker.FixedLocator(mer)
        gl.ylocator = mticker.FixedLocator(par)

        #ax.set_facecolor('grey')

        m.add_feature(cart.feature.LAND,
                      edgecolor='k',
                      facecolor='grey',
                      zorder=3)
        #m.add_feature(cart.feature.COASTLINE,linewidth=0.5, zorder=15)
        plt.title(title)
        orient = 'vertical'
        if np.abs(bnds[1] - bnds[0]) > (np.abs(bnds[3] - bnds[2]) - 10):
            orient = 'horizontal'

        cb = plt.colorbar(p,
                          label=units,
                          fraction=cbfrac,
                          pad=0.11,
                          orientation=orient)

        #cb.set_ticks([-0.4,1.0,1.6,2.0])
        #cb.ax.set_ticklabels([-0.4,1.0,1.6,2.0])
        if logscale:
            if vmin >= 0:
                ticklabels = [vmin, 0.1, 1.0, vmax]
            else:
                #ticklabels = [vmin,-0.01,0,0.01,vmax]
                #ticklabels = [vmin,-0.1,0,0.1,vmax]
                ticklabels = [vmin, -0.1, 0, 0.1, vmax]
                #ticklabels = [vmin,-1.0,-0.1,0.1,1.0,vmax]
            cb.set_ticks(ticklabels)
            cb.ax.set_xticklabels(ticklabels)
        cb.ax.tick_params(labelsize=24)

        return m, ax
Exemple #16
0
def parallel_coordinates(frame, class_column, cols=None, ax=None, color=None,
                     use_columns=False, xticks=None, colormap=None, 
                     title = None, cblabel = None, savetitle = None,
                     **kwds):
    import matplotlib.pyplot as plt
    import matplotlib as mpl
    from matplotlib import ticker
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    
    n = len(frame)
    class_col = frame[class_column]
    class_min = np.amin(class_col)
    class_max = np.amax(class_col)

    if cols is None:
        df = frame.drop(class_column, axis=1)
    else:
        df = frame[cols]

    #used_legends = set([])
    fig = plt.figure(1, figsize=(9,4.5))
    ncols = len(df.columns)
    Colorm = plt.get_cmap(colormap)

    #gs0 = gridspec.GridSpec(1, 2, height_ratios=[1], 
    #                       width_ratios=[0.9, 0.1],)
    #gs0.update(left=0.05, right=0.95, bottom=0.08, top=0.93, 
    #           wspace=0.0, hspace=0.03)

    #gs1 = GridSpec(3, 3)
    #gs1.update(left=0.05, right=0.48, wspace=0.05)
#gs00 = gridspec.GridSpecFromSubplotSpec(3, 3, subplot_spec=gs0[0])

    gs = gridspec.GridSpec(1,ncols - 1, 
                           height_ratios=[1], 
                           width_ratios=[1]*(ncols - 1))
    gs.update(left=0.05, right=0.85, wspace=0.0)
    
    gs_cb = gridspec.GridSpec(1,1, 
                           height_ratios=[1], 
                           width_ratios=[1])
    gs_cb.update(left=0.92, right=0.95)
    
    
    
    #fig, axes = plt.subplots(1, ncols - 1, sharey=False, figsize=(8,5))
    
    x = [i for i, _ in enumerate(df.columns)]
    
    if title is not None:    
        plt.suptitle(title, fontsize=16)
    
    min_max_range = {}
    cols = df.columns
    for col in cols:
        min_max_range[col] = [df[col].min(), df[col].max(), np.ptp(df[col])]
        df[col] = np.true_divide(df[col] - df[col].min(), np.ptp(df[col])) 
    
    for i in range(ncols - 1):
        ax = plt.subplot(gs[0,i])
        ax.set_ylim([-0.1,1.1])
        for idx in df.index:
            kls = class_col.iat[idx]
            
            ax.plot(x, df.loc[idx, cols], linewidth=2, alpha = 0.5,
                    color=Colorm((kls - class_min)/(class_max-class_min)))
            
        ax.set_xlim([x[i], x[i+1]])
        
        '''
        if i == (ncols - 1):
            ax = plt.twinx(ax)
            dim = ncols - 1
            ax.xaxis.set_major_locator(ticker.FixedLocator([x[-2], x[-1]]))
            set_ticks_for_axis(dim, ax, min_max_range, df, cols, ticks=6)
            ax.set_xticklabels([cols[-2], cols[-1]])
        '''
            

    #print(gs.get_subplot_params())
    for i in range(ncols - 1):    
        ax = plt.subplot(gs[0,i])               
    #for i, ax in enumerate(axes):
        ax.xaxis.set_major_locator(ticker.FixedLocator([i]))
        set_ticks_for_axis(i, ax, min_max_range, df, cols, ticks=6)
        ax.set_xticklabels([cols[i]])
        
    
    # Move the final axis' ticks to the right-hand side
    last_ax = plt.subplot(gs[0,ncols - 2])
    ax = plt.twinx(last_ax)
    #ax.set_ylim([-0.1,1.1])
    #ax = plt.twinx(axes[-1])
    #dim = len(axes)
    dim = ncols - 1
    ax.xaxis.set_major_locator(ticker.FixedLocator([x[-2], x[-1]]))
    set_ticks_for_axis(dim, ax, min_max_range, df, cols, ticks=6)
    ax.set_xticklabels([cols[-2], cols[-1]])
    
    
    # Remove space between subplots
    #plt.subplots_adjust(right = 0.75)
    

        
    #a = twiny(ax)
    #print(ax.get_aspect())
    #[0.85, 0.1, 0.03, 0.73]
    #divider = make_axes_locatable(axes)
    #cbaxes = divider.append_axes("right", size="5%", pad=0.45)
    #plt.colorbar(cax = cbaxes, cmap = Colorm)
    #cbaxes = fig.add_axes([0.85, 0.12, 0.03, 0.76]) 
   
    #cb = plt.colorbar(ax1, cax = cbaxes) 
    #divider = make_axes_locatable(ax)
    #cax = divider.append_axes("right", size="5%", pad=0.35)
    #cbar_ax = fig.add_axes([0.85, 0.0, 0.05, 0.8])
    
    

    #ax = fig.add_subplot(231)
    bounds = np.linspace(class_min,class_max,10)
    #ax = plt.gca()
    
    
    
    #cax = plt.subplot(gs[0,ncols - 1])
    cax = plt.subplot(gs_cb[0,0])
    #pos1 = cax.get_position()
    #pos2 = [pos1.x0 + 0.1, pos1.y0,  pos1.width, pos1.height] 
    #cax.set_position(pos2)
    #cax,_ = mpl.colorbar.make_axes(ax)
 
    cb = mpl.colorbar.ColorbarBase(cax, cmap=Colorm, 
                                   spacing='proportional', ticks=bounds, 
                                   boundaries=bounds, format='%.2f', 
                                   label = cblabel)
    #cb.set_label(cblabel)
    plt.gcf().subplots_adjust(right=0.15)
    
    
    #plt.tight_layout(h_pad = 2)
    if savetitle is not None:
        plt.savefig(savetitle, dpi=400, bbox_inches="tight")
    plt.show()
    return fig
Exemple #17
0
y_wrd = y_wrd[::-1]
xx_wrd, yy_wrd = np.meshgrid(x_wrd, y_wrd)

ax = plt.axes(projection=ccrs.PlateCarree())
ax.pcolormesh(xx_wrd, yy_wrd, smap_9km_mean_1, transform=ccrs.PlateCarree())

gl = ax.gridlines(crs=ccrs.PlateCarree(),
                  draw_labels=True,
                  linewidth=2,
                  color='gray',
                  alpha=0.5,
                  linestyle='--')
gl.xlabels_top = False
gl.ylabels_left = False
gl.xlines = False
gl.xlocator = mticker.FixedLocator([-180, -45, 0, 45, 180])
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
gl.xlabel_style = {'size': 15, 'color': 'gray'}
gl.xlabel_style = {'color': 'red', 'weight': 'bold'}

map_wrd_mesh = plt.pcolormesh(xx_wrd,
                              yy_wrd,
                              smap_9km_mean_1,
                              vmin=0,
                              vmax=0.5,
                              cmap='gist_earth_r')
# ax.set_extent(map_extent)
ax.imshow(smap_9km_mean_1,
          origin='upper',
          transform=ccrs.PlateCarree(),
Exemple #18
0
    def __init__(self, axes, crs, draw_labels=False, xlocator=None,
                 ylocator=None, collection_kwargs=None,
                 xformatter=None, yformatter=None, dms=False,
                 x_inline=None, y_inline=None, auto_inline=True,
                 xlim=None, ylim=None, rotate_labels=None,
                 xlabel_style=None, ylabel_style=None, labels_bbox_style=None,
                 xpadding=5, ypadding=5, offset_angle=25,
                 auto_update=False, formatter_kwargs=None):
        """
        Object used by :meth:`cartopy.mpl.geoaxes.GeoAxes.gridlines`
        to add gridlines and tick labels to a map.

        Parameters
        ----------
        axes
            The :class:`cartopy.mpl.geoaxes.GeoAxes` object to be drawn on.
        crs
            The :class:`cartopy.crs.CRS` defining the coordinate system that
            the gridlines are drawn in.
        draw_labels: optional
            Toggle whether to draw labels. For finer control, attributes of
            :class:`Gridliner` may be modified individually. Defaults to False.

            - string: "x" or "y" to only draw labels of the respective
              coordinate in the CRS.
            - list: Can contain the side identifiers and/or coordinate
              types to select which ones to draw.
              For all labels one would use
              `["x", "y", "top", "bottom", "left", "right", "geo"]`.
            - dict: The keys are the side identifiers
              ("top", "bottom", "left", "right") and the values are the
              coordinates ("x", "y"); this way you can precisely
              decide what kind of label to draw and where.
              For x labels on the bottom and y labels on the right you
              could pass in `{"bottom": "x", "left": "y"}`.

            Note that, by default, x and y labels are not drawn on left/right
            and top/bottom edges respectively, unless explicitly requested.

        xlocator: optional
            A :class:`matplotlib.ticker.Locator` instance which will be used
            to determine the locations of the gridlines in the x-coordinate of
            the given CRS. Defaults to None, which implies automatic locating
            of the gridlines.
        ylocator: optional
            A :class:`matplotlib.ticker.Locator` instance which will be used
            to determine the locations of the gridlines in the y-coordinate of
            the given CRS. Defaults to None, which implies automatic locating
            of the gridlines.
        xformatter: optional
            A :class:`matplotlib.ticker.Formatter` instance to format labels
            for x-coordinate gridlines. It defaults to None, which implies the
            use of a :class:`cartopy.mpl.ticker.LongitudeFormatter` initiated
            with the ``dms`` argument, if the crs is of
            :class:`~cartopy.crs.PlateCarree` type.
        yformatter: optional
            A :class:`matplotlib.ticker.Formatter` instance to format labels
            for y-coordinate gridlines. It defaults to None, which implies the
            use of a :class:`cartopy.mpl.ticker.LatitudeFormatter` initiated
            with the ``dms`` argument, if the crs is of
            :class:`~cartopy.crs.PlateCarree` type.
        collection_kwargs: optional
            Dictionary controlling line properties, passed to
            :class:`matplotlib.collections.Collection`. Defaults to None.
        dms: bool
            When default locators and formatters are used,
            ticks are able to stop on minutes and seconds if minutes
            is set to True, and not fraction of degrees.
        x_inline: optional
            Toggle whether the x labels drawn should be inline.
        y_inline: optional
            Toggle whether the y labels drawn should be inline.
        auto_inline: optional
            Set x_inline and y_inline automatically based on projection.
        xlim: optional
            Set a limit for the gridlines so that they do not go all the
            way to the edge of the boundary. xlim can be a single number or
            a (min, max) tuple. If a single number, the limits will be
            (-xlim, +xlim).
        ylim: optional
            Set a limit for the gridlines so that they do not go all the
            way to the edge of the boundary. ylim can be a single number or
            a (min, max) tuple. If a single number, the limits will be
            (-ylim, +ylim).
        rotate_labels: optional, bool, str
            Allow the rotation of non-inline labels.

            - False: Do not rotate the labels.
            - True: Rotate the labels parallel to the gridlines.
            - None: no rotation except for some projections (default).
            - A float: Rotate labels by this value in degrees.

        xlabel_style: dict
            A dictionary passed through to ``ax.text`` on x label creation
            for styling of the text labels.
        ylabel_style: dict
            A dictionary passed through to ``ax.text`` on y label creation
            for styling of the text labels.
        labels_bbox_style: dict
            bbox style for all text labels
        xpadding: float
            Padding for x labels. If negative, the labels are
            drawn inside the map.
        ypadding: float
            Padding for y labels. If negative, the labels are
            drawn inside the map.
        offset_angle: float
            Difference of angle in degrees from 90 to define when
            a label must be flipped to be more readable.
            For example, a value of 10 makes a vertical top label to be
            flipped only at 100 degrees.
        auto_update: bool
            Whether to redraw the gridlines and labels when the figure is
            updated.
        formatter_kwargs: dict, optional
            Options passed to the default formatters.
            See :class:`~cartopy.mpl.ticker.LongitudeFormatter` and
            :class:`~cartopy.mpl.ticker.LatitudeFormatter`

        Notes
        -----
        The "x" and "y" labels for locators and formatters do not necessarily
        correspond to X and Y, but to the first and second coordinates of the
        specified CRS. For the common case of PlateCarree gridlines, these
        correspond to longitudes and latitudes. Depending on the projection
        used for the map, meridians and parallels can cross both the X axis and
        the Y axis.
        """
        self.axes = axes

        #: The :class:`~matplotlib.ticker.Locator` to use for the x
        #: gridlines and labels.
        if xlocator is not None:
            if not isinstance(xlocator, mticker.Locator):
                xlocator = mticker.FixedLocator(xlocator)
            self.xlocator = xlocator
        elif isinstance(crs, PlateCarree):
            self.xlocator = LongitudeLocator(dms=dms)
        else:
            self.xlocator = classic_locator

        #: The :class:`~matplotlib.ticker.Locator` to use for the y
        #: gridlines and labels.
        if ylocator is not None:
            if not isinstance(ylocator, mticker.Locator):
                ylocator = mticker.FixedLocator(ylocator)
            self.ylocator = ylocator
        elif isinstance(crs, PlateCarree):
            self.ylocator = LatitudeLocator(dms=dms)
        else:
            self.ylocator = classic_locator

        formatter_kwargs = {
            **(formatter_kwargs or {}),
            "dms": dms,
        }

        if xformatter is None:
            if isinstance(crs, PlateCarree):
                xformatter = LongitudeFormatter(**formatter_kwargs)
            else:
                xformatter = classic_formatter()
        #: The :class:`~matplotlib.ticker.Formatter` to use for the lon labels.
        self.xformatter = xformatter

        if yformatter is None:
            if isinstance(crs, PlateCarree):
                yformatter = LatitudeFormatter(**formatter_kwargs)
            else:
                yformatter = classic_formatter()
        #: The :class:`~matplotlib.ticker.Formatter` to use for the lat labels.
        self.yformatter = yformatter

        # Draw label argument
        if isinstance(draw_labels, list):

            # Select to which coordinate it is applied
            if 'x' not in draw_labels and 'y' not in draw_labels:
                value = True
            elif 'x' in draw_labels and 'y' in draw_labels:
                value = ['x', 'y']
            elif 'x' in draw_labels:
                value = 'x'
            else:
                value = 'y'

            #: Whether to draw labels on the top of the map.
            self.top_labels = value if 'top' in draw_labels else False

            #: Whether to draw labels on the bottom of the map.
            self.bottom_labels = value if 'bottom' in draw_labels else False

            #: Whether to draw labels on the left hand side of the map.
            self.left_labels = value if 'left' in draw_labels else False

            #: Whether to draw labels on the right hand side of the map.
            self.right_labels = value if 'right' in draw_labels else False

            #: Whether to draw labels near the geographic limits of the map.
            self.geo_labels = value if 'geo' in draw_labels else False

        elif isinstance(draw_labels, dict):

            self.top_labels = draw_labels.get('top', False)
            self.bottom_labels = draw_labels.get('bottom', False)
            self.left_labels = draw_labels.get('left', False)
            self.right_labels = draw_labels.get('right', False)
            self.geo_labels = draw_labels.get('geo', False)

        else:

            self.top_labels = draw_labels
            self.bottom_labels = draw_labels
            self.left_labels = draw_labels
            self.right_labels = draw_labels
            self.geo_labels = draw_labels

        for loc in 'top', 'bottom', 'left', 'right', 'geo':
            value = getattr(self, f'{loc}_labels')
            if isinstance(value, str):
                value = value.lower()
            if (not isinstance(value, (list, bool)) and
                    value not in ('x', 'y')):
                raise ValueError(f"Invalid draw_labels argument: {value}")

        if auto_inline:
            if isinstance(self.axes.projection, _X_INLINE_PROJS):
                self.x_inline = True
                self.y_inline = False
            elif isinstance(self.axes.projection, _POLAR_PROJS):
                self.x_inline = False
                self.y_inline = True
            else:
                self.x_inline = False
                self.y_inline = False

        # overwrite auto_inline if necessary
        if x_inline is not None:
            #: Whether to draw x labels inline
            self.x_inline = x_inline
        elif not auto_inline:
            self.x_inline = False

        if y_inline is not None:
            #: Whether to draw y labels inline
            self.y_inline = y_inline
        elif not auto_inline:
            self.y_inline = False

        # Apply inline args
        if not draw_labels:
            self.inline_labels = False
        elif self.x_inline and self.y_inline:
            self.inline_labels = True
        elif self.x_inline:
            self.inline_labels = "x"
        elif self.y_inline:
            self.inline_labels = "y"
        else:
            self.inline_labels = False

        # Gridline limits so that the gridlines don't extend all the way
        # to the edge of the boundary
        self.xlim = xlim
        self.ylim = ylim

        #: Whether to draw the x gridlines.
        self.xlines = True

        #: Whether to draw the y gridlines.
        self.ylines = True

        #: A dictionary passed through to ``ax.text`` on x label creation
        #: for styling of the text labels.
        self.xlabel_style = xlabel_style or {}

        #: A dictionary passed through to ``ax.text`` on y label creation
        #: for styling of the text labels.
        self.ylabel_style = ylabel_style or {}

        #: bbox style for grid labels
        self.labels_bbox_style = (
            labels_bbox_style or {'pad': 0, 'visible': False})

        #: The padding from the map edge to the x labels in points.
        self.xpadding = xpadding

        #: The padding from the map edge to the y labels in points.
        self.ypadding = ypadding

        #: Control the rotation of labels.
        if rotate_labels is None:
            rotate_labels = (
                self.axes.projection.__class__ in _ROTATE_LABEL_PROJS)
        if not isinstance(rotate_labels, (bool, float, int)):
            raise ValueError("Invalid rotate_labels argument")
        self.rotate_labels = rotate_labels

        self.offset_angle = offset_angle

        # Current transform
        self.crs = crs

        # if the user specifies tick labels at this point, check if they can
        # be drawn. The same check will take place at draw time in case
        # public attributes are changed after instantiation.
        if draw_labels and not (x_inline or y_inline or auto_inline):
            self._assert_can_draw_ticks()

        #: The number of interpolation points which are used to draw the
        #: gridlines.
        self.n_steps = 100

        #: A dictionary passed through to
        #: ``matplotlib.collections.LineCollection`` on grid line creation.
        self.collection_kwargs = collection_kwargs

        #: The x gridlines which were created at draw time.
        self.xline_artists = []

        #: The y gridlines which were created at draw time.
        self.yline_artists = []

        # List of all labels (Label objects)
        self._labels = []

        # Draw status
        self._drawn = False
        self._auto_update = auto_update

        # Check visibility of labels at each draw event
        # (or once drawn, only at resize event ?)
        self.axes.figure.canvas.mpl_connect('draw_event', self._draw_event)
Exemple #19
0
def main():

 #experiment_ids = ['djzns', 'djznq', 'djzny', 'djznw', 'dkhgu', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq','dkbhu' ] 
 
 experiment_ids = ['djzny' ] 
 for experiment_id in experiment_ids:
 
  expmin1 = experiment_id[:-1]
  pfile = '/projects/cascade/pwille/moose_retrievals/%s/%s/%s.pp' % (expmin1, experiment_id, pp_file)

     #pc =  iris(pfile)
  pcube = iris.load_cube(pfile)
  print pcube
     #print pc
 
 # Get min and max latitude/longitude and unrotate  to get min/max corners to crop plot automatically - otherwise end with blank bits on the edges 
  lats = pcube.coord('grid_latitude').points
  lons = pcube.coord('grid_longitude').points
  
  cs = pcube.coord_system('CoordSystem')
  if isinstance(cs, iris.coord_systems.RotatedGeogCS):

      print 'Rotated CS %s' % cs
     
      lon_low= np.min(lons)
      lon_high = np.max(lons)
      lat_low = np.min(lats)
      lat_high = np.max(lats)

      lon_corners, lat_corners = np.meshgrid((lon_low, lon_high), (lat_low, lat_high))
      
      lon_corner_u,lat_corner_u = unrotate.unrotate_pole(lon_corners, lat_corners, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude)
      lon_low = lon_corner_u[0,0]
      lon_high = lon_corner_u[0,1]
      lat_low = lat_corner_u[0,0]
      lat_high = lat_corner_u[1,0]

  else: 
      lon_low= np.min(lons)
      lon_high = np.max(lons)
      lat_low = np.min(lats)
      lat_high = np.max(lats)

  lon_low_tick=lon_low -(lon_low%divisor)
  lon_high_tick=math.ceil(lon_high/divisor)*divisor

  lat_low_tick=lat_low - (lat_low%divisor)
  lat_high_tick=math.ceil(lat_high/divisor)*divisor
 
  print lat_high_tick
  print lat_low_tick
  plt.figure(figsize=(8,8))
         
  cmap= cmap=plt.cm.RdBu_r
  
  ax = plt.axes(projection=ccrs.PlateCarree(), extent=(lon_low,lon_high,lat_low+degs_crop_bottom,lat_high-degs_crop_top))
  
 
  clevs = np.linspace(min_contour, max_contour,256)
  cont = iplt.contourf(pcube, clevs, cmap=cmap, extend='both')
                     
  #plt.clabel(cont, fmt='%d')
  #ax.stock_img()
  ax.coastlines(resolution='110m', color='#262626') 
                     
  gl = ax.gridlines(draw_labels=True,linewidth=0.5, color='#262626', alpha=0.5, linestyle='--')
  gl.xlabels_top = False
  gl.ylabels_right = True
            #gl.xlines = False
  dx, dy = 10, 10
  gl.xlocator = mticker.FixedLocator(range(int(lon_low_tick),int(lon_high_tick)+dx,dx))
  gl.ylocator = mticker.FixedLocator(range(int(lat_low_tick),int(lat_high_tick)+dy,dy))
  gl.xformatter = LONGITUDE_FORMATTER
  gl.yformatter = LATITUDE_FORMATTER
  
  gl.xlabel_style = {'size': 12, 'color':'#262626'}
  #gl.xlabel_style = {'color': '#262626', 'weight': 'bold'}
  gl.ylabel_style = {'size': 12, 'color':'#262626'}         
 
  cbar = plt.colorbar(cont, orientation='horizontal', pad=0.05, extend='both', format = '%d')
  #cbar.set_label('') 
  cbar.set_label(pcube.units)
  cbar.set_ticks(np.arange(min_contour, max_contour+tick_interval,tick_interval))
  ticks = (np.arange(min_contour, max_contour+tick_interval,tick_interval))
  cbar.set_ticklabels(['%d' % i for i in ticks])
  main_title=pcube.standard_name.title().replace('_',' ')
  model_info=re.sub('(.{75})', '\\1\n', str(model_name_convert_title.main(experiment_id)), 0, re.DOTALL)
  model_info = re.sub(r'[(\']', ' ', model_info)
  model_info = re.sub(r'[\',)]', ' ', model_info)
  print model_info
  plt.title('\n'.join(wrap('%s\n%s' % (main_title, model_info), 1000,replace_whitespace=False)), fontsize=12)
 
  plt.show()

  if not os.path.exists('/home/pwille/figures/%s/%s' % (experiment_id, plot_diag)): os.makedirs('/home/pwille/figures/%s/%s' % (experiment_id, plot_diag))
Exemple #20
0
ds = (snm2 - snm1) * filter_coeff
# Love numbers
kn = pgfl.LoveNumbers(deg_max)
# Legendre functions
lf = pgfl.LegendreFunctions(deg_max)

if __name__ == '__main__':
    # calculations
    w = ewh_calc()
    # Plot of result
    fig = plt.figure(figsize=[15, 8])
    ax = plt.subplot(projection=ccrs.PlateCarree())
    imgextend = [-180, 180, -90, 90]
    t = ax.imshow(w,
                  origin='upper',
                  extent=imgextend,
                  transform=ccrs.PlateCarree(),
                  cmap='RdBu')
    ax.coastlines('110m')  # 50m is also available
    lonLabels = np.arange(-180, 181, 60)
    latLabels = np.arange(-90, 91, 30)
    gl = ax.gridlines(draw_labels=True, color='k', linewidth=1.5)
    gl.xlocator = mticker.FixedLocator(lonLabels)
    gl.ylocator = mticker.FixedLocator(latLabels)
    gl.xformatter = LongitudeFormatter()
    gl.yformatter = LatitudeFormatter()

    cbar = plt.colorbar(t)
    cbar.set_label('EWH / m', rotation=90)
    plt.show()
Exemple #21
0
def plot_violins_multiwarp(depth_vals_global, dists, outer_all=None):
    data_epi = []
    data_epi_nostack = []
    data_fs5 = []
    data_fs9 = []
    data_stack = []

    for dd in dists:
        d = str(dd)

        if outer_all == "outer":
            ####### Multiwarp-outer ##########
            data_epi.append(depth_vals_global[d + "_multiwarp-outer_epi"].flatten())
            data_epi_nostack.append(depth_vals_global[d + "_multiwarp-outer_epi_without_disp_stack"].flatten())
            data_fs5.append(depth_vals_global[d + "_multiwarp-outer_focalstack-17-5"].flatten())
            data_fs9.append(depth_vals_global[d + "_multiwarp-outer_focalstack-17-9"].flatten())
            data_stack.append(depth_vals_global[d + "_multiwarp-outer_stack"].flatten())
        elif outer_all == "all":
            ####### Multiwarp-all ##########
            data_epi.append(depth_vals_global[d + "_multiwarp-all_epi"].flatten())
            data_epi_nostack.append(depth_vals_global[d + "_multiwarp-all_epi_without_disp_stack"].flatten())
            data_fs5.append(depth_vals_global[d + "_multiwarp-all_focalstack-17-5"].flatten())
            data_fs9.append(depth_vals_global[d + "_multiwarp-all_focalstack-17-9"].flatten())
            data_stack.append(depth_vals_global[d + "_multiwarp-all_stack"].flatten())
        else:
            ####### Multiwarp-5 ##########
            data_epi.append(depth_vals_global[d + "_multiwarp-5_epi"].flatten())
            data_epi_nostack.append(depth_vals_global[d + "_multiwarp-5_epi_without_disp_stack"].flatten())
            data_fs5.append(depth_vals_global[d + "_multiwarp-5_focalstack-17-5"].flatten())
            data_fs9.append(depth_vals_global[d + "_multiwarp-5_focalstack-17-9"].flatten())
            data_stack.append(depth_vals_global[d + "_multiwarp-5_stack"].flatten())

    plt.figure()
    xvals = np.linspace(1, 5, len(dists)) * 0.6
    true_depth = np.array(dists).astype(np.float) / 1000.0

    violin_width = 0.1
    plt.violinplot(data_stack, positions=xvals - 0.2, showextrema=True, showmeans=True, widths=violin_width)
    plt.violinplot(data_fs5, positions=xvals - 0.1, showextrema=True, showmeans=True, widths=violin_width)
    plt.violinplot(data_fs9, positions=xvals, showextrema=True, showmeans=True, widths=violin_width)
    # plt.violinplot(data_epi, positions=xvals + 0.1, showextrema=True, showmeans=True, widths=violin_width)
    plt.violinplot(data_epi_nostack, positions=xvals + 0.2, showextrema=True, showmeans=True, widths=violin_width)
    plt.step(np.concatenate(([0], xvals))+0.3, np.concatenate(([0.4], true_depth)), 'k')

    # plt.xticks(xvals)
    # plt.xlim([0.3, 10.5])
    # plt.ylim([0.3, 0.85])

    ax = plt.gca()
    # Customize minor tick labels
    dists_str = ['0.4', '0.5', '0.6', '0.7', '0.8']

    ax.xaxis.set_major_locator(ticker.FixedLocator(xvals))
    # ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.xaxis.set_major_formatter(ticker.FixedFormatter(dists_str))

    ax.xaxis.set_minor_locator(ticker.FixedLocator(xvals-0.3))
    ax.tick_params(axis="x", labelsize=14)
    ax.tick_params(axis="y", labelsize=14)
    ax.tick_params(axis='x', which='minor', length=0)
    ax.tick_params(axis='x', which='major', length=0)
    plt.grid(axis='x', which='minor', linestyle='dashed')
    plt.title("Depth estimates in multi-warp reconstruction", fontsize=14)
    plt.xlabel("Distance of planar object from the EPIModule [m]", fontsize=14)
    plt.ylabel("Estimated distance [m]", fontsize=14)
    custom_patches = [Patch(facecolor='C0', edgecolor='None', label="volumetric stack"),
                      Patch(facecolor='C1', edgecolor='None', label="focalstack-5"),
                      Patch(facecolor='C2', edgecolor='None', label="focalstack-9"),
                      # Patch(facecolor='C3', edgecolor='None', label="epi"),
                      Patch(facecolor='C3', edgecolor='None', label="ours"),
                      Line2D([0], [0], color='k', lw=2, label='Ground truth depth')]
    ax.legend(handles=custom_patches, loc='lower right')
 fig = plt.figure()
 ax = fig.add_subplot(
             projection='aacgmv2',\
             map_projection = cartopy.crs.NorthPolarStereo(),\
             coords="aacgmv2_mlt", plot_date=plot_date
             )
 # uncomment lines below to add coastlines and lakes individually
 # ax.coastlines()
 # ax.add_feature( cartopy.feature.LAKES)
 # or add coastlines and lakes together!
 ax.overaly_coast_lakes()
 # plot set the map bounds
 ax.set_extent([-180, 180, 50, 90], crs=cartopy.crs.PlateCarree())
 # plot a random line!
 # ax.scatter(54, 60, transform=cartopy.crs.Geodetic())
 ax.plot([-175, 175], [60, 60], transform=cartopy.crs.Geodetic())
 # overaly gridlines!
 # the example here is for plotting gridlines
 plt_lons = numpy.arange(0, 361, 30)
 mark_lons = numpy.arange(0, 360, 30)
 plt_lats = numpy.arange(30, 90, 10)
 gl = ax.gridlines(crs=cartopy.crs.Geodetic(), linewidth=0.5)
 gl.xlocator = mticker.FixedLocator(plt_lons)
 gl.ylocator = mticker.FixedLocator(plt_lats)
 gl.xformatter = LONGITUDE_FORMATTER
 gl.yformatter = LATITUDE_FORMATTER
 gl.n_steps = 90
 # mark the longitudes
 ax.mark_latitudes(plt_lats, fontsize=10)
 ax.mark_longitudes(lon_arr=mark_lons, fontsize=10)
 plt.savefig("test_plots/carto_test.png")
Exemple #23
0
def PlotOneDiffMapsWInconclusives_ax(ax,Wmatrix,Vest,filename,titletext,showax=False,colors='no'):
    
    rc('text', usetex=True)
    rc('font', family='serif')
    
    N=len(Wmatrix)
    cmap1,vmin1,vmax1=maphatchBase2()
    cmap2,vmin2,vmax2=maphatch2()
    cmapc,vminc,vmaxc=map_w_inconclusives()
    
    Vtrue=np.zeros([N,N])
    for i in range(N):
        for j in range(N):
            if Wmatrix[i,j]!=0:
                Vtrue[i,j]=1
                
    
    diffmat=np.zeros([N,N])
    for i in range(N):
        for j in range(N):
            if Vest[i,j]==0:
                if Vtrue[i,j]==0:
                    diffmat[i,j]=0
                if Vtrue[i,j]==1:
                    diffmat[i,j]=2
            if Vest[i,j]==1:
                if Vtrue[i,j]==0:
                    diffmat[i,j]=3
                if Vtrue[i,j]==1:
                    diffmat[i,j]=1
            if Vest[i,j]==-2:
                if Vtrue[i,j]==0:
                    diffmat[i,j]=4
                if Vtrue[i,j]==1:
                    diffmat[i,j]=5
    
    if colors=='no':
        ax.pcolor(diffmat, cmap=cmap1, vmin=vmin1, vmax=vmax1, edgecolors='black' ,hatch='///')
        ax.pcolor(diffmat, cmap=cmap2, vmin=vmin2, vmax=vmax2, edgecolors='black')
    else:        
        ax.pcolor(diffmat, cmap=cmapc, vmin=0, vmax=vmaxc, edgecolors='black' )
        
    
    if showax:    
        ax.set_title(titletext,y=1.12)
        ax.set_ylabel("Presynaptic")
        ax.set_xlabel("Postsynaptic")      
        ax.set(frame_on=False, aspect=1, xticks=range(1,N+1), yticks=range(1,N+1))
    else:
        ax.set_title(titletext)
        
    ax.set(frame_on=False, aspect=1,xticks=[],yticks=[])
    ax.invert_yaxis() 
    if showax:
        ax.xaxis.set_label_position('top')
        ax.xaxis.tick_top()
        tickpos=list(np.array(range(N))+0.5)
        ticknames=[str(i) for i in range(1,N+1)]
        ax.tick_params(axis=u'both', which=u'both',length=0)    
        ax.xaxis.set_major_formatter(ticker.NullFormatter())
        ax.xaxis.set_minor_locator(ticker.FixedLocator(tickpos))
        ax.xaxis.set_minor_formatter(ticker.FixedFormatter(ticknames))
    
        ax.tick_params(axis=u'both', which=u'both',length=0)    
        ax.yaxis.set_major_formatter(ticker.NullFormatter())
        ax.yaxis.set_minor_locator(ticker.FixedLocator(tickpos))
        ax.yaxis.set_minor_formatter(ticker.FixedFormatter(ticknames))
Exemple #24
0
    print(' -> Done!')


## ---- Station info ---- ##
df = pd.read_excel(beachFile)

## ---- draw map ---- ##
print('--- Now plot ---')
fig = plt.figure(figsize=(7,5))
ax = fig.add_subplot(111, projection=ccrs.Mercator())
ax.set_extent([lonLims[0], lonLims[1], latLims[0], latLims[1]], crs=ccrs.PlateCarree())
ax.add_feature(cpf.NaturalEarthFeature('physical', 'coastline', '50m', edgecolor='k', alpha=0.7, linewidth=0.6, facecolor='black'), zorder=1)
m=ax.gridlines(linewidth=0.5, color='black', draw_labels=True, alpha=0.5)
m.xlabels_top=False
m.ylabels_right=False
m.xlocator = mticker.FixedLocator([-60, -58, -56, -54, -52])
m.ylocator = mticker.FixedLocator([46, 48, 50, 52, 54])
m.xformatter = LONGITUDE_FORMATTER
m.yformatter = LATITUDE_FORMATTER
m.ylabel_style = {'size': 7, 'color': 'black', 'weight':'bold'}
m.xlabel_style = {'size': 7, 'color': 'black', 'weight':'bold'}
lightdeep = cmocean.tools.lighten(cmo.deep, 0.5)
c = plt.contourf(lon, lat, -Z, v, transform=ccrs.PlateCarree(), cmap=lightdeep, extend='max', zorder=5)
cc = plt.contour(lon, lat, -Z, [100, 500], colors='silver', linewidths=.5, transform=ccrs.PlateCarree(), zorder=10)
plt.clabel(cc, inline=True, fontsize=7, fmt='%i')

# plot Beaches
beach = df.Short_name.values
lats = df.Lat.values
lons = df.Long.values
ax.plot(lons, lats, '.', color='magenta', transform=ccrs.PlateCarree(), markersize=13, zorder=10)
Exemple #25
0
    out = ax.plot(data1, data2, **param_dict)
    return out[0]


fig = plt.gcf()
ax1 = fig.add_subplot(1, 1, 1)
show_time = [0, 250, 500, 750, 1000, 1250, 1500, 1686]
x_time = np.array(range(records_npy.shape[0]))
for i in range(records_npy.shape[1]):
    print(x_time, records_npy[:, i])
    gen_artist(
        ax1, x_time, records_npy[:, i],
        {"label": 'DEVICE-' + ("2" if item_list[i] == "11" else item_list[i])})
ax1.legend(prop=font_en)
ax1.xaxis.set_major_locator(
    ticker.FixedLocator(show_time)
)  # https://matplotlib.org/api/ticker_api.html?highlight=multiplelocator
ax1.xaxis.set_major_formatter(
    ticker.FixedFormatter([time_list[i][4:] for i in show_time]))
for t in ax1.get_xticklabels():
    t.set_fontproperties(font_en)
    t.set_rotation(30)
for t in ax1.get_yticklabels():
    t.set_fontproperties(font_en)
for i in range(records_npy.shape[1]):
    ax1.text(1686,
             records_npy[-1, i],
             str(records_npy[-1, i]),
             fontproperties=font_en,
             horizontalalignment='right',
             verticalalignment='top')
Exemple #26
0
def loss_fn(output, depth, mode, img=None):
    if mode == 'classification':
        depth_np = depth.cpu().numpy()
        label = np.digitize(np.clip(depth_np, 0, b), bins)
        label = torch.Tensor(label).long().cuda()

        C = output.size()[1]
        mask = (depth != 0.).cuda()
        mask = mask[:, None, :, :].repeat_interleave(C, dim=1)

        h = torch.arange(0., C).view(1, -1).cuda()
        information_gain = torch.exp(-0.5 * (h - h.T) ** 2)
        H = information_gain[label.view(-1), :].view(*label.size(), C).cuda()
        H = H.permute(0, 3, 1, 2)[mask]

        P = F.log_softmax(output, dim=1)[mask]

        return - torch.mean((H * P)) * C

    if mode in ['regression', 'reg_of_cls']:
        mask = (depth != 0).cuda()
        gt_mask = depth.clamp(0, b)[mask]
        pred_mask = output.clamp(1e-3, b).squeeze()[mask]

        # dlog = torch.log(gt_mask) - torch.log(pred_mask)
        # loss = torch.mean(dlog ** 2) - torch.mean(dlog) ** 2
        if mode == 'regression':
            criterion = nn.MSELoss()
            return criterion(pred_mask, gt_mask)
        if mode == 'reg_of_cls':
            return torch.mean(torch.log(torch.cosh(pred_mask - gt_mask + 1e-12)))

    if mode[:4] == 'sord':
        mask = (depth != 0).cuda()
        gt = depth.clamp(0, b)[:, :, :, None]
        # phi = (torch.log(gt) - torch.log(torch.tensor(center).float().cuda()).view(1,1,1,-1))**2
        phi = (gt - torch.tensor(center).float().cuda().view(1, 1, 1, -1)) ** 2
        gt_sord = F.softmax(-phi, dim=3)[mask]
        log_p = F.log_softmax(output, dim=1).permute(0, 2, 3, 1)[mask]

        if VISUALIZE_sord:
            fig1 = plt.figure(0)
            plt.cla()
            axes = fig1.subplots(1, 2, sharex=True, sharey=True)
            axes[0].bar(center, gt_sord.detach().cpu().numpy()[0], width=np.diff(np.append(center, [80])) / 2,
                        align='edge', color=cmap(np.arange(K).astype(float) / K))
            axes[0].set_title('Ground-truth SORD of a pixel')
            axes[0].set_facecolor('black')
            axes[0].set_xscale('log')
            axes[0].set_xlim(0.5, 80)
            axes[0].set_ylim(0, 1)
            axes[0].xaxis.set_minor_locator(ticker.FixedLocator([1] + list(range(10, 81, 10))))
            axes[0].xaxis.set_major_locator(ticker.NullLocator())
            axes[0].xaxis.set_minor_formatter(ticker.ScalarFormatter())
            axes[1].bar(center, np.exp(log_p.detach().cpu().numpy())[0], width=np.diff(np.append(center, [80])) / 2,
                        align='edge', color=cmap(np.arange(K).astype(float) / K))
            axes[1].set_title('Output of the same pixel')
            axes[1].set_facecolor('black')

            log_p_unmask = F.log_softmax(output, dim=1).permute(0, 2, 3, 1)
            p_unmask = F.softmax(output, dim=1).permute(0, 2, 3, 1)
            E = -1 / np.log2(output.shape[1]) * torch.sum((p_unmask * log_p_unmask), dim=3)
            pred_map = depth_inference(output.detach().cpu().numpy(), mode=mode)

            fig2 = plt.figure(1)
            plt.cla()
            axes = fig2.subplots(2, 2)
            axes[0,0].imshow(img[0].cpu().permute(1, 2, 0))
            axes[0,0].set_title('RGB image')
            axes[0,1].imshow(depth[0].cpu().numpy(), cmap='jet')
            axes[0,1].set_title('depth map')
            axes[1,0].imshow(pred_map[0], cmap='jet')
            axes[1,0].set_title('predicted depth map')
            axes[1,1].imshow(E[0].detach().cpu().numpy(), cmap='jet')
            axes[1,1].set_title('pixel-wise entropy of predicted')
            plt.pause(0.1)
            plt.show()

        if mode == 'sord':
            # Normal KLDivergence loss
            criterion = nn.KLDivLoss(reduction='batchmean')
            return criterion(log_p, gt_sord)

        elif mode == 'sord_ent_weighted':
            # KLDivergence loss weighted according to ground truth depthmap local entropy
            ## entropy kernel 16x16
            gt_entropy = torch.Tensor(local_entropy(depth.cpu().numpy(), kernel=16, mask=True)).cuda()

            if VISUALIZE_sord_ent_weighted:
                for i in range(output.size()[0]):
                    fig = plt.figure(i)
                    plt.cla()
                    plt.axis('off')
                    axes = fig.subplots(1, 3, sharex=True, sharey=True)
                    axes[0].imshow(img[i].cpu().permute(1, 2, 0))
                    axes[0].set_title('RGB image')
                    axes[1].imshow(depth[i].cpu().numpy(), cmap='jet')
                    axes[1].set_title('Depth map (ground truth)')
                    axes[2].imshow(gt_entropy[i].cpu().numpy(), cmap='gray')
                    axes[2].set_title('Depth map Entropy')
                    plt.pause(0.1)
                    plt.show()

            gt_entropy_mask = gt_entropy[mask]
            ## linear
            # weight_by_entropy = torch.clamp(1 - gt_entropy_mask / 6, min=0)         ## entropy kernel 16x16, divide by 6; entropy kernel 3x3, divide by 3
            # weight_by_entropy = 1 - gt_entropy_mask / gt_entropy_mask.max()
            ## sigmoid
            weight_by_entropy = 1 - F.sigmoid(gt_entropy_mask)

            KLDiv = torch.sum(F.kl_div(log_p, gt_sord, reduction='none'), dim=1)
            return torch.sum(KLDiv * weight_by_entropy) / torch.sum(weight_by_entropy)

        elif mode == 'sord_min_local_ent':
            # Normal KLDivergence loss
            criterion = nn.KLDivLoss(reduction='batchmean')
            loss_sord = criterion(log_p, gt_sord)

            pred_map = depth_inference(output.detach().cpu().numpy(), mode=mode)

            # entropy of masked predicted depth map (could be wrong)
            pred_entropy = torch.Tensor(local_entropy(pred_map, kernel=16)).cuda()

            if VISUALIZE_sord_min_local_ent:
                for i in range(output.size()[0]):
                    fig = plt.figure(i)
                    plt.cla()
                    plt.axis('off')
                    axes = fig.subplots(2, 2, sharex=True, sharey=True)
                    axes[0, 0].imshow(img[i].cpu().permute(1, 2, 0))
                    axes[0, 0].set_title('RGB image')
                    axes[0, 1].imshow(depth[i].cpu().numpy(), cmap='jet')
                    axes[0, 1].set_title('Depth map (ground truth)')
                    axes[1, 0].imshow(pred_map[i], cmap='jet')
                    axes[1, 0].set_title('Predicted depth map')
                    axes[1, 1].imshow(pred_entropy[i].cpu().numpy(), cmap='gray')
                    axes[1, 1].set_title('Predicted depth map Entropy')
                    plt.pause(0.1)
                    plt.show()

            loss_min_ent = torch.mean(pred_entropy)
            print('loss_sord', loss_sord, 'loss_min_ent', loss_min_ent)
            # return loss_sord + 0.1 * loss_min_ent
            return loss_sord + 1 * loss_min_ent
            # return loss_sord + F.sigmoid(loss_min_ent) * 2 - 1 ?

        elif mode == 'sord_weighted_minent':
            # compute loss_kl_weighted
            gt_entropy = torch.Tensor(local_entropy(depth.cpu().numpy(), kernel=16, mask=True)).cuda()
            gt_entropy_mask = gt_entropy[mask]

            ## linear
            # weight_by_entropy = torch.clamp(1 - gt_entropy_mask / 6, min=0)         ## entropy kernel 16x16, divide by 6; entropy kernel 3x3, divide by 3
            # weight_by_entropy = 1 - gt_entropy_mask / gt_entropy_mask.max()
            ## sigmoid
            weight_by_entropy = 1 - F.sigmoid(gt_entropy_mask)

            KLDiv = torch.sum(F.kl_div(log_p, gt_sord, reduction='none'), dim=1)
            loss_sord_weighted = torch.sum(KLDiv * weight_by_entropy) / torch.sum(weight_by_entropy)

            # compute loss_minEnt
            pred_map = depth_inference(output.detach().cpu().numpy(), mode=mode)
            # entropy of masked predicted depth map (could be wrong)
            pred_entropy = torch.Tensor(local_entropy(pred_map, kernel=16)).cuda()
            loss_min_ent = torch.mean(pred_entropy)

            print('loss_sord_weighted', loss_sord_weighted, 'loss_min_ent', loss_min_ent)
            return loss_sord_weighted + 1 * loss_min_ent

        elif mode == 'sord_align_grad':
            assert img is not None

            # Normal KLDivergence loss
            criterion = nn.KLDivLoss(reduction='batchmean')
            loss_sord = criterion(log_p, gt_sord)

            pred_map = depth_inference(output.detach().cpu().numpy(), mode=mode)

            img_edge = torch.Tensor(edge(img.cpu().numpy())).cuda()
            pred_edge = torch.Tensor(edge(pred_map)).cuda()

            if VISUALIZE_sord_align_grad:
                for i in range(output.size()[0]):
                    fig = plt.figure(i)
                    plt.cla()
                    plt.axis('off')
                    axes = fig.subplots(2, 2, sharex=True, sharey=True)
                    axes[0, 0].imshow(img[i].cpu().permute(1, 2, 0))
                    axes[0, 0].set_title('RGB image')
                    axes[0, 1].imshow(img_edge[i].cpu().numpy(), cmap='gray')
                    axes[0, 1].set_title('RGB Edge')
                    axes[1, 0].imshow(pred_map[i], cmap='jet')
                    axes[1, 0].set_title('Predicted depth map')
                    axes[1, 1].imshow(pred_edge[i].cpu().numpy(), cmap='gray')
                    axes[1, 1].set_title('Predicted depth map Edge')
                    plt.pause(0.1)
                    plt.show()

            ## loss mean absolute error
            loss_align_grad = torch.mean(torch.abs(img_edge - pred_edge))
            ## loss KLDivergence
            # loss_align_grad = F.kl_div(img_edge, pred_edge) ?

            ## with mask
            # img_edge_mask = img_edge[mask]
            # pred_edge_mask = pred_edge[mask]
            # loss_align_grad = torch.mean(torch.abs(img_edge_mask - pred_edge_mask))
            print('loss_sord', loss_sord, 'loss_align_grad', loss_align_grad)
            return loss_sord + 0.1 * loss_align_grad
Exemple #27
0
def plotCoordinatesPlot(Inputdata = "Clustereddata", X = None, labels = None, core_samples_mask = None, axis = [1,2]):
    print("- plotClustering")


    if (Inputdata == "Clustereddata"):
        df2 = rd.readClusteredDataDF()
        axis.append("Label")
        axis.append("Clustercore")
        df2 = df2[axis]

    else:
        X, labels = rd.readTransformedData()
        core_samples_mask = [0] * len(labels)

    df2 = df2.drop('Clustercore', axis = 'columns')
    df2[0] = df2['Label']+2
    df2 = df2.drop('Label', axis = 'columns')
    df2 = df2.rename(columns={0:'Label'})
    df = df2

#    d = {'Label': [2,4,3,2,5,3], 1: [70,23,53,53,12,85], 2: [23,45,23,90,35,12] , 3: [12,34,15,23,56,23], 4: [223,423,125,125,125,522], 5: [2,3,2,3,4,5]}
#    df = pd.DataFrame(data=d)

#    df[1] = pd.to_numeric(df[1].replace('?', np.nan))
    array_to_use = list(set(df['Label']))
    array_to_use.insert(0, min(df['Label'])-1)
    df['Label'] = pd.cut(df['Label'],array_to_use)

    plt.figure()

    cols = list(x for x in df.columns)
    cols.remove("Label")
    x = [i for i, _ in enumerate(cols)]
#    colours = ['#2e8ad8', '#cd3785', '#c64c00', '#889a00']
#    colours = ['red', 'blue', 'green', 'yellow', 'black']

    # create dict of categories: colours
    colours = get_N_HexCol(len(df['Label'].cat.categories))
    colours = {df['Label'].cat.categories[i]: colours[i] for i, _ in enumerate(df['Label'].cat.categories)}

    # Create (X-1) subplots along x axis
    fig, axes = plt.subplots(1, len(x) - 1, sharey=False, figsize=(15, 5))

    # Get min, max and range for each column
    # Normalize the data for each column
    min_max_range = {}
    for col in cols:
        min_max_range[col] = [df[col].min(), df[col].max(), np.ptp(df[col])]
        ### Normalize on/off
        df[col] = np.true_divide(df[col] - df[col].min(), np.ptp(df[col]))

    # Plot each row
    if len(cols) == 2:
        for idx in df.index:
            Label_category = df.loc[idx, 'Label']
            axes.plot(x, df.loc[idx, cols], colours[Label_category])
        axes.set_xlim([x[0], x[0 + 1]])
    else:
        for i, ax in enumerate(axes):
            for idx in df.index:
                Label_category = df.loc[idx, 'Label']
                ax.plot(x, df.loc[idx, cols], colours[Label_category])
            ax.set_xlim([x[i], x[i + 1]])

    # Set the tick positions and labels on y axis for each plot
    # Tick positions based on normalised data
    # Tick labels are based on original data
    def set_ticks_for_axis(dim, ax, ticks):
        min_val, max_val, val_range = min_max_range[cols[dim]]
        step = val_range / float(ticks - 1)
        tick_labels = [round(min_val + step * i, 2) for i in range(ticks)]
        norm_min = df[cols[dim]].min()
        norm_range = np.ptp(df[cols[dim]])
        norm_step = norm_range / float(ticks - 1)
        ticks = [round(norm_min + norm_step * i, 2) for i in range(ticks)]
        ax.yaxis.set_ticks(ticks)
        ax.set_yticklabels(tick_labels)

    if len(cols) == 2:
            axes.xaxis.set_major_locator(ticker.FixedLocator([0]))
            set_ticks_for_axis(0, axes, ticks=6)
            axes.set_xticklabels([cols[0]])
            axes.xaxis.set_major_locator(ticker.FixedLocator([1]))
            set_ticks_for_axis(1, axes, ticks=6)
            axes.set_xticklabels([cols[1]])
    else:
        for dim, ax in enumerate(axes):
            ax.xaxis.set_major_locator(ticker.FixedLocator([dim]))
            set_ticks_for_axis(dim, ax, ticks=6)
            ax.set_xticklabels([cols[dim]])

    # Move the final axis' ticks to the right-hand side
    if not len(cols) == 2:
        ax = plt.twinx(axes[-1])
        dim = len(axes)
        ax.xaxis.set_major_locator(ticker.FixedLocator([x[-2], x[-1]]))
        set_ticks_for_axis(dim, ax, ticks=6)
        ax.set_xticklabels([cols[-2], cols[-1]])
    else:
        axes.xaxis.set_major_locator(ticker.FixedLocator([x[-2], x[-1]]))
        set_ticks_for_axis(1, axes, ticks=6)
        axes.set_xticklabels([cols[-2], cols[-1]])

    # Remove space between subplots
    plt.subplots_adjust(wspace=0)

    legends = list(range(1,len(colours)+1))

    # Add legend to plot
    plt.legend(
        [plt.Line2D((0, 1), (0, 0), color=colours[cat]) for cat in df['Label'].cat.categories],
        legends,
        bbox_to_anchor=(1.2, 1), loc=2, borderaxespad=-1.5)

    img = BytesIO()
    plt.savefig(img)
    #    plt.show()
    img.seek(0)
    plt.close()
    return img
        #### color bar and axis properties ###
        #cbar.ax.set_ylabel(text, rotation=270,labelpad=20,fontsize=10)
        cbar.ax.tick_params(labelsize=8)
        ax1.tick_params(axis='y', which='major', labelsize=8)
        ax1.tick_params(axis='x', which='major', labelsize=10)

        #### axis adjustments ####
        if yr_end - yr_start > 30:  # reduces overcrowding of y-axis tick labels (less frequent ticks with longer data)
            ax1.locator_params(axis='y',
                               nbins=(yr_end - yr_start) / 2,
                               tight=True)  #set number of y ticks
        else:
            ax1.locator_params(axis='y', nbins=(yr_end - yr_start),
                               tight=True)  #set number of y ticks
        ax1.xaxis.set_minor_locator(
            ticker.FixedLocator(
                [31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]))
        ax1.xaxis.set_major_locator(
            ticker.FixedLocator(
                [15, 45, 74, 105, 135, 166, 196, 227, 258, 288, 319, 349]))
        ax1.set_xticklabels([
            'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
            'Oct', 'Nov', 'Dec'
        ])
        ax1.xaxis.grid(b=True, which='minor', color='k', linestyle='--')

        ### set tick marks properties
        ax1.tick_params(which='minor', length=5, width=1.5)
        ax1.tick_params(axis='x', which='major', length=0, width=0)
        lala = ax1.yaxis.get_majorticklocs(
        )  # find the automatic tick mark locations
Exemple #29
0
def plot_time_series_profile(
        t,
        z,
        d,
        filename='/Users/lederer/tmp/rompy.time_series_profile.png',
        clim=None,
        cmap='banas_hsv_cm',
        varname=None,
        title=None,
        caxis_label=None):

    fontsize = 8

    cmap, sm, norm = make_cmap_sm_norm(d=d, clim=clim, cmap=cmap)

    fig = Figure(facecolor='white')
    ax1 = fig.add_axes([0.1, 0.55, 0.75, 0.32])
    ax2 = fig.add_axes([0.1, 0.18, 0.75, 0.32])
    cax = fig.add_axes([0.9, 0.18, 0.02, 0.69], frameon=False)

    my_plot11 = ax1.contourf(t, z, d, 100, norm=norm, cmap=cmap)
    my_plot12 = ax1.contour(t,
                            z,
                            d,
                            100,
                            linewidths=1,
                            linestyle=None,
                            norm=norm,
                            cmap=cmap)
    my_plot21 = ax2.contourf(t, z, d, 100, norm=norm, cmap=cmap)
    my_plot22 = ax2.contour(t,
                            z,
                            d,
                            100,
                            linewidths=1,
                            linestyle=None,
                            norm=norm,
                            cmap=cmap)

    my_colorbar = fig.colorbar(sm, cax=cax)
    if not caxis_label == None:
        my_colorbar.set_label(caxis_label)

    ax1.set_ylim(-20, 2)
    ax1.set_xlim(t[0][0], t[-1][-1])

    # lets pick some x ticks that aren't stupid
    xmin_dt = dt.datetime.fromtimestamp(t[0][0])
    xmax_dt = dt.datetime.fromtimestamp(t[-1][-1])
    time_window = xmax_dt - xmin_dt
    if (time_window) < dt.timedelta(hours=48):
        date_list = []
        next_time = xmax_dt - dt.timedelta(seconds=xmax_dt.minute * 60 +
                                           xmax_dt.second)
        while next_time >= xmin_dt:
            date_list.append(next_time)
            next_time = next_time - dt.timedelta(hours=6)

    elif (time_window) < dt.timedelta(days=8):
        date_list = []
        next_time = xmax_dt - dt.timedelta(
            seconds=(xmax_dt.hour * 60 + xmax_dt.minute) * 60 + xmax_dt.second)
        while next_time >= xmin_dt:
            date_list.append(next_time)
            next_time = next_time - dt.timedelta(days=1)

    elif (time_window) < dt.timedelta(days=50):
        date_list = []
        next_time = xmax_dt - dt.timedelta(
            seconds=(xmax_dt.hour * 60 + xmax_dt.minute) * 60 + xmax_dt.second)
        while next_time >= xmin_dt:
            date_list.append(next_time)
            next_time = next_time - dt.timedelta(days=7)
    else:
        date_list = [xmin_dt, xmax_dt]
    x_tick_list = []
    for date in date_list:
        x_tick_list.append(time.mktime(date.timetuple()))
    ax2.xaxis.set_major_locator(ticker.FixedLocator(x_tick_list))

    for yticklabel in ax1.get_yticklabels():
        yticklabel.set_fontsize(fontsize)
    ax1.set_xticklabels('')

    ax2.set_xlim(t[0][0], t[-1][-1])
    ax2.set_ylim(np.min(z[0, :]), np.max(z[-1, :]))
    for yticklabel in ax2.get_yticklabels():
        yticklabel.set_fontsize(fontsize)
    locs = ax2.get_xticks()
    new_labels = []
    ax2.xaxis.set_major_formatter(ticker.FuncFormatter(time_series_formatter))
    for label in ax2.get_xticklabels():
        label.set_ha('right')
        label.set_rotation(30)

    if title == None or title == '':
        ax1.set_title('%s Over Time at a Point' % map_varname(varname))
    else:
        ax1.set_title(title)

    FigureCanvas(fig).print_png(filename)
Exemple #30
0
def style_map(ax, plot_extent, add_grid=True, map_resolution=globals.naturalearth_resolution,
              add_topo=False, add_coastline=True,
              add_land=True, add_borders=True, add_us_states=False):
    ax.set_extent(plot_extent, crs=globals.data_crs)
    ax.outline_patch.set_linewidth(0.4)
    if add_grid:
        # add gridlines. Bcs a bug in cartopy, draw girdlines first and then grid labels.
        # https://github.com/SciTools/cartopy/issues/1342
        try:
            grid_interval = max((plot_extent[1] - plot_extent[0]),
                                (plot_extent[3] - plot_extent[2])) / 5  # create apprx. 5 gridlines in the bigger dimension
            if grid_interval <= min(globals.grid_intervals):
                raise RuntimeError
            grid_interval = min(globals.grid_intervals, key=lambda x: abs(
                x - grid_interval))  # select the grid spacing from the list which fits best
            gl = ax.gridlines(crs=globals.data_crs, draw_labels=False,
                              linewidth=0.5, color='grey', linestyle='--',
                              zorder=3)  # draw only gridlines.
            # todo this can slow the plotting down!!
            xticks = np.arange(-180, 180.001, grid_interval)
            yticks = np.arange(-90, 90.001, grid_interval)
            gl.xlocator = mticker.FixedLocator(xticks)
            gl.ylocator = mticker.FixedLocator(yticks)
        except RuntimeError:
            pass
        else:
            try:  # drawing labels fails for most projections
                gltext = ax.gridlines(crs=globals.data_crs, draw_labels=True,
                                      linewidth=0.5, color='grey', alpha=0., linestyle='-',
                                      zorder=4)  # draw only grid labels.
                xticks = xticks[(xticks >= plot_extent[0]) & (xticks <= plot_extent[1])]
                yticks = yticks[(yticks >= plot_extent[2]) & (yticks <= plot_extent[3])]
                gltext.xformatter = LONGITUDE_FORMATTER
                gltext.yformatter = LATITUDE_FORMATTER
                gltext.top_labels = False
                gltext.left_labels = False
                gltext.xlocator = mticker.FixedLocator(xticks)
                gltext.ylocator = mticker.FixedLocator(yticks)
            except RuntimeError as e:
                print("No tick labels plotted.\n" + str(e))
    if add_topo:
        ax.stock_img()
    if add_coastline:
        coastline = cfeature.NaturalEarthFeature('physical', 'coastline',
                                                 map_resolution,
                                                 edgecolor='black', facecolor='none')
        ax.add_feature(coastline, linewidth=0.4, zorder=3)
    if add_land:
        land = cfeature.NaturalEarthFeature('physical', 'land',
                                            map_resolution,
                                            edgecolor='none', facecolor='white')
        ax.add_feature(land, zorder=1)
    if add_borders:
        borders = cfeature.NaturalEarthFeature('cultural', 'admin_0_countries',
                                               map_resolution,
                                               edgecolor='black', facecolor='none')
        ax.add_feature(borders, linewidth=0.2, zorder=3)
    if add_us_states:
        ax.add_feature(cfeature.STATES, linewidth=0.1, zorder=3)

    return ax