示例#1
0
    def initiate(self):
        self.f, self.a = plt.subplots()
        self.f.autofmt_xdate()
        # self.at = self.a.twinx()

        self.plot_active_d1()
        self.plot_active_d2()
        self.update_xlim()
        self.event_handling()

        out = self.controller.database.get_all_flights()
        for idx, flight in out.iterrows():
            self.controller.view.plot.plot_flight_duration(
                flight.start, flight.end, flight.alt, flight.alt_source)

        custom_lines = [
            plt.Line2D([0], [0], color=colors[0], alpha=0.3, lw=5),
            plt.Line2D([0], [0], color=colors[1], alpha=0.3, lw=5),
            plt.Line2D([0], [0], color='0.5', alpha=0.3, lw=5),
        ]

        # fig, ax = plt.subplots()
        # lines = self..plot(data)
        legend_source = self.a.legend(custom_lines, ['gps', 'baro', 'bad'],
                                      loc=1)
        self.a.legend(loc=2)
        self.a.add_artist(legend_source)
        self.a.grid(True)
        return self.a, None  #self.at
示例#2
0
def plot_pie_network(model, path, t=20, xylim=None, show_landcover_pies=True, annotation=None):

    fig, node_size = prepare_network_fig(model, model.pars["network_type"], xylim=xylim)

    P_traj = model.sv_traj.T[::model.dim]
    # q_traj = self.sv_traj.T[1::5]
    # k_traj = self.sv_traj.T[2::5]
    F_traj = model.sv_traj.T[3::model.dim]
    S_traj = model.sv_traj.T[4::model.dim]

    if show_landcover_pies:
        node_pos = list(model.node_pos.values())
        for node in range(model.no_agents):
            draw_pie([F_traj[node][t], P_traj[node][t], S_traj[node][t]], center=node_pos[node],
                     radius=model.plot_pars["pie_radius"], startangle=90, width=0.8 * model.plot_pars["pie_radius"],
                     colors=('darkgreen', 'lawngreen', 'm'))

    nx.draw_networkx_edges(model.G, model.node_pos, alpha=0.2)

    strategy_cmap = matplotlib.colors.LinearSegmentedColormap.from_list('mycmap', [(0, 'darkblue'), (1, 'darkred')])
    # because mapping does not work if there is no node with strategy 0:
    if sum(model.strategy_traj[t]) == model.no_agents:
        strategy_cmap = matplotlib.colors.LinearSegmentedColormap.from_list('mycmap', [(0, 'darkred'), (1, 'darkred')])

    nx.draw_networkx_nodes(model.G, model.node_pos, node_color=model.strategy_traj[t], node_size=node_size,
                           cmap=strategy_cmap)

    if annotation is not None:
        plt.annotate(annotation, xy=(0, 1), xycoords='axes fraction', fontsize=36,
                     xytext=(5, -5), textcoords='offset points',
                     horizontalalignment='left', verticalalignment='top')

    circle1 = plt.Line2D((0, 1), (0, 0), marker='o', linestyle='', markersize=12,
                         color="darkblue", label='Extensive Strategy')

    circle2 = plt.Line2D((0, 1), (0, 0), marker='o', linestyle='', markersize=12,
                         color="darkred", label='Intensive Strategy')

    legend_handles = [circle1, circle2]

    if show_landcover_pies:

        fpatch = matplotlib.patches.Patch(facecolor='darkgreen', edgecolor='k', label='Forest')
        ppatch = matplotlib.patches.Patch(facecolor='lawngreen', edgecolor='k', label='Pasture')
        svpatch = matplotlib.patches.Patch(facecolor='m', edgecolor='k', label='Sec. Vegetation')

        legend_handles.append([fpatch, ppatch, svpatch])

    plt.legend(handles=legend_handles, loc='lower left', prop={'size': 24})

    plt.tight_layout()
    plt.axis('off')

    plt.savefig(path, dpi=model.plot_pars["dpi_saving"])

    plt.clf()
    plt.close(fig)

    return 0
def plot_generated_toy_batch(X_real, generator_model, discriminator_model, noise_dim, gen_iter, noise_scale=0.5):

    # Generate images
    X_gen = sample_noise(noise_scale, 10000, noise_dim)
    X_gen = generator_model.predict(X_gen)

    # Get some toy data to plot KDE of real data
    data = load_toy(pts_per_mixture=200)
    x = data[:, 0]
    y = data[:, 1]
    xmin, xmax = -1.5, 1.5
    ymin, ymax = -1.5, 1.5

    # Peform the kernel density estimate
    xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
    positions = np.vstack([xx.ravel(), yy.ravel()])
    values = np.vstack([x, y])
    kernel = stats.gaussian_kde(values)
    f = np.reshape(kernel(positions).T, xx.shape)

    # Plot the contour
    fig = plt.figure(figsize=(10,10))
    plt.suptitle("Generator iteration %s" % gen_iter, fontweight="bold", fontsize=22)
    ax = fig.gca()
    ax.contourf(xx, yy, f, cmap='Blues', vmin=np.percentile(f,80), vmax=np.max(f), levels=np.linspace(0.25, 0.85, 30))

    # Also plot the contour of the discriminator
    delta = 0.025
    xmin, xmax = -1.5, 1.5
    ymin, ymax = -1.5, 1.5
    # Create mesh
    XX, YY = np.meshgrid(np.arange(xmin, xmax, delta), np.arange(ymin, ymax, delta))
    arr_pos = np.vstack((np.ravel(XX), np.ravel(YY))).T
    # Get Z = predictions
    ZZ = discriminator_model.predict(arr_pos)
    ZZ = ZZ.reshape(XX.shape)
    # Plot contour
    ax.contour(XX, YY, ZZ, cmap="Blues", levels=np.linspace(0.25, 0.85, 10))
    dy, dx = np.gradient(ZZ)
    # Add streamlines
    # plt.streamplot(XX, YY, dx, dy, linewidth=0.5, cmap="magma", density=1, arrowsize=1)
    # Scatter generated data
    plt.scatter(X_gen[:1000, 0], X_gen[:1000, 1], s=20, color="coral", marker="o")

    l_gen = plt.Line2D((0,1),(0,0), color='coral', marker='o', linestyle='', markersize=20)
    l_D = plt.Line2D((0,1),(0,0), color='steelblue', linewidth=3)
    l_real = plt.Rectangle((0, 0), 1, 1, fc="steelblue")

    # Create legend from custom artist/label lists
    # bbox_to_anchor = (0.4, 1)
    ax.legend([l_real, l_D, l_gen], ['Real data KDE', 'Discriminator contour',
                                     'Generated data'], fontsize=18, loc="upper left")
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax + 0.8)
    plt.savefig("../../figures/toy_dataset_iter%s.jpg" % gen_iter)
    plt.clf()
    plt.close()
def plot_position(result_a, t_a, positions):

    z_quad_a = result_a[0, :]
    x_quad_a = result_a[2, :]
    alpha_a = result_a[4, :]
    L = 0.5

    z_mass_a = z_quad_a - L * np.cos(alpha_a)
    x_mass_a = x_quad_a - L * np.sin(alpha_a)
    plt.title("Path Followed by Quadrotor")
    plt.plot(x_mass_a, z_mass_a, label='Mass', ls='--', lw=0.5)
    plt.plot(x_quad_a,
             z_quad_a,
             label='Quadrotor',
             ls='--',
             color='tab:blue',
             lw=0.5)
    for p in positions:
        link = plt.Line2D((x_quad_a[p], x_mass_a[p]),
                          (z_quad_a[p], z_mass_a[p]),
                          lw=0.5,
                          color='k')
        plt.gca().add_line(link)
        mass = plt.Circle((x_mass_a[p], z_mass_a[p]), 0.07, fc='k')
        plt.gca().add_patch(mass)

    plt.xlabel('X Position')
    plt.ylabel('Y Position')
def plot_image_with_bboxes(im, bboxes):
    fig = plt.figure(figsize=(6, 6))
    plt.imshow(im, cmap='Greys')

    bboxes = get_bboxes(im)

    for (b_xs, b_ys) in bboxes:
        Xs = [b_xs[0], b_xs[0], b_xs[1], b_xs[1], b_xs[0]]
        Ys = [b_ys[0], b_ys[1], b_ys[1], b_ys[0], b_ys[0]]
        line = plt.Line2D(Ys, Xs, color='red', linestyle='solid')
        fig.add_subplot(111).add_artist(line)
示例#6
0
def draw_rois(ROIs, axes, c):
    i = 0
    for (x, y) in ROIs:
        l = plt.Line2D(y + [y[0]], x + [x[0]], color=c)
        axes.text(np.max(y) - 5,
                  np.min(x) + 7,
                  str(i),
                  fontsize=10,
                  color=c,
                  bbox=dict(facecolor='w', alpha=0.))
        axes.add_line(l)
        i = i + 1
def plot_image_with_bboxes(im_to_plot, im_to_gen_bboxes):
    fig = plt.figure(figsize=(6, 6))
    plt.imshow(im_to_plot)

    bboxes = evaluate_results.get_bboxes(im_to_gen_bboxes)

    for (b_xs, b_ys) in bboxes:
        Xs = [b_xs[0], b_xs[0], b_xs[1], b_xs[1], b_xs[0]]
        Ys = [b_ys[0], b_ys[1], b_ys[1], b_ys[0], b_ys[0]]
        line = plt.Line2D(Ys, Xs, color='red', linestyle='solid')
        fig.add_subplot(111).add_artist(line)

    plt.show()
示例#8
0
 def draw_rois(self):
     i = 0
     for (x, y) in self.ROIs:
         # NOTE: x and y coordinates are exchanged!!
         # imshow and Line2D assume different coordinate arrangements!!
         l = plt.Line2D(y + [y[0]], x + [x[0]], color=self.cmap[i, :])
         self.axes.text(np.max(y) - 5,
                        np.min(x) + 7,
                        str(i),
                        fontsize=10,
                        color=self.cmap[i, :],
                        bbox=dict(facecolor='w', alpha=0.))
         self.axes.add_line(l)
         i = i + 1
示例#9
0
    def plot_n_by_run(self, y, lbl=None, ax=None):
        plt.rc('text', usetex=True)
        plt.rc('font', family='serif', size=16)

        mrk = ('o', 's', 'v', '^', '<', '>')
        nmrk = len(mrk)

        if ax is None:
            fig = plt.figure(figsize=(10, 6))
            ax = fig.gca()

        grps = np.array(self.grps)
        i = np.arange(len(self.runs)) + np.array(grps)

        vmx = float("-inf")
        for j in range(len(y)):
            if lbl is not None:
                l = lbl[j]
            else:
                l = None
            ax.stem(i,
                    y[j],
                    linefmt="C%d" % j,
                    markerfmt="C%d" % j + mrk[j % nmrk],
                    basefmt="None",
                    label=l)
            m = np.max(y[j])
            vmx = max(m, vmx)

        for j in range(np.max(grps) + 1):
            k, = np.where(grps == j)
            k += grps[k]
            k0, kn = k[0], k[-1]
            ax.add_line(
                plt.Line2D([k0, kn], [0.] * 2, c="C%d" % j, linewidth=5))

        ax.set_xticks(i)
        ax.set_xticklabels(self.runs)
        ax.set_xlabel("run")
        ax.tick_params("x", labelrotation=90)
示例#10
0
 def draw_path(u, v, arrow_length=.1, color=(.8, .8, .8), lw=1):
     du = u.direction
     #plt.arrow(u.pose[X], u.pose[Y], du[0] * arrow_length, du[1] * arrow_length,
     #          head_width=.05, head_length=.1, fc=color, ec=color)
     dv = v.direction
     #plt.arrow(v.pose[X], v.pose[Y], dv[0] * arrow_length, dv[1] * arrow_length,
     #          head_width=.05, head_length=.1, fc=color, ec=color)
     center, radius = find_circle(u, v)
     du = u.position - center
     theta1 = np.arctan2(du[1], du[0])
     dv = v.position - center
     theta2 = np.arctan2(dv[1], dv[0])
     # Check if the arc goes clockwise.
     if np.cross(u.direction, du).item() > 0.:
         theta1, theta2 = theta2, theta1
     #ax.add_patch(patches.Arc(center, radius * 2., radius * 2.,
     #                         theta1=theta1 / np.pi * 180., theta2=theta2 / np.pi * 180.,
     #                         color=color, lw=lw))
     line = plt.Line2D(tuple([u.position[0], v.position[0]]),
                       tuple([u.position[1], v.position[1]]),
                       color=color,
                       lw=lw)
     ax.add_line(line)
示例#11
0
    def _get_camera(self, plane, **kargs):
        x0 = self.__params['r'] * (np.sin(self.__params['t'] * np.pi / 180.) *
                                   np.cos(self.__params['p'] * np.pi / 180.))

        y0 = self.__params['r'] * np.sin(self.__params['p'] * np.pi / 180.)

        z0 = self.__params['r'] * (np.cos(self.__params['t'] * np.pi / 180.) *
                                   np.cos(self.__params['p'] * np.pi / 180.))

        xcam = self.__params['x'] + x0
        ycam = self.__params['y'] + y0
        zcam = self.__params['z'] + z0

        if (plane == 'xy'):
            camera = plt.Line2D([xcam], [ycam],
                                c='m',
                                marker='o',
                                markersize=15,
                                **kargs)
            arrow = plt.Line2D([xcam, self.__params['x']],
                               [ycam, self.__params['y']],
                               lw=5)
        elif (plane == 'xz'):
            camera = plt.Line2D([xcam], [zcam],
                                c='m',
                                marker='o',
                                markersize=15,
                                **kargs)
            arrow = plt.Line2D([xcam, self.__params['x']],
                               [zcam, self.__params['z']],
                               lw=5)
        elif (plane == 'yz'):
            camera = plt.Line2D([ycam], [zcam],
                                c='m',
                                marker='o',
                                markersize=15,
                                **kargs)
            arrow = plt.Line2D([ycam, self.__params['y']],
                               [zcam, self.__params['z']],
                               lw=5)
        else:
            print('Incorrect plane:', plane)
            print("Possibles planes are: 'xy';'xz';'yz'")
            return
        return camera, arrow
示例#12
0
    def _plot_dots(self):

        # plt.plot(self.reward_position[0],self.reward_position[1],'ro',markersize=15,label='reward')

        circle1 = plt.Circle((self.reward_position[0], self.reward_position[1]), self.reward_radius, color='r',
                             alpha=0.6)
        plt.gca().add_artist(circle1)

        pl = plt.Line2D([0.1], [0.1], color='g', markersize=10., marker='o', linewidth=0)
        plt.gca().add_artist(pl)

        handlers = [pl, circle1]
        labels = ['initial position', 'goal']

        if self.obstacle:
            # plt.plot(self.obstacle_position[0],self.obstacle_position[1],'bo',markersize=15,label='obstacle')
            circle2 = plt.Circle((self.obstacle_position[0], self.obstacle_position[1]), self.reward_radius, color='b',
                                 alpha=0.6)
            plt.gca().add_artist(circle2)
            handlers.append(circle2)
            labels.append('obstacle')

        plt.legend(handlers, labels, bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
                   ncol=3, mode="center", borderaxespad=0.)
示例#13
0
recordings_noise = []
for n in noise_levels:
    print('noise level:', n)
    params['recordings']['noise_level'] = n
    params['recordings']['seed'] = np.random.randint(1000)
    recgen = mr.gen_recordings(tempgen=tempgen, params=params)
    recordings_noise.append(recgen)

fig1 = plt.figure(figsize=(12, 14))
ax_noise = fig1.add_subplot(111)

for i, rec in enumerate(recordings_noise):
    ax_noise = mr.plot_recordings(rec, colors=colors[i], ax=ax_noise, lw=0.2, start_time=1, end_time=2)

legend_lines = [plt.Line2D([0], [0], color=colors[0], lw=2),
                plt.Line2D([0], [0], color=colors[1], lw=2),
                plt.Line2D([0], [0], color=colors[2], lw=2),
                plt.Line2D([0], [0], color=colors[3], lw=2)]
ax_noise.legend(handles=legend_lines, labels=['30 $\mu$V', '20 $\mu$V', '10 $\mu$V', '5  $\mu$V'],
                fontsize=15, loc='upper right')

y_lim = ax_noise.get_ylim()
x_lim = ax_noise.get_xlim()

ts_lim = (x_lim[1] - x_lim[0]) // 3
ax_noise.plot([x_lim[0], x_lim[0] + 0.2 * ts_lim],
              [np.min(y_lim) + 0.12 * np.abs(np.min(y_lim)),
               np.min(y_lim) + 0.12 * np.abs(np.min(y_lim))], 'k', lw=2)
ax_noise.text(x_lim[0] + 0.01 * ts_lim, np.min(y_lim) + 0.05 * np.abs(np.min(y_lim)), '200 ms')
示例#14
0
def plot_many(bins,
              linestyles,
              bin_labels,
              age_then=None,
              z_func=None,
              colors=None,
              **kwargs):
    import numpy as np
    import matplotlib.pylab as plt
    from seren3.array import SimArray
    from seren3.utils.plot_utils import ncols

    ax1 = plt.gca()

    legendArtists = []
    for i in range(len(bins)):
        ls = linestyles[i]
        plot_mean_integrated_fesc(bins[i], linestyle=ls, colors=colors,\
                     label=False, legend=False, **kwargs)

        legendArtists.append(
            plt.Line2D((0, 1), (0, 0), color='k', linestyle=ls))

    handles, labels = ax1.get_legend_handles_labels()
    display = tuple(range(len(bins[0])))

    ax1.set_xlim(0.2, 0.7)

    # Shrink current axis's height by 10% on the bottom
    box = ax1.get_position()
    ax1.set_position(
        [box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])

    # Put a legend below current axis
    legend_kwargs = {"title" : r"log$_{10}$(Mvir)", "loc" : "upper center", \
                "bbox_to_anchor" : (0.5, -0.1), "fancybox" : True, "shadow" : True, "ncol" : 4}
    ax1.legend([handle for i,handle in enumerate(handles) if i in display]+legendArtists,\
             [label for i,label in enumerate(labels) if i in display]+bin_labels, **legend_kwargs)

    # Redshift axis
    if (z_func is not None) and (age_then is not None):
        ax2 = ax1.twiny()
        ax2.set_position(
            [box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])

        def tick_function(X):
            # return ["%1.1f" % i for i in z_func( age_now - X )]
            # We've scaled the x-axis by the age of halos, so need
            # to account for zero-point in age
            return ["%1.1f" % i for i in z_func(SimArray(X + age_then, "Gyr"))]

        xtickpos = ax1.get_xticks()
        print xtickpos
        new_tick_locations = np.linspace(0.215, 0.685, 5)
        print new_tick_locations
        # new_tick_locations = np.array(ax1.get_xticks())

        ax2.set_xlim(ax1.get_xlim())
        ax2.set_xticks(new_tick_locations)
        ax2.set_xticklabels(tick_function(new_tick_locations))
        ax2.set_xlabel(r"Redshift")

    ax1.set_xlabel(r"t$_{\mathrm{H}}$ [Gyr]")
    ax1.set_ylabel(
        r"$\langle \mathrm{f}_{\mathrm{esc}} \rangle$ (<t$_{\mathrm{H}}$ [%])")
示例#15
0
    stack = []
    info = []
    lines = []
    for i in (1, 2):
        # read image from file
        filename = '../tests/qseries%d.tif' % i
        stack.append(tiff.imread(filename))

        # info for image
        info.append({
            'desc': 'WQStackBrowser: ' + filename,
            'filename': filename,
            'xperchan': 4.,
            'yperchan': 64.
        })

        # additional line plots
        y = np.arange(150, 4096)
        l1 = plt.Line2D(np.poly1d(coeff[i - 1][0])(y), y, color='r', ls='-')
        l2 = plt.Line2D(np.poly1d(coeff[i - 1][1])(y), y, color='g', ls='-')
        lines.append([l1, l2])

    # show single image
    IB = WQBrowser(stack[0], {'desc': 'WQBrowser'}, aspect='auto', verbosity=4)

    # show image stack
    IB = WQStackBrowser(stack, info, lines, verbosity=4)

    plt.show()
示例#16
0
 def draw_current_roi(self):
     # NOTE: x and y exchanged!
     l = plt.Line2D(self.curr_roi_y, self.curr_roi_x, color='r', marker='.')
     self.axes.add_line(l)
示例#17
0
                               frames=dp,
                               interval=0,
                               blit=True)

# Label the axes
ax.set_xlabel('x [Mpc]')
ax.set_ylabel('y [Mpc]')
ax.set_zlabel('z [Mpc]')

# Add a title to the plot
plt.title(str(N) + '-Body Simulation', size=18)

# Set Plot Legend
pos_mass = plt.Line2D([0], [0],
                      linestyle="none",
                      c='b',
                      marker='.',
                      label='+ve Mass')
neg_mass = plt.Line2D([0], [0],
                      linestyle="none",
                      c='r',
                      marker='.',
                      label='-ve Mass')
ax.legend(handles=[pos_mass, neg_mass],
          bbox_to_anchor=(0., 1.075),
          loc=2,
          borderaxespad=0.,
          numpoints=1)

# Show the plot
plt.show()
示例#18
0
def pnorm_ball_line(A=np.eye(2), mu=np.array([0,0]),p=2, N=128,color='r',linewidth=3):
	'''	Creates line objects. Show them with ax.add_line(ln) '''
	dx,dy = pnorm_ball_points(A)
	ln = plt.Line2D(dx,dy, color=color, linewidth=linewidth)
	return ln
示例#19
0
 def draw(self,
          directed=True,
          layout="spring",
          node_label_attr=None,
          show_node_labels=True,
          edge_label_attr=None,
          show_edge_labels=True,
          node_size=1600,
          node_color='blue',
          node_alpha=0.3,
          node_text_size=12,
          edge_color='blue',
          edge_alpha=0.3,
          edge_tickness=1,
          edge_text_pos=0.3,
          text_font='sans-serif',
          ax=None):
     "Plot of a NetworkX multi-graph instance"
     graph = self.graph(directed=directed)
     pos = getattr(nx, "{}_layout".format(layout))(graph)
     node_labels = {}
     edge_labels = {}
     node_colors = set()
     if show_node_labels:
         for node, props in graph.nodes(data=True):
             labels = props.pop('labels', [])
             for label in labels:
                 node_colors.add(label)
             if node_label_attr is None:
                 node_labels[node] = "$:{}$\n{}".format(
                     ":".join(labels),
                     props.values()[0] if props else "",
                 )
             else:
                 props_list = [
                     "{}: {}".format(k, v) for k, v in props.items()
                 ]
                 node_labels[node] = "$:{}$\n{}".format(
                     ":".join(labels), "\n".join(props_list))
     node_color = []
     node_colors = list(node_colors)
     legend_colors = []
     colors = plt.matplotlib.colors.ColorConverter().cache.items()
     for color_name, color_rgb in colors[:len(node_colors)]:
         node_color.append(color_rgb)
         legend_colors.append(color_name)
     if show_edge_labels:
         for start, end, props in graph.edges(data=True):
             if edge_label_attr is None:
                 edge_label = props.get("type", '')
             else:
                 edge_label = props.get(edge_label_attr, '')
             edge_labels[(start, end)] = edge_label
     if not ax:
         fig = plt.figure()
         ax = fig.add_subplot(111)
     nodes = nx.draw_networkx_nodes(graph,
                                    pos=pos,
                                    node_color=node_color,
                                    node_size=node_size,
                                    alpha=node_alpha,
                                    ax=ax)
     nx.draw_networkx_labels(graph,
                             pos=pos,
                             labels=node_labels,
                             font_size=node_text_size,
                             font_family=text_font,
                             ax=ax)
     nx.draw_networkx_edges(graph,
                            pos=pos,
                            width=edge_tickness,
                            alpha=edge_alpha,
                            edge_color=edge_color,
                            ax=ax)
     nx.draw_networkx_edge_labels(graph,
                                  pos=pos,
                                  edge_labels=edge_labels,
                                  ax=ax)
     ax.legend([
         plt.Line2D([0], [0],
                    linestyle="none",
                    marker="o",
                    alpha=node_alpha,
                    markersize=10,
                    markerfacecolor=color) for color in legend_colors
     ],
               node_colors,
               loc=(-0.25, 1),
               numpoints=1,
               frameon=False)
     ax.set_axis_off()
     return graph, ax, nodes
示例#20
0
def main():
    markers = {'pfam': '8', 'cameo': 'p', 'cameo41': "*", 'membrane': "D"}

    total_folds = {"Periscope": 0, "Modeller": 0}

    for dataset in datasets:
        scores = {}
        ds = getattr(DATASETS, dataset)

        for target in ds:
            s = _get_scores(target)
            if s is None:
                continue
            scores[target] = s
        proteins = list(scores.keys())

        def _check_score(s):
            return scores[s]['modeller'] is not None

        proteins = [s for s in proteins if _check_score(s)]

        our_scores = np.array([scores[s]['ms_2'] for s in proteins])
        modeller = np.array([scores[s]['modeller'] for s in proteins])
        refs_scores = np.array([scores[s]['ref'] for s in proteins])

        n_homs = np.array([scores[s]['n_homs'] for s in proteins])
        n_homs = n_homs / 1000  # / (np.max(n_homs) / 20)
        n_refs = np.array([float(scores[s]['n_refs']) for s in proteins])
        n_refs = n_refs  # / np.max(n_refs)

        modeller_correct_fold = np.sum(np.array(modeller) > 0.5)
        total_folds['Modeller'] += modeller_correct_fold
        ms_correct_fold = np.sum(np.array(our_scores) > 0.5)
        total_folds['Periscope'] += ms_correct_fold

        LOGGER.info(
            f'{dataset} (n = {len(modeller)}):\nModeller correct folds: {modeller_correct_fold}\nMs correct fold {ms_correct_fold}'
        )

        modeller_win = np.sum(
            np.logical_and(
                np.array(modeller) > 0.5,
                np.array(our_scores) < 0.5))
        ms_win = np.sum(
            np.logical_and(
                np.array(our_scores) > 0.5,
                np.array(modeller) < 0.5))

        LOGGER.info(
            f'{dataset} (n = {len(modeller)}):\nModeller win: {modeller_win}\nMs win {ms_win}'
        )
        # color = np.array(['blue' if s>0.5 else 'red' for s in our_scores])
        tt = np.where(np.logical_and(modeller > 0.5, our_scores > 0.5))
        ft = np.where(np.logical_and(modeller < 0.5, our_scores > 0.5))
        tf = np.where(np.logical_and(modeller > 0.5, our_scores < 0.5))
        ff = np.where(np.logical_and(modeller < 0.5, our_scores < 0.5))
        our_scores -= refs_scores
        modeller -= refs_scores
        sc1 = plt.scatter(our_scores[tt],
                          modeller[tt],
                          c=n_refs[tt],
                          marker=10,
                          label=dataset,
                          s=n_homs[tt],
                          cmap=plt.cm.get_cmap('Greys'))
        sc = plt.scatter(our_scores[tt],
                         modeller[tt],
                         c=n_refs[tt],
                         marker=10,
                         label=dataset,
                         s=n_homs[tt],
                         cmap=plt.cm.get_cmap('Blues'))
        plt.scatter(our_scores[ft],
                    modeller[ft],
                    c=n_refs[ft],
                    marker=11,
                    label=dataset,
                    s=n_homs[ft],
                    cmap=plt.cm.get_cmap('Blues'))
        plt.scatter(our_scores[tf],
                    modeller[tf],
                    c=n_refs[tf],
                    marker=10,
                    label=dataset,
                    s=n_homs[tf],
                    cmap=plt.cm.get_cmap('Reds'))
        plt.scatter(our_scores[ff],
                    modeller[ff],
                    c=n_refs[ff],
                    marker=11,
                    label=dataset,
                    s=n_homs[ff],
                    cmap=plt.cm.get_cmap('Reds'))

        plt.xlim([-1, 1])
        plt.ylim([-1, 1])
        for i, s in enumerate(proteins):
            if True:  # dataset != 'membrane':
                dx = our_scores[i] - scores[s]['ref']
                dy = modeller[i] - scores[s]['ref']
                start = (scores[s]['ref'], dx)
                end = (scores[s]['ref'], dy)
                # plt.arrow(start[0], end[0], start[1], end[1], linestyle=(0, (1, 10)),
                #           color=color[i])

            # if our_scores[i] > 0.5 and modeller[i] > 0.5:
            #     continue
            # plt.annotate(s, (our_scores[i], modeller[i]), size=6)

        plt.plot([-1, 1], [-1, 1], '--', c='black', alpha=0.3)
        # plt.plot([0.5, 0.5], [0, 1], '--', c='black', alpha=0.3)
        # plt.plot([0, 1], [0.5, 0.5], '--', c='black', alpha=0.3)

        legend_elements = [
            plt.Line2D([0], [0],
                       marker='o',
                       color='blue',
                       label='Periscope > 0.5',
                       linestyle='None'),
            plt.Line2D([0], [0],
                       marker='o',
                       color='red',
                       label='Periscope < 0.5',
                       linestyle='None'),
            plt.Line2D([0], [0],
                       marker=11,
                       color='black',
                       label='Modeller < 0.5',
                       linestyle='None'),
            plt.Line2D([0], [0],
                       marker=10,
                       color='black',
                       label='Modeller > 0.5',
                       linestyle='None')
        ]

        plt.xlabel("Our Method - Ref")
        plt.ylabel("Modeller - Ref")
        cb = plt.colorbar(sc1)
        cb.ax.get_yaxis().labelpad = 25

        cb.ax.set_ylabel('# of templates', rotation=270)

        plt.legend(handles=[mpatches.Patch(color='black', label='Type1')])
        legend1 = plt.legend(legend_elements, [
            "Periscope > 0.5", "Periscope < 0.5", "Modeller < 0.5",
            "Modeller > 0.5"
        ],
                             loc=2,
                             fontsize=6,
                             fancybox=True)
        plt.legend(*sc.legend_elements("sizes", num=6),
                   loc=3,
                   fancybox=True,
                   title='MSA depth\n(Thousends)',
                   fontsize=6)
        plt.gca().add_artist(legend1)
        # plt.legend(loc='upper left')
        plt.title(f'{dataset}')
        plt.savefig(
            os.path.join(PATHS.periscope, 'data', 'figures',
                         f'tm_scores_{dataset}.png'))
        plt.close()

    LOGGER.info(f'Total folds:\n{total_folds}')
示例#21
0
    def fit_aperture_borders(self, order=2, log=False, **kwargs):
        """
    Determine the left and right border of the aperture as polynom x(y) 
    for the series of E-q maps.     
  
    order     ... (opt) order of the polynomial to fit
    log       ... (opt) consider aperture images on log-scale
    for further options, see fit_border.get_border_points()
  
    RETURNS list of tuples(left,right) containing polynomials x = left(y)
    """
        self.ap_order = order
        self.ap_log = log

        # illumination reference (smoothed version)
        if self.ref_name is not None:
            ref = np.abs(gaussfilt1D(self.ref_img, 11))
            # gauss-filter
            #ref = np.abs(lorentzfit1D(self.ref_img,offset=offset));  # fit lorentz
            ref[ref < np.mean(ref)] = np.mean(ref)
            # constant for low values
            # to avoid 0 devision
            if self.verbosity > 9:
                self.__dbg_fig.append(self.plot_reference(ref))
                # draw figure and save in list
        else:
            ref = 1
            # no reference given

        # iterate over all aperture images
        points = []
        fit = []
        lines = []
        stack = []
        info = []
        for i, image in enumerate(self.ap_stack):

            # correct image by illu_ref
            filtimg = image / ref
            if log: filtimg = np.log(np.abs(filtimg) + 1)

            # get aperture border as point list in px (correct for binning!)
            c = self.crop
            l, r = fit_border.get_border_points(
                filtimg,
                interp_out=True,
                xmin=int(c['xmin'] / self.xbin),
                xmax=int(c['xmax'] / self.xbin),
                ymin=int(c['ymin'] / self.ybin),
                ymax=int(c['ymax'] / self.ybin),
                verbosity=self.verbosity - 10,
                **kwargs)
            l = ((l + 0.5).T * (self.xbin, self.ybin)).T
            # convert to px, points (x,y)
            r = ((r + 0.5).T * (self.xbin, self.ybin)).T
            points.append([l, r])

            # fit polynom x=p(y) to left and right border
            polyl = np.poly1d(np.polyfit(l[1], l[0], order))
            polyr = np.poly1d(np.polyfit(r[1], r[0], order))
            fit.append((polyl, polyr))

            # DEBUG: drawing fit points and polynoms
            if self.verbosity > 2:
                y = np.arange(self.crop['ymin'], self.crop['ymax'])
                stack.append(filtimg)
                info.append({
                    'desc': 'DEBUG: ' + self.ap_names[i],
                    'xperchan': self.xbin,
                    'yperchan': self.ybin
                })
                p1 = plt.Line2D(l[0], l[1], marker='x', ls='', c='b')
                p2 = plt.Line2D(r[0], r[1], marker='x', ls='', c='b')
                p3 = plt.Line2D(polyl(y), y, color='r')
                p4 = plt.Line2D(polyr(y), y, color='r')
                lines.append([p1, p2, p3, p4])
        if self.verbosity > 2:
            self.__dbg_fig.append(self.plot_aperture_images(
                stack, info, lines))

        # store results
        self.ap_points = points
        # contains Nap (l,r) tuples; l,r are a lists of (x,y) points
        self.ap_poly = fit
        # contains Nap (pl,pr) tuples; pl,pr are polynoms y(x)

        # comments
        self.history.append("Fit aperture borders")
        self.history.append("|- order=%d,  log=%s" % (order, log))
        params = ", ".join(
            [key + ": " + str(val) for key, val in kwargs.items()])
        self.history.append("|- " + params)

        return fit
示例#22
0
def visualization(robot, pr, factor=7):

    plt.figure("Robot in the world", figsize=(field.w_width, field.w_length))
    plt.title('Particle filter')

    # draw coordinate grid for plotting
    grid = [
        -field.w_width / 2.0, field.w_width / 2.0, -field.w_length / 2.0,
        field.w_length / 2.0
    ]
    ax = plt.axis(grid)

    landmarks = {
        "blue_posts": [[-1.0, -4.5], [1.0, -4.5]],
        "yellow_posts": [[-1.0, 4.5], [1.0, 4.5]]
    }

    for el in field.field:
        if el == 'circles':
            for circle in field.field['circles']:
                plot_circle = plt.Circle((circle[0], circle[1]),
                                         circle[2],
                                         linewidth=2,
                                         fill=False,
                                         edgecolor='#330000')
                plt.gca().add_patch(plot_circle)
        if el == 'lines':
            for line in field.field['lines']:
                plot_line = plt.Line2D(line[0],
                                       line[1],
                                       linewidth=2,
                                       linestyle="-",
                                       color='#330000')
                plt.gca().add_line(plot_line)
        if el == 'rectangles':
            for rectangle in field.field['rectangles']:
                rect = plt.Rectangle(rectangle[0],
                                     rectangle[1],
                                     rectangle[2],
                                     linewidth=2,
                                     linestyle="-",
                                     fill=False,
                                     edgecolor='#330000')
                plt.gca().add_patch(rect)
    '''
    # draw particles
    for ind in range(len(p)):
 
        # particle
        circle = plt.Circle((p[ind][0].x, p[ind][0].y), 1./factor/2, facecolor='#ffb266', edgecolor='#994c00', alpha=0.5)
        plt.gca().add_patch(circle)
 
        # particle's orientation
        arrow = plt.Arrow(p[ind][0].x, p[ind][0].y, 2*math.cos(p[ind][0].yaw)/factor, 2*math.sin(p[ind][0].yaw)/factor, width=1/factor, alpha=1., facecolor='#994c00', edgecolor='#994c00')
        plt.gca().add_patch(arrow)
    '''
    # draw resampled particles
    for ind in range(len(pr)):

        # particle
        circle = plt.Circle((pr[ind][0].y, pr[ind][0].x),
                            1. / factor / 2,
                            facecolor='#ffb266',
                            edgecolor='#cc0000',
                            alpha=0.5)
        plt.gca().add_patch(circle)

        # particle's orientation
        arrow = plt.Arrow(pr[ind][0].y,
                          pr[ind][0].x,
                          2 * math.sin(pr[ind][0].yaw) / factor,
                          math.cos(pr[ind][0].yaw) / factor,
                          width=1 / factor,
                          alpha=1.,
                          facecolor='#006600',
                          edgecolor='#006600')
        plt.gca().add_patch(arrow)

    # robot's location
    circle = plt.Circle((robot.y, robot.x),
                        1. / factor,
                        facecolor='#FF66E9',
                        edgecolor='#FF66E9')
    plt.gca().add_patch(circle)

    # robot's orientation
    arrow = plt.Arrow(robot.y,
                      robot.x,
                      3 * math.sin(robot.yaw) / factor,
                      3 * math.cos(robot.yaw) / factor,
                      width=1.0 / factor,
                      alpha=0.5,
                      facecolor='#000000',
                      edgecolor='#000000')
    plt.gca().add_patch(arrow)

    #fixed landmarks of known locations2

    for lm in landmarks:
        for lms in landmarks[lm]:
            if lm == "yellow_posts":
                circle = plt.Circle(((lms[0], lms[1])),
                                    1. / factor,
                                    facecolor='#ffff00',
                                    edgecolor='#330000')
                plt.gca().add_patch(circle)
            else:
                circle = plt.Circle(((lms[0], lms[1])),
                                    1. / factor,
                                    facecolor='#060C73',
                                    edgecolor='#330000')
                plt.gca().add_patch(circle)
示例#23
0
def xkcd(
    ax,
    mag=1.0,
    f1=50,
    f2=0.01,
    f3=15,
    bgcolor='w',
    title_size=None,
    xaxis_loc=None,
    yaxis_loc=None,
    xaxis_arrow='+',
    yaxis_arrow='+',
    ax_extend=0.1,
    xlabel_inside=0.,
    ylabel_inside=0.,
    ticks=False,
    xticks_inside=0.,
    yticks_inside=0.,
):
    """
        Make axis look hand-drawn

        This adjusts all lines, text, legends, and axes in the figure to look
        like xkcd plots, a webcomic from Randall Munroe. Other plot elements are not modified.


        Definition
        ----------
        def xkcd(ax,
                 mag=1.0,
                 f1=50, f2=0.01, f3=15,
                 bgcolor='w',
                 title_size=None,
                 xaxis_loc=None, yaxis_loc=None,
                 xaxis_arrow='+', yaxis_arrow='+',
                 ax_extend=0.1,
                 xlabel_inside=0., ylabel_inside=0.,
                 ticks=False,
                 xticks_inside=0., yticks_inside=0.,
                 ):


        Input
        -----
        ax    Axes instance the axes instance to be modified.


        Optional Input
        --------------

        mag                            float; the magnitude of the distortion (default: 1.0)
        f1, f2, f3                     int, float, int; filtering parameters.
                                       f1 gives the size of the window (default: 50)
                                       f2 gives the high-frequency cutoff (default: 0.01)
                                       f3 gives the size of the filter (default: 15)
        bgcolor                        str; color around lines so that axis look brocken,
                                       i.e. lines are overdrawn on axis (default: 'w')
        titel_size                     float; poitn size of plot title. If None, same size as axis labels.
                                       (default: None)
        xaxis_loc, yaxis_log           float; The locations to draw the x and y axes in data coordinates.
                                       If not specified, they will be drawn from the bottom left of the plot.
                                       (default: None)
        xaxis_arrow, yaxis_arrow       str; where to draw arrows on the x/y axes
                                       Options are '+', '-', '+-', or '' (default: '+')
        ax_extend                      float; How far (fractionally) to extend the drawn axes beyond
                                       the original axes limits (default: 0.1)
        xlabel_inside, ylabel_inside   float: By how much the labels are shifted (default: 0.0)

        The last two options are not working how with mc_plot_template
        ticks                          True: change tick labels; False: no tick labels are drawn (default: False)
        xticks_inside, yticks_inside   float: By how much the ticks are shifted (default: 0.0)


        Output
        ------
        ax is basically empty and all former elements are redrawn on plot.


        Note
        ----
        For reproducible plots, seed the random number generator before each new plot.
        If a new line was added, the old lines will look the same. The legend will be different though.


        References
        ----------
        This is the modified XKCD plot generator of Jake Vanderplas
        http://nbviewer.ipython.org/url/jakevdp.github.com/downloads/notebooks/XKCD_plots.ipynb

        The idea for this comes from work by Damon McDougall
        http://www.mail-archive.com/[email protected]/msg25499.html


        Examples
        --------
        import matplotlib.pylab as plt
        fig = plt.figure(1)
        ax = fig.add_axes([0.1,0.1,0.5,0.5])
        ax.plot(range(10), label='Line')
        ax.set_title('Title')
        ax.set_xlabel('x label')
        ax.set_ylabel('y label')
        ax.legend()
        xkcd(ax)


        License
        -------
        This file is part of the JAMS Python package, distributed under the MIT License.

        Copyright (c) 2013 Matthias Cuntz - mc (at) macu (dot) de

        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:

        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.

        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.


        History
        -------
        Written,  MC, Mar 2013
    """
    import matplotlib.pylab as plt
    import matplotlib.font_manager as fm

    # remember random state for later resetting
    random_state = np.random.get_state()

    # Get axes aspect
    ext = ax.get_window_extent().extents
    aspect = (ext[3] - ext[1]) / (ext[2] - ext[0])

    xlim = ax.get_xlim()
    ylim = ax.get_ylim()

    xspan = xlim[1] - xlim[0]
    yspan = ylim[1] - xlim[0]

    xax_lim = (xlim[0] - ax_extend * xspan, xlim[1] + ax_extend * xspan)
    yax_lim = (ylim[0] - ax_extend * yspan, ylim[1] + ax_extend * yspan)

    if xaxis_loc is None: xaxis_loc = ylim[0]
    if yaxis_loc is None: yaxis_loc = xlim[0]

    # Draw axes
    acolor = ax.get_xaxis().get_gridlines()[0].get_color()
    xaxis = plt.Line2D([xax_lim[0], xax_lim[1]], [xaxis_loc, xaxis_loc],
                       linestyle='-',
                       color=acolor)
    yaxis = plt.Line2D([yaxis_loc, yaxis_loc], [yax_lim[0], yax_lim[1]],
                       linestyle='-',
                       color=acolor)

    # adjust the axes
    if ticks:
        for x, xtext in zip(ax.get_xticks(), ax.get_xticklabels()):
            ax.text(x,
                    xaxis_loc - 0.08 * yspan * (2 * xticks_inside - 1),
                    xtext.get_text(),
                    fontsize=xtext.get_size(),
                    ha='center',
                    va='bottom' if xticks_inside else 'top',
                    rotation=0)
        for y, ytext in zip(ax.get_yticks(), ax.get_yticklabels()):
            ax.text(yaxis_loc + 0.02 * xspan * (2 * yticks_inside - 1),
                    y,
                    ytext.get_text(),
                    fontsize=ytext.get_size(),
                    ha='left' if yticks_inside else 'right',
                    va='center',
                    rotation=0)

    # Label axes
    siz = ax.get_xaxis().get_label().get_size()
    ax.text(xax_lim[1],
            xaxis_loc - 0.2 * yspan * (2 * xlabel_inside - 1),
            ax.get_xlabel(),
            fontsize=siz,
            ha='right',
            va='bottom' if xlabel_inside else 'top',
            rotation=0)
    ax.text(yaxis_loc + 0.04 * xspan * (2 * ylabel_inside - 1),
            yax_lim[1],
            ax.get_ylabel(),
            fontsize=siz,
            ha='right',
            va='bottom' if ylabel_inside else 'top',
            rotation=84)

    # Title - default: same size as axis labels
    if title_size is not None:
        siz2 = title_size
    else:
        siz2 = siz
    ax.text(0.5 * (xax_lim[1] + xax_lim[0]),
            yax_lim[1],
            ax.get_title(),
            ha='center',
            va='bottom',
            fontsize=siz2)

    # Draw arrow-heads at the end of axes lines
    arr1 = 0.04 * np.array([-1, 0, -1])
    arr2 = 0.03 * np.array([-1, 0, 1])
    arr1[::2] += np.random.normal(0, 0.005 / 2, 2)
    arr2[::2] += np.random.normal(0, 0.005 / 2, 2)
    x, y = xaxis.get_data()
    if '+' in str(xaxis_arrow):
        ax.plot(x[-1] + arr1 * xspan * aspect,
                y[-1] + arr2 * yspan,
                color=acolor,
                lw=2)
    if '-' in str(xaxis_arrow):
        ax.plot(x[0] - arr1 * xspan * aspect,
                y[0] - arr2 * yspan,
                color=acolor,
                lw=2)

    x, y = yaxis.get_data()
    if '+' in str(yaxis_arrow):
        ax.plot(x[-1] + arr2 * xspan * aspect**2,
                y[-1] + arr1 * yspan / aspect,
                color=acolor,
                lw=2)
    if '-' in str(yaxis_arrow):
        ax.plot(x[0] - arr2 * xspan * aspect**2,
                y[0] - arr1 * yspan / aspect,
                color=acolor,
                lw=2)

    # Set the axis limits
    ax.set_xlim(xax_lim[0] - 0.1 * xspan, xax_lim[1] + 0.1 * xspan)
    ax.set_ylim(yax_lim[0] - 0.1 * yspan, yax_lim[1] + 0.1 * yspan)

    # The lines
    Nlines = len(ax.lines)
    lines = [xaxis, yaxis] + [ax.lines.pop(0) for i in range(Nlines)]
    for line in lines:
        x, y = line.get_data()
        ls = line.get_linestyle()
        if ls != 'None':
            x_int, y_int = xkcd_line(x, y, xlim, ylim, mag, f1, f2, f3)
        else:
            x_int, y_int = x, y
        # create foreground and background line
        lw = line.get_linewidth()
        line.set_linewidth(2 * lw)
        line.set_data(x_int, y_int)

        # White surrounding of line makes them look overplot on axis
        if (line is not xaxis) and (line is not yaxis) and ls != 'None':
            line_bg = plt.Line2D(x_int,
                                 y_int,
                                 color=bgcolor,
                                 linewidth=2 * lw + 4)
            ax.add_line(line_bg)
        ax.add_line(line)

    # Change all the fonts to humor-sans.
    # from jams.find_in_path import find_in_path
    # fhumor = find_in_path('Humor-Sans.ttf') # in jams_python
    import os
    fhumor = os.path.join(os.path.dirname(__file__),
                          'Humor-Sans.ttf')  # in jams_python/jams
    for text in ax.texts:
        tsize = text.get_size()
        prop = fm.FontProperties(fname=fhumor, size=tsize)
        text.set_fontproperties(prop)

    # modify legend
    leg = ax.get_legend()
    if leg is not None:
        np.random.set_state(
            random_state
        )  # restate random number generator for reproducible results
        leg.set_frame_on(False)
        for child in leg.get_children():
            if isinstance(child, plt.Line2D):
                x, y = child.get_data()
                child.set_data(
                    xkcd_line(x, y, mag=10. * mag, f1=2 * f1, f2=f2 / 10.))
                child.set_linewidth(2 * child.get_linewidth())
            if isinstance(child, plt.Text):
                tsize = child.get_size()
                prop = fm.FontProperties(fname=fhumor, size=tsize)
                child.set_fontproperties(prop)

    # remove standard axis
    ax.set_title('')
    ax.set_xlabel('')
    ax.set_ylabel('')
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_axis_off()

    return ax
示例#24
0
    def __line_between_two_neurons(self,
                                   ax,
                                   neuron1,
                                   neuron2,
                                   weight=0.4,
                                   textoverlaphandler=None):
        angle = atan((neuron2.x - neuron1.x) / float(neuron2.y - neuron1.y))
        x_adjustment = self.neuron_radius * sin(angle)
        y_adjustment = self.neuron_radius * cos(angle)

        # assign colors to lines depending on the sign of the weight
        color = Tableau_10.mpl_colors[0]
        if weight > 0:
            color = Tableau_10.mpl_colors[1]

        # assign different linewidths to lines depending on the size of the
        # weight
        abs_weight = abs(weight)
        if abs_weight > 0.5:
            linewidth = 10 * abs_weight
        elif abs_weight > 0.8:
            linewidth = 100 * abs_weight
        else:
            linewidth = abs_weight

        # draw the weights and adjust the labels of weights to avoid
        # overlapping
        if abs_weight > 0.5:
            # while loop to determine the optimal locaton for text lables to
            # avoid overlapping
            index_step = 2
            num_segments = 10
            txt_x_pos = (
                neuron1.x - x_adjustment + index_step *
                (neuron2.x - neuron1.x + 2 * x_adjustment) / num_segments)
            txt_y_pos = (
                neuron1.y - y_adjustment + index_step *
                (neuron2.y - neuron1.y + 2 * y_adjustment) / num_segments)
            while (not textoverlaphandler.getspace([
                    txt_x_pos - 0.5,
                    txt_y_pos - 0.5,
                    txt_x_pos + 0.5,
                    txt_y_pos + 0.5,
            ])) and index_step < num_segments:
                index_step = index_step + 1
                txt_x_pos = (
                    neuron1.x - x_adjustment + index_step *
                    (neuron2.x - neuron1.x + 2 * x_adjustment) / num_segments)
                txt_y_pos = (
                    neuron1.y - y_adjustment + index_step *
                    (neuron2.y - neuron1.y + 2 * y_adjustment) / num_segments)

            # print("Label positions: ", "{:.2f}".format(txt_x_pos), "{:.2f}".format(txt_y_pos), "{:3.2f}".format(weight))
            a = ax.text(
                txt_x_pos,
                txt_y_pos,
                "{:3.2f}".format(weight),
                size=8,
                ha='center',
            )
            a.set_bbox(dict(facecolor='white', alpha=0))
            # print(a.get_bbox_patch().get_height())

        line = plt.Line2D(
            (neuron1.x - x_adjustment, neuron2.x + x_adjustment),
            (neuron1.y - y_adjustment, neuron2.y + y_adjustment),
            linewidth=linewidth,
            color=color,
        )
        ax.add_line(line)
示例#25
0
    recgen = mr.gen_recordings(tempgen=tempgen, params=params)
    recordings_noise.append(recgen)

fig1 = plt.figure(figsize=(12, 14))
ax_noise = fig1.add_subplot(111)

for i, rec in enumerate(recordings_noise):
    ax_noise = mr.plot_recordings(rec,
                                  colors=colors[i],
                                  ax=ax_noise,
                                  lw=0.2,
                                  start_time=1,
                                  end_time=2)

legend_lines = [
    plt.Line2D([0], [0], color=colors[0], lw=2),
    plt.Line2D([0], [0], color=colors[1], lw=2),
    plt.Line2D([0], [0], color=colors[2], lw=2),
    plt.Line2D([0], [0], color=colors[3], lw=2)
]
ax_noise.legend(handles=legend_lines,
                labels=['30 $\mu$V', '20 $\mu$V', '10 $\mu$V', '5  $\mu$V'],
                fontsize=12,
                loc='upper right')

y_lim = ax_noise.get_ylim()
x_lim = ax_noise.get_xlim()

ts_lim = (x_lim[1] - x_lim[0]) // 3
ax_noise.plot([x_lim[0], x_lim[0] + 0.2 * ts_lim], [
    np.min(y_lim) + 0.12 * np.abs(np.min(y_lim)),
示例#26
0
    def draw(self,
             directed=True,
             layout="spring",
             node_label_attr=None,
             show_node_labels=True,
             edge_label_attr=None,
             show_edge_labels=True,
             node_size=1600,
             node_color='blue',
             node_alpha=0.3,
             node_text_size=12,
             edge_color='blue',
             edge_alpha=0.3,
             edge_tickness=1,
             edge_text_pos=0.3,
             text_font='sans-serif',
             ax=None):
        """Plot of a NetworkX multi-graph instance

        :param directed: boolean, optional (default=`True`).
            Whether to return a directed graph or not.
        :param layout: string, optional (default=`"spring"`).
            Layout to apply. Any of the possible NetworkX layouts will work:
            ``'circular_layout'``, ``'random_layout'``, ``'shell_layout'``,
            ``'spring_layout'``, ``'spectral_layout'``,
            or ``'fruchterman_reingold_layout'``.
        :param node_label_attr: string, optional (default=`None`).
            Attribute of the nodes that has to be used as the label.
        :param show_node_labels: boolean, optional (default=`True`).
            Whether to show or not the labels of the nodes.
        :param edge_label_attr: boolean, optional (default=`None`).
            Attribute of the edges that has to be used as the label.
        :param show_edge_labels: . optional (default=`True`).
            Whether to show or not the labels of the edges.
        :param node_size: integer, optional (default=`1600`).
            Desired size for nodes.
        :param node_color: color string, or array of floats, (default=`'blue'`)
            Node color. Can be a single color format string, or a sequence of
            colors with the same length as nodelist. If numeric values are
            specified they will be mapped to colors using the ``cmap`` and
            ``vmin``, ``vmax`` parameters. See ``matplotlib.scatter`` for more
            details.
        :param node_alpha: float, optional (default=`0.3`).
            Between 0 and 1 for transparency of nodes.
        :param node_text_size: integer, optional (default=`12`).
            Size of the node text.
        :param edge_color: color string, or array of floats (default=`'blue'`)
            Edge color. Can be a single color format string, or a sequence of
            colors with the same length as edgelist. If numeric values are
            specified they will be mapped to colors using the ``edge_cmap`` and
            ``edge_vmin``, ``edge_vmax`` parameters.
        :param edge_alpha: float, optional (default=`0.3`)
            Transparency for thee edges.
        :param edge_tickness: float or integer, optional (default=`1`).
            Thickness of the lines drawn for the edges.
        :param edge_text_pos: . Default to optional (d0)=
        :param text_font: . Default to optional (default=`'sans-serif'`).
        :param ax: ``matplotlib.Figure``, optional (default=`None`).
            A ``matplotlib.Figure`` to use when rendering the graph. If `None`,
            a new object is created and returned.----

        :return: a ``matplotlib.Figure`` with the graph rendered.
        """
        graph = self.get_graph(directed=directed)
        pos = getattr(nx, "{}_layout".format(layout))(graph)
        node_labels = {}
        edge_labels = {}
        node_colors = set()
        if show_node_labels:
            for node, props in graph.nodes(data=True):
                labels = props.pop('labels', [])
                for label in labels:
                    node_colors.add(label)
                if node_label_attr is None:
                    node_labels[node] = "$:{}$\n{}".format(
                        ":".join(labels),
                        next(iter(props.values())) if props else "",
                    )
                else:
                    props_list = [
                        "{}: {}".format(k, v) for k, v in props.items()
                    ]
                    node_labels[node] = "$:{}$\n{}".format(
                        ":".join(labels), "\n".join(props_list))
        node_color = []
        node_colors = list(node_colors)
        legend_colors = []
        colors = list(plt.matplotlib.colors.ColorConverter().cache.items())[2:]
        for _, color_rgb in colors[:len(node_colors)]:
            node_color.append(color_rgb)
            legend_colors.append(color_rgb)
        if show_edge_labels:
            for start, end, props in graph.edges(data=True):
                if edge_label_attr is None:
                    edge_label = props.get("type", '')
                else:
                    edge_label = props.get(edge_label_attr, '')
                edge_labels[(start, end)] = edge_label
        if not ax:
            fig = plt.figure()
            ax = fig.add_subplot(111)
        nodes = nx.draw_networkx_nodes(graph,
                                       pos=pos,
                                       node_color=node_color,
                                       node_size=node_size,
                                       alpha=node_alpha,
                                       ax=ax)
        nx.draw_networkx_labels(graph,
                                pos=pos,
                                labels=node_labels,
                                font_size=node_text_size,
                                font_family=text_font,
                                ax=ax)
        nx.draw_networkx_edges(graph,
                               pos=pos,
                               width=edge_tickness,
                               alpha=edge_alpha,
                               edge_color=edge_color,
                               ax=ax)
        nx.draw_networkx_edge_labels(graph,
                                     pos=pos,
                                     edge_labels=edge_labels,
                                     ax=ax)
        ax.legend([
            plt.Line2D([0], [0],
                       linestyle="none",
                       marker="o",
                       alpha=node_alpha,
                       markersize=10,
                       markerfacecolor=color) for color in legend_colors
        ],
                  node_colors,
                  loc=(-0.25, 1),
                  numpoints=1,
                  frameon=False)
        ax.set_axis_off()
        return graph, ax, nodes
示例#27
0
文件: plotter.py 项目: EcustBoy/SCR
    def save(self):
        cmap = plt.cm.get_cmap('hsv', 10)

        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)

        x_offset = 0.11
        y_offset = 0.11

        robot_color = 'yellow'

        human_positions = [[state.position for state in states[1]]
                           for states in self.point_list]
        human_num = len(human_positions[0])
        human_radii = [state.radius for state in self.point_list[0][1]]

        robot_positions = [states[0].position for states in self.point_list]
        robot_radius = self.point_list[0][0].radius

        episode_length = len(self.point_list)
        time_step = .25

        for k in range(episode_length):
            if k % 4 == 0 or k == episode_length - 1:
                robot = plt.Circle(robot_positions[k],
                                   robot_radius,
                                   fill=True,
                                   color=robot_color)
                humans = [
                    plt.Circle(human_positions[k][i],
                               human_radii[i],
                               fill=False,
                               color=cmap(i))
                    for i in range(len(human_positions[0]))
                ]
                ax.add_artist(robot)
                for human in humans:
                    ax.add_artist(human)
            # add time annotation
            global_time = k * time_step
            if global_time % 4 == 0 or k == episode_length - 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(human_num + 1)
                ]
                for time in times:
                    ax.add_artist(time)
            if k != 0:
                nav_direction = plt.Line2D(
                    (robot_positions[k - 1][0], robot_positions[k][0]),
                    (robot_positions[k - 1][1], robot_positions[k][1]),
                    color=robot_color,
                    ls='solid')
                human_directions = [
                    plt.Line2D((human_positions[k - 1][i][0],
                                human_positions[k][i][0]),
                               (human_positions[k - 1][i][1],
                                human_positions[k][i][1]),
                               color=cmap(i),
                               ls='solid') for i in range(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.savefig(self.file)
        plt.close(fig)