Exemple #1
0
    def test_prepared(self):
        "Testing PreparedGeometry support."
        # Creating a simple multipolygon and getting a prepared version.
        mpoly = GEOSGeometry("MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))")
        prep = mpoly.prepared

        # A set of test points.
        pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)]
        covers = [True, True, False]  # No `covers` op for regular GEOS geoms.
        for pnt, c in zip(pnts, covers):
            # Results should be the same (but faster)
            self.assertEqual(mpoly.contains(pnt), prep.contains(pnt))
            self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt))
            self.assertEqual(c, prep.covers(pnt))

        if geos_version_info()["version"] > "3.3.0":
            self.assertTrue(prep.crosses(fromstr("LINESTRING(1 1, 15 15)")))
            self.assertTrue(prep.disjoint(Point(-5, -5)))
            poly = Polygon(((-1, -1), (1, 1), (1, 0), (-1, -1)))
            self.assertTrue(prep.overlaps(poly))
            poly = Polygon(((-5, 0), (-5, 5), (0, 5), (-5, 0)))
            self.assertTrue(prep.touches(poly))
            poly = Polygon(((-1, -1), (-1, 11), (11, 11), (11, -1), (-1, -1)))
            self.assertTrue(prep.within(poly))

        # Original geometry deletion should not crash the prepared one (#21662)
        del mpoly
        self.assertTrue(prep.covers(Point(5, 5)))
Exemple #2
0
    def test_prepared(self):
        "Testing PreparedGeometry support."
        # Creating a simple multipolygon and getting a prepared version.
        mpoly = GEOSGeometry(
            'MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))'
        )
        prep = mpoly.prepared

        # A set of test points.
        pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)]
        covers = [True, True, False]  # No `covers` op for regular GEOS geoms.
        for pnt, c in zip(pnts, covers):
            # Results should be the same (but faster)
            self.assertEqual(mpoly.contains(pnt), prep.contains(pnt))
            self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt))
            self.assertEqual(c, prep.covers(pnt))

        if geos_version_info()['version'] > '3.3.0':
            self.assertTrue(prep.crosses(fromstr('LINESTRING(1 1, 15 15)')))
            self.assertTrue(prep.disjoint(Point(-5, -5)))
            poly = Polygon(((-1, -1), (1, 1), (1, 0), (-1, -1)))
            self.assertTrue(prep.overlaps(poly))
            poly = Polygon(((-5, 0), (-5, 5), (0, 5), (-5, 0)))
            self.assertTrue(prep.touches(poly))
            poly = Polygon(((-1, -1), (-1, 11), (11, 11), (11, -1), (-1, -1)))
            self.assertTrue(prep.within(poly))

        # Original geometry deletion should not crash the prepared one (#21662)
        del mpoly
        self.assertTrue(prep.covers(Point(5, 5)))
Exemple #3
0
    def handle(self, *args, **options):
        logger.debug('Running geo_target.py')

        cons_ids = []
        kwargs = {
            'state_cd': options['state'],
            'is_primary': True
        }

        with open(options['geojson_file']) as data_file:
            geojson = json.load(data_file)

        # Get all constituent addresses in the state
        cons_addrs = ConstituentAddress.objects.filter(**kwargs)

        if geojson['type'] == 'FeatureCollection':
            # todo: fetch number, but stick to 1st for now
            geojson = geojson['features'][0]['geometry']

        poly = GEOSGeometry(json.dumps(geojson))

        for con in cons_addrs:
            point = Point(y=con.latitude, x=con.longitude)
            if poly.contains(point):
                cons_ids.append(con.cons_id)

        with open('./cons-ids.csv', 'wb') as myfile:
            wr = csv.writer(myfile)
            wr.writerow(cons_ids)

        logger.debug('Geo targetting finished. Check ./cons-ids.csv')
Exemple #4
0
    def test_prepared(self):
        "Testing PreparedGeometry support."
        # Creating a simple multipolygon and getting a prepared version.
        mpoly = GEOSGeometry('MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))')
        prep = mpoly.prepared

        # A set of test points.
        pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)]
        for pnt in pnts:
            # Results should be the same (but faster)
            self.assertEqual(mpoly.contains(pnt), prep.contains(pnt))
            self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt))
            self.assertEqual(mpoly.covers(pnt), prep.covers(pnt))

        self.assertTrue(prep.crosses(fromstr('LINESTRING(1 1, 15 15)')))
        self.assertTrue(prep.disjoint(Point(-5, -5)))
        poly = Polygon(((-1, -1), (1, 1), (1, 0), (-1, -1)))
        self.assertTrue(prep.overlaps(poly))
        poly = Polygon(((-5, 0), (-5, 5), (0, 5), (-5, 0)))
        self.assertTrue(prep.touches(poly))
        poly = Polygon(((-1, -1), (-1, 11), (11, 11), (11, -1), (-1, -1)))
        self.assertTrue(prep.within(poly))

        # Original geometry deletion should not crash the prepared one (#21662)
        del mpoly
        self.assertTrue(prep.covers(Point(5, 5)))
Exemple #5
0
    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call form.save() for example).
        response = super(GeoTarget, self).form_valid(form)
        if self.request.is_ajax():

            cons_ids = []
            kwargs = {'state_cd': form.cleaned_data['state']}

            if form.cleaned_data['primary_only']:
                kwargs['is_primary'] = True

            # Get all constituent addresses in the state
            cons_addrs = ConstituentAddress.objects.filter(**kwargs)

            geojson = json.loads(form.cleaned_data['geojson'])

            if geojson['type'] == 'FeatureCollection':
                # todo: fetch number, but stick to 1st for now
                logger.debug('is FeatureCollection')
                geojson = geojson['features'][0]['geometry']

            # elif geojson['type'] not ['MultiPolygon', 'Polygon']:

            poly = GEOSGeometry(json.dumps(geojson))

            for con in cons_addrs:
                point = Point(y=con.latitude, x=con.longitude)
                if poly.contains(point):
                    cons_ids.append(con.cons_id)

            return JsonResponse(cons_ids, safe=False)
        else:
            return response
Exemple #6
0
def get_neighborhood(point):
    """
    Gets the neighborhood name for the specified GEOS POINT.
    Returns None if no neighborhood is found.
    """
    for n in neighborhoods["data"]:
        multipolygon = GEOSGeometry(n[MULTIPOLYGON_COL])

        if multipolygon.contains(point):
            return n[NEIGHBORHOOD_COL]

    return None
Exemple #7
0
    def test_prepared(self):
        "Testing PreparedGeometry support."
        # Creating a simple multipolygon and getting a prepared version.
        mpoly = GEOSGeometry('MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))')
        prep = mpoly.prepared

        # A set of test points.
        pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)]
        covers = [True, True, False] # No `covers` op for regular GEOS geoms.
        for pnt, c in zip(pnts, covers):
            # Results should be the same (but faster)
            self.assertEqual(mpoly.contains(pnt), prep.contains(pnt))
            self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt))
            self.assertEqual(c, prep.covers(pnt))
Exemple #8
0
    def test_prepared(self):
        "Testing PreparedGeometry support."
        # Creating a simple multipolygon and getting a prepared version.
        mpoly = GEOSGeometry('MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))')
        prep = mpoly.prepared

        # A set of test points.
        pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)]
        covers = [True, True, False] # No `covers` op for regular GEOS geoms.
        for pnt, c in zip(pnts, covers):
            # Results should be the same (but faster)
            self.assertEqual(mpoly.contains(pnt), prep.contains(pnt))
            self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt))
            self.assertEqual(c, prep.covers(pnt))
Exemple #9
0
 def flag_lombardy(cls):
     lomb_poly = GEOSGeometry(
         'POLYGON((8.49 44.67, 11.42 44.67, 11.42 46.63, 8.49 46.63, 8.49 44.67, 8.49 44.67))',
         srid=4326)
     today_min = datetime.datetime.combine(datetime.date.today(),
                                           datetime.time.min)
     today_max = datetime.datetime.combine(datetime.date.today(),
                                           datetime.time.max)
     today_data = cls.objects.filter(country='ITA',
                                     date__range=(today_min, today_max))
     for t in today_data:
         if t.latitude is not None and lomb_poly.contains(t.point):
             t.lombardy = True
             t.save()
Exemple #10
0
 def get_queryset(self, *args, **kwargs):
     lat = self.kwargs['lati']
     lng = self.kwargs['lngi']
     list_area = Area.objects.all()
     tab = []
     # Convert latitude and longitude in a GEOS Point
     coordinates = 'SRID=32140;POINT(' + str(lat) + ' ' + str(lng) + ')'
     for i in range(len(list_area)):
         elem = list_area[i].poly
         polygo = GEOSGeometry(elem)
         point = GEOSGeometry(coordinates)
         # Check if the Point is within a Polygon area
         if polygo.contains(point):
             tab.append(list_area[i].pk)
     return Area.objects.filter(pk__in=tab)
Exemple #11
0
    def process(self,
                input_filename,
                output_filename,
                geo_reference=None,
                generate_metadata=True,
                merge_with=None,
                original_footprint=None):

        # open the dataset and create an In-Memory Dataset as copy
        # to perform optimizations
        ds = create_mem_copy(gdal.Open(input_filename))

        gt = ds.GetGeoTransform()
        footprint_wkt = None

        if not geo_reference:
            if gt == (0.0, 1.0, 0.0, 0.0, 0.0, 1.0):
                if ds.GetGCPCount() > 0:
                    geo_reference = InternalGCPs()
                else:
                    raise ValueError("No geospatial reference for "
                                     "unreferenced dataset given.")

        if geo_reference:
            logger.debug("Applying geo reference '%s'." %
                         type(geo_reference).__name__)
            # footprint is always in EPSG:4326
            ds, footprint_wkt = geo_reference.apply(ds)

        # apply optimizations
        for optimization in self.get_optimizations(ds):
            logger.debug("Applying optimization '%s'." %
                         type(optimization).__name__)

            try:
                new_ds = optimization(ds)

                if new_ds is not ds:
                    # cleanup afterwards
                    cleanup_temp(ds)
                    ds = new_ds
            except:
                cleanup_temp(ds)
                raise

        # generate the footprint from the dataset
        if not footprint_wkt:
            logger.debug("Generating footprint.")
            footprint_wkt = self._generate_footprint_wkt(ds)
        # check that footprint is inside of extent of generated image
        # regenerate otherwise
        else:
            tmp_extent = getExtentFromRectifiedDS(ds)
            tmp_bbox = Polygon.from_bbox(
                (tmp_extent[0], tmp_extent[1], tmp_extent[2], tmp_extent[3]))
            # transform image bbox to EPSG:4326 if necessary
            proj = ds.GetProjection()
            srs = osr.SpatialReference()
            try:
                srs.ImportFromWkt(proj)
                srs.AutoIdentifyEPSG()
                ptype = "PROJCS" if srs.IsProjected() else "GEOGCS"
                srid = int(srs.GetAuthorityCode(ptype))
                if srid != '4326':
                    out_srs = osr.SpatialReference()
                    out_srs.ImportFromEPSG(4326)
                    transform = osr.CoordinateTransformation(srs, out_srs)
                    tmp_bbox2 = ogr.CreateGeometryFromWkt(tmp_bbox.wkt)
                    tmp_bbox2.Transform(transform)
                    tmp_bbox = GEOSGeometry(tmp_bbox2.ExportToWkt())
            except (RuntimeError, TypeError), e:
                logger.warn("Projection: %s" % proj)
                logger.warn("Failed to identify projection's EPSG code."
                            "%s: %s" % (type(e).__name__, str(e)))

            tmp_footprint = GEOSGeometry(footprint_wkt)
            if not tmp_bbox.contains(tmp_footprint):
                logger.debug("Re-generating footprint because not inside of "
                             "generated image.")
                footprint_wkt = tmp_footprint.intersection(tmp_bbox).wkt
Exemple #12
0
def check_shape_in_conus(aoi):
    conus_boundaries = GEOSGeometry(
        json.dumps(settings.CONUS_PERIMETER['geometry']), 4326)
    return conus_boundaries.contains(aoi)
Exemple #13
0
def update_geo_target_result(geo_target_id):
    """
    Update in progress GeoTarget with result from BSD and set as complete


    Parameters
    ----------
    geo_target_id : int
        GeoTarget id

    Returns
        -------
        int
            Returns updated GeoTarget status
    """

    """Get GeoTarget"""
    geo_target = GeoTarget.objects.get(id=geo_target_id)

    """Status should be new, otherwise do nothing"""
    if geo_target.status != GeoTargetStatus.new.value[0]:
        return geo_target.status

    """Set to in progress and start building result"""
    geo_target.status = GeoTargetStatus.in_progress.value[0]
    geo_target.save()

    try:
        """Get shape from geo json"""
        """Logic copied over from hydra app"""
        gjson = json.loads(geo_target.geo_json)
        if gjson['type'] == 'FeatureCollection':
            # todo: fetch number, but stick to 1st for now
            gjson = gjson['features'][0]['geometry']
        geo_shape = GEOSGeometry(json.dumps(gjson))
    except (GEOSException, GDALException, ValueError):
        geo_target.result = '''The geo json is invalid. Please double check the
        geo json and try again with a new geo target request.
        '''.replace('\n', '')
        geo_target.status = GeoTargetStatus.no_results.value[0]
        geo_target.save()
        return geo_target.status

    """
    Get constitents by state first and we will trim it down later. Don't
    filter by subscribers only.
    """
    constituents = find_constituents_by_state_cd(
        geo_target.state_or_territory,
        cons_group=None,
        subscribers_only=False,
        primary_address_only=geo_target.primary_address_only,
        with_email=False,
        with_phone=False,
    )

    """Update status and exit if we did not find any constituents"""
    if constituents is None:
        geo_target.status = GeoTargetStatus.no_results.value[0]
        geo_target.save()
        return geo_target.status

    """Loop through constituents and update result"""
    result = ""
    result_count = 0
    for constituent in constituents:
        constituent_id = constituent.get('id')

        """Get constituent location"""
        constituent_addresses = constituent.findall('cons_addr')
        for constituent_address in constituent_addresses:
            constituent_latitude = constituent_address.findtext('latitude')
            constituent_longitude = constituent_address.findtext('longitude')
            if constituent_latitude is not None and (
                constituent_longitude is not None
            ):
                constituent_point = Point(
                    y=float(constituent_latitude),
                    x=float(constituent_longitude)
                )
                """
                Add to result if point is in shape and go to next constituent
                """
                if geo_shape.contains(constituent_point):
                    result += "%s, " % constituent_id
                    result_count += 1
                    break

    """Update result and status"""
    geo_target.result = result
    geo_target.result_count = result_count
    geo_target.status = GeoTargetStatus.complete.value[0]
    geo_target.save()

    """Return updated GeoTarget status"""
    return geo_target.status
Exemple #14
0
    def process(self, input_filename, output_filename,
                geo_reference=None, generate_metadata=True,
                merge_with=None, original_footprint=None):

        # open the dataset and create an In-Memory Dataset as copy
        # to perform optimizations
        ds = create_mem_copy(gdal.Open(input_filename))

        gt = ds.GetGeoTransform()
        footprint_wkt = None

        if not geo_reference:
            if gt == (0.0, 1.0, 0.0, 0.0, 0.0, 1.0):
                if ds.GetGCPCount() > 0:
                    geo_reference = InternalGCPs()
                else:
                    raise ValueError("No geospatial reference for "
                                     "unreferenced dataset given.")

        if geo_reference:
            logger.debug("Applying geo reference '%s'."
                         % type(geo_reference).__name__)
            # footprint is always in EPSG:4326
            ds, footprint_wkt = geo_reference.apply(ds)

        # apply optimizations
        for optimization in self.get_optimizations(ds):
            logger.debug("Applying optimization '%s'."
                         % type(optimization).__name__)

            try:
                new_ds = optimization(ds)

                if new_ds is not ds:
                    # cleanup afterwards
                    cleanup_temp(ds)
                    ds = new_ds
            except:
                cleanup_temp(ds)
                raise

        # generate the footprint from the dataset
        if not footprint_wkt:
            logger.debug("Generating footprint.")
            footprint_wkt = self._generate_footprint_wkt(ds)
        # check that footprint is inside of extent of generated image
        # regenerate otherwise
        else:
            tmp_extent = getExtentFromRectifiedDS(ds)
            tmp_bbox = Polygon.from_bbox((tmp_extent[0], tmp_extent[1],
                                          tmp_extent[2], tmp_extent[3]))

            # transform image bbox to EPSG:4326 if necessary
            proj = ds.GetProjection()
            srs = osr.SpatialReference()
            try:
                srs.ImportFromWkt(proj)
                srs.AutoIdentifyEPSG()
                ptype = "PROJCS" if srs.IsProjected() else "GEOGCS"
                srid = int(srs.GetAuthorityCode(ptype))
                if srid != '4326':
                    out_srs = osr.SpatialReference()
                    out_srs.ImportFromEPSG(4326)
                    transform = osr.CoordinateTransformation(srs, out_srs)
                    tmp_bbox2 = ogr.CreateGeometryFromWkt(tmp_bbox.wkt)
                    tmp_bbox2.Transform(transform)
                    tmp_bbox = GEOSGeometry(tmp_bbox2.ExportToWkt())
            except (RuntimeError, TypeError), e:
                logger.warn("Projection: %s" % proj)
                logger.warn("Failed to identify projection's EPSG code."
                    "%s: %s" % ( type(e).__name__ , str(e) ) )

            tmp_footprint = GEOSGeometry(footprint_wkt)
            if not tmp_bbox.contains(tmp_footprint):
                footprint_wkt = tmp_footprint.intersection(tmp_bbox).wkt
Exemple #15
0
 def domain_points(self, domain_pk):
     domain = Domain.objects.get(pk=domain_pk)
     geom = GEOSGeometry(self.geom, srid=4608)
     return [point for point in domain.points.all() if geom.contains(GEOSGeometry(point.location))]