예제 #1
0
def create_hpxmap_hist_figure():
    #fig = plt.figure(figsize=(10.5,4))
    #gridspec=plt.GridSpec(1, 3)
    fig = plt.figure(figsize=(12., 4.))
    gridspec = plt.GridSpec(1, 3, wspace=1.0)
    #gridspec.update(left=0.07,right=0.91,bottom=0.15,top=0.95,wspace=0.08)
    return fig, gridspec
예제 #2
0
def Plot(x, y, legx='', legy=''):
    """
    fig = pl.figure()
    grid = pl.GridSpec(2, 2)
    print(grid)
    ax = fig.add_subplot(grid[0, :])
    pl.plot(tab[whatx],tab[whaty],'k.')

    ax = fig.add_subplot(grid[1, 0])
    ax.hist(tab[whatx],histtype='step')
    
    ax = fig.add_subplot(grid[1, 1])
    ax.hist(tab[whaty],histtype='step')
    """
    fig = pl.figure(figsize=(10, 10))
    grid = pl.GridSpec(4, 4, hspace=0.8, wspace=0.8)
    main_ax = fig.add_subplot(grid[:-1, 1:])
    y_hist = fig.add_subplot(grid[:-1, 0], xticklabels=[], sharey=main_ax)
    x_hist = fig.add_subplot(grid[-1, 1:], yticklabels=[], sharex=main_ax)

    # scatter points on the main axes
    #main_ax.plot(x, y, 'ok', markersize=3, alpha=0.2)
    main_ax.plot(x, y, 'ok', markersize=1.)

    # histogram on the attached axes
    x_hist.hist(x, 40, histtype='step', orientation='vertical', color='red')
    #x_hist.invert_yaxis()

    y_hist.hist(y, 40, histtype='step', orientation='horizontal', color='blue')
    y_hist.invert_xaxis()

    main_ax.set_xlabel(legx)
    main_ax.set_ylabel(legy)
예제 #3
0
파일: fgcmPlotmaps.py 프로젝트: lsst/fgcm
def plot_hpxmap(hpxmap,
                raRange=[-180, 180],
                decRange=[-90, 90],
                lonRef=0.0,
                percRange=[0.1, 99.9],
                figsize=(6.5, 4),
                cbar_kwargs=dict(),
                hpxmap_kwargs=dict()):
    if isinstance(hpxmap, basestring):
        hpxmap = healpy.read_map(f)

    fig = plt.figure(10, figsize=figsize)
    fig.clf()
    gridspec = plt.GridSpec(1, 2)

    bmap = FgcmBasemap(lonRef=lonRef,
                       raMin=raRange[0],
                       raMax=raRange[1],
                       decMin=decRange[0],
                       decMax=decRange[1])
    bmap.create_axes(rect=gridspec[0:2])
    im = bmap.draw_hpxmap(hpxmap, percRange=percRange, **hpxmap_kwargs)
    bmap.draw_inset_colorbar(**cbar_kwargs)
    ax = plt.gca()
    ax.axis['right'].major_ticklabels.set_visible(False)
    ax.axis['top'].major_ticklabels.set_visible(False)

    fig.subplots_adjust(bottom=0.15, top=0.95)

    return fig, ax
def anim_setup():
    fig = py.figure()
    # Define a 2 x 2 grid
    gs = py.GridSpec(2, 2)  # 2 rows, 2 columns

    # Define 3 subplots. First one spanning both rows of column 1, the rest two taking the ramining 2 subplots
    ax_xy = fig.add_subplot(gs[:, 0],
                            aspect=1)  # xy plane (column left, both rows)
    ax_yz = fig.add_subplot(gs[0, 1],
                            aspect=1)  # yz plane (column right, top row)
    ax_xz = fig.add_subplot(gs[1, 1],
                            aspect=1)  # xz plane (column right, bottoom row)

    # Set figure dpi and size
    fig.set_dpi(100)
    fig.set_size_inches(14, 9)

    # Lower and upper limit of the axes of the three subplots

    ax_xy.set_xlim(x_lim[0], x_lim[1])
    ax_xy.set_ylim(y_lim[0], y_lim[1])
    ax_yz.set_xlim(y_lim[0], y_lim[1])
    ax_yz.set_ylim(z_lim[0], z_lim[1])
    ax_xz.set_xlim(x_lim[0], x_lim[1])
    ax_xz.set_ylim(z_lim[0], z_lim[1])

    # Initialize bead patches
    beads_xy = []
    beads_yz = []
    beads_xz = []

    for p in range(Np):
        cl_p = particle_color(p)  # Defined in geometry_draw_X.py module

        beads_xy.append(
            plt.patches.Circle((r_um[0, p, 0], r_um[1, p, 0]),
                               ro[p] * 1e6,
                               fc=cl_p,
                               ec='k',
                               zorder=10))
        beads_yz.append(
            plt.patches.Circle((r_um[1, p, 0], r_um[2, p, 0]),
                               ro[p] * 1e6,
                               fc=cl_p,
                               ec='k',
                               zorder=10))
        beads_xz.append(
            plt.patches.Circle((r_um[0, p, 0], r_um[2, p, 0]),
                               ro[p] * 1e6,
                               fc=cl_p,
                               ec='k',
                               zorder=10))

    time_template = 'Time = %.1f s'
    time_string = ax_xy.text(0.05, 0.90, '', transform=ax_xy.transAxes)
    text_string1 = ax_xy.text(0.05, 0.85, '', transform=ax_xy.transAxes)
    text_string2 = ax_xy.text(0.05, 0.80, '', transform=ax_xy.transAxes)

    return fig, ax_xy, ax_yz, ax_xz, beads_xy, beads_yz, beads_xz, time_template, time_string, text_string1, text_string2
예제 #5
0
def Plot(med_log,
         bands,
         season,
         whata,
         whatb,
         simu_name,
         thetype,
         saveplot=False):

    if saveplot:
        dirout = 'Plots_' + simu_name + '_' + thetype + '/Season_' + str(
            season)
        if not os.path.isdir(dirout):
            os.makedirs(dirout)

    for band in bands:
        idxb = med_log['band'] == band
        sel = med_log[idxb]
        """
        figa, axa = plt.subplots(ncols=1, nrows=1)
        figa.suptitle(band+' band')
        axa.plot(sel[whata],sel[whatb],'k.')
        axa.set_xlabel(whata)
        axa.set_ylabel(whatb)
        """
        fig = plt.figure(figsize=(10, 10))
        fig.suptitle('Season ' + str(season) + ' - ' + band + ' band')
        grid = plt.GridSpec(4, 4, hspace=0.8, wspace=0.8)
        main_ax = fig.add_subplot(grid[:-1, 1:])
        y_hist = fig.add_subplot(grid[:-1, 0], xticklabels=[], sharey=main_ax)
        x_hist = fig.add_subplot(grid[-1, 1:], yticklabels=[], sharex=main_ax)

        # scatter points on the main axes
        #main_ax.plot(x, y, 'ok', markersize=3, alpha=0.2)
        main_ax.plot(sel[whata], sel[whatb], 'ok', markersize=1.)

        # histogram on the attached axes
        x_hist.hist(sel[whata],
                    40,
                    histtype='step',
                    orientation='vertical',
                    color='red')
        #x_hist.invert_yaxis()

        y_hist.hist(sel[whatb],
                    40,
                    histtype='step',
                    orientation='horizontal',
                    color='blue')
        y_hist.invert_xaxis()

        main_ax.set_xlabel(whata)
        main_ax.set_ylabel(whatb)
        if saveplot:
            plt.gcf().savefig(dirout + '/' + whata + '_' + whatb + '_' + band +
                              '.png',
                              bbox_inches='tight')
예제 #6
0
def anim_setup():
    fig = py.figure()
    # Define a 2 x 2 grid
    gs = py.GridSpec(2, 2)  # 2 rows, 2 columns

    # Define 3 subplots. First one spanning both rows of column 1, the rest two taking the ramining 2 subplots
    ax1 = fig.add_subplot(gs[:, 0],
                          aspect=1)  # xy plane (column left, both rows)
    ax2 = fig.add_subplot(gs[0, 1],
                          aspect=1)  # yz plane (column right, top row)
    ax3 = fig.add_subplot(gs[1, 1],
                          aspect=1)  # xz plane (column right, bottoom row)

    # Set figure dpi and size
    fig.set_dpi(100)
    fig.set_size_inches(14, 6)

    # Lower and upper limit of the axes of the three subplots

    ax1.set_xlim(-1e6 * xrange_limit, 1e6 * xrange_limit)
    ax1.set_ylim(-1e6 * xrange_limit, 1e6 * xrange_limit)
    ax2.set_xlim(-1e6 * xrange_limit, 1e6 * xrange_limit)
    ax2.set_ylim(1e6 * zlow_limit, 1e6 * zhigh_limit)
    ax3.set_xlim(-1e6 * xrange_limit, 1e6 * xrange_limit)
    ax3.set_ylim(1e6 * zlow_limit, 1e6 * zhigh_limit)

    # Initialize bead patches
    beads_xy = []
    beads_yz = []
    beads_xz = []

    for p in range(Np):
        beads_xy.append(
            plt.patches.Circle((r_um[0, p, 0], r_um[1, p, 0]),
                               ro[p] * 1e6,
                               fc='#C21808',
                               ec='k',
                               zorder=10))
        beads_yz.append(
            plt.patches.Circle((r_um[1, p, 0], r_um[2, p, 0]),
                               ro[p] * 1e6,
                               fc='#C21808',
                               ec='k',
                               zorder=10))
        beads_xz.append(
            plt.patches.Circle((r_um[0, p, 0], r_um[2, p, 0]),
                               ro[p] * 1e6,
                               fc='#C21808',
                               ec='k',
                               zorder=10))

    time_template = 'Time = %.1f s'
    time_string = ax1.text(0.05, 0.9, '', transform=ax1.transAxes)

    return fig, ax1, ax2, ax3, beads_xy, beads_yz, beads_xz, time_template, time_string
def plot_neuron(tp):
    fig2 = py.figure(figsize=(9, 6), dpi=200)
    grid = py.GridSpec(8, 8, hspace=0.1, wspace=0.1)
    ax = fig2.add_subplot(grid[:-1, 1:7], projection='3d')
    ax.set_title('True CSD')
    #    ax.scatter(posxyz[0], posxyz[1], posxyz[2], alpha = 0.1, s = 20,
    #               c = vs[:, tp], cmap='PRGn', vmin = -60, vmax = 60, antialiased=True)
    #    ax.scatter(posswc[2, ::skip], posswc[3, ::skip], posswc[4, ::skip], alpha = 0.5, s = 8,
    #               c = vs[:1216, tp], cmap='PRGn', vmin = -60, vmax = 60, antialiased=True)
    ax.scatter(posswc[3, ::skip],
               posswc[2, ::skip],
               posswc[4, ::skip],
               alpha=0.1,
               s=12,
               c='grey',
               linewidths=0,
               antialiased=True)
    ax.scatter(wsp_ele[1],
               wsp_ele[0],
               wsp_ele[2],
               alpha=1,
               s=6,
               c=pots[tp, :],
               cmap='PRGn',
               vmin=-0.2,
               vmax=0.2,
               linewidths=0.5,
               edgecolors='black',
               antialiased=True)
    ax.scatter(posxyz[1],
               posxyz[0],
               posxyz[2],
               alpha=0.5,
               s=15,
               c=-ks[:, tp] - nas[:, tp] - pas[n, tp],
               cmap=cm.bwr,
               vmin=-0.3,
               vmax=0.3,
               antialiased=True)
    ax3 = fig2.add_subplot(grid[-1, 1:-1])

    ax3.plot(xtime, pots[:, 0], label='ele bot')
    ax3.plot(xtime, pots[:, 15], label='ele mid')
    ax3.plot(xtime, pots[:, 31], label='ele top')
    py.legend()
    ax3.spines['right'].set_visible(False)
    ax3.spines['top'].set_visible(False)
    ax3.spines['bottom'].set_visible(False)

    ax3.set_xlim(100, 150)
    ax3.axvline(xtime[tp], linestyle='--')
    ax.view_init(elev=90, azim=0)
    return fig2
    def plot_facade_cuts(self):

        facade_sig = self.facade_edge_scores.sum(0)
        facade_cuts = find_facade_cuts(
            facade_sig, dilation_amount=self.facade_merge_amount)
        mu = np.mean(facade_sig)
        sigma = np.std(facade_sig)

        w = self.rectified.shape[1]
        pad = 10

        gs1 = pl.GridSpec(5, 5)
        gs1.update(wspace=0.5, hspace=0.0)  # set the spacing between axes.

        pl.subplot(gs1[:3, :])
        pl.imshow(self.rectified)
        pl.vlines(facade_cuts, *pl.ylim(), lw=2, color='black')
        pl.axis('off')
        pl.xlim(-pad, w + pad)

        pl.subplot(gs1[3:, :], sharex=pl.gca())
        pl.fill_between(np.arange(w), 0, facade_sig, lw=0, color='red')
        pl.fill_between(np.arange(w),
                        0,
                        np.clip(facade_sig, 0, mu + sigma),
                        color='blue')
        pl.plot(np.arange(w), facade_sig, color='blue')

        pl.vlines(facade_cuts,
                  facade_sig[facade_cuts],
                  pl.xlim()[1],
                  lw=2,
                  color='black')
        pl.scatter(facade_cuts, facade_sig[facade_cuts])

        pl.axis('off')

        pl.hlines(mu, 0, w, linestyle='dashed', color='black')
        pl.text(0, mu, '$\mu$ ', ha='right')

        pl.hlines(
            mu + sigma,
            0,
            w,
            linestyle='dashed',
            color='gray',
        )
        pl.text(0, mu + sigma, '$\mu+\sigma$ ', ha='right')
        pl.xlim(-pad, w + pad)
def plot_score_test(inputs,test_parameter,test_scores,test_tuning_indexes,test_parameter_label,same_vmax=True,tuning_index_lims=(-0.03,0.6)):
  """
  Plot gridness scores and grid-tuning indexes agains a test parameter (e.g., modulation depth, tuning strengths)
  """
  ms=5

  fig=pl.figure(figsize=(4,2.5))
  pl.subplots_adjust(left=0.2,bottom=0.2,right=0.8)
  
  num_cells=6
  gs = pl.GridSpec(3,num_cells,hspace=0.35,wspace=0.1)
  
  
  cell_idxs=np.linspace(0,n**2-1,num_cells).astype(int)
  vmax=inputs.max()
  for idx,cell_idx in enumerate(cell_idxs):
    ax=fig.add_subplot(gs[0,idx],aspect='equal')
    r_map=inputs[:,cell_idx].reshape(nx,nx).T
    if same_vmax is True:
      ax.pcolormesh(r_map,rasterized=True,vmin=0,vmax=vmax)
    else:
      ax.pcolormesh(r_map,rasterized=True,vmin=0)
      
    pp.noframe(ax)  
    
  ax1 = fig.add_subplot(gs[1:3,0:num_cells])
  
  ax1=pl.gca()
  
  color = 'tab:red'
  ax1.set_xlabel(test_parameter_label)
  ax1.set_ylabel('Grid tuning index', color=color)
  ax1.plot(test_parameter, test_tuning_indexes, color=color,marker='o',lw=0,alpha=.5,ms=ms,mec='none')
  ax1.tick_params(axis='y', labelcolor=color)
  ax1.set_ylim(tuning_index_lims)
  ax1.spines['top'].set_color('none')
  
  pl.plot(test_parameter[cell_idxs],np.ones_like(test_parameter[cell_idxs])*0,'vk')
    
    
  ax2 = ax1.twinx()  
  
  color = 'tab:orange'
  ax2.set_ylabel('Gridness score', color=color)  
  ax2.plot(test_parameter, test_scores, color=color,marker='o',lw=0,alpha=.5,ms=ms,mec='none')
  ax2.tick_params(axis='y', labelcolor=color)
  ax2.set_ylim(-1,2)
  ax2.spines['top'].set_color('none')
예제 #10
0
파일: fgcmPlotmaps.py 프로젝트: lsst/fgcm
def plot_hpxmap_hist(hpxmap,
                     raRange=[-180, 180],
                     decRange=[-90, 90],
                     lonRef=0.0,
                     cbar_kwargs=dict(),
                     hpxmap_kwargs=dict(),
                     hist_kwargs=dict(),
                     fit_gaussian=False,
                     figsize=(10, 4)):

    hist_defaults = dict(peak=True)
    set_defaults(hist_kwargs, hist_defaults)

    if isinstance(hpxmap, basestring):
        hpxmap = healpy.read_map(f)

    fig = plt.figure(10, figsize=figsize)
    fig.clf()
    gridspec = plt.GridSpec(1, 3)

    bmap = FgcmBasemap(lonRef=lonRef,
                       raMin=raRange[0],
                       raMax=raRange[1],
                       decMin=decRange[0],
                       decMax=decRange[1])
    bmap.create_axes(rect=gridspec[0:2])
    im = bmap.draw_hpxmap(hpxmap, **hpxmap_kwargs)
    bmap.draw_inset_colorbar(**cbar_kwargs)
    ax1 = plt.gca()
    ax1.axis['right'].major_ticklabels.set_visible(False)
    ax1.axis['top'].major_ticklabels.set_visible(False)

    ax2 = Subplot(fig, gridspec[2])
    fig.add_subplot(ax2)
    plt.sca(ax2)
    ret = draw_hist(hpxmap, fit_gaussian=fit_gaussian, **hist_kwargs)
    ax2.yaxis.set_major_locator(MaxNLocator(6, prune='both'))
    ax2.xaxis.set_major_locator(MaxNLocator(5))
    ax2.axis['left'].major_ticklabels.set_visible(False)
    ax2.axis['right'].major_ticklabels.set_visible(True)
    ax2.axis['right'].label.set_visible(True)
    ax2.axis['right'].label.set_text(r'Normalized Area (a.u.)')
    ax2.axis['bottom'].label.set_visible(True)

    plt.subplots_adjust(bottom=0.15, top=0.95)

    return fig, [ax1, ax2], ret
def draw():
    #-----Simulation map plot-----------------------------------------------------------------
    grid = pl.GridSpec(3, 2, wspace=0.4, hspace=0.3)
    pl.subplot(grid[0:, 0])
    pl.cla()
    pl.pcolor(envir, cmap = pl.cm.YlOrRd, vmin = 0, vmax = 15)
    pl.axis('image')
    pl.hold(True)
    # Plot the walls on the matrix
    pl.scatter(np.add(wall_x, [0.5]), np.add(wall_y, [0.5]), marker = "s", c = 'gray')
    # Plot the office on the matrix
    pl.scatter(np.add(office_x, [0.5]), np.add(office_y, [0.5]), marker = "s", c = 'gray')
    # Plot the gates on the matrix
    pl.scatter(np.add(gate_x, [0.5]), np.add(gate_y, [0.5]), marker = "s", c = 'green')
    # For each agent plot: location, intention, goal
    for ag in agents:
        # Plot the agent's location on the matrix
        x, y = ag.get_pos()
        pl.scatter(x + 0.5, y + 0.5, c = "dark" + ag.color)
        if(len(ag.goal) > 0):
            goals = ag.goal
            # Plot the agent's goal on the matrix
            pl.scatter(goals[1] + 0.5, goals[0] + 0.5, marker = "x", c = "green")
    pl.title('t = ' + str(time))
    #-----Stats text: Orders -----------------------------------------------------------------
    ax2 = pl.subplot(grid[0, 1])
    ax2.axis("off")
    ax2.invert_yaxis()
    to_plot_string1 = "\nTotal orders: "+ total_numb_orders + "\nDone orders: "+ str(len(orders_list[orders_list["status"] == 2].index))
    ax2.text(0,0, to_plot_string1, verticalalignment="top")
    #-----1° Stats plot: Articles-----------------------------------------------------------------
    pl.subplot(grid[1, 1])
    x = range(0, len(total_stats))
    pl.plot(x,  total_stats["Articles"], color = 'blue')
    pl.title('Articles')
    #-----2° Stats plot: Conflicts-----------------------------------------------------------------
    pl.subplot(grid[2, 1])
    x = range(0, len(total_stats))
    pl.plot(x,  total_stats["Conflicts"], color = 'red')
    pl.title('Conflicts')

    pl.hold(False)
예제 #12
0
    def draw(self):
        fig = _pylab.figure(1)
        gs = _pylab.GridSpec(2, 1, height_ratios=(1, 4))

        axMachine = _pylab.subplot(gs[0])
        axMachine.axes.get_yaxis().set_visible(False)
        self.drawMachine()

        axOptics = _pylab.subplot(gs[1])
        self.plotOptics()

        def machineXlim(ax):
            axMachine.set_autoscale_on(False)
            axOptics.set_xlim(axMachine.get_xlim())

        def click(a):
            if a.button == 3:
                print self.tfs.NameFromNearestS(a.xdata)

        axMachine.callbacks.connect('xlim_changed', machineXlim)
        fig.canvas.mpl_connect('button_press_event', click)
예제 #13
0
plt.show()

plt.imshow(np.resize(mean, (26, 26)), cmap=plt.cm.gray)
plt.title('mean')
plt.show()

diff = np.zeros((213, 676))
for i in range(len(data)):
    diff[i] = data[i].astype('float64') - mean
# end for

plt.imshow(np.resize(diff[0], (26, 26)), cmap=plt.cm.gray)
plt.title('diff image #1')
plt.show()

layout = pylab.GridSpec(213 + 1, 4)
fig = plt.figure()
subplt = fig.add_subplot(layout[0, 0])
subplt.set_title('#')
subplt = fig.add_subplot(layout[0, 1])
subplt.set_title('o')
subplt = fig.add_subplot(layout[0, 2])
subplt.set_title('m')
subplt = fig.add_subplot(layout[0, 3])
subplt.set_title('d')

for i in range(len(data))[::50]:
    subplt = fig.add_subplot(layout[i + 1, 0])
    subplt.set_title('#{}'.format(i))

    subplt = fig.add_subplot(layout[i + 1, 1])
예제 #14
0
def plot_tracking(frame, pos, target_sz, im, ground_truth):
    global tracking_figure, tracking_figure_title, tracking_figure_axes, tracking_rectangle, gt_point,\
        z_figure_axes, response_figure_axes, z, response

    timeout = 1e-6
    # timeout = 0.05  # uncomment to run slower
    if frame == 0:
        # pylab.ion()  # interactive mode on
        tracking_figure = pylab.figure()
        gs = pylab.GridSpec(1, 3, width_ratios=[3, 1, 1])

        tracking_figure_axes = tracking_figure.add_subplot(gs[0])
        tracking_figure_axes.set_title("Tracked object (and ground truth)")

        z_figure_axes = tracking_figure.add_subplot(gs[1])
        z_figure_axes.set_title("Template")

        response_figure_axes = tracking_figure.add_subplot(gs[2])
        response_figure_axes.set_title("Response")

        tracking_rectangle = pylab.Rectangle((0, 0), 0, 0)
        tracking_rectangle.set_color((1, 0, 0, 0.5))
        tracking_figure_axes.add_patch(tracking_rectangle)

        gt_point = pylab.Circle((0, 0), radius=5)
        gt_point.set_color((0, 0, 1, 0.5))
        tracking_figure_axes.add_patch(gt_point)

        tracking_figure_title = tracking_figure.suptitle("")

        pylab.show(block=False)

    elif tracking_figure is None:
        return  # we simply go faster by skipping the drawing
    elif not pylab.fignum_exists(tracking_figure.number):
        # print("Drawing window closed, end of game. "
        #      "Have a nice day !")
        # sys.exit()
        print("From now on drawing will be omitted, "
              "so that computation goes faster")
        tracking_figure = None
        return

    tracking_figure_axes.imshow(im, cmap=pylab.cm.gray)

    rect_y, rect_x = tuple(pos - target_sz / 2.0)
    rect_height, rect_width = target_sz
    tracking_rectangle.set_xy((rect_x, rect_y))
    tracking_rectangle.set_width(rect_width)
    tracking_rectangle.set_height(rect_height)

    if len(ground_truth) > 0:
        gt = ground_truth[frame]
        gt_y, gt_x = gt
        gt_point.center = (gt_x, gt_y)

    if z is not None:
        z_figure_axes.imshow(z, cmap=pylab.cm.hot)

    if response is not None:
        response_figure_axes.imshow(response, cmap=pylab.cm.hot)

    tracking_figure_title.set_text("Frame %i (out of %i)" %
                                   (frame + 1, len(ground_truth)))

    if debug and False and (frame % 1) == 0:
        print("Tracked pos ==", pos)

    # tracking_figure.canvas.draw()  # update
    pylab.draw()
    pylab.waitforbuttonpress(timeout=timeout)

    return
예제 #15
0
def log_tracked(image, tracked_roi, cached, template_f, response_f):
    timeout = 1e-6
    tracking_figure_axes = results.tracking_figure_axes
    tracking_figure = results.tracking_figure
    tracking_figure_title = results.tracking_figure_title
    response_figure_axes = results.response_figure_axes
    tracking_rectangle = results.tracking_rectangle
    gt_rectangle = results.gt_rectangle
    template_axes = results.template_axes

    if not results.initialized:
        # pylab.ion()  # interactive mode on
        tracking_figure = results.tracking_figure = pylab.figure()

        gs = pylab.GridSpec(1, 3, width_ratios=[3, 1, 1])

        tracking_figure_axes = results.tracking_figure_axes = tracking_figure.add_subplot(gs[0])
        tracking_figure_axes.set_title("Tracked object (and ground truth)")

        template_axes = results.template_axes = tracking_figure.add_subplot(gs[1])
        template_axes.set_title("Template")

        response_figure_axes = results.response_figure_axes = tracking_figure.add_subplot(gs[2])
        response_figure_axes.set_title("Response")

        tracking_rectangle = results.tracking_rectangle = pylab.Rectangle((0, 0), 0, 0)
        tracking_rectangle.set_color((1, 1, 0, 0.5))
        tracking_figure_axes.add_patch(tracking_rectangle)

        gt_rectangle = results.gt_rectangle = pylab.Rectangle((0, 0), 0, 0)
        gt_rectangle.set_color((0, 0, 1, 0.5))
        tracking_figure_axes.add_patch(gt_rectangle)

        tracking_figure_title = results.tracking_figure_title = tracking_figure.suptitle("")

        pylab.show(block=False)

    elif tracking_figure is None:
        return  # we simply go faster by skipping the drawing
    elif not pylab.fignum_exists(tracking_figure.number):
        print("From now on drawing will be omitted, "
              "so that computation goes faster")
        results.omitted_at_frame_number = loader.frame_number()
        results.tracking_figure = None
        return

    tracking_figure_axes.imshow(image)

    tracking_rectangle.set_bounds(tracked_roi[0] - tracked_roi[2] / 2, tracked_roi[1] - tracked_roi[3] / 2, tracked_roi[2], tracked_roi[3])

    gt = loader.get_gt_bounding_box()
    gt_rectangle.set_bounds(gt[0], gt[1], gt[2], gt[3])

    if template_f is not None:
        template_axes.imshow(template_f, cmap=pylab.cm.hot)

    if response_f is not None:
        response_figure_axes.imshow(response_f, cmap=pylab.cm.hot)

    tracking_rectangle.set_color((0 if not cached else 1, 0.5 if not cached else 0, 0, 0.7 if not cached else 0.2))

    tracking_figure_title.set_text("Frame {}".format(loader.frame_number()))

    pylab.draw()

    if results.initialized:
        pylab.savefig(loader.get_log_dir() + 'image%05i.jpg' % loader.frame_number(), bbox_inches='tight')

    pylab.waitforbuttonpress(timeout=timeout)

    results.initialized = True

    return
예제 #16
0
def run_single_tilt_angle(ang, subtomogram, offset, vol_size,
                          particle_position, particle_rotation,
                          particle_filename, particle_number, binning, img,
                          create_graphics, fsc_path, dimz, peak_border):
    """
    To run a single tilt angle to allow for parallel computing

    @param ang: the tilt angle
    @type ang: int
    @param subtomogram: the filename of the subtomogram
    @type subtomogram: str
    @param offset: the offset used (x,y,z)
    @type offset: list(int, int, int)
    @param vol_size: the size of the volume to be reconstructed (in pixels)
    @type vol_size: int
    @param particle_position: the position of the particle in vector format,
               as given by particle.pickPosition().toVector()
    @type particle_position: tuple
    @param particle_rotation: the rotation of the particle (Z1/phi, X/the, Z2/psi)
    @type particle_rotation: tuple
    @param particle_filename: the filename of the particle, as given by particle.getfilename()
    @type particle_filename: str
    @param particle_number: the number of the particle, to allow for unique mapping
    @type particle_number: int
    @param binning: the binning factor used
    @type binning: int
    @param img: the filename of the projection to be used
    @type img: str
    @param create_graphics: to flag if images should be created for human inspection of the work done
    @type create_graphics: bool
    @return: the newly found positions of the particle, as a list  in the LOCAL_ALIGNMENT_RESULTS format
    @returntype: list
    """

    print(ang, offset, binning, particle_position)
    from pytom.tompy.transform import rotate3d
    import numpy as np
    from math import cos, sin, pi
    from pytom.tompy.transform import cut_from_projection
    from pytom.tompy.io import read

    subtomogram = read(subtomogram)
    img = read(img)

    # Get the size of the original projection
    dim_x = img.shape[0]
    dim_z = dim_x if dimz is None else dimz
    print(dim_x, dim_z)

    x, y, z = particle_position
    x = (x + offset[0]) * binning
    y = (y + offset[1]) * binning
    z = (z + offset[2]) * binning

    # Get template
    # First rotate towards orientation of the particle, then to the tilt angle
    rotated1 = rotate3d(subtomogram,
                        phi=particle_rotation[0],
                        the=particle_rotation[1],
                        psi=particle_rotation[2])
    rotated2 = rotate3d(rotated1, the=ang)  # 'the' is the rotational axis
    template = rotated2.sum(axis=2)

    # Get coordinates of the paricle adjusted for the tilt angle
    yy = y  # assume the rotation axis is around y
    xx = (cos(ang * pi / 180) * (x - dim_x / 2) - sin(ang * pi / 180) *
          (z - dim_z / 2)) + dim_x / 2

    # Cut the small patch out
    patch = cut_from_projection(img.sum(axis=2), [xx, yy],
                                [vol_size, vol_size])
    patch = patch - patch.mean()

    # Filter using FSC
    fsc_mask = None
    import os
    if os.path.isfile(fsc_path):
        f = open(fsc_path, "r")
        fsc = map(lambda a: float(a), f.readlines())
        f.close()
        fsc_mask = create_fsc_mask(fsc, vol_size)
    elif fsc_path != "":
        print("Not an existing FSC file: " + fsc_path)

    # Cross correlate the template and patch, this should give the pixel shift it is after
    ccf = normalised_cross_correlation(template, patch, fsc_mask)
    points2d = find_sub_pixel_max_value_2d(ccf, ignore_border=peak_border)

    x_diff = points2d[0] - vol_size / 2
    y_diff = points2d[1] - vol_size / 2

    if create_graphics:
        # Create an image to display and/or test the inner workings of the algorithm
        m_style = dict(color='tab:blue',
                       linestyle=':',
                       marker='o',
                       markersize=5,
                       markerfacecoloralt='tab:red')
        m_style_alt = dict(color='tab:red',
                           linestyle=':',
                           marker='o',
                           markersize=5,
                           markerfacecoloralt='tab:blue')

        points = find_sub_pixel_max_value(ccf)

        nx, ny, nz = particle_position
        nx += x_diff
        ny += y_diff

        npatch = cut_from_projection(
            img.sum(axis=2), [xx + x_diff, yy + y_diff], [vol_size, vol_size]
        )  # img.sum(axis=2)[int(xx+x_diff-v):int(xx+x_diff+v), int(yy+y_diff-v):int(yy+y_diff+v)]  #
        npatch = npatch - np.mean(npatch)

        nccf = normalised_cross_correlation(template, npatch.squeeze())
        npoints = find_sub_pixel_max_value(nccf)
        npoints2d = find_sub_pixel_max_value_2d(nccf,
                                                ignore_border=peak_border)

        import pylab as pp

        grid = pp.GridSpec(3,
                           3,
                           wspace=0,
                           hspace=0.35,
                           left=0.05,
                           right=0.95,
                           top=0.90,
                           bottom=0.05)

        ax_0_0 = pp.subplot(grid[0, 0])
        ax_0_1 = pp.subplot(grid[0, 1])
        ax_0_2 = pp.subplot(grid[0, 2])
        ax_1_0 = pp.subplot(grid[1, 0])
        ax_1_1 = pp.subplot(grid[1, 1])
        ax_1_2 = pp.subplot(grid[1, 2])
        ax_2_0 = pp.subplot(grid[2, 0])
        ax_2_1 = pp.subplot(grid[2, 1])
        ax_2_2 = pp.subplot(grid[2, 2])

        ax_0_0.axis('off')
        ax_0_1.axis('off')
        ax_0_2.axis('off')
        ax_1_0.axis('off')
        ax_1_1.axis('off')
        ax_1_2.axis('off')
        ax_2_0.axis('off')
        ax_2_1.axis('off')
        ax_2_2.axis('off')

        axis_title(ax_0_0, "Cutout")
        ax_0_0.imshow(patch)
        axis_title(ax_0_1, "Template")
        ax_0_1.imshow(template)
        axis_title(ax_0_2, "Shifted Cutout\n(based on cross correlation)")
        ax_0_2.imshow(npatch.squeeze())

        axis_title(ax_1_0, u"Cross correlation\ncutout × template")
        ax_1_0.imshow(ccf)
        ax_1_0.plot([p[1] for p in points], [p[0] for p in points],
                    fillstyle='none',
                    **m_style)
        ax_1_0.plot([points2d[1]], [points2d[0]],
                    fillstyle='none',
                    **m_style_alt)
        ax_1_0.plot([vol_size / 2], [vol_size / 2], ",k")

        ax_1_1.text(
            0.5,
            0.8,
            "Red: 2D spline interpolation\nx: {:f}\ny: {:f}\nBlue: 1D spline interpolation\nx: {:f}\ny: {:f}"
            "\nBlack: center".format(x_diff, y_diff,
                                     points[0][0] - vol_size / 2,
                                     points[0][1] - vol_size / 2),
            fontsize=8,
            horizontalalignment='center',
            verticalalignment='center',
            transform=ax_1_1.transAxes)

        axis_title(ax_1_2, u"Cross correlation\nshifted cutout × template")
        ax_1_2.imshow(nccf)
        ax_1_2.plot([p[0] for p in npoints], [p[1] for p in npoints],
                    fillstyle='none',
                    **m_style)
        ax_1_2.plot([npoints2d[0]], [npoints2d[1]],
                    fillstyle='none',
                    **m_style_alt)
        ax_1_2.plot([vol_size / 2], [vol_size / 2], ",k")

        axis_title(ax_2_0, u"Zoom into red peak\nin CC cutout × template")
        d = 10
        peak = ccf[int(points2d[0]) - d:int(points2d[0]) + d,
                   int(points2d[1]) - d:int(points2d[1] + d)]
        ax_2_0.imshow(peak)

        axis_title(
            ax_2_1,
            u"Zoom into red peak\nin CC cutout × template\ninterpolated")
        ax_2_1.imshow(points2d[2])

        axis_title(ax_2_2, u"Cutout\nGaussian filter σ3")
        import scipy
        ax_2_2.imshow(scipy.ndimage.gaussian_filter(patch, 3))

        pp.savefig("polish_particle_{:04d}_tiltimage_{:05.2f}.png".format(
            particle_number, ang))

    return particle_number, x_diff, y_diff, ang, 0, 0, particle_filename
예제 #17
0
def make_plots_seg(data_dict, max_events, normed_img, pred_dict):
    """
    Copy of make_plots adapted for pid plots
    """
    target_plane_codes = {9: 1, 18: 2, 27: 3, 36: 6, 45: 4, 50: 5}
    pkeys = []
    for k in data_dict.keys():
        if len(data_dict[k]) > 0:
            pkeys.append(k)
    print('Data dictionary present keys: {}'.format(pkeys))

    types = ['energy', 'time']
    views = ['x', 'u', 'v']   # TODO? build dynamically?

    # only working with two-deep imgs these days
    # plotting_two_tensors = True

    def get_maybe_missing(data_dict, key, counter):
        try:
            return data_dict[key][counter]
        except KeyError:
            pass
        return -1

    evt_plotted = 0

    with PdfPages("evt_all.pdf") as pdf:
        for counter in range(len(data_dict[EVENTIDS])):
            evtid = data_dict[EVENTIDS][counter]
            segment = get_maybe_missing(data_dict, SEGMENTS, counter)
            planecode = get_maybe_missing(data_dict, PLANECODES, counter)
            n_hadmultmeas = get_maybe_missing(data_dict, N_HADMULTMEAS, counter)
            (run, subrun, gate, phys_evt) = decode_eventid(evtid)
            if evt_plotted > max_events:
                break
            status_string = 'Plotting entry %d: %d: ' % (counter, evtid)
            title_string = '{}/{}/{}/{}'
            title_elems = [run, subrun, gate, phys_evt]
            if segment != -1 and planecode != -1:
                title_string = title_string + ', segment {}, planecode {}'
                title_elems.extend([segment, planecode])
                if planecode in tuple(target_plane_codes.keys()):
                    title_string = title_string + ', targ {}'
                    title_elems.append(target_plane_codes[planecode[0]])
            if n_hadmultmeas != -1:
                title_string = title_string + ', n_chghad {}'
                title_elems.append(n_hadmultmeas)
            if pred_dict is not None:
                try:
                    prediction = pred_dict[str(evtid)]
                    title_string = title_string + ', pred={}'
                    title_elems.append(prediction)
                except KeyError:
                    pass
            print(status_string + title_string.format(*title_elems))

            # run, subrun, gate, phys_evt = decode_eventid(evtid)
            fig_wid = 9
            fig_height = 9
            grid_height = 3
            fig = pylab.figure(figsize=(fig_wid, fig_height))
            fig.suptitle(title_string.format(*title_elems))
            gs = pylab.GridSpec(grid_height, 3)

            for i, t in enumerate(types):
                datatyp = 'energies+times'
                # set the bounds on the color scale
                if normed_img:
                    minv = 0 if t == 'energy' else -1
                    maxv = 1
                else:
                    maxes = []
                    mins = []
                    for v in views:
                        maxes.append(
                            np.abs(np.max(data_dict[datatyp][v][counter, i, :, :]))
                        )
                        mins.append(
                            np.abs(np.max(data_dict[datatyp][v][counter, i, :, :]))
                        )
                    minv = np.max(mins)
                    maxv = np.max(maxes)
                    maxex = maxv if maxv > minv else minv
                    minv = 0 if minv < 0.0001 else 0 if t == 'energy' else -maxv
                    maxv = maxex
                for j, view in enumerate(views):
                    gs_pos = i * 3 + j
                    ax = pylab.subplot(gs[gs_pos])
                    ax.axis('on')
                    ax.xaxis.set_major_locator(pylab.NullLocator())
                    ax.yaxis.set_major_locator(pylab.NullLocator())
                    cmap = 'Reds' if t == 'energy' else 'bwr'
                    cbt = 'energy' if t == 'energy' else 'times'
                    datap = data_dict[datatyp][view][counter, i, :, :]
                    # make the plot
                    im = ax.imshow(
                        datap,
                        cmap=pylab.get_cmap(cmap),
                        interpolation='nearest',
                        vmin=minv, vmax=maxv
                    )
                    cbar = pylab.colorbar(im, fraction=0.04)
                    cbar.set_label(cbt, size=9)
                    cbar.ax.tick_params(labelsize=6)
                    pylab.title(t + ' - ' + view, fontsize=12)
                    pylab.xlabel('plane', fontsize=10)
                    pylab.ylabel('strip', fontsize=10)
            # plot pid
            for j, view in enumerate(views):
                gs_pos = 6 + j
                ax = pylab.subplot(gs[gs_pos])
                ax.axis('on')
                ax.xaxis.set_major_locator(pylab.NullLocator())
                ax.yaxis.set_major_locator(pylab.NullLocator())
                cmap = 'tab10'
                cbt = 'pid'
                datap = data_dict["pid"][view][counter, 0, :, :]
                # make the plot                
                im = ax.imshow(
                    datap,
                    cmap=pylab.get_cmap(cmap),
                    interpolation='nearest',
                    vmin=0, vmax=7
                )
                cbar = pylab.colorbar(im, fraction=0.04, ticks=[0, 1, 2, 3, 4, 5, 6, 7])
                cbar.ax.set_yticklabels(['nth', 
                                         'EM',
                                         'mu',
                                         'pi+',
                                         'pi-',
                                         'n',
                                         'p',
                                         'oth'])
                cbar.set_label("pid", size=9)
                cbar.ax.tick_params(labelsize=6)
                pylab.title("pid" + ' - ' + view, fontsize=12)
                pylab.xlabel('plane', fontsize=10)
                pylab.ylabel('strip', fontsize=10)
            
            pdf.savefig()
            evt_plotted += 1
예제 #18
0
def f5_cadence_plot_new(lsstpg,
                        band,
                        lims=None,
                        median_log_summary=None,
                        median_log_summaryb=None,
                        dict_marker=None,
                        lims_sncosmo=None,
                        mag_range=(23., 26.5),
                        dt_range=(0.5, 15.),
                        target={},
                        targetb={},
                        alpha=1.,
                        simu_name='',
                        thetype='all',
                        seas=1,
                        save_it=False):
    #                    SNR=dict(zip(['LSSTPG::' + b for b in 'grizy'],
    #                                 [20., 20., 20., 20., 10.]))):

    dt = np.linspace(dt_range[0], dt_range[1], 50)
    m5 = np.linspace(mag_range[0], mag_range[1], 50)
    b = [band] * len(m5)
    f5 = lsstpg.mag_to_flux(m5, b)

    F5, DT = np.meshgrid(f5, dt)
    M5, DT = np.meshgrid(m5, dt)
    metric = np.sqrt(DT) * F5
    #print('metric',metric)
    sorted_keys = np.sort([k for k in lims.keys()])[::-1]

    # draw limits
    fig = plt.figure(figsize=(10, 10))
    grid = plt.GridSpec(4, 4, hspace=0.8, wspace=0.8)
    main_ax = fig.add_subplot(grid[:-1, 1:])
    y_hist = fig.add_subplot(grid[:-1, 0], xticklabels=[], sharey=main_ax)
    x_hist = fig.add_subplot(grid[-1, 1:], yticklabels=[], sharex=main_ax)

    main_ax.imshow(metric,
                   extent=(mag_range[0], mag_range[1], dt_range[0],
                           dt_range[1]),
                   aspect='auto',
                   alpha=0.25)

    if median_log_summary is not None:
        idx = median_log_summary['band'] == band
        m = median_log_summary[idx]
        main_ax.plot(m['m5'], m['cadence'], 'r+', alpha=alpha)
        m5_exp = np.median(m['m5'])

        idxb = (median_log_summary['band']
                == band) & (median_log_summary['cadence'] <= 30)
        m = median_log_summary[idxb]
        #print(len(m),m['cadence'])
        # histogram on the attached axes
        x_hist.hist(m['m5'],
                    40,
                    histtype='step',
                    orientation='vertical',
                    color='red')
        #x_hist.invert_yaxis()

        y_hist.hist(m['cadence'],
                    40,
                    histtype='step',
                    orientation='horizontal',
                    color='blue')
        y_hist.invert_xaxis()
        """
        x_hist.set_xlabel('$m_{5\sigma}$', fontsize=18)
        x_hist.set_ylabel('Number of Events', fontsize=18)
        y_hist.set_xlabel('Observer frame cadence $^{-1}$ [days]', fontsize=16)
        y_hist.set_ylabel('Number of Events', fontsize=18)
        """

        #print 'h1',band,np.median(m['m5'])

    if median_log_summaryb is not None:
        """
        idx = median_log_summaryb['band'] == band
        m = median_log_summaryb[idx]
        plt.plot(m['m5'], m['cadence'], 'b+',alpha=alpha)
        m5_exp=np.median(m['m5'])
        """
        #print 'h2',band,np.median(m['m5'])
        for key, val in median_log_summaryb.items():
            idx = val['band'] == band
            m = val[idx]
            main_ax.plot(m['m5'], m['cadence'], dict_marker[key], alpha=alpha)
            m5_exp = np.median(m['m5'])

    cadence_ref = 3

    if lims is not None:
        fmt = {}
        ll = [lims[zz][band] for zz in sorted_keys]
        print('limits', ll)
        cs = main_ax.contour(M5, DT, metric, ll, colors='k')
        dict_target_snsim = Get_target(cs, sorted_keys, cadence_ref, m5_exp)

        strs = ['$z=%3.1f$' % zz for zz in sorted_keys]
        for l, s in zip(cs.levels, strs):
            fmt[l] = s
        main_ax.clabel(cs,
                       inline=True,
                       fmt=fmt,
                       fontsize=16,
                       use_clabeltext=True)

    if lims_sncosmo is not None:
        #llc = [lims_sncosmo[zz][band.split('::')[1]] for zz in sorted_keys]
        llc = [lims_sncosmo[zz][band] for zz in sorted_keys]
        b = [band] * len(llc)
        print 'baba', band, llc, [zz for zz in sorted_keys
                                  ], lsstpg.flux_to_mag(llc, b)
        csc = main_ax.contour(M5, DT, metric, llc, colors='b')
        dict_target_sncosmo = Get_target(csc, sorted_keys, cadence_ref, m5_exp)

        strs = ['$z=%3.1f$' % zz for zz in sorted_keys]
        for l, s in zip(csc.levels, strs):
            fmt[l] = s
        main_ax.clabel(csc, inline=1, fmt=fmt, fontsize=16)
    """
    t = target.get(band, None)
    print target, t

    if t is not None:
        main_ax.plot(t[0], t[1], 
                color='r', marker='*', 
                markersize=15)
    """

    main_ax.set_xlabel('$m_{5\sigma}$', fontsize=18)
    main_ax.set_ylabel(r'Observer frame cadence $^{-1}$ [days]', fontsize=18)
    main_ax.set_title('$%s$ - %s' % (band.split(':')[-1], simu_name),
                      fontsize=18)
    main_ax.set_xlim(mag_range)
    main_ax.set_ylim(dt_range)
    main_ax.grid(1)
    if save_it:
        outdir = 'Plots_' + simu_name + '_' + thetype + '/Season_' + str(seas)
        if seas == -1:
            outdir = 'Plots_' + simu_name + '_' + thetype
        Check_Dir(outdir)
        plt.gcf().savefig(outdir + '/metric_' + band + '.png',
                          bbox_inches='tight')
예제 #19
0
 else:
     pstring = '{} - {} - {} - {}'.format(run, subrun, gate, phys_evt)
 print(pstring)
 evt = []
 titles = []
 if data_x is not None:
     evt.append(data_x[counter])
     titles.append('x view')
 if data_u is not None:
     evt.append(data_u[counter])
     titles.append('u view')
 if data_v is not None:
     evt.append(data_v[counter])
     titles.append('v view')
 fig = pylab.figure(figsize=(9, 3))
 gs = pylab.GridSpec(1, len(evt))
 # print np.where(evt == np.max(evt))
 # print np.max(evt)
 for i in range(len(evt)):
     ax = pylab.subplot(gs[i])
     ax.axis('on')
     ax.xaxis.set_major_locator(pylab.NullLocator())
     ax.yaxis.set_major_locator(pylab.NullLocator())
     # images are normalized such the max e-dep has val 1, independent
     # of view, so set vmin, vmax here to keep matplotlib from
     # normalizing each view on its own
     minv = 0
     cmap = 'jet'
     if have_times:
         minv = -1
         cmap = 'bwr'
#sim.recompute_and_save_amplification_index()

sim.load_steady_scores()

# recompute gridness scores
#sim.compute_steady_scores(force_input_scores=True)
#sim.save_steady_scores()


#%%

### COMPARE GRIDNESS SCORE AND GRID-TUNING INDEX

fig=pl.figure(figsize=(8,3.5))
pl.subplots_adjust(top=0.95,right=0.95,bottom=0.15,left=0.15)
gs = pl.GridSpec(3,3,hspace=0.55,wspace=0.35)

ax_joint = fig.add_subplot(gs[1:3,0:2])
ax_marg_x = fig.add_subplot(gs[0,0:2],sharex=ax_joint)
ax_marg_y = fig.add_subplot(gs[1:3,2],sharey=ax_joint)

xlims=0,0.6
ylims=-0.3,1.7
ms=5

ax_joint.plot(sim.grid_tuning_out_inhib,sim.ri_scores,color='dodgerblue',marker='o',lw=0,alpha=0.5,ms=ms,mec='none')
ax_joint.plot(sim.grid_tuning_in,sim.he_scores,color='m',marker='o',lw=0,alpha=0.5,ms=ms,mec='none')
ax_joint.plot(sim.grid_tuning_out,sim.re_scores,color='black',marker='o',lw=0,alpha=0.5,ms=ms,mec='none')
ax_joint.set_xlabel('Grid tuning index')
ax_joint.set_ylabel('Gridness score')
예제 #21
0
def allplot(xb, yb, bins=30, fig=1, xlabel='x', ylabel='y'):
    """
Input:
X,Y : objects referring to the variables produced by PyMC that you want
to analyze. Example: X=M.theta, Y=M.slope.

Inherited from Tommy LE BLANC's code at astroplotlib|STSCI.
	"""
    #X,Y=xb.trace(),yb.trace()
    X, Y = xb, yb

    #pylab.rcParams.update({'font.size': fontsize})
    fig = pylab.figure(fig)
    pylab.clf()

    gs = pylab.GridSpec(2,
                        2,
                        width_ratios=[3, 1],
                        height_ratios=[1, 3],
                        wspace=0.07,
                        hspace=0.07)
    scat = pylab.subplot(gs[2])
    histx = pylab.subplot(gs[0], sharex=scat)
    histy = pylab.subplot(gs[3], sharey=scat)
    #scat=fig.add_subplot(2,2,3)
    #histx=fig.add_subplot(2,2,1, sharex=scat)
    #histy=fig.add_subplot(2,2,4, sharey=scat)

    # Scatter plot
    scat.plot(X,
              Y,
              linestyle='none',
              marker='o',
              color='green',
              mec='green',
              alpha=.2,
              zorder=-99)

    gkde = scipy.stats.gaussian_kde([X, Y])
    x, y = numpy.mgrid[X.min():X.max():(X.max() - X.min()) / 25.,
                       Y.min():Y.max():(Y.max() - Y.min()) / 25.]
    z = numpy.array(gkde.evaluate([x.flatten(), y.flatten()])).reshape(x.shape)
    scat.contour(x, y, z, linewidths=2)
    scat.set_xlabel(xlabel)
    scat.set_ylabel(ylabel)

    # X-axis histogram
    histx.hist(X, bins, histtype='stepfilled')
    pylab.setp(histx.get_xticklabels(), visible=False)  # no X label
    #histx.xaxis.set_major_formatter(pylab.NullFormatter())	# no X label

    # Y-axis histogram
    histy.hist(Y, bins, histtype='stepfilled', orientation='horizontal')
    pylab.setp(histy.get_yticklabels(), visible=False)  # no Y label
    #histy.yaxis.set_major_formatter(pylab.NullFormatter())	# no Y label

    #pylab.minorticks_on()
    #pylab.subplots_adjust(hspace=0.1)
    #pylab.subplots_adjust(wspace=0.1)
    pylab.draw()
    pylab.show()
예제 #22
0
    def plot_vars(cls,
                  var_dic,
                  suffix="evolution",
                  show=False,
                  save=True,
                  func=utils.plot):
        """plot variation/comparison/boxplots of all variables organized by categories

        Args:
          var_dic:
          suffix:  (Default value = "")
          show(bool): If True, show the figure (Default value = True)
          save(bool): If True, save the figure (Default value = False)
          func:  (Default value = plot)

        Returns:

        """
        fig = plt.figure()
        grid = plt.GridSpec(2, 3)
        for nb in range(len(GATES)):
            gate = GATES[nb]
            cls.plot_vars_gate(gate,
                               var_dic['{}__mdp'.format(gate)],
                               var_dic['{}__scale'.format(gate)],
                               var_dic['{}__tau'.format(gate)],
                               fig,
                               grid[nb], (nb % 3 == 0),
                               func=func)
        cls.plot_vars_gate('h',
                           var_dic['h__mdp'],
                           var_dic['h__scale'],
                           var_dic['h__alpha'],
                           fig,
                           grid[5],
                           False,
                           func=func)
        plt.tight_layout()
        utils.save_show(show,
                        save,
                        name='{}Rates_{}'.format(utils.NEUR_DIR, suffix),
                        dpi=300)

        fig = plt.figure()
        grid = plt.GridSpec(1, 2)
        subgrid = gridspec.GridSpecFromSubplotSpec(4, 1, grid[0], hspace=0.1)
        for i, var in enumerate(CONDS):
            ax = plt.Subplot(fig, subgrid[i])
            func(ax, var_dic[var])  # )
            ax.set_ylabel(var)
            if (i == 0):
                ax.set_title('Conductances')
            fig.add_subplot(ax)
        subgrid = gridspec.GridSpecFromSubplotSpec(4, 1, grid[1], hspace=0.1)
        for i, var in enumerate(MEMB):
            ax = plt.Subplot(fig, subgrid[i])
            func(ax, var_dic[var])  # )
            ax.set_ylabel(var)
            if (i == 0):
                ax.set_title('Membrane')
            ax.yaxis.tick_right()
            fig.add_subplot(ax)
        plt.tight_layout()
        utils.save_show(show,
                        save,
                        name='{}Membrane_{}'.format(utils.NEUR_DIR, suffix),
                        dpi=300)

        plt.figure()
        ax = plt.subplot(211)
        func(ax, var_dic['rho_ca'])  # , 'r')
        plt.ylabel('Rho_ca')
        plt.yscale('log')
        ax = plt.subplot(212)
        func(ax, var_dic['decay_ca'])  # , 'b')
        plt.ylabel('Decay_ca')
        utils.save_show(show,
                        save,
                        name='{}CalciumPump_{}'.format(utils.NEUR_DIR, suffix),
                        dpi=300)
예제 #23
0

# SCRIPT
# # # # # # # # # #

# ax1 predefined
dt = 0.1  # ms per bin
T = 2e3  # in ms

t = np.arange(0, T, dt)
spktr = np.zeros(t.shape)
spktr[[4000, 5000, 6000, 7000, 14000]] = 1

fig1 = pl.figure(num=1, figsize=figsize, dpi=dpi)
lim1 = [0.24, 0.24, 0.72, 0.70]
gs = pl.GridSpec(5, 3, wspace=0.5, hspace=0.5)

fig2 = pl.figure(num=2, figsize=spiketrain_figsize, dpi=dpi)

if __name__ == "__main__":
    import os, inspect

    # FIGURE 1 PLOTTING

    current_dir = os.path.dirname(
        os.path.abspath(inspect.getfile(inspect.currentframe())))
    parent_dir = os.path.dirname(current_dir)

    figure1, figure1_spiketrain = plot()
    figure1.savefig(current_dir + "/figures/Fig1_raw.pdf")
    figure1_spiketrain.savefig(current_dir +
예제 #24
0
#     ax_ts.set_ylim([0, 5.0])
#     ax_ts.set_xlim([0, 6*np.pi])
#     ax_ts.set_xticks([0, 2*np.pi, 4*np.pi, 6*np.pi])
#     ax_ts.set_xticklabels([r'$0$', r'$2\pi$', r'$4\pi$',
#                            r'$6\pi$'])
#
#     fig.tight_layout(**layout_pad)
#     fig.savefig('cont_plot/cont' + "%03d" % (i,) + '.png',
#                 bbox_inches='tight')
#     plt.close(fig)

# Desync movie
pulse_inds = range(len(ts_pre), len(ts_pre) + len(ts_pulse))
for i in xrange(ys_pert.shape[0]):
    fig = plt.figure(dpi=70, figsize=(6, 2.2))
    gs = plt.GridSpec(1, 3)
    ax_ss = fig.add_subplot(gs[0])
    ax_ss.plot(model.sol[:, 0], model.sol[:, 1], 'k')
    ax_ss.plot(ys_pert[:i, :, 0].mean(1), ys_pert[:i, :, 1].mean(1), 'r--')
    ax_ss.plot(ys_pert[i, :, 0], ys_pert[i, :, 1], 'go')
    ax_ss.plot(ys_pert[i, :, 0].mean(0), ys_pert[i, :, 1].mean(0), 'ro')
    ax_ss.set_xlim([0, 0.8])
    ax_ss.set_xlabel('X')
    ax_ss.set_ylabel('Y')
    ax_ss.set_ylim([0, 5.0])

    ax_ts = fig.add_subplot(gs[1:], sharey=ax_ss)
    ax_ts.set_xlabel(r'$\hat{t}$')
    ax_ts.plot(ts_pert[:i] - ts_pert[0], ys_pert[:i, :, 1].mean(1), 'r--')
    ax_ts.plot(ts_pert[i] - ts_pert[0], ys_pert[i, :, 1].mean(0), 'ro')
    ax_ts.set_ylim([0, 5.0])
예제 #25
0
pp.save_fig(sl.get_figures_path(),
            fname,
            exts=['png', 'svg'],
            transparent=True)

#%%

### BUMP LOCATION AND AMPLITUDE WITH SWITCHING OFF FEED-FORWARD INPUTS (ATTRACTOR DYNAMICS)

fig = pl.figure(figsize=(8, 4))
time = np.arange(num_snaps) * sim.delta_snap * sim.dt

gs = pl.GridSpec(8,
                 1,
                 hspace=2.,
                 wspace=0.1,
                 bottom=0.15,
                 left=0.125,
                 right=0.99)

ax = fig.add_subplot(gs[0:2, 0])

for idx, curr_sim in enumerate(sims):
    pl.plot(time, curr_sim.bump_peak_evo[0, :] / 30., color='salmon')

pl.plot(time, sims[4].bump_peak_evo[0, :] / 30., color='black', lw=1.5)
pp.custom_axes()
pl.yticks([0, 1])
pl.ylabel('Bump\nphase\n(vert.)')
pl.xlim([-0.1, walk_time + 0.1])
pl.gca().axes.get_xaxis().set_visible(False)
예제 #26
0
def plotting_from_dat(data, area='PFC'):

    pdf = PdfPages('/Users/veronikasamborska/Desktop/' + area + 'from_dat.pdf')
    cmap = palettable.scientific.sequential.Acton_3.mpl_colormap

    dm = data['DM'][0]
    fr = data['Data'][0]
    neuron_ID = 0

    for s, session in enumerate(dm):
        # Get raw spike data across the task
        firing_rate = fr[s]
        DM = dm[s]
        n_trials, n_neurons, n_times = firing_rate.shape

        choices = DM[:, 1]
        b_pokes = DM[:, 7]
        a_pokes = DM[:, 6]
        i_pokes = DM[:, 8]
        reward = DM[:, 2]

        task = DM[:, 5]
        _t_1 = np.where(task == 1)[0]
        _t_2 = np.where(task == 2)[0]
        _t_3 = np.where(task == 3)[0]

        x_points = [132, 232, 232, 332, 332, 432, 432, 532]
        y_points = [2.8, 3.8, 1.8, 4.8, 0.8, 3.8, 1.8, 2.8]

        global _4
        global _2
        global _7
        global _1
        global _9
        global _3
        global _8
        global _6

        _4 = [x_points[0], y_points[0]]
        _2 = [x_points[1], y_points[1]]
        _7 = [x_points[2], y_points[2]]
        _1 = [x_points[3], y_points[3]]
        _9 = [x_points[4], y_points[4]]
        _3 = [x_points[5], y_points[5]]
        _8 = [x_points[6], y_points[6]]
        _6 = [x_points[7], y_points[7]]

        a_1 = globals()['_' + str(int(a_pokes[_t_1][0]))]
        a_2 = globals()['_' + str(int(a_pokes[_t_2][0]))]
        a_3 = globals()['_' + str(int(a_pokes[_t_3][0]))]
        b_1 = globals()['_' + str(int(b_pokes[_t_1][0]))]
        b_2 = globals()['_' + str(int(b_pokes[_t_2][0]))]
        b_3 = globals()['_' + str(int(b_pokes[_t_3][0]))]
        i_1 = globals()['_' + str(int(i_pokes[_t_1][0]))]
        i_2 = globals()['_' + str(int(i_pokes[_t_2][0]))]
        i_3 = globals()['_' + str(int(i_pokes[_t_3][0]))]

        ind_init = 25
        ind_choice = 36
        ind_reward = 42

        a_rew_1_f = np.mean(
            firing_rate[np.where((task == 1) & (choices == 1)
                                 & (reward == 1))[0]], 0)
        a_nrew_1_f = np.mean(
            firing_rate[np.where((task == 1) & (choices == 1)
                                 & (reward == 0))[0]], 0)

        a_rew_2_f = np.mean(
            firing_rate[np.where((task == 2) & (choices == 1)
                                 & (reward == 1))[0]], 0)
        a_nrew_2_f = np.mean(
            firing_rate[np.where((task == 2) & (choices == 1)
                                 & (reward == 0))[0]], 0)

        a_rew_3_f = np.mean(
            firing_rate[np.where((task == 3) & (choices == 1)
                                 & (reward == 1))[0]], 0)
        a_nrew_3_f = np.mean(
            firing_rate[np.where((task == 3) & (choices == 1)
                                 & (reward == 0))[0]], 0)

        b_rew_1_f = np.mean(
            firing_rate[np.where((task == 1) & (choices == 0)
                                 & (reward == 1))[0]], 0)
        b_nrew_1_f = np.mean(
            firing_rate[np.where((task == 1) & (choices == 0)
                                 & (reward == 0))[0]], 0)

        b_rew_2_f = np.mean(
            firing_rate[np.where((task == 2) & (choices == 0)
                                 & (reward == 1))[0]], 0)
        b_nrew_2_f = np.mean(
            firing_rate[np.where((task == 2) & (choices == 0)
                                 & (reward == 0))[0]], 0)

        b_rew_3_f = np.mean(
            firing_rate[np.where((task == 3) & (choices == 0)
                                 & (reward == 1))[0]], 0)
        b_nrew_3_f = np.mean(
            firing_rate[np.where((task == 3) & (choices == 0)
                                 & (reward == 0))[0]], 0)

        i_rew_1_f = np.mean(
            firing_rate[np.where((task == 1) & (reward == 1))[0]], 0)
        i_nrew_1_f = np.mean(
            firing_rate[np.where((task == 1) & (reward == 0))[0]], 0)

        i_rew_2_f = np.mean(
            firing_rate[np.where((task == 2) & (reward == 1))[0]], 0)
        i_nrew_2_f = np.mean(
            firing_rate[np.where((task == 2) & (reward == 0))[0]], 0)

        i_rew_3_f = np.mean(
            firing_rate[np.where((task == 3) & (reward == 1))[0]], 0)
        i_nrew_3_f = np.mean(
            firing_rate[np.where((task == 3) & (reward == 0))[0]], 0)

        plt.ioff()

        task_arrays = np.zeros(shape=(n_trials, 3))
        task_arrays[:_t_2[0], 0] = 1
        task_arrays[_t_2[0]:_t_3[0], 1] = 1
        task_arrays[_t_3[0]:, 2] = 1

        isl = wes.Royal2_5.mpl_colors
        isl_1 = wes.Moonrise5_6.mpl_colors



        vector_for_normalising = np.concatenate([a_rew_1_f,a_nrew_1_f,a_rew_2_f,a_nrew_2_f,\
                                                 a_rew_3_f,a_nrew_3_f,b_rew_1_f,b_nrew_1_f,b_rew_2_f,b_nrew_2_f,\
                                                 b_rew_3_f,b_nrew_3_f,\
                                                 i_rew_1_f,i_nrew_1_f,i_rew_2_f,i_nrew_2_f,\
                                                 i_rew_3_f,i_nrew_3_f], axis = 1)

        normalised = vector_for_normalising / (
            np.tile(np.max(vector_for_normalising, 1),
                    [vector_for_normalising.shape[1], 1]).T + .0000001)

        a_rew_1_f = normalised[:, :n_times]
        a_nrew_1_f = normalised[:, n_times:n_times * 2]

        a_rew_2_f = normalised[:, n_times * 2:n_times * 3]
        a_nrew_2_f = normalised[:, n_times * 3:n_times * 4]

        a_rew_3_f = normalised[:, n_times * 4:n_times * 5]
        a_nrew_3_f = normalised[:, n_times * 5:n_times * 6]

        b_rew_1_f = normalised[:, n_times * 6:n_times * 7]
        b_nrew_1_f = normalised[:, n_times * 7:n_times * 8]

        b_rew_2_f = normalised[:, n_times * 8:n_times * 9]
        b_nrew_2_f = normalised[:, n_times * 9:n_times * 10]

        b_rew_3_f = normalised[:, n_times * 10:n_times * 11]
        b_nrew_3_f = normalised[:, n_times * 11:n_times * 12]

        i_rew_1_f = normalised[:, n_times * 12:n_times * 13]
        i_nrew_1_f = normalised[:, n_times * 13:n_times * 14]

        i_rew_2_f = normalised[:, n_times * 14:n_times * 15]
        i_nrew_2_f = normalised[:, n_times * 15:n_times * 16]

        i_rew_3_f = normalised[:, n_times * 16:n_times * 17]
        i_nrew_3_f = normalised[:, n_times * 17:]

        for neuron in range(n_neurons):

            neuron_ID += 1
            #Port Firing
            fig = plt.figure(figsize=(8, 15))
            grid = plt.GridSpec(2, 1, hspace=0.7, wspace=0.4)
            fig.add_subplot(grid[0])

            plt.scatter(x_points, y_points, s=100, c='black')

            plt.plot(np.arange(a_1[0] - 30, a_1[0] + 33, 1),
                     a_rew_1_f[neuron] + a_1[1] + 1,
                     color=isl[0],
                     label='task 1 A')
            plt.plot(np.arange(a_1[0] - 30, a_1[0] + 33, 1),
                     a_nrew_1_f[neuron] + a_1[1] + 1,
                     color=isl[0],
                     linestyle=':')

            plt.plot(np.arange(a_2[0] - 30, a_2[0] + 33, 1),
                     a_rew_2_f[neuron] + a_2[1] + 1,
                     color=isl[1],
                     label='task 2 A')
            plt.plot(np.arange(a_2[0] - 30, a_2[0] + 33, 1),
                     a_nrew_2_f[neuron] + a_2[1] + 1,
                     color=isl[1],
                     linestyle=':')

            plt.plot(np.arange(a_3[0] - 30, a_3[0] + 33, 1),
                     a_rew_3_f[neuron] + a_3[1] + 1,
                     color=isl[2],
                     label='task 3 A')
            plt.plot(np.arange(a_3[0] - 30, a_3[0] + 33, 1),
                     a_nrew_3_f[neuron] + a_3[1] + 1,
                     color=isl[2],
                     linestyle=':')

            plt.plot(np.arange(b_1[0] - 30, b_1[0] + 33, 1),
                     b_rew_1_f[neuron] + b_1[1] + 1,
                     color=isl[0],
                     label='task 1 B')
            plt.plot(np.arange(b_1[0] - 30, b_1[0] + 33, 1),
                     b_nrew_1_f[neuron] + b_1[1] + 1,
                     color=isl[0],
                     linestyle=':')

            plt.plot(np.arange(b_2[0] - 30, b_2[0] + 33, 1),
                     b_rew_2_f[neuron] + b_2[1] + 1,
                     color=isl[1],
                     label='task 2 B')
            plt.plot(np.arange(b_2[0] - 30, b_2[0] + 33, 1),
                     b_nrew_2_f[neuron] + b_2[1] + 1,
                     color=isl[1],
                     linestyle=':')

            plt.plot(np.arange(b_3[0] - 30, b_3[0] + 33, 1),
                     b_rew_3_f[neuron] + b_3[1] + 1,
                     color=isl[2],
                     label='task 3 B')
            plt.plot(np.arange(b_3[0] - 30, b_3[0] + 33, 1),
                     b_nrew_3_f[neuron] + b_3[1] + 1,
                     color=isl[2],
                     linestyle=':')

            plt.plot(np.arange(i_1[0] - 30, i_1[0] + 33, 1),
                     i_rew_1_f[neuron] + i_1[1] + 1,
                     color=isl_1[0],
                     label='task 1 I')
            plt.plot(np.arange(i_1[0] - 30, i_1[0] + 33, 1),
                     i_nrew_1_f[neuron] + i_1[1] + 1,
                     color=isl_1[0],
                     linestyle=':')

            plt.plot(np.arange(i_2[0] - 30, i_2[0] + 33, 1),
                     i_rew_2_f[neuron] + i_2[1] + 1,
                     color=isl_1[1],
                     label='task 2 I')
            plt.plot(np.arange(i_2[0] - 30, i_2[0] + 33, 1),
                     i_nrew_2_f[neuron] + i_2[1] + 1,
                     color=isl_1[1],
                     linestyle=':')

            plt.plot(np.arange(i_3[0] - 30, i_3[0] + 33, 1),
                     i_rew_3_f[neuron] + i_3[1] + 1,
                     color=isl_1[2],
                     label='task 3 I')
            plt.plot(np.arange(i_3[0] - 30, i_3[0] + 33, 1),
                     i_nrew_3_f[neuron] + i_3[1] + 1,
                     color=isl_1[2],
                     linestyle=':')

            inds = [
                a_1, b_1, b_1, b_2, b_2, b_3, b_3, i_1, i_1, i_2, i_2, i_3, i_3
            ]
            for i, ind in enumerate(inds):

                plt.vlines(np.arange(ind[0] - 30, ind[0] + 33, 1)[ind_init],
                           ymin=ind[1] + 1,
                           ymax=ind[1] + 2,
                           linestyle='--',
                           color='Grey',
                           linewidth=0.5)
                plt.vlines(np.arange(ind[0] - 30, ind[0] + 33, 1)[ind_choice],
                           ymin=ind[1] + 1,
                           ymax=ind[1] + 2,
                           linestyle='--',
                           color='Black',
                           linewidth=0.5)
                plt.vlines(np.arange(ind[0] - 30, ind[0] + 33, 1)[ind_reward],
                           ymin=ind[1] + 1,
                           ymax=ind[1] + 2,
                           linestyle='--',
                           color='Pink',
                           linewidth=0.5)

            plt.legend()
            # Pokes
            plt.axis('off')

            # Heatmap
            fig.add_subplot(grid[1])
            heatplot = firing_rate[:, neuron, :]
            # normalised = (heatplot - np.min(heatplot,1)[:, None]) / (np.max(heatplot,1)[:, None]+1e-08 - np.min(heatplot,1)[:, None])
            heatplot = heatplot / (
                np.tile(np.max(heatplot, 1), [heatplot.shape[1], 1]).T + 1e-08)

            heatplot_con = np.concatenate([heatplot, task_arrays], axis=1)

            plt.imshow(heatplot_con, cmap=cmap, aspect='auto')
            plt.xticks([ind_init, ind_choice, ind_reward], ('I', 'C', 'O'))
            plt.title('{}'.format(neuron_ID))

            pdf.savefig()
            plt.clf()
    pdf.close()
예제 #27
0
    trackfilename = sys.argv[2]

trackarr = None
if trackfilename:
    trackarr = pylab.load(trackfilename)

zsegs = [0, 1, 6, 2, 7, 3, 8, 4, 9, 5, 10]
desc = [
    'upstream of target 1', 'target 1', 'between 1 and 2', 'target 2',
    'between 2 and 3', 'target 3', 'between 3 and 4', 'target 4',
    'between 4 and 5', 'target 5', 'downstream of target 5'
]
zdesc = dict(zip(zsegs, desc))

fig = pylab.figure(figsize=(15, 15))
gs = pylab.GridSpec(4, 3)
pur = pylab.zeros_like(arr)
for i in range(11):
    pur[i, :] = arr[i, :] / arr.sum(axis=1)[i]

if trackarr is not None:
    trackpur = pylab.zeros_like(trackarr)
    for i in range(11):
        trackpur[i, :] = trackarr[i, :] / trackarr.sum(axis=1)[i]

for i, v in enumerate(zsegs):
    ax = pylab.subplot(gs[i])
    ax.set_autoscaley_on(False)
    ax.set_ylim([0.0, 1.0])
    ax.set_ylabel('fraction of events')
    ax.set_title('true ' + str(v) + ':' + zdesc[v], loc='right')
예제 #28
0
def run_single_tilt_angle(subtomogram, ang, offset, vol_size,
                          particle_position, particle_rotation,
                          particle_filename, particle_number, binning, img,
                          create_graphics, fsc_path, dimz, peak_border):
    """
    To run a single tilt angle to allow for parallel computing

    @param ang: the tilt angle
    @type ang: int
    @param subtomogram: the filename of the subtomogram
    @type subtomogram: str
    @param offset: the offset used (x,y,z)
    @type offset: list(int, int, int)
    @param vol_size: the size of the volume to be reconstructed (in pixels)
    @type vol_size: int
    @param particle_position: the position of the particle in vector format,
               as given by particle.pickPosition().toVector()
    @type particle_position: tuple
    @param particle_rotation: the rotation of the particle (Z1/phi, X/the, Z2/psi)
    @type particle_rotation: tuple
    @param particle_filename: the filename of the particle, as given by particle.getfilename()
    @type particle_filename: str
    @param particle_number: the number of the particle, to allow for unique mapping
    @type particle_number: int
    @param binning: the binning factor used
    @type binning: int
    @param img: the filename of the projection to be used
    @type img: str
    @param create_graphics: to flag if images should be created for human inspection of the work done
    @type create_graphics: bool
    @return: the newly found positions of the particle, as a list  in the LOCAL_ALIGNMENT_RESULTS format
    @returntype: list
    """

    from pytom.reconstruction.reconstructionFunctions import alignImageUsingAlignmentResultFile
    from pytom.tompy.transform import rotate3d, rotate_axis
    from pytom.gui.guiFunctions import datatypeAR, loadstar
    import numpy as np
    from math import cos, sin, pi, sqrt
    from pytom.tompy.tools import create_circle
    from pytom.tompy.transform import cut_from_projection
    from pytom.tompy.filter import applyFourierFilterFull, bandpass_circle
    from pytom.tompy.io import read, write
    from pytom.tompy.correlation import meanUnderMask, stdUnderMask
    import os
    import time

    t = time.time()
    # print(particle_filename, ang)

    # Filter using FSC
    fsc_mask = None
    k = 0.01
    subtomogram = read(subtomogram) * read(
        '/data/gijsvds/ctem/05_Subtomogram_Analysis/Alignment/GLocal/mask_200_75_5.mrc'
    )

    import os
    from pytom.tompy.filter import filter_volume_by_profile, profile2FourierVol
    fsc_path = ''
    if os.path.isfile(fsc_path):
        profile = [line.split()[0] for line in open(fsc_path, 'r').readlines()]
        fsc_mask3d = profile2FourierVol(profile, subtomogram.shape)

        subtomogram = applyFourierFilterFull(subtomogram, fsc_mask3d)

    # Cross correlate the templat
    # e and patch, this should give the pixel shift it is after
    from pytom.tompy.correlation import nXcf

    # Get template
    # First rotate the template towards orientation of the particle, then to the tilt angle

    img = read(img)

    rotated1 = rotate3d(subtomogram,
                        phi=particle_rotation[0],
                        the=particle_rotation[1],
                        psi=particle_rotation[2])
    rotated2 = rotate_axis(
        rotated1, -ang,
        'y')  # SWITCHED TO ROTATE AXIS AND ANGLE *-1 THIS IS AN ATTEMPT
    template = rotated2.sum(axis=2)

    # write('pp1_template.mrc', template)

    # img = read(img)
    try:
        patch, xx, yy = cut_patch(img,
                                  ang,
                                  particle_position,
                                  dimz=dimz,
                                  vol_size=vol_size,
                                  binning=binning)
        mask2d = create_circle(patch.shape, radius=75, sigma=5, num_sigma=2)
        patch *= mask2d
        # write('pp1_patch.mrc', patch)

        if os.path.isfile(fsc_path):
            profile = [
                line.split()[0] for line in open(fsc_path, 'r').readlines()
            ]
            fsc_mask2d = profile2FourierVol(profile, patch.shape)
            patch = applyFourierFilterFull(patch, fsc_mask2d)

        template = normalize_image(template, mask2d, mask2d.sum())
        patch = normalize_image(patch, mask2d, mask2d.sum())

        if 1:
            ff = xp.ones_like(patch)
        else:
            ff = bandpass_circle(patch.squeeze(), 6, 25, 3)

        ccf = normalised_cross_correlation(template, patch, ff)

        points2d1 = find_sub_pixel_max_value_2d(ccf.copy(),
                                                ignore_border=peak_border)
        points2d2 = find_sub_pixel_max_value(ccf.copy(),
                                             ignore_border=peak_border)
        points2d = list(points2d2[:2]) + [points2d1[-1]]

        x_diff = points2d[0] - vol_size / 2
        y_diff = points2d[1] - vol_size / 2

        dist = sqrt(x_diff**2 + y_diff**2)

        #rx, ry, ii, oox, ooy, x2, y2 = find_sub_pixel_max_value_voltools(ccf.copy())

        #print(rx,ry, x_diff, y_diff, x2, y2, oox, ooy, ii.shape)
        #print(f'{particle_number:3d} {ang:5.1f}, {dist:5.2f} {x_diff} {y_diff} {ccf.max()}')
        if create_graphics:
            rx, ry, ii, oox, ooy, x2, y2 = find_sub_pixel_max_value_voltools(
                ccf.copy(), k=k)
            print(rx, ry)
            from scipy.ndimage.filters import gaussian_filter
            # Create an image to display and/or test the inner workings of the algorithm

            points = find_sub_pixel_max_value(ccf, ignore_border=peak_border)

            nx, ny, nz = particle_position
            nx += x_diff
            ny += y_diff

            npatch = cut_from_projection(
                img.squeeze(), [xx + x_diff, yy + y_diff],
                [vol_size, vol_size]
            )  # img.sum(axis=2)[int(xx+x_diff-v):int(xx+x_diff+v), int(yy+y_diff-v):int(yy+y_diff+v)]  #
            npatch = normalize_image(npatch, mask2d, mask2d.sum())

            nccf = normalised_cross_correlation(template, npatch.squeeze(), ff)
            npoints = find_sub_pixel_max_value(nccf, ignore_border=peak_border)
            npoints2d = find_sub_pixel_max_value_2d(nccf,
                                                    ignore_border=peak_border)
            #rx, ry = abs(xp.array(npoints2d[:2]) - 100)

            from scipy.ndimage.filters import gaussian_filter
            # Create an image to display and/or test the inner workings of the algorithm

            points = find_sub_pixel_max_value(ccf, ignore_border=peak_border)

            nx, ny, nz = particle_position
            nx += x_diff
            ny += y_diff

            npatch = cut_from_projection(
                img.squeeze(), [xx + x_diff, yy + y_diff],
                [vol_size, vol_size]
            )  # img.sum(axis=2)[int(xx+x_diff-v):int(xx+x_diff+v), int(yy+y_diff-v):int(yy+y_diff+v)]  #
            npatch = normalize_image(npatch, mask2d, mask2d.sum())

            nccf = normalised_cross_correlation(template, npatch.squeeze(), ff)
            npoints = find_sub_pixel_max_value(nccf, ignore_border=peak_border)
            npoints2d = find_sub_pixel_max_value_2d(nccf,
                                                    ignore_border=peak_border)
            #rx, ry = abs(xp.array(npoints2d[:2]) - 100)

            m_style = dict(color='tab:blue',
                           linestyle=':',
                           marker='o',
                           markersize=5,
                           markerfacecoloralt='tab:red')
            m_style_alt = dict(color='tab:red',
                               linestyle=':',
                               marker='o',
                               markersize=5,
                               markerfacecoloralt='tab:orange')

            grid = pp.GridSpec(3,
                               3,
                               wspace=0,
                               hspace=0.35,
                               left=0.05,
                               right=0.95,
                               top=0.90,
                               bottom=0.05)

            ax_0_0 = pp.subplot(grid[0, 0])
            ax_0_1 = pp.subplot(grid[0, 1])
            ax_0_2 = pp.subplot(grid[0, 2])
            ax_1_0 = pp.subplot(grid[1, 0])
            ax_1_1 = pp.subplot(grid[1, 1])
            ax_1_2 = pp.subplot(grid[1, 2])
            ax_2_0 = pp.subplot(grid[2, 0])
            ax_2_1 = pp.subplot(grid[2, 1])
            ax_2_2 = pp.subplot(grid[2, 2])

            ax_0_0.axis('off')
            ax_0_1.axis('off')
            ax_0_2.axis('off')
            ax_1_0.axis('off')
            ax_1_1.axis('off')
            ax_1_2.axis('off')
            ax_2_0.axis('off')
            ax_2_1.axis('off')
            ax_2_2.axis('off')

            axis_title(ax_0_0, "Cutout")
            ax_0_0.imshow(applyFourierFilterFull(patch, xp.fft.fftshift(ff)))
            axis_title(ax_0_1, "Template")
            ax_0_1.imshow(template)
            axis_title(ax_0_2, "Shifted Cutout\n(based on cross correlation)")
            ax_0_2.imshow(npatch.squeeze())

            axis_title(ax_1_0, u"Cross correlation\ncutout × template")
            ax_1_0.imshow(ccf)
            ax_1_0.plot([points[1]], [points[0]], fillstyle='none', **m_style)
            ax_1_0.plot([points2d[1]], [points2d[0]],
                        fillstyle='none',
                        **m_style_alt)
            ax_1_0.plot([vol_size / 2], [vol_size / 2], ",k")

            ax_1_1.text(
                0.5,
                0.8,
                "Red: 2D spline interpolation\nx: {:f}\ny: {:f}\nBlue: 1D spline interpolation\nx: {:f}\ny: {:f}"
                "\nBlack: center".format(x_diff, y_diff,
                                         points[0] - vol_size / 2,
                                         points[1] - vol_size / 2),
                fontsize=8,
                horizontalalignment='center',
                verticalalignment='center',
                transform=ax_1_1.transAxes)

            axis_title(ax_1_2, u"Cross correlation\nshifted cutout × template")
            ax_1_2.imshow(nccf)
            ax_1_2.plot([npoints[0]], [npoints[1]],
                        fillstyle='none',
                        **m_style)
            ax_1_2.plot([npoints2d[0]], [npoints2d[1]],
                        fillstyle='none',
                        **m_style_alt)
            ax_1_2.plot([vol_size / 2], [vol_size / 2], ",k")

            axis_title(ax_2_0, u"Zoom into red peak\nin CC cutout × template")
            d = 10

            points2d = list(xp.unravel_index(ccf.argmax(),
                                             ccf.shape)) + [points2d[-1]]
            peak = ccf[int(points2d[0]) - d:int(points2d[0]) + d,
                       int(points2d[1]) - d:int(points2d[1] + d)]
            ax_2_0.imshow(peak)

            axis_title(
                ax_2_1,
                u"Zoom into red peak\nin CC cutout × template\ninterpolated")
            ax_2_1.imshow(ii)

            ax_2_1.plot([y2 + (y_diff - ry) / k], [x2 + (x_diff - rx) / k],
                        fillstyle='none',
                        **m_style)
            ax_2_1.plot([y2], [x2], fillstyle='none', **m_style_alt)
            axis_title(ax_2_2, u"Cutout\nGaussian filter σ3")
            import scipy
            ax_2_2.imshow(scipy.ndimage.gaussian_filter(patch, 3))

            pp.savefig(
                "../Images/test/polish_particle_{:04d}_tiltimage_{:05.2f}_shift_{:.1f}.png"
                .format(particle_number, ang, dist))
        del img
    except Exception as e:
        print(e)
        x_diff = y_diff = 0

    print(
        f'{particle_number:3d} {ang:4d} {x_diff:5.2f} {y_diff:5.2f} {points2d1[0]-patch.shape[0]//2:.2f} {points2d1[1]-patch.shape[0]//2:.2f} {time.time()-t:5.3f}'
    )
    return particle_number, x_diff, y_diff, ang, 0, 0, particle_filename
py.xlabel('$x$ ($\mu$m)')
py.ylabel('$y$ ($\mu$m)')


#py.figure(3)



# Animation call
# =============================================================================

print('Processing animation ... \n')

fig = py.figure()
# Define a 2 x 2 grid
gs = py.GridSpec(2,2) # 2 rows, 2 columns


# Define 3 subplots. First one spanning both rows of column 1, the rest two taking the ramining 2 subplots
ax1 = fig.add_subplot(gs[:,0],aspect = 1)       # xy plane (column left, both rows)
ax2 = fig.add_subplot(gs[0,1],aspect = 1)       # yz plane (column right, top row)
ax3 = fig.add_subplot(gs[1,1],aspect = 1)       # xz plane (column right, bottoom row)



# Set figure dpi and size
fig.set_dpi(100)
fig.set_size_inches(14, 6)

# Lower and upper limit of the axes of the three subplots
예제 #30
0
def jointplotx(X,
               Y,
               xlabel=None,
               ylabel=None,
               binsim=40,
               binsh=20,
               binscon=15):
    """
Plots the joint distribution of posteriors for X1 and X2, including the 1D
histograms showing the median and standard deviations. Uses simple method
for drawing the confidence contours compared to jointplot (which is wrong).

The work that went in creating this method is shown, step by step, in 
the ipython notebook "error contours.ipynb". Sources of inspiration:
- http://python4mpia.github.io/intro/quick-tour.html

Usage:
>>> jointplot(M.rtr.trace(),M.mdot.trace(),xlabel='$\log \ r_{\\rm tr}$', ylabel='$\log \ \dot{m}$')
	"""
    # Generates 2D histogram for image
    histt, xt, yt = numpy.histogram2d(X,
                                      Y,
                                      bins=[binsim, binsim],
                                      normed=False)
    histt = numpy.transpose(
        histt)  # Beware: numpy switches axes, so switch back.

    # assigns correct proportions to subplots
    fig = pylab.figure()
    gs = pylab.GridSpec(2,
                        2,
                        width_ratios=[3, 1],
                        height_ratios=[1, 3],
                        wspace=0.001,
                        hspace=0.001)
    con = pylab.subplot(gs[2])
    histx = pylab.subplot(gs[0], sharex=con)
    histy = pylab.subplot(gs[3], sharey=con)

    # Image
    con.imshow(histt,
               extent=[xt[0], xt[-1], yt[0], yt[-1]],
               origin='lower',
               cmap=pylab.cm.gray_r,
               aspect='auto')

    # Overplot with error contours 1,2 sigma
    # Contour plot
    histdata, x, y = numpy.histogram2d(X,
                                       Y,
                                       bins=[binscon, binscon],
                                       normed=False)
    histdata = numpy.transpose(
        histdata)  # Beware: numpy switches axes, so switch back.
    pmax = histdata.max()
    cs = con.contour(histdata,
                     levels=[0.68 * pmax, 0.05 * pmax],
                     extent=[x[0], x[-1], y[0], y[-1]],
                     colors=['black', 'blue'])
    # use dictionary in order to assign your own labels to the contours.
    #fmtdict = {s[0]:r'$1\sigma$',s[1]:r'$2\sigma$'}
    #con.clabel(cs, fmt=fmtdict, inline=True, fontsize=20)
    if xlabel != None: con.set_xlabel(xlabel)
    if ylabel != None: con.set_ylabel(ylabel)

    # X-axis histogram
    histx.hist(X, binsh, histtype='stepfilled', facecolor='lightblue')
    pylab.setp(histx.get_xticklabels(), visible=False)  # no X label
    pylab.setp(histx.get_yticklabels(), visible=False)  # no Y label
    # Vertical lines with median and 1sigma confidence
    yax = histx.set_ylim()
    histx.plot([numpy.median(X), numpy.median(X)], [yax[0], yax[1]],
               'k-',
               linewidth=2)  # median
    xsd = scipy.stats.scoreatpercentile(X, [15.87, 84.13])
    histx.plot([xsd[0], xsd[0]], [yax[0], yax[1]], 'k--')  # -1sd
    histx.plot([xsd[-1], xsd[-1]], [yax[0], yax[1]], 'k--')  # +1sd

    # Y-axis histogram
    histy.hist(Y,
               binsh,
               histtype='stepfilled',
               orientation='horizontal',
               facecolor='lightyellow')
    pylab.setp(histy.get_yticklabels(), visible=False)  # no Y label
    pylab.setp(histy.get_xticklabels(), visible=False)  # no X label
    # Vertical lines with median and 1sigma confidence
    xax = histy.set_xlim()
    histy.plot([xax[0], xax[1]],
               [numpy.median(Y), numpy.median(Y)],
               'k-',
               linewidth=2)  # median
    ysd = scipy.stats.scoreatpercentile(Y, [15.87, 84.13])
    histy.plot([xax[0], xax[1]], [ysd[0], ysd[0]], 'k--')  # -1sd
    histy.plot([xax[0], xax[1]], [ysd[-1], ysd[-1]], 'k--')  # +1sd