Beispiel #1
0
    def verify_geom(self, geom, model_field):
        """
        Verifies the geometry -- will construct and return a GeometryCollection
        if necessary (for example if the model field is MultiPolygonField while
        the mapped shapefile only contains Polygons).
        """
        # Downgrade a 3D geom to a 2D one, if necessary.
        if self.coord_dim != geom.coord_dim:
            geom.coord_dim = self.coord_dim

        if self.make_multi(geom.geom_type, model_field):
            # Constructing a multi-geometry type to contain the single geometry
            multi_type = self.MULTI_TYPES[geom.geom_type.num]
            g = OGRGeometry(multi_type)
            g.add(geom)
        else:
            g = geom

        # Transforming the geometry with our Coordinate Transformation object,
        # but only if the class variable `transform` is set w/a CoordTransform
        # object.
        if self.transform:
            g.transform(self.transform)

        # Returning the WKT of the geometry.
        return g.wkt
Beispiel #2
0
 def test05_multilinestring(self):
     "Testing MultiLineString objects."
     prev = OGRGeometry('POINT(0 0)')
     for mls in self.geometries.multilinestrings:
         mlinestr = OGRGeometry(mls.wkt)
         self.assertEqual(5, mlinestr.geom_type)
         self.assertEqual('MULTILINESTRING', mlinestr.geom_name)
         self.assertEqual(mls.n_p, mlinestr.point_count)
         self.assertEqual(mls.coords, mlinestr.tuple)
         self.assertEqual(True, mlinestr == OGRGeometry(mls.wkt))
         self.assertEqual(True, mlinestr != prev)
         prev = mlinestr
         for ls in mlinestr:
             self.assertEqual(2, ls.geom_type)
             self.assertEqual('LINESTRING', ls.geom_name)
         self.assertRaises(OGRIndexError, mlinestr.__getitem__,
                           len(mlinestr))
Beispiel #3
0
 def test_multipolygons(self):
     "Testing MultiPolygon objects."
     OGRGeometry('POINT(0 0)')
     for mp in self.geometries.multipolygons:
         mpoly = OGRGeometry(mp.wkt)
         self.assertEqual(6, mpoly.geom_type)
         self.assertEqual('MULTIPOLYGON', mpoly.geom_name)
         if mp.valid:
             self.assertEqual(mp.n_p, mpoly.point_count)
             self.assertEqual(mp.num_geom, len(mpoly))
             msg = 'Index out of range when accessing geometry in a collection: %s.'
             with self.assertRaisesMessage(IndexError, msg % len(mpoly)):
                 mpoly.__getitem__(len(mpoly))
             for p in mpoly:
                 self.assertEqual('POLYGON', p.geom_name)
                 self.assertEqual(3, p.geom_type)
         self.assertEqual(mpoly.wkt, OGRGeometry(mp.wkt).wkt)
Beispiel #4
0
 def test17_pickle(self):
     "Testing pickle support."
     import cPickle
     g1 = OGRGeometry('LINESTRING(1 1 1,2 2 2,3 3 3)', 'WGS84')
     g2 = cPickle.loads(cPickle.dumps(g1))
     self.assertEqual(g1, g2)
     self.assertEqual(4326, g2.srs.srid)
     self.assertEqual(g1.srs.wkt, g2.srs.wkt)
Beispiel #5
0
 def test_from_gml(self):
     self.assertEqual(
         OGRGeometry('POINT(0 0)'),
         OGRGeometry.from_gml(
             '<gml:Point gml:id="p21" srsName="http://www.opengis.net/def/crs/EPSG/0/4326">'
             '    <gml:pos srsDimension="2">0 0</gml:pos>'
             '</gml:Point>'),
     )
Beispiel #6
0
 def polymask(self,threshold):
     get_pts = self.get_pts
     sims = self.simplifiers
     list_of_pts = [get_pts(sim,threshold) for sim in sims]
     if self.return_OGR:
       return OGRGeometry(self.poly2wkt(list_of_pts),srs=self.geom_srs)
     else:
       return [get_pts(sim,threshold) for sim in sims]
Beispiel #7
0
 def set_simple_linestrings(self, tolerance=500):
     """
     Simplifies the source linestrings so they don't use so many points.
     
     Provide a tolerance score the indicates how sharply the
     the lines should be redrawn.
     
     Returns True if successful.
     """
     # Get the list of SRIDs we need to update
     srid_list = self.get_srid_list()
     
     # Loop through each
     for srid in srid_list:
         
         # Fetch the source polygon
         source_field_name = 'linestring_%s' % str(srid)
         source = getattr(self, source_field_name)
         
         # Fetch the target polygon where the result will be saved
         target_field_name = 'simple_%s' % source_field_name
         
         # If there's nothing to transform, drop out now.
         if not source:
             setattr(self, target_field_name, None)
             continue
         
         if srid != 900913:
             # Transform the source out of lng/lat before the simplification
             copy = source.transform(900913, clone=True)
         else:
             copy = deepcopy(source)
         
         # Simplify the source
         simple = copy.simplify(tolerance, True)
         
         # If the result is a polygon ...
         if simple.geom_type == 'LineString':
             # Create a new Multipolygon shell
             ml = OGRGeometry(OGRGeomType('MultiLineString'))
             # Transform the new poly back to its SRID
             simple.transform(srid)
             # Stuff it in the shell
             ml.add(simple.wkt)
             # Grab the WKT
             target = ml.wkt
         
         # If it's not a polygon...
         else:
             # It should be ready to go, so transform
             simple.transform(srid)
             # And grab the WKT
             target = simple.wkt
         
         # Stuff the WKT into the field
         setattr(self, target_field_name, target)
     return True
Beispiel #8
0
 def test_multilinestring(self):
     "Testing MultiLineString objects."
     prev = OGRGeometry('POINT(0 0)')
     for mls in self.geometries.multilinestrings:
         mlinestr = OGRGeometry(mls.wkt)
         self.assertEqual(5, mlinestr.geom_type)
         self.assertEqual('MULTILINESTRING', mlinestr.geom_name)
         self.assertEqual(mls.n_p, mlinestr.point_count)
         self.assertEqual(mls.coords, mlinestr.tuple)
         self.assertEqual(mlinestr, OGRGeometry(mls.wkt))
         self.assertNotEqual(mlinestr, prev)
         prev = mlinestr
         for ls in mlinestr:
             self.assertEqual(2, ls.geom_type)
             self.assertEqual('LINESTRING', ls.geom_name)
         msg = 'Index out of range when accessing geometry in a collection: %s.'
         with self.assertRaisesMessage(IndexError, msg % len(mlinestr)):
             mlinestr.__getitem__(len(mlinestr))
Beispiel #9
0
 def test_polygons_templates(self):
     # Accessing Polygon attributes in templates should work.
     engine = Engine()
     template = engine.from_string('{{ polygons.0.wkt }}')
     polygons = [
         OGRGeometry(p.wkt) for p in self.geometries.multipolygons[:2]
     ]
     content = template.render(Context({'polygons': polygons}))
     self.assertIn('MULTIPOLYGON (((100', content)
Beispiel #10
0
 def handle(self, *args, **options):
     wards = Ward.objects.all()
     for ward in wards:
         tifs = TifDistrict.objects.filter(geom__overlaps=ward.geom)
         for tif in tifs:
             shape = OGRGeometry(ward.geom.intersection(tif.geom).wkt)
             overlap_geom = verify_geom(shape, Overlap._meta.get_field('overlap'))
             overlap = Overlap(ward=ward, tif=tif, overlap=overlap_geom)
             overlap.save()
 def test_cascaded_union(self):
     geometry = Geometry(
         OGRGeometry(
             'MULTIPOLYGON (((0 0,0 5,5 5,0 0)),((0 0,5 0,5 5,0 0)))')
     ).cascaded_union()
     self.assertIsInstance(geometry, Geometry)
     self.assertEqual(geometry.geometry.geom_name, 'MULTIPOLYGON')
     self.assertEqual(geometry.wkt,
                      'MULTIPOLYGON (((0 0,0 5,5 5,5 0,0 0)))')
Beispiel #12
0
    def add_aois_to_shapefile(self, ds, job_object):
        aois = job_object.aois.all()
        if len(aois) == 0:
            return

        geo_field = aois[0].polygon

        # Get the right geometry type number for ogr
        ogr_type = OGRGeomType(geo_field.geom_type).num

        # Set up the native spatial reference of the geometry field using the srid
        native_srs = SpatialReference(geo_field.srid)

        # create the AOI layer
        layer = lgdal.OGR_DS_CreateLayer(ds, 'lyr', native_srs._ptr, ogr_type,
                                         None)

        # Create the fields that each feature will have
        fields = AOI._meta.fields
        attributes = []
        for field in fields:
            if field.name in 'id, active, name, created_at, updated_at, analyst, priority, status, properties':
                attributes.append(field)

        for field in attributes:
            data_type = 4
            if field.name == 'id':
                data_type = 0
            fld = lgdal.OGR_Fld_Create(str(field.name), data_type)
            added = lgdal.OGR_L_CreateField(layer, fld, 0)
            check_err(added)

        # Getting the Layer feature definition.
        feature_def = lgdal.OGR_L_GetLayerDefn(layer)

        # Loop through queryset creating features
        for item in aois:
            feat = lgdal.OGR_F_Create(feature_def)

            for idx, field in enumerate(attributes):
                if field.name == 'properties':
                    value = json.dumps(item.properties)
                else:
                    value = getattr(item, field.name)
                string_value = str(value)[:80]
                lgdal.OGR_F_SetFieldString(feat, idx, string_value)

            # Transforming & setting the geometry
            geom = item.polygon
            ogr_geom = OGRGeometry(geom.wkt, native_srs)
            check_err(lgdal.OGR_F_SetGeometry(feat, ogr_geom._ptr))

            # create the feature in the layer.
            check_err(lgdal.OGR_L_CreateFeature(layer, feat))

        check_err(lgdal.OGR_L_SyncToDisk(layer))
Beispiel #13
0
 def test01b_gml(self):
     "Testing GML output."
     for g in self.geometries.wkt_out:
         geom = OGRGeometry(g.wkt)
         exp_gml = g.gml
         if GDAL_VERSION >= (1, 8):
             # In GDAL 1.8, the non-conformant GML tag  <gml:GeometryCollection> was
             # replaced with <gml:MultiGeometry>.
             exp_gml = exp_gml.replace('GeometryCollection', 'MultiGeometry')
         self.assertEqual(exp_gml, geom.gml)
 def test_transform_multipolygon(self):
     geometry = Geometry(
         OGRGeometry('MULTIPOLYGON (((0 0,0 5,5 5,0 0)))')).transform(
             SpatialReference(26917))
     self.assertIsInstance(geometry, Geometry)
     self.assertEqual(geometry.geometry.geom_name, 'MULTIPOLYGON')
     self.assertEqual(
         geometry.wkt,
         'MULTIPOLYGON (((-85.488743884706892 0.0,-85.488743884708271 0.000045096879048,-85.488699089723454 0.000045096881835,-85.488743884706892 0.0)))'
     )
Beispiel #15
0
 def test_transform_multipolygon(self):
     geometry = Geometry(
         OGRGeometry('MULTIPOLYGON (((0 0,0 5,5 5,0 0)))')).transform(
             SpatialReference(26917))
     self.assertIsInstance(geometry, Geometry)
     self.assertEqual(geometry.geometry.geom_name, 'MULTIPOLYGON')
     assertRegex(
         self, geometry.wkt,
         r'MULTIPOLYGON \(\(\(-85.488743884\d{6} 0.0,-85.488743884\d{6} 0.000045096\d{6},-85.488699089\d{6} 0.000045096\d{6},-85.488743884\d{6} 0.0\)\)\)'
     )
    def test_unary_union(self):
        boundary = Boundary(
            shape='MULTIPOLYGON (((0 0,0 5,2.5 5.0001,5 5,0 0)))')
        boundary.unary_union(
            Geometry(OGRGeometry('MULTIPOLYGON (((0 0,5 0,5 5,0 0)))')))

        self.assertEqual(boundary.shape.ogr.wkt,
                         'MULTIPOLYGON (((5 5,5 0,0 0,0 5,2.5 5.0001,5 5)))')
        self.assertEqual(boundary.simple_shape.ogr.wkt,
                         'MULTIPOLYGON (((5 5,5 0,0 0,0 5,5 5)))')
Beispiel #17
0
    def test04_linestring(self):
        "Testing LineString objects."
        prev = OGRGeometry('POINT(0 0)')
        for ls in self.geometries.linestrings:
            linestr = OGRGeometry(ls.wkt)
            self.assertEqual(2, linestr.geom_type)
            self.assertEqual('LINESTRING', linestr.geom_name)
            self.assertEqual(ls.n_p, linestr.point_count)
            self.assertEqual(ls.coords, linestr.tuple)
            self.assertEqual(True, linestr == OGRGeometry(ls.wkt))
            self.assertEqual(True, linestr != prev)
            self.assertRaises(OGRIndexError, linestr.__getitem__, len(linestr))
            prev = linestr

            # Testing the x, y properties.
            x = [tmpx for tmpx, tmpy in ls.coords]
            y = [tmpy for tmpx, tmpy in ls.coords]
            self.assertEqual(x, linestr.x)
            self.assertEqual(y, linestr.y)
Beispiel #18
0
    def processa(self):
        for arquivo, arqsaida in self.getArquivos():

            f = open(arquivo, 'r')
            dados = []
            for line in f:
                dados.append(line.split())
            f.close()

            ano = int(dados[3][1][:4])
            mes = 1
            dia = 1
            hora = int(dados[3][3][:2])
            minuto = int(dados[3][3][-2:])

            datahora = datetime(ano, mes, dia, hora, minuto)

            dias = int(dados[3][1][-3:]) - 1
            datahora = datahora + timedelta(days=dias)

            datareg = datetime.utcnow()

            for reg in dados[5:]:
                _posicao = 'SRID=4326;POINT({0} {1})'.format(reg[0], reg[1])
                _Satzen = float(reg[2])
                _PixSize = float(reg[3])
                _T4 = float(reg[4])
                _T11 = float(reg[5])
                _FireSize = float(reg[6])
                _Temp = int(reg[7].replace('.', ''))
                _FRP = int(reg[8].replace('.', ''))
                _Ecosystem = int(reg[9].replace('.', ''))
                _FireFlag = int(reg[10].replace('.', ''))

                ponto = OGRGeometry('POINT ({0} {1})'.format(reg[0], reg[1]))
                self.layer.spatial_filter = ponto.extent
                if len(self.layer) > 0:
                    regFocoItem = FocoWFABBA(dataUTC=datahora,
                                             dataregUTC=datareg,
                                             arquivo=arquivo,
                                             posicao=_posicao,
                                             Satzen=_Satzen,
                                             PixSize=_PixSize,
                                             T4=_T4,
                                             T11=_T11,
                                             FireSize=_FireSize,
                                             Temp=_Temp,
                                             FRP=_FRP,
                                             Ecosystem=_Ecosystem,
                                             FireFlag=_FireFlag)
                    regFocoItem.save()

                self.layer.spatial_filter = None

            shutil.move(arquivo, arqsaida)
    def handle(self, *args, **kwargs):
        tree_id = int(args[0])
        level = int(args[1])
        shape_file = args[2]

        ds = DataSource(shape_file)
        layer = ds[0]

        with Area.objects.delay_mptt_updates():

            for feat in layer:
                parent_id = feat['ID_%s' % (level - 1, )].value
                area_id = feat['ID_%s' % level].value
                area_name = unicode(feat['NAME_%s' % level].value,
                                    'iso-8859-1')
                try:
                    area_varname = unicode(feat['VARNAME_%s' % level].value,
                                           'iso-8859-1')
                except:
                    area_varname = ''
                area_type = unicode(feat['TYPE_%s' % level].value,
                                    'iso-8859-1')

                try:
                    Area.objects.get(tree_id=tree_id,
                                     level=level,
                                     shape_id=area_id)
                except Area.DoesNotExist:
                    pass
                else:
                    continue

                mpgeom = OGRGeometry('MultiPolygon')
                mpgeom.add(feat.geom)

                area_geom = GEOSGeometry(mpgeom.wkt)

                print "%s (%s): %s (%s)" % (area_id, parent_id, area_name,
                                            area_type)

                area = Area()
                area.shape_id = area_id
                area.parent_id = Area.objects.get(tree_id=tree_id,
                                                  level=(level - 1),
                                                  shape_id=parent_id).pk
                area.name = area_name
                area.varname = area_varname
                area.type = area_type

                area.save()

                areageom = Geom(area=area)
                areageom.geom = area_geom
                areageom.save()
Beispiel #20
0
    def __init__(self, geo_input, srid=None):
        """
        The base constructor for GEOS geometry objects, and may take the 
        following inputs:
         
         * string: WKT
         * string: HEXEWKB (a PostGIS-specific canonical form)
         * buffer: WKB
        
        The `srid` keyword is used to specify the Source Reference Identifier
        (SRID) number for this Geometry.  If not set, the SRID will be None.
        """
        if isinstance(geo_input, basestring):
            if isinstance(geo_input, UnicodeType):
                # Encoding to ASCII, WKT or HEXEWKB doesn't need any more.
                geo_input = geo_input.encode('ascii')

            wkt_m = wkt_regex.match(geo_input)
            if wkt_m:
                # Handling WKT input.
                if wkt_m.group('srid'): srid = int(wkt_m.group('srid'))
                g = from_wkt(wkt_m.group('wkt'))
            elif hex_regex.match(geo_input):
                # Handling HEXEWKB input.
                g = from_hex(geo_input, len(geo_input))
            elif GEOJSON and json_regex.match(geo_input):
                # Handling GeoJSON input.
                wkb_input = str(OGRGeometry(geo_input).wkb)
                g = from_wkb(wkb_input, len(wkb_input))
            else:
                raise ValueError(
                    'String or unicode input unrecognized as WKT EWKT, and HEXEWKB.'
                )
        elif isinstance(geo_input, GEOM_PTR):
            # When the input is a pointer to a geomtry (GEOM_PTR).
            g = geo_input
        elif isinstance(geo_input, buffer):
            # When the input is a buffer (WKB).
            wkb_input = str(geo_input)
            g = from_wkb(wkb_input, len(wkb_input))
        else:
            # Invalid geometry type.
            raise TypeError('Improper geometry input type: %s' %
                            str(type(geo_input)))

        if bool(g):
            # Setting the pointer object with a valid pointer.
            self._ptr = g
        else:
            raise GEOSException(
                'Could not initialize GEOS Geometry with given input.')

        # Post-initialization setup.
        self._post_init(srid)
Beispiel #21
0
    def processa(self):
        for arquivo, arqsaida in self.getArquivos():

            f = open(arquivo, 'r')
            dados = []
            for line in f:
                dados.append(line.split(','))
            f.close()

            for reg in dados[1:]:
                mask = '{0} {1}:00'.format(reg[5], reg[6])

                _dataRegUTC = datetime.utcnow()
                _posicao = 'SRID=4326;POINT({0} {1})'.format(reg[1], reg[0])
                _bright = float(reg[2])
                _scan = float(reg[3])
                _track = float(reg[4])
                _dataUTC = parser.parse(mask)
                _satellite = reg[7]
                _confidence = float(reg[8])
                _version = reg[9]
                _brightT31 = float(reg[10])
                _frp = float(reg[11])

                ponto = OGRGeometry(_posicao)
                self.layer.spatial_filter = ponto.extent

                query = FocoFIRMS.objects.filter(dataUTC = _dataUTC,\
                                                 posicao = _posicao,\
                                                 satellite = _satellite)

                if (len(self.layer) > 0 and len(query) == 0):
                    regFocoItem = FocoFIRMS(dataregUTC = _dataRegUTC,\
                                            posicao    = _posicao,\
                                            bright     = _bright,\
                                            scan       = _scan,\
                                            track      = _track,\
                                            dataUTC    = _dataUTC,\
                                            satellite  = _satellite,\
                                            confidence = _confidence,\
                                            version    = _version,\
                                            brightT31  = _brightT31,\
                                            frp        = _frp\
                                         )

                    regFocoItem.save()

                self.layer.spatial_filter = None

            # Se já foi processado apaga
            if path.isfile(arqsaida):
                remove(arqsaida)

            shutil.move(arquivo, arqsaida)
Beispiel #22
0
    def add_features_subset_to_shapefile(self, ds, features, layer_name):
        if len(features) == 0:
            return

        geo_field = features[0].the_geom

        # Get the right geometry type number for ogr
        ogr_type = OGRGeomType(geo_field.geom_type).num

        # Set up the native spatial reference of the geometry field using the srid
        native_srs = SpatialReference(geo_field.srid)

        # create the Feature layer
        layer = lgdal.OGR_DS_CreateLayer(ds, layer_name, native_srs._ptr,
                                         ogr_type, None)

        # Create the fields that each feature will have
        fields = Feature._meta.fields
        attributes = []
        for field in fields:
            if field.name in 'id, analyst, template, created_at, updated_at, job, project':
                attributes.append(field)

        for field in attributes:
            data_type = 4
            if field.name == 'id':
                data_type = 0
            fld = lgdal.OGR_Fld_Create(str(field.name), data_type)
            added = lgdal.OGR_L_CreateField(layer, fld, 0)
            check_err(added)

        # Getting the Layer feature definition.
        feature_def = lgdal.OGR_L_GetLayerDefn(layer)

        # Loop through queryset creating features
        for item in features:
            feat = lgdal.OGR_F_Create(feature_def)

            for idx, field in enumerate(attributes):
                value = getattr(item, field.name)
                # if field.name == 'template':
                #     value = value.name
                string_value = str(value)
                lgdal.OGR_F_SetFieldString(feat, idx, string_value)

            # Transforming & setting the geometry
            geom = item.the_geom
            ogr_geom = OGRGeometry(geom.wkt, native_srs)
            check_err(lgdal.OGR_F_SetGeometry(feat, ogr_geom._ptr))

            # create the feature in the layer.
            check_err(lgdal.OGR_L_CreateFeature(layer, feat))

        check_err(lgdal.OGR_L_SyncToDisk(layer))
Beispiel #23
0
def get_extent_from_text(points, srid_in, srid_out):
    """Transform an extent from srid_in to srid_out."""
    proj_in = SpatialReference(srid_in)

    proj_out = SpatialReference(srid_out)

    if srid_out == 900913:
        if int(float(points[0])) == -180:
            points[0] = -179
        if int(float(points[1])) == -90:
            points[1] = -89
        if int(float(points[2])) == 180:
            points[2] = 179
        if int(float(points[3])) == 90:
            points[3] = 89

    wkt = 'POINT(%f %f)' % (float(points[0]), float(points[1]))
    wkt2 = 'POINT(%f %f)' % (float(points[2]), float(points[3]))

    ogr = OGRGeometry(wkt)
    ogr2 = OGRGeometry(wkt2)

    if hasattr(ogr, 'srs'):
        ogr.srs = proj_in
        ogr2.srs = proj_in
    else:
        ogr.set_srs(proj_in)
        ogr2.set_srs(proj_in)

    ogr.transform_to(proj_out)
    ogr2.transform_to(proj_out)

    wkt = ogr.wkt
    wkt2 = ogr2.wkt

    mins = wkt.replace('POINT (', '').replace(')', '').split(' ')
    maxs = wkt2.replace('POINT (', '').replace(')', '').split(' ')
    mins.append(maxs[0])
    mins.append(maxs[1])

    return mins
Beispiel #24
0
    def test07b_closepolygons(self):
        "Testing closing Polygon objects."
        # Both rings in this geometry are not closed.
        poly = OGRGeometry('POLYGON((0 0, 5 0, 5 5, 0 5), (1 1, 2 1, 2 2, 2 1))')
        self.assertEqual(8, poly.point_count)
        print "\nBEGIN - expecting IllegalArgumentException; safe to ignore.\n"
        try:
            c = poly.centroid
        except OGRException:
            # Should raise an OGR exception, rings are not closed
            pass
        else:
            self.fail('Should have raised an OGRException!')
        print "\nEND - expecting IllegalArgumentException; safe to ignore.\n"

        # Closing the rings -- doesn't work on GDAL versions 1.4.1 and below:
        # http://trac.osgeo.org/gdal/ticket/1673
        if GDAL_VERSION <= (1, 4, 1): return
        poly.close_rings()
        self.assertEqual(10, poly.point_count) # Two closing points should've been added
        self.assertEqual(OGRGeometry('POINT(2.5 2.5)'), poly.centroid)
Beispiel #25
0
    def test_linestring(self):
        "Testing LineString objects."
        prev = OGRGeometry('POINT(0 0)')
        for ls in self.geometries.linestrings:
            linestr = OGRGeometry(ls.wkt)
            self.assertEqual(2, linestr.geom_type)
            self.assertEqual('LINESTRING', linestr.geom_name)
            self.assertEqual(ls.n_p, linestr.point_count)
            self.assertEqual(ls.coords, linestr.tuple)
            self.assertEqual(linestr, OGRGeometry(ls.wkt))
            self.assertNotEqual(linestr, prev)
            msg = 'Index out of range when accessing points of a line string: %s.'
            with self.assertRaisesMessage(IndexError, msg % len(linestr)):
                linestr.__getitem__(len(linestr))
            prev = linestr

            # Testing the x, y properties.
            x = [tmpx for tmpx, tmpy in ls.coords]
            y = [tmpy for tmpx, tmpy in ls.coords]
            self.assertEqual(x, linestr.x)
            self.assertEqual(y, linestr.y)
Beispiel #26
0
    def test07b_closepolygons(self):
        "Testing closing Polygon objects."
        # Both rings in this geometry are not closed.
        poly = OGRGeometry(
            'POLYGON((0 0, 5 0, 5 5, 0 5), (1 1, 2 1, 2 2, 2 1))')
        self.assertEqual(8, poly.point_count)
        print(
            "\nBEGIN - expecting IllegalArgumentException; safe to ignore.\n")
        try:
            c = poly.centroid
        except OGRException:
            # Should raise an OGR exception, rings are not closed
            pass
        else:
            self.fail('Should have raised an OGRException!')
        print("\nEND - expecting IllegalArgumentException; safe to ignore.\n")

        poly.close_rings()
        self.assertEqual(
            10, poly.point_count)  # Two closing points should've been added
        self.assertEqual(OGRGeometry('POINT(2.5 2.5)'), poly.centroid)
Beispiel #27
0
 def polygon_to_multipolygon(geom):
     """
     Convert polygons to multipolygons so all features are homogenous in the database.
     """
     if geom.__class__.__name__ == 'Polygon':
         g = OGRGeometry(OGRGeomType('MultiPolygon'))
         g.add(geom)
         return g
     elif geom.__class__.__name__ == 'MultiPolygon':
         return geom
     else:
         raise ValueError('Geom is neither Polygon nor MultiPolygon.')
Beispiel #28
0
def rasterize(geom, rast, burn_value=1, all_touched=False, add=False):
    """
    Rasterize a geometry. The result is aligned with the input raster.
    """
    # Create in memory target raster
    rasterized = rast.warp({'name': 'rasterized.MEM', 'driver': 'MEM'})

    # Set all values to zero if add option is off.
    if not add:
        rasterized.bands[0].data(numpy.zeros(rast.width * rast.height))

    # Set zero as nodata
    rasterized.bands[0].nodata_value = 0

    # Make sure geom is an OGR geometry
    if not isinstance(geom, OGRGeometry):
        geom = OGRGeometry(geom.ewkt)
    geom.transform(rast.srs)

    # Set rasterization parameters
    nr_of_bands_to_rasterize = 1
    band_indices_to_rasterize = (c_int * 1)(1)

    nr_of_geometries = 1
    burn_value = (c_double * 1)(burn_value)
    geometry_list = (c_void_p * 1)(geom.ptr)

    # Setup papsz options
    papsz_options = []
    if all_touched:
        papsz_options.append('ALL_TOUCHED=TRUE'.encode())
    if add:
        papsz_options.append('MERGE_ALG=ADD'.encode())

    papsz_options = (c_char_p * len(papsz_options))(*papsz_options)

    # Rasterize this geometry
    rasterize_geometries(
        rasterized.ptr,
        nr_of_bands_to_rasterize,
        band_indices_to_rasterize,
        nr_of_geometries,
        geometry_list,
        None,
        None,  # Transform parameters
        burn_value,
        papsz_options,
        None,
        None  # Progress functions
    )

    return rasterized
Beispiel #29
0
def transform_geom(wkt, srid_in, srid_out):

    proj_in = SpatialReference(int(srid_in))
    proj_out = SpatialReference(int(srid_out))
    ogr = OGRGeometry(wkt)
    if hasattr(ogr, 'srs'):
        ogr.srs = proj_in
    else:
        ogr.set_srs(proj_in)

    ogr.transform_to(proj_out)

    return ogr.wkt
Beispiel #30
0
 def geometry_to_multipolygon(geometry):
     """
     Converts a Polygon to a MultiPolygon.
     """
     value = geometry.__class__.__name__
     if value == 'MultiPolygon':
         return geometry
     elif value == 'Polygon':
         multipolygon = OGRGeometry(OGRGeomType('MultiPolygon'))
         multipolygon.add(geometry)
         return multipolygon
     else:
         raise ValueError(_('The geometry is a %(value)s but must be a Polygon or a MultiPolygon.') % {'value': value})