def number_of_images(self, sourceposition):
        rc=self.radial_caustic()
        tc=self.tangential_caustic()

        if usePath:
        
            # New Matplotlib:
            rc=Path(rc)
            tc=Path(tc)
            if rc.contains_points(np.atleast_2d(sourceposition))[0]:
               if tc.contains_points(np.atleast_2d(sourceposition))[0]:
                   return 4
               return 2
            if tc.contains_points(np.atleast_2d(sourceposition))[0]:
               return 3
        
        else:
            # Old Matplotlib:
            if nxutils.points_inside_poly(np.atleast_2d(sourceposition),rc)[0]:
                if nxutils.points_inside_poly(np.atleast_2d(sourceposition),tc)[0]:
                    return 4
                return 2
            if nxutils.points_inside_poly(np.atleast_2d(sourceposition),tc)[0]:
                return 3

        return 1
Example #2
0
 def number_of_images(self, sourceposition):
     if nx.points_inside_poly(np.atleast_2d(sourceposition), self.radial_caustic())[0]:
         if nx.points_inside_poly(np.atleast_2d(sourceposition), self.tangential_caustic())[0]:
             return 4
         return 2
     if nx.points_inside_poly(np.atleast_2d(sourceposition), self.tangential_caustic())[0]:
         return 3
     return 1
Example #3
0
def main(shapefile, picklefile):
    if picklefile:
      [npts, x, y, z, zraw, xil, yil, grid, missing] = cPickle.load(open(picklefile,'rb'))
      points = np.vstack((x,y)).T

    # Load administrative area
    shp = ShapeFile(shapefile)
    dbf = dbflib.open(shapefile)

    coastline = []

    # Process every shape from the ShapeFile
    print "Processing shapes ..."
    for npoly in range(shp.info()[0]):
        shp_object = shp.read_object(npoly)
        shp_dict = dbf.read_record(npoly)
        verts = shp_object.vertices()

        if "NAME_1" in shp_dict:
          name = "%s" % (shp_dict["NAME_1"])
        else:
          name = "Unknown"

        print "Processing %s" % (name)
        # Extract city polygon vertices (ring per ring)
        for ring in verts:
          vx = []
          vy = []
          for point in ring:
            vx.append(point[0])
            vy.append(point[1])

          # Only process big enough rings
          if len(vx) > 256: # big enough
            poly_verts = zip(vx,vy)

            if picklefile:
              # Compute intersections with the city
              intersection = points_inside_poly(points, poly_verts)
              npts = sum(1 for x in points_inside_poly(points, poly_verts) if x)
            else:
              npts = 1 # Add this polygon

            # Add the ring to the coastine if measures inside
            if npts > 0:
              polygon = Polygon(poly_verts)
              if not polygon.is_empty and polygon.is_valid:
                print "- Add polygon (%d)" % (len(vx))
                coastline.append(polygon)
            else:
                print "- Skip polygon (%d)" % (len(vx))
    
    print "Union of %d polygons" % len(coastline)
    coast = cascaded_union(coastline)
    cPickle.dump(coast,open('coastline.pickle','wb'),-1)
    print "Done."
Example #4
0
    def gate(self, fcm, chan=None, invert=False, name=None):
        """
        return gated region of FCM data
        """
        if chan is None:
            chan = self.chan
        if isinstance(chan, tuple):
            chan = list(chan)
        for i, j in enumerate(chan):
            if isinstance(j, str):
                chan[i] = fcm.name_to_index(j)

        if name is None:
            name = self.name
        #idxs = points_in_poly(self.vert, fcm.view()[:, chan])

        # matplotlib has points in poly routine in C
        # no faster than our numpy version
        idxs = points_inside_poly(fcm.view()[:, chan], self.vert)

        if invert:
            idxs = numpy.invert(idxs)

        node = GatingNode(name, fcm.get_cur_node(), idxs)
        fcm.add_view(node)
        return fcm
Example #5
0
def getSRTMv3Areas(polygons):
    rawAreas = []
    for p in polygons:
        lons = sorted([el[0] for el in p])
        lats = sorted([el[1] for el in p])
        minLon = lons[0]
        maxLon = lons[-1]
        minLat = lats[0]
        maxLat = lats[-1]
        for lon in numpy.arange(minLon + 0.5, maxLon, 1.0):
            for lat in numpy.arange(minLat + 0.5, maxLat, 1.0):
                points = [
                    (lon, lat),
                ]
                if mplversion < "1.3.0":
                    inside = points_inside_poly(points, p)
                else:
                    inside = PolygonPath(p).contains_points(points)
                if numpy.all(inside):
                    areaName = makeFileNamePrefix(getLowInt(lon),
                                                  getLowInt(lat))
                    rawAreas.append(areaName)
    # some tiles are located in holes and may have been wrongly identified
    # as lying inside a polygon.  To eliminate those entries, only elements
    # occuring an odd number of times are kept
    areas = []
    for area in rawAreas:
        nOccurrences = rawAreas.count(area)
        if nOccurrences % 2 == 1 and not area in areas:
            areas.append(area)
    return sorted(areas)
Example #6
0
    def contains(self, x, y):
        """
        Test whether a set of (x,y) points falls within
        the region of interest

        :param x: A list of x points
        :param y: A list of y points

        *Returns*

           A list of True/False values, for whether each (x,y)
           point falls within the ROI

        """
        if not self.defined():
            raise UndefinedROI
        if not isinstance(x, np.ndarray):
            x = np.asarray(x)
        if not isinstance(y, np.ndarray):
            y = np.asarray(y)

        xypts = np.column_stack((x.flat, y.flat))
        xyvts = np.column_stack((self.vx, self.vy))
        result = points_inside_poly(xypts, xyvts)
        good = np.isfinite(xypts).all(axis=1)
        result[~good] = False
        result.shape = x.shape
        return result
Example #7
0
def _raster_points(tmpx, tmpy, gridShape) :
    """
    Find the raster grid points that lie within the voxel
    """
    if (max(tmpx) < 0 or max(tmpy) < 0 or
        min(tmpx) >= gridShape[1] or min(tmpy) >= gridShape[0]) :
        # points lie outside the rasterization grid
        # so, none of them are good.
        return ([], [])

    resVol = zip(tmpx[[0, 1, 2, 3, 0]],
                 tmpy[[0, 1, 2, 3, 0]])

    # Getting all of the points that the polygon has, and then some.
    # This meshed grid is bounded by the domain.
    bbox = ((int(max(np.floor(min(tmpy)), 0)),
             int(min(np.ceil(max(tmpy)), gridShape[0] - 1))),
            (int(max(np.floor(min(tmpx)), 0)),
             int(min(np.ceil(max(tmpx)), gridShape[1] - 1))))
    (ygrid, xgrid) = np.meshgrid(np.arange(bbox[0][0], bbox[0][1] + 1),
                                 np.arange(bbox[1][0], bbox[1][1] + 1))
    gridPoints = zip(xgrid.flat, ygrid.flat)

    if len(gridPoints) == 0 :
        print "Bad situation...:", bbox, gridShape, min(tmpy), max(tmpy), \
                                                    min(tmpx), max(tmpx)
        gridPoints = np.zeros((0, 2), dtype='i')

    # Determines which points fall within the resolution volume.  These
    # points will be the ones that will be assigned the value of the
    # original data point that the resolution volume represents.
    goodPoints = points_inside_poly(gridPoints, resVol)

    return (ygrid.flat[goodPoints], xgrid.flat[goodPoints])
Example #8
0
def get_contour_mask(doselut, dosegridpoints, contour):
    """Get the mask for the contour with respect to the dose plane."""

    grid = nx.points_inside_poly(dosegridpoints, contour)
    grid = grid.reshape((len(doselut[1]), len(doselut[0])))

    return grid
Example #9
0
def inregion(x,y,r):
    """
    ins = inregion(x,y,r)

    Returns an array of booleans indicating whether the x,y pairs are
    in region r. If region r contains multiple polygons, the ones inside 
    the biggest one are assumed to be holes; the ones inside holes
    are assumed to be islands; and so on.
    
    :Parameters:
      x : array
        x coordinates of test points
      y : array
        y coordinates of test points
      r : ShapeObject
        The region.
    """
    xy = np.vstack((x,y)).T

    # Record whether each point is inside each polygon.
    ins = []
    for v in r:
        ins.append(points_inside_poly(xy,v))
    ins = np.array(ins)
    
    # Return an array of booleans. An element is True if
    # the corresponding point is inside an odd number of polygons.
    return np.sum(ins, axis=0) % 2 == 1
	def __find(self, verts):
		ps = np.array(map(lambda x: [x[1], x[2]], self.points), float)
		points_in = nx.points_inside_poly(ps, verts)
		for i in range(len(points_in)):
			if points_in[i] == True:
				 return self.points[i]
		return None
Example #11
0
    def countMDPoints(self, bmap, dx=20000, dy=20000):
        from matplotlib.nxutils import points_inside_poly
        xs = np.arange(bmap.llcrnrx, bmap.urcrnrx + dx, dx)
        ys = np.arange(bmap.llcrnry, bmap.urcrnry + dy, dy)
        lon, lat, x_grid, y_grid = bmap.makegrid(xs.shape[0],
                                                 ys.shape[0],
                                                 returnxy=True)
        x, y = x_grid.flatten(), y_grid.flatten()
        points = np.vstack((x, y)).T

        nx = xs.shape[0]
        ny = ys.shape[0]
        counts = np.zeros((points.shape[0], ))

        for i in xrange(self.data.shape[0]):
            md_x, md_y = bmap(self.data['Lon'][i], self.data['Lat'][i])
            poly_xy = np.vstack((md_x, md_y)).T
            counts = np.where(points_inside_poly(points, poly_xy), counts + 1,
                              counts)

        counts = counts.reshape((ny, nx))
        counts = np.ma.array(counts, mask=counts < 1)
        x = x.reshape((ny, nx))
        y = y.reshape((ny, nx))
        return counts, x, y
Example #12
0
def get_ds9_mask(shape, show=False):
    import commands
    import string
    from matplotlib.nxutils import points_inside_poly  #@UnresolvedImport

    mask = np.zeros(shape)
    ind = np.indices(shape)
    ind = zip(ind[0].ravel(), ind[1].ravel())
    out = string.split(commands.getoutput('xpaget ds9 regions'), '\n')
    for r in out:
        if r[0] != '#' and r[:
                             6] != 'global' and r[:
                                                  3] != 'XPA' and r[:
                                                                    8] != 'physical':
            i = string.find(r, '(')
            type = r[:i]
            if type == 'polygon':
                vertices = eval(r[i + 1:-1])
                vertices = [
                    vertices[2 * i:2 * i + 2]
                    for i in range(len(vertices) / 2)
                ]
                mask += points_inside_poly(ind, vertices).reshape(shape)
            if type == 'circle':
                c1, c2, r = eval(r[i + 1:-1])
                c = lambda x, y: (x - c1)**2. + (y - c2)**2. < r**2.
                mask += np.fromfunction(c, shape)
    if show: array2ds9(mask)
    return np.bool8(mask)
Example #13
0
 def mask_polygon(self, polyverts, mask_value=0.0):
     """
     Mask Cartesian points contained within the polygon defined by polyverts
     
     A cell is masked if the cell center (x_rho, y_rho) is within the
     polygon. Other sub-masks (mask_u, mask_v, and mask_psi) are updated
     automatically.
     
     mask_value [=0.0] may be specified to alter the value of the mask set
     within the polygon.  E.g., mask_value=1 for water points.
     """
     
     polyverts = np.asarray(polyverts)
     assert polyverts.ndim == 2, \
         'polyverts must be a 2D array, or a similar sequence'
     assert polyverts.shape[1] == 2, \
         'polyverts must be two columns of points'
     assert polyverts.shape[0] > 2, \
         'polyverts must contain at least 3 points'
     
     mask = self.mask_rho
     inside = points_inside_poly(
         np.vstack( (self.x_rho.flat, self.y_rho.flat) ).T,
         polyverts)
     if np.any(inside):
         self.mask_rho.flat[inside] = mask_value
Example #14
0
    def get_variables(self, requestedVariables, time=None,
                      x=None, y=None, z=None, block=False):

        if isinstance(requestedVariables, str):
            requestedVariables = [requestedVariables]

        self.check_arguments(requestedVariables, time, x, y, z)

        # Apparently it is necessary to first convert from x,y to lon,lat
        # using proj library, and back to x,y using Basemap instance
        # Perhaps a bug in Basemap related to x_0/y_0 offsets?
        # Nevertheless, seems not to affect performance
        lon, lat = self.xy2lonlat(x, y)
        x, y = self.map(lon, lat, inverse=False)
        points = np.c_[x, y]

        insidePoly = np.array([False]*len(x))
        if has_nxutils is True:
            for polygon in self.polygons:
                insidePoly[nx.points_inside_poly(points, polygon)] = True
        else:
            for polygon in self.polygons:
                insidePoly += np.array(polygon.contains_points(points))

        variables = {}
        variables['land_binary_mask'] = insidePoly

        return variables
Example #15
0
def brown_fct(t_act_hphb, **kwargs):
    '''
    This was made to check the fct around brown98 area.
    '''
    sup_phot = kwargs['sup_phot']
    btrack = kwargs.get('btrack')
    mag1_cut = kwargs.get('mag1_cut')
    mag2_cut = kwargs.get('mag2_cut')
    frac_bulge = sup_phot['bulge_fraction'][1]  # Bulge fraction B/(B+D)

    # file locations
    file_src = '/astro/net/angst2/philrose/PHAT/paper/supporting_files/'
    if not os.path.isdir(file_src):
        file_src = '/Users/phil/research/PHAT//paper/supporting_files/'
    b98region = os.path.join(file_src, 'brown98_region_masked.reg')
    b98fits = os.path.join(file_src, 'phat_photcat_b98region.fits')

    # load b98 photometry file
    b98_phat = pyfits.open(b98fits)[1].data
    b98_ra = b98_phat.field('ra')
    b98_dec = b98_phat.field('dec')
    b98_mag1 = b98_phat.field('mag1_uvis')
    b98_mag2 = b98_phat.field('mag2_uvis')
    b98_color = b98_mag1 - b98_mag2

    # load b98 region
    ras, decs = file_io.read_reg(b98region, shape='polygon')
    foc_fov = np.column_stack((ras[0], decs[0]))

    # b98 called uv-brights stars 1 mag brighter than completeness limit
    b98_mag1_cut = mag1_cut - 1.
    b98_mag2_cut = mag2_cut - 1.
    inds1 = np.nonzero(b98_mag1 < b98_mag1_cut)[0]
    inds2 = np.nonzero(b98_mag2 < b98_mag2_cut)[0]
    b98_cut = list(set(inds1) & set(inds2))

    # load the hphb color-mag limits
    verts = get_hphb_cmd_verts(btrack, **kwargs)

    # which b98 stars are in the hphb color-mag limit
    points = np.column_stack((b98_color[b98_cut], b98_mag2[b98_cut]))
    #points = np.column_stack((b98_color,b98_mag2))
    inds = np.nonzero(nxutils.points_inside_poly(points, verts))[0]

    nhphb_foc = float(len(inds))

    rif_36_foc = 0.527
    L_T = rif_36_foc * 1.61e8 * frac_bulge  #230893.52211437
    Bt = 2.2e-11  # From Spectral Evolution of Galaxies ASSL 122 p195+
    t_hphb = nhphb_foc / (Bt * L_T)

    # hard coded expected lifetimes.
    # median time_spent_on_cmd for the three largest mass tracks
    #t_act_hphb =  2e6#1e7 # 10694600 # 994000.0
    print 'Brown Check:'
    print 'NHPHB expected:', L_T * Bt * t_act_hphb
    print 'percent msto that become x as a function of radius:'
    print 'HPHB', t_hphb / t_act_hphb * 100
    print 'nhbhbs', len(inds)
    return
Example #16
0
    def getMDAreas(self,dx=20000,dy=20000,
                    llcrnrlon=-119.2,
                    llcrnrlat=23.15,
                    urcrnrlon=-65.68,
                    urcrnrlat=48.7):
        bmap = Basemap(projection="lcc",
                       llcrnrlon=llcrnrlon,
                       llcrnrlat=llcrnrlat,
                       urcrnrlon=urcrnrlon,
                       urcrnrlat=urcrnrlat,
                       resolution='l',
                       lat_0=38.5,
                       lat_1=38.5,
                       lon_0=-97.0)
        from matplotlib.nxutils import points_inside_poly
        xs = np.arange(bmap.llcrnrx,bmap.urcrnrx + dx,dx)
        ys = np.arange(bmap.llcrnry,bmap.urcrnry + dy,dy)
        lon,lat,x_grid,y_grid = bmap.makegrid(xs.shape[0],ys.shape[0],returnxy=True)
        x, y = x_grid.flatten(), y_grid.flatten()
        points = np.vstack((x,y)).T
        
        nx = xs.shape[0]
        ny = ys.shape[0]
        areas = np.zeros((self.data.shape[0],))

        for i in xrange(self.data.shape[0]):
            md_x,md_y = bmap(self.data['Lon'][i],self.data['Lat'][i])
            poly_xy = np.vstack((md_x,md_y)).T
            areas[i] = np.nonzero(points_inside_poly(points,poly_xy))[0].shape[0] * dx * dy / 1000**2

        return areas
Example #17
0
def _raster_points(tmpx, tmpy, gridShape):
    """
    Find the raster grid points that lie within the voxel
    """
    if max(tmpx) < 0 or max(tmpy) < 0 or min(tmpx) >= gridShape[1] or min(tmpy) >= gridShape[0]:
        # points lie outside the rasterization grid
        # so, none of them are good.
        return ([], [])

    resVol = zip(tmpx[[0, 1, 2, 3, 0]], tmpy[[0, 1, 2, 3, 0]])

    # Getting all of the points that the polygon has, and then some.
    # This meshed grid is bounded by the domain.
    bbox = (
        (int(max(np.floor(min(tmpy)), 0)), int(min(np.ceil(max(tmpy)), gridShape[0] - 1))),
        (int(max(np.floor(min(tmpx)), 0)), int(min(np.ceil(max(tmpx)), gridShape[1] - 1))),
    )
    (ygrid, xgrid) = np.meshgrid(np.arange(bbox[0][0], bbox[0][1] + 1), np.arange(bbox[1][0], bbox[1][1] + 1))
    gridPoints = zip(xgrid.flat, ygrid.flat)

    if len(gridPoints) == 0:
        print("Bad situation...:", bbox, gridShape, min(tmpy), max(tmpy), min(tmpx), max(tmpx))
        gridPoints = np.zeros((0, 2), dtype="i")

    # Determines which points fall within the resolution volume.  These
    # points will be the ones that will be assigned the value of the
    # original data point that the resolution volume represents.
    goodPoints = points_inside_poly(gridPoints, resVol)

    return (ygrid.flat[goodPoints], xgrid.flat[goodPoints])
Example #18
0
 def crownMap(self, objList):
     """
     Create a crown map. Crowns area treated as the convex hull of the tree material.
     Image values represent the number of intercepted tree crowns.
     Returns the vertically projected fractional crown cover of the scene.
     Only live trees are included, as measured in the field.
     """
     xDim, yDim = self.getDims()
     crowns = zeros([xDim,yDim], dtype=uint8)
     xi = repeat([arange(xDim)*self.resolution-self.extent[0]/2.0+self.resolution/2.0],yDim,axis=0)
     yi = repeat([arange(yDim)*self.resolution-self.extent[1]/2.0+self.resolution/2.0],xDim,axis=0).transpose()
     points = array([xi.flatten(),yi.flatten()]).transpose()
     obj = libratScene()
     obj.readObjList(objList,positions=True)
     for i,tree in enumerate(obj.scene["object"]):
         if (obj.scene["status"][i] == "live"):
             treeObj = libratObject(tree)
             xyz = treeObj.get_vertices()
             chull = utilities.convex_hull(xyz[:,0],xyz[:,1])
             xr,yr = utilities.rotate2D(chull[:,0], chull[:,1], obj.scene["rotation"][i])
             xr0 = append(xr,xr[0])
             yr0 = append(yr,yr[0])
             poly = array([xr0+obj.scene["x"][i],yr0+obj.scene["y"][i]]).transpose()
             inside = nxutils.points_inside_poly(points, poly).reshape((xDim,yDim))
             crowns = where(inside, crowns+uint(1), crowns)
             
     self.type = "crown"
     self.map = crowns
Example #19
0
def get_contour_mask(doselut, dosegridpoints, contour):
    """Get the mask for the contour with respect to the dose plane."""

    grid = nx.points_inside_poly(dosegridpoints, contour)
    grid = grid.reshape((len(doselut[1]), len(doselut[0])))

    return grid
Example #20
0
File: roi.py Project: hayd/glue
    def contains(self, x, y):
        """
        Test whether a set of (x,y) points falls within
        the region of interest

        :param x: A list of x points
        :param y: A list of y points

        *Returns*

           A list of True/False values, for whether each (x,y)
           point falls within the ROI

        """
        if not self.defined():
            raise UndefinedROI
        if not isinstance(x, np.ndarray):
            x = np.asarray(x)
        if not isinstance(y, np.ndarray):
            y = np.asarray(y)

        xypts = np.column_stack((x.flat, y.flat))
        xyvts = np.column_stack((self.vx, self.vy))
        result = points_inside_poly(xypts, xyvts)
        good = np.isfinite(xypts).all(axis=1)
        result[~good] = False
        result.shape = x.shape
        return result
Example #21
0
def inside_poly(vertices,data):
    if(matplotlib.__version__ < '1.2'):
        mask = points_inside_poly(data, vertices)
    else:
        mask = Path(vertices).contains_points(data)

    return mask
Example #22
0
def get_polygon(verts, padding=None, dilate=False):
    """Get a polygon from a list of verts"""

    verts = np.array(verts)

    shape = verts.max(0)

    im = np.zeros(shape)

    pts_list = np.where(im == 0)

    pts = np.array(zip(*pts_list))

    im.ravel()[nx.points_inside_poly(pts, verts)] = 1

    if padding is not None:

        im = get_padded(im)

    if dilate:

        return binary_dilation(im)

    else:

        return im
Example #23
0
 def __lasso_callback__(self, verts):
     """ Callback for the lasso """
     if self.y is not None:
         xys = array([self.x, self.y]).T
         mask = points_inside_poly(xys, verts)
         ind = nonzero(mask)[0]
     else:
         _verts = np.asarray(verts)
         xmin = _verts[:, 0].min()
         xmax = _verts[:, 0].max()
         ind = np.where((self.x >= xmin) & (self.x <= xmax))
     self.canvas.draw_idle()
     self.canvas.widgetlock.release(self._lasso)
     del self._lasso
     self.ind = ind
     (f1d, f2d, f1d_kwargs, f2d_kwargs) = self._next_select
     self.add_sample(ind,
                     f1d=f1d,
                     f2d=f2d,
                     f1d_kwargs=f1d_kwargs,
                     f2d_kwargs=f2d_kwargs)
     while len(self._next_select) > 0:
         del self._next_select[0]
     self.draw()
     self.pchanged()
def get_overlap_areas():
    ast_file = kwargs.get('ast_file')
    ast = ASTs.load_ast_file(ast_file)
    ra = ast['ra']
    dec = ast['dec']
    points = np.column_stack((ra, dec))

    v3_contours = PHAT_DIR_EXTRA3 + 'contours_v3.reg'
    annulus_areas = calcs.area_within_annulus(v3_contours)
    annuli = reg_to_array(v3_contours, shape='polygon')
    aras = [annuli[i]['ra'] for i in np.sort(annuli.keys())]
    adecs = [annuli[i]['dec'] for i in np.sort(annuli.keys())]
    verts = [np.column_stack((aras[i], adecs[i])) for i in range(len(aras))]

    center_ra = 10.68463
    center_dec = 41.26693
    top = np.nonzero(dec >= center_dec)[0]
    bottom = np.nonzero(dec <= center_dec)[0]
    overlaps = reg_to_array('overlaps.reg', shape='polygon')
    mra, mdec = overlaps['2']['ra'], overlaps['2']['dec']
    overlap_verts = np.column_stack((mra, mdec))

    overlap_mask = nxutils.points_inside_poly(points, overlap_verts)
    ov_inds = np.nonzero(overlap_mask)[0]
    # much better verts:
    ov_verts = GenUtils.get_verts(ra[ov_inds],
                                  dec[ov_inds],
                                  nbinsx=300,
                                  nbinsy=300)

    inds_annuli = calcs.points_inside_ds9_polygon(v3_contours, ra, dec)

    masked_vertst = []
    masked_vertsb = []
    areas = []
    for i, rad_inds in enumerate(inds_annuli):
        tinds = list(set(rad_inds) & set(ov_inds) & set(top))
        binds = list(set(rad_inds) & set(ov_inds) & set(bottom))
        vertst = GenUtils.get_verts(ra[tinds],
                                    dec[tinds],
                                    nbinsx=50,
                                    nbinsy=50)
        vertsb = GenUtils.get_verts(ra[binds],
                                    dec[binds],
                                    nbinsx=50,
                                    nbinsy=50)
        masked_vertst.append(vertst)
        masked_vertsb.append(vertsb)
        areat = GenUtils.area(vertst)
        areab = GenUtils.area(vertsb)
        areas.append(areat + areab)

    # testing
    #[plt.plot(r,d) for r,d in zip(aras,adecs)]
    #[ax.plot(mv[:,0],mv[:,1],lw=3,color='cyan') for i,mv in enumerate(masked_vertst)]
    #[ax.plot(mv[:,0],mv[:,1],lw=3,color='cyan') for i,mv in enumerate(masked_vertsb)]
    # get rid of center exclusion
    areas[0] = areas[0] - annulus_areas[0]
    frac_areas = np.array(areas) / annulus_areas[1:]
    return np.array(areas), frac_areas
Example #25
0
def gen_spectral_grid_from_kurucz(outfile, osl, oiso, Z=0.02):
    """ Reinterpolate a given stellar spectral library on to an Isochrone grid
    INPUTS:
        outfile     str         fits file to export to
        osl     stellib.stellib     a stellar library
        oiso        isochrone.Isochrone an isochrone library
        Z       float           metallicity to use

    OUTPUTS:
        None

        only write into outfile
    """
    assert(grid.isNestedInstance(osl, stellib.Stellib) )
    assert(grid.isNestedInstance(oiso, isochrone.Isochrone) )
    specs = np.empty( (oiso.data.nrows + 1, len(osl.wavelength)), dtype=float )
    specs[-1] = osl.wavelength[:]

    def get_radius(logl, logt):
        #get the radius of a star given its luminosity and temperature
        #(assuming a black body)
        lsun = 3.839e26  # W
        sig  = 5.67037321 * 1e-8   # W m**-2 K**-4
        return np.sqrt( (10 ** logl) * lsun / (4.0 * np.pi * sig * ((10 ** logt) ** 4)) )

    bounds = get_stellib_boundaries(osl, dlogT=0.1, dlogg=0.3, closed=True)

    progress = 0
    data = np.array([oiso.data['logg'], oiso.data['logT']]).T
    bound_cond = points_inside_poly(data, bounds)
    del data
    radii = get_radius(oiso.data['logL'], oiso.data['logT'])
    weights = 4. * np.pi * (radii * 1e2) ** 2  # denorm models are in cm**-2 (4 * pi * rad)
    with timeit('interpolation'):
        for k in range(oiso.data.nrows):
            p = int(100 * (k + 1) / oiso.data.nrows)
            if (progress < p):
                progress = p
                sys.stdout.write("progress... %d / 100\r" % progress )
            if bound_cond[k] is True:
                r = np.array( osl.interp(oiso.data['logT'][k], oiso.data['logg'][k], Z, 0.) ).T
                specs[k, :] = osl.genSpectrum(r) * weights[k]
            else:
                specs[k, :] = np.zeros(len(osl.wavelength), dtype=float )
        sys.stdout.write("progress... %d / 100" % progress )

    specs = specs[bound_cond, :]

    pyfits.writeto(outfile, specs)

    #copy pars
    data = {}
    for k in oiso.data.keys():
        data[k] = oiso.data[k][bound_cond]
    data['radius'] = radii[bound_cond] / 6.955e8  # Rsun
    pars  = Table(data, name='Reinterpolated stellib grid')
    pars.header['stellib'] = osl.source
    pars.header['isoch'] = oiso.source

    pars.write(outfile, append=True)
Example #26
0
def poly_over_under(ra,dec,patch_left,patch_right):
    '''
    Short cut to Polygon.Polygon
    (p and q are polygons)
    p & q: intersection: a polygon with the area that is covered by both p and q
    p | q: union: a polygon containing the area that is covered by p or q or both
    p - q: difference: a polygon with the area of p that is not covered by q
    p + q: sum: same as union
    p ^ q: xor: a polygon with the area that is covered by exactly one of p and q

    len(p):
    p[i]:

    number of contours
    contour with index i, the same as p.contour(i), slicing is not yet supported
    '''
    # returns indices of ra, dec that are not in the overlap region 
    # of the two patches.
    # use ra,dec.
    lr,ld = mpl_patch_XY2radec(patch_left)
    rr,rd = mpl_patch_XY2radec(patch_right)
    # Polygon needs tuples...
    left = Polygon.Polygon(ndarray2tuple(np.column_stack((lr,ld))))
    right = Polygon.Polygon(ndarray2tuple(np.column_stack((rr,rd))))
    # p & q: intersection: a polygon with the area that is covered by both p and q
    overlap = right & left
    # vertices of overlapped region
    if len(overlap[0]) > 0:
        verts = np.transpose(np.array(overlap[0]))
        radec = np.column_stack((ra,dec))
        mask = nxutils.points_inside_poly(radec, np.array(overlap[0]))
    # sloppy? flip T/F: subtract 1 from bool array and then get rid of neg sign
        not_overlapped = np.nonzero(abs(mask-1))[0]
    else: not_overlapped = []
    return not_overlapped
def points_in_polys(points, polys):
	# Function to quickly check stranding of many points
	insidePoly = np.array([False]*len(points))
	for poly in polys:
		# NB: use contains_points for matplotlib version >= 1.2.0
		insidePoly[nx.points_inside_poly(points, poly)] = True
	return insidePoly
Example #28
0
def points_in_polys(points, polys):
    # Function to quickly check stranding of many points
    insidePoly = np.array([False] * len(points))
    for poly in polys:
        # NB: use contains_points for matplotlib version >= 1.2.0
        insidePoly[nx.points_inside_poly(points, poly)] = True
    return insidePoly
Example #29
0
 def calculate_polygon_intersection (self, geometry, points):
     ''' Apply nxutils algorithm to determine point-in-polygon relationship. '''
     rings = geometry ['coordinates']
     ring_points = []
     for ring in rings:
         for point in ring:
             ring_points.append (list (point))
     numpy_geometry = numpy.array (ring_points)
     return nx.points_inside_poly (points, numpy_geometry)
Example #30
0
 def getROI(self, verts):
     ind = points_inside_poly(self.xys, verts)
     self.canvas.draw_idle()
     self.canvas.widgetlock.release(self.lasso)
     del self.lasso
     self.ROI = ind
     self.ROI = self.ROI.reshape((600,800), order='F')
     self.canvas.mpl_disconnect(self.cid)
     self.onDraw()
Example #31
0
def inpolygon(x,y,xp,yp):
  '''
  Points inside polygon test.

  Based on matplotlib nxutils for old matplotlib versions
  http://matplotlib.sourceforge.net/faq/howto_faq.html#test-whether-a-point-is-inside-a-polygon

  Can also use Path.contains_point, for recent versions, or
  the pnpoly extension - point in polyon test - by W R Franklin,
  http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
  '''

  try:
    from matplotlib.nxutils import pnpoly, points_inside_poly
    _use_mpl = 1
  except ImportError:
    from matplotlib.path import Path
    _use_mpl = 2
  except:
    import pnpoly
    _use_mpl = False

  shape=False
  try:
    if x.ndim>1:
      shape=x.shape
      x=x.flat
      y=y.flat
  except: pass

  if _use_mpl==1:
    verts=np.array(zip(xp,yp))
    if isiterable(x,y):
      points=np.array(zip(x,y))
      res=points_inside_poly(points,verts)
    else:
      res=pnpoly(x,y,verts)==1

  elif _use_mpl==2:
    verts=np.array(zip(xp,yp))
    p=Path(verts)
    if not isiterable(x,y): x,y,itr=[x],[y],0
    else: itr=1
    res=[p.contains_point((x[i],y[i]), radius=0.) for i in range(len(x))]
    res=np.asarray(res,'bool')
    if not itr: res=res[0]

  else:
    if not isiterable(x,y): x,y,itr=[x],[y],0
    else: itr=1
    res=np.zeros(len(x))
    res=[pnpoly.pnpoly(x[i],y[i],xp,yp,len(xp)) for i in range(len(x))]
    res=np.asarray(res)==1
    if not itr: res=res[0]

  if not shape is False: res.shape=shape
  return res
    def outer_loop(G, cycles):
        coms = array([c.com for c in cycles])

        for c in cycles:
            xyverts = zeros((c.coords.shape[0] + 1, c.coords.shape[1]))
            xyverts[:-1, :] = c.coords
            xyverts[-1, :] = c.coords[0, :]
            if nxutils.points_inside_poly(coms, xyverts).all():
                return c
Example #33
0
 def getROI(self, verts):
     ind = points_inside_poly(self.xys, verts)
     self.canvas.draw_idle()
     self.canvas.widgetlock.release(self.lasso)
     del self.lasso
     self.ROI = ind
     self.ROI = self.ROI.reshape((600, 800), order='F')
     self.canvas.mpl_disconnect(self.cid)
     self.onDraw()
Example #34
0
def makeExteriorPoint(node, adjNode, pc, tri, xRange, yRange):
    """
    :return: a tuple (xd,yd) of a point exterior to the bounding box, that
        defines a voronoi cell wall between `node` and `adjNode`.
    """
    # Get coordinates of the two points that define convex hull line seg
    p1 = (tri.x[node], tri.y[node])
    p2 = (tri.x[adjNode], tri.y[adjNode])
    # Get slope of that line
    m = (p2[1]-p1[1]) / (p2[0]-p1[0])
    # Get perpendicular slope; that of the voronoi cell edge
    mPerp = -1./m
    print "mPerp func %.2f" % mPerp
    
    ydf = lambda x: mPerp*(x - pc[0]) + pc[1]
    
    # Get the point pi where the voronoi cell line intersects the convex hull line
    xi = (pc[1]-p1[1] + m*p1[0] - mPerp*pc[0]) / (m - mPerp)
    yi = m * (xi - p1[0]) + p1[1]
    
    # Length of line perpendicular to convex hull line segment; defines where (xd,yd) is from (xc,yc)
    D = math.sqrt((xRange[1]-xRange[0])**2. + (yRange[1]-yRange[0])**2.)
    width = max(xRange)-min(xRange)
    
    pHull = []
    for ii in tri.hull:
        pHull.append((tri.x[ii],tri.y[ii]))
    if nxutils.points_inside_poly([pc], pHull)[0]:
        # the circumcenter is inside the convex hull
        inside = True
    else:
        # the circumcentre is outside the convex hull
        inside = False
    
    xdTest = min(xRange) - width
    ydTest = ydf(xdTest)
    testCellLine = (pc, (xdTest,ydTest))
    hullLine = (p1,p2)
    intersects = testLineSegIntersection(testCellLine, hullLine)
    if intersects and inside:
        # the line intersects the convex hull, as it should
        print "Intersects %s and inside %s" % (str(intersects), str(inside))
        xd = xdTest
        yd = ydTest
    else:
        # must use the opposite orientation
        if (intersects == False) & (inside == False):
            print "Intersects %s and inside %s -- not flipping" % (str(intersects), str(inside))
            xd = xdTest
            yd = ydTest
        else:
            print "Intersects %s and inside %s -- flipping" % (str(intersects), str(inside))
            xd = max(xRange) + width
            yd = ydf(xd)
    
    return (xd, yd)
 def on_land_polycheck(self, x, y):
     points = np.c_[x, y]
     land = np.zeros_like(x, dtype=np.bool)
     if has_nxutils is True:
         for polygon in self.polygons:
             land[nx.points_inside_poly(points, polygon)] = True
     else:
         for polygon in self.polygons:
             land += polygon.contains_points(points)
     return land
Example #36
0
 def filter(self):
     """ Data flow into here """
     while True:
         a = (yield)
         # good = np.ones(a.shape, dtype=bool)
         
         coord0 = self.coord_names[0]
         coord1 = self.coord_names[1]
         in_poly_mask = points_inside_poly(zip(a[coord0], a[coord1]), self.verts) == 1                    
         self.target.send(a[in_poly_mask])
Example #37
0
File: mmsca.py Project: oz123/mmspy
 def getmask(self, vertices):
     """
     getMask takes a list of points, and a list of vertices, 
     representing the polygon boundaries, and returns a Boolean 
     array with True for points inside the polygon and False for 
     points outside the polygon.
     !make this function use multithreading so we can go
     a bit faster !
     """
     self.mask = nxutils.points_inside_poly(self.rasterpoints, vertices)
 def on_land_polycheck(self, x, y):
     points = np.c_[x, y]
     land = np.zeros_like(x, dtype=np.bool)
     if has_nxutils is True:
         for polygon in self.polygons:
             land[nx.points_inside_poly(points, polygon)] = True
     else:
         for polygon in self.polygons:
             land = land + polygon.contains_points(points)
     return land
Example #39
0
def get_contour_mask(doselut, dosegridpoints, contour):
    """Get the mask for the contour with respect to the dose plane."""

    if matplotlib.__version__ > '1.2':
        grid = mpl_Path(contour).contains_points(dosegridpoints)
    else:
        grid = nx.points_inside_poly(dosegridpoints, contour)
    grid = grid.reshape((len(doselut[1]), len(doselut[0])))

    return grid
Example #40
0
def dpoly(p,pv):
    """Signed distance function for polygon with vertices pv.

    Usually pv should also be provided as fixed points in distmesh2d.

    pv should be provided as a list of coordinates [(x0,y0), (x1,y1), ...]
    or an array of shape (nv, 2).
    """
    from matplotlib.nxutils import points_inside_poly
    return (-1)**points_inside_poly(p, pv) * dsegment(p, pv).min(1)
Example #41
0
def points_to_mask(hull_ijs, nx, ny):
    # This seems inefficient, but actually timed out at 0.3ms
    # very reasonable.
    # Create vertex coordinates for each grid cell...
    # (<0,0> is at the top left of the grid in this system)
    x, y = np.meshgrid(np.arange(nx), np.arange(ny))
    x, y = x.flatten(), y.flatten()
    points = np.vstack((x, y)).T
    mask = points_inside_poly(points, hull_ijs)
    return mask.reshape((ny, nx))
Example #42
0
def polygonsOverlap(poly1, poly2):
    """Determine if two polygons intersect; can fail for pointy polygons.

    Accepts two polygons, as lists of vertices (x,y) pairs. If given `ShapeStim`-based
    instances, will use rendered (vertices + pos) as the polygon.

    Checks if any vertex of one polygon is inside the other polygon; will fail in
    some cases, especially for pointy polygons. "crossed-swords" configurations
    overlap but may not be detected by the algorithm.

    Used by :class:`~psychopy.visual.ShapeStim` `.overlaps()`
    """
    try:  # do this using try:...except rather than hasattr() for speed
        poly1 = poly1.verticesPix  # we want to access this only once
    except:
        pass
    try:  # do this using try:...except rather than hasattr() for speed
        poly2 = poly2.verticesPix  # we want to access this only once
    except:
        pass
    # faster if have matplotlib tools:
    if haveMatplotlib:
        if matplotlib.__version__ > "1.2":
            if any(mpl_Path(poly1).contains_points(poly2)):
                return True
            return any(mpl_Path(poly2).contains_points(poly1))
        else:
            try:  # deprecated in matplotlib 1.2
                if any(nxutils.points_inside_poly(poly1, poly2)):
                    return True
                return any(nxutils.points_inside_poly(poly2, poly1))
            except:
                pass

    # fall through to pure python:
    for p1 in poly1:
        if pointInPolygon(p1[0], p1[1], poly2):
            return True
    for p2 in poly2:
        if pointInPolygon(p2[0], p2[1], poly1):
            return True
    return False
Example #43
0
def polygonsOverlap(poly1, poly2):
    """Determine if two polygons intersect; can fail for pointy polygons.

    Accepts two polygons, as lists of vertices (x,y) pairs. If given `ShapeStim`-based
    instances, will use rendered (vertices + pos) as the polygon.

    Checks if any vertex of one polygon is inside the other polygon; will fail in
    some cases, especially for pointy polygons. "crossed-swords" configurations
    overlap but may not be detected by the algorithm.

    Used by :class:`~psychopy.visual.ShapeStim` `.overlaps()`
    """
    try:  #do this using try:...except rather than hasattr() for speed
        poly1 = poly1.verticesPix  #we want to access this only once
    except:
        pass
    try:  #do this using try:...except rather than hasattr() for speed
        poly2 = poly2.verticesPix  #we want to access this only once
    except:
        pass
    # faster if have matplotlib tools:
    if haveMatplotlib:
        if matplotlib.__version__ > '1.2':
            if any(mpl_Path(poly1).contains_points(poly2)):
                return True
            return any(mpl_Path(poly2).contains_points(poly1))
        else:
            try:  # deprecated in matplotlib 1.2
                if any(nxutils.points_inside_poly(poly1, poly2)):
                    return True
                return any(nxutils.points_inside_poly(poly2, poly1))
            except:
                pass

    # fall through to pure python:
    for p1 in poly1:
        if pointInPolygon(p1[0], p1[1], poly2):
            return True
    for p2 in poly2:
        if pointInPolygon(p2[0], p2[1], poly1):
            return True
    return False
Example #44
0
    def maskFromPoints(self, vertex_list, size_x, size_y):
        # Create vertex coordinates for each grid cell...
        # (<0,0> is at the top left of the grid in this system)
        x, y = np.meshgrid(np.arange(size_x), np.arange(size_y))
        x, y = x.flatten(), y.flatten()
        point_space = np.vstack((x, y)).T

        poly_mask = nx.points_inside_poly(point_space, vertex_list)
        poly_mask = poly_mask.reshape(size_x, size_y)

        return poly_mask.T
Example #45
0
    def callback(self, verts):
        ind = nonzero(points_inside_poly(self.xys, verts))[0]
        for i in range(self.Nxy):
            if i in ind:
                self.facecolors[i] = Datum.colorin
            else:
                self.facecolors[i] = Datum.colorout

        self.canvas.draw_idle()
        self.canvas.widgetlock.release(self.lasso)
        del self.lasso
Example #46
0
 def callback(self, verts):
     mask = points_inside_poly(self.xys, verts)
     ind = nonzero(mask)[0]
     self.canvas.draw_idle()
     self.canvas.widgetlock.release(self.lasso)
     self.canvas.mpl_disconnect(self.cid)        
     del self.lasso
     del self.xys
     self.verts = verts
     self.ind = ind
     self.mask = mask
Example #47
0
 def getmask(self, vertices):
     """
     getMask takes a list of points, and a list of vertices, 
     representing the polygon boundaries, and returns a Boolean 
     array with True for points inside the polygon and False for 
     points outside the polygon.
     !make this function use multithreading so we can go
     a bit faster !
     """
     self.mask = nxutils.points_inside_poly(self.rasterpoints, 
                 vertices)
Example #48
0
 def callback(self, verts):
     mask = points_inside_poly(self.xys, verts)
     ind = nonzero(mask)[0]
     self.canvas.draw_idle()
     self.canvas.widgetlock.release(self.lasso)
     self.canvas.mpl_disconnect(self.cid)
     del self.lasso
     del self.xys
     self.verts = verts
     self.ind = ind
     self.mask = mask
Example #49
0
def points_in_box(X,Y,box):
    """ Given a grid X,Y as given by meshgrid and a list of vertices
    of a rectangle (or any four sided polygon) return the grid points
    inside the box and the indices of these grid points. """
    xx = X.flatten()
    yy = Y.flatten()
    xypoints = [(xx[k],yy[k]) for k in range(len(xx))]
    xyverts = [(box[k,0],box[k,1]) for k in range(4)]
    inside = points_inside_poly(xypoints,xyverts)
    xyin = array(xypoints)[inside]
    inside.shape = X.shape
    return xyin,inside
Example #50
0
    def motionContour(self , event):
        if self._ind is None: return
        if event.inaxes is None: return
        if event.button != 1: return
        x,y = event.xdata, event.ydata

        self.poly.xy[self._ind] = x,y
        self.line.set_data(zip(*self.poly.xy))
        self.redraw()
        
        self.actualSelection = points_inside_poly(np.dot( self.data, self.projection ), self.poly.xy)
        self.selection_changed.emit()
Example #51
0
def points_in_box(X, Y, box):
    """ Given a grid X,Y as given by meshgrid and a list of vertices
    of a rectangle (or any four sided polygon) return the grid points
    inside the box and the indices of these grid points. """
    xx = X.flatten()
    yy = Y.flatten()
    xypoints = [(xx[k], yy[k]) for k in range(len(xx))]
    xyverts = [(box[k, 0], box[k, 1]) for k in range(4)]
    inside = points_inside_poly(xypoints, xyverts)
    xyin = array(xypoints)[inside]
    inside.shape = X.shape
    return xyin, inside
def extractSpeeds(objects, zone):
    speeds = {}
    objectsNotInZone = []
    import matplotlib.nxutils as nx        
    for o in objects:
        inPolygon = nx.points_inside_poly(o.getPositions().asArray().T, zone.T)
        if inPolygon.any():
            objspeeds = [o.getVelocityAt(i).norm2() for i in xrange(int(o.length()-1)) if inPolygon[i]]
            speeds[o.num] = np.mean(objspeeds) # km/h
        else:
            objectsNotInZone.append(o)
    return speeds.values(), speeds, objectsNotInZone
Example #53
0
def inside(x, y, u, v, verts=False):
    """
    returns the indices of u,v that are within the boundries of x,y.
    """
    if verts != True:
        verts = get_verts(x, y, nbinsx=60, nbinsy=60, smooth=1)
    else:
        verts = np.column_stack((x, y))
    points = np.column_stack((u, v))
    mask = nxutils.points_inside_poly(points, verts)
    ind = np.nonzero(mask)[0]
    return ind
Example #54
0
def inside(x,y,u,v,verts=False):
    """
    returns the indices of u,v that are within the boundries of x,y.
    """
    if verts != True:
        verts = get_verts(x,y,nbinsx=60,nbinsy=60,smooth=1)
    else:
        verts =  np.column_stack((x,y))
    points = np.column_stack((u,v))
    mask = nxutils.points_inside_poly(points, verts)
    ind = np.nonzero(mask)[0]
    return ind
def extractSpeeds(objects, zone):
    speeds = {}
    objectsNotInZone = []
    import matplotlib.nxutils as nx
    for o in objects:
        inPolygon = nx.points_inside_poly(o.getPositions().asArray().T, zone.T)
        if inPolygon.any():
            objspeeds = [o.getVelocityAt(i).norm2() for i in xrange(int(o.length() - 1)) if inPolygon[i]]
            speeds[o.num] = np.mean(objspeeds)  # km/h
        else:
            objectsNotInZone.append(o)
    return speeds.values(), speeds, objectsNotInZone
Example #56
0
def areaNeeded(lat, lon, bbox, polygon, corrx, corry):
    """checks if a source file is needed depending on the bounding box and
	the passed polygon.
	"""
    if polygon == None:
        return True, False
    minLat = lat + corry
    maxLat = minLat + 1
    minLon = lon + corrx
    maxLon = minLon + 1
    MinLon, MinLat, MaxLon, MaxLat = bbox
    MinLon += corrx
    MaxLon += corrx
    MinLat += corry
    MaxLat += corry
    print("checking if area {0:s} intersects with polygon ...".format(
        makeFileNamePrefix(lon, lat)),
          end=" ")
    if minLon == MinLon and minLat == MinLat and maxLon == MaxLon and maxLat == MaxLat:
        # the polygon is completely inside the bounding box
        print("yes")
        #writeTex(lon, lat, lon+1, lat+1, "green")
        return True, True
    # the area is not or completely inside one of the polygons passed to
    # <polygon>.  We just look if the corners are inside the polygons.
    points = []
    for lo in [minLon, maxLon]:
        for la in [minLat, maxLat]:
            points.append((lo, la))
    inside = numpy.zeros((1, 4))
    for p in polygon:
        if mplversion < "1.3.0":
            inside += points_inside_poly(points, p)
        else:
            inside += PolygonPath(p).contains_points(points)
    if numpy.all(inside):
        # area ist completely inside
        print("yes")
        #writeTex(lon, lat, lon+1, lat+1, "green")
        return True, False
    elif not numpy.any(inside):
        # area is completely outside
        print("no")
        #writeTex(lon, lat, lon+1, lat+1, "red")
        return False, False
    else:
        # This only happens it a polygon vertex is on the tile border.
        # Because in this case points_inside_poly() returns unpredictable
        # results, we better return True here.
        print("maybe")
        #writeTex(lon, lat, lon+1, lat+1, "pink")
        return True, True