示例#1
0
    def plotPolicy(self, policy, prefix):
        plt.clf()
        for idx in range(len(policy)):
            i, j = self.env.getStateXY(idx)

            dx = 0
            dy = 0
            if policy[idx] == 0:  # up
                dy = 0.35
            elif policy[idx] == 1:  #right
                dx = 0.35
            elif policy[idx] == 2:  #down
                dy = -0.35
            elif policy[idx] == 3:  #left
                dx = -0.35
            elif self.matrixMDP[i][j] != -1 and policy[idx] == 4:  # termination
                circle = plt.Circle((j + 0.5, self.numRows - i + 0.5 - 1),
                                    0.025,
                                    color='k')
                plt.gca().add_artist(circle)

            if self.matrixMDP[i][j] != -1:
                plt.arrow(j + 0.5,
                          self.numRows - i + 0.5 - 1,
                          dx,
                          dy,
                          head_width=0.05,
                          head_length=0.05,
                          fc='k',
                          ec='k')
            else:
                plt.gca().add_patch(
                    patches.Rectangle(
                        (j, self.numRows - i - 1),  # (x,y)
                        1.0,  # width
                        1.0,  # height
                        facecolor="gray"))

        plt.xlim([0, self.numCols])
        plt.ylim([0, self.numRows])

        for i in range(self.numCols):
            plt.axvline(i, color='k', linestyle=':')
        plt.axvline(self.numCols, color='k', linestyle=':')

        for j in range(self.numRows):
            plt.axhline(j, color='k', linestyle=':')
        plt.axhline(self.numRows, color='k', linestyle=':')

        plt.savefig(self.outputPath + prefix + 'policy.png')
        plt.close()
示例#2
0
def connect(axe, n1, n2, shape, radio, color, order, sign):
    radio2 = radio
    if sign == -1: radio2 = 1.65
    From, To = positions[n1], positions[n2]
    alpha = get_alpha(From, To)
    To_edge = (To[0] - radio2 * np.cos(alpha), To[1] - radio2 * np.sin(alpha))
    From_edge = (From[0] + radio * np.cos(alpha),
                 From[1] + radio * np.sin(alpha))
    arrow_shape = (0.8, 2, 2)

    if sign == -1:
        l = axe.annotate(
            "",
            xy=To_edge,
            xycoords='data',
            xytext=From_edge,
            textcoords='data',
            arrowprops=dict(
                arrowstyle=
                'simple, tail_width = %s, head_width = %s, head_length = %s' %
                (0.8, 0.1, 0.1),
                facecolor=color,
                edgecolor='k',
                connectionstyle=shape),
            alpha=1.0,
            zorder=order)
        c = plt.Circle(To_edge,
                       radius=0.35,
                       fc=color,
                       edgecolor='k',
                       alpha=1.0,
                       zorder=order + 2)
        cir = axe.add_patch(c)

    else:
        arrowprops = dict(
            arrowstyle=
            'simple, tail_width=%.2f,head_width=%.2f,head_length=%.2f' %
            (arrow_shape),
            facecolor=color,
            edgecolor='k',
            linewidth=0.6,
            connectionstyle=shape)
        axe.annotate("",
                     xy=To_edge,
                     xycoords='data',
                     xytext=From_edge,
                     textcoords='data',
                     arrowprops=arrowprops,
                     zorder=order)
示例#3
0
def select_disks_randomly(width, height, n_points, disk_geoms, figsize=(5, 5)):
    xs = np.random.uniform(low=0.0, high=width, size=n_points)
    ys = np.random.uniform(low=0.0, high=height, size=n_points)
    centroids = [(x, y) for (x, y) in zip(xs, ys)]

    fig, ax = plt.subplots(figsize=figsize)
    ax.set(xlim=(0, width), ylim=(0, height))

    for c in centroids:
        geom = plt.Circle(c, radius=1, alpha=0.3, edgecolor='b')
        disk_geoms.append(geom)
        ax.add_artist(geom)

    fig.show()
示例#4
0
def homofire_nowind():
    """
    Simulate fire on homogeneous field with no wind: fire spread rate is (sqrt{n+1} - sqrt{n})*r.
    
    Black shows burned area, red shows burning area, and white shows unburned area.
    """

    r_homo = [1]
    n = 1
    r = 1
    while r > .1:
        r = np.sqrt(n + 1) - np.sqrt(n)
        r_homo.append(r)
        n = n + 1

    radius = np.array(r_homo).cumsum()

    for i in range(len(r_homo) - 1):
        """Red color shows burning areas and black color represents burned areas."""
        if i == 0:
            circle = plt.Circle((0, 0), radius[i], color='red')
            ax = plt.gca()
            ax.set_xlim((-6, 6))
            ax.set_ylim((-6, 6))
            ax.axis('square')
            ax.add_artist(circle)
        else:
            circle1 = plt.Circle((0, 0), radius[i], color='black')
            circle2 = plt.Circle((0, 0), radius[i + 1], color='red')
            ax = plt.gca()
            ax.set_xlim((-6, 6))
            ax.set_ylim((-6, 6))
            ax.axis('square')
            ax.add_artist(circle2)
            ax.add_artist(circle1)
        show_animation()
示例#5
0
    def _plot_dots(self):

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

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

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

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

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

        plt.legend(handlers, labels, bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
                   ncol=3, mode="center", borderaxespad=0.)
示例#6
0
文件: crowd_sim.py 项目: EcustBoy/SCR
 def add_robots(self, robots):
     for i, robot in enumerate(robots):
         robot_circle = plt.Circle(robot.get_position(),
                                   robot.radius,
                                   fill=True,
                                   color='k',
                                   fc='orange')
         self.ax.add_artist(robot_circle)
         goal = mlines.Line2D([robot.get_goal_position()[0]],
                              [robot.get_goal_position()[1]],
                              color='red',
                              marker='*',
                              linestyle='None',
                              markersize=15,
                              label='Goal')
         self.ax.add_artist(goal)
def plotty(X, Y):
    pl.figure(1)
    for i in range(0, len(X) - 1):
        if Y[i] == 1:
            pl.scatter(X[i][0], X[i][1], color='blue')
        else:
            pl.scatter(X[i][0], X[i][1], color='red')

    circle1=pl.Circle((0,0), sqrt(0.6), edgecolor='k', facecolor='none')
    figure = pl.gcf()
    figure.gca().add_artist(circle1)
    pl.axis([-1, 1, -1, 1])
    pl.xlabel('x1 or feature 1')
    pl.ylabel('x2 or feature 2')
    pl.title('Generated Sample Data w/10% Simulated Noise')
    pl.show()
示例#8
0
    def RF_location_plot(self, i, ax=None):

        _, ax, _ = self.ge.matrix(0.4 + 0 * self.model.SCREEN['x_2d'],
                                  vmin=0.,
                                  vmax=1.,
                                  colormap=self.ge.binary_r,
                                  ax=ax)
        circ = plt.Circle(
            (self.model.CELLS['x0'][i] * self.SCREEN['dpd'],
             self.model.CELLS['y0'][i] * self.SCREEN['dpd']),
            radius=self.model.CELLS['size'][i] * self.SCREEN['dpd'],
            facecolor='w',
            fill=True,
            lw=0)
        ax.add_patch(circ)
        ax.axis('off')
def mag_plot():
    fnames, p1, p2, p3, _, _ = load_data(uvis=True, radec=True)
    hdu = fits.open(fnames[0])
    mag = hdu[1].data.f275w_vega
    recovered, = np.nonzero((mag < 24))

    c1 = np.array([10.69346, 41.26869])
    c2 = np.array([10.70488, 41.26733])
    c3 = np.array([10.71671, 41.26608])

    ra = hdu[1].data.ra[recovered]
    dec = hdu[1].data.dec[recovered]
    mag = mag[recovered]
    grid = np.column_stack((ra, dec))

    cols = ['c', 'm', 'y']
    ax = plt.subplots()[1]

    #img = fits.open('hst_12058_10_wfc3_uvis_f275w_drz.fits')
    #ax.imshow(img[2].data, cmap=plt.cm.Greys)
    #all_inds = np.array([], dtype=np.int)
    for p, c in zip([p1, p2, p3], [c1, c2, c3]):
        ax.plot(p[:, 0], p[:, 1], color='k')
        circ = plt.Circle(c, radius=0.0075, color='k', fill=False)
        ax.add_artist(circ)
        ax.plot(c[0], c[1], '+', color='k', ms=30)
        #path = Path(p)
        #isInside = path.contains_points(grid)
        #inds, = np.nonzero(isInside)
        #all_inds = np.append(all_inds, inds)

    all_inds, = np.nonzero((ra < 10.73) & (ra > 10.5) & \
                           (dec > 41.23) & (dec < 41.33))
    sort = np.argsort(mag[all_inds])[::-1]
    s = np.zeros(len(sort)) + 20
    bright, = np.nonzero(mag[all_inds][sort] < 20)
    s[bright] = 50
    l = ax.scatter(ra[all_inds][sort], dec[all_inds][sort],
                   c=mag[all_inds][sort], cmap=plt.cm.Greys_r, alpha=0.9, s=s,
                   linewidths=0)
    [ax.annotate(r'$%.2f$' % mag[all_inds][sort][b], (ra[all_inds][sort][b],
                dec[all_inds][sort][b])) for b in bright]
    plt.colorbar(l)
    ax.set_xlim(ax.get_xlim()[::-1])
    ticklabel_format(style='scientific', useOffset=False)
    ax.set_xlabel('$RA$')
    ax.set_ylabel('$DEC$')
示例#10
0
    def show_CaImaging_FOV(self,
                           key='meanImg',
                           NL=1,
                           cmap='viridis',
                           ax=None,
                           roiIndex=None,
                           with_roi_zoom=False):

        if ax is None:
            fig, ax = ge.figure()
        else:
            fig = None

        img = self.nwbfile.processing['ophys'].data_interfaces[
            'Backgrounds_0'].images[key][:]
        img = (img - img.min()) / (img.max() - img.min())
        img = np.power(img, 1 / NL)
        ax.imshow(img,
                  vmin=0,
                  vmax=1,
                  cmap=cmap,
                  aspect='equal',
                  interpolation='none')
        ax.axis('off')

        if roiIndex is not None:
            indices = np.arange(self.pixel_masks_index[roiIndex],
                                self.pixel_masks_index[roiIndex + 1])
            x = np.mean([self.pixel_masks[ii][1] for ii in indices])
            sx = np.std([self.pixel_masks[ii][1] for ii in indices])
            y = np.mean([self.pixel_masks[ii][0] for ii in indices])
            sy = np.std([self.pixel_masks[ii][1] for ii in indices])
            # ellipse = plt.Circle((x, y), sx, sy)
            ellipse = plt.Circle((x, y),
                                 1.5 * (sx + sy),
                                 edgecolor='r',
                                 facecolor='none',
                                 lw=3)
            ax.add_patch(ellipse)
            if with_roi_zoom:
                ax.set_xlim([x - 10 * sx, x + 10 * sx])
                ax.set_ylim([y - 10 * sy, y + 10 * sy])

        ge.title(ax, key)

        return fig, ax
  def plot_policy(self, policy, prefix, policy_folder):
    plt.clf()
    for idx in range(len(policy)):
      i, j = self.env.get_state_xy(idx)

      dx = 0
      dy = 0
      if policy[idx] == 0:  # up
        dy = 0.35
      elif policy[idx] == 1:  # right
        dx = 0.35
      elif policy[idx] == 2:  # down
        dy = -0.35
      elif policy[idx] == 3:  # left
        dx = -0.35
      elif self.env.not_wall(i, j) and policy[idx] == 4:  # termination
        circle = plt.Circle(
          (j + 0.5, self.config.input_size[0] - i + 0.5 - 1), 0.025, color='k')
        plt.gca().add_artist(circle)

      if self.env.not_wall(i, j):
        plt.arrow(j + 0.5, self.config.input_size[0] - i + 0.5 - 1, dx, dy,
                  head_width=0.05, head_length=0.05, fc='k', ec='k')
      else:
        plt.gca().add_patch(
          patches.Rectangle(
            (j, self.config.input_size[0] - i - 1),  # (x,y)
            1.0,  # width
            1.0,  # height
            facecolor="gray"
          )
        )

    plt.xlim([0, self.config.input_size[1]])
    plt.ylim([0, self.config.input_size[0]])

    for i in range(self.config.input_size[1]):
      plt.axvline(i, color='k', linestyle=':')
    plt.axvline(self.config.input_size[1], color='k', linestyle=':')

    for j in range(self.config.input_size[0]):
      plt.axhline(j, color='k', linestyle=':')
    plt.axhline(self.config.input_size[0], color='k', linestyle=':')

    plt.savefig(os.path.join(policy_folder, "SuccessorFeatures_" + prefix + 'policy.png'))
    plt.close()
示例#12
0
文件: crowd_sim.py 项目: EcustBoy/SCR
 def add_humans(self, humans):
     self.reset_axis()
     for i, human in enumerate(humans):
         human_circle = plt.Circle(human.get_position(),
                                   human.radius,
                                   fill=False,
                                   color=self.cmap(i))
         self.ax.add_artist(human_circle)
         goal = mlines.Line2D([human.get_goal_position()[0]],
                              [human.get_goal_position()[1]],
                              color=self.cmap(i),
                              marker='*',
                              linestyle='None',
                              markersize=15,
                              label='Goal',
                              fillstyle='none')
         self.ax.add_artist(goal)
示例#13
0
def drawFDO(humo, orb, fig=None, ax=None):
    assert hasattr(humo, 'xyz')
    assert hasattr(humo, 'atoms')
    assert hasattr(humo, 'links')

    if fig is None or ax is None:
        fig, ax = plt.subplots()

    xy = molskeleton.draw(fig, ax, humo.xyz, humo.atoms, humo.links)

    for i in xrange(humo.n):
        color = 'r' if np.real(orb[i]) < 0 else 'b'
        # print(tuple(xy[i, 0:2]))
        # print(orb[i])
        circle = plt.Circle(tuple(xy[i, 0:2]),
                            np.abs(orb[i]) * 60,
                            color=color,
                            zorder=10)
        ax.add_artist(circle)
示例#14
0
def draw_circle_around_clique(clique, coords, color):
    dist = 0
    temp_dist = 0
    center = [0 for i in range(2)]
    for a in clique:
        for b in clique:
            temp_dist = (coords[a][0] - coords[b][0])**2 + (coords[a][1] -
                                                            coords[b][1])**2
            if temp_dist > dist:
                dist = temp_dist
                for i in range(2):
                    center[i] = (coords[a][i] + coords[b][i]) / 2
    rad = dist**0.5 / 2
    cir = plt.Circle((center[0], center[1]),
                     radius=rad * 1.3,
                     fill=False,
                     color=color,
                     hatch=next(hatches))
    plt.gca().add_patch(cir)
    plt.axis('scaled')
示例#15
0
    def snapshot(self):
        """Function creates a snapshot of the pendulum.
        
        
        TODO:
        ----
            Still a scelecton.
        
        """
        
        
        Lcolor='green'
        Icolor='red'
        Llwidth=3
        ILwidth=3

        fig=plt.figure() 
        ax = plt.axes(xlim=(-3,3), ylim=(-3, 3))
        plt.hold(True)
        
        plt.axes().set_aspect('equal')
        #L shape:
        #p2->p3
        
        
        t=zip(self.p2,p3)
        ax.plot(t[0],t[1],color=Lcolor,linewidth=Llwidth)
        #p3->p5
        t=zip(p3,p5)
        ax.plot(t[0],t[1],color=Lcolor,linewidth=Llwidth)

        #plt.plot(,color=Lcolor)
        #I shape:
        #p2->p4
        t=zip(p2,p4)
        ax.plot(t[0],t[1],color=Icolor,linewidth=Ilwidth)
        
        #splt.plot(,color=Icolor)
        for piv in allpivots:
            circle=plt.Circle(piv,l1*0.05,color='black')
            fig.gca().add_artist(circle)
示例#16
0
 def linkage_plot(self, alpha=0.1, linewidth=1, nofig=False):
     """
     Display segmentation regions and linkage using arcs
     """
     if not nofig:
         pl.figure()
     ax = pl.gca()
     cols = ['r', 'g', 'b', 'c', 'm', 'y', 'k']
     for k in range(self.num_clusters):
         kpos = np.where(self.assigns[self.diffs[:-1]] == k)
         for j in self.diffs[kpos]:
             for l in self.diffs[kpos]:
                 arc = pl.Circle(((l + j) / 2.0, 0.),
                                 radius=abs(l - j) / 2.0,
                                 color=cols[k % len(cols)],
                                 fill=0,
                                 linewidth=linewidth,
                                 alpha=alpha)
                 ax.add_patch(arc)
     pl.show()
     pl.axis([0, self.F.X.shape[1], 0, self.F.X.shape[1] / 2.])
     pl.colorbar()
示例#17
0
def plot(ax, cs, points, title: str):
    cs = np.array(cs)
    ax.set_title(title)
    ax.scatter(points[:, 0],
               points[:, 1],
               marker='o',
               alpha=0.6,
               c='red',
               label='data points')
    ax.scatter(cs[:, 0],
               cs[:, 1],
               alpha=0.6,
               marker='x',
               c='blue',
               label='centroids')
    ax.legend()

    ax.set_xlim(0, 100)
    ax.set_ylim(0, 100)

    for c in cs:
        ax.add_artist(plt.Circle(c, radius, color='yellow', alpha=0.2))
示例#18
0
def plot_cluster(fpath=None,save_dir=None,addBackground=True,circle=True,instrument='eROSITA'):
    cluster_ar = read_cluster(fpath=fpath)
    
    plt.figure(figsize=(4,4))
    file_name = Path(fpath).stem
    cluster_row = clusterList[clusterList['id']==int(file_name)]
    log_m = np.log10(cluster_row['M500_msolh'])[0]
    
    if circle:
        r_pixel = int(cluster_row['R500_pixel'][0])
        circle = plt.Circle((mid_pixel, mid_pixel), r_pixel, color="red",fill=False,zorder=2000)
        ax.add_patch(circle)
    plt.title(r'$\log\left(\frac{M_\mathrm{500c}}{h^{-1}\,M_\odot}\right) = $'+'{:.2f}'.format(log_m))
    
    cmap = mpl.cm.viridis
    lam = 0.1133929878
    noise = np.random.poisson(lam=lam, size=cluster.shape)

    plt.imshow(noise,cmap=cmap)
    im = plt.imshow(np.log10(cluster),cmap=cmap,interpolation='none')

    ax = plt.gca()
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.12)

    plt.colorbar(im, cax=cax)
    ax.set_xticks(np.linspace(0,,7))
    ax.set_yticks(np.linspace(0,384,7))

    ax.set_xlabel("x"), ax.set_ylabel("y")
    ax.set_facecolor('#DADADA')
    plt.tight_layout()
    #plt.savefig('../figs/eROSITA/' + file_name + '.png',dpi=250,bbox_inches='tight')

    ax.invert_yaxis()

    plt.close()
    
    return None
示例#19
0
def movPlot(ax,xC,yC,aL,xM,yM,xT,yT):
    
    """
    plot the 2D motion of a single cobra over a convergence run. Generally called by badCobraDiagram.

    input: 
       ax: axis on which to plot the diagram
       xC, yC, aL: centres and armlengths for cobra patrol regions
       xM, yM: measured positions (same units as above)
       xT, yT: target positions (same units as above)
    
    output: plot to the provided axis

    """

    #sequence of colours for spots, goes basically red -> purple in chromatic order
    
    cols=['firebrick','orangered','orange','yellow','yellowgreen','green','teal','cornflowerblue','blue','purple','firebrick','orangered','orange','yellow','yellowgreen','green','teal','cornflowerblue','blue','purple']

    nIter = len(xM)
    
    #plot the motions in sequence
    for i in range(nIter):
        ax.scatter(xM[i],yM[i],color=cols[i])

    
    #draw patrol region and center
    circle=plt.Circle((xC,yC),aL,fill=False,color='black')
    a=ax.add_artist(circle)
    a=ax.scatter(xC,yC,color='black')

    #target - black adn white x so it shows over background and spots
    a=ax.scatter(xT,yT,c='black',marker="+",s=80)
    a=ax.scatter(xT,yT,c='white',marker="x",s=80)

    #adjust limits
    a=ax.set_xlim((xC-aL*1.3,xC+aL*1.3))
    a=ax.set_ylim((yC-aL*1.3,yC+aL*1.3))
    a=ax.set_aspect('equal')
def draw_circle_around_clique(clique, coords):
    dist = 0
    temp_dist = 0
    center = [0 for i in range(2)]
    color = colors.next()
    for a in clique:
        for b in clique:
            temp_dist = (coords[a][0] - coords[b][0])**2 + (coords[a][1] -
                                                            coords[b][1])**2
            if temp_dist > dist:
                dist = temp_dist
                for i in range(2):
                    center[i] = (coords[a][i] + coords[b][i]) / 2
    rad = dist**0.5 / 2
    cir = plt.Circle((center[0], center[1]),
                     radius=rad * 1.3,
                     fill=False,
                     color=color,
                     hatch=hatches.next())
    plt.gca().add_patch(cir)
    plt.axis('scaled')
    # return color of the circle, to use it as the color for vertices of the cliques
    return color
示例#21
0
def cplot(fobj, line, *args):
    n = 100
    x1 = np.linspace(-3.5, 2, n)
    x2 = np.linspace(-3.5, 2, n)
    X1, X2 = np.meshgrid(x1, x2)
    f = np.zeros((n, n))

    if line:
        for j in range(n):
            for i in range(n):
                f[i, j] = fobj([X1[i, j], X2[i, j]])
        fig, ax = plt.subplots(1, 1)
        ax.contour(X1, X2, f)

    else:
        # Query the function at the specified locations
        for i in range(n):
            for j in range(n):
                f[i, j] = fobj([X1[i, j], X2[i, j]])

        fig, ax = plt.subplots(1, 1)
        ax.contourf(X1, X2, f)

    #this is the constraint
    circ = plt.Circle((0, 0), 2**0.5, color='r', fill=False, linestyle='-')
    ax.add_artist(circ)

    if len(args) != 0:
        uncon_min = args[0]
        x_star = args[1]
        ax.plot(uncon_min[0], uncon_min[1], 'ro')
        ax.plot(x_star[0], x_star[1], 'ko')

    ax.set_aspect('equal', 'box')
    fig.tight_layout()
    plt.xlabel('x1')
    plt.ylabel('x2')
示例#22
0
        def draw_pies(axis, fractal, cent, rad, reverseY):

            c = plt.Circle(cent.T, rad, ec='k', fc=None, fill=False)
            axis.add_patch(c)
            fractal2 = (fractal - self.minval) / (self.maxval - self.minval)
            for val, e1, e2 in zip(fractal2, self.edges[:-1], self.edges[1:]):
                w = patches.Wedge(cent.T,
                                  rad,
                                  e1,
                                  e2,
                                  ec='k',
                                  fc='k',
                                  alpha=0.1)
                axis.add_patch(w)
                if reverseY:
                    x = -rad * np.cos(e1 * np.pi / 180.0)
                    y = rad * np.sin(e1 * np.pi / 180.0)
                    ee2 = 180.0 * np.arctan2(y, x) / np.pi
                    x = -rad * np.cos(e2 * np.pi / 180.0)
                    y = rad * np.sin(e2 * np.pi / 180.0)
                    ee1 = 180.0 * np.arctan2(y, x) / np.pi
                    w = patches.Wedge(cent.T,
                                      rad,
                                      ee1,
                                      ee2,
                                      ec=plt.cm.RdYlBu_r(val),
                                      fc=plt.cm.RdYlBu_r(val),
                                      width=5)
                else:
                    w = patches.Wedge(cent.T,
                                      rad,
                                      e1,
                                      e2,
                                      ec=plt.cm.RdYlBu_r(val),
                                      fc=plt.cm.RdYlBu_r(val),
                                      width=5)
                axis.add_patch(w)
示例#23
0
    def plot_network(self,
                     state_sizes=None,
                     state_scale=1.0,
                     state_colors='#ff5500',
                     state_labels='auto',
                     arrow_scale=1.0,
                     arrow_curvature=1.0,
                     arrow_labels='weights',
                     arrow_label_format='%10.2f',
                     max_width=12,
                     max_height=12,
                     figpadding=0.2,
                     xticks=False,
                     yticks=False,
                     show_frame=False,
                     **textkwargs):
        """
        Draws a network using discs and curved arrows.

        The thicknesses and labels of the arrows are taken from the off-diagonal matrix elements in A.

        """
        if self.pos is None:
            self.layout_automatic()
        # number of nodes
        n = len(self.pos)
        # get bounds and pad figure
        xmin = np.min(self.pos[:, 0])
        xmax = np.max(self.pos[:, 0])
        Dx = xmax - xmin
        xmin -= Dx * figpadding
        xmax += Dx * figpadding
        Dx *= 1 + figpadding
        ymin = np.min(self.pos[:, 1])
        ymax = np.max(self.pos[:, 1])
        Dy = ymax - ymin
        ymin -= Dy * figpadding
        ymax += Dy * figpadding
        Dy *= 1 + figpadding
        # sizes of nodes
        if state_sizes is None:
            state_sizes = 0.5 * state_scale * \
                min(Dx, Dy)**2 * np.ones(n) / float(n)
        else:
            state_sizes = 0.5 * state_scale * \
                min(Dx, Dy)**2 * state_sizes / (np.max(state_sizes) * float(n))
        # automatic arrow rescaling
        arrow_scale *= 1.0 / \
            (np.max(self.A - np.diag(np.diag(self.A))) * math.sqrt(n))
        # size figure
        if (Dx / max_width > Dy / max_height):
            figsize = (max_width, Dy * (max_width / Dx))
        else:
            figsize = (Dx / Dy * max_height, max_height)
        fig = plt.gcf()
        fig.set_size_inches(figsize, forward=True)
        # font sizes
        old_fontsize = rcParams['font.size']
        rcParams['font.size'] = 20
        # remove axis labels
        frame = plt.gca()
        if not xticks:
            frame.axes.get_xaxis().set_ticks([])
        if not yticks:
            frame.axes.get_yaxis().set_ticks([])
        # show or suppress frame
        frame.set_frame_on(show_frame)
        # set node labels
        if state_labels is 'auto':
            state_labels = [str(i) for i in np.arange(n)]
        else:
            assert len(
                state_labels
            ) == n, "Mistmatch between nstates and nr. state_labels (%u vs %u)" % (
                n, len(state_labels))
        # set node colors
        if state_colors is None:
            state_colors = '#ff5500'  # None is not acceptable
        if isinstance(state_colors, str):
            state_colors = [state_colors] * n
        if isinstance(state_colors, list):
            assert len(
                state_colors
            ) == n, "Mistmatch between nstates and nr. state_colors (%u vs %u)" % (
                n, len(state_colors))
        try:
            colorscales = _types.ensure_ndarray(state_colors,
                                                ndim=1,
                                                kind='numeric')
            colorscales /= colorscales.max()
            state_colors = [
                plt.cm.binary(int(256.0 * colorscales[i])) for i in range(n)
            ]
        except:
            pass  # assume we have a list of strings now.
        # set arrow labels
        if isinstance(arrow_labels, np.ndarray):
            L = arrow_labels
        else:
            L = np.empty(np.shape(self.A), dtype=object)
        if arrow_labels is None:
            L[:, :] = ''
        elif arrow_labels.lower() == 'weights':
            for i in range(n):
                for j in range(n):
                    L[i, j] = arrow_label_format % self.A[i, j]
        else:
            rcParams['font.size'] = old_fontsize
            raise ValueError('invalid arrow label format')

        # Set the default values for the text dictionary
        textkwargs.setdefault('size', 14)
        textkwargs.setdefault('horizontalalignment', 'center')
        textkwargs.setdefault('verticalalignment', 'center')
        textkwargs.setdefault('color', 'black')

        # draw circles
        circles = []
        for i in range(n):
            fig = plt.gcf()
            # choose color
            c = plt.Circle(self.pos[i],
                           radius=math.sqrt(0.5 * state_sizes[i]) / 2.0,
                           color=state_colors[i],
                           zorder=2)
            circles.append(c)
            fig.gca().add_artist(c)
            # add annotation
            plt.text(self.pos[i][0],
                     self.pos[i][1],
                     state_labels[i],
                     zorder=3,
                     **textkwargs)

        assert len(circles) == n, "%i != %i" % (len(circles), n)

        # draw arrows
        for i in range(n):
            for j in range(i + 1, n):
                if (abs(self.A[i, j]) > 0):
                    self._draw_arrow(self.pos[i, 0],
                                     self.pos[i, 1],
                                     self.pos[j, 0],
                                     self.pos[j, 1],
                                     Dx,
                                     Dy,
                                     label=str(L[i, j]),
                                     width=arrow_scale * self.A[i, j],
                                     arrow_curvature=arrow_curvature,
                                     patchA=circles[i],
                                     patchB=circles[j],
                                     shrinkA=3,
                                     shrinkB=0)
                if (abs(self.A[j, i]) > 0):
                    self._draw_arrow(self.pos[j, 0],
                                     self.pos[j, 1],
                                     self.pos[i, 0],
                                     self.pos[i, 1],
                                     Dx,
                                     Dy,
                                     label=str(L[j, i]),
                                     width=arrow_scale * self.A[j, i],
                                     arrow_curvature=arrow_curvature,
                                     patchA=circles[j],
                                     patchB=circles[i],
                                     shrinkA=3,
                                     shrinkB=0)

        # plot
        plt.xlim(xmin, xmax)
        plt.ylim(ymin, ymax)
        rcParams['font.size'] = old_fontsize
        return fig
示例#24
0
               extent=(xleft, xright, ylower, yupper))
    lambda_obs = np.arange(xleft, xright, separation[i])
    ax1.set_xticks(lambda_obs)

    for j in range(0, len(name)):
        if z != 0:
            xcoords = [(1 + z) * rest_lambda[j]]
            for xc in xcoords:
                if xc < xright and xc > xleft:
                    plt.axvline(xc, color='r', lw=1.5, linestyle=':')

    for k in range(0, len(detected_lines)):
        if detected_lines[k] != 99:
            circle = plt.Circle((detected_lines[k], 12),
                                20,
                                color='r',
                                fill=False,
                                lw=1)
            ax = fig.gca()
            ax.add_artist(circle)

    ax2 = fig.add_axes(ax1.get_position(), frameon=False)
    ax2.tick_params(labelbottom='off',
                    labeltop='on',
                    labelleft='off',
                    labelright='off',
                    bottom='off',
                    left='off',
                    right='off')
    ax2.set_xlim(ax1.get_xlim())
    ax2.set_xticks(lambda_obs)
示例#25
0
def affichage_polaire(limits, ax, list_obstacles, dico, fig):
    """
        Affichage.

    """

    # Liste des points détectés aux extrémités d'un obstacle
    list_detected = []
    for detected in limits:
        for n in range(len(detected)):
            list_detected.append(detected[n])

    # Mise en place du graphe
    ax.clear()
    ax.set_xlim(0, 2 * pi)
    ax.set_ylim(0, +distance_max)
    ax.axhline(0, 0)
    ax.axvline(0, 0)

    for o in list_obstacles:

        # Ajout de la position mesurée de l'obstacle
        angle = o.center
        r = dico[angle]
        _loggerAffichage.debug("nb_obstacles: %s.", len(list_obstacles))
        circle = pl.Circle((r * cos(angle), -r * sin(angle)),
                           o.width / 2,
                           transform=ax.transData._b,
                           color='m',
                           alpha=0.4)  # Attention: -y
        ax.add_artist(circle)

        # Ajout de la position Kalman de l'obstacle
        if o.get_predicted_kalman() is not None:
            x_kalman = o.get_predicted_kalman()[0][0]
            y_kalman = o.get_predicted_kalman()[0][2]
            _loggerAffichage.debug("position kalman: x = %s et y = %s.",
                                   x_kalman, y_kalman)
            circle = pl.Circle((x_kalman, -y_kalman),
                               o.width / 2,
                               transform=ax.transData._b,
                               color='g',
                               alpha=0.4)  # Attention: -y
            ax.add_artist(circle)

        # Ajout des précédentes positions Kalman de l'obstacle
        if o.get_piste_obstacle() is not None:
            _loggerAffichage.debug("piste : %s.", o.get_piste_obstacle())
            for elt_piste in o.get_piste_obstacle():
                x_elt = elt_piste[0]
                y_elt = elt_piste[1]
                circle = pl.Circle((x_elt, -y_elt),
                                   8,
                                   transform=ax.transData._b,
                                   color='darkolivegreen',
                                   alpha=0.4)
                ax.add_artist(circle)

    # Listes des positions des obstacles à afficher
    detected_r = [dico[detected] for detected in list_detected]
    detected_theta = [-detected
                      for detected in list_detected]  # Attention: -theta

    # Listes des positions des points à afficher
    r = [distance for distance in dico.values()]
    theta = [-angle for angle in dico.keys()]  # Attention: -theta

    pl.plot(detected_theta, detected_r, 'bo', markersize=1.8)
    pl.plot(theta, r, 'ro', markersize=0.6)

    # Affichage
    pl.grid()
    fig.canvas.draw()
示例#26
0
def affichage_cartesien(limits, ax, list_obstacles, dico, fig):
    """
        Affichage.

    """

    # Liste des points détectés aux extrémités d'un obstacle
    list_detected = []
    for detected in limits:
        for n in range(len(detected)):
            list_detected.append(detected[n])

    # Mise en place du graphe
    ax.clear()
    ax.set_xlim(-distance_max_x_cartesien / 2, distance_max_x_cartesien / 2)
    ax.set_ylim(-distance_max_y_cartesien / 2, distance_max_y_cartesien / 2)
    ax.axhline(0, 0)
    ax.axvline(0, 0)
    pl.grid()

    for o in list_obstacles:

        # Ajout de la position mesurée de l'obstacle
        angle = o.center
        r = dico[angle]
        _loggerAffichage.debug("nb_obstacles: %s.", len(list_obstacles))
        circle = pl.Circle((r * cos(angle), -r * sin(angle)),
                           radius=200,
                           fc='orange')  # Attention: -y
        ax.add_artist(circle)

        # Ajout de la position Kalman de l'obstacle
        if o.get_predicted_kalman() is not None:
            x_kalman = o.get_predicted_kalman()[0][0]
            y_kalman = o.get_predicted_kalman()[0][2]
            _loggerAffichage.debug("position kalman: x = %s et y = %s.",
                                   x_kalman, y_kalman)
            circle = pl.Circle((x_kalman, -y_kalman), radius=200,
                               fc='crimson')  # Attention: -y
            ax.add_artist(circle)

        # Ajout des précédentes positions Kalman de l'obstacle
        if o.get_piste_obstacle() is not None:
            _loggerAffichage.debug("piste : %s.", o.get_piste_obstacle())
            for elt_piste in o.get_piste_obstacle():
                x_elt = elt_piste[0]
                y_elt = elt_piste[1]
                circle = pl.Circle((x_elt, -y_elt), radius=20,
                                   fc='black')  # Attention: -y
                ax.add_artist(circle)

    # Listes des positions des obstacles à afficher
    detected_x = [dico[detected] * cos(detected) for detected in list_detected]
    detected_y = [
        -dico[detected] * sin(detected) for detected in list_detected
    ]  # Attention: -y

    # Listes des positions des points à afficher
    x = [
        distance * cos(angle)
        for distance, angle in zip(dico.values(), dico.keys())
    ]
    y = [
        -distance * sin(angle)
        for distance, angle in zip(dico.values(), dico.keys())
    ]  # Attention: -y

    pl.plot(detected_x, detected_y, 'bo', markersize=1.8)
    pl.plot(x, y, 'ro', markersize=0.6)

    # Affichage
    fig.canvas.draw()
示例#27
0
    fig, ax = plt.subplots()
    # Plot field.
    X, Y = np.meshgrid(np.linspace(-WALL_OFFSET, WALL_OFFSET, 30),
                       np.linspace(-WALL_OFFSET, WALL_OFFSET, 30))
    U = np.zeros_like(X)
    V = np.zeros_like(X)
    for i in range(len(X)):
        for j in range(len(X[0])):
            velocity = get_velocity(np.array([X[i, j], Y[i, j]]), args.mode)
            U[i, j] = velocity[0]
            V[i, j] = velocity[1]
    plt.quiver(X, Y, U, V, units='width')

    # Plot environment.
    ax.add_artist(plt.Circle(CYLINDER_POSITION1, CYLINDER_RADIUS,
                             color='gray'))
    ax.add_artist(plt.Circle(CYLINDER_POSITION2, CYLINDER_RADIUS,
                             color='gray'))
    plt.plot([-WALL_OFFSET, WALL_OFFSET], [-WALL_OFFSET, -WALL_OFFSET], 'k')
    plt.plot([-WALL_OFFSET, WALL_OFFSET], [WALL_OFFSET, WALL_OFFSET], 'k')
    plt.plot([-WALL_OFFSET, -WALL_OFFSET], [-WALL_OFFSET, WALL_OFFSET], 'k')
    plt.plot([WALL_OFFSET, WALL_OFFSET], [-WALL_OFFSET, WALL_OFFSET], 'k')

    # Plot a simple trajectory from the start position.
    # Uses Euler integration.
    dt = 0.01
    x = START_POSITION
    positions = [x]
    for t in np.arange(0., 20., dt):
        v = get_velocity(x, args.mode)
        x = x + v * dt
示例#28
0
            r.append(funcion(x2, y2))
            x1.append(x2)
            x1.append(x2)
        else:
            beta = np.random.uniform(low=0, high=1.0, size=1)
            if (beta <= alpha):
                r.append(funcion(x2, y2))
                x1.append(x2)
                y1.append(y2)
            else:
                r.append(r[i])
                x1.append(x1[i])
                y1.append(y1[i])
    return r, x1, y1


erre = metro()[0]
x_1 = metro()[1]
y_2 = metro()[2]
for i in range(len(erre)):
    if (erre[i] == max(erre)):
        mex = x_1[i]
        mey = y_1[i]
plt.figure()
fig, ax = plt.subplots()
plt.axis('equal')
circle1 = plt.Circle((mex, myy), max(erre), color='r', fill=False)
ax.add_artist(circle1)
plt.scatter(x, y)
plt.savefig("Canal_ionico.png")
plt.close()
    dR2_dt2 = sp.array(
        [[-sp.cos(omega * t) * omega**2,
          sp.sin(omega * t) * omega**2, 0],
         [-sp.sin(omega * t) * omega**2, -sp.cos(omega * t) * omega**2, 0],
         [0, 0, 0]])

    zp = sp.zeros(6)
    zp[0:3] = z[3:6]
    z1 = (-G * mt / r**3) * z[0:3] - R.T @ (dR2_dt2 @ z[0:3] +
                                            2 * dR_dt @ z[3:6])
    zp[3:6] = z1
    return zp


plt.figure(1)
a = np.arange(0, 2 * np.pi, .01)
x_at = atmosphere_radius * np.sin(a)
y_at = atmosphere_radius * np.cos(a)
fig, ax = plt.subplots()
sol = odeint(satelite, z0, t)
earth = plt.Circle((0, 0), earth_radius, color="green")
x = sol[:, 0]
y = sol[:, 1]
z = sol[:, 2]
plt.plot(x, y)
plt.plot(x_at, y_at)
ax.add_artist(earth)
plt.title(f"Orbita para un valor vt = {vy}m/s")
plt.xlabel("Posición x (metros)")
plt.ylabel("Posición y (metros)")
plt.savefig('finding_vt_value.png')
示例#30
0
    lon_max = 141.525
    lat_min = 34.475
    lat_max = 37.025

    # セルごとに区切るように罫線を引く
    for lat in lats:
        p = plt.plot([lon_min, lon_max], [lat, lat], "black", linestyle='-')
        for lon in lons:
            p = plt.plot([lon, lon], [lat_min, lat_max],
                         "black",
                         linestyle='-')

    plt.scatter(140.90, 36.300, c='b', marker='.')
    c = plt.Circle((140.90, 36.300),
                   radius=0.09,
                   ec='y',
                   fill=False,
                   linewidth=4)
    ax.add_patch(c)
    print('[1000,0] = {},[1000,1] = {}'.format(cell_center[1000, 0],
                                               cell_center[1000, 1]))
    plt.xlabel(u'経度', fontdict={"fontproperties": fontprop})
    plt.ylabel(u'緯度', fontdict={"fontproperties": fontprop})
    plt.title(u'地震発生位置', fontdict={"fontproperties": fontprop})  # グラフのタイトル
    plt.show()
    # -------------------------------------------------------------
    #'''

    #--------------------------------------------------------------------------------------
    for S in Ss:
        a = 0