Exemple #1
0
def checkInside(polygonOne, polygonTwo):
    polygon = np.array(polygonOne) # All points of polygon (but in different form)
    path = mplPath.Path(polygon) # Makes polygon
    checkPoints = polygonTwo # The inside polygon (points, not lines)
    edgeInside = [path.contains_point(point, radius = 0.001) or path.contains_point(point, radius = -0.001) for point in checkPoints]
    edgeOutside = [(path.contains_point(point, radius = 0) or path.contains_point(point, radius = 0)) and point not in polygonOne for point in checkPoints]
    return edgeInside, edgeOutside
Exemple #2
0
    def get_area_name(self,point):
        area_found_result = False
        area_name = ""
        for i in areas_dict:
            path = Path(areas_dict[i])

            if path.contains_point(point) == 1:
                area_name = i
                area_found_result = True
                break
        if area_found_result == False:
            area_name = self.default_no_suburb
        return area_name
    def get_area_name(self,point):
        # the parameter must be like  point = (latitude, longitude)
        area_found_result = False
        area_name = ""
        for i in areas_dict:
            path = Path(areas_dict[i])

            if path.contains_point(point) == 1:
                area_name = i
                area_found_result = True
                break
        if area_found_result == False:
            area_name = self.default_no_suburb
        return area_name
Exemple #4
0
    def remove_selection(self):
        if len(self.selected_path_verts) == 0:
            print "Nothing selected!"
            return
        
        path = self.points_to_path(close=True)
        
        nodes = [n for n in self.graph.nodes_iter() if
                path.contains_point((self.graph.node[n]['x'], 
                    self.graph.node[n]['y']))]

        print nodes
        
        self.graph.remove_nodes_from(nodes)
        
        plt.clf()
        plot.draw_leaf(self.graph)
        self.selected_path_verts = []
        self.path_patch = None

        plt.show()
Exemple #5
0
    def experiment(self, feature_geom, point_geom):
        """
        feature and point are geometrys
        Is a QgsPoint within an arbitrary QgsPolygon?
        """
        polygon = feature_geom.asPolygon()
        point = point_geom.asPoint()

        codes = []
        codes.append(Path.MOVETO)

        for i in range(0, len(polygon[0]) - 2):
            codes.append(Path.LINETO)

        codes.append(Path.CLOSEPOLY)
        path = Path(polygon[0], codes)

        if path.contains_point(point):
            return True
        else:
            return False
Exemple #6
0
    def experiment(self, feature_geom, point_geom):
        """
        feature and point are geometrys
        Is a QgsPoint within an arbitrary QgsPolygon?
        """
        polygon = feature_geom.asPolygon()
        point = point_geom.asPoint()

        codes = []
        codes.append(Path.MOVETO)

        for i in range(0, len(polygon[0]) - 2):
            codes.append(Path.LINETO)

        codes.append(Path.CLOSEPOLY)
        path = Path(polygon[0], codes)

        if path.contains_point(point):
            return True
        else:
            return False
def var_to_polygon(mx,vertices,lx,ly):
    minx=min(np.asarray(lx))
    miny=min(np.asarray(ly))
    maxx=max(np.asarray(lx))
    maxy=max(np.asarray(ly))
    mask_polygon = np.zeros(( maxy-miny+1, maxx-minx+1 ))
    poly_vert=[]
    for i in vertices:
        poly_vert.append((i[1]-miny,i[0]-minx))
            
    path = Path(poly_vert)
    print minx,maxx, miny,maxy
    mx_slice = mx[(miny):(maxy+1), (minx):(maxx+1)]
    for index, val in np.ndenumerate(mx_slice):
        if path.contains_point(index)==1:
            mask_polygon[index]=1
        else:
            pass
    mx_slice_masked = ma.masked_where(mask_polygon==0,mx_slice)
    mx_slice_out = ma.masked_where(mask_polygon==1,mx_slice)

    return mx_slice_masked, mx_slice_out
Exemple #8
0
    def export_selection(self):
        if len(self.selected_path_verts) == 0:
            print "Nothing selected!"
            return

        path = self.points_to_path(close=True)
        
        nodes = [n for n in self.graph.nodes_iter() if
                path.contains_point((self.graph.node[n]['x'], 
                    self.graph.node[n]['y']))]

        subgraph = nx.Graph(self.graph.subgraph(nodes))
        
        suggested_name = self.suggested_name(self.fname,
                extension="_selection_")

        savname = raw_input("Save to [{}]: ".format(suggested_name))

        if savname == '':
            savname = suggested_name

        nx.write_gpickle(subgraph, savname)
        print "Done."
    def __call__(self, event):
        print 'click', event
        if event.inaxes!=self.line.axes: return
        if event.button == 1:
            self.xs.append(event.xdata)
            self.ys.append(event.ydata)
            self.line.set_data(self.xs, self.ys)
            self.line.figure.canvas.draw()
        if  event.button == 3:
            vertices=zip(self.xs,self.ys)
            if len(self.xs) > 1:
                cycle=vertices
                cycle.append((self.xs[0],self.ys[0]))
                fig_line = plt.figure(figsize=(22, 8))
                ax_line = fig_line.add_subplot(121)
              
                lat_vert, lon_vert,vert,ncv,absx,lx,ly =[],[],[],[],[],[],[]
                label_vert=[]
                #---------------Line plot----------------------------
                for i in range(0,len(self.xs)):
                    points=get_line(int(round(cycle[i][0])), int(round(cycle[i][1])), int(round(cycle[i+1][0])),int(round(cycle[i+1][1])))
                    for j in points:
                        lx.append(j[0])
                        ly.append(j[1])
                        ncv.append(self.mx[j[1],j[0]])
                        lat_vert.append(self.lat[j[1],j[0]])
                        lon_vert.append(self.lon[j[1],j[0]])
                        if len(lx) ==1:
                            absx.append(lx[0])
                        else:
                            absx.append(absx[-1]+int(sqrt((lx[-1]-lx[-2])**2+(ly[-1]-ly[-2])**2)))
                    if len(vert)==0:
                        vert.append((absx[0],lat_vert[0],lon_vert[0]))
                        vert.append((absx[-1],lat_vert[-1],lon_vert[-1]))
                    else:
                        vert.append((absx[-1],lat_vert[-1],lon_vert[-1]))

                #Line plot parameters and line plot itself

                ncv = np.asarray(ncv)
                r_ncv = ncv[~np.isnan(ncv)]
                if len(r_ncv) != 0:
                    ax_line.axis([min(absx)-(max(absx)-min(absx))/20., max(absx)+(max(absx)-min(absx))/20., min(r_ncv), max(r_ncv)+(max(r_ncv)-min(r_ncv))/20.])
                else:
                    pass
                x_tick=[]
                x_label=[]
                if len(vert) > 1:
                    for v in vert:
                        x_tick.append(v[0])
                        x_label.append('('+str('%.1f' % v[1])+','+str('%.1f' % v[2])+')')
              
                else:
                    pass
                ax_line.set_xticks(x_tick)
                ax_line.set_xticklabels(x_label, rotation=30, fontsize=8)
                ax_line.xaxis.grid(True)
                ax_line.yaxis.grid(True)
                ax_line.plot(absx,ncv)




                # Polygon mask
                mask_polygon = np.zeros(( np.amax(np.asarray(ly))-np.amin(np.asarray(ly))+1, np.amax(np.asarray(lx))-np.amin(np.asarray(lx))+1))
                poly_vert=[]
                for i in vertices:
                    poly_vert.append((i[1]-np.amin(np.asarray(ly)),i[0]-np.amin(np.asarray(lx))))
            
                path = Path(poly_vert)
                mx_slice = mx[(min(np.asarray(ly))-1):(max(np.asarray(ly))), (min(np.asarray(lx))-1):(max(np.asarray(lx)))]
                for index, val in np.ndenumerate(mx_slice):
                    if path.contains_point(index)==1:
                        mask_polygon[index]=1
                    else:
                        pass

                #polygon plot
                ax_zoom = fig_line.add_subplot(122)
                x_tick, y_tick, x_label, y_label = [],[],[],[]
                for v in np.linspace(0,  np.amax(np.asarray(ly))-np.amin(np.asarray(ly)), num = 21):
                    y_tick.append(v)
                    y_label.append(str(int(y_0+v+ np.amin(np.asarray(ly)))))
                for v in np.linspace(0,  np.amax(np.asarray(lx))-np.amin(np.asarray(lx)), num = 21):
                    x_tick.append(v)
                    x_label.append(str(int(x_0+v+ np.amin(np.asarray(lx)))))
                ax_zoom.set_xticks(x_tick)
                ax_zoom.set_xticklabels(x_label, rotation=30)
                ax_zoom.set_yticks(y_tick)
                ax_zoom.set_yticklabels(y_label)
                mx_slice_masked = ma.masked_where(mask_polygon==0,mx_slice)
                mx_slice_out = ma.masked_where(mask_polygon==1,mx_slice)
                lvls = np.linspace(np.amin(mx_slice_masked),np.amax(mx_slice_masked),num=21)
                print "the following arguments can be passed to the script for further zooming if needed:"
                print "--yrange ", str(y_0+min(np.asarray(ly)))+":"+str(y_0+max(np.asarray(ly))), " --xrange ", str(x_0+min(np.asarray(lx)))+":"+str(x_0+max(np.asarray(lx))), " --var_min ", np.amin(mx_slice_masked), " --var_max ", np.amax(mx_slice_masked)
                cmap_zoom=plt.cm.spectral 
                cmap_out = plt.cm.Greys

                if args.contourf == "yes":
                    slice_mesh=ax_zoom.contourf(mx_slice_masked,levels=lvls, cmap=cmap_zoom)
                    slice_mesh_out=ax_zoom.contourf(mx_slice_out,levels=lvls, cmap=cmap_out, vmin=np.amin(mx_slice_masked), vmax=np.amax(mx_slice_masked))
                else:
                    slice_mesh=ax_zoom.pcolormesh(mx_slice_masked, cmap=cmap_zoom)
                    slice_out=ax_zoom.pcolormesh(mx_slice_out, cmap=cmap_out, vmin=np.amin(mx_slice_masked), vmax=np.amax(mx_slice_masked))
                for vert in vertices:
                    txt = plt.text(round(vert[0])-min(np.asarray(lx)), round(vert[1])-min(np.asarray(ly)), "("+str('%.1f' %  lat[(round(vert[1]),round(vert[0]))])+","+str('%.1f' % lon[(round(vert[1]),round(vert[0]))])+")", fontsize=8)
                    txt.set_bbox(dict(color='white', alpha=0.5, edgecolor='red'))

                plt.axis('tight')
                # info at polygon vertices 
                box = ax_zoom.get_position()
                ax_zoom.set_position([box.x0*1.05, box.y0, box.width, box.height])
                axColor = plt.axes([box.x0 + box.width * 1.16, box.y0, 0.01, box.height])
                plt.colorbar(slice_mesh, cax = axColor, ticks=lvls, orientation="vertical")

                #nullify arrays for next pick
                self.xs = []
                self.ys = []
                plt.show()

            else:
                print "click one more time please!"
            
        if event.dblclick ==  True:
            print "double click detected"
            line.figure.canvas.mpl_disconnect(self.cid)
            exit()
Exemple #10
0
    def get_contours(self, fitsfile, Ak=None):
        """
        Given a continuum FITS file, return the contours enclosing 
        the source position at a given flux level.
        
        There are a couple complications:
        1) We seek a closed contour
        2) The contour should only extend over the region
            covered by the NIR image (K-band, in this case)
        
        This function could usefully be refactored/simplified
        """

        hdulist = fits.open(fitsfile)

        header = hdulist[0].header
        img = hdulist[0].data
        if not Ak:
            contour_level = self.contour_level  #10 av in Jy?
            print("Using a contour level of: " + str(round(contour_level, 3)))

        else:
            contour_level = self.calculate_continuum_level(
                cont_survey=self.cont_survey, Ak=Ak)
            print("Using a contour level of: " + str(round(contour_level, 3)))

        wcs = pywcs.WCS(header)
        yy, xx = np.indices(img.shape)

        img[img != img] = 0

        #Set the borders of an image to be zero (blank) so that all contours close
        img[0, :] = 0.0
        img[-1, :] = 0.0
        img[:, 0] = 0.0
        img[:, -1] = 0.0

        self.all_contours = []

        #for contour_level in contour_levels:
        wcs_paths = self.make_contour_at_level(wcs, img, yy, xx, contour_level)
        #    self.all_contours.append(np.array(wcs_paths))

        index = 0
        self.good_contour = False

        print(self.glon, self.glat)

        if len(wcs_paths) > 1:
            print("More than one contour")
            for i, wcs_path in enumerate(wcs_paths):
                path = Path(wcs_path)
                #print(path)
                if path.contains_point((self.glon, self.glat)):
                    index = i
                    self.good_contour = True
                    print("This was the contour containing the center")
            #index = 1
            #self.good_contour = True
            self.contours = wcs_paths[index]
            #self.contours[:,0] -= 0.02
            #self.contours[:,1] += 0.02
            #print(self.contours[:,1])

        else:
            self.good_contour = True
            self.contours = wcs_paths[0]

        #This selects a contour containing the center
        #Now we trim the contour to the boundaries of the UKIDSS image
        if self.good_contour:
            #And check to see which contour (if any) contains the center
            self.good_contour = False
            #Find the boundaries of the UKIDSS (K-band image) in Galactic coordinates
            h = fits.getheader(self.kim)
            xmin = 0
            xmax = h['NAXIS1']
            ymin = 0
            ymax = h['NAXIS2']
            wcs = pywcs.WCS(h)
            corners = wcs.wcs_pix2world(
                [[xmin, ymin], [xmin, ymax], [xmax, ymax], [xmax, ymin]], 0)
            gals = []
            for coord in corners:
                c = coordinates.ICRS(ra=coord[0],
                                     dec=coord[1],
                                     unit=[u.deg, u.deg])
                gal = c.transform_to(coordinates.Galactic)
                gals.append(gal)
            mycoords = []
            for gal in gals:
                l, b = gal.l.degree, gal.b.degree
                mycoords.append((l, b))
            p1 = shapely.geometry.Polygon(self.contours)
            p1 = p1.buffer(0)
            #print(p1.is_valid)
            p2 = shapely.geometry.Polygon(mycoords)
            p2.buffer(0)
            #print(p2.is_valid)
            ya = p1.intersection(p2)
            #print(ya)
            try:
                mycontours = []
                xx, yy = ya.exterior.coords.xy
                for ix, iy in zip(xx, yy):
                    mycontours.append((ix, iy))
                self.contours = np.array(mycontours)
                self.good_contour = True
            except AttributeError:  #MultiPolygon
                mycontours = []
                for j, poly in enumerate(ya):
                    try:
                        #print(poly)
                        yoyo = np.asarray(poly.exterior.coords.xy)
                        #print(yoyo.shape)
                        #print(yoyo)
                        yoyo2 = yoyo.T
                        #print(poly.exterior.coords.xy)
                        #yya = poly.exterior.coords.xy[0]
                        #print(yya.shape)
                        #print(yoyo2)
                        path = Path(yoyo2)
                        if path.contains_point((self.glon, self.glat)):
                            self.good_contour = True
                            index = i
                            print("This was the contour containing the center")
                            xx, yy = poly.exterior.coords.xy
                            for ix, iy in zip(xx, yy):
                                mycontours.append((ix, iy))
                            self.contours = np.array(mycontours)
                    except IOError:
                        pass

        self.contour_area = self.calc_contour_area(self.contours)

        if not self.good_contour:
            print("######## No good contour found ########")
            self.contours = None
            self.contour_area = 0
    def get_contours(self, fitsfile, Ak=None):
        """
        Given a continuum FITS file, return the contours enclosing 
        the source position at a given flux level.
        
        There are a couple complications:
        1) We seek a closed contour
        2) The contour should only extend over the region
            covered by the NIR image (K-band, in this case)
        
        This function could usefully be refactored/simplified
        """
        
        hdulist = fits.open(fitsfile)

        header = hdulist[0].header
        img = hdulist[0].data
        if not Ak:
            contour_level = self.contour_level #10 av in Jy?
            print("Using a contour level of: "+str(round(contour_level,3)))
            
        else:
            contour_level = self.calculate_continuum_level(
                                 cont_survey=self.cont_survey, 
                                 Ak=Ak)
            print("Using a contour level of: "+str(round(contour_level,3)))

        wcs = pywcs.WCS(header)
        yy,xx = np.indices(img.shape)

        img[img!=img] = 0
        
        #Set the borders of an image to be zero (blank) so that all contours close
        img[0,:] = 0.0
        img[-1,:] = 0.0
        img[:,0] = 0.0
        img[:,-1] = 0.0
        
        self.all_contours = []
        
        
        #for contour_level in contour_levels:
        wcs_paths = self.make_contour_at_level(wcs,img,yy,xx,contour_level)
        #    self.all_contours.append(np.array(wcs_paths))

        index = 0
        self.good_contour = False
        
        print(self.glon,self.glat)
        
        if len(wcs_paths) > 1:
            print("More than one contour")
            for i,wcs_path in enumerate(wcs_paths):
                path = Path(wcs_path)
                #print(path)
                if path.contains_point((self.glon,self.glat)):
                    index = i
                    self.good_contour = True
                    print("This was the contour containing the center")
            #index = 1
            #self.good_contour = True
            self.contours = wcs_paths[index]
            #self.contours[:,0] -= 0.02
            #self.contours[:,1] += 0.02
            #print(self.contours[:,1])
            
        else:
            self.good_contour = True
            self.contours =  wcs_paths[0]            
        
        #This selects a contour containing the center
        #Now we trim the contour to the boundaries of the UKIDSS image
        if self.good_contour:
            #And check to see which contour (if any) contains the center
            self.good_contour = False
            #Find the boundaries of the UKIDSS (K-band image) in Galactic coordinates
            h = fits.getheader(self.kim)
            xmin = 0
            xmax = h['NAXIS1']
            ymin = 0
            ymax = h['NAXIS2']
            wcs = pywcs.WCS(h)
            corners = wcs.wcs_pix2world([[xmin,ymin],[xmin,ymax],[xmax,ymax],[xmax,ymin]],0)
            gals = []
            for coord in corners:
                c = coordinates.ICRS(ra=coord[0],dec=coord[1],unit=[u.deg,u.deg])
                gal = c.transform_to(coordinates.Galactic)
                gals.append(gal)
            mycoords = []
            for gal in gals:
                l,b = gal.l.degree,gal.b.degree
                mycoords.append((l,b))
            p1 = shapely.geometry.Polygon(self.contours)
            p1 = p1.buffer(0)
            #print(p1.is_valid)
            p2 = shapely.geometry.Polygon(mycoords)
            p2.buffer(0)
            #print(p2.is_valid)
            ya = p1.intersection(p2)
            #print(ya)
            try:
                mycontours = []
                xx,yy = ya.exterior.coords.xy
                for ix,iy in zip(xx,yy):
                    mycontours.append((ix,iy))
                self.contours = np.array(mycontours)
                self.good_contour = True
            except AttributeError: #MultiPolygon
                mycontours = []
                for j,poly in enumerate(ya):
                    try:
                        #print(poly)
                        yoyo = np.asarray(poly.exterior.coords.xy)
                        #print(yoyo.shape)
                        #print(yoyo)
                        yoyo2 = yoyo.T
                        #print(poly.exterior.coords.xy)
                        #yya = poly.exterior.coords.xy[0]
                        #print(yya.shape)
                        #print(yoyo2)
                        path = Path(yoyo2)
                        if path.contains_point((self.glon,self.glat)):
                            self.good_contour = True
                            index = i
                            print("This was the contour containing the center")
                            xx,yy = poly.exterior.coords.xy
                            for ix,iy in zip(xx,yy):
                                mycontours.append((ix,iy))
                            self.contours = np.array(mycontours)
                    except IOError:
                        pass
                        
        self.contour_area = self.calc_contour_area(self.contours)
        
        if not self.good_contour:
            print("######## No good contour found ########")
            self.contours = None
            self.contour_area = 0