Constructs a numpy-compatible polygon from a page representation.
434255
def polygon_from_points(points):
    
    polygon = []
    for pair in points.split(" "):
        x_y = pair.split(",")
        polygon.append([float(x_y[0]), float(x_y[1])])
    return polygon
849359
def polygonize_full
      cuts = FFI::MemoryPointer.new(:pointer)
      dangles = FFI::MemoryPointer.new(:pointer)
      invalid_rings = FFI::MemoryPointer.new(:pointer)

      rings = cast_geometry_ptr(FFIGeos.GEOSPolygonize_full_r(Geos.current_handle_pointer, ptr, cuts, dangles, invalid_rings), srid_copy: srid)

      cuts = cast_geometry_ptr(cuts.read_pointer, srid_copy: srid)
      dangles = cast_geometry_ptr(dangles.read_pointer, srid_copy: srid)
      invalid_rings = cast_geometry_ptr(invalid_rings.read_pointer, srid_copy: srid)

      {
        rings: rings.to_a,
        cuts: cuts.to_a,
        dangles: dangles.to_a,
        invalid_rings: invalid_rings.to_a
      }
    end
1134030
def get_blocks_3d(A, blocksizes, pagesizes=None):
    
    assert (A.shape[0]==A.shape[1]) and len(A.shape)==3, "can't blockify this non-square matrix, may need to use 2d version"
    N = np.sum(blocksizes)
    assert A.shape[0] == N, "bad blocksizes"
    num_blocks = len(blocksizes)
    if pagesizes == None:
        #Assume each page of A should be its own dimension
        pagesizes = range(A.shape[2])#[0]*A.shape[2]
    num_pages = len(pagesizes)
    B = np.empty(shape=(num_blocks, num_blocks, num_pages), dtype=np.object)
    count_k = 0
    #for Bk, k in enumerate(pagesizes):
    for Bk in pagesizes:
        count_i = 0
        for Bi, i in enumerate(blocksizes):
            count_j = 0
            for Bj, j in enumerate(blocksizes):
                #We want to have it count_k:count_k + k but its annoying as it makes a NxNx1 array is page sizes are set to 1
                B[Bi, Bj, Bk] = A[count_i:count_i + i, count_j:count_j + j, Bk]
                count_j += j
            count_i += i
        #count_k += k
    return B
23500
private Polygon createPolygon(double[][][] coordinates, CrsId crsId) {
        LinearRing[] rings = new LinearRing[coordinates.length];
        for (int i = 0; i < coordinates.length; i++) {
            rings[i] = new LinearRing(createPointSequence(coordinates[i], crsId));
        }
        return new Polygon(rings);
    }
1280531
def segments_from_numpy(segments):
    """"""
    segments = segments if SEGMENTS_DIRECTION == 0 else segments.tranpose()
    segments = [map(int, s) for s in segments]
    return segments
235177
def polygon_load(filename):
    ''''''
    ret = []
    f = open(filename)
    for line in f:
        if line.startswith('#'):
            continue
        line = line.strip()
        if not line:
            continue
        a = line.split()
        if len(a) != 2:
            raise RuntimeError("invalid polygon line: %s" % line)
        ret.append((float(a[0]), float(a[1])))
    f.close()
    return ret
715864
def from_numpy(cls, 
      arr, vol_path='file:///tmp/image/'+generate_random_string(),
      resolution=(4,4,40), voxel_offset=(0,0,0), 
      chunk_size=(128,128,64), layer_type=None, max_mip=0,
      encoding='raw', compress=None
    ):
    
    if not layer_type:
      if arr.dtype in (np.bool, np.uint32, np.uint64, np.uint16):
        layer_type = 'segmentation'
      elif np.issubdtype(arr.dtype, np.integer) \
                        or np.issubdtype(arr.dtype, np.floating):
        layer_type = 'image'
      else:
        raise NotImplementedError

    if arr.ndim == 3:
      num_channels = 1
    elif arr.ndim == 4:
      num_channels = arr.shape[-1]
    else:
      raise NotImplementedError

    info = cls.create_new_info(num_channels, layer_type, arr.dtype.name, encoding, resolution, 
                               voxel_offset, arr.shape[:3], chunk_size=chunk_size, max_mip=max_mip)
    vol = CloudVolume(vol_path, info=info, bounded=True, compress=compress) 
    # save the info file
    vol.commit_info()
    vol.provenance.processing.append({
      'method': 'from_numpy',
      'date': strftime('%Y-%m-%d %H:%M %Z')
    })
    vol.commit_provenance()
    # save the numpy array
    vol[:,:,:] = arr
    return vol
1265398
def make_2d(array, verbose=True):
    
    array = np.asarray(array)
    if array.ndim < 2:
        msg = 'Expected 2D input data array, but found {}D. '\
              'Expanding to 2D.'.format(array.ndim)
        if verbose:
            warnings.warn(msg)
        array = np.atleast_1d(array)[:,None]
    return array
1146484
def _path_polygon(self, points):
        ""
        (xmin, ymin, xmax, ymax) = _compute_bounding_box(points)
        if invisible_p(xmax, ymax):
            return
        self.setbb(xmin, ymin)
        self.setbb(xmax, ymax)

        self.newpath()
        self.moveto(xscale(points[0][0]), yscale(points[0][1]))
        for point in points[1:]:
            self.lineto(xscale(point[0]), yscale(point[1]))
        self.closepath()
480982
def raster_to_shape(raster):
    """"""
    left = raster.bounds.left
    right = raster.bounds.right
    top = raster.bounds.top
    bottom = raster.bounds.bottom

    top_left = (left, top)
    top_right = (right, top)
    bottom_left = (left, bottom)
    bottom_right = (right, bottom)

    return Polygon((
        top_left, top_right, bottom_right, bottom_left, top_left,
    ))
1252277
def ds_geom(ds, t_srs=None):
    
    gt = ds.GetGeoTransform()
    ds_srs = get_ds_srs(ds)
    if t_srs is None:
        t_srs = ds_srs
    ns = ds.RasterXSize
    nl = ds.RasterYSize
    x = np.array([0, ns, ns, 0, 0], dtype=float)
    y = np.array([0, 0, nl, nl, 0], dtype=float)
    #Note: pixelToMap adds 0.5 to input coords, need to account for this here
    x -= 0.5
    y -= 0.5
    mx, my = pixelToMap(x, y, gt)
    geom_wkt = 'POLYGON(({0}))'.format(', '.join(['{0} {1}'.format(*a) for a in zip(mx,my)]))
    geom = ogr.CreateGeometryFromWkt(geom_wkt)
    geom.AssignSpatialReference(ds_srs)
    if not ds_srs.IsSame(t_srs):
        geom_transform(geom, t_srs)
    return geom
255794
function polygon( $p, $np, $f = 0 )
    {
        $this->objects[$this->currentContents]['c'].= "\n";
        $this->objects[$this->currentContents]['c'].= sprintf('%.3F',$p[0]).' '.sprintf('%.3F',$p[1]).' m ';
        for ( $i = 2; $i < $np*2; $i = $i + 2 )
        {
            $this->objects[$this->currentContents]['c'].= sprintf('%.3F',$p[$i]).' '.sprintf('%.3F',$p[$i+1]).' l ';
        }
        if ( $f == 1 )
        {
            $this->objects[$this->currentContents]['c'].= ' f';
        }
        else
        {
            $this->objects[$this->currentContents]['c'].= ' S';
        }
    }
222787
def to_python(self, value):
        

        if not value or isinstance(value, BaseGeometry):
            return value

        geometry_type = value['type']
        geometry = value['geometry']

        try:
            if geometry_type == 'esriGeometryPoint':
                if 'x' in geometry:
                    data = json.loads(geometry)
                    x, y = data['x'], data['y']
                else:
                    x, y = [float(val) for val in geometry.split(',')]
                return Point(x, y)

            elif geometry_type == 'esriGeometryMultipoint':
                data = json.loads(geometry)
                return MultiPoint([(p['0'], p['1']) for p in data['points']])

            elif geometry_type == 'esriGeometryPolyline':
                data = json.loads(geometry)
                return MultiLineString([((l[0][0], l[0][1]), (l[1][0], l[1][1])) for l in data['paths']])

            elif geometry_type == 'esriGeometryPolygon':
                data = json.loads(geometry)
                rings = [LinearRing([(p[0], p[1]) for p in r]) for r in data['rings']]
                return Polygon([r for r in rings if not r.is_ccw], interiors=[r for r in rings if r.is_ccw])

            elif geometry_type == 'esriGeometryEnvelope':
                if 'xmin' in geometry:
                    data = json.loads(geometry)
                    xmin, ymin, xmax, ymax = [data[k] for k in ('xmin', 'ymin', 'xmax', 'ymax')]
                else:
                    xmin, ymin, xmax, ymax = [float(val) for val in geometry.split(',')]
                return MultiPoint([(xmin, ymin), (xmax, ymax)]).envelope

            else:
                raise ValueError
        except ValueError:
            raise ValidationError('Invalid geometry')
190512
def _in_polygon(points, polygon):
    """"""
    from matplotlib.path import Path
    points = _as_array(points)
    polygon = _as_array(polygon)
    assert points.ndim == 2
    assert polygon.ndim == 2
    if len(polygon):
        polygon = np.vstack((polygon, polygon[0]))
    path = Path(polygon, closed=True)
    return path.contains_points(points)
116989
def bounding_polygon(self):
        
        lon_left, lat_bottom, lon_right, lat_top = Tile.tile_coords_to_bbox(self.x, self.y, self.zoom)
        print(lon_left, lat_bottom, lon_right, lat_top)
        return Polygon([[[lon_left, lat_top],
                       [lon_right, lat_top],
                       [lon_right, lat_bottom],
                       [lon_left, lat_bottom],
                       [lon_left, lat_top]]])
1024457
def mesh(faces, coordinates, meta_data=None, properties=None):
    '''
    
    '''
    return Mesh(faces, coordinates, meta_data=meta_data, properties=properties)
653841
def create_actor_polygon(pts, color, **kwargs):
    
    # Keyword arguments
    array_name = kwargs.get('name', "")
    array_index = kwargs.get('index', 0)
    line_width = kwargs.get('size', 1.0)

    # Create points
    points = vtk.vtkPoints()
    points.SetData(pts)

    # Number of points
    num_points = points.GetNumberOfPoints()

    # Create lines
    cells = vtk.vtkCellArray()
    for i in range(num_points - 1):
        line = vtk.vtkLine()
        line.GetPointIds().SetId(0, i)
        line.GetPointIds().SetId(1, i + 1)
        cells.InsertNextCell(line)

    # Create a PolyData object and add points & lines
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetLines(cells)

    # Map poly data to the graphics primitives
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputDataObject(polydata)
    mapper.SetArrayName(array_name)
    mapper.SetArrayId(array_index)

    # Create an actor and set its properties
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(*color)
    actor.GetProperty().SetLineWidth(line_width)

    # Return the actor
    return actor