How to use the shapely.geometry function in shapely

To help you get started, we’ve selected a few shapely examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ppintosilva / anprx / anprx / cameras.py View on Github external
log(("Dropping {} {} with no direction.")\
                 .format(count_na_direction, snames),
             level = lg.WARNING)

 if len(objects) == 0:
     log("No more {} to process..".format(snames), level = lg.WARNING)
     return pd.DataFrame(columns = objects.columns.values)

 # Project coordinates
 log("Projecting {} to utm and adding geometry column.".format(snames),
     level = lg.INFO)

 objects.reset_index(drop=True, inplace = True)

 points = gpd.GeoSeries(
     [ shp.geometry.Point(x,y) for x, y in zip(
         objects['lon'],
         objects['lat'])
     ])

 geodf = gpd.GeoDataFrame(index    = objects.index,
                          geometry = points)
 geodf.crs = 'epsg:4326'

 avg_longitude = geodf['geometry'].unary_union.centroid.x
 utm_zone = int(math.floor((avg_longitude + 180) / 6.) + 1)
 utm_crs["zone"] = utm_zone

 proj_objects = geodf.to_crs(utm_crs)
 objects = proj_objects.join(objects, how = 'inner')

 return objects
github OGGM / oggm / oggm / sandbox / rgi_tools / tools.py View on Github external
for i, neighbor in gdfs.iterrows():

            if neighbor.RGIId in out.RGIId_1 or neighbor.RGIId in out.RGIId_2:
                continue

            # Exterior only
            # Buffer is needed for numerical reasons
            neighbor_poly = neighbor.geometry.exterior.buffer(0.0001)

            # Go
            try:
                mult_intersect = major_poly.intersection(neighbor_poly)
            except:
                continue

            if isinstance(mult_intersect, shpg.Point):
                continue
            if isinstance(mult_intersect, shpg.linestring.LineString):
                mult_intersect = [mult_intersect]
            if len(mult_intersect) == 0:
                continue
            mult_intersect = [m for m in mult_intersect if
                              not isinstance(m, shpg.Point)]
            if len(mult_intersect) == 0:
                continue
            mult_intersect = linemerge(mult_intersect)
            if isinstance(mult_intersect, shpg.linestring.LineString):
                mult_intersect = [mult_intersect]
            for line in mult_intersect:
                assert isinstance(line, shpg.linestring.LineString)
                line = gpd.GeoDataFrame([[major.RGIId, neighbor.RGIId, line]],
                                        columns=out_cols)
github boland1992 / SeisSuite / ambient / sort_later / space_contour_stationary.py View on Github external
def shape_(input_shape):
    with fiona.open(input_shape) as fiona_collection:
        # In this case, we'll assume the shapefile only has one record/layer 
        shapefile_record = fiona_collection.next()
        # Use Shapely to create the polygon
        return geometry.asShape( shapefile_record['geometry'] )
github TravelModellingGroup / TMGToolbox / TMGToolbox / src / common / geometry.py View on Github external
self._atts = {}
        root.__init__(coordinates)

class Polygon(_geo.Polygon, _attachable):
    def __init__(self, shell=None, holes=None):
        root = super(Polygon, self)
        self._atts = {}
        root.__init__(shell, holes)

class MultiPoint(_geo.MultiPoint, _attachable):
    def __init__(self, points=None):
        root = super(MultiPoint, self)
        self._atts = {}
        root.__init__(points)

class MultiLineString(_geo.MultiLineString, _attachable):
    def __init__(self, lines=None):
        root = super(MultiLineString, self)
        self._atts = {}
        root.__init__(lines)

class MultiPolygon(_geo.MultiPolygon, _attachable):
    def __init__(self, polygons=None, context_type='polygons'):
        root = super(MultiPolygon, self)
        self._atts = {}
        root.__init__(polygons, context_type)

class GeometryCollection(_geo.GeometryCollection, _attachable):
    def __init__(self):
        root = super(GeometryCollection, self)
        self._atts = {}
        root.__init__()
github openaddresses / population / code / map-population-density.py View on Github external
def coverage_feature(poly, area, count, population, density):
    ''' Return GeoJSON feature for coverage tuple values.
    '''
    properties = {'address count': count, 'population': population, 'density': density, 'area': area}
    feature = dict(type='Feature', properties=properties)
    feature.update(geometry=shapely.geometry.mapping(poly))
    return feature
github kapadia / usgs / usgs / soap.py View on Github external
create_dataset_element(el, dataset)
    create_node_element(el, node)
    
    # Latitude and longitude take precedence over ll and ur
    if lat and lng:
        
        try:
            import pyproj
            from shapely import geometry
        except ImportError:
            raise USGSDependencyRequired("Shapely and PyProj are required for search.")
        
        prj = pyproj.Proj(proj='aeqd', lat_0=lat, lon_0=lng)
        half_distance = 0.5 * distance
        box = geometry.box(-half_distance, -half_distance, half_distance, half_distance)
        
        lngs, lats = prj(*box.exterior.xy, inverse=True)
        
        ll = { "longitude": min(*lngs), "latitude": min(*lats) }
        ur = { "longitude": max(*lngs), "latitude": max(*lats) }
    
    if ll and ur:
        
        create_service_class_coordinate(el, "lowerLeft", latitude=ll["latitude"], longitude=ll["longitude"])
        create_service_class_coordinate(el, "upperRight", latitude=ur["latitude"], longitude=ur["longitude"])
        
    if start_date:
        
        start_date_el = SubElement(el, "startDate")
        start_date_el.set("xsi:type", "xsd:string")
        start_date_el.text = start_date
github sambler / myblendercontrib / blendercam / ops.py View on Github external
if self.invert:  # and ci>0:
                                sign *= -1
                            if (sign < 0 and a < -self.threshold) or (sign > 0 and a > self.threshold):
                                p = Vector((co[0], co[1]))
                                v1.normalize()
                                v2.normalize()
                                v = v1 - v2
                                v.normalize()
                                p = p - v * diameter / 2
                                if abs(a) < math.pi / 2:
                                    shape = utils.Circle(diameter / 2, 64)
                                    shape = shapely.affinity.translate(shape, p.x, p.y)
                                else:
                                    l = math.tan(a / 2) * diameter / 2
                                    p1 = p - sign * v * l
                                    l = shapely.geometry.LineString((p, p1))
                                    shape = l.buffer(diameter / 2, resolution=64)

                                if sign > 0:
                                    negative_overcuts.append(shape)
                                else:
                                    positive_overcuts.append(shape)

                            print(a)

        # for c in s.boundary:
        negative_overcuts = shapely.ops.unary_union(negative_overcuts)
        positive_overcuts = shapely.ops.unary_union(positive_overcuts)
        # shapes.extend(overcuts)
        fs = shapely.ops.unary_union(shapes)
        fs = fs.union(positive_overcuts)
        fs = fs.difference(negative_overcuts)
github HelgeGehring / gdshelpers / gdshelpers / parts / splitter.py View on Github external
if self._implement_cadence_bug:
            v1 = Splitter._connect_two_points([self._wl / 2, 0], [self._sep / 2 + self._wr / 2, self._total_length],
                                              self._n_points)
            if self._wl < 2 * self._wr:
                v2 = (v1 - [self._wr, 0])[::-1, :]
            else:
                # NOTE: In this obscure case, the generated splitter looks different than the cadence version.
                #       But probably it is better, since the paths are all smooth and curvy instead of just painting a
                #       triangle.
                v2 = Splitter._connect_two_points([-self._wr / 2, 0],
                                                  [self._sep / 2 - self._wr / 2, self._total_length],
                                                  self._n_points)[::-1, :]

            v = np.vstack((v1, v2))
            polygon1 = shapely.geometry.Polygon(v)
            polygon1 = polygon1.difference(shapely.geometry.box(-self._sep / 2, 0, 0, self._total_length))
            polygon2 = shapely.affinity.scale(polygon1, xfact=-1, origin=[0, 0, 0])

            polygon = polygon1.union(polygon2)

            polygon = shapely.affinity.rotate(polygon, -np.pi / 2 + self._angle, origin=[0, 0], use_radians=True)
            polygon = shapely.affinity.translate(polygon, self._origin[0], self._origin[1])

            # Keep track of the ports
            port_points = shapely.geometry.MultiPoint([(0, 0),
                                                       (-self._sep / 2, self._total_length),
                                                       (+self._sep / 2, self._total_length)])
            port_points = shapely.affinity.rotate(port_points, -np.pi / 2 + self._angle, origin=[0, 0],
                                                  use_radians=True)
            port_points = shapely.affinity.translate(port_points, self._origin[0], self._origin[1])

            self._polygon = polygon
github popupcad / popupcad / popupcad / algorithms / csg_shapely.py View on Github external
def get_shapely_vertices(entity,scaling = 1.0):
    import shapely.geometry as sg
    import numpy
    
    if isinstance(entity,sg.Polygon):
        exterior = (numpy.array([coord for coord in entity.exterior.coords])*scaling).tolist()
        interiors = [(numpy.array([coord for coord in interior.coords])*scaling).tolist()
                     for interior in entity.interiors]

    elif isinstance(entity,sg.LineString) or isinstance(entity,sg.Point):
        exterior = (numpy.array([coord for coord in entity.coords])*scaling).tolist()
        interiors = []
    else:
        raise GeometryNotHandled()

    return exterior, interiors