Exemple #1
0
def make_legend_arrow_wrapper(theta, label2theta_dict=None):
    if isinstance(theta, str):
        if theta == 'lr':
            return HandlerPatch(patch_func=make_legend_arrow_lr)
        elif theta == 'rl':
            return HandlerPatch(patch_func=make_legend_arrow_rl)
        else:
            raise ValueError

    def make_legend_arrow(legend, orig_handle, xdescent, ydescent, width,
                          height, fontsize):
        if label2theta_dict is not None and orig_handle.get_label(
        ) in label2theta_dict:
            theta2 = label2theta_dict[orig_handle.get_label()]
        else:
            theta2 = theta

        dx = np.cos(theta2) * height
        dy = np.sin(theta2) * height
        return patches.FancyArrow(x=width / 2 - dx,
                                  y=height / 2 - dy,
                                  dx=2 * dx,
                                  dy=2 * dy,
                                  length_includes_head=True,
                                  head_width=height / 2)

    return HandlerPatch(patch_func=make_legend_arrow)
Exemple #2
0
def make_handler_map_to_scale_circles_as_in(ax, dont_resize_actively=False):
    fig = ax.get_figure()

    def axes2pt():
        return np.diff(ax.transData.transform([(0, 0), (1, 1)]), axis=0)[0] * (
            300.0 / fig.dpi
        )

    ellipses = []
    if not dont_resize_actively:

        def update_width_height(event):
            dist = axes2pt()
            for e, radius in ellipses:
                e.width, e.height = 2.0 * radius * dist

        fig.canvas.mpl_connect("resize_event", update_width_height)
        ax.callbacks.connect("xlim_changed", update_width_height)
        ax.callbacks.connect("ylim_changed", update_width_height)

    def legend_circle_handler(
        legend, orig_handle, xdescent, ydescent, width, height, fontsize
    ):
        w, h = 2.0 * orig_handle.get_radius() * axes2pt()
        e = Ellipse(
            xy=(0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent),
            width=w,
            height=w,
        )
        ellipses.append((e, orig_handle.get_radius()))
        return e

    return {Circle: HandlerPatch(patch_func=legend_circle_handler)}
Exemple #3
0
    def add_arrow(label):
        # not sure why quiver key is not working
        # https://stackoverflow.com/a/22349717/859591
        from matplotlib.legend_handler import HandlerPatch
        import matplotlib.patches as mpatches

        def make_legend_arrow(legend, orig_handle, xdescent, ydescent, width,
                              height, fontsize):
            p = mpatches.FancyArrow(0,
                                    0.5 * height,
                                    width,
                                    0,
                                    length_includes_head=True,
                                    head_width=0.5 * height)
            return p

        arrow = plt.arrow(0, 0, 1, 1, color='k')
        handles, labels = ax.get_legend_handles_labels()

        labels = labels[:1] + [label] + labels[1:]
        handles = handles[:1] + [arrow] + handles[1:]
        plt.legend(handles,
                   labels,
                   handler_map={
                       mpatches.FancyArrow:
                       HandlerPatch(patch_func=make_legend_arrow),
                   },
                   loc=loc)
Exemple #4
0
def add_arrow_to_leg(ax, label):
    handles, labels = ax.get_legend_handles_labels()
    arrow = plt.arrow(0., 0., 0., 0., color='k')
    return ax.legend(handles + [arrow], labels + [label],
              handler_map={arrow: HandlerPatch(
                patch_func=make_legend_arrow)},
              loc='upper right')
Exemple #5
0
def animation_frame(i):
    #data = pd.read_csv("./dataset.csv")
    #subset_vehicle = data[['Vehicle_GPS_X', 'Vehicle_GPS_Y']]
    #subset_user = data[['User_GPS_X', 'User_GPS_Y']]

    #print(subset_vehicle)

    #circle_center_x = subset_vehicle.iloc[i-1].Vehicle_GPS_X
    #circle_center_y = subset_vehicle.iloc[i-1].Vehicle_GPS_Y

    ax = plt.subplot(111, aspect=1)

    x_vehicle = subset_vehicle.iloc[i].Vehicle_GPS_X
    y_vehicle = subset_vehicle.iloc[i].Vehicle_GPS_Y

    x_user = subset_user.iloc[i].User_GPS_X
    y_user = subset_user.iloc[i].User_GPS_Y

    plt.cla()

    vehicle_x, = ax.plot(x_vehicle, y_vehicle, "k+", mew=5, ms=5)
    vehicle_y, = ax.plot(x_vehicle, y_vehicle, "w+", mew=1, ms=1)

    user_x, = ax.plot(x_user, y_user, "k+", mew=3, ms=12)
    user_y, = ax.plot(x_user, y_user, "w+", mew=1, ms=10)

    ax.set_xlim([37.44, 37.46])
    ax.set_ylim([126.94, 126.96])

    c = mpatches.Circle((subset_vehicle.iloc[i].Vehicle_GPS_X,
                         subset_vehicle.iloc[i].Vehicle_GPS_Y),
                        0.0041,
                        fc="g",
                        ec="r",
                        lw=3)
    ax.add_patch(c)

    plt.tight_layout()

    def make_legend_circle(legend, orig_handle, xdescent, ydescent, width,
                           height, fontsize):
        p = mpatches.Circle(xy=(0.5 * width - 0.5 * xdescent,
                                0.5 * height - 0.5 * ydescent),
                            radius=5)

        return p

    plt.legend([c, (vehicle_x, vehicle_y), (user_x, user_y)],
               ["Alertion Boundary", "Vehicle", "User"],
               handler_map={
                   mpatches.Circle:
                   HandlerPatch(patch_func=make_legend_circle),
               })
    def _plot_main_scene(self, ax):
        step = self.i_step

        # config
        x_min = -50
        x_max = 10
        y_min = -5
        y_max = 10

        ax.clear()
        ax.title.set_text(
            f'Simulation Animation - time at {self.traj_t[step]:.3f} s')
        ax.set_xlabel('x position (m)')
        ax.set_ylabel('y position (m)')
        ax.axis('equal')
        ax.set_xlim(x_min, x_max)
        ax.set_ylim(y_min, y_max)
        ax.grid(linestyle='--', linewidth=0.5)

        # layout
        for key, cts in self.layout.items():
            if key == 'lane_line_solid':
                for ct in cts:
                    ax.plot(ct[0], ct[1], '-g')
            elif key == 'lane_line_dashed':
                for ct in cts:
                    ax.plot(ct[0], ct[1], '--g')
            else:
                raise Exception('undifeind layout type.')

        # vehicle
        # --- shape
        vertices, x, y, yaw, vel = self._get_veh_info()
        polygon = Polygon(vertices.swapaxes(0, 1), fill=True, color='y')
        ax.add_artist(polygon)
        # --- position
        circle = plt.Circle((x, y), 0.2, color='#f08102')
        ax.add_artist(circle)
        # --- orientation
        ar_vel_veh = ax.arrow(
            x,
            y,
            vel * np.cos(yaw),
            vel * np.sin(yaw),
            width=0.05,
            # length_includes_head=True,
            linestyle='-',
            color='#f08102',
            head_width=0.3,
            head_length=0.5)

        # pedestrian prediction
        pred = self.pred.pred_traj[step]
        if pred is None:
            ax.text(-10, y_min + 1, f'no prediction result', color='r')
        else:
            # plot prediction
            # print(pred)
            for i, p in enumerate(pred):
                circle = plt.Circle(
                    (p[0], p[1]),
                    p[4],
                    color=(1.0, 0.5 + 0.5 * i / len(pred), 1.0))
                # circle = plt.Circle((p[0], p[1]), p[4], color='g')
                ax.add_artist(circle)

        # pedestrian
        state_ped = self.ped.state_traj[step]
        circle = plt.Circle((state_ped[0], state_ped[1]),
                            self.ped.R,
                            color='r')
        ax.add_artist(circle)
        alpha_arrow = 0.3
        ar_vel_ped = ax.arrow(
            state_ped[0],
            state_ped[1],
            state_ped[2],
            state_ped[3],
            # length_includes_head=True,
            width=0.03,
            color='k',
            head_width=0.3,
            head_length=0.5,
            alpha=alpha_arrow)

        # pedestrian motion - social forces
        f_total = self.sfm.f_total_traj[step]
        fv = self.sfm.fv_traj[step]
        fd = self.sfm.fd_traj[step]
        state_sfm = self.sfm.state_traj[step]
        des = self.sfm.des_traj[step]
        gap = self.sfm.gap_traj[step]

        scale = 50
        ar1 = ax.arrow(
            state_ped[0],
            state_ped[1],
            (state_ped[0] + fv[0][0]) / scale,
            (state_ped[1] + fv[1][0]) / scale,
            # length_includes_head=True,
            width=0.03,
            color='c',
            head_width=0.3,
            head_length=0.5,
            alpha=alpha_arrow)
        ar2 = ax.arrow(
            state_ped[0],
            state_ped[1],
            (state_ped[0] + fd[0][0]) / scale,
            (state_ped[1] + fd[1][0]) / scale,
            # length_includes_head=True,
            width=0.03,
            color='m',
            head_width=0.3,
            head_length=0.5,
            alpha=alpha_arrow)
        ar3 = ax.arrow(
            state_ped[0],
            state_ped[1],
            (state_ped[0] + f_total[0][0]) / scale,
            (state_ped[1] + f_total[1][0]) / scale,
            # length_includes_head=True,
            width=0.03,
            color='b',
            head_width=0.3,
            head_length=0.5,
            alpha=alpha_arrow)

        ax.plot(des[0], des[1], 'xb', label='destination')
        ax.legend([ar_vel_veh, ar_vel_ped, ar1, ar2, ar3], [
            'vehicle velocity', 'pedestrian velocity', 'f_vehicle',
            'f_destination', 'f_total'
        ],
                  loc='upper center',
                  bbox_to_anchor=(0.78, -0.08),
                  shadow=True,
                  ncol=5,
                  handler_map={
                      mpatches.FancyArrow:
                      HandlerPatch(patch_func=make_legend_arrow),
                  })

        # text
        ax.text(x_min + 2, y_max - 1,
                f'vehicle speed = {vel * 2.237:.2f} MPH ({vel:.2f} m/s)')
        ax.text(x_min + 2, y_max - 2,
                f'vehicle control = {self.con.u_traj[step]:.2f} m/s^2')

        ax.text(-30, y_max - 1, f'pedestrian motion status: {state_sfm}')
        ax.text(
            -30, y_max - 2,
            f'gap acceptance = {self.sfm.thr_gap:.4f}; current gap = {gap:.4f} s; '
            f'pedestrian desired v = {self.sfm.vd:.4f} m/s')
        ax.text(
            -30, y_max - 3,
            f'f_total = [{f_total[0][0]:.4f},{f_total[1][0]:.4f}], '
            f'f_vehicle = [{fv[0][0]:.4f},{fv[1][0]:.4f}], '
            f'f_destination = [{fd[0][0]:.4f},{fd[1][0]:.4f}].')
    def graph_visualizer(self,
                         x0lim=np.pi,
                         x1lim=np.pi * 3.5,
                         figsize=8,
                         no_interconnect=False):
        edge_funnel = []
        edge_inter = []

        fig = plt.figure(figsize=(5, 5))
        #             fig = plt.figure(figsize=(figsize, figsize * x1lim / x0lim))
        plt.xlim(-x0lim, x0lim)
        plt.ylim(-x1lim, x1lim)
        plt.xlabel(r"$\theta$", fontsize=20)
        plt.ylabel(r"$\dot{\theta}$", fontsize=20)

        for index, vertex in enumerate(self.vertex_ls):
            curr_x, curr_y = vertex.position
            plt.scatter(curr_x, curr_y, facecolors='none', edgecolors='k')
            if vertex.next != None:
                edge_funnel.append((index, vertex.next))
            for neighbor_index in vertex.neighbor_vertex[1:]:
                edge_inter.append((index, neighbor_index))

        for e in tqdm(edge_funnel):
            if np.isclose(self.vertex_ls[e[1]].position,
                          self.vertex_ls[e[0]].position).all():
                continue
            plt.arrow(*self.vertex_ls[e[0]].position,
                      *(self.vertex_ls[e[1]].position -
                        self.vertex_ls[e[0]].position),
                      head_width=0.2,
                      head_length=0.4,
                      fc='r',
                      ec='b',
                      shape="left",
                      length_includes_head=True)

        if not no_interconnect:
            for e in tqdm(edge_inter):
                if np.isclose(self.vertex_ls[e[1]].position,
                              self.vertex_ls[e[0]].position).all():
                    continue
                plt.arrow(*self.vertex_ls[e[0]].position,
                          *(self.vertex_ls[e[1]].position -
                            self.vertex_ls[e[0]].position),
                          head_width=0.2,
                          head_length=0.4,
                          fc='r',
                          ec='g',
                          shape="left",
                          length_includes_head=True)
        # dummy
        scatter = plt.scatter(100,
                              100,
                              facecolors='none',
                              edgecolors='k',
                              label="Vertices")
        arrow1 = plt.arrow(100,
                           100,
                           0,
                           0,
                           head_width=0.2,
                           head_length=0.4,
                           fc='r',
                           ec='b',
                           shape="left",
                           length_includes_head=True,
                           label="Edges inside Funnels")
        if not no_interconnect:
            arrow2 = plt.arrow(100,
                               100,
                               0,
                               0,
                               head_width=0.2,
                               head_length=0.4,
                               fc='r',
                               ec='g',
                               shape="left",
                               length_includes_head=True,
                               label="Interconnective Edges")
            plt.legend([
                scatter,
                arrow1,
                arrow2,
            ], [
                'Vertices',
                'Edges inside Funnels',
                'Interconnective Edges',
            ],
                       handler_map={
                           mpatches.FancyArrow:
                           HandlerPatch(patch_func=make_legend_arrow),
                       },
                       loc="best")
        else:
            plt.legend([scatter, arrow1], ['Vertices', 'Edges inside Funnels'],
                       handler_map={
                           mpatches.FancyArrow:
                           HandlerPatch(patch_func=make_legend_arrow),
                       },
                       loc="best")
#         plt.legend(loc="best")

        plt.show()
        # if no_interconnect:
        #     figure_name = "graph_no_interconnect"
        # else:
        #     figure_name = "graph_w_interconnect"
        # plt.savefig("fig/{}.png".format(figure_name), dpi=300, bbox_inches='tight')


#     def funnel_visualizer_2d(self,):
#             fig = plt.figure(figsize=(5,5))
#             plt.xlim(-2*np.pi, 2*np.pi)
#             plt.ylim(-4*np.pi, 4*np.pi)
    def _plot_main_scene_small(self, ax, step, legend=False):
        # config
        x_min = -20
        x_max = 5
        y_min = -5
        y_max = 12

        ax.clear()
        # ax.title.set_text(f'Simulation Animation - time at {self.traj_t[step]:.3f} s')
        ax.set_xlabel('x position (m)')
        ax.set_ylabel('y position (m)')
        ax.axis('equal')
        ax.set_xlim(x_min, x_max)
        ax.set_ylim(y_min, y_max)
        ax.grid(linestyle='--', linewidth=0.5)

        # layout
        for key, cts in self.layout.items():
            if key == 'lane_line_solid':
                for ct in cts:
                    ax.plot(ct[0], ct[1], '-g')
            elif key == 'lane_line_dashed':
                for ct in cts:
                    ax.plot(ct[0], ct[1], '--g')
            else:
                raise Exception('undifeind layout type.')

        # vehicle
        # --- shape
        vertices, x, y, yaw, vel = self._get_veh_info(step=step)
        polygon = Polygon(vertices.swapaxes(0, 1), fill=True, color='y')
        ax.add_artist(polygon)
        # --- position
        circle = plt.Circle((x, y), 0.2, color='#f08102')
        ax.add_artist(circle)
        # --- orientation
        ar_vel_veh = ax.arrow(
            x,
            y,
            vel * np.cos(yaw),
            vel * np.sin(yaw),
            width=0.05,
            # length_includes_head=True,
            linestyle='-',
            color='#f08102',
            head_width=0.3,
            head_length=0.5)

        # pedestrian prediction
        pred = self.pred.pred_traj[step]
        if pred is None:
            ax.text(-10, y_min + 1, f'no prediction result', color='r')
        else:
            # plot prediction
            # print(pred)
            for i, p in enumerate(pred):
                circle = plt.Circle(
                    (p[0], p[1]),
                    p[4],
                    color=(1.0, 0.5 + 0.5 * i / len(pred), 1.0))
                # circle = plt.Circle((p[0], p[1]), p[4], color='g')
                ax.add_artist(circle)

        # pedestrian
        state_ped = self.ped.state_traj[step]
        circle = plt.Circle((state_ped[0], state_ped[1]),
                            self.ped.R,
                            color='r')
        ax.add_artist(circle)
        alpha_arrow = 0.3
        ar_vel_ped = ax.arrow(
            state_ped[0],
            state_ped[1],
            state_ped[2],
            state_ped[3],
            # length_includes_head=True,
            width=0.03,
            color='k',
            head_width=0.3,
            head_length=0.5,
            alpha=alpha_arrow)

        # pedestrian motion - social forces
        f_total = self.sfm.f_total_traj[step]
        fv = self.sfm.fv_traj[step]
        fd = self.sfm.fd_traj[step]
        state_sfm = self.sfm.state_traj[step]
        des = self.sfm.des_traj[step]
        gap = self.sfm.gap_traj[step]

        # scale = 20
        # ar1 = ax.arrow(
        #     state_ped[0], state_ped[1],
        #     (state_ped[0] + fv[0][0]) / scale, (state_ped[1] + fv[1][0]) / scale,
        #     # length_includes_head=True,
        #     width=0.03, color='c', head_width=0.3, head_length=0.5, alpha=alpha_arrow
        # )
        # ar2 = ax.arrow(
        #     state_ped[0], state_ped[1],
        #     (state_ped[0] + fd[0][0]) / scale, (state_ped[1] + fd[1][0]) / scale,
        #     # length_includes_head=True,
        #     width=0.03, color='m', head_width=0.3, head_length=0.5, alpha=alpha_arrow
        # )
        # ar3 = ax.arrow(
        #     state_ped[0], state_ped[1],
        #     (state_ped[0] + f_total[0][0]) / scale, (state_ped[1] + f_total[1][0]) / scale,
        #     # length_includes_head=True,
        #     width=0.03, color='b', head_width=0.3, head_length=0.5, alpha=alpha_arrow
        # )

        ax.plot(des[0], des[1], 'xb', label='destination')

        # text
        ax.text(x_min, y_max - 2, '$t=%.2fs$' % self.traj_t[step])
        ax.text(x_min, y_max - 3.5,
                '$v_{veh}=%.2fMPH(%.2fm/s)$' % (vel * 2.237, vel))
        ax.text(x_min, y_max - 5,
                '$u_{veh}=%.2fm/s^2$' % self.con.u_traj[step])
        # ax.text(x_min, y_max - 5, '$f_{total}=[%.2f,%.2f]$' % (f_total[0][0],f_total[1][0]))
        # ax.text(x_min, y_max - 6.6, '$f_{veh}=[%.2f,%.2f]$' % (fv[0][0], fv[1][0]))
        # ax.text(x_min, y_max - 8.1, '$f_{des}=[%.2f,%.2f]$' % (fd[0][0], fd[1][0]))

        ax.text(x_min, -1.5, f'pedestrian status: {state_sfm}')
        ax.text(
            x_min, -3, '$\\tau_{gap}=%.2fs,t_{gap}=%.2fs,v_0=%.2fm/s$' %
            (self.sfm.thr_gap, gap, self.sfm.vd))

        # ax.text(x_min, -4.5, '$f_{total}=[%.2f,%.2f],f_{veh}=[%.2f,%.2f],f_{des}=[%.2f,%.2f]$'
        #         % (f_total[0][0],f_total[1][0],fv[0][0],fv[1][0],fd[0][0],fd[1][0]) )

        # legend
        if legend:
            ax.legend(
                # [ar_vel_veh, ar_vel_ped, ar1, ar2, ar3],
                [ar_vel_veh, ar_vel_ped],
                [
                    'vehicle velocity', 'pedestrian velocity', 'f_vehicle',
                    'f_destination', 'f_total'
                ],
                loc='upper center',
                bbox_to_anchor=(-0.15, -0.22),
                shadow=True,
                ncol=5,
                handler_map={
                    mpatches.FancyArrow:
                    HandlerPatch(patch_func=make_legend_arrow),
                })
Exemple #9
0
def draw_lattice(config, Lx, Ly, boundary_left):
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()

    ax.set_xlim([-1, Lx])
    ax.set_ylim([-1, Ly])
    ax.axis('off')
    ax.set_title('$L_x =' + str(Lx) + ', L_y=' + str(Ly) + '$')

    # draw incoming arrows
    for iy in range(Ly):
        if boundary_left[iy] == 1:
            arrow_bound = plt.arrow(0 - 1,
                                    iy,
                                    0.9,
                                    0,
                                    head_width=0.08,
                                    length_includes_head=True,
                                    alpha=0.3,
                                    linestyle='dashed')
        else:
            arrow_bound = plt.arrow(0,
                                    iy,
                                    -0.9,
                                    0,
                                    linestyle='dashed',
                                    head_width=0.08,
                                    length_includes_head=True,
                                    alpha=0.3)
        ax.add_artist(arrow_bound)

    for ix in range(Lx):
        for iy in range(Ly):

            node_id = ix * Ly + iy
            circle = plt.Circle((ix, iy), 0.1, color='r')

            link_up_id = node_id * 2 + 1
            if config[link_up_id] == 1:
                arrow_up = plt.arrow(ix,
                                     iy,
                                     0,
                                     0.9,
                                     head_width=0.08,
                                     length_includes_head=True)
            else:
                arrow_up = plt.arrow(ix,
                                     iy + 1,
                                     0,
                                     -0.9,
                                     head_width=0.08,
                                     length_includes_head=True)

            link_right_id = node_id * 2

            if ix < Lx - 1:
                if config[link_right_id] == 1:
                    arrow_right = plt.arrow(ix + 0.1,
                                            iy,
                                            0.8,
                                            0,
                                            head_width=0.08,
                                            length_includes_head=True)
                else:
                    arrow_right = plt.arrow(ix + 1,
                                            iy,
                                            -0.9,
                                            0,
                                            head_width=0.08,
                                            length_includes_head=True)
            else:
                if config[link_right_id] == 1:
                    arrow_bound = plt.arrow(ix + 0.1,
                                            iy,
                                            0.9,
                                            0,
                                            alpha=0.3,
                                            linestyle='dashed',
                                            head_width=0.08,
                                            length_includes_head=True)
                else:
                    arrow_bound = plt.arrow(ix + 1,
                                            iy,
                                            -0.9,
                                            0,
                                            alpha=0.3,
                                            linestyle='dashed',
                                            head_width=0.08,
                                            length_includes_head=True)
                ax.add_artist(arrow_bound)
        # copy periodic links at iy = 0 from iy = Ly - 1
            if iy == 0:
                # copy link of the upper bound
                node_id = ix * Ly + Ly - 1
                link_up_id = node_id * 2 + 1
                if config[link_up_id] == 1:
                    arrow_down = plt.arrow(ix,
                                           iy - 1,
                                           0,
                                           0.9,
                                           alpha=0.3,
                                           linestyle='dashed',
                                           head_width=0.08,
                                           length_includes_head=True)
                else:
                    arrow_down = plt.arrow(ix,
                                           iy - 0.1,
                                           0,
                                           -0.9,
                                           alpha=0.3,
                                           linestyle='dashed',
                                           head_width=0.08,
                                           length_includes_head=True)
                ax.add_artist(arrow_down)

            if ix == Lx - 1:
                arrow_right.set_alpha = 0.3

            ax.add_artist(arrow_up)
            ax.add_artist(arrow_right)
            ax.add_artist(circle)

    plt.legend([arrow_bound, arrow_right], ['boundary link', 'active link'],
               bbox_to_anchor=(1.15, 0.2),
               handler_map={
                   mpatches.FancyArrow:
                   HandlerPatch(patch_func=make_legend_arrow),
               })
Exemple #10
0
def plotcorr(x,
             headers=None,
             figure=None,
             axis=None,
             legend=False,
             bbox_anchor=None,
             non_zero=False):
    '''
    Plot a correlation matrix, much like the 'plotcorr' command in R.

    X must be a two dimensional array indexed by [variable, sample]
    so you typically have arrays of shape [15, 500] or so.

    If no figure or axis is given, one is created and scaled by the number of variables

    If specified, non_zero will only compare cases where both variables
    are non-zero.

    Returns the figure
    '''
    colors = [
        "#A50F15", "#DE2D26", "#FB6A4A", "#FCAE91", "#FEE5D9", "white",
        "#EFF3FF", "#BDD7E7", "#6BAED6", "#3182BD", "#08519C"
    ]

    if bbox_anchor is None:
        bbox_anchor = (1, 0, 1, 1)

    if figure is None and axis is None:
        # Scale by size of array
        dim = 6 + len(x) / 4
        figure = plt.figure(figsize=(dim, dim))
    if axis is None:
        axis = plt.gca()
    ax = axis
    ax.set_axis_bgcolor('white')
    ax.grid('off')
    lim = len(x)
    for i in range(len(x)):
        for j in range(len(x)):
            # all of them
            valid_rows = x[i] == x[i]
            if non_zero:
                # non-zero indices
                inz = x[i] != 0
                jnz = x[j] != 0
                valid_rows = inz * jnz
            # Calculate correlation (p is actually rho)
            p = pearsonr(x[i][valid_rows], x[j][valid_rows])[0]
            # Pick a color
            c = p
            c += 1
            c *= (len(colors) - 1) / 2
            c = int(round(c))
            c = colors[c]

            # Angle
            if p >= 0:
                # Linear correlation
                angle = -45
            else:
                # Anti linear correlation
                angle = 45

            e = Ellipse(xy=(i, j), width=1, height=(1 - abs(p)), angle=angle)
            ax.add_artist(e)
            e.set_clip_box(ax.bbox)
            #e.set_alpha(rand())
            e.set_facecolor(c)

    ax.set_ylim((-0.5, len(x) - 0.5))
    ax.set_xlim((-0.5, len(x) - 0.5))
    ax.invert_yaxis()
    ax.set_yticks(np.arange(len(x)))
    ax.set_xticks(np.arange(len(x)))

    if (headers is not None and len(headers) == len(x)):
        if mpl.rcParams['text.usetex']:
            #ax.set_yticklabels(wraparray(headers, '\huge{', '}'))
            ax.set_yticklabels(wraparray(headers, r'\normalsize{', '}'))
            ax.set_xticklabels(wraparray(headers, r'\normalsize{', '}'))
        else:
            #xx-large
            ax.set_yticklabels(headers, fontsize='medium')
            ax.set_xticklabels(headers, fontsize='medium')

    # Move bottom to top
    for tick in ax.xaxis.iter_ticks():
        tick[0].label2On = True
        tick[0].label1On = False
        tick[0].label2.set_rotation('vertical')
        tick[0].label2.set_size('medium')

    if not legend:
        return figure

    # Explanatory legend
    labels = []
    artists = []
    centers = np.linspace(-1, 1, len(colors))
    diff = (centers[1] - centers[0]) / 2
    for i, c in enumerate(colors):
        #if i != 0 and i != len(colors)/2 and i % 2 != 0:
        #    continue
        l, r = centers[i] - diff, centers[i] + diff
        if i == 0:
            # No left edge
            l = centers[i]
        elif i == len(colors) - 1:
            # No right edge
            r = centers[i]
        labels.append(r"${:.1f} < p < {:.1f}$".format(l, r))
        if mpl.rcParams['text.usetex']:
            labels[-1] = r"\small{" + r"${:.1f} < \rho < {:.1f}$".format(
                l, r) + "}"

        # Angle
        if centers[i] <= 0:
            angle = -45
        else:
            angle = 45
        e = Ellipse(xy=(0, 0),
                    width=1,
                    height=(1 - abs(centers[i])),
                    angle=angle)
        e.set_facecolor(c)
        artists.append(e)

    from matplotlib.legend_handler import HandlerPatch

    def make_ellipse(legend, orig_handle, xdescent, ydescent, width, height,
                     fontsize):
        #size = height+ydescent
        size = width + xdescent
        p = Ellipse(xy=(0.5 * width - 0.5 * xdescent,
                        0.5 * height - 0.5 * ydescent),
                    width=size * orig_handle.width,
                    height=size * orig_handle.height,
                    angle=orig_handle.angle)
        return p

    title = 'p = Pearson correlation'
    fontsize = 'medium'
    if mpl.rcParams['text.usetex']:
        title = r'\small{$\rho$ = Pearson correlation}'
        fontsize = None

    leg = ax.legend(
        artists,
        labels,
        handler_map={Ellipse: HandlerPatch(patch_func=make_ellipse)},
        labelspacing=1.3,
        fontsize=fontsize,
        loc='upper left',
        title=title,
        bbox_to_anchor=bbox_anchor)
    leg.legendPatch.set_facecolor('white')

    return figure
Exemple #11
0
def plot_directions(projection, labels, x_lines, lines, config, save=True):
    """
    Create scatter plot that project into a 2D plot the direction vector

    The direction between path of dots are correct, therefore two dots that looks to have 90 degree difference between
    them has in the multispace also a difference of 90 degree

    In contrast, the distance between the center and the dots are correct but two dots close to each other doesn't mean
    that they are in the real multi dimensional space. One should think of it a bit as the radius, therefore a patch of
    dots may be close simply because their distance are somehow on a sphere

    :param projection:
    :param labels:
    :param x_lines:
    :param lines:
    :param config:
    :param save:
    :return:
    """
    # plot
    fig, axs = plt.subplots(1,
                            projection.shape[0] - 1,
                            figsize=(5 * (projection.shape[0] - 1), 5),
                            sharey=True,
                            sharex=True)
    fig.suptitle(
        "Projection of difference vector preserving 2-norm and scalar product")
    for n_plot, ax in enumerate(axs):
        category = n_plot + 1
        ax.set_title(["Neutral", "Expression 1", "Expression 2"][category])
        point_reference = ax.plot(0, 0, 'kx', label="reference vector")
        arrow_tuning = ax.arrow(0,
                                0,
                                1,
                                0,
                                label="tuning vector",
                                color="black",
                                head_width=0.05,
                                length_includes_head=True)
        #an_tuning = ax.annotate('', xy=(1, 0), xytext=(0, 0), arrowprops={'arrowstyle': '->'}, va='center')
        scatter = ax.scatter(projection[category, :, 0],
                             projection[category, :, 1],
                             s=1,
                             c=labels)

        # set axis limits
        ax.set_ylim(ymin=-0.02, ymax=ax.get_ylim()[1] * 1.2)
        x_max = max(max(np.abs(ax.get_xlim())), 1)
        ax.set_xlim(xmin=-x_max, xmax=x_max)

        #plot lines of constant activation
        line_activation = ax.plot(x_lines, lines, color="k", linewidth=0.5)
    # legend
    handles_scatter, labels_scatter = scatter.legend_elements()
    fig.legend([point_reference[0], arrow_tuning] + handles_scatter +
               [line_activation[0]], [
                   "reference vector", "tuning vector", "Neutral",
                   "Expression 1", "Expression 2", "constant activation"
               ],
               handler_map={
                   mpatches.FancyArrow:
                   HandlerPatch(patch_func=make_legend_arrow)
               },
               loc="upper right",
               borderaxespad=0.1)

    if save:
        plt.savefig(
            os.path.join("models/saved", config['config_name'],
                         "_direction_scatter.png"))
Exemple #12
0
    def draw_requirements_graph(self, ax):
        """Draw the requirement graph on a given Axes.

        Args:
            ax: Axes to draw on.

        Return:
            The Axes with requirements_graph drawn on it.

        """
        graph = self.get_requirements_graph()
        compute_levels(graph)
        nodes_by_level = graph.graph["nodes_by_level"]
        pos = leveled_layout_energy(graph)
        compute_edges_color(graph)

        dashed_edges = [
            (u, v)
            for u, v, style in graph.edges(data="linestyle", default=None)
            if style == "dashed"
        ]

        # Dashed edges
        nx.draw_networkx_edges(
            graph,
            pos,
            edgelist=dashed_edges,
            ax=ax,
            arrowsize=40,
            arrowstyle="->",
            style=(0, (8, 4)),
            edge_color=[graph.edges[u, v]["color"] for u, v in dashed_edges],
        )

        plain_edges = [
            (u, v)
            for u, v, style in graph.edges(data="linestyle", default=None)
            if style is None
        ]

        # Plain edges
        nx.draw_networkx_edges(
            graph,
            pos,
            edgelist=plain_edges,
            ax=ax,
            arrowsize=20,
            arrowstyle="->",
            edge_color=[graph.edges[u, v]["color"] for u, v in plain_edges],
        )

        draw_networkx_nodes_images(graph, pos, ax=ax, img_zoom=0.3)

        # nx.draw_networkx_labels(
        #     graph, pos,
        #     ax=ax,
        #     font_color='black',
        #     font_size=6,
        #     labels=dict(graph.nodes(data='label'))
        # )

        # Create the legend patches
        legend_patches = [
            mpatches.Patch(facecolor="none", edgecolor="cyan", label="Tool"),
            mpatches.Patch(facecolor="none",
                           edgecolor="green",
                           label="Item (foundable)"),
            mpatches.Patch(facecolor="none", edgecolor="blue", label="Item"),
        ]
        legend_arrows = [
            mpatches.FancyArrow(0,
                                0,
                                1,
                                0,
                                facecolor="cyan",
                                edgecolor="none",
                                label="Tool requirement"),
            mpatches.FancyArrow(0,
                                0,
                                1,
                                0,
                                facecolor="red",
                                edgecolor="none",
                                label="Craft"),
        ]

        # Add zone_property legend only if there is any
        is_prop = [
            node_type == "zone_property"
            for _, node_type in graph.nodes(data="type")
        ]
        if any(is_prop):
            prop_legend = mpatches.Patch(facecolor="none",
                                         edgecolor="orange",
                                         label="Zone property")
            legend_patches.append(prop_legend)

        # Add drop legend only if any edge is a drop
        is_drop = [
            edge_type == "drop" for _, _, edge_type in graph.edges(data="type")
        ]
        if any(is_drop):
            drop_legend = mpatches.FancyArrow(0,
                                              0,
                                              1,
                                              0,
                                              facecolor="green",
                                              edgecolor="none",
                                              label="Drop")
            legend_arrows.append(drop_legend)

        # Draw the legend
        ax.legend(
            handles=legend_patches + legend_arrows,
            handler_map={
                # Patch arrows with fancy arrows in legend
                mpatches.FancyArrow:
                HandlerPatch(patch_func=lambda width, height, **kwargs:
                             mpatches.FancyArrow(
                                 0,
                                 0.5 * height,
                                 width,
                                 0,
                                 width=0.2 * height,
                                 length_includes_head=True,
                                 head_width=height,
                                 overhang=0.5,
                             )),
            },
        )

        # Add Hierarchies numbers
        for level in nodes_by_level:
            level_poses = np.array(
                [pos[node] for node in nodes_by_level[level]])
            mean_x = np.mean(level_poses[:, 0])
            if level == 0:
                ax.text(mean_x - 1, -0.07, "Depth", ha="left", va="center")
            ax.text(mean_x, -0.07, str(level), ha="center", va="center")
        return ax
import matplotlib.pyplot as plt
import numpy as np

ax = plt.subplot(111, aspect=1)
x, y = np.random.randn(2, 20)
#[1.1, 2, 2.8], [1.1, 2, 1.8]
l1, = ax.plot(x,y, "k+", mew=3, ms=12)
l2, = ax.plot(x,y, "w+", mew=1, ms=10)

import matplotlib.patches as mpatches
c = mpatches.Circle((0, 0), 1, fc="g", ec="r", lw=3)
ax.add_patch(c)



from matplotlib.legend_handler import HandlerPatch

def make_legend_ellipse(legend, orig_handle,
                        xdescent, ydescent,
                        width, height, fontsize):
    p = mpatches.Ellipse(xy=(0.5*width-0.5*xdescent, 0.5*height-0.5*ydescent),
                         width = width+xdescent, height=(height+ydescent))

    return p

plt.legend([c, (l1, l2)], ["Label 1", "Label 2"],
           handler_map={mpatches.Circle:HandlerPatch(patch_func=make_legend_ellipse),
                        })

plt.show()
latlon = pd.read_csv('2014KALMAEGI.TC', usecols=['Time', 'Latitude', 'Longitude'])
lon = np.array(latlon['Longitude'])
lat = np.array(latlon['Latitude'])
plt.plot(lon[:-5], lat[:-5], linestyle='-', linewidth= 1.5,
         zorder=2, transform=ccrs.PlateCarree())
Arrow2 = plt.arrow(lon[-6], lat[-6], -(lon[-6]-lon[-5]), -(lat[-6]-lat[-5]),
                  head_width=0.2, head_length=0.35, edgecolor=colors[2], linewidth =1.52,
                  facecolor=colors[2], zorder=3, transform=ccrs.PlateCarree())
# color boundds map for time stamp
#colors = np.arange(len(lon))
#norm = matplotlib.colors.BoundaryNorm(colors, 256)
#plt.scatter(lon, lat, c=colors, cmap='jet', norm=norm,
#            zorder=3, transform=ccrs.PlateCarree())


# color boundds map for time stamp
#colors = np.arange(len(lon))
#norm = matplotlib.colors.BoundaryNorm(colors, 256)
#plt.scatter(lon, lat, c=colors, cmap='jet', norm=norm,
#            zorder=3, transform=ccrs.PlateCarree())
# legends
plt.legend([Arrow0,Arrow1,Arrow2],\
            ['HAGIBIS','RAMMASUN','KALMAEGI',],\
            handler_map ={mpathes.FancyArrow : HandlerPatch(patch_func=make_legend_arrow)},\
            shadow = None, facecolor = 'white', edgecolor = 'black', framealpha = 1)

plt.savefig('Trajectory.svg')
plt.show()
plt.close(fig)
plt.close('all')
# p9 = ax.plot([], [], color='tab:green', linewidth=0.5)
# p10 = ax.fill([], [], color='tab:green', alpha=0.45)
p0 = ax.errorbar([-3], [0], [2], fmt='o',
            color='black', capsize=1.2,ms=2.5,elinewidth=0.6,mew=0.6)

# ax.legend()

def make_legend_polygon(legend, orig_handle,
                      xdescent, ydescent,
                      width, height, fontsize):
    a=2*height
    p = mpatches.Polygon(np.array([[0,-a/2],[width,-a/2],[width,height+a/2],[0,height+a/2],[0,-a/2]]))
    return p


hm = {p0: HandlerErrorbar(xerr_size=0.9), p4[0]: HandlerPatch(patch_func=make_legend_polygon), p2[0]: HandlerPatch(patch_func=make_legend_polygon), p6[0]: HandlerPatch(patch_func=make_legend_polygon),p8[0]: HandlerPatch(patch_func=make_legend_polygon)}
l=ax.legend([(p3[0],p4[0]),(p5[0],p6[0]),(p7[0], p8[0]),(p1[0], p2[0]),p0], ['Gardner et al.'+'$^{5}$'+ ' (2003-2009):\ngravi., in-situ, elev. change','Wouters et al.'+'$^{19}$'+' (2002-2016):\ngravi.','Ciracì et al.'+'$^{20}$'+' (2002-2019):\ngravi.','Zemp et al.'+'$^{21}$'+' (2006-2015):\nin-situ, elev. change','This study\n(corresp. period):\nelev. change'],ncol=3,
          handlelength=0.75,framealpha=0.8,loc='upper right',labelspacing=0.25,handler_map=hm,borderpad=0.4)
# ax.yaxis.grid(True,linestyle='--')
ax.tick_params(width=0.35,length=2.5)
l.get_frame().set_linewidth(0.5)

reg_dir = '/home/atom/ongoing/work_worldwide/vol/final'
list_fn_reg_multann = [os.path.join(reg_dir,'dh_'+str(i).zfill(2)+'_rgi60_int_base_reg_subperiods.csv') for i in np.arange(1,20)]
df_all = pd.DataFrame()
for fn_reg_multann in list_fn_reg_multann:
    df_all= df_all.append(pd.read_csv(fn_reg_multann))

tlims = [np.datetime64('20'+str(i).zfill(2)+'-01-01') for i in range(21)]

list_df_glob = []
Exemple #16
0
def main(args):
    # Parameters for toy data and experiments
    plt.figure(figsize=(6.4, 3.4))
    rng_seed = 42
    np.random.seed(rng_seed)

    wstar = torch.tensor([[0.973, 1.144]], dtype=torch.float)
    xs = torch.tensor(np.random.randn(50, 2), dtype=torch.float)
    labels = torch.mm(xs, wstar.T)

    p = torch.tensor(np.random.uniform(0.05, 1.0, xs.shape[0]),
                     dtype=torch.float)
    ips = 1.0 / p
    n_iters = 50
    plot_every = n_iters // 10
    arrow_width = 0.012
    legends = {}

    # The loss function we want to optimize
    def loss_fn(out, y, mult):
        l2loss = (out - y)**2.0
        logl2loss = torch.log(1.0 + (out - y)**2.0)
        return torch.mean(mult * l2loss)

    # IPS-weighted approach
    for color_index, lr in enumerate([0.01, 0.02, 0.03, 0.05,
                                      0.1]):  # 0.01, 0.03, 0.05, 0.1, 0.3
        color = "C%d" % (color_index + 2) if color_index > 0 else "C1"
        model = torch.nn.Linear(2, 1)
        optimizer = torch.optim.SGD(model.parameters(), lr=lr)
        optimizer = SWA(optimizer, swa_start=0, swa_freq=1, swa_lr=lr)
        with torch.no_grad():
            model.bias.zero_()
            model.weight.zero_()
        old_weights = np.copy(model.weight.data.numpy())
        np.random.seed(rng_seed + color_index + 1)
        for t in range(n_iters):
            i = np.random.randint(xs.shape[0])
            x = xs[i, :]
            y = labels[i]
            optimizer.zero_grad()
            o = model(x)
            l = loss_fn(o, y, ips[i])
            l.backward()
            optimizer.step()
            if t % plot_every == 0:
                optimizer.swap_swa_sgd()
                x, y = model.weight.data.numpy()[0]
                optimizer.swap_swa_sgd()
                ox, oy = old_weights[0]
                label = f"IPS-SGD ($\\eta={lr}$)"
                arr = plt.arrow(ox,
                                oy,
                                x - ox,
                                y - oy,
                                width=arrow_width,
                                length_includes_head=True,
                                color=color,
                                label=label)
                optimizer.swap_swa_sgd()
                old_weights = np.copy(model.weight.data.numpy())
                optimizer.swap_swa_sgd()
                legends[label] = arr

    # Sample based approach
    for lr in [10.0]:
        # lr = 3.0 # 1.0
        model = torch.nn.Linear(2, 1)
        optimizer = torch.optim.SGD(model.parameters(), lr=lr)
        optimizer = SWA(optimizer, swa_start=0, swa_freq=1, swa_lr=lr)
        with torch.no_grad():
            model.bias.zero_()
            model.weight.zero_()
        old_weights = np.copy(model.weight.data.numpy())
        sample_probs = np.array(ips / torch.sum(ips))
        Mbar = float(np.mean(sample_probs))
        np.random.seed(rng_seed - 1)
        for t in range(n_iters):
            i = np.argwhere(np.random.multinomial(1, sample_probs) == 1.0)[0,
                                                                           0]
            x = xs[i, :]
            y = labels[i]
            optimizer.zero_grad()
            o = model(x)
            l = loss_fn(o, y, Mbar)
            l.backward()
            optimizer.step()
            if t % plot_every == 0:
                optimizer.swap_swa_sgd()
                x, y = model.weight.data.numpy()[0]
                optimizer.swap_swa_sgd()
                ox, oy = old_weights[0]
                label = f"\\textsc{{CounterSample}} ($\\eta={lr}$)"
                arr = plt.arrow(ox,
                                oy,
                                x - ox,
                                y - oy,
                                width=arrow_width,
                                length_includes_head=True,
                                color="C2",
                                label=label)

                optimizer.swap_swa_sgd()
                old_weights = np.copy(model.weight.data.numpy())
                optimizer.swap_swa_sgd()
                legends[label] = arr

    # True IPS-weighted loss over all datapoints, used for plotting contour
    def f(x1, x2):
        w = torch.tensor([[x1], [x2]], dtype=torch.float)
        o = torch.mm(xs, w)
        return float(loss_fn(o, torch.mm(xs, wstar.reshape((2, 1))), ips))

    # Compute all useful combinations of weights and compute true loss for each one
    # This will be used to compute a contour plot
    true_x1 = np.linspace(float(wstar[0, 0]) - 1.5,
                          float(wstar[0, 0]) + 0.8)  # - 1.5 / + 1.0
    true_x2 = np.linspace(float(wstar[0, 1]) - 1.5,
                          float(wstar[0, 1]) + 1.2)  # - 1.5 / + 1.0
    true_x1, true_x2 = np.meshgrid(true_x1, true_x2)
    true_y = np.array(
        [[f(true_x1[i1, i2], true_x2[i1, i2]) for i2 in range(len(true_x2))]
         for i1 in range(len(true_x1))])

    # Contour plot with optimum
    plt.plot(wstar[0, 0], wstar[0, 1], marker='o', markersize=3, color="black")
    plt.contour(true_x1, true_x2, true_y, 10, colors="black", alpha=0.35)

    # Generate legends from arrows and make figure
    def make_legend_arrow(legend, orig_handle, xdescent, ydescent, width,
                          height, fontsize):
        p = mpatches.FancyArrow(0,
                                0.5 * height,
                                width,
                                0,
                                length_includes_head=True,
                                head_width=0.75 * height)
        return p

    def sort_op(key):
        if "CounterSample" in key:
            return ""
        else:
            return key

    labels = [key for key in sorted(legends.keys(), key=sort_op)]
    arrows = [legends[key] for key in sorted(legends.keys(), key=sort_op)]
    plt.legend(arrows,
               labels,
               ncol=2,
               loc='upper center',
               framealpha=0.95,
               handler_map={
                   mpatches.FancyArrow:
                   HandlerPatch(patch_func=make_legend_arrow)
               },
               bbox_to_anchor=(0.5, 1.0 + 0.03))
    plt.xlabel("$w_1$")
    plt.ylabel("$w_2$")
    plt.tight_layout()
    plt.savefig(args.out, format=args.format)
Exemple #17
0
def set_legend(obj, handle, label, props={}, inds=-1, **kwargs):
    def make_legend_arrow(legend, orig_handle, xdescent, ydescent, width,
                          height, fontsize):
        return matplotlib.patches.FancyArrow(0,
                                             0.5 * height,
                                             width,
                                             0,
                                             length_includes_head=True,
                                             head_width=0.5 * height)

    def make_legend_rectangle(legend, orig_handle, xdescent, ydescent, width,
                              height, fontsize):
        return matplotlib.patches.FancyArrow(0,
                                             0.5 * height,
                                             width,
                                             0,
                                             length_includes_head=True,
                                             head_width=0.25 * height)

    for ax in plt.gcf().axes:
        h, l = [], []
        hi, li = ax.get_legend_handles_labels()
        h.extend(hi)
        l.extend(li)
        handles, texts = ax.get_legend().legendHandles, ax.get_legend().texts
        if not ([] in handles or [] in texts):
            h.extend(handles)
            l.extend([t.get_text() for t in texts])

    if label not in l:
        h.append(handle)
        l.append(label)

    h = [
        hi[1]
        for hi in sorted(enumerate(h), key=lambda x: l[x[0]], reverse=True)
    ]
    l = [
        li[1]
        for li in sorted(enumerate(l), key=lambda x: l[x[0]], reverse=True)
    ]

    # handles_labels = sort_unhashable([a.get_legend_handles_labels()
    # 									for a in plt.gcf().axes],
    # 								inds=inds,key=lambda i: i[-1])
    try:
        obj.get_legend().remove()
    except:
        pass

    if h != [] and l != [] and props_plotting.get('legend') is not None:
        obj.legend(h,
                   l,
                   handler_map={
                       matplotlib.patches.FancyArrowPatch:
                       HandlerPatch(patch_func=make_legend_arrow),
                       matplotlib.patches.FancyArrow:
                       HandlerPatch(patch_func=make_legend_arrow),
                       matplotlib.patches.Rectangle:
                       HandlerPatch(patch_func=make_legend_rectangle)
                   },
                   **props_plotting.get('legend', {}))

    return
Exemple #18
0
    def plot(self,
             plot_spirals=True,
             plot_sun_body_line=False,
             show_earth_centered_coord=True,
             outfile=''):
        """
        Make a polar plot showing the Sun in the center (view from North) and the positions of the selected bodies

        Parameters
        ----------
        plot_spirals: bool
                    if True, the magnetic field lines connecting the bodies with the Sun are plotted
        plot_sun_body_line: bool
                    if True, straight lines connecting the bodies with the Sun are plotted
        show_earth_centered_coord: bool
                    if True, additional longitudinal tickmarks are shown with Earth at longitude 0
        outfile: string
                if provided, the plot is saved with outfile as filename
        """
        import pylab as pl
        AU = const.au / 1000  # km

        fig, ax = plt.subplots(subplot_kw=dict(projection='polar'),
                               figsize=(12, 8))
        self.ax = ax

        r = np.arange(0.007, self.max_dist + 0.3, 0.001)
        omega = np.radians(360. /
                           (25.38 * 24 * 60 *
                            60))  # solar rot-angle in rad/sec, sidereal period

        for i, body_id in enumerate(self.body_dict):
            body_lab = self.body_dict[body_id][1]
            body_color = self.body_dict[body_id][2]
            body_vsw = self.body_dict[body_id][4]
            body_pos = self.body_dict[body_id][3]

            pos = body_pos
            dist_body = pos.radius.value
            body_long = pos.lon.value

            E_long = self.pos_E.lon.value
            dist_e = self.pos_E.radius.value

            # plot body positions
            ax.plot(np.deg2rad(body_long),
                    dist_body,
                    's',
                    color=body_color,
                    label=body_lab)
            if plot_sun_body_line:
                # ax.plot(alpha_ref[0], 0.01, 0)
                ax.plot([np.deg2rad(body_long),
                         np.deg2rad(body_long)], [0.01, dist_body],
                        ':',
                        color=body_color)
            # plot the spirals
            if plot_spirals:
                tt = dist_body * AU / body_vsw
                alpha = np.degrees(omega * tt)
                alpha_body = np.deg2rad(
                    body_long) + omega / (body_vsw / AU) * (dist_body - r)
                ax.plot(alpha_body, r, color=body_color)

        if self.reference_long is not None:
            delta_ref = self.reference_long
            if delta_ref < 0.:
                delta_ref = delta_ref + 360.
            alpha_ref = np.deg2rad(delta_ref) + omega / (400 / AU) * (
                dist_e / AU - r) - (omega / (400 / AU) * (dist_e / AU))
            arrow_dist = min([self.max_dist + 0.1, 2.])
            ref_arr = plt.arrow(alpha_ref[0],
                                0.01,
                                0,
                                arrow_dist,
                                head_width=0.12,
                                head_length=0.11,
                                edgecolor='black',
                                facecolor='black',
                                lw=2,
                                zorder=5,
                                overhang=0.2)

            if plot_spirals:
                ax.plot(
                    alpha_ref,
                    r,
                    '--k',
                    label='field line connecting to\nref. long. (vsw=400 km/s)'
                )

        leg1 = ax.legend(loc=(1.2, 0.7), fontsize=13)
        if self.reference_long is not None:

            def legend_arrow(width, height, **_):
                return mpatches.FancyArrow(0,
                                           0.5 * height,
                                           width,
                                           0,
                                           length_includes_head=True,
                                           head_width=0.75 * height)

            leg2 = ax.legend([ref_arr], ['reference long.'],
                             loc=(1.2, 0.6),
                             handler_map={
                                 mpatches.FancyArrow:
                                 HandlerPatch(patch_func=legend_arrow),
                             },
                             fontsize=13)
            ax.add_artist(leg1)

        ax.set_rlabel_position(E_long + 120)
        ax.set_theta_offset(np.deg2rad(270 - E_long))
        ax.set_rmax(self.max_dist + 0.3)
        ax.set_rmin(0.01)
        ax.yaxis.get_major_locator().base.set_params(nbins=4)
        circle = pl.Circle((0., 0.),
                           self.max_dist + 0.29,
                           transform=ax.transData._b,
                           edgecolor="k",
                           facecolor=None,
                           fill=False,
                           lw=2)
        ax.add_artist(circle)

        ax.set_title(self.date + '\n', pad=40)

        plt.tight_layout()
        plt.subplots_adjust(bottom=0.15)

        if show_earth_centered_coord:
            pos1 = ax.get_position(
            )  # get the original position of the polar plot
            offset = 0.12
            pos2 = [
                pos1.x0 - offset / 2, pos1.y0 - offset / 2,
                pos1.width + offset, pos1.height + offset
            ]
            ax2 = self._polar_twin(ax, E_long, pos2)

        ax.tick_params(axis='x', pad=6)

        if outfile != '':
            plt.savefig(outfile)
        plt.show()
Exemple #19
0
        disp_bm.append(np.sqrt((x-xbm)**2+(y-ybm)**2))
        disp_bp.append(np.sqrt((x-xbp)**2+(y-ybp)**2))
        disp_br.append(np.sqrt((x-xbr)**2+(y-ybr)**2))
        plt.figure()
        p = plt.plot(x,y,'ok',label='ideal pos')
        plt.title('Electron XY displacement for Z={:.1f}'.format(z), fontsize=20)
        plt.xlabel('X (mm)', fontsize=18)
        plt.ylabel('Y (mm)', fontsize=18)
        ax =plt.gca()
        ax.set_ylim(y-0.5,y+0.5)
        ax.set_xlim(x-0.5,x+0.5)
        a1 = ax.arrow(x,y,x-xbm,y-ybm,head_width=0.03, head_length=0.03, linewidth=2, length_includes_head=True, fc='g', ec='g',label='meas syst')
        a2 = ax.arrow(x,y,x-xbr,y-ybr,head_width=0.03, head_length=0.03, linewidth=2, length_includes_head=True, fc='b', ec='b')
        a3 = ax.arrow(x,y,x-xbp,y-ybp,head_width=0.03, head_length=0.03, linewidth=2, length_includes_head=True, fc='r', ec='r')
        plt.legend([p[0],a1,a2,a3], ['ideal position', 'meas syst', 'rot syst', 'pos syst'],
                handler_map={mpatches.FancyArrow: HandlerPatch(patch_func=make_legend_arrow),}, fontsize=16)
        plt.tick_params(labelsize=18)
        if start_in_tracker:
            plt.savefig('../plots/anim/epath_tmp/electron_path_displacements_trk_'+str(i).zfill(3)+'.png')
        else:
            plt.savefig('../plots/anim/epath_tmp/electron_path_displacements_'+str(i).zfill(3)+'.png')
        print (np.sqrt((x-xbm)**2+(y-ybm)**2),  np.sqrt((x-xbr)**2+(y-ybr)**2), np.sqrt((x-xbp)**2+(y-ybp)**2))

    images = []
    if start_in_tracker:
        for image in glob.glob('../plots/anim/epath_tmp/electron_path_displacements_trk_0*.png'):
            img = PIL_Image.open(image)
            images.append(img.copy())
            img.close()
    else:
        for image in glob.glob('../plots/anim/epath_tmp/electron_path_displacements_0*.png'):
Exemple #20
0
def plot_spectrum_datasets_off_regions(datasets,
                                       ax=None,
                                       legend=None,
                                       legend_kwargs=None,
                                       **kwargs):
    """Plot the off regions of spectrum datasets.

    Parameters
    ----------
    datasets : `~gammapy.datasets.Datasets` of or sequence of `~gammapy.datasets.SpectrumDatasetOnOff`
        List of spectrum on-off datasets.
    ax : `~astropy.visualization.wcsaxes.WCSAxes`
        Axes object to plot on.
    legend : bool
        Whether to add/display the labels of the off regions in a legend. By default True if
        ``len(datasets) <= 10``.
    legend_kwargs : dict
        Keyword arguments used in `matplotlib.axes.Axes.legend`. The ``handler_map`` cannot be
        overridden.
    **kwargs : dict
        Keyword arguments used in `gammapy.maps.RegionNDMap.plot_region`. Can contain a
        `~cycler.Cycler` in a ``prop_cycle`` argument.

    Notes
    -----
    Properties from the ``prop_cycle`` have maximum priority, except ``color``,
    ``edgecolor``/``color`` is selected from the sources below in this order:
    ``kwargs["edgecolor"]``, ``kwargs["prop_cycle"]``, ``matplotlib.rcParams["axes.prop_cycle"]``
    ``matplotlib.rcParams["patch.edgecolor"]``, ``matplotlib.rcParams["patch.facecolor"]``
    is never used.

    Examples
    --------
    Plot forcibly without legend and with thick circles::

        plot_spectrum_datasets_off_regions(datasets, ax, legend=False, linewidth=2.5)

    Plot that quantifies the overlap of off regions::

        plot_spectrum_datasets_off_regions(datasets, ax, alpha=0.3, facecolor='black')

    Plot that cycles through colors (``edgecolor``) and line styles together::

        plot_spectrum_datasets_off_regions(datasets, ax, prop_cycle=plt.cycler(color=list('rgb'), ls=['--', '-', ':']))

    Plot that uses a modified `~matplotlib.rcParams`, has two legend columns, static and
    dynamic colors, but only shows labels for ``datasets1`` and ``datasets2``. Note that
    ``legend_kwargs`` only applies if it's given in the last function call with ``legend=True``::

        plt.rc('legend', columnspacing=1, fontsize=9)
        plot_spectrum_datasets_off_regions(datasets1, ax, legend=True, edgecolor='cyan')
        plot_spectrum_datasets_off_regions(datasets2, ax, legend=True, legend_kwargs=dict(ncol=2))
        plot_spectrum_datasets_off_regions(datasets3, ax, legend=False, edgecolor='magenta')
    """
    import matplotlib.pyplot as plt
    from matplotlib.patches import Patch, CirclePolygon
    from matplotlib.legend_handler import HandlerTuple, HandlerPatch

    ax = ax or plt.gca(projection=datasets[0].counts_off.geom.wcs)
    legend = legend or legend is None and len(datasets) <= 10
    legend_kwargs = legend_kwargs or {}
    handles, labels = [], []

    kwargs.setdefault("facecolor", "none")
    prop_cycle = kwargs.pop("prop_cycle", plt.rcParams["axes.prop_cycle"])
    plot_kwargs = kwargs.copy()

    for props, dataset in zip(prop_cycle(), datasets):
        props = props.copy()
        color = props.pop("color", plt.rcParams["patch.edgecolor"])
        plot_kwargs["edgecolor"] = kwargs.get("edgecolor", color)
        plot_kwargs.update(props)
        dataset.counts_off.plot_region(ax, **plot_kwargs)

        # create proxy artist for the custom legend
        if legend:
            handle = Patch(**plot_kwargs)
            handles.append(handle)
            labels.append(dataset.name)

    if legend:
        legend = ax.get_legend()
        if legend:
            handles = legend.legendHandles + handles
            labels = [text.get_text() for text in legend.texts] + labels

        handles = [(handle, handle) for handle in handles]
        tuple_handler = HandlerTuple(ndivide=None, pad=0)

        def patch_func(legend, orig_handle, xdescent, ydescent, width, height,
                       fontsize):
            radius = width / 2
            return CirclePolygon((radius - xdescent, height / 2 - ydescent),
                                 radius)

        patch_handler = HandlerPatch(patch_func)

        legend_kwargs.setdefault("handletextpad", 0.5)
        legend_kwargs["handler_map"] = {
            Patch: patch_handler,
            tuple: tuple_handler
        }
        ax.legend(handles, labels, **legend_kwargs)
Exemple #21
0
def printGraph(tasksExecuted, arrivalJob, offsetList, begin):
	"""
	Plotting the schedule graphically 
	"""

	x = []
	y = []
	xCircle = []
	yCircle = [] 
	plt.figure(figsize=(12,7)) 
	
	# Create two arrays for the execution time to be plotted
	missed = 0
	for i in range(begin, len(tasksExecuted)):
		if(tasksExecuted[i] != "Missed"):
			plt.text(i,tasksExecuted[i][0], str(tasksExecuted[i][1]), color = 'w', position =(i+0.5,tasksExecuted[i][0]))
			y.append(tasksExecuted[i][0])
			x.append(i)
		else:
			missed += 1
			plt.text(i,tasksExecuted[i-1][0], "Job missed !",ha="center", va="center",bbox=dict(boxstyle="round",ec=(1., 0.5, 0.5),fc=(1., 0.8, 0.8),))

	# Create two arrays for the deadlines to be plotted and draw the arrows corresponding to the arrival
	for i in range(len(arrivalJob)):
		for deadline in arrivalJob[i]:
			yCircle.append(i)
			xCircle.append(deadline)
			jobArrival  = plt.arrow(deadline,i-0.35,0,0.2, fc="k", ec="k", head_width = 0.5, head_length = 0.1)

	# Draw the first arrival of the job of each tasks
	for i in range(len(offsetList)):
		firstJob =plt.arrow(offsetList[i]+0.05,i-0.35,0,0.2,fc="g", ec="g", head_width = 0.5, head_length = 0.1, linewidth = 2)

	y = np.array(y)
	x = np.array(x)		
	xCircle = np.array(xCircle)
	yCircle = np.array(yCircle)
	deadline = plt.scatter(xCircle, yCircle, s=120, linewidth = 2,facecolors='none', edgecolors='red', zorder=1)

	ylabels = []
	xlabels = [] 

	countX = begin
	for j in range(begin, len(x)+begin+missed):
		xlabels.append(countX)
		countX += 1 
	
	xlabels = np.array(xlabels)
	
	countY = 0 
	for i in range(len(x)):
		ylabels.append(countY)
		countY += 1

	executionTime = plt.barh(y, [1]*len(x), left=x, color = 'blue', edgecolor = 'green', align='center', height=0.1, zorder = -1)

	plt.grid(color='black', linestyle='dotted', linewidth=1)
	plt.ylim(max(y)+0.5, min(y)-0.5)
	plt.xlim(min(x), max(x)+missed)
	plt.yticks(np.arange(y.max()+1), ylabels)
	plt.xticks(np.arange(begin,xlabels.max()+1), xlabels)
	plt.xlabel("t")
	plt.ylabel("Task number")
	plt.legend([jobArrival,executionTime, deadline,firstJob,], ['Arrival of a new job',"Execution time","deadlines", "Arrival of the first job"],handler_map={mpatches.FancyArrow : HandlerPatch(patch_func=make_legend_arrow),})
	plt.show()
Exemple #22
0
                                          label='CPU')
        #custom_arrow = mpatches.FancyArrowPatch((1, 1), (2, 2), mutation_scale=100, color='black', label='FPGA')
        custom_arrow = mpatches.Arrow(0, 0, 0, 0, color='black', label='FPGA')
        ax1handles, dud = ax1.get_legend_handles_labels()
        if ideal_multiplier > 0:
            temphand = ax1handles[0]
            del ax1handles[0]
            ax1handles.append(temphand)
        ax1handles.append(custom_hatch)
        ax1handles.append(custom_arrow)
        #ax1.legend(handles=ax1handles,loc=0)
        ax1.legend(handles=ax1handles,
                   loc=0,
                   handler_map={
                       mpatches.Arrow:
                       HandlerPatch(patch_func=make_legend_arrow)
                   })

        fig.tight_layout()
        plt.show()

        if outputfile != '':
            pp = PdfPages(outputfile)
            pp.savefig(fig)
            pp.close()

    if plottype == 3:
        #Power/Energy Bar chart
        config_labels = []
        for num, infile in enumerate(inputfile):
            config_labels.append(sched_type[num] + "+IOCTL(" +
Exemple #23
0
    # ax.xaxis.set_minor_locator(mloc)
    ax.grid(True)
    if i == 0:
        p1 = ax.plot([], [], color='tab:blue', linewidth=1)
        p2 = ax.fill([], [], color='tab:blue', alpha=0.15, edgecolor=None)

        def make_legend_polygon(legend, orig_handle, xdescent, ydescent, width,
                                height, fontsize):
            a = 1.5 * height
            p = mpatches.Polygon(
                np.array([[0, -a / 2], [width, -a / 2],
                          [width, height + a / 2], [0, height + a / 2],
                          [0, -a / 2]]))
            return p

        hm = {p2[0]: HandlerPatch(patch_func=make_legend_polygon)}
        ax.legend([(p1[0], p2[0]), p4, p3], ['Wouters', 'Zemp', 'This study'],
                  handlelength=1,
                  framealpha=0.8,
                  loc='lower left',
                  ncol=3,
                  labelspacing=0.1,
                  columnspacing=0.3,
                  handler_map=hm)

        ax.text(0.95,
                0.95,
                region_names[i],
                horizontalalignment='right',
                verticalalignment='top',
                transform=ax.transAxes,