def test_set_get_polygon(self):
        """Test setting and getting geometries from a casestudy"""
        # create a casestudy
        casestudy = self.uic.casestudy

        # define the urls
        url = reverse('casestudy-detail', kwargs={
            'pk': casestudy.pk,
        })

        # put polygon as geometry
        polygon = geos.Polygon([(2.38, 57.322), (23.194, -20.28),
                                (-120.43, 19.15),
                                (2.38, 57.322)], [(-5.21, 23.51),
                                                  (15.21, -10.81),
                                                  (-20.51, 1.51),
                                                  (-5.21, 23.51)])
        data = {
            'geom': polygon.geojson,
        }

        response = self.patch('casestudy-detail', pk=casestudy.pk, data=data)
        self.response_200()

        casestudy.refresh_from_db()
        # polygon should have been converted to a multipolygon
        self.assertJSONEqual(casestudy.geom.json,
                             geos.MultiPolygon(polygon).json)

        # send geom as multipolygon and focusarea as polygon
        multipolygon = geos.MultiPolygon(
            polygon, geos.Polygon([(3, 3), (4, 4), (5, 3), (3, 3)]))

        data = {
            'geom': multipolygon.geojson,
            'focusarea': polygon.geojson,
        }

        response = self.patch('casestudy-detail', pk=casestudy.pk, data=data)
        assert response.status_code == status.HTTP_200_OK
        casestudy.refresh_from_db()

        # multipolygon should be a multipolygon
        self.assertJSONEqual(casestudy.geom.json, multipolygon.json)
        # polygon for focus area should have been converted to multipolygon
        self.assertJSONEqual(casestudy.focusarea.json,
                             geos.MultiPolygon(polygon).json)

        # get the response
        response = self.get_check_200('casestudy-detail', pk=casestudy.pk)

        assert response.data['id'] == casestudy.id
        assert response.data['type'] == 'Feature'
        self.assertJSONEqual(str(response.data['geometry']), multipolygon.json)

        # name and focusarea are stored in as property
        assert response.data['properties']['name'] == casestudy.name
        self.assertJSONEqual(str(response.data['properties']['focusarea']),
                             geos.MultiPolygon(polygon).json)
Example #2
0
 def test_detail_view_without_login_fails(self):
     p1 = geos.Polygon(((0, 0), (0, 1), (1, 1), (0, 0)))
     p2 = geos.Polygon(((1, 1), (1, 2), (2, 2), (1, 1)))
     multi_polygon = geos.MultiPolygon(p1, p2)
     clipping_area = ClippingArea.objects.create(
         name='test clipping area',
         clipping_multi_polygon=multi_polygon,
     )
     url = reverse('clipping_area-detail', args=[clipping_area.id])
     response = self.client.get(url, format='json')
     self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
Example #3
0
 def test_detail_view_with_correct_data_succeeds(self):
     p1 = geos.Polygon(((0, 0), (0, 1), (1, 1), (0, 0)))
     p2 = geos.Polygon(((1, 1), (1, 2), (2, 2), (1, 1)))
     multi_polygon = geos.MultiPolygon(p1, p2)
     clipping_area = ClippingArea.objects.create(
         name='test clipping area',
         clipping_multi_polygon=multi_polygon,
     )
     url = reverse('clipping_area-detail', args=[clipping_area.id])
     self.client.force_authenticate(user=self.user)
     response = self.client.get(url, format='json')
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     self.assertEqual(response.data['name'], "test clipping area")
Example #4
0
    def test_add_geometry_with_parent_area(self):
        """Test adding/updating features with parent levels"""
        polygon1 = geos.Polygon(((0, 0), (0, 10), (10, 10), (0, 10), (0, 0)))
        polygon2 = geos.Polygon(((4, 4), (4, 6), (6, 6), (6, 4), (4, 4)))
        kreis1 = geojson.Feature(geometry=geojson.loads(polygon1.geojson),
                                 properties={
                                     'name': 'Kreis1',
                                     'code': '01001',
                                 })
        kreis2 = geojson.Feature(geometry=geojson.loads(polygon1.geojson),
                                 properties={
                                     'name': 'Kreis2',
                                     'code': '01002',
                                 })
        gem1 = geojson.Feature(geometry=geojson.loads(polygon2.geojson),
                               properties={'name': 'Gemeinde1',
                                           'code': '01002001',
                                           'parent_area_code': \
                                           kreis2['properties']['code'],})
        gem2 = geojson.Feature(geometry=geojson.loads(polygon2.geojson),
                               properties={'name': 'Gemeinde2',
                                           'code': '01001002',
                                           'parent_area_code': \
                                           kreis1['properties']['code'],})
        kreise = geojson.FeatureCollection([kreis1, kreis2])
        self.post(
            'area-list',
            casestudy_pk=self.casestudy.pk,
            level_pk=self.kreis.pk,
            data=kreise,
            extra=dict(content_type='application/json'),
        )
        self.response_201()

        gemeinden = geojson.FeatureCollection([gem1, gem2])
        gemeinden['parent_level'] = 6
        self.post(
            'area-list',
            casestudy_pk=self.casestudy.pk,
            level_pk=self.gemeinde.pk,
            data=gemeinden,
            extra=dict(content_type='application/json', ),
        )
        self.response_201()

        gem1 = models.Area.objects.get(code='01002001')
        assert gem1.parent_area.code == '01002'
        gem2 = models.Area.objects.get(code='01001002')
        assert gem2.parent_area.code == '01001'
Example #5
0
def get_camden_parks():
    parks_file = os.path.join(DATA_DIR, 'osm_london', 'natural')
    camden = models.Division.objects.get(type='borough', name='Camden').mpoly
    sf = shapefile.Reader(parks_file)
    recs = sf.records()
    shapes = sf.shapes()
    # get all parks
    park_idx = [i for i, x in enumerate(recs) if x[-1] == 'park']
    # park_shapes = [shapes[i] for i in park_idx]
    # park_recs = [recs[i] for i in park_idx]

    # restrict to camden
    camden_parks = {}
    for i in park_idx:
        ps = shapes[i]
        pr = recs[i]
        poly = geos.Polygon(np.array(ps.points), srid=4326)
        poly.transform(27700)
        if camden.intersects(poly):
            print "Intersection"
            name = pr[1]
            if name.strip(' '):
                camden_parks[name] = poly

    return camden_parks
Example #6
0
File: utils.py Project: sau29/scale
def create_country(name=None,
                   fips='TT',
                   gmi='TT',
                   iso2='TT',
                   iso3='TST',
                   iso_num=0,
                   border=None,
                   effective=None):
    """Creates a country data model for unit testing

    :returns: The file model
    :rtype: :class:`storage.models.CountryData`
    """
    if not name:
        global COUNTRY_NAME_COUNTER
        name = 'test-country-%i' % COUNTRY_NAME_COUNTER
        COUNTRY_NAME_COUNTER += 1
    if not border:
        border = geos.Polygon(((0, 0), (0, 10), (10, 10), (10, 0), (0, 0)))
    if not effective:
        effective = timezone.now()

    return CountryData.objects.create(name=name,
                                      fips=fips,
                                      gmi=gmi,
                                      iso2=iso2,
                                      iso3=iso3,
                                      iso_num=iso_num,
                                      border=border,
                                      effective=effective)
Example #7
0
 def test_create_polygon(self):
     poly = geos.Polygon(
         ((-13018143.159491, 3811914.6000511), (-12961274.010455,
                                                3792958.217039),
          (-13004690.242515, 3778282.3076103), (-13018143.159491,
                                                3811914.6000511)))
     Feature.objects.create(geom_multipolygon=poly)
Example #8
0
 def get_bbox(self, obj):
     return geos.Polygon((
         (obj.bbox_x0, obj.bbox_y0),
         (obj.bbox_x0, obj.bbox_y1),
         (obj.bbox_x1, obj.bbox_y1),
         (obj.bbox_x1, obj.bbox_y0),
         (obj.bbox_x0, obj.bbox_y0),
     ))
Example #9
0
def geodjango_rectangle_from_vertices(xmin, ymin, xmax, ymax):
    return geos.Polygon([
        (xmin, ymin),
        (xmax, ymin),
        (xmax, ymax),
        (xmin, ymax),
        (xmin, ymin),
    ])
Example #10
0
 def test_border_update(self):
     newborder = geos.Polygon(((0, 0), (42, 0), (42, 42), (0, 42), (0, 0)))
     neweffective = datetime.datetime(2010, 4, 5, 18, 26, 0, tzinfo=utc)
     CountryData.objects.update_border('Test Country', newborder, neweffective)
     tmp = CountryData.objects.filter(name='Test Country', effective=neweffective)
     self.assertEqual(tmp[0].border, newborder)
     self.assertEqual(tmp[0].effective, neweffective)
     self.assertEqual(tmp[0].fips, 'TC')
Example #11
0
 def test_country_data(self):
     '''Tests adding a border and country intersection calculation.'''
     testborder = geos.Polygon(((0, 0), (0, 10), (10, 10), (10, 0), (0, 0)))
     testborder2 = geos.Polygon(
         ((11, 0), (11, 8), (19, 8), (19, 0), (11, 0)))
     testborder3 = geos.Polygon(
         ((11, 11), (11, 15), (15, 15), (15, 11), (11, 11)))
     testeffective = datetime.datetime(2000, 1, 1, 0, 0, 0, tzinfo=utc)
     CountryData.objects.create(name="Test Country",
                                fips="TC",
                                gmi="TCY",
                                iso2="TC",
                                iso3="TCY",
                                iso_num=42,
                                border=testborder,
                                effective=testeffective)
     CountryData.objects.create(name="Test Country 2",
                                fips="TT",
                                gmi="TCT",
                                iso2="TT",
                                iso3="TCT",
                                iso_num=43,
                                border=testborder2,
                                effective=testeffective)
     CountryData.objects.create(name="Test Country 3",
                                fips="TH",
                                gmi="TCH",
                                iso2="TH",
                                iso3="TCH",
                                iso_num=44,
                                border=testborder3,
                                effective=testeffective)
     ws = storage_test_utils.create_workspace(name='test',
                                              base_url='http://localhost')
     file = storage_test_utils.create_file(file_name='test.txt',
                                           workspace=ws)
     with transaction.atomic():
         file.geometry = geos.Polygon(
             ((5, 5), (5, 10), (12, 10), (12, 5), (5, 5)))
         file.set_countries()
         file.save()
     tmp = [c.iso2 for c in file.countries.all()]
     self.assertEqual(len(tmp), 2)
     self.assertIn("TC", tmp)
     self.assertIn("TT", tmp)
Example #12
0
File: srs.py Project: shikhach/quac
def bounding_box_srid(srid):
    '''Return a bounding box for given SRID as a polygon in that SRID. E.g.:

      >>> bounding_box_srid(54003).coords
      (((240181312.2..., -14671436.0...), (240181312.2..., 14671436.0...), (-240181312.2..., 14671436.03...), (-240181312.2..., -14671436.0...), (240181312.2..., -14671436.0...)),)'''
    (xmin, xmax) = lon_bounds_srid(srid)
    (ymin, ymax) = lat_bounds_srid(srid)
    return geos.Polygon([(xmin, ymin), (xmin, ymax), (xmax, ymax),
                         (xmax, ymin), (xmin, ymin)],
                        srid=srid)
Example #13
0
    def test_polygon_to_coord_string(self):
        # Note that the lon,lat order is reversed in the expected string
        # (compared to the polygon below).
        expected_str = '38.0, -122.2, 38.0, -121.7, 37.5, -121.7, 37.5, -122.2'
        polygon = geos.Polygon(
            ((-122.2, 38.0), (-121.7, 38.0), (-121.7, 37.5),
             (-122.2, 37.5), (-122.2, 38.0)))

        actual_str = _polygon_to_coord_string(polygon)
        self.assertEqual(expected_str, actual_str)
Example #14
0
 def polygons(self, create, extracted, **kwargs):
     if not create:
         return  # build, can't record many to many relationship
     if extracted:
         for polygon in extracted:
             self.polygons.add(polygon)
     else:
         geom = geos.Polygon(((0.0, 0.0), (0.0, 50.0), (50.0, 50.0),
                              (50.0, 0.0), (0.0, 0.0)))
         poly = Polygon(geom=geom)
         self.polygons.add(poly)
Example #15
0
 def setUp(self):
     django.setup()
     self.testborder = geos.Polygon(
         ((0, 0), (0, 10), (10, 10), (0, 10), (0, 0)))
     self.testeffective = datetime.datetime(2000, 1, 1, 0, 0, 0, tzinfo=utc)
     CountryData.objects.create(name="Test Country",
                                fips="TC",
                                gmi="TCY",
                                iso2="TC",
                                iso3="TCY",
                                iso_num=42,
                                border=self.testborder,
                                effective=self.testeffective)
Example #16
0
    def test_add_geometry(self):
        """Test adding a geometry to an area"""
        response = self.get_check_200('area-detail',
                                      casestudy_pk=self.casestudy.pk,
                                      level_pk=self.kreis_pi.adminlevel.pk,
                                      pk=self.kreis_pi.pk)
        data = response.data
        self.assertEqual(data['type'], 'Feature')
        properties = data['properties']
        cs_uri = self.reverse('casestudy-detail', pk=self.casestudy.pk)
        level_uri = self.reverse('adminlevels-detail',
                                 casestudy_pk=self.casestudy.pk,
                                 pk=self.kreis_pi.adminlevel.pk)
        self.assertURLEqual(properties['casestudy'], cs_uri)
        self.assertURLEqual(properties['adminlevel'], level_uri)
        assert properties['name'] == self.kreis_pi.name

        # geometry is None
        assert data['geometry'] is None

        # add new Polygon as geometry

        polygon = geos.Polygon(((0, 0), (0, 10), (10, 10), (0, 10), (0, 0)),
                               ((4, 4), (4, 6), (6, 6), (6, 4), (4, 4)),
                               srid=4326)

        # and change the name
        new_name = 'Kreis Pinneberg-Elmshorn'
        data = {
            'geometry': polygon.geojson,
            'properties': {
                'name': new_name,
            },
        }
        response = self.patch(
            'area-detail',
            casestudy_pk=self.casestudy.pk,
            level_pk=self.kreis_pi.adminlevel.pk,
            pk=self.kreis_pi.pk,
            data=json.dumps(data),
            extra=dict(content_type='application/json'),
        )
        self.response_200()
        # test if the new geometry is a multipolygon
        multipolygon = geos.MultiPolygon(polygon)
        self.assertJSONEqual(str(response.data['geometry']),
                             multipolygon.geojson)
        # and that the name has changed
        self.assertEqual(response.data['properties']['name'], new_name)
Example #17
0
    def test_grid_offset(self):
        """
        Simple square domain, test with offset coords
        """
        domain = geos.Polygon([
            (0, 0),
            (0, 1),
            (1, 1),
            (1, 0),
            (0, 0),
        ])
        igrid, egrid, fgs = spatial.create_spatial_grid(domain, grid_length=0.1) # no offset
        self.assertEqual(len(igrid), 100)
        self.assertEqual(len(egrid), 100)
        self.assertAlmostEqual(sum([g.area for g in igrid]), 1.0)
        for g in igrid:
            self.assertAlmostEqual(g.area, 0.01)
            self.assertTrue(g.intersects(domain))
        for g in egrid:
            self.assertAlmostEqual(g[2], g[0] + 0.1)
            self.assertAlmostEqual(g[3], g[1] + 0.1)
        self.assertTrue(np.all(fgs))

        igrid, egrid, fgs = spatial.create_spatial_grid(domain, grid_length=0.1, offset_coords=(0.05, 0.)) # offset
        self.assertEqual(len(igrid), 110)
        self.assertEqual(len(igrid), 110)
        self.assertAlmostEqual(sum([g.area for g in igrid]), 1.0)
        self.assertAlmostEqual(igrid[0].area, 0.005)
        for g in igrid:
            self.assertTrue(g.intersects(domain))
        for g in egrid:
            self.assertAlmostEqual(g[2], g[0] + 0.1)
            self.assertAlmostEqual(g[3], g[1] + 0.1)
        # 20 grid squares are not fully within the domain
        self.assertEqual(sum(fgs), 90)

        igrid, egrid, fgs = spatial.create_spatial_grid(domain, grid_length=0.1, offset_coords=(0., 1.1)) # offset outside of domain
        self.assertEqual(len(igrid), 100)
        self.assertEqual(len(egrid), 100)
        self.assertAlmostEqual(sum([g.area for g in igrid]), 1.0)
        for g in igrid:
            self.assertAlmostEqual(g.area, 0.01)
            self.assertTrue(g.intersects(domain))
        for g in egrid:
            self.assertAlmostEqual(g[2], g[0] + 0.1)
            self.assertAlmostEqual(g[3], g[1] + 0.1)
        self.assertTrue(np.all(fgs))
Example #18
0
    def validate_geometries(self, row, rownum):
        try:
            geom = fromstr(row['ATTRIBUTEVALUE'])
            coord_limit = 1500
            bbox = geos.Polygon(settings.DATA_VALIDATION_BBOX)

            if geom.num_coords > coord_limit:
                self.append_error('ERROR ROW: {0} - {1} has too many coordinates ({2}), Please limit to less then {3} coordinates of 5 digits of precision or less.'.format(rownum, row['ATTRIBUTEVALUE'][:75] + '......', geom.num_coords, coord_limit), 'geometry_errors')

            # if fromstr(row['ATTRIBUTEVALUE']).valid == False:
            #     self.append_error('ERROR ROW: {0} - {1} is an invalid geometry.'.format(rownum, row['ATTRIBUTEVALUE']), 'geometry_errors')

            if bbox.contains(geom) == False:
                self.append_error('ERROR ROW: {0} - {1} does not fall within the bounding box of the selected coordinate system. Adjust your coordinates or your settings.DATA_EXTENT_VALIDATION property.'.format(rownum, row['ATTRIBUTEVALUE']), 'geometry_errors')

        except:
            self.append_error('ERROR ROW: {0} - {1} is not a properly formatted geometry.'.format(rownum, row['ATTRIBUTEVALUE']), 'geometry_errors')
Example #19
0
def create_grid_centroid_hotspots_shapefile(grid_spacing=25):
    grid_spacing = 25  # distance between centroids in metres

    res, t0, cid = cad.get_crimes_by_type(nicl_type=range(1, 17))
    sk = hotspot.SKernelHistoricVariableBandwidthNn(dt=60, nn=15)

    # choose final date 2011/11/1 for training -> 60 days prior ends AFTER crossover to new non-snapped data
    days_offset = 245
    dt_pred = t0.date() + datetime.timedelta(days=days_offset)
    training = res[res[:, 0] <= days_offset]
    sk.train(training)

    # generate grid
    camden = cad.get_camden_region()
    # convert to buffered rectangular region
    sq_poly = camden.buffer(grid_spacing).envelope
    # lock to integer multiples of grid_spacing
    c = []
    for i in range(len(sq_poly.coords[0])):
        a = int(sq_poly.coords[0][i][0] / grid_spacing) * grid_spacing
        b = int(sq_poly.coords[0][i][1] / grid_spacing) * grid_spacing
        c.append((a, b))
    sq_poly = geos.Polygon(geos.LinearRing(c))

    r = roc.RocGrid(poly=sq_poly)
    print "Setting ROC grid..."
    r.set_sample_units(grid_spacing)
    print "Done."

    # prediction on grid
    print "Computing KDE prediction..."
    z = sk.predict(r.sample_points)
    print "Done."

    print "Writing shapefile..."
    out_shp = 'risk_surface_%s.shp' % dt_pred.strftime('%Y-%m-%d')
    w = shapefile.Writer(shapefile.POINT)
    w.field('risk', fieldType='N')
    for x, y in zip(r.sample_points, z.flat):
        w.point(int(x[0]), int(x[1]))
        w.record(risk=y)
    w.save(out_shp)
    print "Done."
Example #20
0
    def setUp(self):
        self.compiler = ExpressionEvaluator()
        poly = geos.Polygon(
            ((0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (0.0, 0.0)))

        self.context = {
            'testint': 1,
            'location_1': geos.Point(66, 66),
            'location_2': geos.Point(1, 1),
            'maincat': 'dieren',
            'subcat': 'subcat',
            'time': time.strptime("16:00:00", "%H:%M:%S"),
            'area': {
                'stadsdeel': {
                    'oost': geos.MultiPolygon(poly)
                }
            },
            'listval': 'geo1',
            'list': set(['geo1', 'geo2'])
        }
Example #21
0
    def _cell_to_polygon(center, cell_size):
        """Return the cell with the given mid point and size.

        :param center: the center of the risk cell
        :type center: a :py:class:`openquake.shapes.Site` instance
        :param float cell_size: the configured risk cell size

        :return: the risk cell as a :py:class:`django.contrib.gis.geos.Polygon`
        """
        clon, clat = center.coords
        half_csize = cell_size / 2.0
        lon, lat = (clon - half_csize, clat - half_csize)

        coos = [
            (lon, lat),  # lower left
            (lon, lat + cell_size),  # upper left
            (lon + cell_size, lat + cell_size),  # upper right
            (lon + cell_size, lat),  # lower right
            (lon, lat)
        ]
        coos = [(round_float(x), round_float(y)) for x, y in coos]
        return geos.Polygon(coos)
Example #22
0
    def setup_classic_job(self, create_job_path=True, upload_id=None):
        """Create a classic job with associated upload and inputs.

        :param integer upload_id: if set use upload record with given db key.
        :param bool create_job_path: if set the path for the job will be
            created and captured in the job record
        :returns: a :py:class:`geonode.mtapi.models.OqJob` instance
        """
        upload = self.setup_upload(upload_id)
        oqp = OqParams()
        oqp.job_type = "classical"
        oqp.upload = upload
        oqp.region_grid_spacing = 0.01
        oqp.min_magnitude = 5.0
        oqp.investigation_time = 50.0
        oqp.component = "gmroti50"
        oqp.imt = "pga"
        oqp.truncation_type = "twosided"
        oqp.truncation_level = 3
        oqp.reference_vs30_value = 760
        oqp.imls = [
            0.005, 0.007, 0.0098, 0.0137, 0.0192, 0.0269, 0.0376, 0.0527,
            0.0738, 0.103, 0.145, 0.203, 0.284, 0.397, 0.556, 0.778
        ]
        oqp.poes = [0.01, 0.10]
        oqp.realizations = 1
        from django.contrib.gis import geos
        oqp.region = geos.Polygon(
            ((-122.2, 38.0), (-121.7, 38.0), (-121.7, 37.5), (-122.2, 37.5),
             (-122.2, 38.0)))
        oqp.save()
        job = OqJob(oq_params=oqp, owner=upload.owner, job_type="classical")
        job.save()
        if create_job_path:
            job.path = os.path.join(upload.path, str(job.id))
            os.mkdir(job.path)
            os.chmod(job.path, 0777)
            job.save()
        return job
Example #23
0
    def get(self, request, **kwargs):
        params = request.GET
        if params:
            print()
            self.latitude = round(float(params.get('lat')), 4)
            self.longitude = round(float(params.get('lng')), 4)
            self.radius = int(params.get('radius'))
            self.geometry = self.geodesic_point_buffer(self.latitude,
                                                       self.longitude,
                                                       self.radius)
            geosGeom = geos.Polygon(self.geometry)
            self.near_rivers = River.objects.filter(geom__intersects=geosGeom)
            self.nearby_rivers = serialize('geojson', self.near_rivers)
            self.response['lat'] = self.latitude
            self.response['lng'] = self.longitude
            self.response['nearby_rivers'] = self.nearby_rivers
            self.response['geometry'] = mapping(Polygon(self.geometry))
            self.response['flood_prone'] = self.is_flood_prone_area(geosGeom)
            #eopatch = self.get_elevation(Polygon(self.geometry).bounds)
            #eopatch_sq = eopatch.data_timeless['MAPZEN_DEM'].squeeze()
            self.response['mean_slope'] = np.random.rand(
            )  #self.calclute_slope(eopatch_sq).mean()
            self.response['msl'] = np.random.uniform(
                low=600, high=4000,
                size=None)  #self.calculate_mean_sea_level(eopatch_sq)
            self.response['rain_prediction'] = self.get_rain_prediction(
                self.latitude, self.longitude)
            self.response['remarks'] = self.determine_flood_safe()
            """plt.figure(figsize=(10,10))
			plt.imshow(eopatch.data_timeless['MAPZEN_DEM'].squeeze())
			plt.show()"""

        else:
            print("No query params")

        return Response(self.response)
Example #24
0
 def _getBusStops(regions: FeatureCollection) -> [Point]:
     ret = GeoSampa_BusStops.objects.all()[:0]
     for feature in regions['features']:
         #This represents a simple exterior linear ring.  Interior rings are
         #not considered.
         geom = geos.Polygon(
             feature['geometry']['coordinates'][0],
             srid=int(regions['crs']['properties']['name'].split(':')[1]))
         partial = GeoSampa_BusStops.objects.filter(mpoint__within=geom)
         #TODO: Replace union with Collect
         #//https://docs.djangoproject.com/en/2.0/ref/contrib/gis/geoquerysets/#intersects
         ret = ret.union(partial)
     featuresList = []
     for busStop in ret.all():
         GeoSampaMiner._reproject(busStop.mpoint)
         featuresList.append(
             Feature(id=busStop.id,
                     properties={
                         'name': busStop.name,
                         'description': busStop.description,
                         'address': busStop.address
                     },
                     geometry=Point(busStop.mpoint)))
     return FeatureCollection(featuresList, crs=GeoSampaMiner._crs)
Example #25
0
def import_events(data_from_feed, tolerance=0.0001):
    """
    For every shapefile in _merged folder, creates or updates event in Django DB and Geoserver DB. 
    The geometry inserted in Geoserver DB is the union of all features found in layer.
    """
    db = DbUtils()
    conn = db.get_db_conn()
    curs = conn.cursor()
    allowed_extensions = [".shp"]

    try:
        for root, dirs, files in os.walk(SHAPEFILES_BASE_DIR):
            print('shapefiles base dir: {}'.format(SHAPEFILES_BASE_DIR))
            for d in dirs:
                if d.endswith('_merged'):

                    print('found merged folder')
                    for f in os.listdir(os.path.join(SHAPEFILES_BASE_DIR, d)):
                        if f.endswith(tuple(allowed_extensions)):
                            print('found shapefiles: {}'.format(f))
                            '''try:
                                filepath = os.path.join(SHAPEFILES_BASE_DIR, d, f)
                                ds = DataSource(filepath)
                            except GDALException, e:
                                traceback.print_exc()
                                break
                            for layer in ds:
                                count = 0 
                                polygon_union = None   
                                for feat in layer:   
                                    print('processing feature {}'.format(count))                                 
                                    # Simplify the Geometry
                                    geom = geos.fromstr(feat.geom.wkt, srid=4326)                                                    
                                    if tolerance > 0:                    
                                        geom = geom.simplify(tolerance, preserve_topology=True)

                                    # Generalize to 'Multiploygon'                
                                    if isinstance(geom, geos.Polygon):
                                        geom = geos.MultiPolygon(geom)
                                    
                                    if count == 0:
                                        polygon_union = geom.buffer(0)
                                    else:
                                        polygon_union = polygon_union.union(geom.buffer(0))
                                    count += 1                                
                                try:
                                    print('re-extracting geom from union polygon')
                                    polygon_union = geos.fromstr(polygon_union.wkt, srid=4326)
                                except:
                                    break'''
                            ems = d.split('_')[0]
                            select_template = "SELECT ST_AsText(ST_Union(ARRAY(SELECT ST_Buffer(the_geom, 1e-5) FROM {})))".format(
                                ems)
                            row = None
                            try:
                                curs.execute(select_template)
                                row = curs.fetchone()
                            except:
                                pass
                            #set default multipolygon
                            ext_coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0,
                                                                           0))
                            int_coords = ((0.4, 0.4), (0.4, 0.6), (0.6, 0.6),
                                          (0.6, 0.4), (0.4, 0.4))
                            polygon_union = geos.MultiPolygon(geos.Polygon(
                                ext_coords, int_coords),
                                                              srid=4326)
                            if row:
                                polygon_union = geos.fromstr(row[0], srid=4326)

                            # Update event in Django
                            event_from_feed = get_event_from_feed(
                                data_from_feed, ems)
                            new_event = generate_event_from_feed(
                                event_from_feed, polygon_union)

                            if new_event:
                                params = {
                                    'geom': polygon_union,
                                    'event_id': new_event.event_id,
                                    'begin_date': new_event.begin_date,
                                    'end_date': new_event.end_date
                                }
                                update_template = """INSERT INTO events (the_geom, event_id, begin_date, end_date) 
                                                        SELECT 
                                                            '{geom}', '{event_id}', '{begin_date}', '{end_date}'
                                                        ON CONFLICT (event_id)
                                                        DO UPDATE SET the_geom = excluded.the_geom;"""
                                print update_template.format(**params)
                                curs.execute(update_template.format(**params))
                    archive_path = os.path.join(SHAPEFILES_BASE_DIR, d,
                                                'archive')
                    if not os.path.exists(archive_path):
                        os.makedirs(archive_path)
                    for f2 in os.listdir(os.path.join(SHAPEFILES_BASE_DIR, d)):
                        filepath = os.path.join(SHAPEFILES_BASE_DIR, d, f2)
                        if os.path.isfile(filepath):
                            print('moving file {} to {}'.format(
                                f2, archive_path))
                            os.rename(filepath, os.path.join(archive_path, f2))

        conn.commit()
    except Exception:
        try:
            conn.rollback()
        except:
            pass

        traceback.print_exc()
    finally:
        conn.close()
Example #26
0
    def test_add_geometries(self):
        """Test adding features as feature collection"""
        response = self.get_check_200('area-list',
                                      casestudy_pk=self.casestudy.pk,
                                      level_pk=self.kreis.pk)
        num_kreise = len(response.data['results'])

        polygon1 = geos.Polygon(((0, 0), (0, 10), (10, 10), (0, 10), (0, 0)))
        polygon2 = geos.Polygon(((4, 4), (4, 6), (6, 6), (6, 4), (4, 4)))
        kreis1 = geojson.Feature(geometry=geojson.loads(polygon1.geojson),
                                 properties={
                                     'name': 'Kreis1',
                                     'code': '01001'
                                 })
        kreis2 = geojson.Feature(geometry=geojson.loads(polygon2.geojson),
                                 properties={
                                     'name': 'Kreis2',
                                     'code': '01002',
                                     'parent_area_code': self.sh.code,
                                 })
        kreise = geojson.FeatureCollection([kreis1, kreis2])
        kreise['parent_level'] = str(4)
        self.post(
            'area-list',
            casestudy_pk=self.casestudy.pk,
            level_pk=self.kreis.pk,
            data=kreise,
            extra=dict(content_type='application/json'),
        )
        self.response_201()
        k2 = models.Area.objects.get(code='01002')
        k1 = models.Area.objects.get(code='01001')
        assert k2.name == 'Kreis2'
        assert k1.name == 'Kreis1'

        k2 = models.Area.objects.get(code='01002')
        assert k2.name == 'Kreis2'
        assert k2.parent_area == self.sh

        response = self.get_check_200('area-list',
                                      casestudy_pk=self.casestudy.pk,
                                      level_pk=self.kreis.pk)
        assert len(response.data['results']) == num_kreise + 2

        # posting with relating to parents by area code
        # should fail, when parent_level is missing
        del kreise['parent_level']
        self.post(
            'area-list',
            casestudy_pk=self.casestudy.pk,
            level_pk=self.kreis.pk,
            data=kreise,
            extra=dict(content_type='application/json'),
        )
        self.response_400()

        # relate to parent by id
        kreis3 = geojson.Feature(geometry=geojson.loads(polygon2.geojson),
                                 properties={
                                     'name': 'Kreis3',
                                     'code': '01003',
                                     'parent_area': self.sh.id
                                 })
        self.post(
            'area-list',
            casestudy_pk=self.casestudy.pk,
            level_pk=self.kreis.pk,
            data=kreis3,
            extra=dict(content_type='application/json'),
        )
        self.response_201()

        k3 = models.Area.objects.get(code='01003')
        assert k3.parent_area == self.sh

        # posting with both parent_area_code and parent_area_id should fail
        # (only one allowed at a time)
        kreis4 = geojson.Feature(geometry=geojson.loads(polygon2.geojson),
                                 properties={
                                     'name': 'Kreis4',
                                     'code': '01004',
                                     'parent_area_code': self.sh.code,
                                     'parent_area': 1
                                 })
        kreise = geojson.FeatureCollection([kreis4])
        kreise['parent_level'] = str(4)
        self.post(
            'area-list',
            casestudy_pk=self.casestudy.pk,
            level_pk=self.kreis.pk,
            data=kreise,
            extra=dict(content_type='application/json'),
        )
        self.response_400()
Example #27
0
 def test_border_update_not_found(self):
     newborder = geos.Polygon(((0, 0), (42, 0), (42, 42), (0, 42), (0, 0)))
     self.assertRaises(CountryData.DoesNotExist, CountryData.objects.update_border, 'Kerblekistan', newborder)
Example #28
0
 def is_polygon_equal(self, d):
     g = geos.Polygon(d['features'][0]['geometry']['coordinates'][0])
     g.srid = self.g.srid
     return g.equals_exact(self.g, self.tolerance)
from ConfigParser import ConfigParser
from geonode.mtapi import models as mt_models
from utils.oqrunner import config_writer

from django.contrib.gis import geos

TEST_OWNER_ID = 1
TEST_JOB_PID = 1
TEST_OUTPUT_BASE_PATH = "/tmp/oqserver_tests"

TEST_PARAMS = {
    'CALCULATION_MODE':
    'classical',
    'REGION_VERTEX':
    geos.Polygon(((-122.2, 38.0), (-121.7, 38.0), (-121.7, 37.5),
                  (-122.2, 37.5), (-122.2, 38.0))),
    'REGION_GRID_SPACING':
    0.01,
    'MINIMUM_MAGNITUDE':
    5.0,
    'INVESTIGATION_TIME':
    50.0,
    'COMPONENT':
    'gmroti50',
    'INTENSITY_MEASURE_TYPE':
    'pga',
    'GMPE_TRUNCATION_TYPE':
    'twosided',
    'TRUNCATION_LEVEL':
    '3',
    'REFERENCE_VS30_VALUE':
Example #30
0
    y = np.random.random(sim_times.size)
    out = x > 1.
    while np.any(out):
        xn = np.random.exponential(scale=2, size=out.sum())
        x[out] = xn
        out = x > 1.
    return CartesianSpaceTimeData.from_args(sim_times, x, y)


if b_sim:
    max_t = 0.1
    max_d = 0.1
    du = 0.01
    dv = 0.01
    number_nn = [25, 25]
    poly = geos.Polygon([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)])
    res_all = simulation()
    cid_all = np.arange(res_all.ndata)

else:
    max_t = 90
    max_d = 500
    du = 50
    dv = 5
    number_nn = [15, 100]
    simplification_tol = 20  # for speedup in intersection etc.

    full_poly = cad.get_camden_region()
    poly = full_poly.simplify(simplification_tol)
    bdy = poly.boundary