Example #1
0
def draw_circle(ax):
    """
    Draw a circle in axis coordinates
    """
    from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDrawingArea
    from matplotlib.patches import Circle
    ada = AnchoredDrawingArea(20,
                              20,
                              0,
                              0,
                              loc='upper right',
                              pad=0.,
                              frameon=False)
    p = Circle((10, 10), 10)
    ada.da.add_artist(p)
    ax.add_artist(ada)
Example #2
0
def plot_scalar2_xy(grid,
                    PI,
                    unite,
                    s,
                    name='n',
                    colormesh=True,
                    pos=None,
                    ax=None,
                    fig=None,
                    **kwargs):
    if ax is None:
        if fig is None:
            fig = plt.figure(dpi=150)
        ax = fig.add_subplot(111)

    if pos is None:
        # If no position is supplied, take the middle!
        pos = grid.resolution[2] // 2

    im = ax.contourf(grid.x[:, :, 75], grid.y[:, :, 75], PI, **kwargs)

    ada = AnchoredDrawingArea(
        2,
        2,
        0,
        0,
        loc='lower left',
        pad=0.,
        frameon=False,
    )
    p = Circle((7, 7), s, fill=False, color="black")
    ada.da.add_artist(p)
    ax.add_artist(ada)

    #im = ax.imshow(I)

    ax.set_aspect('equal', adjustable='box')
    ax.set_xlabel(r'$x\;[\rm pc]$')
    ax.set_ylabel(r'$y\;[\rm pc]$')
    cax = plt.colorbar(im, ax=ax)
    cax.set_label(r'${}\;\left[\,{}\,\right]$'.format(name,
                                                      get_latex_units(unite)))

    return fig
Example #3
0
def draw_circles():
    for ip in logfile:
        if ip[-1] == '2':
            left_dbm = logfile[ip]['a8:96:75:c3:58:0d'][-1][1]
        elif ip[-1] == '5':
            #print(dbm, " came from erick")
            right_dbm = logfile[ip]['a8:96:75:c3:58:0d'][-1][1]
        elif ip[-1] == '4':
            #print(dbm, " came from justin")
            back_left_dbm = logfile[ip]['a8:96:75:c3:58:0d'][-1][1]
        elif ip[-1] == '3':
            #print(dbm, " came from aaron")
            back_right_dbm = logfile[ip]['a8:96:75:c3:58:0d'][-1][1]
            #back_right_dbm =  logfile['172.24.1.90']['a8:96:75:c3:58:0d'][-1][1]
    print('{0}         {1}            {2}               {3}'.format(
        left_dbm, back_left_dbm, back_right_dbm, right_dbm),
          end='\r')

    fig, ax = plt.subplots(figsize=(10, 10))

    ada = AnchoredDrawingArea(10, 10, 0, 0, loc=1, pad=0., frameon=False)

    left_circle = Circle((-550, -540), radius(left_dbm), fc="none", ec='g')
    ada.drawing_area.add_artist(left_circle)

    back_left_circle = Circle((-550, 20),
                              radius(back_left_dbm),
                              fc="none",
                              ec='r')
    ada.drawing_area.add_artist(back_left_circle)

    back_right_circle = Circle((20, 20),
                               radius(back_right_dbm),
                               fc="none",
                               ec="b")
    ada.drawing_area.add_artist(back_right_circle)

    right_circle = Circle((20, -540), radius(right_dbm), fc="none", ec='k')
    ada.drawing_area.add_artist(right_circle)

    ax.add_artist(ada)
    plt.show()
    time.sleep(2)
    fig.clf()
Example #4
0
    def plot_greens(bin_ends, values, image_width, image_height, radius, driver_action):
        ada = AnchoredDrawingArea(radius * 2, radius, 0, 0, loc=10, pad=0., borderpad=0., frameon=False)

        def add_to_ada(ada, pos_x, pos_y, radius, angle_s, angle_e, ring_width, color_code, alpha_value):
            ada.drawing_area.add_artist(
                Wedge((pos_x, pos_y), radius, angle_s, angle_e, width=ring_width, fc=color_code  # '#DAF7A6'
                      , ec='none', alpha=alpha_value, antialiased=True))

        bin_ends = 180 - np.array(bin_ends)
        bin_ends = bin_ends[::-1]
        values = np.array(values)
        values = np.squeeze(values)
        values = values[::-1]

        mask = gen_mask(bin_ends, values, radius, image_height, image_width)
        plt.imshow(mask, alpha=0.8)

        white_border = 2
        border_color = '#FFFFFF'
        add_to_ada(ada, radius, -(image_height / 2 - radius / 2), radius + white_border, 0, 180, white_border + 1,
                   border_color, 1)

        tick_len = 20
        tick_color = '#FFFFFF'
        tick_width = 1.0 / 2
        for i in range(len(bin_ends)):
            if abs(bin_ends[i] - 90) > 10:
                add_to_ada(ada, radius, -(image_height / 2 - radius / 2), radius + white_border,
                           bin_ends[i] - tick_width / 2, bin_ends[i] + tick_width / 2, tick_len, tick_color, 10)

        driver_action = driver_action / 180.0 * math.pi
        start = np.array([radius, -(image_height / 2 - radius / 2)])
        delta = np.array([radius * math.cos(driver_action), radius * math.sin(driver_action)]) * 0.8
        color_driver = "#0000FF"
        ada.drawing_area.add_artist(FancyArrowPatch(start, start + delta, linewidth=2, color=color_driver))

        return ada
Example #5
0
def plot_scalar_xy_col(grid,
                       scalar_field,
                       unite,
                       s,
                       name='n',
                       colormesh=True,
                       pos=None,
                       ax=None,
                       fig=None,
                       **kwargs):
    """
    Plots a slice of a scalar field defined on a 3D cartesian grid
    """
    if ax is None:
        if fig is None:
            fig = plt.figure(dpi=150)
        ax = fig.add_subplot(111)

    if pos is None:
        # If no position is supplied, take the middle!
        pos = grid.resolution[2] // 2

    if len(scalar_field.shape) == 3:
        im_slice = scalar_field[:, :, pos]
    else:
        im_slice = scalar_field

    if 'cmap' not in kwargs:
        if unite.unit.is_equivalent(u.rad):
            kwargs['cmap'] = 'bwr'

    if colormesh:
        im = ax.pcolormesh(grid.x[:, :, pos].value,
                           grid.y[:, :, pos].value,
                           im_slice,
                           cmap='bwr',
                           **kwargs)
    else:
        im = ax.contourf(grid.x[:, :, pos], grid.y[:, :, pos], im_slice,
                         **kwargs)

    ada = AnchoredDrawingArea(
        2,
        2,
        0,
        0,
        loc='lower left',
        pad=0.,
        frameon=False,
    )
    p = Circle((7, 7), s, fill=False, color="black")
    ada.da.add_artist(p)
    ax.add_artist(ada)

    ax.set_aspect(1)
    ax.set_xlabel(r'$x\;[\rm pc]$')
    ax.set_ylabel(r'$y\;[\rm pc]$')
    cax = plt.colorbar(im, ax=ax)
    cax.set_label(r'${}\;\left[\,{}\,\right]$'.format(name,
                                                      get_latex_units(unite)))
    return fig
Example #6
0
    def plot_greens(bin_ends, values, image_width, image_height, radius,
                    driver_action):
        # bins are: [0, bin_ends[0]], [bin_ends[0], bin_ends[1]] ...
        # and the corresponding values to display are: values[0], values[1]
        # the final results are added to ada

        ada = AnchoredDrawingArea(radius * 2,
                                  radius,
                                  0,
                                  0,
                                  loc=10,
                                  pad=0.,
                                  frameon=False)

        def add_ada_custom(angle_s, angle_e, value, color):
            add_to_ada(ada, radius, -(image_height / 2 - radius / 2), radius,
                       angle_s, angle_e, None, color, value)

        def add_to_ada(ada, pos_x, pos_y, radius, angle_s, angle_e, ring_width,
                       color_code, alpha_value):
            ada.drawing_area.add_artist(
                Wedge(
                    (pos_x, pos_y),
                    radius,
                    angle_s,
                    angle_e,
                    width=ring_width,
                    fc=color_code  # '#DAF7A6'
                    ,
                    ec='none',
                    alpha=alpha_value,
                    antialiased=True))

        bin_ends = 180 - np.array(bin_ends)
        bin_ends = bin_ends[::-1]
        values = np.array(values)
        values = np.squeeze(values)
        values = values[::-1]

        # add a black background
        add_ada_custom(0, 180, 0.8, "#000000")

        color_shading = "#00FF00"
        for i in range(len(values)):
            #print(bin_ends.shape, '____all____bin_____')
            #print(values.shape, '___all_____values____')
            if i < 5:
                print(bin_ends[i], bin_ends[i + 1], values[i],
                      '________________________')
            add_ada_custom(bin_ends[i], bin_ends[i + 1], values[i],
                           color_shading)

        white_border = 1
        border_color = '#FFFFFF'
        add_to_ada(ada, radius, -(image_height / 2 - radius / 2),
                   radius + white_border, 0, 180, white_border, border_color,
                   1)

        tick_len = 20
        tick_color = '#FFFFFF'
        tick_width = 1.0 / 2
        for i in range(len(bin_ends)):
            add_to_ada(ada, radius, -(image_height / 2 - radius / 2),
                       radius + white_border, bin_ends[i] - tick_width / 2,
                       bin_ends[i] + tick_width / 2, tick_len, tick_color, 10)

        driver_action = driver_action / 180.0 * math.pi
        start = np.array([radius, -(image_height / 2 - radius / 2) - 2])
        delta = np.array([
            radius * math.cos(driver_action), radius * math.sin(driver_action)
        ]) * 0.8
        color_driver = "#0000FF"
        ada.drawing_area.add_artist(
            FancyArrowPatch(start,
                            start + delta,
                            linewidth=2,
                            color=color_driver))

        return ada
Example #7
0
def vis_discrete_colormap_antialias(tout,
                                    predict,
                                    frame_rate,
                                    j=0,
                                    save_visualize=False,
                                    dir_name="temp",
                                    string_type='image'):
    if FLAGS.only_seg:
        decoded = tout[0]
        speed = tout[1]
        name = tout[2]
        isstop = tout[5]
        turn = tout[6]
        locs = tout[7]
    else:
        decoded, speed, name, isstop, turn, locs = tout

    images = copy.deepcopy(decoded[j, :, :, :, :])
    _, hi, wi, _ = images.shape
    turn = turn[j, :, :]

    def get_color(prob):
        cm = pylab.get_cmap('viridis')  # inferno
        color = cm(prob)  # color will now be an RGBA tuple
        r = color[0] * 255
        g = color[1] * 255
        b = color[2] * 255
        return r, g, b

    def clamp(x):
        x = float(x)
        return max(0, min(x, 1))

    def add_to_ada(ada, pos_x, pos_y, radius, angle_s, angle_e, ring_width,
                   color_code, edge_color, alpha_value):
        ada.drawing_area.add_artist(
            Wedge(
                (pos_x, pos_y),
                radius,
                angle_s,
                angle_e,
                width=ring_width  # , color=color_code#'#DAF7A6'
                ,
                alpha=alpha_value,
                antialiased=True,
                ec=edge_color,
                fc=color_code))

    def draw_cake(ada,
                  pos_x,
                  pos_y,
                  radius,
                  angle_s,
                  angle_diff,
                  ring_width,
                  color_code,
                  edge_color,
                  alpha_value,
                  share,
                  shift=45):
        angle_s = angle_s + shift
        for i in range(share):
            if (angle_s + (i + 1) * (angle_diff) / share) == 360:
                angle_end = 360
            else:
                angle_end = angle_s + (i + 1) * (angle_diff) / share
            #print(i,'_______________________________________')
            add_to_ada(ada,
                       pos_x,
                       pos_y,
                       radius,
                       angle_s + i * (angle_diff) / share,
                       angle_end,
                       ring_width,
                       color_code=color_code,
                       edge_color=edge_color,
                       alpha_value=alpha_value[i])

    def draw_pile_cake(ada,
                       pos_x,
                       pos_y,
                       radius,
                       angle_s,
                       angle_diff,
                       ring_width,
                       color_code,
                       edge_color,
                       alpha_value,
                       share,
                       x_frac,
                       y_frac,
                       split,
                       fontsize=24,
                       shift=45):
        # draw the black one
        draw_cake(ada,
                  pos_x=pos_x,
                  pos_y=pos_y,
                  radius=radius,
                  angle_s=angle_s,
                  angle_diff=360,
                  ring_width=None,
                  color_code='k',
                  edge_color=None,
                  alpha_value=[0.6],
                  share=1)
        # draw the green one

        draw_cake(ada,
                  pos_x=pos_x,
                  pos_y=pos_y,
                  radius=radius,
                  angle_s=angle_s,
                  angle_diff=360,
                  ring_width=ring_width,
                  color_code=color_code,
                  edge_color='#FFFFFF',
                  alpha_value=alpha_value,
                  share=4)
        # draw the white edge
        draw_cake(ada,
                  pos_x=pos_x,
                  pos_y=pos_y,
                  radius=radius,
                  angle_s=angle_s,
                  angle_diff=360,
                  ring_width=ring_width,
                  color_code='none',
                  edge_color='#FFFFFF',
                  alpha_value=[1, 1, 1, 1],
                  share=4)
        ada.da.add_artist(
            ax.annotate(split,
                        xy=(x_frac, y_frac),
                        xycoords="axes fraction",
                        fontsize=fontsize,
                        color='w'))

    def draw_cake_type(ada, string_type, action_mean, predict_mean):
        if string_type == 'video':
            draw_pile_cake(ada,
                           pos_x=210,
                           pos_y=70,
                           radius=60,
                           angle_s=0,
                           angle_diff=360,
                           ring_width=30,
                           color_code='#00FF00',
                           edge_color=None,
                           alpha_value=predict_mean,
                           share=1,
                           x_frac=0.513,
                           y_frac=0.895,
                           split='P')
            draw_pile_cake(ada,
                           pos_x=80,
                           pos_y=70,
                           radius=60,
                           angle_s=0,
                           angle_diff=360,
                           ring_width=30,
                           color_code='#00FF00',
                           edge_color=None,
                           alpha_value=action_mean,
                           share=1,
                           x_frac=0.185,
                           y_frac=0.895,
                           split='G')
        elif string_type == 'image':

            draw_pile_cake(ada,
                           pos_x=240,
                           pos_y=70,
                           radius=70,
                           angle_s=0,
                           angle_diff=360,
                           ring_width=40,
                           color_code='#00FF00',
                           edge_color=None,
                           alpha_value=predict_mean,
                           share=1,
                           x_frac=0.580,
                           y_frac=0.89,
                           split='P',
                           fontsize=32)
            draw_pile_cake(ada,
                           pos_x=80,
                           pos_y=70,
                           radius=70,
                           angle_s=0,
                           angle_diff=360,
                           ring_width=40,
                           color_code='#00FF00',
                           edge_color=None,
                           alpha_value=action_mean,
                           share=1,
                           x_frac=0.18,
                           y_frac=0.89,
                           split='G',
                           fontsize=32)

    _, short_name = os.path.split(name[j])
    short_name = short_name.split(".")[0]

    for i in range(images.shape[0]):
        action_mean = [
            clamp(turn[i, 0] + 0.05),
            clamp(turn[i, 2] + 0.05),
            clamp(turn[i, 1] + 0.1),
            clamp(turn[i, 3] + 0.05)
        ]
        predict_mean = [
            clamp(predict[i, 0] + 0.05),
            clamp(predict[i, 2] + 0.05),
            clamp(predict[i, 1] + 0.05),
            clamp(predict[i, 3] + 0.05)
        ]
        fig = plt.figure(figsize=(16, 12))
        ax_original = plt.gca()
        ax_original.set_axis_off()
        ax_original.get_xaxis().set_visible(False)
        ax_original.get_yaxis().set_visible(False)
        plt.imshow(images[i, :, :, :])
        plt.axis('off')
        ax = fig.add_subplot(121, projection='polar')
        ax_2 = fig.add_subplot(122, projection='polar')

        ada = AnchoredDrawingArea(200, 100, 0, 0, loc=2, pad=0., frameon=False)
        draw_cake_type(ada, string_type, action_mean, predict_mean)

        ax.add_artist(ada)
        ax.set_axis_off()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        ax_2.set_axis_off()
        ax_2.get_xaxis().set_visible(False)
        ax_2.get_yaxis().set_visible(False)

        if not os.path.exists(os.path.join(dir_name, 'viz')):
            os.mkdir(os.path.join(dir_name, 'viz'))
        if not os.path.exists(
                os.path.join(dir_name, 'viz', short_name + string_type)):
            os.mkdir(os.path.join(dir_name, 'viz', short_name + string_type))
        fig.savefig(os.path.join(dir_name, 'viz', short_name + string_type,
                                 '{0:04}.png'.format(i)),
                    bbox_inches='tight',
                    pad_inches=-0.04,
                    Transparent=True,
                    dpi=100)

        print(short_name, ' ', i, 'Done!')
        plt.show()
        plt.close()

    images2video_highqual(frame_rate=3,
                          name=short_name,
                          dir_name=os.path.join(dir_name, 'viz',
                                                short_name + string_type))
Example #8
0
# the drawing area are not related to the placement of the drawing
# area itself. Only the initial size matters.
#
# The artists that are added to the drawing area should not have a
# transform set (it will be overridden) and the dimensions of those
# artists are interpreted as a pixel coordinate, i.e., the radius of the
# circles in above example are 10 pixels and 5 pixels, respectively.

from matplotlib.patches import Circle
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDrawingArea

fig, ax = plt.subplots()
ada = AnchoredDrawingArea(40,
                          20,
                          0,
                          0,
                          loc='upper right',
                          pad=0.,
                          frameon=False)
p1 = Circle((10, 10), 10)
ada.drawing_area.add_artist(p1)
p2 = Circle((30, 10), 5, fc="r")
ada.drawing_area.add_artist(p2)
ax.add_artist(ada)

###############################################################################
# Sometimes, you want your artists to scale with the data coordinate (or
# coordinates other than canvas pixels). You can use
# ``AnchoredAuxTransformBox`` class. This is similar to
# ``AnchoredDrawingArea`` except that the extent of the artist is
# determined during the drawing time respecting the specified transform.
Example #9
0
"""
==============
Anchored Box02
==============

"""
from matplotlib.patches import Circle
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredDrawingArea

fig, ax = plt.subplots(figsize=(3, 3))

ada = AnchoredDrawingArea(40, 20, 0, 0, loc=1, pad=0., frameon=False)
p1 = Circle((10, 10), 10)
ada.drawing_area.add_artist(p1)
p2 = Circle((30, 10), 5, fc="r")
ada.drawing_area.add_artist(p2)

ax.add_artist(ada)

plt.show()
Example #10
0
File: core.py Project: lxy1991/mcr3
    def get_nn(self,
               nnradius=10.01,
               axin=None,
               yshift=0,
               ms=9,
               lp='k-',
               ts=0,
               text_off=False,
               labels_off=False,
               atoms_off=False):
        # TODO: docstring

        if self.structure:
            env = self.structure[0].\
                  get_sites_in_sphere(self.structure[0][self.structure[1]].\
                  coords, nnradius)

            def getKey(item):
                # TODO: docstring

                return item[1]

            self.env = sorted(env, key=getKey)
            ss = []
            for i in env:
                ss.append(i[0].specie.name)
            self.species = list(set(ss))

            if not atoms_off:
                atext = []
                cs = []
                c = 0
                s = 10
                for i in self.species:
                    ada = AnchoredDrawingArea(s * 3, (len(self.species)) * s,
                                              0,
                                              0,
                                              loc=2,
                                              pad=0.,
                                              frameon=False)
                    cs.append(Circle((s * 2, c * s), 3, fc=get_c(i)))
                    atext.append(i)
                    c += 1

                at = AnchoredText('\n'.join(atext[::-1]),
                                  loc=2,
                                  prop=dict(size=s),
                                  frameon=False,
                                  bbox_to_anchor=(0., 1.),
                                  bbox_transform=axin.transAxes)
                for i in cs:
                    ada.drawing_area.add_artist(i)
                ada.drawing_area.add_artist(at)
                axin.add_artist(ada)

            if axin:
                if self.vcn:
                    astr = 'mult.={:d}\nvcn={:04.2f}'.\
                           format(self.multiplicity, self.vcn)
                else:
                    astr = 'mult.={:d}\nvcn=na'.format(self.multiplicity)

                if not text_off:
                    axin.annotate(astr, (-3, ts + yshift - 0.1),
                                  fontsize=10,
                                  weight='bold')

                ss = []
                ds = []
                for i in self.env:
                    ss.append(i[0].specie.name)
                    ds.append(i[1])
                ds = np.array(ds, np.float)

                axin.plot(yshift + ds[0:21], lp)

                for i, d in enumerate(ds[0:21]):
                    c = get_c(ss[i])
                    axin.plot(i, yshift + d, 'o', color=c, ms=ms, alpha=0.8)

                axin.set_xticks(list(range(1, 21)))

                if text_off:
                    axin.set_xlim([-0.5, 21])
                else:
                    axin.set_xlim([-3.5, 21])

                if not labels_off:
                    axin.set_xlabel('Neighbour index #')
                    axin.set_ylabel('Distance to absorbing atom ($\AA$)')
                else:
                    axin.set_xticklabels([])
        else:
            env = []
            if axin:
                print('nn info is not available.')

        return env
Example #11
0
        new_ax[beam_id].legend(loc="upper left", fontsize="x-small")
    # plot empty hexagons
    for beam_id in id_not_exist:
        new_ax[beam_id] = hexagonPlot(axins, [0], [0],
                                      centerxy=tuple(beam_shift[beam_id]),
                                      radius=radius,
                                      title='beam_{}'.format(beam_id))

    os.system("rm -rf hexplotcache")
    # Big cirle
    hexagon = Circle((0, 0),
                     radius * 5,
                     ec="black",
                     fc='blue',
                     alpha=0.1,
                     lw=2)
    ada = AnchoredDrawingArea(radius * coef,
                              radius * coef,
                              radius * coef / 2,
                              radius * coef / 2,
                              loc=10,
                              pad=0,
                              frameon=False)
    ada.da.add_artist(hexagon)
    ax.add_artist(ada)
    ax.axis('off')
    axins.axis('off')
    ax.set_title('Load files from dir:{}'.format(filein))

    plt.savefig(png_name)