Exemplo n.º 1
0
def test_wedge_movement():
    param_dict = {
        'center': ((0, 0), (1, 1), 'set_center'),
        'r': (5, 8, 'set_radius'),
        'width': (2, 3, 'set_width'),
        'theta1': (0, 30, 'set_theta1'),
        'theta2': (45, 50, 'set_theta2')
    }

    init_args = {k: v[0] for k, v in param_dict.items()}

    w = mpatches.Wedge(**init_args)
    for attr, (old_v, new_v, func) in param_dict.items():
        assert getattr(w, attr) == old_v
        getattr(w, func)(new_v)
        assert getattr(w, attr) == new_v
Exemplo n.º 2
0
def test_wedge_movement():
    param_dict = {
        'center': ((0, 0), (1, 1), 'set_center'),
        'r': (5, 8, 'set_radius'),
        'width': (2, 3, 'set_width'),
        'theta1': (0, 30, 'set_theta1'),
        'theta2': (45, 50, 'set_theta2')
    }

    init_args = dict((k, v[0]) for (k, v) in six.iteritems(param_dict))

    w = mpatches.Wedge(**init_args)
    for attr, (old_v, new_v, func) in six.iteritems(param_dict):
        assert_equal(getattr(w, attr), old_v)
        getattr(w, func)(new_v)
        assert_equal(getattr(w, attr), new_v)
Exemplo n.º 3
0
def plot2(d, outfile):

    fig, ax = plt.subplots()

    pieValues = d.values()

    wedges, texts = ax.pie(
        pieValues,
        # colors=colors,
        # explode=explode,
        # autopct='%1.1f%%',
        # startangle=90,
        # wedgeprops={'linewidth': 0.5, 'edgecolor': 'black'}
        # pctdistance=0.85
    )

    ax.set_aspect('equal')
    ax.axis('off')
    
    groups = [[0], [1, 2], [3, 4]]

    radfraction = 0.1
    patches = []
    for i in groups:
        # print((wedges[i[-1]].theta2 + wedges[i[0]].theta1)/2)
        ang = np.deg2rad((wedges[i[-1]].theta2 + wedges[i[0]].theta1)/2,)
        print(ang)
        for j in i:
            we = wedges[j]
            print(we)
            print(ang)
            center = (radfraction*we.r*np.cos(ang), radfraction*we.r*np.sin(ang))
            patches.append(mpatches.Wedge(center, we.r, we.theta1, we.theta2))

    # # print(patches)

    # colors = ['#E26882', '#EDC363', '#5EC3E5', '#47E0B7', '#A273CE']
    colors = np.linspace(0, 1, len(patches))
    collection = PatchCollection(patches, cmap=plt.cm.hsv)
    collection.set_array(np.array(colors))
    collection = PatchCollection(patches)
    ax.add_collection(collection)
    ax.autoscale(True)

    fig.tight_layout()
    # plt.savefig(outfile, dpi=300, format=None)
    plt.savefig(outfile)
Exemplo n.º 4
0
    def update_el(self, el, state):
        ''' el = TSCS.EL 
            state = STATL.TELDRIVE '''

        self.logger.debug('updating el=%s state=%s' % (str(el), state))

        val, color = self.__get_val_state(el, state)

        try:
            Artist.remove(self.el)
            el_kwargs = dict(alpha=0.5, fc=color, ec=color, lw=8)
            self.el = mpatches.Wedge((1, 0), 0.99, 180 - val, 180, **el_kwargs)
            self.axes.add_patch(self.el)
            self.draw()
        except Exception as e:
            self.logger.error('error: updating. %s' % str(e))
            pass
Exemplo n.º 5
0
    def add_self_loop(self, ax, prob=None, direction='up'):
        """
        Draws a self loop
        """
        if direction == 'up':
            start = -30
            angle = 180
            ring_x = self.x
            ring_y = self.y + self.radius
            prob_y = self.y + 1.3*self.radius
            x_cent = ring_x - self.radius + (self.ring_width/2)
            y_cent = ring_y - 0.15
        else:
            start = -210
            angle = 0
            ring_x = self.x
            ring_y = self.y - self.radius
            prob_y = self.y - 1.4*self.radius
            x_cent = ring_x + self.radius - (self.ring_width/2)
            y_cent = ring_y + 0.15
            
        # Add the ring
        ring = mpatches.Wedge(
            (ring_x, ring_y), 
            self.radius, 
            start, 
            angle, 
            width = self.ring_width
        )
        # Add the triangle (arrow)
        offset = 0.2
        left   = [x_cent - offset, ring_y]
        right  = [x_cent + offset, ring_y]
        bottom = [(left[0]+right[0])/2., y_cent]
        arrow  = plt.Polygon([left, right, bottom, left])

        p = PatchCollection(
            [ring, arrow], 
            edgecolor = self.ring_edgecolor, 
            facecolor = self.ring_facecolor
        )
        ax.add_collection(p)
        
        # Probability to add?
        if prob:
            ax.annotate(str(prob), xy=(self.x, prob_y), color='#000000', **self.text_args)
Exemplo n.º 6
0
    def create_mpl_patch(self):
        """Create a matplotlib patch for the region.

        Returns
        -------
        patch : matplotlib patch
        
        """

        patch = mpatches.Wedge([self.xc, self.zc],
                               self.radius_out,
                               0,
                               360,
                               self.radius_out - self.radius_in,
                               edgecolor='red',
                               facecolor="None")
        return patch
Exemplo n.º 7
0
def plot_bpg_connection(ref_placements,cycle,total_length,prev_seg_index_is_adj,bpg_dict,seg_end_pos_d):
    connect_width = bar_width/2.
    for ind,refObj in ref_placements.iteritems():
        next_ind = (ind+1) % len(ref_placements)
        next_refObj = ref_placements[next_ind]
        if not prev_seg_index_is_adj[next_ind]: #or next_ind == 0 to try and close
            bpg_adjacency = vu.pair_is_edge(refObj.id, next_refObj.id,refObj.direction, next_refObj.direction, 
                bpg_dict, seg_end_pos_d)

            if not bpg_adjacency:
                continue

            start_angle, end_angle = start_end_angle(next_refObj.abs_start_pos,refObj.abs_end_pos,total_length)
            #makes the reference genome wedges
            patches.append(mpatches.Wedge((0,0), outer_bar - bar_width/4, end_angle, start_angle, width=connect_width))
            f_color_v.append('grey')
            e_color_v.append('grey')
            lw_v.append(0.2)
Exemplo n.º 8
0
    def __init__(self, position, velocity=None, acceleration=0, animated=True):
        super().__init__(position, velocity, acceleration, animated)
        self.r = 15
        self.phi = 50
        self.sensor = patch.Wedge((self.pos[0], self.pos[1]),
                                  self.r,
                                  self.gch() - self.phi / 2,
                                  self.gch() + self.phi / 2,
                                  edgecolor='k',
                                  facecolor=None,
                                  fill=False)
        # self.sensor= patch.Circle((self.pos[0], self.pos[1]), self.r,edgecolor='r', facecolor=None, fill=False)
        ax.add_patch(self.sensor)

        self.target_point, = ax.plot(0, 0, 'bo')
        self.goal = np.array([35, 35])
        ax.plot(*self.goal, 'go', markersize=15)
        self.trail, = ax.plot(self.pos, 'ro', markersize=5)
Exemplo n.º 9
0
    def tas_simulate(self, data):
        se = cc.SampleEnviGeometry()
        TasSimulate.tas_simulate(self, data)
        # add sample enviroment
        for x in se.dead_angle:

            if data['s1s2_limit'] == 0:
                color = 'red'
            else:
                color = 'black'
            se_dead = mpatches.Wedge(self.sample_center,
                                     se.radius,
                                     180 + data.m2 - x[1] - data.s1,
                                     180 + data.m2 - x[0] - data.s1,
                                     ec='none',
                                     alpha=0.7,
                                     color=color)
            self.ax.add_patch(se_dead)
Exemplo n.º 10
0
    def animate_sector(ax, currentVessel):
        current = 0
        for i in range(10):
            next = current + config.sectors[i]
            patch = patches.Wedge(
                (currentVessel.shipstate.position.x,
                 currentVessel.shipstate.position.y),
                config.radius['ra'],
                helpers.nav_to_theta(currentVessel.shipstate.heading +
                                     current),
                helpers.nav_to_theta(currentVessel.shipstate.heading + next),
                ls='solid',
                linewidth=1,
                fill=False)

            collissionSectors.append(patch)
            ax.add_patch(patch)
            current = next
Exemplo n.º 11
0
def affichagePointsCles(im, listeAvecOrientation):
    print('...Affichage des résultats')
    fig, axd = plt.subplots(1)
    axd.imshow(im, cmap='gray')
    for liste in listeAvecOrientation:
        [o, s, x, y, sigma, deltaO, theta] = liste
        circ = patches.Wedge((int(y), int(x)),
                             sigma,
                             0,
                             360,
                             width=1,
                             color='red')
        axd.add_patch(circ)
        axd.add_line(
            mlines.Line2D([int(y), int(y + sigma * math.sin(theta))],
                          [int(x), int(x + sigma * math.cos(theta))]))
    plt.title('Affichage des lieux des points-clés')
    plt.show()
Exemplo n.º 12
0
def stepUi(cur_h, cur_depth, arc, lines):
    global all_lines
    a = 2. * pi * cur_h.toFloat()
    b = a + 2. * pi / (2**(cur_depth))
    arc.append(
        ringx.add_patch(
            mpatches.Wedge([
                0.,
                0,
            ],
                           1.,
                           a * 180 / pi,
                           b * 180 / pi,
                           fill=True,
                           color="blue",
                           alpha=0.5)))
    lines.extend(ringx.plot([0, cos(a)], [0, sin(a)], 'k-', lw=1.2))
    all_lines.extend(lines)
Exemplo n.º 13
0
def plot_gene_track(currStart, genes, segment, total_length_with_spacing, strand, exons = True):
  delta = control_delta if 'control' in segment.info else 0
  for gene in genes:    
    if gene.info['Name'].upper().startswith('RP11-') or gene.info['Name'].startswith('RP4-') or gene.info['Name'].startswith('RNU6') or gene.info['Name'].startswith('SNOR') or gene.info['Name'].startswith('U6') or gene.info['Name'].startswith('AC099') or gene.info['Name'].startswith('RP5') or gene.info['Name'].startswith('U4') or gene.info['Name'].find('RNA') != -1:
      continue
    #e_posns is a list of tuples of exon (start,end)
    #do exons
    tstart,tend = (gene.start,gene.end)
    #tstart,tend = (ensembl_map[gene.info['data'][-4]].start,ensembl_map[gene.info['data'][-4]].end)
    seg_len = segment.end - segment.start
    if strand == "+":
      normStart = currStart - max(0,tstart-segment.start)
      normEnd = currStart - min(segment.end-segment.start,tend-segment.start)
    else:
      normEnd = currStart - min(segment.end-segment.start,segment.end-tstart)
      normStart = currStart - max(0,segment.end - tend)
    # if tstart < pTup[1]:
    #   truncStart = True
    # if tend > pTup[2]:
    #   truncEnd = True
    gstart_angle = normStart/total_length_with_spacing*360
    gend_angle = normEnd/total_length_with_spacing*360
    
    text_angle = (gstart_angle + gend_angle)/2.0
    if gend_angle < 0 and gstart_angle > 0:
      gend_angle+=360      
    
    patches.append(mpatches.Wedge((0,0), outer_bar+delta, gend_angle, gstart_angle, width=bar_width/2.0))    
    color = 'r' if gene.info['Name'].upper() in oncogene_map else 'teal'    
    f_color_v.append(color)
    e_color_v.append(color)
    lw_v.append(0)
    
    x,y = pol2cart(outer_bar+(bar_width/2.0),(text_angle/360*2*np.pi))
    x_t,y_t = pol2cart(outer_bar + bar_width + gene_delta + delta,(text_angle/360*2*np.pi))
    #ax.plot([x,x_t],[y,y_t],color='grey',linewidth=0.4)
    
    if text_angle < -90 and text_angle > -360:
      text_angle+=180
      ax.text(x_t,y_t,gene.info['Name'],color=color,rotation=text_angle,
        ha='right',fontsize=font_size,rotation_mode='anchor')    
    else:
       ax.text(x_t,y_t,gene.info['Name'],color=color,rotation=text_angle,
        ha='left',fontsize=font_size,rotation_mode='anchor')
Exemplo n.º 14
0
def analysis_new_mission_commonparameters_tagged_100_200(city):
    lines = commonparameters(city)
    db = pymysql.connect(host=HOST,
                         user=USER,
                         password=PASSWD,
                         db=DB,
                         charset='utf8')
    cursor = db.cursor()
    for l in range(0, len(lines)):
        cgi = lines[l][4]
        district = lines[l][3]
        shapes = gaodemapscene(district, city, 120000)
        Path = mpath.Path
        for s in range(0, len(shapes)):
            shape = shapes[s][-1]
            shape_array = np.array([
                float(i)
                for i in shape.replace('|', ',').replace(';', ',').split(',')
            ]).reshape(-1, 2)
            angle = float(lines[l][18])
            point = (float(lines[l][15]), float(lines[l][14]))
            Path(shape_array)
            try:
                a = mpatches.Wedge(point,
                                   0.0018,
                                   angle - 65,
                                   angle + 65,
                                   width=0.0009)._path.vertices
                a = Polygon(a).buffer(0)
                b = Polygon(shape_array)
                c = a.intersection(b)
                polygon = Polygon(c)
                f = polygon.area / b.area
            except NotImplementedError as e:
                f = 0
            if f > 0.5:
                query_commonparameters_tagged = """UPDATE {} set residential_flag='3' where cgi='{}'""".format(
                    TABLE_NAME_ANALYSIS_Commonparameters, cgi)
                cursor.execute(query_commonparameters_tagged)
                break
        print('%.2f%%' % (l / len(lines) * 100))
    cursor.close()
    db.commit()
    db.close()
Exemplo n.º 15
0
def plot_ref_cmaps(start_point,seg_cmap_vector):
  start_angle = start_point/total_length_with_spacing*360
  end_angle = (start_point - seg_cmap_vector[-1])/total_length_with_spacing*360
  if end_angle < 0 and start_angle >0:
    end_angle+=360  
  patches.append(mpatches.Wedge((0,0), mid_bar+bar_width, end_angle, start_angle, width=bar_width))
  f_color_v.append('darkorange')
  e_color_v.append('k')
  lw_v.append(0)
  
  lab_locs = []
  print seg_cmap_vector
  for i in seg_cmap_vector[:-1]:
    label_angle = (start_point - i)/total_length_with_spacing*2*np.pi
    x,y = pol2cart(mid_bar,label_angle)
    x_t,y_t = pol2cart(mid_bar+bar_width,label_angle)
    ax.plot([x,x_t],[y,y_t],color='k',alpha=0.9,linewidth=0.2)
    lab_locs.append(start_point - i)
  return lab_locs
Exemplo n.º 16
0
    def drawBot(self, row, col, angleRotation, cellSize, axes):
        """Metodo dibuja a BB8 en una posicion.

            Argumentos:
                + row (int): Fila que nos indica en que fila esta el bot
                + col (int): Fila que nos indica en que columna esta el bot
                + angleRotation (int): No se usa
                + cellSize (float): Tamaño de la celda a dibujar el robot
                + axes (matplotlib axes): Ejes donde se dibuja el bot

        """
        x = (col + 0.5) * cellSize
        y = (row + 0.5) * cellSize

        #Dibujamos a BB8
        head1 = mpatches.Wedge((0, 0.25), cellSize / 5, 0, 180, color="orange")
        head2 = mpatches.Circle((0, 0.4), radius=cellSize / 16, color="black")
        body1 = mpatches.Circle((0, -0.25),
                                radius=cellSize / 4,
                                color="orange")
        body2 = mpatches.Circle((0, -0.25), radius=cellSize / 6, color="white")

        #Movemos el poligono a la posicion indicada
        t2 = mpl.transforms.Affine2D().translate(x, y)

        #Unimos todas las transformaciones
        tra = t2 + axes.transData
        head1.set_transform(tra)
        body1.set_transform(tra)
        body2.set_transform(tra)
        head2.set_transform(tra)

        patches = []
        patches.append(head1)
        patches.append(body1)
        patches.append(body2)
        patches.append(head2)

        self.drawing = patches

        for parts in patches:
            axes.add_patch(parts)
Exemplo n.º 17
0
    def draw_screen(self):
        title = " Avg. Reward: %d Reward: %d Total Game: %d" % (
            self.total_reward / self.total_game, self.current_reward,
            self.total_game)

        self.axis.clear()
        self.axis.set_title(title, fontsize=12)

        road = patches.Rectangle((self.road_left - 1, 0),
                                 self.road_width + 1,
                                 self.screen_height,
                                 linewidth=0,
                                 facecolor="#333333")

        if self._is_gameover():
            car_color = "#FF0000"
        else:
            car_color = "#00FF00"
        car = patches.Wedge((self.car["col"] - 0.5, self.car["row"] - 0.5),
                            0.5,
                            20,
                            340,
                            linewidth=0,
                            facecolor=car_color)
        block1 = patches.Circle(
            (self.block[0]["col"] - 0.5, self.block[0]["row"]),
            0.5,
            linewidth=0,
            facecolor="#0099FF")
        block2 = patches.Circle(
            (self.block[1]["col"] - 0.5, self.block[1]["row"]),
            0.5,
            linewidth=0,
            facecolor="#EB70AA")

        self.axis.add_patch(road)
        self.axis.add_patch(car)
        self.axis.add_patch(block1)
        self.axis.add_patch(block2)

        self.fig.canvas.draw()
        plt.pause(0.0001)
Exemplo n.º 18
0
 def updateIcon(self, now):
     self.timePassedAngle = int(
         (now - self.start + 0.5) / (self.end - self.start) * 360)
     #self.fig = plt.figure(figsize=(1, 1), dpi=100)
     #self.fig.delaxes(self.ax)
     #self.ax = self.fig.add_subplot(111)
     if self.timePassedAngle < 360:
         #self.w1 = pat.Wedge(center = (0.5, 0.5), r = 0.5, theta1 = 0, theta2 = 360, color = 'black', width=0.03 )
         self.w2 = pat.Wedge(
             center=(0.5, 0.5),
             r=0.45,
             theta1=90,
             theta2=450 - self.timePassedAngle,
             color=actTmColor if self.timerActive else deactTmColor)
         #self.ax.add_patch(self.w1)
         self.ax.add_patch(self.w2)
     plt.axis('off')
     plt.savefig(self.img_path, transparent=True, dpi=100)
     self.icon = self.img_path
     self.ax.clear()
Exemplo n.º 19
0
def plot_flow_cyliner_2(img_epoch, m, n, epoch, Xmean):
    import cmocean

    x2 = np.arange(0, 384, 1)
    y2 = np.arange(0, 199, 1)
    mX, mY = np.meshgrid(x2, y2)

    img_epoch += Xmean.reshape(m, n)

    minmax = np.max(np.abs(img_epoch)) * 0.65
    plt.figure(facecolor="white", edgecolor='k', figsize=(7.9, 4.7))
    im = plt.imshow(img_epoch.T,
                    cmap=cmocean.cm.balance,
                    interpolation='none',
                    vmin=-minmax,
                    vmax=minmax)
    plt.contourf(mX,
                 mY,
                 img_epoch.T,
                 80,
                 cmap=cmocean.cm.balance,
                 alpha=1,
                 vmin=-minmax,
                 vmax=minmax)

    wedge = mpatches.Wedge((0, 99),
                           33,
                           270,
                           90,
                           ec="#636363",
                           color='#636363',
                           lw=5)
    im.axes.add_patch(p=wedge)

    #plt.title('Epoch number ' + str(epoch), fontsize = 16 )
    plt.axis('off')
    plt.title('Reconstructed flow filed using the shallow decoder')
    plt.tight_layout()
    #plt.show()
    plt.savefig('results/reconstruction_via_shallow_decoder.png', dpi=300)
    plt.close()
    def load_and_plot_map(self, mmap):
        # setup a plot axis
        self.ax.set_aspect('equal')
        self.ax.set_xlim(-3, 3)
        self.ax.set_ylim(0, 5)

        for i in range(mmap["num_markers"]):
            # load marker pose
            map_entry = "marker{0}".format(i)
            x = mmap[map_entry]["x"]
            y = mmap[map_entry]["y"]
            th = mmap[map_entry]["theta"]

            if mmap[map_entry]["units"][0] == "inch":
                x *= inch_to_meter
                y *= inch_to_meter
            if mmap[map_entry]["units"][1] == "deg":
                th *= np.pi / 180.0

            # calculate marker boarders for plotting
            x_border = np.array([
                x + 0.5 * self.marker_size * np.cos(th),
                x - 0.5 * self.marker_size * np.cos(th)
            ])
            y_border = np.array([
                y + 0.5 * self.marker_size * np.sin(th),
                y - 0.5 * self.marker_size * np.sin(th)
            ])

            # plotting and keep the handle
            h = self.ax.plot(x_border, y_border, 'r-', lw=2)
            self.marker_handles[mmap[map_entry]["id"]] = h

        # draw camera at (0, 0)
        cam_wedge = mpatches.Wedge((0, 3.0),
                                   .2,
                                   75,
                                   105,
                                   facecolor="blue",
                                   alpha=0.75)
        self.cam_handle = self.ax.add_patch(cam_wedge)
Exemplo n.º 21
0
    def get_points(self):
        if self._invalid:
            points = self._viewLim.get_points().copy()

            # Scale angular limits to work with Wedge.
            points[:, 0] *= 180 / np.pi
            if points[0, 0] > points[1, 0]:
                points[:, 0] = points[::-1, 0]

            # Scale radial limits based on origin radius.
            points[:, 1] -= self._originLim.y0

            # Scale radial limits to match axes limits.
            rscale = 0.5 / points[1, 1]
            points[:, 1] *= rscale
            width = min(points[1, 1] - points[0, 1], 0.5)

            # Generate bounding box for wedge.
            wedge = mpatches.Wedge(self._center,
                                   points[1, 1],
                                   points[0, 0],
                                   points[1, 0],
                                   width=width)
            self.update_from_path(wedge.get_path())

            # Ensure equal aspect ratio.
            w, h = self._points[1] - self._points[0]
            if h < w:
                deltah = (w - h) / 2.0
                deltaw = 0.0
            elif w < h:
                deltah = 0.0
                deltaw = (h - w) / 2.0
            else:
                deltah = 0.0
                deltaw = 0.0
            self._points += np.array([[-deltaw, -deltah], [deltaw, deltah]])

            self._invalid = 0

        return self._points
Exemplo n.º 22
0
    def _render_on_subplot(self, subplot):
        """
        TESTS::

            sage: D = disk((2,-1), 2, (0, pi), color='black', thickness=3, fill=False); D
        """
        import matplotlib.patches as patches        
        options = self.options()
        deg1 = self.rad1*(180./pi) #convert radians to degrees 
        deg2 = self.rad2*(180./pi)
        z = int(options.pop('zorder', 0))
        p = patches.Wedge((float(self.x), float(self.y)), float(self.r), float(deg1),
                            float(deg2), zorder=z)
        p.set_linewidth(float(options['thickness']))
        p.set_fill(options['fill'])
        p.set_alpha(options['alpha'])
        c = to_mpl_color(options['rgbcolor'])
        p.set_edgecolor(c)
        p.set_facecolor(c)
        p.set_label(options['legend_label'])
        subplot.add_patch(p)
Exemplo n.º 23
0
    def plot_2D_vehicle(self, ax, vehicle):
        '''plot vehicle
        '''

        lidar = mpatches.Wedge((vehicle.location[0], vehicle.location[1]),
                               vehicle.lidar_length,
                               vehicle.lidar_theta[0],
                               vehicle.lidar_theta[1],
                               width=None,
                               fc='g',
                               alpha=0.3)

        loc = mpatches.Rectangle((vehicle.location[0], vehicle.location[1]),
                                 1,
                                 1,
                                 fc='k')

        ax.add_patch(lidar)
        ax.add_patch(loc)

        return ax
Exemplo n.º 24
0
def _draw_nucleotide_keys(keys_required: Optional[List[str]],
                          keys_optional: Optional[List[str]],
                          center: Sequence[float],
                          nucleotide_body_patch: patches.Circle,
                          subplot: plt_axes.Subplot,
                          color, radius=10.0, width=5.0,
                          theta_min=0, theta_max=180):
    # pylint: disable=too-many-arguments
    # not possible to have less arguments without more complexity
    # pylint: disable=too-many-locals
    # is not possible to split the method without more complexity
    keys_required = keys_required or []
    keys_optional = keys_optional or []

    keys_all = keys_required + keys_optional

    if not keys_all:
        return None

    number_of_keys = len(keys_all)
    theta_delta = (theta_max - theta_min) / number_of_keys
    thetas = np.arange(theta_min, theta_max, theta_delta)
    key_patches = {}
    for each_key, each_start_theta in zip(keys_all, thetas):
        hatch = "x" if each_key in keys_optional else None
        theta1 = each_start_theta
        theta2 = theta1 + theta_delta
        key_patch = patches.Wedge(
            center, radius + width, theta1, theta2, width=width,
            facecolor=color, hatch=hatch, edgecolor="white")
        key_patches[each_key] = key_patch

        text_object = _draw_key_text(
            each_key, center, theta1, theta2, radius, width, subplot)
        key_patch.add_callback(partial(
            _nucleotide_key_text_callback,
            text_object=text_object,
            nucleotide_body_patch=nucleotide_body_patch))
        subplot.add_patch(key_patch)
    return key_patches
Exemplo n.º 25
0
def step(cur_h, cur_depth):
    global done, all_nodes, all_lines
    done += 1
    a = 2. * pi * cur_h.toFloat()
    b = a + 2. * pi / (2**(cur_depth))
    print("step", cur_h, cur_depth)
    arc = ringx.add_patch(
        mpatches.Wedge([
            0.,
            0,
        ],
                       1.,
                       a * 180 / pi,
                       b * 180 / pi,
                       fill=True,
                       color="blue",
                       alpha=0.5))
    lines = ringx.plot([0, cos(a)], [0, sin(a)], 'k-', lw=1.2)
    all_lines.extend(lines)
    r.get(
        cur_h, gcb, lambda d, nodes: loop.call_soon_threadsafe(
            nextstep, cur_h, cur_depth, d, nodes, arc, lines))
Exemplo n.º 26
0
    def __init__(self, xy, r, theta1, theta2, fc, ec, width, lw, mplprops,
                 figure):
        self.xy = xy
        self.r = r
        self.theta1 = theta1
        self.theta2 = theta2
        self.mplprops = mplprops
        self.figure = figure
        self.width = width
        self.maple = "12"

        wedge = patches.Wedge(xy,
                              r,
                              theta1,
                              theta2,
                              width,
                              fc=fc,
                              ec=ec,
                              lw=lw,
                              **self.mplprops)
        self.matplotlib_obj = wedge
        self.patch = self.figure.ax.add_patch(self.matplotlib_obj)
Exemplo n.º 27
0
def test_patch_str():
    """
    Check that patches have nice and working `str` representation.

    Note that the logic is that `__str__` is defined such that:
    str(eval(str(p))) == str(p)
    """
    p = mpatches.Circle(xy=(1, 2), radius=3)
    assert str(p) == 'Circle(xy=(1, 2), radius=3)'

    p = mpatches.Ellipse(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Ellipse(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Rectangle(xy=(1, 2), width=3, height=4, angle=5)
    assert str(p) == 'Rectangle(xy=(1, 2), width=3, height=4, angle=5)'

    p = mpatches.Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)
    assert str(p) == 'Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)'

    p = mpatches.Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)
    expected = 'Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)'
    assert str(p) == expected
Exemplo n.º 28
0
 def AddAgent(self,name,radius,color,data,show_circle=False,circle_rad = 10):
     #agt = plt.Circle((0.0, 0.0), radius=radius, fc=color)
     agt = self.GetTriangle(radius,(0.0,0,0),(1.0,0.0),color)
     self.ax.add_patch(agt)
     self.agents.append(agt)
     self.agentNames.append(name)
     self.data[name] = data
     self.minlen = len(data['positionNED'])
     line, = plt.plot(0,0)
     self.paths[name] = line
     self.agentsRadius[name] = radius
     if show_circle:
         circlePatch = plt.Circle((0, 0), radius=circle_rad, fc='y',alpha=0.5)
         self.circle[name] = circlePatch
         self.ax.add_patch(circlePatch)
         # Draw bands
         sectors = []
         for i in range(10):
             ep = patches.Wedge((0,0),circle_rad,theta1=0,theta2=0,fill=True,alpha=0.6)
             sectors.append(ep)
             self.ax.add_patch(ep)
         self.bands[name] = sectors
Exemplo n.º 29
0
def get_angle_intensity_glyphs(xy, angles, magnitudes, **kwargs):
    """Returns a list of pie glyphs at coordinates xy representing values

    Parameters
    ----------
    xy: array
        An (N, 2) array of the xy coordinates of the glyphs.
    angles: float radians
        An (N, ) array of the angles of the glyphs.
    magnitudes: float
        An (N, ...) array of the magnitudes of the glyphs.
    """
    assert len(xy) == len(magnitudes), \
        "Each value needs exactly one coodrinate."
    assert len(xy) == len(angles), \
        "Each value needs exactly one coodrinate."
    # Normalize angles to [0, 1] range
    angles = np.mod(angles * 0.5 / np.pi, 1.0)
    # Assign angle to hue, and magnitude value in hsv colorspace
    hsv = np.ones([len(magnitudes), 3])
    hsv[:, 0] = angles
    hsv[:, 2] = magnitudes
    # Determine properties of each glyph
    wedge_arc = 120  # degrees
    wedge_start = angles * 360
    wedge_color = hsv_to_rgb(hsv)
    # Create pie wedges
    wedges = list()
    for i in range(len(xy)):
        wedges.append(
            patches.Wedge(
                xy[i],
                0.5,  # radius
                wedge_start[i],
                wedge_start[i] + wedge_arc,
                color=wedge_color[i],
                linewidth=0,  # otherwise wedges overlap
                **kwargs))
    return wedges
Exemplo n.º 30
0
def PlotWindow(ax, d1, d2, count):
    angle_fraction = 360 / count
    #    angle = angle_fraction * 0.5
    #    x = np.cos(angle*np.pi/180)*d1
    #    y = np.sin(angle*np.pi/180)*d1
    #    x2 = np.cos(angle*np.pi/180)*d2
    #    y2 = np.sin(angle*np.pi/180)*d2
    #    ax.plot((x,x2),(y,y2), "black")
    #    angle = angle_fraction * -0.5
    #    x = np.cos(angle*np.pi/180)*d1
    #    y = np.sin(angle*np.pi/180)*d1
    #    x2 = np.cos(angle*np.pi/180)*d2
    #    y2 = np.sin(angle*np.pi/180)*d2
    #    ax.plot((x,x2),(y,y2), "black")

    wedge1 = mpatches.Wedge((0, 0),
                            d2,
                            angle_fraction * -0.5,
                            angle_fraction * 0.5,
                            width=d2 - d1,
                            ec="black",
                            fc="none")
    ax.add_patch(wedge1)