def plot_evolution():
    N = ff.current_generation
    M = ff.generation_size

    fig, ax = plt.subplots(figsize=(20, 20))
    grid = np.mgrid[0.1:0.9:complex(0, N), 0.1:0.9:complex(0, M)].T

    patches = []
    colors = []

    line_color = {'replace_by_other': 'green', 'replace_by_random': 'cyan', 'promoted': 'black', 'duplicate': 'orange'}
    dx = 0.01

    for j in range(N):
        dup_dx = 0.5 * dx
        for i in range(M):
            entry_id = ff.lineage[str(i)][j]

            nres2 = ff.population.get_entry(entry_id, {'properties.nres2': 1})['properties']['nres2']
            if nres2 < 1E14:
                lw = 1
                ls = 'solid'
            else:
                lw = 1
                ls = 'dotted'

            if ff.population.is_evaluated(entry_id):
                colors.append(ff.population.value(entry_id))
                circle = mpatches.Circle(grid[i, j], 0.4 / float(M), ec="black", linewidth=lw, linestyle=ls)
                patches.append(circle)
                label(grid[i, j], "%7.2f" % ff.population.value(entry_id), 0.0)

            for ichange in ff.population.pcdb.db.generation_changes.find({'from': entry_id, 'generation': j}):
                if ichange['change'] == 'duplicate':
                    orig = ichange['from']
                    dest = ichange['to']
                    newi = int(ff.lineage_inv[dest])
                    dup_dx += dx/10.0
                    x, y = np.array([[grid[i, j][0] - 1.5 * dup_dx, grid[i, j][0] - 2 * dup_dx,
                                      grid[newi, j][0] - 2 * dup_dx, grid[newi, j][0] - dx],
                                     [grid[i, j][1], grid[i, j][1], grid[newi, j][1], grid[newi, j][1]]])
                    line = mlines.Line2D(x, y, lw=1., alpha=0.8, color=line_color[ichange['change']],
                                         marker='>', markersize=5, markeredgecolor='none')
                    line.set_markevery([3])
                    ax.add_line(line)
                elif j < N - 1:
                    x, y = np.array(
                        [[grid[i, j][0] + dx, grid[i, j + 1][0] - 2 * dx], [grid[i, j][1], grid[i, j + 1][1]]])
                    line = mlines.Line2D(x, y, lw=5., alpha=0.3, color=line_color[ichange['change']])
                    # label(0.5*(grid[i, j]+grid[i, j+1]), ichange['change'], 0.0)
                    ax.add_line(line)

    collection = PatchCollection(patches, cmap=plt.cm.hsv, alpha=0.3)
    collection.set_array(np.array(colors))
    ax.add_collection(collection)

    plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
    plt.axis('equal')
    plt.axis('off')
    plt.savefig(figname+'_evo.pdf')
def draw(options):
    files = [f for f in os.listdir(options['outdir']) if f.endswith('.data')]

    degrees = list()
    diameters = list()
    velocities = list()
    for f in files:
        fin = open(options['outdir']+'/'+f, 'r')
        ts = -1
        for line in fin:
            if line.startswith('#'):
                continue
            time, degree, diameter, velocity = [t.strip() for t in line.split(',')]
            time = int(time)
            assert(ts == time-1)
            ts = time
            try:
                degrees[time].append(float(degree))
                diameters[time].append(int(diameter))
                velocities[time].append(float(velocity))
            except IndexError:
                degrees.append([float(degree)])
                diameters.append([int(diameter)])
                velocities.append([float(velocity)])

    polies = list()
    times = range(len(degrees))
    times2 = times + times[::-1]

    degrees_conf_upper = [confidence(d)[0] for d in degrees]
    degrees_conf_lower = [confidence(d)[1] for d in degrees]
    polies.append(conf2poly(times, degrees_conf_upper, degrees_conf_lower, color='blue'))

    diameters_conf_upper = [confidence(d)[0] for d in diameters]
    diameters_conf_lower = [confidence(d)[1] for d in diameters]
    polies.append(conf2poly(times, diameters_conf_upper, diameters_conf_lower, color='blue'))

    velocities_conf_upper = [confidence(d)[0] for d in velocities]
    velocities_conf_lower = [confidence(d)[1] for d in velocities]
    polies.append(conf2poly(times, velocities_conf_upper, velocities_conf_lower, color='green'))

    velocities = [scipy.mean(d) for d in velocities]
    diameters = [scipy.mean(d) for d in diameters]
    degrees = [scipy.mean(d) for d in degrees]

    fig = MyFig(options, figsize=(10, 8), xlabel='Time [s]', ylabel='Metric', grid=False, legend=True, aspect='auto', legend_pos='upper right')

    patch_collection = PatchCollection(polies, match_original=True)
    patch_collection.set_alpha(0.3)
    patch_collection.set_linestyle('dashed')
    fig.ax.add_collection(patch_collection)

    fig.ax.plot(times, degrees, label='Mean degree', color='blue')
    fig.ax.plot(times, diameters, label='Diameter', color='red')
    fig.ax.plot(times, velocities, label='Mean velocity $[m/s]$', color='green')

    fig.ax.set_xlim(0, options['duration'])
    y_max = max(max(degrees), max(diameters), max(velocities))
    fig.ax.set_ylim(0, y_max+10)
    fig.save('metrics', fileformat='pdf')
예제 #3
0
    def plot_Vexons(self, ybar, Vbar, fig, ax):
       
        x=1
        width=5
        patches=[]
        y=ybar

        cnt=0
        for p in Vbar:
            x= p[0]-xstart
            width= p[1] - p[0]
            print x, width
            rect= Rectangle( (x,y), width, self.height )
            patches.append(rect)

            epsilon=-0.35
            """
            ax.annotate(self.exonLabels[cnt], (x+(width)/2.,y-epsilon),
                        fontsize=10, ha='center', va='center')
            """
            cnt+=1


        colors = 100*np.random.rand(len(patches))
        q = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.6)
        q.set_array(np.array(colors))
        ax.add_collection(q)
        ax.set_xlim([self.xLower, self.xUpper])
        ax.set_ylim([4, 6])
예제 #4
0
파일: gfx.py 프로젝트: caosuomo/rads
def show_uboxes(uboxes,S=None,col='b',ecol='k', fig=None):
	if uboxes.dim != 2:
		raise Exception("show_uboxes: dimension must be 2")
	if S is None:
		S = range(uboxes.size)

	patches = []
	for i in S:
		art = mpatches.Rectangle(uboxes.corners[i],uboxes.width[0],uboxes.width[1])
		patches.append(art)

	if not fig:
		fig = plt.figure()

	ax = fig.gca()
	ax.hold(True)
	collection = PatchCollection(patches)
	collection.set_facecolor(col)
	collection.set_edgecolor(ecol)
	ax.add_collection(collection,autolim=True)
	ax.autoscale_view()
	plt.draw()
        plt.show()

	return fig
예제 #5
0
	def circles(x, y, s, c='b', vmin=None, vmax=None, **kwargs):
		import numpy as np
		import matplotlib.pyplot as plt
		from matplotlib.patches import Circle
		from matplotlib.collections import PatchCollection

		if np.isscalar(c):
			kwargs.setdefault('color', c)
			c = None
		if 'fc' in kwargs: kwargs.setdefault('facecolor', kwargs.pop('fc'))
		if 'ec' in kwargs: kwargs.setdefault('edgecolor', kwargs.pop('ec'))
		if 'ls' in kwargs: kwargs.setdefault('linestyle', kwargs.pop('ls'))
		if 'lw' in kwargs: kwargs.setdefault('linewidth', kwargs.pop('lw'))

		patches = [Circle((x_, y_), s_) for x_, y_, s_ in np.broadcast(x, y, s)]
		collection = PatchCollection(patches, **kwargs)
		if c is not None:
			collection.set_array(np.asarray(c))
			collection.set_clim(vmin, vmax)

		ax = plt.gca()
		ax.add_collection(collection)
		ax.autoscale_view()
		if c is not None:
			plt.sci(collection)
		return collection
예제 #6
0
def draw_zips_3(zctashapes, dfl, colorcol='', gamma=1.0):

    if len(colorcol)>0:
        c = dfl[colorcol].copy()#**gamma

    shapes = zctashapes
    Nshp    = len(shapes)

    cm    = plt.get_cmap('Dark2')
    cccol = cm(1.*c/max(c))

    #   -- plot --
    fig     = plt.figure()
    ax      = fig.add_subplot(111)
    for nshp in xrange(Nshp):
        ptchs   = []
        pts     = np.array(shapes[nshp].points)
        prt     = shapes[nshp].parts
        par     = list(prt) + [pts.shape[0]]

        for pij in xrange(len(prt)):
            ptchs.append(Polygon(pts[par[pij]:par[pij+1]]))

#        ax.add_collection(PatchCollection(ptchs,facecolor=cccol[nshp,:],edgecolor='k', linewidths=.1))
        pc = PatchCollection(ptchs,facecolor=cccol[nshp],norm=colors.PowerNorm(gamma=gamma),edgecolor='k', linewidths=.1)
        # for collection in pc:?
        pc.set_facecolor(cccol[nshp])

        ax.add_collection(pc)
    ax.set_xlim(-91,-82)
    ax.set_ylim(41,48)

    return ax
예제 #7
0
    def draw(self, colorbars=True, **kwargs):
        self.cbars = []
        for coll, cmap, label in zip(self.collections, self.cmaps, self.cbar_labels):
            pc = PatchCollection(coll, cmap=cmap)
            pc.set_array(np.array([ p.value for p in coll ]))
            self._ax.add_collection(pc)

            if colorbars:
                options = {
                        'orientation':'horizontal',
                        'pad':0.05, 'aspect':60
                        }

                options.update(kwargs.get('colorbar-options', {}))
                cbar = plt.colorbar(pc, **options)
                cbar.set_label(label)
                self.cbars.append(cbar)

        fontdict = kwargs.get('font', {'color':'white'})
        for s in self.squares:
            if not s.label:
                continue
            x = s.x + s.dx/2
            y = s.y + s.dy/2
            self._ax.text(x, y, s.label, ha='center', 
                                         va='center', 
                                         fontdict=fontdict)

        if self.guide_square:
            self.guide_square.set_labels(self.labels)
            pc = PatchCollection(self.guide_square.patches, match_original=True)
            self._ax.add_collection(pc)
        self._ax.autoscale_view()
예제 #8
0
def plotshapefile(shpfile, colorlist):
    fig, ax = plt.subplots()
    #shpfile = 'C:/_DATA/CancerData/SatScan/NorthEasternUS.shp'
    sf = shapefile.Reader(shpfile)
    shapes = sf.shapes()
    #records = np.array(sf.records())
    [x1, y1, x2, y2] = find_bounding_box(shpfile)



    patches = []
    for shape in shapes:
        lons,lats = zip(*shape.points)
        data = np.array([lons, lats]).T
        polygon = Polygon(data, True)
        patches.append(polygon)
        
    #colors = 100*np.random.rand(len(patches))
    #colors = normalize(records[:,-3].astype(np.int32))
    c#olors = records[:,-3].astype(np.int32)
    colors = colorlist
    p = PatchCollection(patches, cmap=cm.OrRd, alpha=0.8)
    p.set_array(np.array(colors))
    ax.add_collection(p)
    ax.set_xlim(x1, x2)
    ax.set_ylim(y1, y2)
    plt.colorbar(p)
    #plt.savefig('tutorial10.png',dpi=300)
    plt.show()
예제 #9
0
def data2fig(data, X, options, legend_title, xlabel, ylabel=r'Reachability~$\reachability$'):
    if options['grayscale']:
        colors = options['graycm'](pylab.linspace(0, 1, len(data.keys())))
    else:
        colors = options['color'](pylab.linspace(0, 1, len(data.keys())))
    fig = MyFig(options, figsize=(10, 8), xlabel=r'Sources~$\sources$', ylabel=ylabel, grid=False, aspect='auto', legend=True)
    for j, nhdp_ht in enumerate(sorted(data.keys())):
        d = data[nhdp_ht]
        try:
            mean_y = [scipy.mean(d[n]) for n in X]
        except KeyError:
            logging.warning('key \"%s\" not found, continuing...', nhdp_ht)
            continue
        confs_y = [confidence(d[n])[2] for n in X]
        poly = [conf2poly(X, list(numpy.array(mean_y)+numpy.array(confs_y)), list(numpy.array(mean_y)-numpy.array(confs_y)), color=colors[j])]
        patch_collection = PatchCollection(poly, match_original=True)
        patch_collection.set_alpha(0.3)
        patch_collection.set_linestyle('dashed')
        fig.ax.add_collection(patch_collection)
        fig.ax.plot(X, mean_y, label='$%d$' % nhdp_ht, color=colors[j])
    fig.ax.set_xticks(X)
    fig.ax.set_xticklabels(['$%s$' % i for i in X])
    fig.ax.set_ylim(0,1)
    fig.legend_title = legend_title
    return fig
예제 #10
0
    def animate_path(self, path, key_xy):
        fig, ax = plt.subplots()

        colors = 100*np.random.rand(len(self.plot_obstacles_polygon))
        p = PatchCollection(self.plot_obstacles_polygon, cmap=matplotlib.cm.jet, alpha=0.4)
        p.set_array(np.array(colors))
        ax.add_collection(p)
        plt.colorbar(p)

        plt.plot([self.initial_state[0]], [self.initial_state[1]], 'bs', self.goal_state[0], self.goal_state[1], 'g^')
        plt.axis([0, self.resolution, 0, self.resolution])

        x_0, y_0 = key_xy(path[0])[0], key_xy(path[0])[1]
        x_1, y_1 = key_xy(path[0 + 1])[0], key_xy(path[0 + 1])[1]
        dx, dy = x_1 - x_0, y_0 - y_1
        qv = ax.quiver(x_0, y_0, dx, dy, angles='xy',scale_units='xy',scale=1)

        def animate(i):
            x_init, y_init =key_xy(path[i])[0], key_xy(path[i])[1]
            x_f, y_f = key_xy(path[i + 1])[0], key_xy(path[i + 1])[1]
            dx, dy = x_f - x_init, y_f - y_init
            qv.set_UVC(np.array(dx), np.array(dy))
            qv.set_offsets((x_init, y_init))
            return qv

        anim = animation.FuncAnimation(fig, animate, frames=range(0, len(path)-1), interval=500)
        plt.show()
예제 #11
0
class Visualize:
    def __init__(self, v, t, e, fig, win, axesLimit=[-3,3.5,-2,2]):
        self.e = e.copy()
        self.p = [Polygon(v[ti]) for ti in t]
        self.p = PatchCollection(self.p, edgecolors='none')
        self.l = LineCollection(v[e[:,:2]])

        win = win or fig.canvas.manager.window
        if fig is None: fig = gcf()
        fig.clf()
        ax = fig.add_axes([0.02,0.02,.98,.98])
        ax.axis('scaled')
        ax.axis(axesLimit)
        ax.set_autoscale_on(False)
        self.axis, self.fig, self.win = ax, fig, win

        ax.add_collection(self.p)
        ax.add_collection(self.l)
        # ax.add_collection(self.l1)
        # ax.add_collection(self.l2)

    def update(self, title, phi):
        norm = Normalize(phi.min(), phi.max())
        self.p.set_norm(norm)
        self.l.set_norm(norm)
        self.p.set_array(phi)
        self.l.set_array(phi[self.e[:,2:]].mean(1))
        if not self.__dict__.has_key('colorbar'):
            self.colorbar = self.fig.colorbar(self.p)
        self.win.set_title(title)
        #self.fig.canvas.set_window_title(title)
        self.fig.canvas.draw()
def scatter_withcirclesize(ax,x,y,s,alpha=1.0,c='k',cmap=plt.cm.PRGn,colorbar=False,**kwargs):
    if c != 'k':
        if type(c)==str:
            c = [c for dump in range(len(s))]
            cmap=None
        if type(c)==list:
            if len(c) == len(s):
                c = c
            else:
                print 'incorrect number of colors specified.';return None
    else:
        c = [c for dump in range(len(s))]
    
    points=[]    
    for (x_i,y_i,r_i,c_i) in zip(x,y,s,c):
        points.append(patches.Circle((x_i,y_i),radius=r_i))
    if cmap is not None:
        p = PatchCollection(points,cmap=cmap,alpha=alpha,clim=(-1,1))
        p.set_array(np.array(c))
        ax.add_collection(p)
    else:
        p = PatchCollection(points,color=c,alpha=alpha)
        ax.add_collection(p)
    if colorbar:
        plt.colorbar(p)
예제 #13
0
def circles(ax, x, y, r, c="b", **kwargs):

    from matplotlib.patches import Circle
    from matplotlib.collections import PatchCollection

    if isinstance(c, basestring):
        color = c
    else:
        color = None
    kwargs.update(color=color)

    if np.isscalar(x):
        patches = [Circle((x, y), r)]
    elif np.isscalar(r):
        patches = [Circle((x_, y_), r) for x_, y_ in zip(x, y)]
    else:
        patches = [Circle((x_, y_), s_) for x_, y_, s_ in zip(x, y, r)]
    collection = PatchCollection(patches, **kwargs)

    if color is None:
        collection.set_array(np.asarray(c))

    ax.add_collection(collection)

    return collection
예제 #14
0
    def plot_refexons(self, fig, ax):
       
        x=1
        width=5
        patches=[]
        y=5.0

        cnt=0
        for p in self.exons:
            x= p[0]-xstart
            width= p[1] - p[0]
            print x, width
            rect= Rectangle( (x,y), width, self.height )
            patches.append(rect)

            epsilon=-0.25

            ax.annotate(self.exonLabels[cnt], (x+(width)/2., y-(self.height/2.+epsilon)), fontsize=10, ha='center', va='center')
            cnt+=1


        colors = 100*np.random.rand(len(patches))
        q = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.6)
        q.set_array(np.array(colors))
        ax.add_collection(q)
예제 #15
0
def drawboxes(breaks, axis, boxcolor=1):
    '''Draws boxes on the current plot.'''
    from matplotlib.patches import Polygon
    from matplotlib.collections import PatchCollection
    import matplotlib.pyplot as plt
    ax = plt.gca()
    x1, x2 = plt.xlim()
    y1, y2 = plt.ylim()
    patches = []
    if axis == 0:
        for i in range(len(breaks) - 1):
            y1, y2 = (breaks[i + 1], breaks[i])
            patches.append(
                Polygon([[x1, y2], [x1, y1], [x2, y1], [x2, y2]], True))
    else:
        for i in range(len(breaks) - 1):
            x1, x2 = (breaks[i + 1], breaks[i])
            patches.append(
                Polygon([[x1, y2], [x1, y1], [x2, y1], [x2, y2]], True))
    if boxcolor == 1:
        p = PatchCollection(patches, cmap=plt.cm.jet, alpha=0.4)
    else:
        p = PatchCollection(patches, cmap=plt.cm.Greys, alpha=0.2)
    p.set_array(np.array([0, 0.2, 0.4, 0.5, 0.7, 0.9, 1]))
    ax.add_collection(p)
예제 #16
0
    def _setup(self):
        # "Cheat" to see 2D map of collision data
        patches = []
        if isinstance(self.environment, Environment_Simulator):
            for obj in self.environment.get_objects():
                patch = self._create_patch(obj)
                if patch is not None:
                    patches.append(patch)

        p = None
        if len(patches) > 0:
            p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4)
            patch_colors = 50*np.ones(len(patches))
            p.set_array(np.array(patch_colors))

        self.plot_polygons = p
        self.arrow_options = {
            "arrowstyle": "->",
            "linewidth": 2,
            "alpha": 0.5
        }
        self.plt = plt
        self.fig, self.ax = self.plt.subplots()

        # Set up interactive drawing of the memory map. This makes the 
        # dronekit/mavproxy fairly annoyed since it creates additional 
        # threads/windows. One might have to press Ctrl-C and normal keys to 
        # make the program stop.
        self.plt.gca().set_aspect("equal", adjustable="box")
        if self.interactive:
            self.plt.ion()
            self.plt.show()
예제 #17
0
def plot_(pnts):
    """plot a circle, arc sector etc
    """
    import matplotlib.pyplot as plt
    import matplotlib
    from matplotlib.patches import Polygon
    from matplotlib.collections import PatchCollection
    #x_min = pnts[:,0].min()
    #x_max = pnts[:,0].max()
    #y_min = pnts[:,1].min()
    #y_max = pnts[:,1].max()
    fig, ax = plt.subplots()
    patches = []
    # Points need to form a closed loopset closed to True if your 1st and
    # last pnt aren't equal.
    for i in pnts:
        polygon = Polygon(i, closed=False)
        patches.append(polygon)
    p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=1.0)
    colors = 100*np.random.rand(len(patches))
    p.set_array(np.array(colors))
    #ax.set_xlim(x_min-0.5, x_max+0.5)  # (x_min, x_max)
    #ax.set_ylim(y_min-0.5, y_max+0.5)  # y_min, y_max)
    ax.add_collection(p)
    plt.axis('equal')
    plt.show()
예제 #18
0
파일: gfx.py 프로젝트: caosuomo/rads
def show_uboxes_corners( corners, width, S=None, col='b', ecol='k' ):
	"""
	This version takes the corners and width arrays as arguments
	instead.
	"""
	if corners.ndim != 2:
		raise Exception("show_uboxes_corners: dimension must be 2")
	if S is None:
		S = range( len(corners) )

	patches = []
	for i in S:
		art = mpatches.Rectangle( corners[i], width[0], width[1] )
		patches.append(art)

	fig = plt.figure()
	ax = fig.gca()
	ax.hold(True)
	collection = PatchCollection(patches)
	collection.set_facecolor(col)
	collection.set_edgecolor(ecol)
	ax.add_collection(collection,autolim=True)
	ax.autoscale_view()
	plt.show()
	
	return fig
예제 #19
0
def plot_single_circle_grid(centroids, radiuses, ax, intensities, grid=True, alpha=0.75):
    # intensities = np.ma.masked_equal(abs(np.array(intensities)), .0)
    patches = []
    count = 0
    if grid:
        for n, x in enumerate(centroids):
            for y, r in zip(centroids, radiuses):
                # ax.text(x, y, count)
                count += 1
                circle = Circle((x, y), r)
                patches.append(circle)
    else:
        for xy, r in zip(centroids, radiuses):
            count += 1
            circle = Circle(xy, r)
            patches.append(circle)

    sorted_index = [idx for (intensity, idx) in sorted(zip(intensities, range(len(intensities))))]
    patches = [patches[idx] for idx in sorted_index]
    intensities = [intensities[idx] for idx in sorted_index]

    norm = mpl.colors.Normalize(vmin=0.0, vmax=max(intensities))
    cm.jet.set_bad(color='white', alpha=0.0)
    colors = [('white')] + [(cm.jet(i)) for i in xrange(1, 256)]
    new_map = mpl.colors.LinearSegmentedColormap.from_list('new_map', colors, N=256)

    p = PatchCollection(patches, cmap=new_map, alpha=alpha, norm=norm, linewidth=0)
    p.set_array(np.array(intensities))
    ax.add_collection(p)

    ax.annotate(int(np.sqrt(count)), xy=(2, 90), fontsize=30,
                path_effects=[PathEffects.withStroke(linewidth=3, foreground="w")])
예제 #20
0
파일: LED_matrix.py 프로젝트: kodda/Gui_LED
def matrix_figure(N1=160, N2=32):
   r=0.4

   fsx=20.
   fsy=fsx*N2/N1

   f=Figure(figsize=(fsx,fsy),frameon=False)
   #f=plt.figure(figsize=(fsx,fsy),frameon=False)
   
   ax=f.add_subplot(111,axisbg='k')
   ax.set_xlim([-2*r,N1-1+2*r])
   ax.set_ylim([-2*r,N2-1+2*r])
   ax.set_axis_bgcolor('k')
   ax.set_yticks([])
   ax.set_xticks([])
   ax.set_frame_on(False) 
   x=np.arange(N1)
   y=np.arange(N2)

   xx,yy=np.meshgrid(x,y)
   cmap = col.ListedColormap([ '#6E6E6E','#FE2E2E', '#64FE2E', '#FF8000'])
   colors=np.random.randint(0,4,(N1,N2))

   patches = []
   for x1,y1 in zip(xx.flatten(), yy.flatten()):
     circle = Circle((x1,y1), r)
     patches.append(circle)

   p = PatchCollection(patches, cmap=cmap)
   p.set_array(colors.flatten())
   ax.add_collection(p)
   f.subplots_adjust(0,0,1,1)
   return ax, colors
예제 #21
0
def plotGrid(verbose=True, save=False, show=True, dpi=300):
    '''Show Dymaxion Grid'''
    plt.figure(figsize=(20,12))
    patches = []
    for zdx, vertset in enumerate(constants.vert_indices):
        if zdx==8 or zdx==15: continue # Edge Triangles
        x,y = [],[]
        for i,vert in enumerate(vertset):
            xt,yt = convert.vert2dymax(vert,vertset)
            #print(xt,yt)
            x += [xt]
            y += [yt]
            #print(xt,yt,i,vert)
        #plt.plot(x,y,'k',lw=.1)
        patches.append(Polygon(np.array([x,y]).T,closed=False, fill=True))
    
    colors = 100*np.random.random(len(patches))
    p = PatchCollection(patches, cmap=plt.cm.jet, alpha=1,linewidths=0.)
    p.set_array(np.array(colors))
    plt.gca().add_collection(p)
    if verbose: print(':: plotted',len(patches),'coastlines')
    plt.gca().set_aspect('equal')
    plt.gca().set_xlim([0,5.5])
    plt.gca().set_ylim([0,2.6])
    plt.gca().get_xaxis().set_visible(False)
    plt.gca().get_yaxis().set_visible(False)
    plt.gca().axis('off')
    
    if save: plt.savefig('dymax_grid.png',bbox_inches='tight',dpi=dpi,transparent=True,pad_inches=0)
    if show:
        plt.tight_layout()
        plt.show()
    else: plt.close()
예제 #22
0
def plotLandmasses(verbose=True, save=False, show=True, dpi=300, resolution='c'):
    '''Draw Landmasses Only, no Background'''
    lonlat_islands, dymax_islands = getIslands(resolution)
    
    patches = []
    for island in dymax_islands:
        #if np.all(island==islands[4]): print (island)
        
        try: polygon = Polygon(np.array(island),closed=True, fill=True)
        except: continue
        #plt.plot(island[:,0],island[:,1])
        patches.append(polygon)
    

    plt.figure(figsize=(20,12),frameon=False)
    colors = 100*np.random.random(len(patches))
    p = PatchCollection(patches, cmap=plt.cm.jet, alpha=1,linewidths=0.)
    p.set_array(np.array(colors))
    plt.gca().add_collection(p)
    if verbose: print(':: plotted',len(patches),'coastlines')
    plt.gca().set_aspect('equal')
    plt.gca().set_xlim([0,5.5])
    plt.gca().set_ylim([0,2.6])
    plt.gca().get_xaxis().set_visible(False)
    plt.gca().get_yaxis().set_visible(False)
    plt.gca().axis('off')
    if save: plt.savefig('dymax_landmasses.png',bbox_inches='tight',dpi=dpi,transparent=True,pad_inches=0)
    if show:
        plt.tight_layout()
        plt.show()
    else: plt.close()
예제 #23
0
 def plot_patches(self, x_range, y_range, file_name="voronoi_p1.png"):
     t0=time.time()
     self.run()
     print((time.time()-t0))
     pts = self.sites
     pts_dict = defaultdict(list)
     patches = []
     colors = []
     for edge in self.edges:
         pts_dict[edge.pl].append((edge.start, edge.end))
         pts_dict[edge.pr].append((edge.start, edge.end))
     for center, v_raw in pts_dict.items():
         starts, ends = zip(*v_raw)
         vertices = set(starts + ends)
         vertices = sorted(vertices, key=lambda p: np.arctan2(p.y-center.y,p.x-center.x))
         vertices = [(v.x, v.y) for v in vertices]
         patches.append(Polygon(vertices, True))
         colors.append(center.dist_to_point(Point(0,0)))
     fig, ax = plt.subplots()
     colors = 100*np.random.rand(len(patches))
     pc = PatchCollection(patches, cmap=jet, alpha=0.2)
     pc.set_array(np.array(colors))
     ax.axis([*x_range, *y_range])
     ax.add_collection(pc)
     ax.margins(0.1)
     xs, ys = zip(*[(p.x, p.y) for p in pts])
     ax.plot(xs, ys, 'ro', markersize=1)
     fig.savefig(file_name)
예제 #24
0
	def circles(x, y, s, c='b', ax=None, vmin=None, vmax=None, **kwargs):
		from matplotlib.patches import Circle
		from matplotlib.collections import PatchCollection
		import pylab as plt
		
		if ax is None:
		        ax = plt.gca()    
	
		if isinstance(c,basestring):
		        color = c     # ie. use colors.colorConverter.to_rgba_array(c)
		else:
		        color = None  # use cmap, norm after collection is created
		        kwargs.update(color=color)
		if np.isscalar(x):
		        patches = [Circle((x, y), s),]
		elif np.isscalar(s):
		        patches = [Circle((x_,y_), s) for x_,y_ in zip(x,y)]
		else:
		        patches = [Circle((x_,y_), s_) for x_,y_,s_ in zip(x,y,s)]
		        collection = PatchCollection(patches, **kwargs)
		if color is None:
		        collection.set_array(np.asarray(c))
		if vmin is not None or vmax is not None:
		        collection.set_clim(vmin, vmax)

		ax.add_collection(collection)
		ax.autoscale_view()
		return collection
예제 #25
0
파일: mapping.py 프로젝트: jomerson/pysal
def quantile_map(coords,y,k, title='Quantile'):
    """
    Quantile choropleth map

    Arguments
    =========

    coords: Map_Projection instance

    y: array
       variable to map

    k: int
       number of classes

    title: string
           map title

    """


    classification = ps.Quantiles(y,k)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    patches = []
    colors = []
    i = 0
    shape_colors = classification.bins[classification.yb]
    shape_colors = y
    #classification.bins[classification.yb]
    for shp in coords.projected:
        for ring in shp:
            x,y = ring
            x = x / coords.bounding_box[2]
            y = y / coords.bounding_box[3]
            n = len(x)
            x.shape = (n,1)
            y.shape = (n,1)
            xy = np.hstack((x,y))
            polygon = Polygon(xy, True)
            patches.append(polygon)
            colors.append(shape_colors[i])
        i += 1
    cmap = cm.get_cmap('hot_r', k+1)
    boundaries = classification.bins.tolist()
    boundaries.insert(0,0)
    norm = clrs.BoundaryNorm(boundaries, cmap.N)
    p = PatchCollection(patches, cmap=cmap, alpha=0.4, norm=norm)
    colors = np.array(colors)
    p.set_array(colors)
    ax.add_collection(p)
    ax.set_frame_on(False)
    ax.axes.get_yaxis().set_visible(False)
    ax.axes.get_xaxis().set_visible(False)
    ax.set_title(title)
    plt.colorbar(p, cmap=cmap, norm = norm, boundaries = boundaries, ticks=
            boundaries)
    plt.show()
    return classification
예제 #26
0
def plot():
    from matplotlib.patches import Circle, Ellipse, Polygon, Rectangle, Wedge
    from matplotlib.collections import PatchCollection
    from matplotlib import pyplot as plt
    import numpy as np
    import matplotlib as mpl

    np.random.seed(123)

    fig = plt.figure()
    ax = fig.add_subplot(111)

    N = 3
    x = np.random.rand(N)
    y = np.random.rand(N)
    radii = 0.1 * np.random.rand(N)
    patches = []
    for x1, y1, r in zip(x, y, radii):
        circle = Circle((x1, y1), r)
        patches.append(circle)

    rect = Rectangle(xy=[0.0, 0.25], width=1.0, height=0.5, angle=-45.0)
    patches.append(rect)

    x = np.random.rand(N)
    y = np.random.rand(N)
    radii = 0.1 * np.random.rand(N)
    theta1 = 360.0 * np.random.rand(N)
    theta2 = 360.0 * np.random.rand(N)
    for x1, y1, r, t1, t2 in zip(x, y, radii, theta1, theta2):
        wedge = Wedge((x1, y1), r, t1, t2)
        patches.append(wedge)

    # Some limiting conditions on Wedge
    patches += [
        Wedge((0.3, 0.7), 0.1, 0, 360),  # Full circle
        Wedge((0.7, 0.8), 0.2, 0, 360, width=0.05),  # Full ring
        Wedge((0.8, 0.3), 0.2, 0, 45),  # Full sector
        Wedge((0.8, 0.3), 0.2, 45, 90, width=0.10),  # Ring sector
    ]

    for _ in range(N):
        polygon = Polygon(np.random.rand(N, 2), True)
        patches.append(polygon)

    colors = 100 * np.random.rand(len(patches))
    p = PatchCollection(patches, cmap=mpl.cm.jet, alpha=0.4)
    p.set_array(np.array(colors))
    ax.add_collection(p)

    ellipse = Ellipse(xy=[1.0, 0.5], width=1.0, height=0.5, angle=45.0, alpha=0.4)
    ax.add_patch(ellipse)

    circle = Circle(xy=[0.0, 1.0], radius=0.5, color="r", alpha=0.4)
    ax.add_patch(circle)

    plt.colorbar(p)

    return fig
예제 #27
0
 def do_3d_projection(self, renderer):
     xs, ys, zs = self._offsets3d
     vxs, vys, vzs, vis = proj3d.proj_transform_clip(xs, ys, zs, renderer.M)
     self._alpha = None
     self.set_facecolors(zalpha(self._facecolor3d, vzs))
     self.set_edgecolors(zalpha(self._edgecolor3d, vzs))
     PatchCollection.set_offsets(self, zip(vxs, vys))
     return min(vzs)
def plotseedsandctg(shpfile, cur_scale):
    import matplotlib.colors as colors
    import numpy as np
    from matplotlib.collections import PatchCollection
    from matplotlib.patches import Polygon
    import shapefile
    import matplotlib.pyplot as plt
    from matplotlib import cm
    
    cur_amg_weight = scale_amg_weight[cur_scale]
    fig, ax = plt.subplots()
    #shpfile = 'C:/_DATA/CancerData/SatScan/NorthEasternUS.shp'
    sf = shapefile.Reader(shpfile)
    shapes = sf.shapes()
    #shapes = shapefile.Reader(shpfile).shapes()
    #records = np.array(sf.records())
    [x1, y1, x2, y2] = find_bounding_box(shapes)

    points = []
    patches = []
    for shape in shapes:
        lons,lats = zip(*shape.points)
        data = np.array([lons, lats]).T
        points.append([np.mean(lons), np.mean(lats)])
        polygon = Polygon(data, True)
        patches.append(polygon)

    
    colorlist = np.zeros(len(patches))
    for idx in scale_amg_weight[cur_scale].seeds:
        colorlist[idx] = 1.0
    #tcmap = cm.get_cmap(cmap_color)
    print colorlist
    #p = PatchCollection(patches, cmap=tcmap, alpha=0.8, edgecolors='grey')
    p = PatchCollection(patches, facecolors=colorlist, alpha=0.8, edgecolors='grey')
    p.set_array(np.array(colorlist))
    ax.add_collection(p)
    ax.set_xlim(x1, x2)
    ax.set_ylim(y1, y2)

    '''
    ## plot association between pixels and seeds            
    for idx in cur_amg_weight.seeds:
        #tempimagedata[idx] = 0
        temp_set = cur_amg_weight.seeds[idx] ## pixels associated with the seed sid
        for pid in temp_set:
            #if pid <> idx:
            plt.plot([points[idx][0], points[pid][0]], [points[idx][1], points[pid][1]], color = 'r', marker='o')
    '''
    ## plot neigbhors of seeds
    for idx in cur_amg_weight.seedsweight:
        temp_set = cur_amg_weight.seedsweight[idx]
        for pid in temp_set:
            plt.plot([points[idx][0], points[pid][0]], [points[idx][1], points[pid][1]], color = 'y', marker='o')

    plt.colorbar(p)
    #plt.savefig('tutorial10.png',dpi=300)
    plt.show()
예제 #29
0
def plotEarthMeridiansTriangles(verbose=True, save=False, show=True, dpi=300, resolution='c'):
    '''Draw Dymax Triangles, All countries, and Meridians'''
    lonlat_islands, dymax_islands = getIslands(resolution)
    n = 1000
    plt.figure(figsize=(20,12))
    plt.title('Dymaxion Map Projection')
    
    ### Dymaxion Latitude Meridians
    lons = np.linspace(-180,180,n)
    latgrid = np.linspace(-85,85,35)
    points = []
    start = time.time()
    for lat in latgrid:
        for lon in lons:
            points += [convert.lonlat2dymax(lon,lat)]
    if verbose: print(':: mapped {:d} points to dymax projection @ {:.1f} pts/sec [{:.1f} secs total]'.format(len(points),len(points)/(time.time()-start),time.time()-start))
    points = np.array(points)
    plt.plot(points[:,0],points[:,1],',',c='k',alpha=.3)#,'.',lw=0)#,c=range(n))

    ### Dymaxion Longitude Meridians
    lats = np.linspace(-85,85,n)
    longrid = np.linspace(-180,175,72)
    points = []
    start = time.time()
    for lon in longrid:
        for lat in lats:
            points += [convert.lonlat2dymax(lon,lat)]
    if verbose: print(':: mapped {:d} points to dymax projection @ {:.1f} pts/sec [{:.1f} secs total]'.format(len(points),len(points)/(time.time()-start),time.time()-start))
    points = np.array(points)
    plt.plot(points[:,0],points[:,1],',',c='k',alpha=.3)#,'.',lw=0)#,c=range(n))

    ### Dymaxion Face Tiles
    for jdx in range(constants.facecount):
        if jdx == 8 or jdx == 15: continue
        points = convert.face2dymax(jdx,push=.95)
        xcenter,ycenter = convert.dymax_centers[jdx]
        plt.text(xcenter,ycenter,str(jdx),size='x-large')
        plt.plot(points[:,0],points[:,1],lw=5,alpha=.7)
        
    ### Draw Landmasses
    patches = []
    for island in dymax_islands:
        polygon = Polygon(np.array(island))#, closed=False, fill=False)
        patches.append(polygon)
    
    p = PatchCollection(patches, alpha=.3, linewidths=1.,facecolors=None)
    colors = 100*np.random.random(len(patches))
    p.set_array(np.array(colors))
    plt.gca().add_collection(p)
    if verbose: print(':: plotted',len(patches),'coastlines')
    plt.gca().set_xlim([0,5.5])
    plt.gca().set_ylim([0,2.6])
    plt.gca().set_aspect('equal')   
    if save: plt.savefig('dymax_earthmeridianstriangles.png',bbox_inches='tight',dpi=dpi,transparent=True,pad_inches=0)
    if show:
        plt.tight_layout()
        plt.show()
    else: plt.close()
예제 #30
0
def plot2D(patches, values, vmin, vmax):
    color_map = plt.cm.get_cmap('plasma_r')
    p = PatchCollection(patches, cmap=color_map, edgecolor="#ffffff", linewidth=0)
    colors = values
    p.set_array(np.array(colors))
    ax = plt.axes()
    ax.add_collection(p)
    #plt.colorbar(p)
    p.set_clim([vmin, vmax])
예제 #31
0
    def showAnns(self, anns, draw_bbox=False):
        """
        Display the specified annotations.
        :param anns (array of object): annotations to display
        :return: None
        """
        if len(anns) == 0:
            return 0
        if 'segmentation' in anns[0] or 'keypoints' in anns[0]:
            datasetType = 'instances'
        elif 'caption' in anns[0]:
            datasetType = 'captions'
        else:
            raise Exception('datasetType not supported')
        if datasetType == 'instances':
            ax = plt.gca()
            ax.set_autoscale_on(False)
            polygons = []
            color = []
            for ann in anns:
                c = (np.random.random((1, 3)) * 0.6 + 0.4).tolist()[0]
                if 'segmentation' in ann:
                    if type(ann['segmentation']) == list:
                        # polygon
                        for seg in ann['segmentation']:
                            poly = np.array(seg).reshape(
                                (int(len(seg) / 2), 2))
                            polygons.append(Polygon(poly))
                            color.append(c)
                    else:
                        # mask
                        t = self.imgs[ann['image_id']]
                        if type(ann['segmentation']['counts']) == list:
                            rle = maskUtils.frPyObjects([ann['segmentation']],
                                                        t['height'],
                                                        t['width'])
                        else:
                            rle = [ann['segmentation']]
                        m = maskUtils.decode(rle)
                        img = np.ones((m.shape[0], m.shape[1], 3))
                        if ann['iscrowd'] == 1:
                            color_mask = np.array([2.0, 166.0, 101.0]) / 255
                        if ann['iscrowd'] == 0:
                            color_mask = np.random.random((1, 3)).tolist()[0]
                        for i in range(3):
                            img[:, :, i] = color_mask[i]
                        ax.imshow(np.dstack((img, m * 0.5)))
                if 'keypoints' in ann and type(ann['keypoints']) == list:
                    # turn skeleton into zero-based index
                    sks = np.array(
                        self.loadCats(ann['category_id'])[0]['skeleton']) - 1
                    kp = np.array(ann['keypoints'])
                    x = kp[0::3]
                    y = kp[1::3]
                    v = kp[2::3]
                    for sk in sks:
                        if np.all(v[sk] > 0):
                            plt.plot(x[sk], y[sk], linewidth=3, color=c)
                    plt.plot(x[v > 0],
                             y[v > 0],
                             'o',
                             markersize=8,
                             markerfacecolor=c,
                             markeredgecolor='k',
                             markeredgewidth=2)
                    plt.plot(x[v > 1],
                             y[v > 1],
                             'o',
                             markersize=8,
                             markerfacecolor=c,
                             markeredgecolor=c,
                             markeredgewidth=2)

                if draw_bbox:
                    [bbox_x, bbox_y, bbox_w, bbox_h] = ann['bbox']
                    poly = [[bbox_x, bbox_y], [bbox_x, bbox_y + bbox_h],
                            [bbox_x + bbox_w, bbox_y + bbox_h],
                            [bbox_x + bbox_w, bbox_y]]
                    np_poly = np.array(poly).reshape((4, 2))
                    polygons.append(Polygon(np_poly))
                    color.append(c)

            p = PatchCollection(polygons,
                                facecolor=color,
                                linewidths=0,
                                alpha=0.4)
            ax.add_collection(p)
            p = PatchCollection(polygons,
                                facecolor='none',
                                edgecolors=color,
                                linewidths=2)
            ax.add_collection(p)
        elif datasetType == 'captions':
            for ann in anns:
                print(ann['caption'])
예제 #32
0
    def plotar_estrutura_otimizada(self,
                                   tecnica_otimizacao: int,
                                   rmin: float = 0,
                                   tipo_cmap: str = 'binary',
                                   visualizar_areas_barras=False):
        """Exibe a malha final gerada. cmad jet ou binary"""
        logger.info('Criando o desenho da malha final')

        plt.rcParams['pdf.fonttype'] = 42
        plt.rcParams['font.family'] = 'Calibri'

        # Resultados finais
        rho_final = self.dados.rhos_iteracao_final()
        results_gerais_finais = self.dados.resultados_gerais_iteracao_final()

        fig, ax = plt.subplots()
        win = plt.get_current_fig_manager()
        win.window.state('zoomed')
        ax.axis('equal')

        xmin, ymin, xmax, ymax = self.dados.poligono_dominio_estendido.bounds
        dx = xmax - xmin
        dy = ymax - ymin
        plt.xlim(xmin - 0.1 * dx, xmax + 0.1 * dx)
        plt.ylim(ymin - 0.1 * dy, ymax + 0.1 * dy)

        elementos_poli = []
        elementos_barra = []

        x_bar_max = 0
        if self.dados.tem_barras():
            x_bar_max = max(rho_final[self.dados.num_elementos_poli::])

        for j, el in enumerate(self.dados.elementos):
            if j < self.dados.num_elementos_poli:
                if tipo_cmap == 'jet':
                    elementos_poli.append(
                        patches.Polygon(self.dados.nos[el],
                                        linewidth=0,
                                        fill=True,
                                        facecolor=cm.jet(rho_final[j])))
                else:
                    elementos_poli.append(
                        patches.Polygon(self.dados.nos[el],
                                        linewidth=0,
                                        fill=True,
                                        facecolor=cm.binary(rho_final[j])))
            else:
                verts = [self.dados.nos[el[0]], self.dados.nos[el[1]]]
                codes = [path.Path.MOVETO, path.Path.LINETO]

                rho = 15 * rho_final[j] / x_bar_max
                # rho = 6 if rho_final[j] > 0 else 0

                if rho > 0:
                    if tipo_cmap == 'jet':
                        elementos_barra.append(
                            patches.PathPatch(path.Path(verts, codes),
                                              linewidth=rho,
                                              edgecolor='black'))
                    else:
                        elementos_barra.append(
                            patches.PathPatch(path.Path(verts, codes),
                                              linewidth=rho,
                                              edgecolor='red'))
        # Enumerar os pontos
        if self.dados.tem_barras():
            if visualizar_areas_barras:
                for i in range(self.dados.num_elementos_poli,
                               self.dados.num_elementos):
                    if rho_final[i] > 0:
                        # Centro da barra
                        nos_barra_i = self.dados.nos[self.dados.elementos[i]]
                        c = (nos_barra_i[0] + nos_barra_i[1]) / 2

                        cor = 'white' if tipo_cmap == 'jet' else 'blue'
                        ax.text(c[0],
                                c[1],
                                f'{rho_final[i] / x_bar_max:.2E}',
                                ha="center",
                                va="center",
                                size=0.05 * min(dx, dy),
                                color=cor)

        # Desenhar o domínio do desenho
        # contorno = self.dados.poligono_dominio_estendido.boundary.coords[:]
        # linhas_cont = []
        # for lin in contorno:
        #     linhas_cont.append(patches.PathPatch(path.Path(lin, [path.Path.MOVETO, path.Path.LINETO]),
        #                                          linewidth=1, edgecolor='black'))

        # Adicionar marcador do diâmetro mínimo dos elementos
        path_diam_verts = [[xmax - rmin * 2 - 0.01 * dx, ymax - 0.01 * dx],
                           [xmax - 0.01 * dx, ymax - 0.01 * dx]]
        path_diam_codes = [path.Path.MOVETO, path.Path.LINETO]
        path_diam = path.Path(path_diam_verts, path_diam_codes)
        ax.add_patch(patches.PathPatch(path_diam, linewidth=2,
                                       color='magenta'))

        ax.add_collection(PatchCollection(elementos_poli, match_original=True))

        if self.dados.tem_barras():
            ax.add_collection(
                PatchCollection(elementos_barra, match_original=True))
        # ax.add_collection(PatchCollection(linhas_cont, match_original=True))
        plt.axis('off')
        plt.grid(b=None)

        # Título
        # Fixos
        di = f'Di: {results_gerais_finais[5]:.2f}%'
        els = f'NumElems: {len(self.dados.elementos)}'
        vf = f'vol: {results_gerais_finais[4]:.4f}%'
        # Variáveis
        rmin = ''
        tecnica_otm = 'Técnica: '

        if tecnica_otimizacao == 0:
            tecnica_otm += 'Sem filtro'
        else:
            rmin = f'rmin: {rmin}'

            if tecnica_otimizacao in OC.TECNICA_OTM_EP_LINEAR:
                tecnica_otm += 'Linear '
            elif tecnica_otimizacao in OC.TECNICA_OTM_EP_HEAVISIDE:
                tecnica_otm += 'Heaviside '
            else:
                raise ValueError(
                    f'A técnica de otimização "{tecnica_otimizacao}" não é válida!'
                )

            if tecnica_otimizacao in OC.TECNICA_OTM_EP_DIRETO:
                tecnica_otm += 'direto'
            elif tecnica_otimizacao in OC.TECNICA_OTM_EP_INVERSO:
                tecnica_otm += 'inverso'
            else:
                raise ValueError(
                    f'A técnica de otimização "{tecnica_otimizacao}" não é válida!'
                )

        plt.title(f'{tecnica_otm}     {els}     {vf}     {di}    {rmin}')
        plt.show()
예제 #33
0
        add_layer(patches,
                  colors,
                  size=size_list[ind],
                  num=num_show_list[ind],
                  top_left=top_left_list[ind],
                  loc_diff=loc_diff_list[ind])
        label(top_left_list[ind],
              text_list[ind] + '\n{}'.format(num_list[ind]))

    text_list = ['Flatten\n', 'Fully\nconnected', 'Fully\nconnected']

    for ind in range(len(size_list)):
        label(top_left_list[ind], text_list[ind], xy_off=[-10, -65])

    ############################
    colors += [0, 1]
    collection = PatchCollection(patches, cmap=plt.cm.gray)
    collection.set_array(np.array(colors))
    ax.add_collection(collection)
    plt.tight_layout()
    plt.axis('equal')
    plt.axis('off')
    plt.show()
    fig.set_size_inches(8, 2.5)

    fig_dir = './'
    fig_ext = '.png'
    fig.savefig(os.path.join(fig_dir, 'convnet_fig' + fig_ext),
                bbox_inches='tight',
                pad_inches=0)
예제 #34
0
                 horizontalalignment='center',
                 verticalalignment='center',
                 fontsize=4)
        #
        #
    # if pixID[i_pix] < 51:
    # 	posX = 0.5
    # 	posY = 0.5
    # 	plt.text(pixel[0] + pixelDiameter * posX,
    # 			 pixel[1] + pixelDiameter * posY,
    # 			 pixID[i_pix],
    # 			 horizontalalignment='center',
    # 			 verticalalignment='center',
    # 			 fontsize=4)

ax3.add_collection(PatchCollection(pixels, facecolor='none', edgecolor='k'))

# plotAxesDef(plt, 0)

# ax3.add_collection(PatchCollection(edgePixels, facecolor='brown', edgecolor='C0'))
# print(gaps)
# ax3.add_collection(PatchCollection(edgePixels,
# 										 facecolor=mcolors.to_rgb('brown') + (0.5,),
# 										 edgecolor=mcolors.to_rgb('black') + (1,)))
# ax3.add_collection(PatchCollection(offPixels, facecolor='black', edgecolor='black'))

# legendObjects = [legH.pixelObject(), legH.edgePixelObject()]
# legendLabels = ['Pixel', 'Edge pixel']
# ax3.set_aspect('equal', 'datalim')
# plt.tight_layout()
xTitle = 'Horizontal scale [cm] (Y pix)'
        #axes.add_patch(p)
        patches.append(p)

    #### calc overlap for fires and enpoints
    #plot a density map of fire points that is on the same grid as the endpoints
    #multiply the values of each cell, if no enpoints or fires value is 0, else value is #hours x #fires in units of hours
    lats_f = [row[1] for row in MODIS_fires]
    lons_f = [row[2] for row in MODIS_fires]
    xs2, ys2, density_fires, max_density2 = INPmod.getGriddedData(
        nx, ny, lats_f, lons_f, m)

    #zip together the density maps for the fires and endpoints
    fire_overlap = [a * b for a, b in zip(density_trajs, density_fires)]
    print 'hours*fires ', np.sum(fire_overlap) / total_endpoints
    patch_coll = PatchCollection(patches,
                                 facecolor='#ff531a',
                                 edgecolor='#ff531a')
    fire_patches = axes.add_collection(patch_coll)

#### add deserts
if include_deserts == True:
    # create a list of possible coordinates
    g = xs, ys
    coords = list(zip(*(c.flat for c in g)))
    plot_pts = []
    endpoint_counts = []
    desert_names, desert_patches = INPmod.getDesertShapes(m)
    patch_coll_d = PatchCollection(desert_patches,
                                   facecolor='#bf8040',
                                   edgecolor='#362D0C',
                                   alpha=0.15)
예제 #36
0
    patches.append(wedge)

# Some limiting conditions on Wedge
patches += [
    Wedge((.3, .7), .1, 0, 360),             # Full circle
    Wedge((.7, .8), .2, 0, 360, width=0.05),  # Full ring
    Wedge((.8, .3), .2, 0, 45),              # Full sector
    Wedge((.8, .3), .2, 45, 90, width=0.10),  # Ring sector
]

for i in range(N):
    polygon = Polygon(np.random.rand(N, 2), True)
    patches.append(polygon)

colors = 100 * np.random.rand(len(patches))
p = PatchCollection(patches, alpha=0.4)
p.set_array(np.array(colors))
ax.add_collection(p)
fig.colorbar(p, ax=ax)

plt.show()


# 2 rectangle
import matplotlib.pyplot as plt

# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
예제 #37
0
    color_ree = 'white'
    zippy = patches[1]

    ##################################################################################
    ##################################################################################
    # Change m2011 to change the industry and year, everything else should be the same
    ##################################################################################
    ##################################################################################
    if (len(m2011[m2011['zipcode'] == zippy]['affordable'].values) > 0):
        if (m2011[m2011['zipcode'] == zippy]['affordable'].values[0]):
            color_ree = 'green'
        else:
            color_ree = 'red'
    p = PatchCollection(patches[0],
                        color=color_ree,
                        lw=.3,
                        edgecolor='k',
                        label='fdlfj')
    ax.add_collection(p)
    #     print(float(patches[3]))
    #     print(float(patches[2]))
    #     print(patches[1])
    x_coord = float(patches[3])
    y_coord = float(patches[2])
    if (x_coord > x_min and x_coord < x_max and y_coord > y_min
            and y_coord < y_max):
        ax.text(x_coord,
                y_coord,
                str(patches[1]),
                fontsize=10,
                horizontalalignment='center')
예제 #38
0
    def visualize(self):

        # will hold all bones to be plotted as line segments
        segs = []

        # point masses
        markers = []

        # anchor for first bone
        anchor_x = self.skeleton.bones[0].endpoint1.coords[0]
        anchor_y = self.skeleton.bones[0].endpoint1.coords[1]
        segs.append(((anchor_x, anchor_y + 0.05), (anchor_x, anchor_y - 0.05)))

        # add all bones to the collection of segments to be plotted
        for bone in self.skeleton.bones:
            segs.append(
                (tuple(bone.endpoint1.coords), tuple(bone.endpoint2.coords)))
            if bone.point_mass[0] != 0:
                markers.append([bone.point_mass_loc, bone.point_mass[0]])

        line_segments = LineCollection(segs, color='g', linewidth=2, zorder=2)

        muscle_segs = []

        # add all muscles to a collection of segments to be plotted
        for muscle in self.musculature.muscles:
            if isinstance(muscle, BiarticularMuscle):
                muscle_segs.append(
                    (tuple(muscle.endpoint1), tuple(muscle.wrap_point[0]),
                     tuple(muscle.wrap_point[1]), tuple(muscle.endpoint2)))
            else:

                if muscle.wraps == True:
                    muscle_segs.append(
                        (tuple(muscle.endpoint1), tuple(muscle.wrap_point),
                         tuple(muscle.endpoint2)))
                else:
                    muscle_segs.append(
                        (tuple(muscle.endpoint1), tuple(muscle.endpoint2)))

        muscle_lines = LineCollection(muscle_segs,
                                      linewidth=2,
                                      color='r',
                                      zorder=1)

        # will hold all joints and hand to be plotted as circles
        circles = []

        # add circles representing each joint
        for joint in self.skeleton.joints:
            circle = patches.Circle((joint.location[0], joint.location[1]),
                                    joint.diameter / 2,
                                    fill=True)
            circles.append(circle)

        # add circle representing hand
        circle = patches.Circle((self.skeleton.bones[-1].endpoint2.coords[0],
                                 self.skeleton.bones[-1].endpoint2.coords[1]),
                                0.015,
                                fill=True)
        circles.append(circle)

        circles_collection = PatchCollection(circles, color='k', zorder=3)

        # initialize figure
        fig, ax = plt.subplots()

        # circles look like ovals if you don't include this
        ax.axis('square')

        # formatting
        ax.set_xlabel('x')
        ax.set_ylabel('y')
        ax.set_title('Current Skeleton')
        ax.set_xlim(self.skeleton.x_lim[0], self.skeleton.x_lim[1])
        ax.set_ylim(self.skeleton.y_lim[0], self.skeleton.y_lim[1])

        # add all visualization elements
        ax.add_collection(line_segments)
        ax.add_collection(muscle_lines)
        ax.add_collection(circles_collection)
        for marker in markers:
            ax.plot(marker[0][0],
                    marker[0][1],
                    marker='s',
                    color='purple',
                    markersize=marker[1],
                    zorder=4)
예제 #39
0
per = ab + ac+ bc
Ox = (bc * A[0] + ac * B[0] + ab * C[0])/(per)
Oy = (bc * A[1] + ac * B[1] + ab * C[1])/(per)
O = (Ox, Oy)

p = per / 2
r = sqrt((p - ab)*(p - ac)*(p - bc)/p)

fig, ax = plt.subplots()

for dot in dots:
    plt.scatter(dot[0], dot[1])
plt.scatter(O[0], O[1])

plt.plot([A[0], B[0]], [A[1], B[1]])
plt.plot([C[0], B[0]], [C[1], B[1]])
plt.plot([A[0], C[0]], [A[1], C[1]])

circle = Circle((Ox, Oy), r)
patches = [circle]
p = PatchCollection(patches, alpha=0.4)
ax.add_collection(p)

plt.grid(True)
plt.show()

            
            
        
예제 #40
0
    patches.append(circle)

x = np.random.rand(N)
y = np.random.rand(N)
radii = 0.1 * np.random.rand(N)
theta1 = 360.0 * np.random.rand(N)
theta2 = 360.0 * np.random.rand(N)
for x1, y1, r, t1, t2 in zip(x, y, radii, theta1, theta2):
    wedge = Wedge((x1, y1), r, t1, t2)
    patches.append(wedge)

# Some limiting conditions on Wedge
patches += [
    Wedge((.3, .7), .1, 0, 360),  # Full circle
    Wedge((.7, .8), .2, 0, 360, width=0.05),  # Full ring
    Wedge((.8, .3), .2, 0, 45),  # Full sector
    Wedge((.8, .3), .2, 45, 90, width=0.10),  # Ring sector
]

for i in range(N):
    polygon = Polygon(np.random.rand(N, 2), True)
    patches.append(polygon)

colors = 100 * np.random.rand(len(patches))
p = PatchCollection(patches, alpha=0.4)
p.set_array(np.array(colors))
ax.add_collection(p)
fig.colorbar(p, ax=ax)

plt.show()
예제 #41
0
    def animate(self, data, save=False, muscle_tracker=None):

        # finished video fps
        video_fps = 60

        # data formatting
        joint_angles_pre_zip = []
        for joint_data in data.joints:
            joint_angles_pre_zip.append(joint_data.angle)

        joint_angles = [list(a) for a in zip(*joint_angles_pre_zip)]

        # constants for converting data fps to video fps
        data_fps = data.f_s
        num_data_frames = len(joint_angles)
        vid_length = num_data_frames / data_fps
        num_video_frames = round(vid_length * video_fps)

        # initialize figure
        fig, ax = plt.subplots()

        # circles look like ovals if you don't include this
        ax.axis('square')

        # formatting
        ax.set_xlabel('x')
        ax.set_ylabel('y')
        ax.set_title('Animated Model')
        ax.set_xlim(self.skeleton.x_lim[0], self.skeleton.x_lim[1])
        ax.set_ylim(self.skeleton.y_lim[0], self.skeleton.y_lim[1])

        # set skeleton for first frame
        self.skeleton.write_joint_angles(joint_angles[0])
        self.musculature.update_muscle_endpoints()

        # will hold all bones to be plotted as line segments
        segs = []

        markers = []

        # anchor for first bone
        anchor_x = self.skeleton.bones[0].endpoint1.coords[0]
        anchor_y = self.skeleton.bones[0].endpoint1.coords[1]
        segs.append(((anchor_x, anchor_y + 0.05), (anchor_x, anchor_y - 0.05)))

        # add all bones to the collection of segments to be plotted
        for bone in self.skeleton.bones:
            segs.append(
                (tuple(bone.endpoint1.coords), tuple(bone.endpoint2.coords)))
            if bone.point_mass[0] != 0:
                markers.append([bone.point_mass_loc, bone.point_mass[0]])

        line_segments = LineCollection(segs, color='g', linewidth=2, zorder=2)

        muscle_segs = []

        # add all muscles to a collection of segments to be plotted
        for muscle in self.musculature.muscles:
            if isinstance(muscle, BiarticularMuscle):
                muscle_segs.append(
                    (tuple(muscle.endpoint1), tuple(muscle.wrap_point[0]),
                     tuple(muscle.wrap_point[1]), tuple(muscle.endpoint2)))
            else:

                if muscle.wraps == True:
                    muscle_segs.append(
                        (tuple(muscle.endpoint1), tuple(muscle.wrap_point),
                         tuple(muscle.endpoint2)))
                else:
                    muscle_segs.append(
                        (tuple(muscle.endpoint1), tuple(muscle.endpoint2)))

        if muscle_tracker is not None:
            acts = []
            for muscle_data in muscle_tracker.muscles:
                acts.append(muscle_data.activation[0])

            colors = []
            for act in acts:
                red = act
                blue = 1 - act
                green = 0
                alpha = 1
                colors.append((red, blue, green, alpha))

            muscle_lines = LineCollection(muscle_segs,
                                          linewidth=2,
                                          colors=colors,
                                          zorder=1)

        else:
            muscle_lines = LineCollection(muscle_segs,
                                          linewidth=2,
                                          color='r',
                                          zorder=1)

        # will hold all joints and hand to be plotted as circles
        circles = []

        # add circles representing each joint
        for joint in self.skeleton.joints:
            circle = patches.Circle((joint.location[0], joint.location[1]),
                                    joint.diameter / 2,
                                    fill=True)
            circles.append(circle)

        # add circle representing hand
        circle = patches.Circle((self.skeleton.bones[-1].endpoint2.coords[0],
                                 self.skeleton.bones[-1].endpoint2.coords[1]),
                                0.015,
                                fill=True)
        circles.append(circle)

        circles_collection = PatchCollection(circles, color='k', zorder=3)

        # add visualization elements for first frame
        ax.add_collection(line_segments)
        ax.add_collection(muscle_lines)
        ax.add_collection(circles_collection)
        for marker in markers:
            ax.plot(marker[0][0],
                    marker[0][1],
                    marker='s',
                    color='purple',
                    markersize=marker[1],
                    zorder=4)

        # other stuff that needs to be passed to our animation function
        fargs = self, joint_angles, num_data_frames, num_video_frames, muscle_tracker

        # function that will be called for each frame of animation
        def func(frame, *fargs):

            # convert video frame number to data frame number
            data_frame = round((frame / num_video_frames) * num_data_frames)

            # set skeleton
            self.skeleton.write_joint_angles(joint_angles[data_frame])
            self.musculature.update_muscle_endpoints()

            # will hold all bones to be plotted as line segments
            segs = []

            markers = []

            # anchor for first bone
            anchor_x = self.skeleton.bones[0].endpoint1.coords[0]
            anchor_y = self.skeleton.bones[0].endpoint1.coords[1]
            segs.append(
                ((anchor_x, anchor_y + 0.05), (anchor_x, anchor_y - 0.05)))

            # add all bones to the collection of segments to be plotted
            for bone in self.skeleton.bones:
                segs.append((tuple(bone.endpoint1.coords),
                             tuple(bone.endpoint2.coords)))
                if bone.point_mass[0] != 0:
                    markers.append([bone.point_mass_loc, bone.point_mass[0]])

            muscle_segs = []

            # add all muscles to a collection of segments to be plotted
            for muscle in self.musculature.muscles:
                if isinstance(muscle, BiarticularMuscle):
                    muscle_segs.append(
                        (tuple(muscle.endpoint1), tuple(muscle.wrap_point[0]),
                         tuple(muscle.wrap_point[1]), tuple(muscle.endpoint2)))
                else:

                    if muscle.wraps == True:
                        muscle_segs.append(
                            (tuple(muscle.endpoint1), tuple(muscle.wrap_point),
                             tuple(muscle.endpoint2)))
                    else:
                        muscle_segs.append(
                            (tuple(muscle.endpoint1), tuple(muscle.endpoint2)))

            # will hold all joints and hand to be plotted as circles
            circles = []

            # add circles representing each joint
            for joint in self.skeleton.joints:
                circle = patches.Circle((joint.location[0], joint.location[1]),
                                        joint.diameter / 2,
                                        fill=True)
                circles.append(circle)

            # add circle representing hand
            circle = patches.Circle(
                (self.skeleton.bones[-1].endpoint2.coords[0],
                 self.skeleton.bones[-1].endpoint2.coords[1]),
                0.015,
                fill=True)
            circles.append(circle)

            if muscle_tracker is not None:
                acts = []
                for muscle_data in muscle_tracker.muscles:
                    acts.append(muscle_data.activation[data_frame])

                colors = []
                for act in acts:
                    red = act
                    green = 0
                    blue = 1 - act
                    alpha = 1
                    colors.append((red, green, blue, alpha))

                muscle_lines.set_color(colors)

            # update and plot line and circle collections
            line_segments.set_paths(segs)
            muscle_lines.set_paths(muscle_segs)
            circles_collection.set_paths(circles)

            for line in ax.lines:
                line.set_marker(None)
            for marker in markers:
                ax.plot(marker[0][0],
                        marker[0][1],
                        marker='s',
                        color='purple',
                        markersize=marker[1],
                        zorder=4)

        # animate each frame using animation function
        anim = FuncAnimation(fig,
                             func,
                             frames=num_video_frames,
                             interval=1 / video_fps)

        # save the animation as a video
        if save == True:
            # Set up formatting for the movie files
            Writer = animation.writers['ffmpeg']
            writer = Writer(fps=video_fps,
                            metadata=dict(artist='Me'),
                            bitrate=3000)
            anim.save(self.name + '.mp4', writer=writer)

        return anim
예제 #42
0
    def __init__(
        self,
        geometry,
        image=None,
        ax=None,
        title=None,
        norm="lin",
        cmap=None,
        allow_pick=False,
        autoupdate=True,
        autoscale=True,
        show_frame=True,
    ):
        self.axes = ax if ax is not None else plt.gca()
        self.pixels = None
        self.colorbar = None
        self.autoupdate = autoupdate
        self.autoscale = autoscale
        self._active_pixel = None
        self._active_pixel_label = None
        self._axes_overlays = []

        self.geom = geometry

        if title is None:
            title = f"{geometry.camera_name}"

        # initialize the plot and generate the pixels as a
        # RegularPolyCollection

        patches = []

        if hasattr(self.geom, "mask"):
            self.mask = self.geom.mask
        else:
            self.mask = np.ones_like(self.geom.pix_x.value, dtype=bool)

        pix_x = self.geom.pix_x.value[self.mask]
        pix_y = self.geom.pix_y.value[self.mask]
        pix_width = self.geom.pixel_width.value[self.mask]

        for x, y, w in zip(pix_x, pix_y, pix_width):
            if self.geom.pix_type == PixelShape.HEXAGON:
                r = w / np.sqrt(3)
                patch = RegularPolygon(
                    (x, y),
                    6,
                    radius=r,
                    orientation=self.geom.pix_rotation.to_value(u.rad),
                    fill=True,
                )
            elif self.geom.pix_type == PixelShape.CIRCLE:
                patch = Circle((x, y), radius=w / 2, fill=True)
            elif self.geom.pix_type == PixelShape.SQUARE:
                patch = Rectangle(
                    (x - w / 2, y - w / 2),
                    width=w,
                    height=w,
                    angle=self.geom.pix_rotation.to_value(u.deg),
                    fill=True,
                )

            patches.append(patch)

        self.pixels = PatchCollection(patches, cmap=cmap, linewidth=0)
        self.axes.add_collection(self.pixels)

        self.pixel_highlighting = copy.copy(self.pixels)
        self.pixel_highlighting.set_facecolor("none")
        self.pixel_highlighting.set_linewidth(0)
        self.axes.add_collection(self.pixel_highlighting)

        # Set up some nice plot defaults

        self.axes.set_aspect("equal", "datalim")
        self.axes.set_title(title)
        self.axes.autoscale_view()

        if show_frame:
            self.add_frame_name()
        # set up a patch to display when a pixel is clicked (and
        # pixel_picker is enabled):

        self._active_pixel = copy.copy(patches[0])
        self._active_pixel.set_facecolor("r")
        self._active_pixel.set_alpha(0.5)
        self._active_pixel.set_linewidth(2.0)
        self._active_pixel.set_visible(False)
        self.axes.add_patch(self._active_pixel)

        if hasattr(self._active_pixel, "xy"):
            center = self._active_pixel.xy
        else:
            center = self._active_pixel.center

        self._active_pixel_label = self.axes.text(*center,
                                                  "0",
                                                  horizontalalignment="center",
                                                  verticalalignment="center")
        self._active_pixel_label.set_visible(False)

        # enable ability to click on pixel and do something (can be
        # enabled on-the-fly later as well:

        if allow_pick:
            self.enable_pixel_picker()

        if image is not None:
            self.image = image
        else:
            self.image = np.zeros_like(self.geom.pix_id, dtype=np.float64)

        self.norm = norm
        self.auto_set_axes_labels()
예제 #43
0
class CameraDisplay:
    """
    Camera Display using matplotlib.

    Parameters
    ----------
    geometry : `~ctapipe.instrument.CameraGeometry`
        Definition of the Camera/Image
    image: array_like
        array of values corresponding to the pixels in the CameraGeometry.
    ax : `matplotlib.axes.Axes`
        A matplotlib axes object to plot on, or None to create a new one
    title : str (default "Camera")
        Title to put on camera plot
    norm : str or `matplotlib.color.Normalize` instance (default 'lin')
        Normalization for the color scale.
        Supported str arguments are
        - 'lin': linear scale
        - 'log': logarithmic scale (base 10)
    cmap : str or `matplotlib.colors.Colormap` (default 'hot')
        Color map to use (see `matplotlib.cm`)
    allow_pick : bool (default False)
        if True, allow user to click and select a pixel
    autoupdate : bool (default True)
        redraw automatically (otherwise need to call plt.draw())
    autoscale : bool (default True)
        rescale the vmin/vmax values when the image changes.
        This is set to False if `set_limits_*` is called to explicity
        set data limits.

    Notes
    -----

    Speed:
        CameraDisplay is not intended to be very fast (matplotlib
        is not a very speed performant graphics library, it is
        intended for nice output plots). However, most of the
        slowness of CameraDisplay is in the constructor.  Once one is
        displayed, changing the image that is displayed is relatively
        fast and efficient. Therefore it is best to initialize an
        instance, and change the data, rather than generating new
        CameraDisplays.

    Pixel Implementation:
        Pixels are rendered as a
        `matplotlib.collections.PatchCollection` of Polygons (either 6
        or 4 sided).  You can access the PatchCollection directly (to
        e.g. change low-level style parameters) via
        `CameraDisplay.pixels`

    Output:
        Since CameraDisplay uses matplotlib, any display can be
        saved to any output file supported via
        plt.savefig(filename). This includes ``.pdf`` and ``.png``.

    """
    def __init__(
        self,
        geometry,
        image=None,
        ax=None,
        title=None,
        norm="lin",
        cmap=None,
        allow_pick=False,
        autoupdate=True,
        autoscale=True,
        show_frame=True,
    ):
        self.axes = ax if ax is not None else plt.gca()
        self.pixels = None
        self.colorbar = None
        self.autoupdate = autoupdate
        self.autoscale = autoscale
        self._active_pixel = None
        self._active_pixel_label = None
        self._axes_overlays = []

        self.geom = geometry

        if title is None:
            title = f"{geometry.camera_name}"

        # initialize the plot and generate the pixels as a
        # RegularPolyCollection

        patches = []

        if hasattr(self.geom, "mask"):
            self.mask = self.geom.mask
        else:
            self.mask = np.ones_like(self.geom.pix_x.value, dtype=bool)

        pix_x = self.geom.pix_x.value[self.mask]
        pix_y = self.geom.pix_y.value[self.mask]
        pix_width = self.geom.pixel_width.value[self.mask]

        for x, y, w in zip(pix_x, pix_y, pix_width):
            if self.geom.pix_type == PixelShape.HEXAGON:
                r = w / np.sqrt(3)
                patch = RegularPolygon(
                    (x, y),
                    6,
                    radius=r,
                    orientation=self.geom.pix_rotation.to_value(u.rad),
                    fill=True,
                )
            elif self.geom.pix_type == PixelShape.CIRCLE:
                patch = Circle((x, y), radius=w / 2, fill=True)
            elif self.geom.pix_type == PixelShape.SQUARE:
                patch = Rectangle(
                    (x - w / 2, y - w / 2),
                    width=w,
                    height=w,
                    angle=self.geom.pix_rotation.to_value(u.deg),
                    fill=True,
                )

            patches.append(patch)

        self.pixels = PatchCollection(patches, cmap=cmap, linewidth=0)
        self.axes.add_collection(self.pixels)

        self.pixel_highlighting = copy.copy(self.pixels)
        self.pixel_highlighting.set_facecolor("none")
        self.pixel_highlighting.set_linewidth(0)
        self.axes.add_collection(self.pixel_highlighting)

        # Set up some nice plot defaults

        self.axes.set_aspect("equal", "datalim")
        self.axes.set_title(title)
        self.axes.autoscale_view()

        if show_frame:
            self.add_frame_name()
        # set up a patch to display when a pixel is clicked (and
        # pixel_picker is enabled):

        self._active_pixel = copy.copy(patches[0])
        self._active_pixel.set_facecolor("r")
        self._active_pixel.set_alpha(0.5)
        self._active_pixel.set_linewidth(2.0)
        self._active_pixel.set_visible(False)
        self.axes.add_patch(self._active_pixel)

        if hasattr(self._active_pixel, "xy"):
            center = self._active_pixel.xy
        else:
            center = self._active_pixel.center

        self._active_pixel_label = self.axes.text(*center,
                                                  "0",
                                                  horizontalalignment="center",
                                                  verticalalignment="center")
        self._active_pixel_label.set_visible(False)

        # enable ability to click on pixel and do something (can be
        # enabled on-the-fly later as well:

        if allow_pick:
            self.enable_pixel_picker()

        if image is not None:
            self.image = image
        else:
            self.image = np.zeros_like(self.geom.pix_id, dtype=np.float64)

        self.norm = norm
        self.auto_set_axes_labels()

    def highlight_pixels(self, pixels, color="g", linewidth=1, alpha=0.75):
        """
        Highlight the given pixels with a colored line around them

        Parameters
        ----------
        pixels : index-like
            The pixels to highlight.
            Can either be a list or array of integers or a
            boolean mask of length number of pixels
        color: a matplotlib conform color
            the color for the pixel highlighting
        linewidth: float
            linewidth of the highlighting in points
        alpha: 0 <= alpha <= 1
            The transparency
        """

        l = np.zeros_like(self.image)
        l[pixels] = linewidth
        self.pixel_highlighting.set_linewidth(l)
        self.pixel_highlighting.set_alpha(alpha)
        self.pixel_highlighting.set_edgecolor(color)
        self._update()

    def enable_pixel_picker(self):
        """ enable ability to click on pixels """
        self.pixels.set_picker(True)  # enable click
        self.pixels.set_pickradius(
            sqrt(u.Quantity(self.geom.pix_area[0]).value) / np.pi)
        self.pixels.set_snap(True)  # snap cursor to pixel center
        self.axes.figure.canvas.mpl_connect("pick_event", self._on_pick)

    def set_limits_minmax(self, zmin, zmax):
        """ set the color scale limits from min to max """
        self.pixels.set_clim(zmin, zmax)
        self.autoscale = False
        self._update()

    def set_limits_percent(self, percent=95):
        """ auto-scale the color range to percent of maximum """
        zmin = np.nanmin(self.pixels.get_array())
        zmax = np.nanmax(self.pixels.get_array())
        dz = zmax - zmin
        frac = percent / 100.0
        self.autoscale = False
        self.set_limits_minmax(zmin, zmax - (1.0 - frac) * dz)

    @property
    def norm(self):
        """
        The norm instance of the Display

        Possible values:

        - "lin": linear scale
        - "log": log scale (cannot have negative values)
        - "symlog": symmetric log scale (negative values are ok)
        -  any matplotlib.colors.Normalize instance, e. g. PowerNorm(gamma=-2)
        """
        return self.pixels.norm

    @norm.setter
    def norm(self, norm):

        if norm == "lin":
            self.pixels.norm = Normalize()
        elif norm == "log":
            self.pixels.norm = LogNorm()
            self.pixels.autoscale()  # this is to handle matplotlib bug #5424
        elif norm == "symlog":
            self.pixels.norm = SymLogNorm(linthresh=1.0, base=10)
            self.pixels.autoscale()
        elif isinstance(norm, Normalize):
            self.pixels.norm = norm
        else:
            raise ValueError(
                "Unsupported norm: '{}', options are 'lin',"
                "'log','symlog', or a matplotlib Normalize object".format(
                    norm))

        self.update(force=True)
        self.pixels.autoscale()

    @property
    def cmap(self):
        """
        Color map to use. Either a name or  `matplotlib.colors.ColorMap`
        instance, e.g. from `matplotlib.pyplot.cm`
        """
        return self.pixels.get_cmap()

    @cmap.setter
    def cmap(self, cmap):
        self.pixels.set_cmap(cmap)
        self._update()

    @property
    def image(self):
        """The image displayed on the camera (1D array of pixel values)"""
        return self.pixels.get_array()

    @image.setter
    def image(self, image):
        """
        Change the image displayed on the Camera.

        Parameters
        ----------
        image: array_like
            array of values corresponding to the pixels in the CameraGeometry.
        """
        image = np.asanyarray(image)
        if image.shape != self.geom.pix_x.shape:
            raise ValueError(
                ("Image has a different shape {} than the "
                 "given CameraGeometry {}").format(image.shape,
                                                   self.geom.pix_x.shape))

        self.pixels.set_array(np.ma.masked_invalid(image[self.mask]))
        self.pixels.changed()
        if self.autoscale:
            self.pixels.autoscale()
        self._update()

    def _update(self, force=False):
        """ signal a redraw if autoupdate is turned on """
        if self.autoupdate:
            self.update(force)

    def update(self, force=False):
        """ redraw the display now """
        self.axes.figure.canvas.draw()
        if self.colorbar is not None:
            if force is True:
                self.colorbar.update_bruteforce(self.pixels)
            else:
                self.colorbar.update_normal(self.pixels)
            self.colorbar.draw_all()

    def add_colorbar(self, **kwargs):
        """
        add a colorbar to the camera plot
        kwargs are passed to `figure.colorbar(self.pixels, **kwargs)`
        See matplotlib documentation for the supported kwargs:
        http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.colorbar
        """
        if self.colorbar is not None:
            raise ValueError(
                "There is already a colorbar attached to this CameraDisplay")
        else:
            if "ax" not in kwargs:
                kwargs["ax"] = self.axes
            self.colorbar = self.axes.figure.colorbar(self.pixels, **kwargs)
        self.update()

    def add_ellipse(self,
                    centroid,
                    length,
                    width,
                    angle,
                    asymmetry=0.0,
                    **kwargs):
        """
        plot an ellipse on top of the camera

        Parameters
        ----------
        centroid: (float, float)
            position of centroid
        length: float
            major axis
        width: float
            minor axis
        angle: float
            rotation angle wrt x-axis about the centroid, anticlockwise, in radians
        asymmetry: float
            3rd-order moment for directionality if known
        kwargs:
            any MatPlotLib style arguments to pass to the Ellipse patch

        """
        ellipse = Ellipse(
            xy=centroid,
            width=length,
            height=width,
            angle=np.degrees(angle),
            fill=False,
            **kwargs,
        )
        self.axes.add_patch(ellipse)
        self.update()
        return ellipse

    def overlay_moments(self,
                        hillas_parameters,
                        with_label=True,
                        keep_old=False,
                        **kwargs):
        """helper to overlay ellipse from a `HillasParametersContainer` structure

        Parameters
        ----------
        hillas_parameters: `HillasParametersContainer`
            structuring containing Hillas-style parameterization
        with_label: bool
            If True, show coordinates of centroid and width and length
        keep_old: bool
            If True, to not remove old overlays
        kwargs: key=value
            any style keywords to pass to matplotlib (e.g. color='red'
            or linewidth=6)
        """
        if not keep_old:
            self.clear_overlays()

        # strip off any units
        cen_x = u.Quantity(hillas_parameters.x).value
        cen_y = u.Quantity(hillas_parameters.y).value
        length = u.Quantity(hillas_parameters.length).value
        width = u.Quantity(hillas_parameters.width).value

        el = self.add_ellipse(
            centroid=(cen_x, cen_y),
            length=length * 2,
            width=width * 2,
            angle=hillas_parameters.psi.to_value("rad"),
            **kwargs,
        )

        self._axes_overlays.append(el)

        if with_label:
            text = self.axes.text(
                cen_x,
                cen_y,
                "({:.02f},{:.02f})\n[w={:.02f},l={:.02f}]".format(
                    hillas_parameters.x,
                    hillas_parameters.y,
                    hillas_parameters.width,
                    hillas_parameters.length,
                ),
                color=el.get_edgecolor(),
            )

            self._axes_overlays.append(text)

    def clear_overlays(self):
        """ Remove added overlays from the axes """
        while self._axes_overlays:
            overlay = self._axes_overlays.pop()
            overlay.remove()

    def _on_pick(self, event):
        """ handler for when a pixel is clicked """
        pix_id = event.ind[-1]
        xx, yy, aa = (
            u.Quantity(self.geom.pix_x[pix_id]).value,
            u.Quantity(self.geom.pix_y[pix_id]).value,
            u.Quantity(np.array(self.geom.pix_area)[pix_id]),
        )
        if self.geom.pix_type.startswith("hex"):
            self._active_pixel.xy = (xx, yy)
        else:
            rr = sqrt(aa)
            self._active_pixel.xy = (xx - rr / 2.0, yy - rr / 2.0)
        self._active_pixel.set_visible(True)
        self._active_pixel_label.set_x(xx)
        self._active_pixel_label.set_y(yy)
        self._active_pixel_label.set_text(f"{pix_id:003d}")
        self._active_pixel_label.set_visible(True)
        self._update()
        self.on_pixel_clicked(pix_id)  # call user-function

    def on_pixel_clicked(self, pix_id):
        """virtual function to overide in sub-classes to do something special
        when a pixel is clicked
        """
        print(f"Clicked pixel_id {pix_id}")

    def show(self):
        self.axes.figure.show()

    def auto_set_axes_labels(self):
        """ set the axes labels based on the Frame attribute"""
        axes_labels = ("X", "Y")
        if self.geom.frame is not None:
            axes_labels = list(
                self.geom.frame.get_representation_component_names().keys())

        self.axes.set_xlabel(f"{axes_labels[0]}  ({self.geom.pix_x.unit})")
        self.axes.set_ylabel(f"{axes_labels[1]}  ({self.geom.pix_y.unit})")

    def add_frame_name(self, color="grey"):
        """ label the frame type of the display (e.g. CameraFrame) """

        frame_name = (self.geom.frame.__class__.__name__
                      if self.geom.frame is not None else "Unknown Frame")
        self.axes.text(  # position text relative to Axes
            1.0,
            0.0,
            frame_name,
            ha="right",
            va="bottom",
            transform=self.axes.transAxes,
            color=color,
            fontsize="smaller",
        )
예제 #44
0
파일: utils.py 프로젝트: XJLOVEXXH/afw
def plotFocalPlane(camera, fieldSizeDeg_x=0, fieldSizeDeg_y=None, dx=0.1, dy=0.1, figsize=(10., 10.),
                   useIds=False, showFig=True, savePath=None):
    """Make a plot of the focal plane along with a set points that sample
    the field of view.

    Parameters
    ----------
    camera : `lsst.afw.cameraGeom.Camera`
        A camera object
    fieldSizeDeg_x : `float`
        Amount of the field to sample in x in degrees
    fieldSizeDeg_y : `float` or `None`
        Amount of the field to sample in y in degrees
    dx : `float`
        Spacing of sample points in x in degrees
    dy : `float`
        Spacing of sample points in y in degrees
    figsize : `tuple` containing two `float`
        Matplotlib style tuple indicating the size of the figure in inches
    useIds : `bool`
        Label detectors by name, not id?
    showFig : `bool`
        Display the figure on the screen?
    savePath : `str` or `None`
        If not `None`, save a copy of the figure to this name.
    """
    try:
        from matplotlib.patches import Polygon
        from matplotlib.collections import PatchCollection
        import matplotlib.pyplot as plt
    except ImportError:
        raise ImportError(
            "Can't run plotFocalPlane: matplotlib has not been set up")

    if fieldSizeDeg_x:
        if fieldSizeDeg_y is None:
            fieldSizeDeg_y = fieldSizeDeg_x

        field_gridx, field_gridy = numpy.meshgrid(
            numpy.arange(0., fieldSizeDeg_x + dx, dx) - fieldSizeDeg_x/2.,
            numpy.arange(0., fieldSizeDeg_y + dy, dy) - fieldSizeDeg_y/2.)
        field_gridx, field_gridy = field_gridx.flatten(), field_gridy.flatten()
    else:
        field_gridx, field_gridy = [], []

    xs = []
    ys = []
    pcolors = []

    # compute focal plane positions corresponding to field angles field_gridx, field_gridy
    posFieldAngleList = [lsst.geom.Point2D(x*lsst.geom.radians, y*lsst.geom.radians)
                         for x, y in zip(field_gridx, field_gridy)]
    posFocalPlaneList = camera.transform(posFieldAngleList, FIELD_ANGLE, FOCAL_PLANE)
    for posFocalPlane in posFocalPlaneList:
        xs.append(posFocalPlane.getX())
        ys.append(posFocalPlane.getY())
        dets = camera.findDetectors(posFocalPlane, FOCAL_PLANE)
        if len(dets) > 0:
            pcolors.append('w')
        else:
            pcolors.append('k')

    colorMap = {DetectorType.SCIENCE: 'b', DetectorType.FOCUS: 'y',
                DetectorType.GUIDER: 'g', DetectorType.WAVEFRONT: 'r'}

    patches = []
    colors = []
    plt.figure(figsize=figsize)
    ax = plt.gca()
    xvals = []
    yvals = []
    for det in camera:
        corners = [(c.getX(), c.getY()) for c in det.getCorners(FOCAL_PLANE)]
        for corner in corners:
            xvals.append(corner[0])
            yvals.append(corner[1])
        colors.append(colorMap[det.getType()])
        patches.append(Polygon(corners, True))
        center = det.getOrientation().getFpPosition()
        ax.text(center.getX(), center.getY(), det.getId() if useIds else det.getName(),
                horizontalalignment='center', size=6)

    patchCollection = PatchCollection(patches, alpha=0.6, facecolor=colors)
    ax.add_collection(patchCollection)
    ax.scatter(xs, ys, s=10, alpha=.7, linewidths=0., c=pcolors)
    ax.set_xlim(min(xvals) - abs(0.1*min(xvals)),
                max(xvals) + abs(0.1*max(xvals)))
    ax.set_ylim(min(yvals) - abs(0.1*min(yvals)),
                max(yvals) + abs(0.1*max(yvals)))
    ax.set_xlabel('Focal Plane X (mm)')
    ax.set_ylabel('Focal Plane Y (mm)')
    if savePath is not None:
        plt.savefig(savePath)
    if showFig:
        plt.show()
예제 #45
0
class HexModelGrid(VoronoiDelaunayGrid):
    """A grid of hexagonal cells.

    This inherited class implements a regular 2D grid with hexagonal cells and
    triangular patches. It is a special type of VoronoiDelaunay grid in which
    the initial set of points is arranged in a triangular/hexagonal lattice.

    Parameters
    ----------
    base_num_rows : int
        Number of rows of nodes in the left column.
    base_num_cols : int
        Number of nodes on the first row.
    dx : float, optional
        Node spacing.
    orientation : string, optional
        One of the 3 cardinal directions in the grid, either 'horizontal'
        (default) or 'vertical'
    shape : string, optional
        Controls the shape of the bounding hull, i.e., are the nodes arranged
        in a hexagon, or a rectangle? Either 'hex' (default) or 'rect'.

    Returns
    -------
    HexModelGrid
        A newly-created grid.

    Examples
    --------
    Create a hex grid with 2 rows of nodes. The first and third rows will
    have 2 nodes, and the second nodes.

    >>> from landlab import HexModelGrid
    >>> hmg = HexModelGrid(3, 2, 1.0)
    >>> hmg.number_of_nodes
    7
    """
    def __init__(self,
                 base_num_rows=0,
                 base_num_cols=0,
                 dx=1.0,
                 orientation='horizontal',
                 shape='hex',
                 reorient_links=True,
                 **kwds):
        """Create a grid of hexagonal cells.

        Create a regular 2D grid with hexagonal cells and triangular patches.
        It is a special type of VoronoiDelaunay grid in which the initial set
        of points is arranged in a triangular/hexagonal lattice.

        Parameters
        ----------
        base_num_rows : int
            Number of rows of nodes in the left column.
        base_num_cols : int
            Number of nodes on the first row.
        dx : float, optional
            Node spacing.
        orientation : string, optional
            One of the 3 cardinal directions in the grid, either 'horizontal'
            (default) or 'vertical'

        Returns
        -------
        HexModelGrid
            A newly-created grid.

        Examples
        --------
        Create a hex grid with 2 rows of nodes. The first and third rows will
        have 2 nodes, and the second nodes.

        >>> from landlab import HexModelGrid
        >>> hmg = HexModelGrid(3, 2, 1.0)
        >>> hmg.number_of_nodes
        7
        """
        # Set number of nodes, and initialize if caller has given dimensions
        if base_num_rows * base_num_cols > 0:
            self._initialize(base_num_rows, base_num_cols, dx, orientation,
                             shape, reorient_links)
        super(HexModelGrid, self).__init__(**kwds)

    @classmethod
    def from_dict(cls, params):
        """
        LLCATS: GINF
        """
        shape = params['shape']
        spacing = params.get('spacing', 1.)

        return cls(shape[0], shape[1], spacing)

    def _initialize(self,
                    base_num_rows,
                    base_num_cols,
                    dx,
                    orientation,
                    shape,
                    reorient_links=True):
        r"""Set up a hexagonal grid.

        Sets up a hexagonal grid with cell spacing dx and
        (by default) regular boundaries (that is, all perimeter cells are
        boundaries and all interior cells are active).

        Parameters
        ----------
        base_num_rows : int
            Number of rows along left side of grid
        base_num_cols : int
            Number of columns along bottom side of grid
        dx : float
            Distance between nodes
        orientation : string
            Either 'horizontal' (default in __init__) or 'vertical'
        shape : string
            Either 'hex' (default in __init__) or 'rect'
        reorient_links : bool
            Whether or not to re-orient all links to point between -45 deg
            and +135 deg clockwise from "north" (i.e., along y axis)

        Returns
        -------
        (none)

        Creates/modifies
        ----------------
        Creates and initializes and self._dx

        Notes
        -----
        To be consistent with unstructured grids, the hex grid is
        managed not as a 2D array but rather as a set of arrays that
        describe connectivity information between nodes, links, cells, faces,
        patches, corners, and junctions.

        'Horizontal' orientation means that one of the 3 axes of the grid is
        horizontal, whereas the other two are at 30 degree angles to the
        horizontal, like:

            \ /
           -----
            / \

        'Vertical' means that one axis is vertical, with the other
        two at 30 degree angles to the vertical, more like:

           \   |   /
             \ | /
             / | \
           /   |   \

        (of course, these keyboard characters don't represent the angles quite
        right)

        Numbers of rows and columns: a hex grid with a rectangular shape will
        have a fixed number of rows and columns, and so for rectangular shaped
        grids we record this information in self._nrows and self._ncols. With
        a hex-shaped grid, either the number of columns (if 'horizontal') or
        the number of rows (if 'vertical') will vary across the grid.
        Therefore, for hex-shaped grids we record only self._nrows for
        'horizontal' grids, and only self._ncols for 'vertical' grids.
        """
        if self._DEBUG_TRACK_METHODS:
            six.print_('HexModelGrid._initialize(' + str(base_num_rows) +
                       ', ' + str(base_num_cols) + ', ' + str(dx) + ')')

        # Make sure the parameter *orientation* is correct
        assert (orientation[0].lower() == 'h' or
                orientation[0].lower() == 'v'), \
            'orientation must be either "horizontal" (default) or "vertical"'

        # Make sure the parameter *shape* is correct
        assert (shape[0].lower() == 'h' or shape[0].lower() == 'r'), \
            'shape must be either "hex" (default) or "rect"'

        # Create a set of hexagonally arranged points. These will be our nodes.
        if orientation[0].lower() == 'h' and shape[0].lower() == 'h':
            pts = HexModelGrid._hex_points_with_horizontal_hex(
                base_num_rows, base_num_cols, dx)
            self.orientation = 'horizontal'
            self._nrows = base_num_rows
        elif orientation[0].lower() == 'h' and shape[0].lower() == 'r':
            pts = HexModelGrid._hex_points_with_horizontal_rect(
                base_num_rows, base_num_cols, dx)
            self.orientation = 'horizontal'
            self._nrows = base_num_rows
            self._ncols = base_num_cols
            self._shape = (self._nrows, self._ncols)
            self._nodes = numpy.arange(self._nrows * self._ncols,
                                       dtype=int).reshape(self._shape)
        elif orientation[0].lower() == 'v' and shape[0].lower() == 'h':
            pts = HexModelGrid._hex_points_with_vertical_hex(
                base_num_rows, base_num_cols, dx)
            self.orientation = 'vertical'
            self._ncols = base_num_cols
        else:
            pts = HexModelGrid._hex_points_with_vertical_rect(
                base_num_rows, base_num_cols, dx)
            self.orientation = 'vertical'
            self._nrows = base_num_rows
            self._ncols = base_num_cols
            self._shape = (self._nrows, self._ncols)
            self._nodes = numpy.arange(self._nrows * self._ncols,
                                       dtype=int).reshape(self._shape)
            for col in range(self._ncols):
                base_node = (col // 2) + (col % 2) * ((self._ncols + 1) // 2)
                self._nodes[:, col] = numpy.arange(base_node,
                                                   self._nrows * self._ncols,
                                                   self._ncols)

        # Call the VoronoiDelaunayGrid constructor to triangulate/Voronoi
        # the nodes into a grid.
        super(HexModelGrid, self)._initialize(pts[:, 0], pts[:, 1],
                                              reorient_links)

        # Remember grid spacing
        self._dx = dx

    def _create_cell_areas_array(self):
        r"""Create an array of surface areas of hexagonal cells.

        Creates and returns an array containing the surface areas of the
        hexagonal (Voronoi) cells.

        These cells are perfect hexagons in which the apothem is dx/2. The
        formula for area is:

        .. math::
            A = 3 dx^2 / 2 \sqrt{3} \approx 0.866 dx^2
        """
        self._area_of_cell = (0.8660254 * self._dx**2 +
                              numpy.zeros(self.number_of_cells))
        return self._area_of_cell

    @staticmethod
    def _hex_points_with_horizontal_hex(num_rows, base_num_cols, dxh):
        """Create a set of points on a staggered grid.

        Creates and returns a set of (x,y) points in a staggered grid in which
        the points represent the centers of regular hexagonal cells, and the
        points could be connected to form equilateral triangles. The overall
        shape of the lattice is hexagonal, and one of the 3 axes is horizontal.

        Parameters
        ----------
        num_rows : int
            Number of rows in lattice
        base_num_cols : int
            Number of columns in the bottom and top rows (middle rows have
            more)
        dxh : float
            Horizontal and diagonal spacing between points

        Returns
        -------
        poinst : ndarray
            A 2D numpy array containing point (x,y) coordinates, and total
            number of points.

        Examples
        --------
        >>> from landlab import HexModelGrid
        >>> points = HexModelGrid._hex_points_with_horizontal_hex(3, 2, 1.0)
        >>> len(points)
        7
        >>> points[1, :]
        array([ 1.,  0.])
        >>> points[:3, 0]
        array([ 0. ,  1. , -0.5])
        """
        dxv = dxh * numpy.sqrt(3.) / 2.
        half_dxh = dxh / 2.

        if numpy.mod(num_rows, 2) == 0:  # even number of rows
            npts = num_rows * base_num_cols + (num_rows * num_rows) // 4
        else:  # odd number of rows
            npts = num_rows * base_num_cols + \
                ((num_rows - 1) // 2) * ((num_rows - 1) // 2)
        pts = numpy.zeros((npts, 2))
        middle_row = num_rows // 2
        extra_cols = 0
        xshift = 0.
        i = 0
        for r in range(num_rows):
            for c in range(base_num_cols + extra_cols):
                pts[i, 0] = c * dxh + xshift
                pts[i, 1] = r * dxv
                i += 1
            if r < middle_row:
                extra_cols += 1
            else:
                extra_cols -= 1
            xshift = -half_dxh * extra_cols

        return pts

    @staticmethod
    def _hex_points_with_horizontal_rect(num_rows, num_cols, dxh):
        """Create a set of points in a taggered grid.
        Creates and returns a set of (x,y) points in a staggered grid in which
        the points represent the centers of regular hexagonal cells, and the
        points could be connected to form equilateral triangles. The overall
        shape of the lattice is rectangular, and one of the 3 axes is
        horizontal.

        Parameters
        ----------
        num_rows : int
            Number of rows in lattice
        num_cols : int
            Number of columns in lattice
        dxh : float
            Horizontal and diagonal spacing between points

        Returns
        -------
        points : ndarray of shape `(n_points, 2)`
            A 2D numpy array containing point (x, y) coordinates, and total
            number of points.

        Examples
        --------
        >>> from landlab import HexModelGrid
        >>> points = HexModelGrid._hex_points_with_horizontal_rect(3, 3, 1.0)
        >>> len(points)
        9
        >>> points[1, :]
        array([ 1.,  0.])
        >>> points[:3, 0]
        array([ 0.,  1.,  2.])
        """
        dxv = dxh * numpy.sqrt(3.) / 2.
        half_dxh = dxh / 2.

        npts = num_rows * num_cols
        pts = numpy.zeros((npts, 2))
        xshift = 0.
        i = 0
        for r in range(num_rows):
            for c in range(num_cols):
                xshift = half_dxh * (r % 2)
                pts[i, 0] = c * dxh + xshift
                pts[i, 1] = r * dxv
                i += 1

        return pts

    @staticmethod
    def _hex_points_with_vertical_hex(base_num_rows, num_cols, dxv):
        """
        Creates and returns a set of (x,y) points in a staggered grid in which
        the points represent the centers of regular hexagonal cells, and the
        points could be connected to form equilateral triangles. The overall
        shape of the lattice is hexagonal.

        Parameters
        ----------
        base_num_rows : int
            Number of columns in the left and right columns (middle columns
            have more)
        num_cols : int
            Number of columns in lattice
        dxv : float
            Vertical and diagonal spacing between points

        Returns
        -------
        points : ndarray of shape `(n_points, 2)`
            2D numpy array containing point (x,y) coordinates, and total
            number of points.

        Examples
        --------
        >>> from landlab import HexModelGrid
        >>> points = HexModelGrid._hex_points_with_vertical_hex(2, 3, 1.0)
        >>> len(points)
        7
        >>> points[1, :]
        array([ 0.,  1.])
        >>> points[:3, 1]
        array([ 0. ,  1. , -0.5])
        """
        dxh = dxv * numpy.sqrt(3.) / 2.
        half_dxv = dxv / 2.

        if numpy.mod(num_cols, 2) == 0:  # even number of columns
            npts = base_num_rows * num_cols + (num_cols * num_cols) // 4
        else:  # odd number of columns
            npts = base_num_rows * num_cols + \
                ((num_cols - 1) // 2) * ((num_cols - 1) // 2)
        pts = numpy.zeros((npts, 2))
        middle_col = num_cols // 2
        extra_rows = 0
        yshift = 0.
        i = 0
        for c in range(num_cols):
            for r in range(base_num_rows + extra_rows):
                pts[i, 1] = r * dxv + yshift
                pts[i, 0] = c * dxh
                i += 1
            if c < middle_col:
                extra_rows += 1
            else:
                extra_rows -= 1
            yshift = -half_dxv * extra_rows

        return pts

    @staticmethod
    def _hex_points_with_vertical_rect(num_rows, num_cols, dxv):
        """
        Creates and returns a set of (x,y) points in a staggered grid in which
        the points represent the centers of regular hexagonal cells, and the
        points could be connected to form equilateral triangles. The overall
        shape of the lattice is rectangular.

        Parameters
        ----------
        num_rows : int
            Number of columns in lattice
        num_cols : int
            Number of columns in lattice
        dxv : float
            Vertical and diagonal spacing between points

        Returns
        -------
        points : ndarray of shape `(n_points, 2)`
            2D numpy array containing point (x,y) coordinates, and total
            number of points.

        Examples
        --------
        >>> from landlab import HexModelGrid
        >>> points = HexModelGrid._hex_points_with_vertical_rect(3, 3, 1.0)
        >>> len(points)
        9
        >>> points[1, :]
        array([ 0.,  1.])
        >>> points[:3, 1]
        array([ 0.,  1.,  2.])
        """
        dxh = dxv * numpy.sqrt(3.) / 2.
        half_dxv = dxv / 2.

        npts = num_rows * num_cols
        pts = numpy.zeros((npts, 2))
        yshift = 0.
        i = 0
        for c in range(num_cols):
            for r in range(num_rows):
                yshift = half_dxv * (c % 2)
                pts[i, 1] = r * dxv + yshift
                pts[i, 0] = c * dxh
                i += 1

        return pts

    @property
    def number_of_node_columns(self):
        """Number of node columns hex grid.

        Number of node columns in a rectangular-shaped and/or
        vertically oriented hex grid.

        Returns the number of columns, including boundaries.

        Notes
        -----
        Will generate an error if called with a hex-shaped, horizontally
        aligned grid.

        Examples
        --------
        >>> from landlab import HexModelGrid
        >>> grid = HexModelGrid(5, 5, shape='rect')
        >>> grid.number_of_node_columns
        5

        LLCATS: GINF NINF
        """
        return self._ncols

    @property
    def number_of_node_rows(self):
        """Number of node rows in a rectangular-shaped and/or
        horizontally oriented hex grid.

        Returns the number of rows, including boundaries.

        Notes
        -----
        Will generate an error if called with a hex-shaped, vertically
        aligned grid.

        Examples
        --------
        >>> from landlab import HexModelGrid
        >>> grid = HexModelGrid(5, 5, shape='rect')
        >>> grid.number_of_node_rows
        5

        LLCATS: GINF NINF
        """
        return self._nrows

    @property
    def nodes_at_left_edge(self):
        """Get nodes along the left edge of a grid, if grid is rectangular.

        Examples
        --------
        >>> import numpy as np
        >>> from landlab import HexModelGrid
        >>> grid = HexModelGrid(3, 4, shape='rect')
        >>> grid.nodes_at_left_edge
        array([0, 4, 8])

        LLCATS: NINF BC SUBSET
        """
        try:
            return self._nodes[:, 0]
        except AttributeError:
            raise AttributeError(
                'Only rectangular Hex grids have defined edges.')

    @property
    def nodes_at_right_edge(self):
        """Get nodes along the right edge of a grid, if grid is rectangular.

        Examples
        --------
        >>> import numpy as np
        >>> from landlab import HexModelGrid
        >>> grid = HexModelGrid(3, 4, shape='rect')
        >>> grid.nodes_at_right_edge
        array([ 3,  7, 11])

        LLCATS: NINF BC SUBSET
        """
        try:
            return self._nodes[:, -1]
        except AttributeError:
            raise AttributeError(
                'Only rectangular Hex grids have defined edges.')

    @property
    def nodes_at_top_edge(self):
        """Get nodes along the top edge of a grid, if grid is rectangular.

        Examples
        --------
        >>> import numpy as np
        >>> from landlab import HexModelGrid
        >>> grid = HexModelGrid(3, 4, shape='rect')
        >>> grid.nodes_at_top_edge
        array([ 8,  9, 10, 11])

        LLCATS: NINF BC SUBSET
        """
        try:
            return self._nodes[-1, :]
        except AttributeError:
            raise AttributeError(
                'Only rectangular Hex grids have defined edges.')

    @property
    def nodes_at_bottom_edge(self):
        """Get nodes along the bottom edge of a grid, if grid is rectangular.

        Examples
        --------
        >>> import numpy as np
        >>> from landlab import HexModelGrid
        >>> grid = HexModelGrid(3, 4, shape='rect')
        >>> grid.nodes_at_bottom_edge
        array([0, 1, 2, 3])

        LLCATS: NINF BC SUBSET
        """
        try:
            return self._nodes[0, :]
        except AttributeError:
            raise AttributeError(
                'Only rectangular Hex grids have defined edges.')

    def _configure_hexplot(self, data, data_label=None, color_map=None):
        """
        Sets up necessary information for making plots of the hexagonal grid
        colored by a given data element.

        Parameters
        ----------
        data : str OR node array (1d numpy array with number_of_nodes entries)
            Data field to be colored
        data_label : str, optional
            Label for colorbar
        color_map : matplotlib colormap object, None
            Color map to apply (defaults to "jet")

        Returns
        -------
        (none)

        Notes
        -----
        Creates and stores a PatchCollection representing the hexagons. Also
        stores a handle to the current plotting axis. Both of these are then
        used by hexplot().
        """
        from numpy import array, sqrt, zeros
        import matplotlib
        from matplotlib.patches import Polygon
        from matplotlib.collections import PatchCollection

        # color
        if color_map is None:
            color_map = matplotlib.cm.jet

        # geometry
        apothem = self._dx / 2.0
        # distance from node to each hexagon cell vertex
        radius = 2.0 * apothem / sqrt(3.0)

        # offsets from node x,y position
        offsets = zeros((6, 2))
        poly_verts = zeros((6, 2))

        # Figure out whether the orientation is horizontal or vertical
        if self.orientation[0] == 'h':  # horizontal
            offsets[:,
                    0] = array([0., apothem, apothem, 0., -apothem, -apothem])
            offsets[:, 1] = array([
                radius, radius / 2.0, -radius / 2.0, -radius, -radius / 2.0,
                radius / 2.0
            ])
        else:  # vertical
            offsets[:, 0] = array([
                radius / 2.0, radius, radius / 2.0, -radius / 2.0, -radius,
                -radius / 2.0
            ])
            offsets[:,
                    1] = array([apothem, 0., -apothem, -apothem, 0., apothem])

        patches = []
        for i in range(self.number_of_nodes):
            poly_verts[:, 0] = self.node_x[i] + offsets[:, 0]
            poly_verts[:, 1] = self.node_y[i] + offsets[:, 1]
            p = Polygon(poly_verts, True)
            patches.append(p)

        self._hexplot_pc = PatchCollection(patches,
                                           cmap=color_map,
                                           edgecolor='none',
                                           linewidth=0.0)

        self._hexplot_configured = True

    def hexplot(self, data, data_label=None, color_map=None):
        """Create a plot of the grid elements.

        Creates a plot of the grid and one node-data field, showing hexagonal
        cells colored by values in the field.

        Parameters
        ----------
        data : str or node array (1d numpy array with number_of_nodes entries)
            Data field to be colored.
        data_label : str, optional
            Label for colorbar.
        color_map : matplotlib colormap object, None
            Color map to apply (defaults to "jet")

        See also
        --------
        plot.imshow_grid
            Another Landlab function capable of producing hexplots, with a
            fuller-featured set of options.

        LLCATS: GINF
        """
        from numpy import array, amin, amax
        import matplotlib.pyplot as plt
        import copy

        try:
            self._hexplot_configured is True
        except:
            self._configure_hexplot(data, data_label, color_map)

        # Handle *data*: if it's a numpy array, then we consider it the
        # data to be plotted. If it's a string, we consider it the name of the
        # node-field to plot, and we fetch it.
        if type(data) is str:
            data_label = data
            data = self.at_node[data]

        ax = plt.gca()
        self._hexplot_pc.set_array(array(data))
        copy_of_pc = copy.copy(self._hexplot_pc)
        ax.add_collection(copy_of_pc)
        plt.xlim([amin(self.node_x) - self._dx, amax(self.node_x) + self._dx])
        plt.ylim([amin(self.node_y) - self._dx, amax(self.node_y) + self._dx])

        return ax
예제 #46
0
파일: geology.py 프로젝트: umma-zannat/mtpy
    def plotlocal(self,
                  epsg_from,
                  epsg_to,
                  centre_shift=[0., 0.],
                  ax=None,
                  map_scale='m',
                  **kwargs):
        '''
        Plots a shapefile as lines in local coordinates (for overlaying on
        existing depth slice plotting functions, for example)
        :epsg_from: epsg the sh in
        :epsg_to: epsg you would like the output to be plotted in
        :centre_shift: option to shift by [x,y] to convert (for example) to 
        :ax: axes instance to plot on
        :map_scale: 'km' or 'm' - scale of map we are plotting onto
        :kwargs: key word arguments to the matplotlib plot function
        local coordinates.
        :return:
        '''
        # set default line colour to black
        if 'color' not in kwargs.keys():
            kwargs['color'] = 'k'

        if ax is None:
            ax = plt.subplot(111)

        if map_scale == 'km':
            scale_factor = 1000.
        else:
            scale_factor = 1.

        patches = []
        legend_handles = []
        legend_labels = []
        handles = set()

        ecolor_is_fcolor = False
        if ('edgecolor' in kwargs.keys() and kwargs['edgecolor'] == 'face'):
            ecolor_is_fcolor = True
        # Process geometry
        for i, feature in enumerate(self._geometries):
            fcolor = None
            symbol = ''
            if (self._hasLUT):
                symbol = self._properties[i][self._symbolkey]
                fcolor = self._lutDict[symbol]
            if (fcolor == []): fcolor = default_polygon_color

            if (isinstance(feature, Polygon)):
                polygon = feature
                x, y = polygon.exterior.coords.xy
                px, py = self._xy_to_local(x, y, epsg_from, epsg_to,
                                           centre_shift, scale_factor)
                ppolygon = Polygon(zip(px, py))

                if (fcolor is not None): kwargs['facecolor'] = fcolor
                if ('edgecolor' not in kwargs.keys() and not ecolor_is_fcolor):
                    kwargs['edgecolor'] = 'none'
                else:
                    kwargs['edgecolor'] = fcolor
                if ('fill') not in kwargs.keys(): kwargs['fill'] = True

                pp = PolygonPatch(ppolygon, **kwargs)
                patches.append(pp)

                # filter duplicates
                if (symbol not in handles):
                    handles.add(symbol)
                    legend_handles.append(pp)
                    legend_labels.append(symbol)

            elif (isinstance(feature, MultiPolygon)):
                multiPolygon = feature

                for polygon in multiPolygon:
                    x, y = polygon.exterior.coords.xy
                    px, py = self._xy_to_local(x, y, epsg_from, epsg_to,
                                               centre_shift, scale_factor)
                    ppolygon = Polygon(zip(px, py))

                    if (fcolor is not None): kwargs['facecolor'] = fcolor
                    if ('edgecolor' not in kwargs.keys()
                            and not ecolor_is_fcolor):
                        kwargs['edgecolor'] = 'none'
                    else:
                        kwargs['edgecolor'] = fcolor
                    if ('fill') not in kwargs.keys(): kwargs['fill'] = True

                    pp = PolygonPatch(ppolygon, **kwargs)
                    patches.append(pp)

                    # filter duplicates
                    if (symbol not in handles):
                        handles.add(symbol)
                        legend_handles.append(pp)
                        legend_labels.append(symbol)
                        # end for
            elif (isinstance(feature, LineString)):
                line = feature
                x, y = line.coords.xy
                px, py = self._xy_to_local(x, y, epsg_from, epsg_to,
                                           centre_shift, scale_factor)
                ax.plot(px, py, **kwargs)
                # end if
        # end for
        if (len(patches)):
            ax.add_collection(PatchCollection(patches, match_original=True))

        return ax, legend_handles, legend_labels
예제 #47
0
    def _configure_hexplot(self, data, data_label=None, color_map=None):
        """
        Sets up necessary information for making plots of the hexagonal grid
        colored by a given data element.

        Parameters
        ----------
        data : str OR node array (1d numpy array with number_of_nodes entries)
            Data field to be colored
        data_label : str, optional
            Label for colorbar
        color_map : matplotlib colormap object, None
            Color map to apply (defaults to "jet")

        Returns
        -------
        (none)

        Notes
        -----
        Creates and stores a PatchCollection representing the hexagons. Also
        stores a handle to the current plotting axis. Both of these are then
        used by hexplot().
        """
        from numpy import array, sqrt, zeros
        import matplotlib
        from matplotlib.patches import Polygon
        from matplotlib.collections import PatchCollection

        # color
        if color_map is None:
            color_map = matplotlib.cm.jet

        # geometry
        apothem = self._dx / 2.0
        # distance from node to each hexagon cell vertex
        radius = 2.0 * apothem / sqrt(3.0)

        # offsets from node x,y position
        offsets = zeros((6, 2))
        poly_verts = zeros((6, 2))

        # Figure out whether the orientation is horizontal or vertical
        if self.orientation[0] == 'h':  # horizontal
            offsets[:,
                    0] = array([0., apothem, apothem, 0., -apothem, -apothem])
            offsets[:, 1] = array([
                radius, radius / 2.0, -radius / 2.0, -radius, -radius / 2.0,
                radius / 2.0
            ])
        else:  # vertical
            offsets[:, 0] = array([
                radius / 2.0, radius, radius / 2.0, -radius / 2.0, -radius,
                -radius / 2.0
            ])
            offsets[:,
                    1] = array([apothem, 0., -apothem, -apothem, 0., apothem])

        patches = []
        for i in range(self.number_of_nodes):
            poly_verts[:, 0] = self.node_x[i] + offsets[:, 0]
            poly_verts[:, 1] = self.node_y[i] + offsets[:, 1]
            p = Polygon(poly_verts, True)
            patches.append(p)

        self._hexplot_pc = PatchCollection(patches,
                                           cmap=color_map,
                                           edgecolor='none',
                                           linewidth=0.0)

        self._hexplot_configured = True
예제 #48
0
파일: geology.py 프로젝트: umma-zannat/mtpy
    def plot(self, ax, m, lutfn=None, default_polygon_color='grey', **kwargs):
        '''
        Plots a shapefile. This function assumes that a shapefile containing polygonal
        data will have an attribute column named 'SYMBOL', which is used to pick corresponding
        color values from the colour lookup table, described in function processLUT.

        :param ax: plot axis
        :param m: basemap instance
        :param lutfn: colour look-up-table file name, which if not provided, polygons
                      are coloured by the default colour (default_polygon_color). This
                      parameter is ignored for shapefiles that contain only line data
        :param default_polygon_color: default color for polygons; overridden by colors
                                      provided in look-up-table, if given
        :param kwargs: list of relevant matplotlib arguments, e.g. alpha, zorder, color, etc.
        :return:
            legend_handles: legend handles for polygonal data; empty list for line data
            legend_labels: symbol names for polygonal data; empty list for line data
        '''

        # Populate lookup table
        self.processLUT(lutfn)

        patches = []
        legend_handles = []
        legend_labels = []
        handles = set()

        ecolor_is_fcolor = False
        if ('edgecolor' in kwargs.keys() and kwargs['edgecolor'] == 'face'):
            ecolor_is_fcolor = True
        # Process geometry
        for i, feature in enumerate(self._geometries):
            fcolor = None
            symbol = ''
            if (self._hasLUT):
                symbol = self._properties[i][self._symbolkey]
                fcolor = self._lutDict[symbol]
            if (fcolor == []): fcolor = default_polygon_color

            if (isinstance(feature, Polygon)):
                polygon = feature
                x, y = polygon.exterior.coords.xy
                if m is None:
                    px, py = x, y
                else:
                    px, py = m(x, y)
                ppolygon = Polygon(zip(px, py))

                if (fcolor is not None): kwargs['facecolor'] = fcolor
                if ('edgecolor' not in kwargs.keys() and not ecolor_is_fcolor):
                    kwargs['edgecolor'] = 'none'
                else:
                    kwargs['edgecolor'] = fcolor
                if ('fill') not in kwargs.keys(): kwargs['fill'] = True

                pp = PolygonPatch(ppolygon, **kwargs)
                patches.append(pp)

                # filter duplicates
                if (symbol not in handles):
                    handles.add(symbol)
                    legend_handles.append(pp)
                    legend_labels.append(symbol)

            elif (isinstance(feature, MultiPolygon)):
                multiPolygon = feature

                for polygon in multiPolygon:
                    x, y = polygon.exterior.coords.xy
                    if m is None:
                        px, py = x, y
                    else:
                        px, py = m(x, y)
                    ppolygon = Polygon(zip(px, py))

                    if (fcolor is not None): kwargs['facecolor'] = fcolor
                    if ('edgecolor' not in kwargs.keys()
                            and not ecolor_is_fcolor):
                        kwargs['edgecolor'] = 'none'
                    else:
                        kwargs['edgecolor'] = fcolor
                    if ('fill') not in kwargs.keys(): kwargs['fill'] = True

                    pp = PolygonPatch(ppolygon, **kwargs)
                    patches.append(pp)

                    # filter duplicates
                    if (symbol not in handles):
                        handles.add(symbol)
                        legend_handles.append(pp)
                        legend_labels.append(symbol)
                # end for
            elif (isinstance(feature, LineString)):
                line = feature
                x, y = line.coords.xy
                if m is None:
                    px, py = x, y
                else:
                    px, py = m(x, y)
                ax.plot(px, py, **kwargs)
            # end if
        # end for
        if (len(patches)):
            ax.add_collection(PatchCollection(patches, match_original=True))

        return legend_handles, legend_labels
예제 #49
0
 def showRef(self, ref, seg_box='seg'):
     ax = plt.gca()
     # show image
     image = self.Imgs[ref['image_id']]
     I = io.imread(osp.join(self.IMAGE_DIR, image['file_name']))
     ax.imshow(I)
     # show refer expression
     for sid, sent in enumerate(ref['sentences']):
         if self.data['dataset'] != 'refgta':
             print('%s. %s' % (sid + 1, sent['sent']))
         else:
             print('%s. %s' % (sid + 1, sent['sent']))
             print('[Acc]:{:.2f}%, [time] median:{:.2f},mean:{:.2f}'.format(
                 100 * np.mean([o['if_true'] for o in sent['info']]),
                 np.median([1e-3 * o['time'] for o in sent['info']]),
                 np.mean(
                     sorted([1e-3 * o['time']
                             for o in sent['info']])[1:4])))
     # show segmentations
     if seg_box == 'seg':
         assert self.data['dataset'] != 'refgta', print(
             'segmentation is not supported for refgta')
         ann_id = ref['ann_id']
         ann = self.Anns[ann_id]
         polygons = []
         color = []
         c = 'none'
         if type(ann['segmentation'][0]) == list:
             # polygon used for refcoco*
             for seg in ann['segmentation']:
                 poly = np.array(seg).reshape((len(seg) // 2, 2))
                 polygons.append(Polygon(poly, True, alpha=0.4))
                 color.append(c)
             p = PatchCollection(polygons,
                                 facecolors=color,
                                 edgecolors=(1, 1, 0, 0),
                                 linewidths=3,
                                 alpha=1)
             ax.add_collection(p)  # thick yellow polygon
             p = PatchCollection(polygons,
                                 facecolors=color,
                                 edgecolors=(1, 0, 0, 0),
                                 linewidths=1,
                                 alpha=1)
             ax.add_collection(p)  # thin red polygon
         else:
             # mask used for refclef
             rle = ann['segmentation']
             m = mask.decode(rle)
             img = np.ones((m.shape[0], m.shape[1], 3))
             color_mask = np.array([2.0, 166.0, 101.0]) / 255
             for i in range(3):
                 img[:, :, i] = color_mask[i]
             ax.imshow(np.dstack((img, m * 0.5)))
     # show bounding-box
     elif seg_box == 'box':
         ann_id = ref['ann_id']
         bbox = self.getRefBox(ref['ref_id'])
         box_plot = Rectangle((bbox[0], bbox[1]),
                              bbox[2],
                              bbox[3],
                              fill=False,
                              edgecolor='red',
                              linewidth=3)
         ax.add_patch(box_plot)
         for others in self.imgToAnns[ref['image_id']]:
             if others['id'] != ann_id:
                 bbox = others['bbox']
                 box_plot = Rectangle((bbox[0], bbox[1]),
                                      bbox[2],
                                      bbox[3],
                                      fill=False,
                                      edgecolor='blue',
                                      linewidth=3)
                 ax.add_patch(box_plot)
예제 #50
0
    def point_Refresh(self):
        self.canvas.restore_region(self.background)
        self.title.set_text("Activity Data for Column %s" % (self.index, ))
        self.axes.cla()
        if len(self.similarities) != 0:
            minimum = min([s[2] for s in self.similarities])
            maximum = max([s[2] for s in self.similarities])
            patches = []
            facecolors = []
            for (start, length, similar) in self.similarities:
                value = int(
                    (similar - minimum) * (255.0 / (maximum - minimum)))
                strval = "#%0.2x%0.2x%0.2x" % (value, value, value)
                facecolors.append(strval)
                patches.append(
                    Polygon([[start, self.mins], [start, self.maxs],
                             [start + length, self.maxs],
                             [start + length, self.mins]],
                            closed=True,
                            edgecolor='none',
                            fill=True,
                            facecolor=strval,
                            visible=True))
            p = PatchCollection(patches, match_original=True)
            self.axes.add_collection(p)

        for span in self.spans:
            xs = range(span[1], span[1] + len(span[2]))
            ys = [p for p in span[2]]
            self.axes.plot(xs,
                           ys,
                           color=colors[int(float(span[0])) % len(colors)])

        if self.index_a != None:
            self.sub_canvas_a.restore_region(self.background)
            self.sub_axes_a.cla()
            span = self.spans[self.index_a]
            xs = range(span[1], span[1] + len(span[2]))
            ys = [p for p in span[2]]
            self.sub_axes_a.plot(xs, ys, color="black")
            self.sub_title_a.set_text(
                "Data for Segment beginning at %s, label %s" %
                (xs[0], span[0]))
            self.sub_canvas_ap.restore_region(self.background)
            self.sub_axes_ap.cla()
            persistence = self.persistences.diagrams[self.index_a]
            data = persistence.points
            xs = [d[0] for d in data if d[2] > 0]
            ys = [d[1] for d in data if d[2] > 0]
            max_val = max([max(xs), max(ys)])
            self.sub_axes_ap.scatter(xs, ys)
            self.sub_axes_ap.plot([0, max_val], [0, max_val], color="red")
            self.sub_title_ap.set_text(
                "Persistence for Segment beginning at %s" %
                (persistence.segment_start))

        if self.index_b != None:
            self.sub_canvas_b.restore_region(self.background)
            self.sub_axes_b.cla()
            span = self.spans[self.index_b]
            xs = range(span[1], span[1] + len(span[2]))
            ys = [p for p in span[2]]
            self.sub_axes_b.plot(xs, ys, color="black")
            self.sub_title_b.set_text(
                "Data for Segment beginning at %s, label %s" %
                (xs[0], span[0]))
            self.sub_canvas_bp.restore_region(self.background)
            self.sub_axes_bp.cla()
            persistence = self.persistences.diagrams[self.index_b]
            data = persistence.points
            xs = [d[0] for d in data if d[2] > 0]
            ys = [d[1] for d in data if d[2] > 0]
            max_val = max([max(xs), max(ys)])
            self.sub_axes_bp.scatter(xs, ys)
            self.sub_axes_bp.plot([0, max_val], [0, max_val], color="red")
            self.sub_title_bp.set_text(
                "Persistence for Segment beginning at %s" %
                (persistence.segment_start))
    def plotDroneCorrelations(self):
        """
        Plots of 2D cross-correlations
        """
        x, y = np.meshgrid(
            np.linspace(0, self.hstacks[0].shape[1], self.hstacks[0].shape[1]),
            np.linspace(0, self.hstacks[0].shape[0], self.hstacks[0].shape[0]))

        fig, ax = plt.subplots(10, 1, sharex=True, sharey=True)
        fig.set_figwidth(7, forward=True)
        fig.set_figheight(7, forward=True)
        ax[0].pcolormesh(x, y, self.hstacks[0], cmap='gray', vmin=0, vmax=255)
        ax[2].pcolormesh(x, y, self.hstacks[2], cmap='gray', vmin=0, vmax=255)
        ax[4].pcolormesh(x, y, self.hstacks[4], cmap='gray', vmin=0, vmax=255)
        ax[6].pcolormesh(x, y, self.hstacks[6], cmap='gray', vmin=0, vmax=255)
        ax[8].pcolormesh(x, y, self.hstacks[8], cmap='gray', vmin=0, vmax=255)

        colorMap = 'Blues'
        ax[1].pcolormesh(x, y, self.corrs[0], cmap=colorMap)
        ax[3].pcolormesh(x, y, self.corrs[1], cmap=colorMap)
        ax[5].pcolormesh(x, y, self.corrs[2], cmap=colorMap)
        ax[7].pcolormesh(x, y, self.corrs[3], cmap=colorMap)
        ax[9].pcolormesh(x, y, self.corrs[4], cmap=colorMap)

        peaks = [(139, 251), (159, 249), (179, 250), (195, 285), (211, 301)]

        xLength = 69

        faceColors = ['red', 'yellow', 'yellow', 'yellow', 'yellow']
        for count, peak in enumerate(peaks):

            rect = []
            rect.append(Rectangle((peak[0] - xLength / 2, 0), xLength, 500))
            ax[count * 2].add_collection(
                PatchCollection(rect,
                                facecolor=faceColors[count],
                                alpha=0.3,
                                edgecolor=''))

        ax[0].set_xlim([0, 600])
        ax[0].set_ylim([40, 374])
        fig.subplots_adjust(wspace=0, hspace=0)

        ax[0].yaxis.set_ticks([83, 145, 207, 269, 331])

        ax[0].xaxis.set_ticks([0, 100, 200, 300, 400, 500, 600])
        ax[0].set_xticklabels(['0', '50', '100', '150', '200', '250', '300'])
        ax[0].invert_yaxis()

        ax[0].set_yticklabels(['4', '2', '0', '-2', '-4'])

        fig.text(0.51, 0.05, 't (s)', ha='center')
        fig.text(0.05, 0.5, r'$y_{\xi}$ (m)', va='center', rotation='vertical')

        fig.text(0.13, 0.86, 'a)', va='center', color='black', fontsize=11)
        fig.text(0.16,
                 0.86,
                 r'$x_{\xi}$ = 0 m',
                 va='center',
                 color='black',
                 fontsize=11)

        fig.text(0.13, 0.705, 'b)', va='center', color='black', fontsize=11)
        fig.text(0.16,
                 0.705,
                 r'$x_{\xi}$ = 6 m',
                 va='center',
                 color='black',
                 fontsize=11)

        fig.text(0.13, 0.553, 'c)', va='center', color='black', fontsize=11)
        fig.text(0.16,
                 0.55,
                 r'$x_{\xi}$ = 12 m',
                 va='center',
                 color='black',
                 fontsize=11)

        fig.text(0.13, 0.40, 'd)', va='center', color='black', fontsize=11)
        fig.text(0.16,
                 0.40,
                 r'$x_{\xi}$ = 18 m',
                 va='center',
                 color='black',
                 fontsize=11)

        fig.text(0.13, 0.245, 'e)', va='center', color='black', fontsize=11)
        fig.text(0.16,
                 0.245,
                 r'$x_{\xi}$ = 24 m',
                 va='center',
                 color='black',
                 fontsize=11)

        ax[0].annotate('KH1 pattern',
                       xy=(140, 140),
                       xycoords='data',
                       xytext=(200, 140),
                       textcoords='data',
                       arrowprops=dict(arrowstyle="->", fc='red', ec='red'))
        ax[1].annotate('KH1 peak ($t$ = 69.5 s, $\delta t = 0$)',
                       xy=(140, 245),
                       xycoords='data',
                       xytext=(200, 140),
                       textcoords='data',
                       arrowprops=dict(arrowstyle="->", fc='red', ec='red'))
        ax[3].annotate('KH1 peak ($t$ = 79, $\delta t = 9.5 s$)',
                       xy=(159, 260),
                       xycoords='data',
                       xytext=(200, 140),
                       textcoords='data',
                       arrowprops=dict(arrowstyle="->", fc='red', ec='red'))
        ax[5].annotate('KH1 peak ($t$ = 89, $\delta t = 10s$)',
                       xy=(179, 250),
                       xycoords='data',
                       xytext=(220, 140),
                       textcoords='data',
                       arrowprops=dict(arrowstyle="->", fc='red', ec='red'))
        ax[7].annotate('KH1 peak ($t$ = 97,  $\delta t = 8s$)',
                       xy=(195, 275),
                       xycoords='data',
                       xytext=(236, 140),
                       textcoords='data',
                       arrowprops=dict(arrowstyle="->", fc='red', ec='red'))
        ax[9].annotate('KH1 peak ($t$ = 105, $\delta t = 8s$)',
                       xy=(211, 275),
                       xycoords='data',
                       xytext=(252, 140),
                       textcoords='data',
                       arrowprops=dict(arrowstyle="->", fc='red', ec='red'))

        plt.savefig(self.run.path + "\\" +
                    "\\Images\\fig_droneXcorrelations.png",
                    format='png',
                    dpi=600)
예제 #52
0
def _construct_pointnfig_collections(dates,
                                     highs,
                                     lows,
                                     volumes,
                                     config_pointnfig_params,
                                     closes,
                                     marketcolors=None):
    """Represent the price change with Xs and Os

    NOTE: this code assumes if any value open, low, high, close is
    missing they all are missing

    Algorithm Explanation
    ---------------------
    In the first part of the algorithm, we populate the boxes array
    along with adjusting the dates and volumes arrays into the new_dates and
    new_volumes arrays. A single date includes a range from no boxes to many 
    boxes, if a date has no boxes it shall not be included in new_dates, 
    and if it has n boxes then it will be included n times. Volumes use a 
    volume cache to save volume amounts for dates that do not have any boxes
    before adding the cache to the next date that has at least one box.
    We populate the boxes array with each close values difference from the 
    previously created brick divided by the box size.

    The second part of the algorithm has a series of step. First we combine the
    adjacent like signed values in the boxes array (ex. [-1, -2, 3, -4] -> [-3, 3, -4]).
    Next we subtract 1 from the absolute value of each element in boxes except the 
    first to ensure every time there is a trend change (ex. previous box is
    an X, current brick is a O) we draw one less box to account for the price 
    having to move the previous box's amount before creating a box in the 
    opposite direction. Next we adjust volume and dates to combine volume into 
    non 0 box indexes and to only use dates from non 0 box indexes. We then
    remove all 0s from the boxes array and once again combine adjacent similarly
    signed differences in boxes.

    Lastly, we enumerate through the boxes to populate the line_seg and circle_patches
    arrays. line_seg holds the / and \ line segments that make up an X and 
    circle_patches holds matplotlib.patches Ellipse objects for each O. We start
    by filling an x and y array each iteration which contain the x and y 
    coordinates for each box in the column. Then for each coordinate pair in
    x, y we add to either the line_seg array or the circle_patches array 
    depending on the value of sign for the current column (1 indicates 
    line_seg, -1 indicates circle_patches). The height of the boxes take 
    into account padding which separates each box by a small margin in 
    order to increase readability.

    Useful sources:
    https://stackoverflow.com/questions/8750648/point-and-figure-chart-with-matplotlib
    https://www.investopedia.com/articles/technical/03/081303.asp
    
    Parameters
    ----------
    dates : sequence
        sequence of dates
    highs : sequence
        sequence of high values
    lows : sequence
        sequence of low values
    config_pointnfig_params : kwargs table (dictionary)
        box_size : size of each box
        atr_length : length of time used for calculating atr
    closes : sequence
        sequence of closing values
    marketcolors : dict of colors: up, down, edge, wick, alpha

    Returns
    -------
    ret : tuple
        rectCollection
    """
    pointnfig_params = _process_kwargs(config_pointnfig_params,
                                       _valid_pnf_kwargs())
    if marketcolors is None:
        marketcolors = _get_mpfstyle('classic')['marketcolors']
        #print('default market colors:',marketcolors)

    box_size = pointnfig_params['box_size']
    atr_length = pointnfig_params['atr_length']

    if box_size == 'atr':
        if atr_length == 'total':
            box_size = _calculate_atr(len(closes) - 1, highs, lows, closes)
        else:
            box_size = _calculate_atr(atr_length, highs, lows, closes)
    else:  # is an integer or float
        upper_limit = (max(closes) - min(closes)) / 2
        lower_limit = 0.01 * _calculate_atr(
            len(closes) - 1, highs, lows, closes)
        if box_size > upper_limit:
            raise ValueError(
                "Specified box_size may not be larger than (50% of the close price range of the dataset) which has value: "
                + str(upper_limit))
        elif box_size < lower_limit:
            raise ValueError(
                "Specified box_size may not be smaller than (0.01* the Average True Value of the dataset) which has value: "
                + str(lower_limit))

    alpha = marketcolors['alpha']

    uc = mcolors.to_rgba(marketcolors['ohlc']['up'], alpha)
    dc = mcolors.to_rgba(marketcolors['ohlc']['down'], alpha)
    tfc = mcolors.to_rgba(marketcolors['edge']['down'],
                          0)  # transparent face color

    boxes = [
    ]  # each element in an integer representing the number of boxes to be drawn on that indexes column (negative numbers -> Os, positive numbers -> Xs)
    prev_close_box = closes[
        0]  # represents the value of the last box in the previous column
    volume_cache = 0  # holds the volumes for the dates that were skipped
    temp_volumes, temp_dates = [], [
    ]  # holds the temp adjusted volumes and dates respectively

    for i in range(len(closes) - 1):
        box_diff = int((closes[i + 1] - prev_close_box) / box_size)
        if box_diff == 0:
            if volumes is not None:
                volume_cache += volumes[i]
            continue

        boxes.append(box_diff)
        if volumes is not None:
            temp_volumes.append(volumes[i] + volume_cache)
            volume_cache = 0
        temp_dates.append(dates[i])
        prev_close_box += box_diff * box_size

    # combine adjacent similarly signed differences
    boxes, indexes = combine_adjacent(boxes)
    new_volumes, new_dates = coalesce_volume_dates(temp_volumes, temp_dates,
                                                   indexes)

    #subtract 1 from the abs of each diff except the first to account for the first box using the last box in the opposite direction
    first_elem = boxes[0]
    boxes = [
        boxes[i] - int((boxes[i] / abs(boxes[i])))
        for i in range(1, len(boxes))
    ]
    boxes.insert(0, first_elem)

    # adjust volume and dates to make sure volume is combined into non 0 box indexes and only use dates from non 0 box indexes
    temp_volumes, temp_dates = [], []
    for i in range(len(boxes)):
        if boxes[i] == 0:
            volume_cache += new_volumes[i]
        else:
            temp_volumes.append(new_volumes[i] + volume_cache)
            volume_cache = 0
            temp_dates.append(new_dates[i])

    #remove 0s from boxes
    boxes = list(filter(lambda diff: diff != 0, boxes))

    # combine adjacent similarly signed differences again after 0s removed
    boxes, indexes = combine_adjacent(boxes)
    new_volumes, new_dates = coalesce_volume_dates(temp_volumes, temp_dates,
                                                   indexes)

    curr_price = closes[0]
    box_values = []  # y values for the boxes
    circle_patches = [
    ]  # list of circle patches to be used to create the cirCollection
    line_seg = []  # line segments that make up the Xs

    for index, difference in enumerate(boxes):
        diff = abs(difference)

        sign = (difference / abs(difference))  # -1 or 1
        start_iteration = 0 if sign > 0 else 1

        x = [index] * (diff)
        y = [
            curr_price + (i * box_size * sign)
            for i in range(start_iteration, diff + start_iteration)
        ]

        curr_price += (box_size * sign * (diff))
        box_values.append(sum(y) / len(y))

        for i in range(len(x)):  # x and y have the same length
            height = box_size * 0.85
            width = 0.6
            if height < 0.5:
                width = height

            padding = (box_size * 0.075)
            if sign == 1:  # X
                line_seg.append([(x[i] - width / 2, y[i] + padding),
                                 (x[i] + width / 2, y[i] + height + padding)
                                 ])  # create / part of the X
                line_seg.append([(x[i] - width / 2, y[i] + height + padding),
                                 (x[i] + width / 2, y[i] + padding)
                                 ])  # create \ part of the X
            else:  # O
                circle_patches.append(
                    Ellipse((x[i], y[i] - (height / 2) - padding), width,
                            height))

    useAA = 0,  # use tuple here
    lw = 0.5

    cirCollection = PatchCollection(circle_patches)
    cirCollection.set_facecolor([tfc] * len(circle_patches))
    cirCollection.set_edgecolor([dc] * len(circle_patches))

    xCollection = LineCollection(line_seg,
                                 colors=[uc] * len(line_seg),
                                 linewidths=lw,
                                 antialiaseds=useAA)
    return [cirCollection,
            xCollection], new_dates, new_volumes, box_values, box_size
예제 #53
0
def drawPhaseIIIProbe(colors,
                      ax=-1,
                      highlight=-1,
                      clim=None,
                      cmap='viridis',
                      drawLines=False):
    '''
	Args:
		colors: a list of values to plotted as colors on the probe
		ax
		highlight
		clim: color map limits
		cmap: color map to use; default viridis
		drawLines: whether or not to draw the outline of the probe; default is False
	Returns:
		None, plots an image of the input colors on a Phase3A Neuropixels probes
	written by josh siegle
	'''
    if ax == -1:
        fig, ax = plt.subplots()

    patches = []

    for ch in range(0, len(colors)):

        channelPos = ch % 4
        channelHeight = ch / 4

        if channelPos == 0:
            xloc = -1.5
            yloc = channelHeight * 2
        elif channelPos == 1:
            xloc = 0.5
            yloc = channelHeight * 2
        elif channelPos == 2:
            xloc = -0.5
            yloc = channelHeight * 2 + 1
        else:
            xloc = 1.5
            yloc = channelHeight * 2 + 1

        rect = mpatches.Rectangle([xloc, yloc], 1.0, 2.0, ec="none", ls='None')

        if drawLines:
            if ch % 50 == 0:
                plt.plot([-5, 6], [yloc, yloc], 'gray')

            if ch % 100 == 0:
                plt.plot([-5, 6], [yloc, yloc], '-k')

        patches.append(rect)

        if ch == highlight:
            highlightX = xloc
            highlightY = yloc
            highlight = 1

    collection = PatchCollection(patches, cmap=cmap)

    collection.set_array(colors)
    if clim != None:
        collection.set_clim(clim[0], clim[1])
    ax.add_collection(collection)

    for ch in np.arange(0, len(colors), 50):
        plt.plot([-2.5, -2], [ch / 2, ch / 2], 'k')

    if highlight > -1:
        print(highlightY)
        plt.plot(highlightX, highlightY, color=[1, 1, 1])

    plt.axis('off')
    plt.xlim((-5, 6))
    plt.ylim((-5, ch / 2 + 20))
예제 #54
0
    boxes.append(Rectangle((lbx, lby), hbx-lbx, hby-lby))
    
    ix = int(x1[i]/step)
    iy = int(y1[i]/step)
    vs[ix, iy] = 0
    
gridboxes = []
for i in range(xs.shape[0]):
    for j in range(xs.shape[1]):
        gridboxes.append(Rectangle((xs[i,j], ys[i,j]), step, step))

zs = np.ma.array(~vs, mask=vs).astype(int)*1000

#ax = plt.subplot(338)
ax = plt.subplot2grid((9,3), (6,1), rowspan=3)
pc2 = PatchCollection(gridboxes, facecolor='lightgray', alpha=0.6,
                         edgecolor='lightgray')
ax.add_collection(pc2)
pc = PatchCollection(boxes, facecolor=surfacecolor, alpha=1,
                         edgecolor=surfacecolor)
ax.add_collection(pc)

plt.scatter(x1,y1, color=firstcloudcolor,alpha=1, label='first cloud')#,color='firebrick'
plt.scatter(xL,yL, color='k', marker = 'P', s=135, label = 'release location')
plt.xlabel('$^{\circ}$E', fontsize=18)
ax.tick_params(labelbottom=False, labelleft=False) 
plt.title('(c)', fontsize=18)
plt.xlim(-40,40)
plt.ylim(-40,40)

#%%
#ax = plt.subplot(337)
예제 #55
0
    def plotar_tensoes(self):
        """Exibe a malha final gerada. cmad jet ou binary"""
        plt.rcParams['pdf.fonttype'] = 42
        plt.rcParams['font.family'] = 'Calibri'

        # Resultados finais
        tensoes = self.dados.ler_arquivo_entrada_dados_numpy(22)
        tensoes_norm = np.full(len(tensoes), 0.5)
        rho_final = self.dados.rhos_iteracao_final()

        for i, rho_i in enumerate(rho_final):
            if i < self.dados.num_elementos_poli:
                if abs(rho_i) > 1e-9:
                    if tensoes[i] >= 0:
                        tensoes_norm[i] = 1
                    else:
                        tensoes_norm[i] = 0
            else:
                if tensoes[i] >= 0:
                    tensoes_norm[i] = 1
                else:
                    tensoes_norm[i] = 0

        fig, ax = plt.subplots()
        win = plt.get_current_fig_manager()
        win.window.state('zoomed')
        ax.axis('equal')

        xmin, ymin, xmax, ymax = self.dados.poligono_dominio_estendido.bounds
        dx = xmax - xmin
        dy = ymax - ymin
        plt.xlim(xmin - 0.1 * dx, xmax + 0.1 * dx)
        plt.ylim(ymin - 0.1 * dy, ymax + 0.1 * dy)

        elementos_poli = []
        elementos_barra = []
        x_bar_max = max(rho_final[self.dados.num_elementos_poli::]
                        ) if self.dados.tem_barras() else 0

        for j, el in enumerate(self.dados.elementos):
            if j < self.dados.num_elementos_poli:
                elementos_poli.append(
                    patches.Polygon(self.dados.nos[el],
                                    linewidth=0,
                                    fill=True,
                                    facecolor=cm.seismic(tensoes_norm[j])))
            else:
                verts = [self.dados.nos[el[0]], self.dados.nos[el[1]]]
                codes = [path.Path.MOVETO, path.Path.LINETO]

                rho = 15 * rho_final[j] / x_bar_max
                # rho = 3 if rho_final[j] > 0 else 0

                if rho > 0:
                    elementos_barra.append(
                        patches.PathPatch(path.Path(verts, codes),
                                          linewidth=rho,
                                          edgecolor=cm.seismic(
                                              tensoes_norm[j])))

        ax.add_collection(PatchCollection(elementos_poli, match_original=True))
        ax.add_collection(PatchCollection(elementos_barra,
                                          match_original=True))

        plt.axis('off')
        plt.grid(b=None)

        plt.title(f'Tensões nos elementos')
        plt.show()
예제 #56
0
	def gotoScan(self, scanIndex):
		# clear scans
		if self.collection1 != None:
			self.collection1.remove()
			self.collection1 = None
		if self.collection2 != None:
			self.collection2.remove()
			self.collection2 = None
		if self.collection3 != None:
			self.collection3.remove()
			self.collection3 = None
		# clear texts
		for text in self.texts:
			text.remove()
		self.texts = []

		if len(rectangles[scanIndex])>100 or len(sectors[scanIndex])>100:
			print "cowardly returns"
			return

		# les rectangles de recherche

		patches = []
		for rectangle in rectangles[scanIndex]:
			x1, y1 = self.convertLocalToAbs( rectangle.x1, rectangle.y1, rectangle.index )
			x2, y2 = self.convertLocalToAbs( rectangle.x2, rectangle.y2, rectangle.index )
			m=mpatches.Rectangle( 
				xy = (x1, y1), 
				width=x2-x1, 
				height=y2-y1,
				ec="none", fill=False)
			patches.append(m)
			self.texts.append( self.ax.text( (x1+x2)/2.0, (y1+y2)/2.0, rectangle.name, fontsize=12, color='blue'))

		#collection = PatchCollection(patches, facecolors = ("gray",), edgecolors=("blue",) )
		#collection = PatchCollection(patches, edgecolors=("blue",) )
		collection = PatchCollection(patches, cmap=plt.cm.Greys, alpha=0.3)

		colors = numpy.linspace(0, 1, len(patches))
		collection.set_array(numpy.array(colors))
		
		self.collection2 = self.ax.add_collection(collection)


		# les secteurs
		patches = []
		for sector in sectors[scanIndex]:
			index = sector.index
			x0 = self.posScrutators[index][0]
			y0 = self.posScrutators[index][1]
			'''
			theta0 = -pi/2
			if index==2:
				theta0 = pi/2
			'''
			theta0 = thetaScrutateurs[index]
			x1 = x0 + sector.rmin * cos(sector.thetamin+theta0) 
			y1 = y0 + sector.rmin * sin(sector.thetamin+theta0) 
			x2 = x0 + sector.rmax * cos(sector.thetamin+theta0) 
			y2 = y0 + sector.rmax * sin(sector.thetamin+theta0) 
			x3 = x0 + sector.rmax * cos(sector.thetamax+theta0) 
			y3 = y0 + sector.rmax * sin(sector.thetamax+theta0)
			x4 = x0 + sector.rmin * cos(sector.thetamax+theta0) 
			y4 = y0 + sector.rmin * sin(sector.thetamax+theta0)
			x, y = self.convertLocalToAbs( numpy.array([x1, x2, x3, x4, x1]) , numpy.array([y1, y2, y3, y4, y1]) , sector.index )
			m=mpatches.Polygon( numpy.transpose(numpy.array([x,y])), animated = True)
			patches.append(m)
			self.texts.append( self.ax.text( x[0], y[0], sector.name, fontsize=12, color='blue'))

		#colors = numpy.linspace(0, 1, len(patches))
		#collection = PatchCollection(patches, cmap=plt.cm.cool, alpha=0.3)
		collection = PatchCollection(patches, cmap=plt.cm.Greys, alpha=0.3)
		#colors = numpy.linspace(0, 1, len(patches))
		#collection.set_array(numpy.array(colors))

		self.collection3 = self.ax.add_collection(collection)

		# les scans
		patches = []
		for i in range(0,6):
			# ATTENTION SCAN A L'ENVERS !!!!!!!!!!!!!!      ======> 
			x, y = self.singleScanPlot(clusters[scanIndex][i].x, -clusters[scanIndex][i].y, i )
			m=mpatches.Polygon( numpy.transpose(numpy.array([x,y])), animated = True)
			patches.append(m)

		collection = PatchCollection(patches, cmap=plt.cm.hsv, alpha=0.3)
		colors = numpy.linspace(0, 1, len(patches))
		collection.set_array(numpy.array(colors))
		self.collection1 = self.ax.add_collection(collection)

		plt.title('Scan %03d' % scanIndex)
예제 #57
0
    def plotar_estrutura_deformada(self, escala=1):
        """Exibe a malha final gerada"""

        logger.debug('Plotando a estrutura deformada')

        # Leitura dos dados importantes
        nos = self.dados.nos
        poli = self.dados.poligono_dominio_estendido
        vetor_elementos = self.dados.elementos

        fig, ax = plt.subplots()
        win = plt.get_current_fig_manager()
        win.window.state('zoomed')
        ax.axis('equal')

        xmin, ymin, xmax, ymax = poli.bounds
        dx = xmax - xmin
        dy = ymax - ymin
        plt.xlim(xmin - 0.1 * dx, xmax + 0.1 * dx)
        plt.ylim(ymin - 0.1 * dy, ymax + 0.1 * dy)

        nos_def = self.posicao_nos_deslocados(escala)

        elementos_poli_original = []
        elementos_poli_deformado = []
        elementos_barra = []
        for el in vetor_elementos:
            if len(el) == 2:
                verts = [nos_def[el[0]], nos_def[el[1]]]
                codes = [path.Path.MOVETO, path.Path.LINETO]
                elementos_barra.append(
                    patches.PathPatch(path.Path(verts, codes),
                                      linewidth=1,
                                      edgecolor='purple'))
            elif len(el) > 2:
                elementos_poli_original.append(
                    patches.Polygon(self.dados.nos[el],
                                    linewidth=0.7,
                                    edgecolor=(0, 0, 0, 0.5),
                                    facecolor='None',
                                    linestyle='--'))
                elementos_poli_deformado.append(
                    patches.Polygon(nos_def[el],
                                    linewidth=0.7,
                                    edgecolor='black',
                                    facecolor=(76 / 255, 191 / 255, 63 / 255,
                                               0.4)))

        # Desenhar as cargas
        esc = min(dx, dy)
        dict_forcas = Estrutura.converter_vetor_forcas_em_dict(self.dados)
        dict_apoios = Estrutura.converter_vetor_apoios_em_dict(self.dados)

        for no in dict_forcas:
            for i, cg in enumerate(dict_forcas[no]):
                if cg != 0:
                    delta_x, delta_y = (0.1 * esc,
                                        0) if i == 0 else (0, 0.1 * esc)
                    delta_x = -delta_x if i == 0 and cg < 0 else delta_x
                    delta_y = -delta_y if i == 1 and cg < 0 else delta_y

                    ax.add_patch(
                        patches.Arrow(nos_def[no, 0],
                                      nos_def[no, 1],
                                      delta_x,
                                      delta_y,
                                      facecolor='blue',
                                      edgecolor='blue',
                                      width=0.01 * esc,
                                      linewidth=1))

        # Desenhar os apoios
        path_apoios = []
        for no in dict_apoios:
            for i, ap in enumerate(dict_apoios[no]):
                if ap != 0:
                    p0 = nos[no]
                    if i == 0:
                        p1 = np.array([p0[0] - 0.025 * esc, p0[1]])
                    else:
                        p1 = np.array([p0[0], p0[1] - 0.025 * esc])

                    path_apoios.append(
                        path.Path([p0, p1],
                                  [path.Path.MOVETO, path.Path.LINETO]))

        ax.add_collection(
            PathCollection(path_apoios, linewidths=2, edgecolors='red'))
        ax.add_collection(
            PatchCollection(elementos_poli_original, match_original=True))
        ax.add_collection(
            PatchCollection(elementos_poli_deformado, match_original=True))
        ax.add_collection(PatchCollection(elementos_barra,
                                          match_original=True))
        plt.axis('off')
        plt.grid(b=None)
        plt.title(f'Estrutura original deformada       escala: {escala}')
        plt.show()
예제 #58
0
# ploting 1-dim simplices
vertices = []
for (n1, n2) in mapper_output.simplices[1]:
    if n1 < n2:
        vertices.append(np.array([nodes_centroid[n1, :], nodes_centroid[n2, :]]))
        ax.plot([nodes_centroid[n1, 0], nodes_centroid[n2, 0]], [nodes_centroid[n1, 1], nodes_centroid[n2, 1]], 'b')


# ploting 2-dim simplices
patches = []
for (n1, n2, n3) in mapper_output.simplices[2]:
    if n1 < n2 & n2 < n3:
        polygon = Polygon(nodes_centroid[[n1, n2, n3], :])
        patches.append(polygon)

p = PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4)
ax.add_collection(p)

plt.show()



# mapper_output.draw_scale_graph()
# plt.savefig('scale_graph.png')
# '''
#     Step 5: Display parameters
# '''
# # Node coloring
#
# nodes = mapper_output.nodes
# node_color = None
예제 #59
0
def test_polygon_interiors():

    ax = plt.subplot(211, projection=ccrs.PlateCarree())
    ax.coastlines()
    ax.set_global()

    pth = Path([[0, -45], [60, -45], [60, 45], [0, 45], [0, 45], [10, -20],
                [10, 20], [40, 20], [40, -20], [10, 20]],
               [1, 2, 2, 2, 79, 1, 2, 2, 2, 79])

    patches_native = []
    patches = []
    for geos in cpatch.path_to_geos(pth):
        for pth in cpatch.geos_to_path(geos):
            patches.append(mpatches.PathPatch(pth))

        # buffer by 10 degrees (leaves a small hole in the middle)
        geos_buffered = geos.buffer(10)
        for pth in cpatch.geos_to_path(geos_buffered):
            patches_native.append(mpatches.PathPatch(pth))

    # Set high zorder to ensure the polygons are drawn on top of coastlines.
    collection = PatchCollection(patches_native,
                                 facecolor='red',
                                 alpha=0.4,
                                 transform=ax.projection,
                                 zorder=10)
    ax.add_collection(collection)

    collection = PatchCollection(patches,
                                 facecolor='yellow',
                                 alpha=0.4,
                                 transform=ccrs.Geodetic(),
                                 zorder=10)

    ax.add_collection(collection)

    # test multiple interior polygons
    ax = plt.subplot(212,
                     projection=ccrs.PlateCarree(),
                     xlim=[-5, 15],
                     ylim=[-5, 15])
    ax.coastlines()

    exterior = np.array(sgeom.box(0, 0, 12, 12).exterior.coords)
    interiors = [
        np.array(sgeom.box(1, 1, 2, 2, ccw=False).exterior.coords),
        np.array(sgeom.box(1, 8, 2, 9, ccw=False).exterior.coords)
    ]
    poly = sgeom.Polygon(exterior, interiors)

    patches = []
    for pth in cpatch.geos_to_path(poly):
        patches.append(mpatches.PathPatch(pth))

    collection = PatchCollection(patches,
                                 facecolor='yellow',
                                 alpha=0.4,
                                 transform=ccrs.Geodetic(),
                                 zorder=10)
    ax.add_collection(collection)
예제 #60
0
    def plot_snapshot(self, clusters: list[Cluster]):
        time = max(
            [µcluster.last_time for µcluster in self.dyclee.all_µclusters])

        max_density = max(
            [µcluster.density(time) for µcluster in self.dyclee.all_µclusters])

        unclustered = self.dyclee.all_µclusters

        for cluster in clusters:
            unclustered -= cluster.µclusters

            for µcluster in cluster.µclusters:
                patch_collection = PatchCollection([
                    Rectangle(
                        µcluster.centroid -
                        µcluster.context.hyperbox_lengths / 2,
                        *µcluster.context.hyperbox_lengths)
                ])
                patch_collection.set_edgecolor(
                    self.colour_manager.get_colour(cluster.label))
                patch_collection.set_facecolor(
                    (0, 0, 0, 0.5 * µcluster.density(time) / max_density))
                self.ax.add_collection(patch_collection)

        for µcluster in unclustered:
            patch_collection = PatchCollection([
                Rectangle(
                    µcluster.centroid - µcluster.context.hyperbox_lengths / 2,
                    *µcluster.context.hyperbox_lengths)
            ])
            patch_collection.set_edgecolor(
                self.colour_manager.get_colour(µcluster.label,
                                               self.unclustered_opacity))
            patch_collection.set_facecolor(
                (0, 0, 0, 0.5 * µcluster.density(time) / max_density))
            self.ax.add_collection(patch_collection)

        order = sorted(range(len(clusters)), key=lambda i: clusters[i].label)
        self.ax.legend([
            Rectangle(
                (0, 0),
                1,
                1,
                facecolor='none',
                edgecolor=self.colour_manager.get_colour(clusters[i].label))
            for i in order
        ], [clusters[i].label for i in order],
                       loc=self.legend_loc)