예제 #1
0
    def draw_diagram(self, framedelay):
        cols = self.num_cells
        rows = self.num_genes
        # set up figure canvas
        fig = plt.figure(figsize=(cols + 1.25, rows + 1.5))
        ax = plt.axes([0,0,1,1])
        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_xlim(-1.25, cols + .5)
        ax.set_ylim(-.5, rows + 1.5)
        fig.suptitle(self.label, family=self.font, size=24)
        # set up frame
        border = mpatches.Rectangle((0,0),
                                    cols, rows + .5, fill=False, ec='black', lw=2)
        ax.add_patch(border)
        lines = [mlines.Line2D([0,cols],[rows, rows], lw=2, color='black')]
        for i in range(1,cols):
            line = mlines.Line2D([i,i], [0, rows+.5], lw=2, color='black')
            lines.append(line)
        for line in lines:
            ax.add_line(line)
        del line
        # Set up label text
        for i in range(cols):
            plt.text(i+.25, rows+.15, "C "+str(i+1), 
                     family=self.font, size=20)
        for i in range(rows):
            gene = self.genes[i]
            plt.text(-.9, rows-i-.6, gene, 
                      family=self.font, size=20)
        self.timestamp = plt.text(
            self.num_cells-2.2, self.num_genes+.7, "Timepoint: ", family = self.font, size=20)           
        # Set up RNA / protein patches
        rna_patches = []
        protein_patches = []
        for i in range(cols):
            cell_rna = []
            cell_protein = []
            for j in range(rows):
                face_color = self.colors[self.tissue.genome[j]]
                rna_patch = mpatches.Rectangle((i+.05, rows-j-.5), .9, .4, 
                                               fill=False,
                                               fc=face_color,
                                               ec=None, lw=0)
                protein_patch = mpatches.Rectangle((i+.05, rows-j-.95), .9, .4, 
                                                   fill=False,
                                                   fc=face_color,
                                                   ec=None, lw=0)
                cell_rna.append(rna_patch)
                cell_protein.append(protein_patch)
                ax.add_patch(rna_patch)
                ax.add_patch(protein_patch)
            rna_patches.append(cell_rna)
            protein_patches.append(cell_protein)
        self.rna_patches = rna_patches
        self.protein_patches = protein_patches
        # Animate
        anim = animation.FuncAnimation(fig, self.animation_function, 
                                       init_func = self.init_function,
                                       frames=self.tissue.timepoint+1, 
                                       interval=framedelay, blit=True, repeat=False)
	Writer = animation.writers['ffmpeg']
        writer = Writer(fps=5, metadata=dict(artist='Me'), bitrate=1800)
        anim.save(self.label+".mp4", writer=writer)
예제 #2
0
def f2():
    #was used for plotting stuff from the evaluator
    clist = ["green", "red", "purple", "orange"]
    ptimes = [0, 24, 48, 72]
    target = np.array([[42.733156, 13.449431 + 360]])
    files = list(map(load_file2, range(1, 79)))
    const = list(map(load_file2, [0]))
    files2 = []
    for i in ptimes:
        files2.append(
            list(map(load_file2, range(100 + i * 100, 100 + (i + 1) * 100))))

    fig, ax = plt.subplots(2,
                           3,
                           gridspec_kw={
                               'height_ratios': [1, .63],
                               "hspace": 0,
                           },
                           figsize=(10, 5))
    gs = gridspec.GridSpec(2,
                           3,
                           width_ratios=[0.06, .14, 1],
                           height_ratios=[1, 0.56])
    gs.update(left=0.05, wspace=0, hspace=0.05)
    ax0 = plt.subplot(gs[0, 2:3])
    ax1 = plt.subplot(gs[1, 1:3])
    ax1.plot(0, 14, c="#be1e2d")
    ax1.plot(0, 14, c="blue")

    all_vals = np.concatenate(files + [i1 for i2 in files2 for i1 in i2])
    real_vals = np.concatenate(files)

    for j, fs in enumerate(files2):
        c = clist[j]
        vals = fs[0]
        N = vals.shape[0]
        ax1.plot(ptimes[j] + np.arange(N) / 6,
                 vals[:, 3] / 1000 - vals[:, 4] / 1000,
                 "--",
                 c=c,
                 alpha=0.5)
        ax1.plot(ptimes[j] + np.arange(N) / 6,
                 vals[:, 3] / 1000 + vals[:, 4] / 1000,
                 "--",
                 c=c,
                 alpha=0.5)
        for i in range(0, 50):
            if (i + 1) % 8 != 0:
                continue
            vals = fs[i]
            N = vals.shape[0]
            #ax1.plot(ptimes[j] + np.arange(N)/6,vals[:,2]/1000,c=c,alpha=0.1)

    N = real_vals.shape[0]
    ax1.plot(np.arange(N) / 6,
             real_vals[:, 3] / 1000 + real_vals[:, 4] / 1000,
             "--",
             c="blue",
             alpha=1)
    ax1.plot(np.arange(N) / 6,
             real_vals[:, 3] / 1000 - real_vals[:, 4] / 1000,
             "--",
             c="blue",
             alpha=1)
    ax1.plot(np.arange(N) / 6, real_vals[:, 2] / 1000, c="blue", alpha=1)
    #ax1.legend(["initial","optimized"],loc=(.18,.05))
    ax1.set_xlabel(
        "hours from " +
        datetime.fromtimestamp(1543492801).strftime("%Y-%m-%d %H:%M:%S"))
    ax1.set_ylabel("altitude (km)")
    ax1.grid()

    all_lls = np.vstack((all_vals[:, :2], target))
    m = Basemap(
        projection='merc',
        llcrnrlat=np.min(all_lls[:, 0]) - 5,
        urcrnrlat=np.max(all_lls[:, 0]) + 5,
        llcrnrlon=np.min(all_lls[:, 1]) - 5,
        urcrnrlon=np.max(all_lls[:, 1]) + 5,
        resolution='l',
        ax=ax0,
    )
    m.drawcoastlines(color="grey")
    m.drawcountries(color="grey")
    m.drawstates(color="grey")

    for j, fs in enumerate(files2):
        for i in range(0, 50):
            if (i + 1) % 8 != 0:
                continue
            vals = fs[i]
            xpred, ypred = m(vals[:, 1], vals[:, 0])
            c = clist[j]
            ax0.plot(xpred, ypred, color=c, alpha=0.2)
            #ax0.plot(xpred[-1],ypred[-1],"*",c=c,alpha=0.2)
        ax0.plot(xpred[0], ypred[0], "*", c=c, alpha=1)

    cv = const[0]
    xpred, ypred = m(cv[:, 1], cv[:, 0])
    ax0.plot(xpred,
             ypred,
             color="black",
             alpha=1,
             label="pre-optimized \ntrajectory")
    ax0.plot(xpred[-1], ypred[-1], "*", c="black")

    xpred, ypred = m(real_vals[:, 1], real_vals[:, 0])
    ax0.plot(xpred,
             ypred,
             color="blue",
             alpha=1,
             label="evalaton \nsimulation \ntrajectory")
    ax0.plot(xpred[-1], ypred[-1], "*", c="blue")

    xt, yt = m(target[0, 1], target[0, 0])
    p = ax0.plot(xt, yt, ".", c="red")

    legend_elements = [
        li.Line2D([0], [0],
                  color='b',
                  lw=1.5,
                  label="evalaton \nsimulation \ntrajectory"),
        li.Line2D([0], [0],
                  color='black',
                  lw=1.5,
                  label="pre-optimized \ntrajectory"),
        li.Line2D([0], [0],
                  linestyle="--",
                  color='b',
                  alpha=0,
                  lw=2,
                  label="------------------"),
        li.Line2D([0], [0],
                  color='b',
                  lw=1.5,
                  label="evalaton \nsimulation \naltitude"),
        li.Line2D([0], [0],
                  linestyle="--",
                  color='b',
                  lw=1.5,
                  label="controller \ncounds"),
        li.Line2D([0], [0],
                  marker='o',
                  markerfacecolor='r',
                  color='w',
                  label='goal')
    ]
    print(p)
    ax0.legend(handles=legend_elements,
               loc='uppper right',
               bbox_to_anchor=(0, 1.03),
               ncol=1)
    plt.savefig("mpc2.png")
예제 #3
0
 def patch_point():
     return mlines.Line2D([0], [0],
                          linestyle="none",
                          marker=marker,
                          color=layer_color,
                          label=layer_label)
예제 #4
0
def draw_Miller_Composite_Chart(fcst_info=None,
                                u_300=None,
                                v_300=None,
                                u_500=None,
                                v_500=None,
                                u_850=None,
                                v_850=None,
                                pmsl_change=None,
                                hgt_500_change=None,
                                Td_dep_700=None,
                                Td_sfc=None,
                                pmsl=None,
                                lifted_index=None,
                                vort_adv_500_smooth=None,
                                map_extent=(50, 150, 0, 65),
                                add_china=True,
                                city=True,
                                south_China_sea=True,
                                output_dir=None,
                                Global=False):

    plt.rcParams['font.sans-serif'] = ['SimHei']  # 步骤一(替换sans-serif字体)
    plt.rcParams['axes.unicode_minus'] = False  # 步骤二(解决坐标轴负数的负号显示问题)

    # draw figure
    plt.figure(figsize=(16, 9))

    # set data projection
    if (Global == True):
        plotcrs = ccrs.Robinson(central_longitude=115.)
    else:
        plotcrs = ccrs.AlbersEqualArea(
            central_latitude=(map_extent[2] + map_extent[3]) / 2.,
            central_longitude=(map_extent[0] + map_extent[1]) / 2.,
            standard_parallels=[30., 60.])

    ax = plt.axes([0.01, 0.1, .98, .84], projection=plotcrs)

    plt.title('[' + fcst_info['model'] + '] ' + 'Miller 综合分析图',
              loc='left',
              fontsize=30)

    datacrs = ccrs.PlateCarree()

    #adapt to the map ratio
    map_extent2 = utl.adjust_map_ratio(ax,
                                       map_extent=map_extent,
                                       datacrs=datacrs)
    #adapt to the map ratio

    ax.add_feature(cfeature.OCEAN)
    utl.add_china_map_2cartopy_public(ax,
                                      name='coastline',
                                      edgecolor='gray',
                                      lw=0.8,
                                      zorder=105,
                                      alpha=0.5)
    if add_china:
        utl.add_china_map_2cartopy_public(ax,
                                          name='province',
                                          edgecolor='gray',
                                          lw=0.5,
                                          zorder=105)
        utl.add_china_map_2cartopy_public(ax,
                                          name='nation',
                                          edgecolor='black',
                                          lw=0.8,
                                          zorder=105)
        utl.add_china_map_2cartopy_public(ax,
                                          name='river',
                                          edgecolor='#74b9ff',
                                          lw=0.8,
                                          zorder=105,
                                          alpha=0.5)

    # define return plots
    plots = {}

    lons = fcst_info['lon']
    lats = fcst_info['lat']
    # Plot Lifted Index
    cs1 = ax.contour(lons,
                     lats,
                     lifted_index,
                     range(-8, -2, 2),
                     transform=ccrs.PlateCarree(),
                     colors='red',
                     linewidths=0.75,
                     linestyles='solid',
                     zorder=7)
    cs1.clabel(fontsize=10,
               inline=1,
               inline_spacing=7,
               fmt='%i',
               rightside_up=True,
               use_clabeltext=True)

    # Plot Surface pressure falls
    cs2 = ax.contour(lons,
                     lats,
                     pmsl_change.to('hPa'),
                     range(-10, -1, 4),
                     transform=ccrs.PlateCarree(),
                     colors='k',
                     linewidths=0.75,
                     linestyles='dashed',
                     zorder=6)
    cs2.clabel(fontsize=10,
               inline=1,
               inline_spacing=7,
               fmt='%i',
               rightside_up=True,
               use_clabeltext=True)

    # Plot 500-hPa height falls
    cs3 = ax.contour(lons,
                     lats,
                     hgt_500_change,
                     range(-60, -29, 15),
                     transform=ccrs.PlateCarree(),
                     colors='k',
                     linewidths=0.75,
                     linestyles='solid',
                     zorder=5)
    cs3.clabel(fontsize=10,
               inline=1,
               inline_spacing=7,
               fmt='%i',
               rightside_up=True,
               use_clabeltext=True)

    # Plot surface pressure
    ax.contourf(lons,
                lats,
                pmsl.to('hPa'),
                range(990, 1011, 20),
                alpha=0.5,
                transform=ccrs.PlateCarree(),
                colors='yellow',
                zorder=1)

    # Plot surface dewpoint
    ax.contourf(lons,
                lats,
                Td_sfc.to('degF'),
                range(65, 76, 10),
                alpha=0.4,
                transform=ccrs.PlateCarree(),
                colors=['green'],
                zorder=2)

    # Plot 700-hPa dewpoint depression
    ax.contourf(lons,
                lats,
                Td_dep_700,
                range(15, 46, 30),
                alpha=0.5,
                transform=ccrs.PlateCarree(),
                colors='tan',
                zorder=3)

    # Plot Vorticity Advection
    ax.contourf(lons,
                lats,
                vort_adv_500_smooth,
                range(5, 106, 100),
                alpha=0.5,
                transform=ccrs.PlateCarree(),
                colors='BlueViolet',
                zorder=4)

    # Define a skip to reduce the barb point density
    skip_300 = (slice(None, None, 12), slice(None, None, 12))
    skip_500 = (slice(None, None, 10), slice(None, None, 10))
    skip_850 = (slice(None, None, 8), slice(None, None, 8))
    x, y = np.meshgrid(fcst_info['lon'], fcst_info['lat'])
    # 300-hPa wind barbs
    jet300 = ax.barbs(x[skip_300],
                      y[skip_300],
                      u_300[skip_300].m,
                      v_300[skip_300].m,
                      length=6,
                      transform=ccrs.PlateCarree(),
                      color='green',
                      zorder=10,
                      label='300-hPa Jet Core Winds (m/s)')

    # 500-hPa wind barbs
    jet500 = ax.barbs(x[skip_500],
                      y[skip_500],
                      u_500[skip_500].m,
                      v_500[skip_500].m,
                      length=6,
                      transform=ccrs.PlateCarree(),
                      color='blue',
                      zorder=9,
                      label='500-hPa Jet Core Winds (m/s)')

    # 850-hPa wind barbs
    jet850 = ax.barbs(x[skip_850],
                      y[skip_850],
                      u_850[skip_850].m,
                      v_850[skip_850].m,
                      length=6,
                      transform=ccrs.PlateCarree(),
                      color='k',
                      zorder=8,
                      label='850-hPa Jet Core Winds (m/s)')

    # grid lines
    gl = ax.gridlines(crs=datacrs,
                      linewidth=2,
                      color='gray',
                      alpha=0.5,
                      linestyle='--',
                      zorder=40)
    gl.xlocator = mpl.ticker.FixedLocator(np.arange(0, 360, 15))
    gl.ylocator = mpl.ticker.FixedLocator(np.arange(-90, 90, 15))

    #http://earthpy.org/cartopy_backgroung.html
    #C:\ProgramData\Anaconda3\Lib\site-packages\cartopy\data\raster\natural_earth
    ax.background_img(name='RD', resolution='high')

    # Legend
    purple = mpatches.Patch(color='BlueViolet',
                            label='Cyclonic Absolute Vorticity Advection')
    yellow = mpatches.Patch(color='yellow', label='Surface MSLP < 1010 hPa')
    green = mpatches.Patch(color='green', label='Surface Td > 65 F')
    tan = mpatches.Patch(color='tan',
                         label='700 hPa Dewpoint Depression > 15 C')
    red_line = lines.Line2D([], [], color='red', label='Best Lifted Index (C)')
    dashed_black_line = lines.Line2D(
        [], [],
        linestyle='dashed',
        color='k',
        label='12-hr Surface Pressure Falls (hPa)')
    black_line = lines.Line2D([], [],
                              linestyle='solid',
                              color='k',
                              label='12-hr 500-hPa Height Falls (m)')
    leg = plt.legend(handles=[
        jet300, jet500, jet850, dashed_black_line, black_line, red_line,
        purple, tan, green, yellow
    ],
                     loc=3,
                     title='Composite Analysis Valid: ',
                     framealpha=1)
    leg.set_zorder(100)

    #forecast information
    bax = plt.axes([0.01, 0.835, .25, .1], facecolor='#FFFFFFCC')
    bax.set_yticks([])
    bax.set_xticks([])
    bax.axis([0, 10, 0, 10])

    initTime = pd.to_datetime(str(
        fcst_info['init_time'])).replace(tzinfo=None).to_pydatetime()
    fcst_time = initTime + timedelta(hours=fcst_info['fhour'])
    #发布时间
    if (sys.platform[0:3] == 'lin'):
        locale.setlocale(locale.LC_CTYPE, 'zh_CN.utf8')
    if (sys.platform[0:3] == 'win'):
        locale.setlocale(locale.LC_CTYPE, 'chinese')
    plt.text(2.5, 7.5, '起报时间: ' + initTime.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5, 5, '预报时间: ' + fcst_time.strftime("%Y年%m月%d日%H时"), size=15)
    plt.text(2.5, 2.5, '预报时效: ' + str(fcst_info['fhour']) + '小时', size=15)
    plt.text(2.5, 0.5, 'www.nmc.cn', size=15)

    # add south China sea
    if south_China_sea:
        utl.add_south_China_sea(pos=[0.85, 0.13, .1, .2])

    small_city = False
    if (map_extent2[1] - map_extent2[0] < 25):
        small_city = True

    if city:
        utl.add_city_on_map(ax,
                            map_extent=map_extent2,
                            transform=datacrs,
                            zorder=110,
                            size=13,
                            small_city=small_city)

    utl.add_logo_extra_in_axes(pos=[-0.01, 0.835, .1, .1],
                               which='nmc',
                               size='Xlarge')

    # show figure
    if (output_dir != None):
        plt.savefig(output_dir + 'Miller_综合图_预报_' + '起报时间_' +
                    initTime.strftime("%Y年%m月%d日%H时") + '预报时效_' +
                    str(fcst_info['fhour']) + '小时' + '.png',
                    dpi=200)

    if (output_dir == None):
        plt.show()
예제 #5
0
 def horz_line(y):
     l = mlines.Line2D([-inf,inf], [y,y], color=linecolor)
     ax.add_line(l)
예제 #6
0
            marker='v')
plt.scatter(nullfilters2["timeBnull"],
            nullfilters2["magBnull"],
            s=600,
            color='#95d8e6',
            marker='v')
plt.scatter(nullfilters2["timeVnull"],
            nullfilters2["magVnull"],
            s=600,
            color='#9ccc54',
            marker='v')
plt.gca().invert_yaxis()

sn1_uvw2band = mlines.Line2D([], [],
                             color='black',
                             marker='o',
                             markersize=10,
                             label=sn1name + ' UVW2 band')
sn1_uvm2band = mlines.Line2D([], [],
                             color='red',
                             marker='o',
                             markersize=10,
                             label=sn1name + ' UVM2 band')
sn1_uvw1band = mlines.Line2D([], [],
                             color='purple',
                             marker='o',
                             markersize=10,
                             label=sn1name + ' UVW1 band')
sn1_uband = mlines.Line2D([], [],
                          color='orange',
                          marker='o',
예제 #7
0
import matplotlib.pyplot as plotter
import matplotlib.lines as legend_lines
import csv


qb_age=[]
td_act=[]
td_est=[]
with open('qb_td age_curve.csv','r') as csv_file:
    reader=csv.reader(csv_file)
    for row in reader:
        qb_age.append(row[0])
        td_act.append(row[1])
        td_est.append(row[2])

plotter.plot(qb_age,td_act,qb_age,td_est,'k--')
plotter.ylabel('Toucdowns')
plotter.xlabel('QB Age')
blk_line=legend_lines.Line2D([],[],color='black',marker='',markersize=15,label='Touchdown Estimate')
blue_line=legend_lines.Line2D([],[],color='blue',marker='',markersize=15,label='Touchdown Average')
plotter.legend(handles=[blk_line,blue_line])
plotter.show()
예제 #8
0
    def plot_lines_matplotlib(self, relative_thermal_limits, lines_por, lines_service_status):
        layout = self.grid_layout
        my_dpi = 200
        fig = plt.figure(figsize=(1000 / my_dpi, 700 / my_dpi), dpi=my_dpi,
                         facecolor=[c / 255. for c in self.background_color], clear=True)
        l = []

        layout = np.asarray(deepcopy(layout))
        min_x = np.min(layout[:, 0])
        min_y = np.min(layout[:, 1])
        layout[:, 0] -= (min_x + 890)
        layout[:, 0] *= -1
        layout[:, 1] -= min_y
        if self.grid_case == 14:
            layout[:, 0] -= 120
            layout[:, 1] += 30
        for or_id, ex_id, rtl, line_por, is_on in zip(self.lines_ids_or, self.lines_ids_ex, relative_thermal_limits,
                                                      lines_por, lines_service_status):
            # Compute line thickness + color based on its thermal usage
            thickness = .6 + .25 * (min(1., rtl) // .1)

            color_low = np.asarray((51, 204, 51))
            color_middle = np.asarray((255, 165, 0))
            color_high = np.asarray((214, 0, 0))
            if rtl < .5:
                color = color_low + 2. * rtl * (color_middle - color_low)
            else:
                #color = (51, 204, 51) if rtl < .7 else (255, 165, 0) if rtl < 1. else (214, 0, 0)
                color = color_low + min(1., rtl) * (color_high - color_low)

            # Compute the true origin of the flow (lines always fixed or -> dest in IEEE files)
            if line_por >= 0:
                ori = layout[or_id]
                ext = layout[ex_id]
            else:
                ori = layout[ex_id]
                ext = layout[or_id]

            if not is_on:
                l.append(lines.Line2D([ori[0], ext[0]], [50 + ori[1], 50 + ext[1]], linewidth=.8,
                                      color=[.8, .8, .8], figure=fig, linestyle='dashed'))
            else:
                l.append(lines.Line2D([ori[0], ext[0]], [50 + ori[1], 50 + ext[1]], linewidth=thickness,
                                      color=[c / 255. for c in color], figure=fig,
                                      linestyle='--' if rtl > 1. else '-',
                                      dashes=(1., .33) if rtl > 1. else (None, None)))
        fig.lines.extend(l)

        ######## Draw nodes
        # ax = fig.add_subplot(1, 1, 1)
        # ax.set_xlim(np.min(layout[:, 0])-50, np.max(layout[:, 0])+50)
        # ax.set_ylim(np.min(layout[:, 1])-50, np.max(layout[:, 1])+50)
        # #ax.set_facecolor([c / 255. for c in self.background_color])
        # #plt.axis('off')
        # fig.subplots_adjust(0, 0, 1, 1, 0, 0)
        # ax.set_xticks([])
        # ax.set_yticks([])
        # x_offset = int(self.topology_layout_shape[0] / 2.)
        # y_offset = int(self.topology_layout_shape[1] / 2.)
        # prods_iter = iter(prods)
        # loads_iter = iter(loads)
        # patches = []
        # ax.lines.extend(l)
        # for i, ((x, y), is_prod, is_load, is_changed) in enumerate(
        #         zip(layout, self.are_prods, self.are_loads, are_substations_changed)):
        #     print((x, y))
        #     prod = next(prods_iter) if is_prod else 0.
        #     load = next(loads_iter) if is_load else 0.
        #     prod_minus_load = prod - load
        #     relative_prod = abs(prod / np.max(prods))
        #     relative_load = abs(load / np.max(loads))
        #     # Determine color of filled circle based on the amount of production - consumption
        #     if prod_minus_load > 0:
        #         color = (0, 153, 255)
        #         offset_radius = 0 if relative_prod < 0.4 else 2 if relative_prod < 0.7 else 3
        #     elif prod_minus_load < 0:
        #         color = (210, 77, 255)
        #         offset_radius = 0 if relative_load < 0.4 else 2 if relative_load < 0.7 else 3
        #     else:
        #         color = (255, 255, 255)
        #         offset_radius = 0
        #     color = [c / 255. for c in color]
        #     color = [1., 1., 1.]
        #     # Determine the color of the inner filled circle: background if no action changed at the substation,
        #     # yellow otherwise
        #     inner_circle_color = (255, 255, 0) if is_changed else self.background_color
        #     inner_circle_color = [c / 255. for c in inner_circle_color]
        #
        #     c = Circle((x, y), self.nodes_outer_radius, linewidth=3, fill=True, color=color, figure=fig, zorder=10000)
        #     patches.append(c)
        #     print(self.nodes_outer_radius, offset_radius)
        #     #Circle((x, y), self.nodes_inner_radius, fill=True, color=inner_circle_color)
        #
        # p = PatchCollection(patches, alpha=1.)
        # ax.add_collection(p)
        # p.set_array(np.array(color*len(patches)))
        # Export plot into something readable by pygame
        canvas = agg.FigureCanvasAgg(fig)
        canvas.draw()
        renderer = canvas.get_renderer()
        raw_data = renderer.tostring_rgb()
        size = canvas.get_width_height()

        return pygame.image.fromstring(raw_data, size, "RGB")
예제 #9
0
    def plot(self, x):
        """
        Plots the delta space with matplotlib, for every pair of drones.
        TODO: put this outside coordinator.
        :param x: List of np.array of size n_drones and dtype float. Contains, for each step,
        the position for each drone in the coordination space.
        """
        n_axis = int(len(self.__delta) / 2)
        n_cols = int(math.ceil(math.sqrt(n_axis)))
        n_rows = int(math.ceil(1.0 * n_axis / n_cols))

        fig, ax = plt.subplots(n_rows, n_cols, squeeze=False)
        k = 0
        for i in range(self.__n_drones):
            for j in range(self.__n_drones):
                if j <= i:
                    continue

                i_ax = k // n_cols
                j_ax = k % n_cols
                i_drone = self.__i_to_drone_id[i]
                j_drone = self.__i_to_drone_id[j]

                ax[i_ax][j_ax].set_xlim([0, self.__paths[i_drone].length])
                ax[i_ax][j_ax].set_ylim([0, self.__paths[j_drone].length])
                ax[i_ax][j_ax].set_xlabel("drone " + str(i_drone))
                ax[i_ax][j_ax].set_ylabel("drone " + str(j_drone))

                for intersection in self.__delta[i_drone, j_drone]:
                    x1 = intersection.interval_1[0]
                    y1 = intersection.interval_2[0]
                    dx = intersection.interval_1[1] - x1
                    dy = intersection.interval_2[1] - y1
                    ax[i_ax][j_ax].add_patch(
                        patches.Rectangle((x1, y1), dx, dy, facecolor='k'))
                    if intersection.orientation == 1:
                        s = "CW"
                    else:
                        s = "CCW"
                    ax[i_ax][j_ax].text(x1 + dx / 2.0,
                                        y1 + dy / 2.0,
                                        s,
                                        horizontalalignment='center',
                                        verticalalignment='center',
                                        color="w")

                delta_path = self.__delta.get_precalculated_path()[i_drone,
                                                                   j_drone]
                for z in range(len(delta_path) - 1):
                    x1 = delta_path[z].x
                    x2 = delta_path[z + 1].x
                    y1 = delta_path[z].y
                    y2 = delta_path[z + 1].y
                    ax[i_ax][j_ax].add_line(
                        mlines.Line2D([x1, x2], [y1, y2], color="r"))

                for z in range(len(x) - 1):
                    ax[i_ax][j_ax].add_line(
                        mlines.Line2D([x[z][i], x[z + 1][i]],
                                      [x[z][j], x[z + 1][j]],
                                      color="b"))

                k += 1

        try:
            fig.canvas.draw()
            data = list(
                np.fromstring(fig.canvas.tostring_rgb(),
                              dtype=np.uint8,
                              sep=''))
            h = fig.canvas.get_width_height()[1]
            w = fig.canvas.get_width_height()[0]
            img_publisher = rospy.Publisher('delta_space',
                                            Image,
                                            queue_size=10,
                                            latch=True)
            img = Image(height=h,
                        width=w,
                        data=data,
                        encoding="rgb8",
                        step=3 * w)
            img_publisher.publish(img)
        except rospy.ROSException:
            plt.show()
예제 #10
0
def newline(p1, p2):
    ax = plt.gca()
    l = mlines.Line2D([p1[0],p2[0]], [p1[1],p2[1]],color='k',linewidth=2)
    ax.add_line(l)
    return l
예제 #11
0
def plotBaseline(nmrData,
                 savePath=None,
                 figureFormat='png',
                 dpi=72,
                 figureSize=(11, 7)):
    """
	plotBaseline(nmrData, savePath=None, **kwargs)

	Plot spectral baseline at the high and low end of the spectrum. Visualise the median, bounds of 95% variance, and outliers.

	:param NMRDataset nmrData: Dataset object
	:param savePath: If None, plot interactively, otherwise attempt to save at this path
	:type savePath: None or str
	"""
    fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True, figsize=(15, 7), dpi=72)

    localPPM, ppmMask, meanSpectrum, lowerPercentile, upperPercentile = nmrRangeHelper(
        nmrData, (min(nmrData.Attributes['baselineCheckRegion'][0]),
                  max(nmrData.Attributes['baselineCheckRegion'][0])),
        percentiles=(5, 95))
    ax2.plot(localPPM, meanSpectrum, color=(0.46, 0.71, 0.63))
    ax2.fill_between(localPPM,
                     lowerPercentile,
                     y2=upperPercentile,
                     color=(0, 0.4, .3, 0.2))

    for i in range(nmrData.noSamples):

        if nmrData.sampleMetadata.loc[i, 'BaselineFail']:
            ax2.plot(localPPM,
                     nmrData.intensityData[i, ppmMask],
                     color=(0.05, 0.05, 0.8, 0.7))

    localPPM, ppmMask, meanSpectrum, lowerPercentile, upperPercentile = nmrRangeHelper(
        nmrData, (min(nmrData.Attributes['baselineCheckRegion'][1]),
                  max(nmrData.Attributes['baselineCheckRegion'][1])),
        percentiles=(5, 95))
    ax1.plot(localPPM, meanSpectrum, color=(0.46, 0.71, 0.63))
    ax1.fill_between(localPPM,
                     lowerPercentile,
                     y2=upperPercentile,
                     color=(0, 0.4, .3, 0.2))

    for i in range(nmrData.noSamples):

        if nmrData.sampleMetadata.loc[i, 'BaselineFail']:
            ax1.plot(localPPM,
                     nmrData.intensityData[i, ppmMask],
                     color=(0.05, 0.05, 0.8, 0.7))

    ax1.set_xlabel('ppm')
    ax1.invert_xaxis()
    ax1.get_yaxis().set_ticks([])

    ax2.set_xlabel('ppm')
    ax2.invert_xaxis()
    ax2.get_yaxis().set_ticks([])
    ##
    # Set up legend
    ##
    variance = patches.Patch(color=(0, 0.4, 0.3, 0.2),
                             label='Variance about the median')

    failures = lines.Line2D([], [],
                            color=(0.05, 0.05, 0.8, 0.7),
                            marker='',
                            label='Baseline failed on area')
    plt.legend(handles=[variance, failures])

    if savePath:
        plt.savefig(savePath,
                    bbox_inches='tight',
                    format=figureFormat,
                    dpi=dpi)
        plt.close()
    else:
        plt.show()
예제 #12
0
    def render(self, mode='human', output_file=None):
        from matplotlib import animation
        import matplotlib.pyplot as plt
        plt.rcParams['animation.ffmpeg_path'] = '/usr/bin/ffmpeg'

        x_offset = 0.11
        y_offset = 0.11
        cmap = plt.cm.get_cmap('hsv', 10)
        robot_color = 'yellow'
        goal_color = 'red'
        arrow_color = 'red'
        arrow_style = patches.ArrowStyle("->", head_length=4, head_width=2)

        if mode == 'human':
            fig, ax = plt.subplots(figsize=(7, 7))
            ax.set_xlim(-4, 4)
            ax.set_ylim(-4, 4)
            for human in self.humans:
                human_circle = plt.Circle(human.get_position(),
                                          human.radius,
                                          fill=False,
                                          color='b')
                ax.add_artist(human_circle)
            ax.add_artist(
                plt.Circle(self.robot.get_position(),
                           self.robot.radius,
                           fill=True,
                           color='r'))
            plt.show()
        elif mode == 'traj':
            fig, ax = plt.subplots(figsize=(7, 7))
            ax.tick_params(labelsize=16)
            ax.set_xlim(-5, 5)
            ax.set_ylim(-5, 5)
            ax.set_xlabel('x(m)', fontsize=16)
            ax.set_ylabel('y(m)', fontsize=16)

            robot_positions = [
                self.states[i][0].position for i in range(len(self.states))
            ]
            human_positions = [[
                self.states[i][1][j].position for j in range(len(self.humans))
            ] for i in range(len(self.states))]
            for k in range(len(self.states)):
                if k % 4 == 0 or k == len(self.states) - 1:
                    robot = plt.Circle(robot_positions[k],
                                       self.robot.radius,
                                       fill=True,
                                       color=robot_color)
                    humans = [
                        plt.Circle(human_positions[k][i],
                                   self.humans[i].radius,
                                   fill=False,
                                   color=cmap(i))
                        for i in range(len(self.humans))
                    ]
                    ax.add_artist(robot)
                    for human in humans:
                        ax.add_artist(human)
                # add time annotation
                global_time = k * self.time_step
                if global_time % 4 == 0 or k == len(self.states) - 1:
                    agents = humans + [robot]
                    times = [
                        plt.text(agents[i].center[0] - x_offset,
                                 agents[i].center[1] - y_offset,
                                 '{:.1f}'.format(global_time),
                                 color='black',
                                 fontsize=14)
                        for i in range(self.human_num + 1)
                    ]
                    for time in times:
                        ax.add_artist(time)
                if k != 0:
                    nav_direction = plt.Line2D(
                        (self.states[k - 1][0].px, self.states[k][0].px),
                        (self.states[k - 1][0].py, self.states[k][0].py),
                        color=robot_color,
                        ls='solid')
                    human_directions = [
                        plt.Line2D((self.states[k - 1][1][i].px,
                                    self.states[k][1][i].px),
                                   (self.states[k - 1][1][i].py,
                                    self.states[k][1][i].py),
                                   color=cmap(i),
                                   ls='solid') for i in range(self.human_num)
                    ]
                    ax.add_artist(nav_direction)
                    for human_direction in human_directions:
                        ax.add_artist(human_direction)
            plt.legend([robot], ['Robot'], fontsize=16)
            plt.show()
        elif mode == 'video':
            fig, ax = plt.subplots(figsize=(7, 7))
            ax.tick_params(labelsize=16)
            ax.set_xlim(-6, 6)
            ax.set_ylim(-6, 6)
            ax.set_xlabel('x(m)', fontsize=16)
            ax.set_ylabel('y(m)', fontsize=16)

            # add robot and its goal
            robot_positions = [state[0].position for state in self.states]
            goal = mlines.Line2D([0], [4],
                                 color=goal_color,
                                 marker='*',
                                 linestyle='None',
                                 markersize=15,
                                 label='Goal')
            robot = plt.Circle(robot_positions[0],
                               self.robot.radius,
                               fill=True,
                               color=robot_color)
            ax.add_artist(robot)
            ax.add_artist(goal)
            plt.legend([robot, goal], ['Robot', 'Goal'], fontsize=16)

            # add humans and their numbers
            human_positions = [[
                state[1][j].position for j in range(len(self.humans))
            ] for state in self.states]
            humans = [
                plt.Circle(human_positions[0][i],
                           self.humans[i].radius,
                           fill=False) for i in range(len(self.humans))
            ]
            human_numbers = [
                plt.text(humans[i].center[0] - x_offset,
                         humans[i].center[1] - y_offset,
                         str(i),
                         color='black',
                         fontsize=12) for i in range(len(self.humans))
            ]
            for i, human in enumerate(humans):
                ax.add_artist(human)
                ax.add_artist(human_numbers[i])

            # add time annotation
            time = plt.text(-1, 5, 'Time: {}'.format(0), fontsize=16)
            ax.add_artist(time)

            # compute attention scores
            if self.attention_weights is not None:
                attention_scores = [
                    plt.text(-5.5,
                             5 - 0.5 * i,
                             'Human {}: {:.2f}'.format(
                                 i + 1, self.attention_weights[0][i]),
                             fontsize=16) for i in range(len(self.humans))
                ]

            # compute orientation in each step and use arrow to show the direction
            radius = self.robot.radius
            if self.robot.kinematics == 'unicycle':
                orientation = [
                    ((state[0].px, state[0].py),
                     (state[0].px + radius * np.cos(state[0].theta),
                      state[0].py + radius * np.sin(state[0].theta)))
                    for state in self.states
                ]
                orientations = [orientation]
            else:
                orientations = []
                for i in range(self.human_num + 1):
                    orientation = []
                    for state in self.states:
                        if i == 0:
                            agent_state = state[0]
                        else:
                            agent_state = state[1][i - 1]
                        theta = np.arctan2(agent_state.vy, agent_state.vx)
                        orientation.append(
                            ((agent_state.px, agent_state.py),
                             (agent_state.px + radius * np.cos(theta),
                              agent_state.py + radius * np.sin(theta))))
                    orientations.append(orientation)
            arrows = [[
                patches.FancyArrowPatch(*orientation[0],
                                        color=arrow_color,
                                        arrowstyle=arrow_style)
                for orientation in orientations
            ]]
            for arrow in arrows[0]:
                ax.add_artist(arrow)
            global_step = [0]

            def update(frame_num):
                # nonlocal global_step
                # nonlocal arrows
                global_step[0] = frame_num
                robot.center = robot_positions[frame_num]
                for i, human in enumerate(humans):
                    human.center = human_positions[frame_num][i]
                    human_numbers[i].set_position((human.center[0] - x_offset,
                                                   human.center[1] - y_offset))
                    for arrow in arrows[0]:
                        arrow.remove()
                    arrows = [
                        patches.FancyArrowPatch(*orientation[frame_num],
                                                color=arrow_color,
                                                arrowstyle=arrow_style)
                        for orientation in orientations
                    ]
                    for arrow in arrows[0]:
                        ax.add_artist(arrow)
                    if self.attention_weights is not None:
                        human.set_color(
                            str(self.attention_weights[frame_num][i]))
                        attention_scores[i].set_text('human {}: {:.2f}'.format(
                            i, self.attention_weights[frame_num][i]))

                time.set_text('Time: {:.2f}'.format(frame_num *
                                                    self.time_step))

            def plot_value_heatmap():
                assert self.robot.kinematics == 'holonomic'
                for agent in [self.states[global_step][0]
                              ] + self.states[global_step][1]:
                    print(('{:.4f}, ' * 6 + '{:.4f}').format(
                        agent.px, agent.py, agent.gx, agent.gy, agent.vx,
                        agent.vy, agent.theta))
                # when any key is pressed draw the action value plot
                fig, axis = plt.subplots()
                speeds = [0] + self.robot.policy.speeds
                rotations = self.robot.policy.rotations + [np.pi * 2]
                r, th = np.meshgrid(speeds, rotations)
                z = np.array(self.action_values[global_step %
                                                len(self.states)][1:])
                z = (z - np.min(z)) / (np.max(z) - np.min(z))
                z = np.reshape(z, (16, 5))
                polar = plt.subplot(projection="polar")
                polar.tick_params(labelsize=16)
                mesh = plt.pcolormesh(th, r, z, vmin=0, vmax=1)
                plt.plot(rotations, r, color='k', ls='none')
                plt.grid()
                cbaxes = fig.add_axes([0.85, 0.1, 0.03, 0.8])
                cbar = plt.colorbar(mesh, cax=cbaxes)
                cbar.ax.tick_params(labelsize=16)
                plt.show()

            def on_click(event):
                anim.running ^= True
                if anim.running:
                    anim.event_source.stop()
                    if hasattr(self.robot.policy, 'action_values'):
                        plot_value_heatmap()
                else:
                    anim.event_source.start()

            fig.canvas.mpl_connect('key_press_event', on_click)
            anim = animation.FuncAnimation(fig,
                                           update,
                                           frames=len(self.states),
                                           interval=self.time_step * 1000)
            anim.running = True

            if output_file is not None:
                ffmpeg_writer = animation.writers['ffmpeg']
                writer = ffmpeg_writer(fps=8,
                                       metadata=dict(artist='Me'),
                                       bitrate=1800)
                anim.save(output_file, writer=writer)
            else:
                plt.show()
        else:
            raise NotImplementedError
예제 #13
0
def showdatas(datingDataMat, datingLabels):
    font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc",
                          size=14)  #设置汉字格式,r表示不转义,即字符串中\保留
    fig, axs = plt.subplots(nrows=2,
                            ncols=2,
                            sharex=False,
                            sharey=False,
                            figsize=(13, 8))  #fig画布大小为13*8,nrow和ncol表示分布在几行几列
    #fig, axs = plt.subplots(nrows=2, ncols=2, sharex=False, sharey=False, figsize=(13, 8))
    numberOFLabels = len(datingLabels)
    LabelsColors = []
    for i in datingLabels:
        if i == 1:
            LabelsColors.append('black')
        if i == 2:
            LabelsColors.append('orange')
        if i == 3:
            LabelsColors.append('red')  #标记各个标签的颜色
    axs[0][0].scatter(x=datingDataMat[:, 0],
                      y=datingDataMat[:, 1],
                      color=LabelsColors,
                      s=15,
                      alpha=0.5)  #s表示散点大小为15,alpha表示透明度为0.5
    axs0_title_text = axs[0][0].set_title(u'每年获得的飞行常用里程数与玩视频游戏所消耗时间占比',
                                          FontProperties=font)  #u防止中文字符串出现乱码
    axs0_xlabel_text = axs[0][0].set_xlabel(u'每年获得的飞行常用里程数',
                                            FontProperties=font)
    axs0_ylabel_text = axs[0][0].set_ylabel(u'玩视频游戏所消耗时间占比',
                                            FontProperties=font)
    plt.setp(axs0_title_text, size=9, weight='bold', color='red')
    plt.setp(axs0_xlabel_text, size=7, weight='bold', color='black')
    plt.setp(axs0_ylabel_text, size=7, weight='bold', color='black')

    axs[0][1].scatter(x=datingDataMat[:, 0],
                      y=datingDataMat[:, 2],
                      color=LabelsColors,
                      s=15,
                      alpha=.5)
    axs1_title_text = axs[0][1].set_title(u'每年获得的飞行常用里程数与每周消费的冰激淋公升数',
                                          FontProperties=font)
    axs1_xlabel_text = axs[0][1].set_xlabel(u'每年获得的飞行常用里程数',
                                            FontProperties=font)
    axs1_ylabel_text = axs[0][1].set_ylabel(u'每周消费的冰激淋公升数',
                                            FontProperties=font)
    plt.setp(axs1_title_text, size=9, weight='bold', color='red')
    plt.setp(axs1_xlabel_text, size=7, weight='bold', color='black')
    plt.setp(axs1_ylabel_text, size=7, weight='bold', color='black')

    axs[1][0].scatter(x=datingDataMat[:, 1],
                      y=datingDataMat[:, 2],
                      color=LabelsColors,
                      s=15,
                      alpha=.5)
    axs2_title_text = axs[1][0].set_title(u'玩视频游戏所消耗时间占比与每周消费的冰激淋公升数',
                                          FontProperties=font)
    axs2_xlabel_text = axs[1][0].set_xlabel(u'玩视频游戏所消耗时间占比',
                                            FontProperties=font)
    axs2_ylabel_text = axs[1][0].set_ylabel(u'每周消费的冰激淋公升数',
                                            FontProperties=font)
    plt.setp(axs2_title_text, size=9, weight='bold', color='red')
    plt.setp(axs2_xlabel_text, size=7, weight='bold', color='black')
    plt.setp(axs2_ylabel_text, size=7, weight='bold', color='black')
    didntLike = mlines.Line2D([], [],
                              color='black',
                              marker='.',
                              markersize=6,
                              label='didntLike')
    smallDoses = mlines.Line2D([], [],
                               color='orange',
                               marker='.',
                               markersize=6,
                               label='smallDoses')
    largeDoses = mlines.Line2D([], [],
                               color='red',
                               marker='.',
                               markersize=6,
                               label='largeDoses')  #设置图例

    axs[0][0].legend(handles=[didntLike, smallDoses, largeDoses])
    axs[0][1].legend(handles=[didntLike, smallDoses, largeDoses])
    axs[1][0].legend(handles=[didntLike, smallDoses, largeDoses])  #添加图例

    plt.show()  #显示图片
예제 #14
0
파일: 4_2.py 프로젝트: Akead/FT_II_I
    def plot(self):

        fig, ax = plt.subplots()
        legend = []
        right_flag = False
        for x, y, options in zip(self._x, self._y, self._plot_options):
            if self._settings.setdefault('log', False):
                if options.setdefault('right_axis', None) is not None:
                    right_flag = True
                    ax_right = ax.twinx()
                    line, = ax_right.loglog(x, y)
                else:
                    right_flag = False
                    line, = ax.loglog(x, y)

            else:
                if options.setdefault('right_axis', None) is not None:
                    right_flag = True
                    ax_right = ax.twinx()
                    line, = ax_right.plot(x, y)
                else:
                    right_flag = False
                    line, = ax.plot(x, y)

            color = options['color'] if options.setdefault(
                'color', None) is not None else 'black'
            linestyle = options['linestyle'] if options.setdefault(
                'linestyle', None) is not None else 'solid'
            marker = options['marker'] if options.setdefault(
                'marker', None) is not None else None
            markersize = options['markersize'] if options.setdefault(
                'markersize', None) is not None else 6
            label = options['legend'] if options.setdefault(
                'legend', None) is not None else ''

            line.set_color(color)
            line.set_linestyle(linestyle)
            line.set_linewidth(4)
            line.set_marker(marker)
            line.set_markersize(markersize)
            line.set_markeredgecolor('red')
            description = mlines.Line2D([], [],
                                        label=label,
                                        color=color,
                                        marker=marker,
                                        linestyle=linestyle)
            legend.append(description)

        location = self._settings['location'] if self._settings.setdefault(
            'location', None) is not None else 'lower right'
        if label:
            ax.legend(handles=legend,
                      loc=location,
                      fontsize='large',
                      prop={'size': 30})
        ax.set(title=self._settings['title'],
               xlabel=self._settings['x_label'],
               ylabel=self._settings['y_label'])
        if right_flag:
            ax_right.set(ylabel=self._settings['y_right_label'])
            ax_right.yaxis.label.set_size(18)
            ax_right.tick_params(labelsize='large')
            ax_right.grid()
        ax.grid()
        ax.xaxis.label.set_size(18)
        ax.yaxis.label.set_size(18)
        ax.title.set_size(18)
        ax.tick_params(labelsize='large')
        ax.get_figure().set_size_inches(18.5, 10.5, forward=True)

        if self._plot:
            plt.show()

        if self._save:
            fig.savefig(self._settings['name'], dpi=100, bbox_inches='tight')
            plt.close()
#prepare array of no wear indexes
no_wear=[]

#plot entire signal x and night time
ploty.figure(num=1, figsize=(20,20))
ploty.plot(range(0,len(x_axis)),x_axis,'b-')
ploty.ylabel('g')
ploty.xlabel('samples')
#ploty.axis([0,len(x_axis),-6,6])
ploty.title(plot_filename+' x axis')
ploty.xticks(range(0,len(x_axis),144000),[str(x)+" h" for x in range(0,48)])
ploty.axvspan(first_night_begin_index, first_night_end_index, facecolor='b', alpha=0.5)
ploty.axvspan(second_night_begin_index, second_night_end_index, facecolor='b', alpha=0.5)
blue_shade = mpatches.Patch(color='blue', alpha=0.5, label='night (21.00:7.00)')
red_mark = mlines.Line2D([], [], color='red', linewidth=1, linestyle='-', label='no wear')
ploty.legend(handles=([red_mark,blue_shade]))
ploty.show(block=False)

#plot entire signal y and night time
ploty.figure(num=2, figsize=(20,20))
ploty.plot(range(0,len(y_axis)),y_axis,'b-')
ploty.ylabel('g')
ploty.xlabel('samples')
#ploty.axis([0,len(y_axis),-6,6])
ploty.title(plot_filename+' y axis')
ploty.xticks(range(0,len(y_axis),144000),[str(x)+" h" for x in range(0,48)])
ploty.axvspan(first_night_begin_index, first_night_end_index, facecolor='b', alpha=0.5)
ploty.axvspan(second_night_begin_index, second_night_end_index, facecolor='b', alpha=0.5)
blue_shade = mlines.Line2D([], [], color='blue', alpha=0.5, linewidth=4, linestyle='-', label='night (21.00:7.00)')
red_mark = mlines.Line2D([], [], color='red', linewidth=1, linestyle='-', label='no wear')
예제 #16
0
    ## find the maximum z
    zmax = np.nanmax(c_n_approx_trim)

    ## plots
    ax = fig.add_subplot(2, 2, hgrid_id + 1, projection='3d')
    scatter = ax.scatter(mmgrid_trim,
                         kkgrid_trim,
                         cn_StE_trim,
                         marker='v',
                         color='red')
    surface = ax.plot_surface(mmgrid_trim,
                              kkgrid_trim,
                              c_n_approx_trim,
                              cmap='Blues')
    fake2Dline = lines.Line2D(
        [0], [0], linestyle="none", c='b',
        marker='o')  # fake line for making the legend for surface

    ax.contourf(mmgrid_trim,
                kkgrid_trim,
                distr_fix_trim,
                zdir='z',
                offset=np.min(distr_fix_trim),
                cmap=cm.YlOrRd,
                vmin=distr_min,
                vmax=distr_max)
    fake2Dline2 = lines.Line2D(
        [0], [0], linestyle="none", c='orange',
        marker='o')  # fakeline for making the legend for surface

    ax.set_xlabel('m', fontsize=fontsize_lg)
예제 #17
0
ax1.plot(ds18_present.lon,
         tt - 273.15,
         color='k',
         label='Temp2007',
         linestyle='dotted')
ax1.plot(ds18_present.lon,
         tt2,
         color='b',
         label='Temp2011',
         linestyle='dotted')
ax.plot(ds18_present.lon, (temp) / 100, color='grey', label='Deforestation')

rpatch = patches.Patch(color='seagreen', label='Forest fraction 2001 (%)')
rpatch2 = patches.Patch(color='grey', label='Deforestation (%)')
topoline = lines.Line2D([], [],
                        color='b',
                        label='LST deforested',
                        linestyle='dotted')
t2 = lines.Line2D([], [], color='k', label='LST forested', linestyle='dotted')

night = lines.Line2D([], [],
                     color='b',
                     label='2011-2015',
                     linestyle='-',
                     marker='x',
                     markersize=5)
day = lines.Line2D([], [],
                   color='k',
                   label='2005-2009',
                   linestyle='--',
                   marker='o',
                   markersize=5)
예제 #18
0
# training: one-step ahead
fig, ax = plt.subplots(figsize=(12, 7))
#ax.set_title('Training: SSA', fontsize=14)
start = 0
stop = N
for i in range(K_train):
    ax.semilogx(times,
                X_train['target'].iloc[start:stop],
                color='k',
                alpha=0.5,
                linewidth=1)
    start += N
    stop += N
train_targets = mlines.Line2D([], [],
                              color='k',
                              alpha=0.5,
                              linewidth=1,
                              label='Target')
start = 0
stop = N
for i in range(K_train):
    ax.semilogx(times,
                p_ed_tr[start:stop],
                color=blue,
                alpha=0.7,
                linewidth=1,
                linestyle='--')
    start += N
    stop += N
prediction = mlines.Line2D([], [],
                           color=blue,
    def do_plot(self, seedOutDir, plotOutDir, plotOutFileName, simDataFile,
                validationDataFile, metadata):
        return

        HIGHLIGHT_GENES = False
        USE_CACHE = False  # value of this boolean may change (see line 50)

        if not os.path.isdir(seedOutDir):
            raise Exception, "seedOutDir does not currently exist as a directory"

        if not os.path.exists(plotOutDir):
            os.mkdir(plotOutDir)

        # Check if cache from figure5B_E_F_G.py exist
        if os.path.exists(os.path.join(plotOutDir, "figure5B.pickle")):
            figure5B_data = cPickle.load(
                open(os.path.join(plotOutDir, "figure5B.pickle"), "rb"))
            colors = figure5B_data["colors"]
            mrnaIds = figure5B_data["id"].tolist()
        else:
            print "Requires figure5B.pickle from figure5B_E_F_G.py"
            return

        # Check if cache exists
        if os.path.exists(
                os.path.join(plotOutDir, "%s.cPickle" % plotOutFileName)):
            USE_CACHE = True

        # Get all cells
        ap = AnalysisPaths(seedOutDir, multi_gen_plot=True)
        allDir = ap.get_cells()

        # Load sim data
        sim_data = cPickle.load(open(simDataFile, "rb"))
        rnaIds = sim_data.process.transcription.rnaData["id"][
            sim_data.relation.
            rnaIndexToMonomerMapping]  # orders rna IDs to match monomer IDs

        # Make views for monomers
        ids_complexation = sim_data.process.complexation.moleculeNames
        ids_complexation_complexes = sim_data.process.complexation.ids_complexes
        ids_equilibrium = sim_data.process.equilibrium.moleculeNames
        ids_equilibrium_complexes = sim_data.process.equilibrium.ids_complexes
        ids_translation = sim_data.process.translation.monomerData[
            "id"].tolist()
        ids_protein = sorted(
            set(ids_complexation + ids_equilibrium + ids_translation))
        bulkContainer = BulkObjectsContainer(ids_protein, dtype=np.float64)
        view_complexation = bulkContainer.countsView(ids_complexation)
        view_complexation_complexes = bulkContainer.countsView(
            ids_complexation_complexes)
        view_equilibrium = bulkContainer.countsView(ids_equilibrium)
        view_equilibrium_complexes = bulkContainer.countsView(
            ids_equilibrium_complexes)
        view_translation = bulkContainer.countsView(ids_translation)

        # Identify monomers that are subunits for multiple complexes
        monomersInvolvedInManyComplexes = []
        monomersInvolvedInComplexes = []
        for complexId in ids_complexation_complexes:
            subunitIds = sim_data.process.complexation.getMonomers(
                complexId)["subunitIds"]
            for subunitId in subunitIds:
                if subunitId in monomersInvolvedInComplexes:
                    monomersInvolvedInManyComplexes.append(subunitId)
                monomersInvolvedInComplexes.append(subunitId)
        monomersInvolvedInManyComplexes_id = list(
            set(monomersInvolvedInManyComplexes))
        monomersInvolvedInManyComplexes_dict = {}
        for x in monomersInvolvedInManyComplexes_id:
            monomersInvolvedInManyComplexes_dict[x] = {}
        USE_CACHE = False
        if not USE_CACHE:
            # Get average (over timesteps) counts for All genseration (ie. All cells)
            avgRnaCounts_forAllCells = np.zeros(rnaIds.shape[0], np.float64)
            avgProteinCounts_forAllCells = np.zeros(rnaIds.shape[0],
                                                    np.float64)
            for i, simDir in enumerate(allDir):
                simOutDir = os.path.join(simDir, "simOut")

                # Account for bulk molecules
                bulkMolecules = TableReader(
                    os.path.join(simOutDir, "BulkMolecules"))
                bulkMoleculeCounts = bulkMolecules.readColumn("counts")
                moleculeIds = bulkMolecules.readAttribute("objectNames")
                proteinIndexes = np.array([
                    moleculeIds.index(moleculeId) for moleculeId in ids_protein
                ], np.int)
                proteinCountsBulk = bulkMoleculeCounts[:, proteinIndexes]
                rnaIndexes = np.array(
                    [moleculeIds.index(moleculeId) for moleculeId in rnaIds],
                    np.int)
                avgRnaCounts = bulkMoleculeCounts[:, rnaIndexes].mean(axis=0)
                bulkMolecules.close()
                if i == 0:
                    # Skip first few time steps for 1st generation (becaused complexes have not yet formed during these steps)
                    bulkContainer.countsIs(
                        np.mean(proteinCountsBulk[5:, :], axis=0))
                else:
                    bulkContainer.countsIs(proteinCountsBulk.mean(axis=0))

                # Unique molecules
                uniqueMoleculeCounts = TableReader(
                    os.path.join(simOutDir, "UniqueMoleculeCounts"))
                ribosomeIndex = uniqueMoleculeCounts.readAttribute(
                    "uniqueMoleculeIds").index("activeRibosome")
                rnaPolyIndex = uniqueMoleculeCounts.readAttribute(
                    "uniqueMoleculeIds").index("activeRnaPoly")
                nActiveRibosome = uniqueMoleculeCounts.readColumn(
                    "uniqueMoleculeCounts")[:, ribosomeIndex]
                nActiveRnaPoly = uniqueMoleculeCounts.readColumn(
                    "uniqueMoleculeCounts")[:, rnaPolyIndex]
                uniqueMoleculeCounts.close()

                # Account for unique molecules
                bulkContainer.countsInc(nActiveRibosome.mean(), [
                    sim_data.moleculeIds.s30_fullComplex,
                    sim_data.moleculeIds.s50_fullComplex
                ])
                bulkContainer.countsInc(nActiveRnaPoly.mean(),
                                        [sim_data.moleculeIds.rnapFull])

                # Account for small-molecule bound complexes
                view_equilibrium.countsInc(
                    np.dot(sim_data.process.equilibrium.stoichMatrixMonomers(),
                           view_equilibrium_complexes.counts() * -1))

                # Average counts of monomers
                avgMonomerCounts = view_translation.counts()

                # Get counts of "functional units" (ie. complexed forms)
                avgProteinCounts = avgMonomerCounts[:]
                avgComplexCounts = view_complexation_complexes.counts()

                for j, complexId in enumerate(ids_complexation_complexes):
                    # Map all subsunits to the average counts of the complex (ignores counts of monomers)
                    # Some subunits are involved in multiple complexes - these cases are kept track
                    subunitIds = sim_data.process.complexation.getMonomers(
                        complexId)["subunitIds"]

                    for subunitId in subunitIds:
                        if subunitId not in ids_translation:
                            if subunitId in monomerToTranslationMonomer:
                                # couple monomers have different ID in ids_translation
                                subunitId = monomerToTranslationMonomer[
                                    subunitId]
                            elif "CPLX" in subunitId:
                                # few transcription factors are complexed with ions
                                subunitId = complexToMonomer[subunitId]
                            elif "RNA" in subunitId:
                                continue

                        if subunitId not in monomersInvolvedInManyComplexes_id:
                            avgProteinCounts[ids_translation.index(
                                subunitId)] = avgComplexCounts[j]
                        else:
                            if complexId not in monomersInvolvedInManyComplexes_dict[
                                    subunitId]:
                                monomersInvolvedInManyComplexes_dict[
                                    subunitId][complexId] = 0.
                            monomersInvolvedInManyComplexes_dict[subunitId][
                                complexId] += avgComplexCounts[j]

                # Store
                avgRnaCounts_forAllCells += avgRnaCounts
                avgProteinCounts_forAllCells += avgProteinCounts

            # Cache
            D = {
                "rna": avgRnaCounts_forAllCells,
                "protein": avgProteinCounts_forAllCells,
                "monomersInManyComplexes": monomersInvolvedInManyComplexes_dict
            }
            cPickle.dump(
                D,
                open(os.path.join(plotOutDir, "%s.cPickle" % plotOutFileName),
                     "wb"))

        else:
            # Using cached data
            D = cPickle.load(
                open(os.path.join(plotOutDir, "%s.cPickle" % plotOutFileName),
                     "rb"))
            avgRnaCounts_forAllCells = D["rna"]
            avgProteinCounts_forAllCells = D["protein"]
            monomersInvolvedInManyComplexes_dict = D["monomersInManyComplexes"]

        # Per cell
        avgRnaCounts_perCell = avgRnaCounts_forAllCells / float(len(allDir))
        avgProteinCounts_perCell = avgProteinCounts_forAllCells / float(
            len(allDir))

        # Plot
        fig, ax = plt.subplots(1, 1, figsize=(10, 10))

        for monomer in monomersInvolvedInManyComplexes_id:
            index = ids_translation.index(monomer)
            color_index = mrnaIds.index(rnaIds[index])
            color = colors[color_index]

            for complexId in monomersInvolvedInManyComplexes_dict[monomer]:
                avgComplexCount = monomersInvolvedInManyComplexes_dict[
                    monomer][complexId] / float(len(allDir))

                if avgComplexCount == 0:
                    ax.loglog(avgRnaCounts_perCell[index],
                              2.5e-6,
                              alpha=0.5,
                              marker=".",
                              lw=0.,
                              color=color)

                else:
                    if avgRnaCounts_perCell[index] == 0:
                        ax.loglog(PLOT_ZEROS_ON_LINE,
                                  avgComplexCount,
                                  alpha=0.5,
                                  marker=".",
                                  lw=0.,
                                  color=color)
                    else:
                        ax.loglog(avgRnaCounts_perCell[index],
                                  avgComplexCount,
                                  alpha=0.5,
                                  marker=".",
                                  lw=0.,
                                  color=color)

        # plot monomers that are not involved in complexes or involved in only 1 complex
        monomersInvolvedInManyComplexes_index = [
            ids_translation.index(x)
            for x in monomersInvolvedInManyComplexes_id
        ]
        A = [
            x for x in xrange(len(ids_translation))
            if x not in monomersInvolvedInManyComplexes_index
        ]
        for i in A:
            color = colors[mrnaIds.index(rnaIds[i])]
            ax.loglog(avgRnaCounts_perCell[i],
                      avgProteinCounts_perCell[i],
                      alpha=0.5,
                      marker=".",
                      lw=0.,
                      color=color)
        # ax.loglog(avgRnaCounts_perCell[A], avgProteinCounts_perCell[A], alpha = 0.5, marker = ".", lw = 0., color = plot_colors)

        # Plot genes with zero transcripts an arbitrary line
        noTranscripts_indices = [
            x for x in np.where(avgRnaCounts_perCell == 0)[0]
            if x not in monomersInvolvedInManyComplexes_index
        ]
        for i in noTranscripts_indices:
            color = colors[mrnaIds.index(rnaIds[i])]
            ax.loglog(PLOT_ZEROS_ON_LINE,
                      avgProteinCounts_perCell[i],
                      alpha=0.5,
                      marker=".",
                      lw=0.,
                      color=color)

        # Highlight
        if HIGHLIGHT_GENES:
            rnaIds = rnaIds.tolist()
            highlights_rnaId = ["EG12437_RNA[c]",
                                "EG12058_RNA[c]"]  # menE, ccmB
            colors = ["g", "r"]
            for i, rna in enumerate(highlights_rnaId):
                if avgRnaCounts_perCell[rnaIds.index(rna)] == 0:
                    ax.loglog(PLOT_ZEROS_ON_LINE,
                              avgProteinCounts_perCell[rnaIds.index(rna)],
                              marker='.',
                              lw=0.,
                              color=colors[i],
                              ms=15)
                else:
                    ax.loglog(avgRnaCounts_perCell[rnaIds.index(rna)],
                              avgProteinCounts_perCell[rnaIds.index(rna)],
                              marker='.',
                              lw=0.,
                              color=colors[i],
                              ms=15)

            green_dot = mlines.Line2D([], [],
                                      color="green",
                                      linewidth=0.,
                                      marker=".",
                                      markersize=15,
                                      label="menE")
            red_dot = mlines.Line2D([], [],
                                    color="red",
                                    linewidth=0.,
                                    marker=".",
                                    markersize=15,
                                    label="ccmB")
            plt.legend(handles=[green_dot, red_dot], loc="lower right")

        # ax.hlines(1, ax.get_xlim()[0], ax.get_xlim()[1], linestyle = "--")
        ax.hlines(9786.77, ax.get_xlim()[0], ax.get_xlim()[1], linestyle="--")

        ax.set_title(
            "Each (translatable) gene's functional unit is represented as a point\n(ie. x points per gene where x == number of complexes the monomer is involved in)\n(avg across %s generations)"
            % len(allDir))
        ax.set_xlabel("<RNA> per cell")
        ax.set_ylabel("<Functional units (protein)> per cell")
        ax.tick_params(which="both", direction="out")

        plt.subplots_adjust(hspace=0.5,
                            wspace=0.5,
                            left=0.1,
                            bottom=0.1,
                            top=0.9,
                            right=0.95)

        exportFigure(plt, plotOutDir, plotOutFileName, metadata)
        plt.close("all")
예제 #20
0
    def __init__(self, dist_type='bc'):
        super().__init__(dist_type=dist_type)
        if dist_type == 'bc':
            self.pcoa_df = pd.read_csv(
                'sp_output/between_sample_distances/A/20201207T095144_braycurtis_samples_PCoA_coords_A_sqrt.csv'
            )
        else:
            self.pcoa_df = pd.read_csv(
                'sp_output/between_sample_distances/A/20201207T095144_unifrac_sample_PCoA_coords_A_sqrt.csv'
            )
        self.pcoa_df.set_index('sample', inplace=True)
        # Plot species wise
        # four components per species
        self.fig, self.ax_arr = plt.subplots(nrows=4,
                                             ncols=2,
                                             figsize=self._mm2inch(200, 300))
        self.ax_gen = chain.from_iterable(zip(*self.ax_arr))

        # Then Plot up species by ordination
        for species, species_df in zip(['Pocillopra', 'Stylophora'],
                                       [self.pver_df, self.spis_df]):
            for pc in ['PC2', 'PC3', 'PC4', 'PC5']:
                ax = next(self.ax_gen)
                for region in self.region_color_dict.keys():
                    for reef in self.reef_marker_shape_dict.keys():

                        #Get the samples that are of the given region, reef and in the symbiodinium host samples
                        plot_df = species_df[
                            (species_df['REGION'] == region)
                            & (species_df['REEF'].str.contains(reef))]
                        sym_host_plot = [
                            _ for _ in plot_df.index
                            if _ in self.symbiodinium_host_names
                        ]
                        plot_df = self.pcoa_df.loc[sym_host_plot, :]
                        edgecolors = None
                        if reef == 'R4':
                            scatter = ax.scatter(
                                x=plot_df['PC1'],
                                y=plot_df[pc],
                                c=self.region_color_dict[region],
                                marker=self.reef_marker_shape_dict[reef],
                                s=10,
                                alpha=0.8)
                        else:
                            scatter = ax.scatter(
                                x=plot_df['PC1'],
                                y=plot_df[pc],
                                c=self.region_color_dict[region],
                                marker=self.reef_marker_shape_dict[reef],
                                s=10,
                                alpha=0.8,
                                edgecolors=edgecolors,
                                linewidths=0)
                        foo = 'bar'
                if pc == 'PC2':
                    import matplotlib.lines as mlines
                    handles = []
                    for region in self.regions:
                        # The region markers
                        handles.append(
                            mlines.Line2D([], [],
                                          color=self.region_color_dict[region],
                                          marker='o',
                                          markersize=2,
                                          label=region,
                                          linewidth=0))
                    for reef in self.reefs:
                        # The reef markers
                        handles.append(
                            mlines.Line2D(
                                [], [],
                                color='black',
                                marker=self.reef_marker_shape_dict[reef],
                                markersize=2,
                                label=reef,
                                linewidth=0))
                    ax.legend(handles=handles,
                              loc='upper left',
                              fontsize='xx-small')
                    ax.set_title(species, fontsize='x-small')
                ax.set_ylabel(
                    f'{pc} {self.pcoa_df.at["proportion_explained", pc]:.2f}')
                ax.set_xlabel(
                    f'PC1 {self.pcoa_df.at["proportion_explained", "PC1"]:.2f}'
                )
                self._set_lims(ax)
        foo = 'bar'
        plt.tight_layout()
        print('saving .svg')
        plt.savefig(f'{dist_type}_ITS2_ordinations.svg')
        print('saving .png')
        plt.savefig(f'{dist_type}_ITS2_ordinations.png', dpi=1200)
        foo = 'bar'
예제 #21
0
datemin = np.datetime64(days[0])
datemax = np.datetime64(days[364])
ax.set_xlim(datemin, datemax)

## add legend (try make patches circles..)
legend_dict = {
    'Autumn': 'green',
    'Summer': 'red',
    'Winter': 'blue',
    'Spring': 'orange'
}
patchList = []
for key in legend_dict:
    data_key = mlines.Line2D([], [],
                             linestyle="none",
                             marker='o',
                             color=legend_dict[key],
                             label=key)
    patchList.append(data_key)
ax.legend(handles=patchList, loc=8, ncol=2)

plt.xticks(rotation=45)
plt.savefig(os.path.join(outputPath, "daily_avg_dist.png"),
            dpi=600,
            format='png')

plt.show()
""" Creates polarplot for hourly distance travelled eagle owls in each season. Polar plots are arranged in 2 x 2 grid. """


#Create maximum possible value of average hourly distance
예제 #22
0
def draw_rois(image,
              rois,
              refined_rois,
              mask,
              class_ids,
              class_names,
              limit=10):
    """
    anchors: [n, (y1, x1, y2, x2)] list of anchors in image coordinates.
    proposals: [n, 4] the same anchors but refined to fit objects better.
    """
    masked_image = image.copy()

    # Pick random anchors in case there are too many.
    ids = np.arange(rois.shape[0], dtype=np.int32)
    ids = np.random.choice(ids, limit,
                           replace=False) if ids.shape[0] > limit else ids

    fig, ax = plt.subplots(1, figsize=(12, 12))
    if rois.shape[0] > limit:
        plt.title("Showing {} random ROIs out of {}".format(
            len(ids), rois.shape[0]))
    else:
        plt.title("{} ROIs".format(len(ids)))

    # Show area outside image boundaries.
    ax.set_ylim(image.shape[0] + 20, -20)
    ax.set_xlim(-50, image.shape[1] + 20)
    ax.axis('off')

    for i, id in enumerate(ids):
        color = np.random.rand(3)
        class_id = class_ids[id]
        # ROI
        y1, x1, y2, x2 = rois[id]
        p = patches.Rectangle((x1, y1),
                              x2 - x1,
                              y2 - y1,
                              linewidth=2,
                              edgecolor=color if class_id else "gray",
                              facecolor='none',
                              linestyle="dashed")
        ax.add_patch(p)
        # Refined ROI
        if class_id:
            ry1, rx1, ry2, rx2 = refined_rois[id]
            p = patches.Rectangle((rx1, ry1),
                                  rx2 - rx1,
                                  ry2 - ry1,
                                  linewidth=2,
                                  edgecolor=color,
                                  facecolor='none')
            ax.add_patch(p)
            # Connect the top-left corners of the anchor and proposal for easy visualization
            ax.add_line(lines.Line2D([x1, rx1], [y1, ry1], color=color))

            # Label
            label = class_names[class_id]
            ax.text(rx1,
                    ry1 + 8,
                    "{}".format(label),
                    color='w',
                    size=11,
                    backgroundcolor="none")

            # Mask
            m = utils.unmold_mask(mask[id], rois[id][:4].astype(np.int32),
                                  image.shape)
            masked_image = apply_mask(masked_image, m, color)

    ax.imshow(masked_image)

    # Print stats
    print("Positive ROIs: ", class_ids[class_ids > 0].shape[0])
    print("Negative ROIs: ", class_ids[class_ids == 0].shape[0])
    print("Positive Ratio: {:.2f}".format(class_ids[class_ids > 0].shape[0] /
                                          class_ids.shape[0]))
예제 #23
0
def _plot_extreme(handle, rating, packed_contest_subs_problemset, solved, unsolved, legend):
    extremes = [
        (dt.datetime.fromtimestamp(contest.end_time), _get_extremes(contest, problemset, subs))
        for contest, problemset, subs in packed_contest_subs_problemset
    ]
    regular = []
    fullsolves = []
    nosolves = []
    for t, (mn, mx) in extremes:
        if mn and mx:
            regular.append((t, mn, mx))
        elif mx:
            fullsolves.append((t, mx))
        elif mn:
            nosolves.append((t, mn))
        else:
            # No rated problems in the contest, which means rating is not yet available for
            # problems in this contest. Skip this data point.
            pass

    solvedcolor = 'tab:orange'
    unsolvedcolor = 'tab:blue'
    linecolor = '#00000022'
    outlinecolor = '#00000022'

    def scatter_outline(*args, **kwargs):
        plt.scatter(*args, **kwargs)
        kwargs['zorder'] -= 1
        kwargs['color'] = outlinecolor
        if kwargs['marker'] == '*':
            kwargs['s'] *= 3
        elif kwargs['marker'] == 's':
            kwargs['s'] *= 1.5
        else:
            kwargs['s'] *= 2
        if 'alpha' in kwargs:
            del kwargs['alpha']
        if 'label' in kwargs:
            del kwargs['label']
        plt.scatter(*args, **kwargs)

    plt.clf()
    time_scatter, plot_min, plot_max = zip(*regular)
    if unsolved:
        scatter_outline(time_scatter, plot_min, zorder=10,
                        s=14, marker='o', color=unsolvedcolor,
                        label='Easiest unsolved')
    if solved:
        scatter_outline(time_scatter, plot_max, zorder=10,
                        s=14, marker='o', color=solvedcolor,
                        label='Hardest solved')

    ax = plt.gca()
    if solved and unsolved:
        for t, mn, mx in regular:
            ax.add_line(mlines.Line2D((t, t), (mn, mx), color=linecolor))

    if fullsolves:
        scatter_outline(*zip(*fullsolves), zorder=15,
                        s=42, marker='*',
                        color=solvedcolor)
    if nosolves:
        scatter_outline(*zip(*nosolves), zorder=15,
                        s=32, marker='X',
                        color=unsolvedcolor)

    if legend:
        plt.legend(title=f'{handle}: {rating}', title_fontsize=plt.rcParams['legend.fontsize'],
                   loc='upper left').set_zorder(20)
    gc.plot_rating_bg(cf.RATED_RANKS)
    plt.gcf().autofmt_xdate()
t20_ax.yaxis.set_ticklabels([])

# Label positioning:
ylabel_x = -0.11
xlabel_x = 0.4545
xlabel_y = -0.12

sca(t4_ax)
ylabel('$p_i$')
t4_ax.yaxis.set_label_coords(ylabel_x, 0.5)
## Add a legend to this first sub-figure:

leg_cluster = mlines.Line2D([], [],
                            color=colour_cluster,
                            marker='o',
                            ms=5,
                            mew=0,
                            ls='',
                            label='$p_c$')
leg_dipole = mlines.Line2D([], [],
                           color=colour_dipole,
                           marker='o',
                           ms=5,
                           mew=0,
                           ls='',
                           label='$p_d$')
leg_free = mlines.Line2D([], [],
                         color=colour_free,
                         marker='o',
                         ms=5,
                         mew=0,
예제 #25
0
 def vert_line(x):
     l = mlines.Line2D([x,x], [-inf,inf], color=linecolor)
     ax.add_line(l)
예제 #26
0
freq = np.pi / 100
theta = np.pi / 100
input_data = np.cos(freq * (k * np.cos(theta) + m * np.sin(theta)))
output_data = np.fft.fft2(input_data)
print("magnitude response:", np.log(np.abs(output_data)))
fshift = np.fft.fftshift(output_data)
#magnitude_response = 20*np.log(np.abs(fshift))
magnitude_response = np.abs(fshift)
phase_response = np.angle(fshift)
print("Phase Response:", phase_response)
fig, ax = plt.subplots(1, 3)
l1 = ax[0].imshow(input_data, cmap='gray')
ax[0].set(title="PLANE WAVE")
# defining legend style and data
##Reference: https://stackoverflow.com/questions/11983024/matplotlib-legends-not-working
blue_line = mlines.Line2D([], [], color='blue', label='Freq = 0.034')
reds_line = mlines.Line2D([], [], color='red', label='Theta = 0.034')

l = ax[0].legend(handles=[blue_line, reds_line])
l2 = ax[1].imshow(magnitude_response, cmap='gray')
ax[1].set(title="FOURIER MAGNITUDE")
l3 = ax[2].imshow(phase_response, cmap='gray')
ax[2].set(title="FOURIER PHASE")
# plt.show()

### Slider Implitation
#axcolor = 'lightgoldenrodyellow'
axcolor1 = 'red'
axcolor2 = 'blue'
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor2)
axtheta = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor1)
예제 #27
0
#    print(line)
    comparisonOutcome.append(tempList)
#    f.write(line)
#f.close()
my_df = pd.DataFrame(comparisonOutcome)
my_df.to_csv(myDir + 'ComparisonResult.csv', index=False, header=False)

#vanillaExecutionTimes = [800, 800, 100]
#uwExecutionTimes = [100, 200, 800]
times_range = [100, 200, 300, 400, 500, 600, 700, 800, 900]
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
ax.scatter(vanillaExecutionTimes, uwExecutionTimes, color='b')
ax.set_xlabel('Time Taken by OR(seconds)')
ax.set_ylabel('Time Taken by alpha90(seconds)')
line = mlines.Line2D([0, 1], [0, 1], color='red')
transform = ax.transAxes
line.set_transform(transform)
ax.add_line(line)
ax.set_title('scatter plot')
plt.savefig('plot-scatter.png', dpi=300, bbox_inches='tight')
plt.show()

speedUpX = [
    '    < -10x', '    -10 to -2x', '    -2 to -1.5x', '    -1.5x to 0x',
    '    0x to 1.5x', '    1.5 to 2x', '    2 to 5x', '    5 to 10x',
    '    10 to 20x', '    > 20x'
]
speedUpValues = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for x in speedUp:
    if x < float(-10):
예제 #28
0
def draw_boxes(image, boxes=None, refined_boxes=None,
               masks=None, captions=None, visibilities=None,
               title="", ax=None, cmap=None, vmax=None):
    """Draw bounding boxes and segmentation masks with different
    customizations.

    boxes: [N, (y1, x1, y2, x2, class_id)] in image coordinates.
    refined_boxes: Like boxes, but draw with solid lines to show
        that they're the result of refining 'boxes'.
    masks: [N, height, width]
    captions: List of N titles to display on each box
    visibilities: (optional) List of values of 0, 1, or 2. Determine how
        prominent each bounding box should be.
    title: An optional title to show over the image
    ax: (optional) Matplotlib axis to draw on.
    """
    # Number of boxes
    assert boxes is not None or refined_boxes is not None
    N = boxes.shape[0] if boxes is not None else refined_boxes.shape[0]

    # Matplotlib Axis
    if not ax:
        _, ax = plt.subplots(1, figsize=(12, 12))

    # Generate random colors
    colors = random_colors(N)

    # Show area outside image boundaries.
    margin = image.shape[0] // 10
    ax.set_ylim(image.shape[0] + margin, -margin)
    ax.set_xlim(-margin, image.shape[1] + margin)
    ax.axis('off')

    ax.set_title(title)
    ax.imshow(image[:,:,0], cmap=cmap, vmax=vmax)
    masked_image = image.astype(np.uint32).copy()
    for i in range(N):
        # Box visibility
        visibility = visibilities[i] if visibilities is not None else 1
        if visibility == 0:
            color = "gray"
            style = "dotted"
            alpha = 0.5
        elif visibility == 1:
            color = colors[i]
            style = "dotted"
            alpha = 1
        elif visibility == 2:
            color = colors[i]
            style = "solid"
            alpha = 1

        # Boxes
        if boxes is not None:
            if not np.any(boxes[i]):
                # Skip this instance. Has no bbox. Likely lost in cropping.
                continue
            y1, x1, y2, x2 = boxes[i]
            p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2,
                                  alpha=alpha, linestyle=style,
                                  edgecolor=color, facecolor='none')
            ax.add_patch(p)

        # Refined boxes
        if refined_boxes is not None and visibility > 0:
            ry1, rx1, ry2, rx2 = refined_boxes[i].astype(np.int32)
            p = patches.Rectangle((rx1, ry1), rx2 - rx1, ry2 - ry1, linewidth=2,
                                  edgecolor=color, facecolor='none')
            ax.add_patch(p)
            # Connect the top-left corners of the anchor and proposal
            if boxes is not None:
                ax.add_line(lines.Line2D([x1, rx1], [y1, ry1], color=color))

        # Captions
        if captions is not None:
            caption = captions[i]
            # If there are refined boxes, display captions on them
            if refined_boxes is not None:
                y1, x1, y2, x2 = ry1, rx1, ry2, rx2
            ax.text(x1, y1, caption, size=11, verticalalignment='top',
                    color='w', backgroundcolor="none",
                    bbox={'facecolor': color, 'alpha': 0.5,
                          'pad': 2, 'edgecolor': 'none'})

        # Masks
        if masks is not None:
            mask = masks[:, :, i]
            masked_image = apply_mask(masked_image, mask, color)
            # Mask Polygon
            # Pad to ensure proper polygons for masks that touch image edges.
            padded_mask = np.zeros(
                (mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8)
            padded_mask[1:-1, 1:-1] = mask
            contours = find_contours(padded_mask, 0.5)
            for verts in contours:
                # Subtract the padding and flip (y, x) to (x, y)
                verts = np.fliplr(verts) - 1
                p = Polygon(verts, facecolor="none", edgecolor=color)
                ax.add_patch(p)
예제 #29
0
 def patch_line():
     return mlines.Line2D([], [], color=layer_color, label=layer_label)
예제 #30
0
def test_nan_is_sorted():
    line = mlines.Line2D([], [])
    assert line._is_sorted(np.array([1, 2, 3]))
    assert line._is_sorted(np.array([1, np.nan, 3]))
    assert not line._is_sorted([3, 5] + [np.nan] * 100 + [0, 2])