Пример #1
0
    def update_geom_from_feature(self, feat):
        """
        Given a spatial feature with Geometry, update spatial fields of the aquifer.
        You must still call aquifer.save() afterwards.
        """

        geom = feat.geom

        # Make a GEOSGeometry object using the string representation.
        if not geom.srid == 3005:
            logging.info("Non BC-albers feature, skipping.")
            return
        # Eliminate any 3d geometry so it fits in PostGIS' 2d geometry schema.
        wkt = wkt_w(dim=2).write(GEOSGeometry(geom.wkt, srid=3005)).decode()
        geos_geom = GEOSGeometry(wkt, srid=3005)
        # Convert MultiPolygons to plain Polygons,
        # We assume the largest one is the one we want to keep, and the rest are artifacts/junk.
        if isinstance(geos_geom, geos.MultiPolygon):
            geos_geom_out = geos_geom[0]
            for g in geos_geom:
                if len(g.wkt) > len(geos_geom_out.wkt):
                    geos_geom_out = g
        elif isinstance(geos_geom, geos.Polygon):
            geos_geom_out = geos_geom
        else:
            logging.info("Bad geometry type: {}, skipping.".format(
                geos_geom.__class__))
            return

        self.geom = geos_geom_out
Пример #2
0
    def update_geom_from_feature(self, feat):
        """
        Given a spatial feature with Geometry, update spatial fields of the aquifer.
        You must still call aquifer.save() afterwards.
        """

        geom = feat.geom

        if not geom.srid:
            raise Aquifer.BadShapefileException(
                "Shapefile contains no projection information")

        # Make a GEOSGeometry object using the string representation.
        # Eliminate any 3d geometry so it fits in PostGIS' 2d geometry schema.
        wkt = wkt_w(dim=2).write(GEOSGeometry(geom.wkt,
                                              srid=geom.srid)).decode()
        geos_geom = GEOSGeometry(wkt, srid=geom.srid)
        geos_geom.transform(3005)

        # Convert plain Polygons to MultiPolygons,
        if isinstance(geos_geom, geos.MultiPolygon):
            geos_geom_out = geos_geom
        elif isinstance(geos_geom, geos.Polygon):
            geos_geom_out = MultiPolygon(geos_geom)
        else:
            raise Aquifer.BadShapefileException(
                "Bad geometry type: {}, skipping.".format(geos_geom.__class__))

        self.geom = geos_geom_out
Пример #3
0
def import_hexes():
    data_source = DataSource.objects.get(name="hexes")
    ds = gdalDataSource(data_source.source_file_path)

    # Just clear all old data and rewrite it.
    Service.objects.all().delete()
    ISP.objects.all().delete()
    Hex.objects.all().delete()

    hexes = {}
    print(len(ds[0]), 'features')

    for i, feat in enumerate(ds[0]):
        if not i % 1000:
            print(i)

        hex_id = feat.get('description').split("=")[1].strip()
        try:
            hex = Hex.objects.get(pk=hex_id)
        except Hex.DoesNotExist:
            hex = Hex(id=hex_id)
        wkt = wkt_w(dim=2).write(GEOSGeometry(feat.geom.wkt,
                                              srid=WGS84_SRID)).decode()
        try:
            hex.geom = GEOSGeometry(wkt, srid=WGS84_SRID)
        except TypeError:
            print('skipping bad geom')
        if not hex.geom:
            continue
        hexes[hex_id] = hex

    Hex.objects.bulk_create(hexes.values())

    if data_source.source == SOURCE_DATABC:
        data_source.last_updated = get_databc_last_modified_date(data_source)
        data_source.save()
    elif data_source.source == SOURCE_OPENCA:
        data_source.last_updated = get_openca_last_modified_date(data_source)
        data_source.save()
Пример #4
0
 def wkt(self):
     "Returns the WKT (Well-Known Text) representation of this Geometry."
     return wkt_w().write(self)
Пример #5
0
 def wkt(self):
     "Returns the WKT (Well-Known Text) representation of this Geometry."
     return wkt_w(dim=3 if self.hasz else 2, trim=True).write(self).decode()
Пример #6
0
 def wkt(self):
     "Returns the WKT (Well-Known Text) representation of this Geometry."
     return wkt_w(3 if self.hasz else 2).write(self).decode()
Пример #7
0
 def wkt(self):
     "Returns the WKT (Well-Known Text) representation of this Geometry."
     return wkt_w().write(self)
Пример #8
0
 def wkt(self):
     "Returns the WKT (Well-Known Text) representation of this Geometry."
     return wkt_w(self.hasz and 3 or 2).write(self).decode()
Пример #9
0
def force2d(geom):
    # force geom to be 2d: https://groups.google.com/forum/#!topic/django-users/7c1NZ76UwRU
    wkt = wkt_w(dim=2).write(geom).decode()
    return GEOSGeometry(wkt)
Пример #10
0
    def handle(self, *args, **options):
        logging.info("Inspecting {}".format(options['path']))

        # Recursively unzip ugly masses of zipped shapfiles.
        found_zip = True
        while found_zip:
            found_zip = False
            for root, directories, filenames in os.walk(options['path']):
                for filename in filenames:
                    if filename.lower().endswith(".zip"):
                        logging.info("unzipping {}".format(filename))
                        zip_ref = zipfile.ZipFile(os.path.join(root, filename))
                        zip_ref.extractall(root)
                        zip_ref.close()
                        os.remove(os.path.join(root, filename))
                        found_zip = True

        # Recursively search for shapefiles and import them.
        shp_idx = 0
        for root, directories, filenames in os.walk(options['path']):
            for filename in filenames:
                if filename.lower().endswith(".shp"):
                    logging.info("processing shapefile".format(filename))
                    ds = DataSource(os.path.join(root, filename))
                    for layer in ds:
                        for feat in layer:
                            geom = feat.geom
                            #logging.debug(' '.join(['{}:{}'.format(f, feat.get(f)) for f in feat.fields]))
                            if "AQ_NUMBER" not in feat.fields:
                                logging.info(
                                    "Feature with no AQ_NUMBER attribute found skipping import."
                                )
                                continue

                            # Make a GEOSGeometry object using the string representation.
                            if not geom.srid == 3005:
                                logging.info(
                                    "Non BC-albers feature, skipping.")
                                continue

                            aquifer_id = feat.get("AQ_NUMBER")
                            # In dev environments, just assign these geometries to random aquifers.
                            if settings.DEBUG:
                                ct = Aquifer.objects.count() - 1
                                aquifer = Aquifer.objects.all()[shp_idx %
                                                                ct:][0]
                                shp_idx += 1
                            else:
                                try:
                                    aquifer = Aquifer.objects.get(
                                        pk=int(aquifer_id))
                                except Aquifer.DoesNotExist:
                                    logging.info(
                                        "Aquifer {} not found in database, skipping import."
                                        .format(aquifer_id))
                                    continue

                            wkt = wkt_w(dim=2).write(
                                GEOSGeometry(geom.wkt, srid=3005)).decode()
                            geos_geom = GEOSGeometry(wkt, srid=3005)
                            if isinstance(geos_geom, geos.MultiPolygon):
                                geos_geom_out = geos_geom[0]
                                for g in geos_geom:
                                    if len(g.wkt) > len(geos_geom_out.wkt):
                                        geos_geom_out = g
                            elif isinstance(geos_geom, geos.Polygon):
                                geos_geom_out = geos_geom
                            else:
                                logging.info(
                                    "Bad geometry type: {}, skipping.".format(
                                        geos_geom.__class__))
                                continue

                            try:
                                aquifer.geom = geos_geom_out
                            except Exception as e:
                                logging.info(
                                    "import failed. {}, droppin into shell for inspection"
                                    .format(e))
                                import code
                                code.interact(local=locals())
                                sys.exit(1)

                            aquifer.save()
Пример #11
0
        Returns the EWKT (SRID + WKT) of the Geometry.
=======
        Return the EWKT (SRID + WKT) of the Geometry.
>>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435
        """
        srid = self.srid
        return 'SRID=%s;%s' % (srid, self.wkt) if srid else self.wkt

    @property
    def wkt(self):
<<<<<<< HEAD
        "Returns the WKT (Well-Known Text) representation of this Geometry."
=======
        "Return the WKT (Well-Known Text) representation of this Geometry."
>>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435
        return wkt_w(dim=3 if self.hasz else 2, trim=True).write(self).decode()

    @property
    def hex(self):
        """
<<<<<<< HEAD
        Returns the WKB of this Geometry in hexadecimal form.  Please note
=======
        Return the WKB of this Geometry in hexadecimal form. Please note
>>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435
        that the SRID is not included in this representation because it is not
        a part of the OGC specification (use the `hexewkb` property instead).
        """
        # A possible faster, all-python, implementation:
        #  str(self.wkb).encode('hex')
        return wkb_w(dim=3 if self.hasz else 2).write_hex(self)