Ejemplo n.º 1
0
 def test_raises_invalid_wkt(self):
     poly = 'POLYGON 0.0 0.0, 1.0 4.0, 4.0 1.0, 0.0 0.0))'
     with self.assertRaises(ValueError) as ar:
         wkt.loads(poly)
     self.assertEqual(
         'Invalid WKT: `POLYGON 0.0 0.0, 1.0 4.0, 4.0 1.0, 0.0 0.0))`',
         str(ar.exception)
     )
Ejemplo n.º 2
0
 def test_raises_unmatched_paren(self):
     poly = 'POLYGON ((0.0 0.0, 1.0 4.0, 4.0 1.0, 0.0 0.0)'
     with self.assertRaises(ValueError) as ar:
         wkt.loads(poly)
     self.assertEqual(
         'Invalid WKT: `POLYGON ((0.0 0.0, 1.0 4.0, 4.0 1.0, 0.0 0.0)`',
         str(ar.exception)
     )
Ejemplo n.º 3
0
    def create_from_wkt(self, wkt, item_type, ingest_source, **attributes):
        '''
        Create a single vector in the vector service

        Args:
            wkt (str): wkt representation of the geometry
            item_type (str): item_type of the vector
            ingest_source (str): source of the vector
            attributes: a set of key-value pairs of attributes

        Returns:
            id (str): string identifier of the vector created
        '''
        # verify the "depth" of the attributes is single layer

        geojson = wkt2geojson.loads(wkt)
        vector = {
            'type': "Feature",
            'geometry': geojson,
            'properties': {
                'item_type': item_type,
                'ingest_source': ingest_source,
                'attributes': attributes
            }
        }

        return self.create(vector)[0]
Ejemplo n.º 4
0
    def test_loads_empty_geoms(self):
        types = [
            'Point',
            'LineString',
            'Polygon',
            'MultiPoint',
            'MultiLineString',
            'MultiPolygon',
        ]
        wkts = ['%s EMPTY' % x.upper() for x in types]
        for i, each_wkt in enumerate(wkts):
            expected = dict(type=types[i], coordinates=[])
            self.assertEqual(expected, wkt.loads(each_wkt))

        self.assertEqual(dict(type='GeometryCollection', geometries=[]),
                         wkt.loads('GEOMETRYCOLLECTION EMPTY'))
Ejemplo n.º 5
0
    def _get_route_points_metadata(self, route_points):
        route_points_count = len(route_points)

        if route_points_count <= self.METADATA_ROUTE_POINTS_COUNT:
            metadata_route_points = route_points
        else:
            metadata_route_points = [
                route_points[i * (route_points_count // self.METADATA_ROUTE_POINTS_COUNT)]
                for i in range(1, self.METADATA_ROUTE_POINTS_COUNT)
                ]
        metadata = []
        for point in metadata_route_points:
            response = self.api.geo.search(
                point='{},{}'.format(*point['coordinates']),
                fields='items.geometry.selection',
                radius=100,
                type='attraction,poi',
                page_size=1
            )
            if response['meta']['code'] == 200:
                item = response['result']['items'][0]
                raw_point = wkt.loads(item['geometry']['selection'])
                position = raw_point['coordinates']
                item['point'] = {
                    'longitude': position[0],
                    'latitude': position[1]
                }
                metadata.append(item)
            else:
                pass
        return metadata
Ejemplo n.º 6
0
 def test_2d_alternate(self):
     # alternative style for representing a multipoint in WKT
     mp = 'MULTIPOINT (100.000 3.101, 101.000 2.100, 3.140 2.180)'
     expected = dict(type='MultiPoint', coordinates=[
         [100.0, 3.101], [101.0, 2.1], [3.14, 2.18],
     ])
     self.assertEqual(expected, wkt.loads(mp))
Ejemplo n.º 7
0
def district_geometry():
    simplify = get_simplify_factor(request.args.get('zoom'))
    districts = g.c.execute(
        'SELECT id, statefp, cd114fp, geoid, namelsad, ST_AsText(ST_Simplify(geom, %s)) from districts', (simplify,))
    districts = g.c.fetchall()
    fc = FeatureCollection([Feature(geometry=wkt.loads(x[-1]), properties={'id': str(x[0])}) for x in districts])
    return json.dumps(fc)
Ejemplo n.º 8
0
 def test_4d(self):
     poly = 'POLYGON ((1 2 3 4, 5 6 7 8, 9 10 11 12, 1 2 3 4))'
     expected = dict(type='Polygon', coordinates=[
         [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0],
          [9.0, 10.0, 11.0, 12.0], [1.0, 2.0, 3.0, 4.0]]
     ])
     self.assertEqual(expected, wkt.loads(poly))
Ejemplo n.º 9
0
 def test_2d_srid1234(self):
     ls = 'SRID=1234;LINESTRING (0 -1, -2 -3, -4 5)'
     expected = dict(
         type='LineString',
         coordinates=[[0.0, -1.0], [-2.0, -3.0], [-4.0, 5.0]],
         meta=dict(srid=1234),
     )
     self.assertEqual(expected, wkt.loads(ls))
Ejemplo n.º 10
0
 def test_4d(self):
     mp = WKT['multipoint']['4d']
     expected = dict(type='MultiPoint', coordinates=[
         [100.0, 3.1, 1.0, 0.0],
         [101.0, 2.1, 2.0, 0.0],
         [3.14, 2.18, 3.0, 0.0],
     ])
     self.assertEqual(expected, wkt.loads(mp))
Ejemplo n.º 11
0
 def test_2d_srid4326(self):
     mp = 'SRID=4326;' + WKT['multipoint']['2d']
     expected = dict(
         type='MultiPoint',
         coordinates=[[100.0, 3.101], [101.0, 2.1], [3.14, 2.18]],
         meta=dict(srid=4326),
     )
     self.assertEqual(expected, wkt.loads(mp))
Ejemplo n.º 12
0
 def test_4d(self):
     mp = WKT['multipoint']['4d']
     expected = dict(type='MultiPoint',
                     coordinates=[
                         [100.0, 3.1, 1.0, 0.0],
                         [101.0, 2.1, 2.0, 0.0],
                         [3.14, 2.18, 3.0, 0.0],
                     ])
     self.assertEqual(expected, wkt.loads(mp))
Ejemplo n.º 13
0
 def test(self):
     mlls = WKT['multilinestring']
     expected = dict(type='MultiLineString',
                     coordinates=[
                         [[0.0, -1.0], [-2.0, -3.0], [-4.0, -5.0]],
                         [[1.66, -31023.5, 1.1], [10000.9999, 3.0, 2.2],
                          [100.9, 1.1, 3.3], [0.0, 0.0, 4.4]],
                     ])
     self.assertEqual(expected, wkt.loads(mlls))
Ejemplo n.º 14
0
def make_feature(record):
    """ Get a complete GeoJSON feature object for a record.
    """
    return dict(
        type="Feature",
        id=record.get("Key"),
        geometry=wkt.loads(record.get("WktGeometry")),
        properties=extract_properties(record),
    )
Ejemplo n.º 15
0
 def test(self):
     gc = 'GEOMETRYCOLLECTION (%s,%s,%s,%s,%s,%s)' % (
         WKT['point']['2d'],
         WKT['linestring']['2d'],
         WKT['polygon']['2d'],
         WKT['multipoint']['2d'],
         WKT['multilinestring'],
         WKT['multipolygon'],
     )
     expected = {
         'geometries': [
             {
                 'coordinates': [0.0, 1.0],
                 'type': 'Point'
             },
             {
                 'coordinates': [[-100.0, 0.0], [-101.0, -1.0]],
                 'type': 'LineString'
             },
             {
                 'coordinates': [[[100.001, 0.001], [101.1235, 0.001],
                                  [101.001, 1.001], [100.001, 0.001]],
                                 [[100.201, 0.201], [100.801, 0.201],
                                  [100.801, 0.801], [100.201, 0.201]]],
                 'type':
                 'Polygon'
             },
             {
                 'coordinates': [[100.0, 3.101], [101.0, 2.1], [3.14,
                                                                2.18]],
                 'type': 'MultiPoint'
             },
             {
                 'coordinates': [[[0.0, -1.0], [-2.0, -3.0], [-4.0, -5.0]],
                                 [[1.66, -31023.5, 1.1],
                                  [10000.9999, 3.0, 2.2], [100.9, 1.1, 3.3],
                                  [0.0, 0.0, 4.4]]],
                 'type':
                 'MultiLineString'
             },
             {
                 'coordinates': [[[[100.001, 0.001], [101.001, 0.001],
                                   [101.001, 1.001], [100.001, 0.001]],
                                  [[100.201, 0.201], [100.801, 0.201],
                                   [100.801, 0.801], [100.201, 0.201]]],
                                 [[[1.0, 2.0, 3.0, 4.0],
                                   [5.0, 6.0, 7.0, 8.0],
                                   [9.0, 10.0, 11.0, 12.0],
                                   [1.0, 2.0, 3.0, 4.0]]]],
                 'type':
                 'MultiPolygon'
             },
         ],
         'type':
         'GeometryCollection',
     }
     self.assertEqual(expected, wkt.loads(gc))
Ejemplo n.º 16
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-i',
                        '--input',
                        type=str,
                        help='Input WKT file',
                        required=True)
    parser.add_argument('-o',
                        '--outputDir',
                        type=str,
                        help='Target directory to save all the graphs',
                        required=True)
    args = parser.parse_args()

    if not os.path.isfile(args.input):
        print 'ERROR: {} does not exist'.format(args.input)
        exit(1)

    if not os.path.isdir(args.outputDir):
        os.makedirs(args.outputDir)
        print 'INFO: All WKT graphs will be written to {}'.format(
            args.outputDir)

    else:
        for dirpath, dirnames, files in os.walk(args.outputDir):
            if files:
                print 'ERROR: {} already exists and is not empty'.format(
                    args.outputDir)
                exit(2)
            else:
                print 'INFO: All WKT graphs will be written to {}'.format(
                    args.outputDir)

    empty_line = re.compile('^ *$')
    with open(args.input) as infile:
        for line in infile:
            if empty_line.match(line):
                continue

            all_geometries.append(wkt.loads(line))

    G = nx.Graph()
    for geometry in all_geometries:
        if geometry['type'] in ['Point', 'LineString', 'MultiLineString']:
            add_geometry(geometry, G)

        elif geometry['type'] is 'GeometryCollection':
            for geom in geometry['geometries']:
                add_geometry(geom, G)

    print 'The graph has {0} nodes and {1} edges'.format(
        G.number_of_nodes(), G.number_of_edges())
    components = connected_components(G)
    lComp = components[0]
    print 'The largest connected component has {} nodes and {} edges'.format(
        lComp.number_of_nodes(), lComp.number_of_edges())
    write_all_graphs(args.outputDir, components)
Ejemplo n.º 17
0
 def test_2d_alternate(self):
     # alternative style for representing a multipoint in WKT
     mp = 'MULTIPOINT (100.000 3.101, 101.000 2.100, 3.140 2.180)'
     expected = dict(type='MultiPoint',
                     coordinates=[
                         [100.0, 3.101],
                         [101.0, 2.1],
                         [3.14, 2.18],
                     ])
     self.assertEqual(expected, wkt.loads(mp))
Ejemplo n.º 18
0
def validate_location(value: str) -> bool:
    """Validate a location value as a WKT Point."""
    try:
        geo_json: dict = wkt.loads(value)
    except ValueError:
        return False
    if isinstance(geo_json, dict) and geo_json.get("type") == "Point":
        return True
    else:
        return False
    def getImageCoordinates(pt, rev):

        pt_json = wkt.loads(pt)

        map_x = pt_json['coordinates'][0]
        map_y = pt_json['coordinates'][1]

        col, row = rev * (map_x, map_y)

        return col, row
Ejemplo n.º 20
0
    def from_value(cls, value, **kwargs):
        """Instantiates a Geometry from a value and optional arguments

        Currently precision is supported as an optional argument.

        A rudimentary check on the validity of string values is performed.

        :param value: the value to convert to a geometry
        :param kwargs: optional arguments
        :return: Geometry
        """

        if isinstance(value, str):
            regex = re.compile("^[A-Z]+\s*\([A-Z0-9.,\s\(\)]+\)$")
            if not regex.match(value):
                raise ValueError(f"Illegal Geometry WKT value: {value}")
            # Use wkt load to get correct precision
            value = wkt.loads(value)

        if isinstance(value, geoalchemy2.elements.WKBElement):
            # Use shapely to construct wkt string and use wkt load to get correct precision
            value = wkt.loads(to_shape(value).wkt)

        if isinstance(value, dict):
            # serialize possible geojson
            value = json.dumps(value, cls=GobTypeJSONEncoder)

        # if is geojson dump to wkt string
        try:
            precision = kwargs[
                'precision'] if 'precision' in kwargs else cls._precision
            wkt_string = wkt.dumps(json.loads(value), decimals=precision)
            value = wkt_string

            # it is not a to wkt_string dumpable json, let it pass:
        except JSONDecodeError:
            pass
        except TypeError:
            pass

        # is wkt string
        return cls(value)
Ejemplo n.º 21
0
 def test(self):
     mlls = WKT['multilinestring']
     expected = dict(
         type='MultiLineString',
         coordinates=[
             [[0.0, -1.0], [-2.0, -3.0], [-4.0, -5.0]],
             [[1.66, -31023.5, 1.1], [10000.9999, 3.0, 2.2],
              [100.9, 1.1, 3.3], [0.0, 0.0, 4.4]],
         ]
     )
     self.assertEqual(expected, wkt.loads(mlls))
Ejemplo n.º 22
0
 def test(self):
     mpoly = WKT['multipolygon']
     expected = dict(type='MultiPolygon', coordinates=[
         [[[100.001, 0.001], [101.001, 0.001], [101.001, 1.001],
           [100.001, 0.001]],
          [[100.201, 0.201], [100.801, 0.201], [100.801, 0.801],
           [100.201, 0.201]]],
         [[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0],
           [9.0, 10.0, 11.0, 12.0], [1.0, 2.0, 3.0, 4.0]]],
     ])
     self.assertEqual(expected, wkt.loads(mpoly))
Ejemplo n.º 23
0
 def normalize_geo_response(self, raw_items):
     result = []
     for raw_item in raw_items:
         raw_point = raw_item['geometry']['selection']
         point_coordinates = wkt.loads(raw_point)['coordinates']
         raw_item['geometry'] = {
             'longitude': point_coordinates[0],
             'latitude': point_coordinates[1]
         }
         result.append(raw_item)
     return result
Ejemplo n.º 24
0
 def test(self):
     mpoly = WKT['multipolygon']
     expected = dict(type='MultiPolygon', coordinates=[
         [[[100.001, 0.001], [101.001, 0.001], [101.001, 1.001],
           [100.001, 0.001]],
          [[100.201, 0.201], [100.801, 0.201], [100.801, 0.801],
           [100.201, 0.201]]],
         [[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0],
           [9.0, 10.0, 11.0, 12.0], [1.0, 2.0, 3.0, 4.0]]],
     ])
     self.assertEqual(expected, wkt.loads(mpoly))
Ejemplo n.º 25
0
    def test_empty_component_with_srid(self):
        gc = 'SRID=4326;GEOMETRYCOLLECTION (POINT EMPTY)'

        expected = {
            'type': 'GeometryCollection',
            'meta': {'srid': 4326},
            'geometries': [
                {'type': 'Point', 'coordinates': []}
            ]
        }

        self.assertEqual(expected, wkt.loads(gc))
Ejemplo n.º 26
0
    def test_with_empty_component_simple(self):
        gc = 'GEOMETRYCOLLECTION (POINT (0 0), POINT EMPTY)'

        expected = {
            'type': 'GeometryCollection',
            'geometries': [
                {'type': 'Point', 'coordinates': [0, 0]},
                {'type': 'Point', 'coordinates': []}
            ]
        }

        self.assertEqual(expected, wkt.loads(gc))
Ejemplo n.º 27
0
    def _spatial(self, subject, predicate):
        '''
        Returns a dict with details about the spatial location

        Both subject and predicate must be rdflib URIRef or BNode objects

        Returns keys for uri, text or geom with the values set to
        None if they could not be found.

        Geometries are always returned in GeoJSON. If only WKT is provided,
        it will be transformed to GeoJSON.

        Check the notes on the README for the supported formats:

        https://github.com/ckan/ckanext-dcat/#rdf-dcat-to-ckan-dataset-mapping
        '''

        uri = None
        text = None
        geom = None

        for spatial in self.g.objects(subject, predicate):

            if isinstance(spatial, URIRef):
                uri = unicode(spatial)

            if isinstance(spatial, Literal):
                text = unicode(spatial)

            if (spatial, RDF.type, DCT.Location) in self.g:
                for geometry in self.g.objects(spatial, LOCN.geometry):
                    if (geometry.datatype == URIRef(GEOJSON_IMT) or
                            not geometry.datatype):
                        try:
                            json.loads(unicode(geometry))
                            geom = unicode(geometry)
                        except (ValueError, TypeError):
                            pass
                    if not geom and geometry.datatype == GSP.wktLiteral:
                        try:
                            geom = json.dumps(wkt.loads(unicode(geometry)))
                        except (ValueError, TypeError):
                            pass
                for label in self.g.objects(spatial, SKOS.prefLabel):
                    text = unicode(label)
                for label in self.g.objects(spatial, RDFS.label):
                    text = unicode(label)

        return {
            'uri': uri,
            'text': text,
            'geom': geom,
        }
Ejemplo n.º 28
0
    def _handler(request, response):
        from geomet import wkt
        from defusedxml import ElementTree
        response.update_status('PyWPS Process started.', 0)

        if request.inputs['wkt'][0].data != "":

            try:
                fn = request.inputs['wkt'][0].data
                poly = wkt.loads(fn)

                # Get the coordinates of the first feature
                if len(poly['coordinates']) == 1:  # For Polygons and Multipolygons
                    coordinates = poly['coordinates'][0]
                else:
                    coordinates = poly['coordinates']  # For other geometries

            except Exception as e:
                msg = "{}: WKT not found.".format(e)
                logging.warning(msg=msg)
                raise

        elif request.inputs['xml'][0].file is not None:

            try:
                fn = request.inputs['xml'][0].file
                poly = ElementTree.parse(fn)
                ns = {'gml': 'http://www.opengis.net/gml'}

                # Find the first polygon in the file.
                e = poly.find('.//gml:Polygon', ns)

                # Get the coordinates
                c = e.find('.//gml:coordinates', ns).text
                coordinates = [tuple(map(float, p.split(','))) for p in c.split(' ')]

            except Exception as e:
                msg = "{}: XML not found.".format(e)
                logging.warning(msg=msg)
                raise
        else:
            raise ValueError("Process requires a WKT string or XML file.")

        # Compute the average
        n = len(coordinates)
        x, y = zip(*coordinates)
        centroid_x = sum(x) / n
        centroid_y = sum(y) / n

        response.outputs['output'].data = '{:.5f},{:.5f}'.format(centroid_x, centroid_y)

        response.update_status('PyWPS Process completed.', 100)
        return response
Ejemplo n.º 29
0
    def _spatial(self, subject, predicate):
        '''
        Returns a dict with details about the spatial location

        Both subject and predicate must be rdflib URIRef or BNode objects

        Returns keys for uri, text or geom with the values set to
        None if they could not be found.

        Geometries are always returned in GeoJSON. If only WKT is provided,
        it will be transformed to GeoJSON.

        Check the notes on the README for the supported formats:

        https://github.com/ckan/ckanext-dcat/#rdf-dcat-to-ckan-dataset-mapping
        '''

        uri = None
        text = None
        geom = None

        for spatial in self.g.objects(subject, predicate):

            if isinstance(spatial, URIRef):
                uri = unicode(spatial)

            if isinstance(spatial, Literal):
                text = unicode(spatial)

            if (spatial, RDF.type, DCT.Location) in self.g:
                for geometry in self.g.objects(spatial, LOCN.geometry):
                    if (geometry.datatype == URIRef(GEOJSON_IMT) or
                            not geometry.datatype):
                        try:
                            json.loads(unicode(geometry))
                            geom = unicode(geometry)
                        except (ValueError, TypeError):
                            pass
                    if not geom and geometry.datatype == GSP.wktLiteral:
                        try:
                            geom = json.dumps(wkt.loads(unicode(geometry)))
                        except (ValueError, TypeError):
                            pass
                for label in self.g.objects(spatial, SKOS.prefLabel):
                    text = unicode(label)
                for label in self.g.objects(spatial, RDFS.label):
                    text = unicode(label)

        return {
            'uri': uri,
            'text': text,
            'geom': geom,
        }
Ejemplo n.º 30
0
	def __geojson_from_wkt(self, text):

		try:
			geom = wkt.loads(text)
		except:
			geom = []
		if len(geom) == 0:
			try:
				geom = wkt.loads("POINT(" + text + ")")
			except:
				geom = []
		if len(geom) == 0:
			return text
		else:
			if self.__test_geojson_recurse(geom):
				geom = {"type": "FeatureCollection", "features": [{ "type": "Feature", "properties": {"nodeId": None}, "geometry": geom }]}
				if self.__test_geojson_es(geom):
					return geom
				else:
					return text
			else:
				return text
Ejemplo n.º 31
0
 def test_3d(self):
     poly = (
         'POLYGON ((100.0 0.0 3.1, 101.0 0.0 2.1, 101.0 1.0 1.1, '
         '100.0 0.0 3.1), '
         '(100.2 0.2 3.1, 100.8 0.2 2.1, 100.8 0.8 1.1, 100.2 0.2 3.1))')
     expected = dict(type='Polygon',
                     coordinates=[
                         [[100.0, 0.0, 3.1], [101.0, 0.0, 2.1],
                          [101.0, 1.0, 1.1], [100.0, 0.0, 3.1]],
                         [[100.2, 0.2, 3.1], [100.8, 0.2, 2.1],
                          [100.8, 0.8, 1.1], [100.2, 0.2, 3.1]],
                     ])
     self.assertEqual(expected, wkt.loads(poly))
Ejemplo n.º 32
0
 def test_2d(self):
     poly = ('POLYGON ((100.001 0.001, 101.001 0.001, 101.001 1.001, '
             '100.001 0.001), '
             '(100.201 0.201, 100.801 0.201, 100.801 0.801, '
             '100.201 0.201))')
     expected = dict(type='Polygon',
                     coordinates=[
                         [[100.001, 0.001], [101.001, 0.001],
                          [101.001, 1.001], [100.001, 0.001]],
                         [[100.201, 0.201], [100.801, 0.201],
                          [100.801, 0.801], [100.201, 0.201]],
                     ])
     self.assertEqual(expected, wkt.loads(poly))
Ejemplo n.º 33
0
 def test_3d(self):
     poly = (
         'POLYGON ((100.0 0.0 3.1, 101.0 0.0 2.1, 101.0 1.0 1.1, '
         '100.0 0.0 3.1), '
         '(100.2 0.2 3.1, 100.8 0.2 2.1, 100.8 0.8 1.1, 100.2 0.2 3.1))'
     )
     expected = dict(type='Polygon', coordinates=[
         [[100.0, 0.0, 3.1], [101.0, 0.0, 2.1], [101.0, 1.0, 1.1],
          [100.0, 0.0, 3.1]],
         [[100.2, 0.2, 3.1], [100.8, 0.2, 2.1], [100.8, 0.8, 1.1],
          [100.2, 0.2, 3.1]],
     ])
     self.assertEqual(expected, wkt.loads(poly))
Ejemplo n.º 34
0
 def test(self):
     mlls = (
         'MULTILINESTRING ((0 -1, -2 -3, -4 -5), '
         '(1.66 -31023.5 1.1, 10000.9999 3.0 2.2, 100.9 1.1 3.3, 0 0 4.4))'
     )
     expected = dict(
         type='MultiLineString',
         coordinates=[
             [[0.0, -1.0], [-2.0, -3.0], [-4.0, -5.0]],
             [[1.66, -31023.5, 1.1], [10000.9999, 3.0, 2.2],
              [100.9, 1.1, 3.3], [0.0, 0.0, 4.4]],
         ]
     )
     self.assertEqual(expected, wkt.loads(mlls))
Ejemplo n.º 35
0
 def test_2d(self):
     poly = (
         'POLYGON ((100.001 0.001, 101.001 0.001, 101.001 1.001, '
         '100.001 0.001), '
         '(100.201 0.201, 100.801 0.201, 100.801 0.801, '
         '100.201 0.201))'
     )
     expected = dict(type='Polygon', coordinates=[
         [[100.001, 0.001], [101.001, 0.001], [101.001, 1.001],
          [100.001, 0.001]],
         [[100.201, 0.201], [100.801, 0.201], [100.801, 0.801],
          [100.201, 0.201]],
     ])
     self.assertEqual(expected, wkt.loads(poly))
Ejemplo n.º 36
0
 def test_srid662(self):
     gc = 'SRID=662;GEOMETRYCOLLECTION (%s,%s,%s,%s,%s,%s)' % (
         WKT['point']['2d'],
         WKT['linestring']['2d'],
         WKT['polygon']['2d'],
         WKT['multipoint']['2d'],
         WKT['multilinestring'],
         WKT['multipolygon'],
     )
     expected = {
         'geometries': [
             {'coordinates': [0.0, 1.0], 'type': 'Point'},
             {'coordinates': [[-100.0, 0.0], [-101.0, -1.0]],
              'type': 'LineString'},
             {'coordinates': [[[100.001, 0.001],
                               [101.1235, 0.001],
                               [101.001, 1.001],
                               [100.001, 0.001]],
                              [[100.201, 0.201],
                               [100.801, 0.201],
                               [100.801, 0.801],
                               [100.201, 0.201]]],
              'type': 'Polygon'},
             {'coordinates': [[100.0, 3.101], [101.0, 2.1], [3.14, 2.18]],
              'type': 'MultiPoint'},
             {'coordinates': [[[0.0, -1.0], [-2.0, -3.0], [-4.0, -5.0]],
                              [[1.66, -31023.5, 1.1],
                               [10000.9999, 3.0, 2.2],
                               [100.9, 1.1, 3.3],
                               [0.0, 0.0, 4.4]]],
              'type': 'MultiLineString'},
             {'coordinates': [[[[100.001, 0.001],
                                [101.001, 0.001],
                                [101.001, 1.001],
                                [100.001, 0.001]],
                               [[100.201, 0.201],
                                [100.801, 0.201],
                                [100.801, 0.801],
                                [100.201, 0.201]]],
                              [[[1.0, 2.0, 3.0, 4.0],
                                [5.0, 6.0, 7.0, 8.0],
                                [9.0, 10.0, 11.0, 12.0],
                                [1.0, 2.0, 3.0, 4.0]]]],
              'type': 'MultiPolygon'},
         ],
         'type': 'GeometryCollection',
         'meta': dict(srid=662),
     }
     self.assertEqual(expected, wkt.loads(gc))
Ejemplo n.º 37
0
def ver_local(request, id_local):
    local_FK = Local.objects.get(pk=id_local)
    geometria, obj = Local.campo.auto_get(instance=id_local)

    geojson = wkt.loads(obj)

    context = {
        'nome_mapa': local_FK.descricao,
        'obj': {
            'type': geojson['type'],
            'coordinates': geojson['coordinates']
        }
    }

    return render(request, 'camada/ver_local.html', context)
Ejemplo n.º 38
0
    def from_wkt(cls, s):
        """
        Parse a LineString geometry from a wkt string and return a new LineString object.
        """
        try:
            geom = wkt.loads(s)
        except ValueError:
            raise ValueError("Invalid WKT geometry: '{0}'".format(s))

        if geom['type'] != 'LineString':
            raise ValueError("Invalid WKT geometry type. Expected 'LineString', got '{0}': '{1}'".format(geom['type'], s))

        geom['coordinates'] = list_contents_to_tuple(geom['coordinates'])

        return LineString(coords=geom['coordinates'])
Ejemplo n.º 39
0
def ver_local(request, id_local):
    local_FK = Local.objects.get(pk=id_local)
    geometria, obj = Local.campo.auto_get(instance=id_local)

    geojson = wkt.loads(obj)

    context = {
        'nome_mapa': local_FK.descricao,
        'obj': {
            'type': geojson['type'],
            'coordinates': geojson['coordinates']
            }
        }

    return render(request, 'camada/ver_local.html', context)
Ejemplo n.º 40
0
def extract_geometry(record):
    ''' Get a GeoJSON geometry object for a record.
    '''
    prop = extract_properties(record)

    try:
        geom = parseWkt.loads(prop['WktGeometry'])
    except KeyError:
        geom = dict(type='Point',
                    coordinates=[float(prop['Long']),
                                 float(prop['Lat'])])
    except ValueError:
        geom = None

    return geom
Ejemplo n.º 41
0
 def test(self):
     mpoly = (
         'MULTIPOLYGON (((100.001 0.001, 101.001 0.001, 101.001 1.001, '
         '100.001 0.001), '
         '(100.201 0.201, 100.801 0.201, 100.801 0.801, '
         '100.201 0.201)), ((1 2 3 4, 5 6 7 8, 9 10 11 12, 1 2 3 4)))'
     )
     expected = dict(type='MultiPolygon', coordinates=[
         [[[100.001, 0.001], [101.001, 0.001], [101.001, 1.001],
           [100.001, 0.001]],
          [[100.201, 0.201], [100.801, 0.201], [100.801, 0.801],
           [100.201, 0.201]]],
         [[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0],
           [9.0, 10.0, 11.0, 12.0], [1.0, 2.0, 3.0, 4.0]]],
     ])
     self.assertEqual(expected, wkt.loads(mpoly))
Ejemplo n.º 42
0
    def _set_feature_co(self):
        self._set_hashid('hashid', 'src_id', 'id')
        self._set_node_hashid('shashid', 'src_id', 'sinfo_id')
        self._set_node_hashid('thashid', 'src_id', 'tinfo_id')

        # self._set_alias("shid", 'shashid')
        # self._set_alias("thid", 'thashid')

        self._set_feat_properties(weight=lambda row: round(row.len, 3))
        if 'geom' in self.fields and self['geom'].type == 'geometry()':

            self.feature = Field.Virtual(
                'feature', lambda row: geojson.Feature(
                    geometry=wkt.loads(row[self._tablename].geom),
                    properties=row[self._tablename].feat_properties,
                    id=row[self._tablename].hashid))
Ejemplo n.º 43
0
def reproject_wkt_entity(entity, projection):
    if entity is '' or entity.rstrip() is '':
        return ''

    srcProj = pyproj.Proj(init=projection, preserve_units=True)

    json = wkt.loads(entity)
    if json['type'] is 'Point':
        origin = json['coordinates']
        x_1, y_1 = reproject_single_point(origin[0], origin[1], srcProj)
        new_entitiy = 'POINT ({0} {1})'
        return new_entitiy.format(x_1, y_1)

    elif json['type'] is 'LineString':
        newLine = 'LINESTRING ('
        initial_char = ''
        for point in json['coordinates']:
            newX, newY = reproject_single_point(point[0], point[1], srcProj)
            fmt = '{} {}'
            newLine += initial_char + fmt.format(newX, newY)
            initial_char = ', '

        return newLine + ')'

    elif json['type'] is 'MultiLineString':
        multiline = 'MULTILINESTRING ('
        initial_char = ''
        for line in json['coordinates']:
            newLine = '('
            line_initial_char = ''
            for point in line:
                nX, nY = reproject_single_point(point[0], point[1], srcProj)
                fmt = '{} {}'
                newLine += line_initial_char + fmt.format(nX, nY)
                line_initial_char = ', '

            multiline += initial_char + newLine + ')'
            initial_char = ', '

        return multiline + ')'

    elif json['type'] is 'Polygon':
        print 'POLYGON'

    print 'NONE'
    print json
    return ''
Ejemplo n.º 44
0
 def search_optimal_geo_point(self, start_point, items):
     optimal_point = None
     optimal_time = None
     metadata = None
     for item in items:
         item_point = wkt.loads(item['geometry']['selection'])
         walking_time = math.pi * self.estimate_walking_time(
             start_point, item_point)
         if (optimal_time is None
                 or math.fabs(optimal_time - self.OPTIMAL_WALK_TIME) >
                 math.fabs(walking_time - self.OPTIMAL_WALK_TIME)):
             optimal_time = walking_time
             optimal_point = item_point
             metadata = item
     position = optimal_point['coordinates']
     metadata['point'] = {'longitude': position[0], 'latitude': position[1]}
     return optimal_point, metadata
Ejemplo n.º 45
0
def cdistrict_bbox():
    bbox = request.args.get('bbox')
    zoom = request.args.get('zoom')
    simplify = get_simplify_factor(zoom)
    x1, y1, x2, y2 = [float(x) for x in bbox.split(',')]
    bounded_districts = get_districts(simplify).filter(
        func.ST_Intersects(func.ST_MakeEnvelope(x1, y1, x2, y2), District.geom)).all()

    fc = FeatureCollection([Feature(geometry=wkt.loads(x[-1]), properties={'id': str(x[0]),
                                                                           'state': get_state(x[1]),
                                                                           'stateabbr': get_state_abbr(x[1]),
                                                                           'statefp': x[1],
                                                                           'cd114fp': x[2],
                                                                           'geoid': x[3],
                                                                           'namelsad': x[4]}) for x in
                            bounded_districts])
    return json.dumps(fc)
Ejemplo n.º 46
0
def cdistrict_bbox():
    bbox = request.args.get('bbox')
    zoom = request.args.get('zoom')
    simplify = get_simplify_factor(zoom)
    bounds = [float(x) for x in bbox.split(',')]
    districts = g.c.execute(
        'SELECT id, statefp, cd114fp, geoid, namelsad, ST_AsText(ST_Simplify(geom, %s)) from districts WHERE ST_MakeEnvelope(%s,%s,%s,%s) && geom',
        [simplify] + bounds)
    districts = g.c.fetchall()
    fc = FeatureCollection([Feature(geometry=wkt.loads(x[-1]), properties={'id': str(x[0]),
                                                                           'state': get_state(x[1]),
                                                                           'stateabbr': get_state_abbr(x[1]),
                                                                           'statefp': x[1],
                                                                           'cd114fp': x[2],
                                                                           'geoid': x[3],
                                                                           'namelsad': x[4]}) for x in districts])
    return json.dumps(fc)
Ejemplo n.º 47
0
    def from_wkt(cls, s):
        """
        Parse a Polygon geometry from a wkt string and return a new Polygon object.
        """
        try:
            geom = wkt.loads(s)
        except ValueError:
            raise ValueError("Invalid WKT geometry: '{0}'".format(s))

        if geom['type'] != 'Polygon':
            raise ValueError("Invalid WKT geometry type. Expected 'Polygon', got '{0}': '{1}'".format(geom['type'], s))

        coords = geom['coordinates']
        exterior = coords[0] if len(coords) > 0 else tuple()
        interiors = coords[1:] if len(coords) > 1 else None

        return Polygon(exterior=exterior, interiors=interiors)
Ejemplo n.º 48
0
 def test_2d_srid2666(self):
     poly = (
         'SRID=2666;POLYGON ((100.001 0.001, 101.001 0.001, 101.001 1.001, '
         '100.001 0.001), '
         '(100.201 0.201, 100.801 0.201, 100.801 0.801, '
         '100.201 0.201))')
     expected = dict(
         type='Polygon',
         coordinates=[
             [[100.001, 0.001], [101.001, 0.001], [101.001, 1.001],
              [100.001, 0.001]],
             [[100.201, 0.201], [100.801, 0.201], [100.801, 0.801],
              [100.201, 0.201]],
         ],
         meta=dict(srid=2666),
     )
     self.assertEqual(expected, wkt.loads(poly))
Ejemplo n.º 49
0
    def aggregate_query(self,
                        searchAreaWkt,
                        agg_def,
                        query=None,
                        start_date=None,
                        end_date=None,
                        count=10,
                        index=default_index):
        """Aggregates results of a query into buckets defined by the 'agg_def' parameter.  The aggregations are
        represented by dicts containing a 'name' key and a 'terms' key holding a list of the aggregation buckets.
        Each bucket element is a dict containing a 'term' key containing the term used for this bucket, a 'count' key
        containing the count of items that match this bucket, and an 'aggregations' key containing any child
        aggregations.

        Args:
            searchAreaWkt (str): wkt representation of the geometry
            agg_def (str or AggregationDef): the aggregation definitions
            query (str): a valid Elasticsearch query string to constrain the items going into the aggregation
            start_date (str): either an ISO-8601 date string or a 'now' expression (e.g. "now-6d" or just "now")
            end_date (str): either an ISO-8601 date string or a 'now' expression (e.g. "now-6d" or just "now")
            count (int): the number of buckets to include in the aggregations (the top N will be returned)
            index (str): the index (or alias or wildcard index expression) to run aggregations against, set to None for the entire set of vector indexes

        Returns:
            results (list): A (usually single-element) list of dict objects containing the aggregation results.
        """

        geojson = wkt2geojson.loads(searchAreaWkt)
        aggs_str = str(agg_def)  # could be string or AggregationDef

        params = {"count": count, "aggs": aggs_str}

        if query:
            params['query'] = query
        if start_date:
            params['start_date'] = start_date
        if end_date:
            params['end_date'] = end_date

        url = self.aggregations_by_index_url % index if index else self.aggregations_url

        r = self.gbdx_connection.post(url, params=params, json=geojson)
        r.raise_for_status()

        return r.json(object_pairs_hook=OrderedDict)['aggregations']
Ejemplo n.º 50
0
 def user_grids(self):
     if len(self._grids) < 1:
         gridnames = set(self.df_adhoc["GridName"].unique().tolist() +
                         self.df_cameratrap["GridName"].unique().tolist() +
                         self.df_signsurvey["GridName"].unique().tolist())
         for gridname in gridnames:
             gridcells_query = (
                 f"SELECT CI_GridCellCode, Geom.STAsText() AS geom "
                 f"FROM CI_GridCell gc "
                 f"INNER JOIN CI_Grid g ON (gc.CI_GridID = g.CI_GridID) "
                 f"WHERE g.CI_GridName = '{gridname}' "
                 f"ORDER BY CI_GridCellCode")
             df_gridcells = pd.read_sql(gridcells_query, self.obsconn)
             gridcells_list = df_gridcells.values.tolist()
             self._grids[gridname] = [(wkt.loads(g[1]), {
                 self.CELL_LABEL: g[0]
             }) for g in gridcells_list]
     return self._grids
Ejemplo n.º 51
0
    def test_all_types_empty(self):
        gc = 'GEOMETRYCOLLECTION (%s)' % ','.join(
            '%s EMPTY' % typ for typ in sorted(
                wkt._type_map_caps_to_mixed.keys()))

        expected = {
            'type': 'GeometryCollection',
            'geometries': [
                {'geometries': [], 'type': 'GeometryCollection'},
                {'coordinates': [], 'type': 'LineString'},
                {'coordinates': [], 'type': 'MultiLineString'},
                {'coordinates': [], 'type': 'MultiPoint'},
                {'coordinates': [], 'type': 'MultiPolygon'},
                {'coordinates': [], 'type': 'Point'},
                {'coordinates': [], 'type': 'Polygon'}
            ]
        }
        self.assertEqual(expected, wkt.loads(gc))
Ejemplo n.º 52
0
 def search_optimal_geo_point(self, start_point, items):
     optimal_point = None
     optimal_time = None
     metadata = None
     for item in items:
         item_point = wkt.loads(item['geometry']['selection'])
         walking_time = math.pi * self.estimate_walking_time(start_point, item_point)
         if (optimal_time is None or math.fabs(optimal_time - self.OPTIMAL_WALK_TIME) >
             math.fabs(walking_time - self.OPTIMAL_WALK_TIME)):
             optimal_time = walking_time
             optimal_point = item_point
             metadata = item
     position = optimal_point['coordinates']
     metadata['point'] = {
         'longitude': position[0],
         'latitude': position[1]
     }
     return optimal_point, metadata
Ejemplo n.º 53
0
 def test_2d_srid2666(self):
     poly = (
         'SRID=2666;POLYGON ((100.001 0.001, 101.001 0.001, 101.001 1.001, '
         '100.001 0.001), '
         '(100.201 0.201, 100.801 0.201, 100.801 0.801, '
         '100.201 0.201))'
     )
     expected = dict(
         type='Polygon',
         coordinates=[
             [[100.001, 0.001], [101.001, 0.001], [101.001, 1.001],
              [100.001, 0.001]],
             [[100.201, 0.201], [100.801, 0.201], [100.801, 0.801],
              [100.201, 0.201]],
         ],
         meta=dict(srid=2666),
     )
     self.assertEqual(expected, wkt.loads(poly))
Ejemplo n.º 54
0
def wkt_to_segment_list(_wkt):

    segment_list = []

    geom_json = wkt.loads(_wkt)
    #geom_json = wkt.loads('POLYGON ((35 10, 45 45, 15 40, 10 20, 35 10), (20 30, 35 35, 30 20, 20 30))')
    #wkt.dumps(geom_json, decimals=6)
    #print(geom_json)

    geometry_type = geom_json['type']
    if geometry_type != "Polygon":
        print('Only Polygon is supported.')
        return []

    coordinates = geom_json['coordinates']
    #print(coordinates)

    for i in range(0, len(coordinates)):
        values = coordinates[i]
        #print(values)
        # Face.
        if i == 0:

            for j in range(0, len(values) - 1):
                # Close the segment list.
                if (j == len(values) - 2):
                    segment_list.append((tuple(values[j]), tuple(values[0])))
                else:
                    segment_list.append(
                        (tuple(values[j]), tuple(values[j + 1])))

        # Holes.
        else:
            """
            for j in range(0, len(values) - 1):
                # Close the segment list.
                if (j == len(values) - 2):
                    segment_list.append((tuple(values[j]), tuple(values[0])))
                else:
                    segment_list.append((tuple(values[j]), tuple(values[j+1])))
            """

    #print(segment_list)
    return segment_list
Ejemplo n.º 55
0
def translate(text, output_format='json', indent=None, precision=-1):
    if text.startswith('{'):
        geom = json.loads(text)
    elif text.startswith(('G', 'L', 'M', 'P')):
        geom = wkt.loads(text)
    else:
        geom = wkb.loads(a2b_hex(text))
    if output_format == 'wkb':
        output = b2a_hex(wkb.dumps(geom))
    elif output_format == 'wkt':
        kwds = {}
        if precision >= 0:
            kwds['decimals'] = precision
        output = wkt.dumps(geom, **kwds)
    else:
        if precision >= 0:
            geom = util.round_geom(geom, precision)
        output = json.dumps(geom, indent=indent, sort_keys=True)
    return output
Ejemplo n.º 56
0
 def build_route(self, points, alternative=0):
     query_points = self.points_to_query(points)
     response = self.api.transport.calculate_directions(
         waypoints=query_points,
         edge_filter='pedestrian',
         alternative=alternative,
     )
     if response['meta']['code'] != 200:
         raise ValidationError(response)
     legs = response['result']['items'][0]['legs']
     linestrings = []
     for leg in legs:
         for step in leg['steps']:
             for edge in step['edges']:
                 linestrings.append(wkt.loads(edge['geometry']['selection']))
     # Первое и последнее ребро - это отметки нулевой длины
     final_linestring_positions = []
     for linestring in linestrings[:-1]:
         final_linestring_positions.extend(linestring['coordinates'][1:])
     return LineString(tuple(final_linestring_positions))
Ejemplo n.º 57
0
    def test_with_empty_component(self):
        # Example from https://github.com/geomet/geomet/issues/49
        gc = 'GEOMETRYCOLLECTION (POLYGON((27 25,102 36,102 46,92 61,13 41,16 30,27 25)),LINESTRING EMPTY)'

        expected = {
            'type':
            'GeometryCollection',
            'geometries': [{
                'type':
                'Polygon',
                'coordinates': [[[27.0, 25.0], [102.0, 36.0], [102.0, 46.0],
                                 [92.0, 61.0], [13.0, 41.0], [16.0, 30.0],
                                 [27.0, 25.0]]]
            }, {
                'type': 'LineString',
                'coordinates': []
            }]
        }

        self.assertEqual(expected, wkt.loads(gc))
Ejemplo n.º 58
0
    def from_wkt(cls, s):
        """
        Parse a Point geometry from a wkt string and return a new Point object.
        """
        try:
            geom = wkt.loads(s)
        except ValueError:
            raise ValueError("Invalid WKT geometry: '{0}'".format(s))

        if geom['type'] != 'Point':
            raise ValueError("Invalid WKT geometry type. Expected 'Point', got '{0}': '{1}'".format(geom['type'], s))

        coords = geom['coordinates']
        if len(coords) < 2:
            x = y = _nan
        else:
            x = coords[0]
            y = coords[1]

        return Point(x=x, y=y)
Ejemplo n.º 59
0
def get_poly_arr(im_id, summeryData_path, im_id_prefix='AOI_5_Khartoum_img'):
    '''
    Get pixel coords of polygon vertices for image with id im_id.  Return as list.
    Requires image ids have prefix given by im_id_prefix.
    :param im_id: string of the integer id of image.
    :param summeryData_path: path to csv file containing polygon vertex information.
    :param im_id_prefix: prefix of field 'image_id' in summaryData csv file.
    :return: array of polygon vertices in units of pixels.
    '''
    # read as dataframe, extract wkt pixels for the desired im_id
    df = pd.read_csv(summeryData_path)
    df = df.loc[df['ImageId'] == im_id_prefix + im_id]['PolygonWKT_Pix']
    # convert coords to list
    patches = []
    if df.values[0] != 'POLYGON EMPTY':
        # if no ground truth polygons in image, return empty
        for wkt_poly in df:
            lst_poly = np.array(wkt.loads(wkt_poly)['coordinates'][0])
            lst_poly = lst_poly[:, 0:2]
            patches.append(lst_poly.astype(int))
    return patches