Debian Codegraph @

gavo/formats/geojson.py

raw
1 """
2 Generating geojson (RFC 7946) files.
3
4 This requires annotation with the geojson (DaCHS-private) data model.
5
6 See separate documentation in the reference documentation.
7
8 No streaming is forseen for this format for now; whatever a web browser
9 can cope with, we can, too. I hope.
10
11 To add more geometry types, pick a type name (typically different
12 from what geojson calls the thing because it also depends on the input),
13 add it to _FEATURE_MAKERS and write the Factory, taking _getSepcooFactory as
14 a model.
15 """
16
17 #c Copyright 2008-2025, the GAVO project <[email protected]>
18 #c
19 #c This program is free software, covered by the GNU GPL. See the
20 #c COPYING file in the source distribution.
21
22
23 import codecs
24 import json
25
26 from gavo import base
27 from gavo.formats import common
28 from gavo.utils import serializers
29
30
31 # we need to protect some of our columns from being mapped (by giving
32 # them a magic attribute), hence a special MFRegistry
33
34 JSON_MF_REGISTRY = serializers.defaultMFRegistry.clone()
35 registerMF = JSON_MF_REGISTRY.registerFactory
36
37 def _rawMapperFactory(colDesc):
38 if hasattr(colDesc.original, "geojson_do_not_touch"):
39 return lambda val: val
40 registerMF(_rawMapperFactory)
41
42
43 def _makeCRS(gjAnnotation):
44 """returns a dictionary to add a geoJSON CRS structure from a DaCHS
45 annotation to a dictionary.
46 """
47 try:
48 rawCRS = gjAnnotation["crs"]
49 if rawCRS["type"]=="name":
50 return {"crs": {
51 "type": "name",
52 "properties": {
53 "name": rawCRS["properties"]["name"],
54 }
55 }
56 }
57
58 elif rawCRS["type"]=="link":
59 return {"crs": {
60 "type": "url",
61 "properties": {
62 "href": rawCRS["properties"]["href"],
63 "type": rawCRS["properties"]["type"],
64 }
65 }
66 }
67
68 else:
69 raise base.DataError("Unknown GeoJSON CRS type: %s"%rawCRS["type"])
70
71 except KeyError:
72 return {}
73
74
75 def _makeFeatureFactory(tableDef, skippedFields, geoFactory):
76 """returns a factory function for building geoJson features from
77 rowdicts.
78
79 skippedFields are not included in the properties (i.e., they're
80 what geometry is built from),, geoFactory is a function returning
81 the geometry itself, given a row.
82 """
83 propertiesFields = [f.name for f in tableDef.columns
84 if f.name not in skippedFields]
85
86 def buildFeature(row):
87 feature = geoFactory(row)
88 feature["properties"] = dict((n, row[n]) for n in propertiesFields)
89 return feature
90
91 return buildFeature
92
93
94 def _getGeometryFactory(tableDef, geometryAnnotation):
95 """returns a row factory for a geometry-valued column.
96
97 This expects a value key referencing a column typed either
98 spoint or spoly.
99 """
100 geoCol = geometryAnnotation["value"].value
101
102 if geoCol.type=="spoint":
103 def annMaker(row):
104 return {
105 "type": "Point",
106 "coordinates": list(row[geoCol.name].asCooPair())}
107 geoCol.geojson_do_not_touch = True
108
109 elif geoCol.type=="spoly":
110 def annMaker(row):
111 return {
112 "type": "Polygon",
113 "coordinates": [list(p) for p in
114 row[geoCol.name].asCooPairs()]}
115 geoCol.geojson_do_not_touch = True
116
117 else:
118 raise base.DataError("Cannot serialise %s-valued columns"
119 " with a 'geometry' geometry type (only spoint and spoly)")
120
121 return _makeFeatureFactory(tableDef, [geoCol.name], annMaker)
122
123
124 def _getSepsimplexFactory(tableDef, geometryAnnotation):
125 """returns a row factory for polygons specified with a min/max coordinate
126 range.
127
128 This expects c1min/max, c2min/max keys. It does not do anything special
129 if the simplex spans the stitching line.
130 """
131 c1min = geometryAnnotation["c1min"].value.name
132 c1max = geometryAnnotation["c1max"].value.name
133 c2min = geometryAnnotation["c2min"].value.name
134 c2max = geometryAnnotation["c2max"].value.name
135
136 return _makeFeatureFactory(tableDef,
137 [c1min, c2min, c1max, c2max],
138 lambda row: {
139 "type": "Polygon",
140 "coordinates": [
141 [row[c1min], row[c2min]],
142 [row[c1min], row[c2max]],
143 [row[c1max], row[c2max]],
144 [row[c1max], row[c2min]],
145 [row[c1min], row[c2min]]]})
146
147
148 def _getSeppolyFactory(tableDef, geometryAnnotation):
149 """returns a features factory for polygons made of separate
150 coordinates.
151
152 This expects cn_m keys; it will gooble them up until the first is not
153 found. m is either 1 or 2.
154 """
155 # hard code the assumption that these are column annotations for now
156 # -- make a type check if we may put in literals
157 cooIndex = 1
158 polyCoos, ignoredNames = [], set()
159 while True:
160 try:
161 polyCoos.append((
162 geometryAnnotation["c%d_1"%cooIndex].value.name,
163 geometryAnnotation["c%d_2"%cooIndex].value.name))
164 ignoredNames |= set(polyCoos[-1])
165 except KeyError:
166 break
167 cooIndex += 1
168 polyCoos.append(polyCoos[0])
169
170 return _makeFeatureFactory(tableDef,
171 ignoredNames,
172 lambda row: {
173 "type": "Polygon",
174 "coordinates": [[row[name1], row[name2]]
175 for name1, name2 in polyCoos]})
176
177
178 def _getSepcooFactory(tableDef, geometryAnnotation):
179 """returns a features factory for points made up of separate coordinates.
180
181 This expects latitude and longitude keys.
182 """
183 # hard code the assumption that these are column annotations for now
184 # -- make a type check if we may put in literals
185 latCoo = geometryAnnotation["latitude"].value.name
186 longCoo = geometryAnnotation["longitude"].value.name
187 return _makeFeatureFactory(tableDef,
188 [latCoo, longCoo],
189 lambda row: {
190 "type": "Point",
191 "coordinates": [row[longCoo], row[latCoo]]})
192
193
194 # a dict mapping feature.geometry.type names to row factories dealing
195 # with them
196 _FEATURE_MAKERS = {
197 "sepcoo": _getSepcooFactory,
198 "seppoly": _getSeppolyFactory,
199 "sepsimplex": _getSepsimplexFactory,
200 "geometry": _getGeometryFactory,
201 }
202
203 def _makeFeatures(table, gjAnnotation):
204 """returns a list of geoJSON features from the (annotated) table.
205 """
206 geometryAnnotation = gjAnnotation["feature"]["geometry"]
207 try:
208 makeFeature = _FEATURE_MAKERS[
209 geometryAnnotation["type"]](
210 table.tableDef, geometryAnnotation)
211 except KeyError as msg:
212 raise base.ui.logOldExc(
213 base.DataError("Invalid geoJSON annotation on table %s: %s missing"%(
214 table.tableDef.id, msg)))
215
216 sm = base.SerManager(table, acquireSamples=False,
217 mfRegistry=JSON_MF_REGISTRY)
218
219 # let geo builders manually ignore rows they can't do anything with
220 features = []
221 for r in sm.getMappedValues():
222 try:
223 features.append(makeFeature(r))
224 except base.SkipThis:
225 pass
226 return features
227
228 def writeTableAsGeoJSON(table, target, acquireSamples=False):
229 """writes a table as geojson.
230
231 This requires an annotation with geojson:FeatureCollection.
232 """
233 # for now, don't bother with complete data items, just serialise the
234 # primary table.
235 if hasattr(table, "getPrimaryTable"):
236 table = table.getPrimaryTable()
237
238 try:
239 ann = next(table.tableDef.iterAnnotationsOfType("geojson:FeatureCollection"
240 ))
241 except IndexError:
242 raise base.DataError("Table has no geojson:FeatureCollection annotation."
243 " Cannot serialise to GeoJSON.")
244
245 result = {
246 "type": "FeatureCollection",
247 "features": _makeFeatures(table, ann),
248 }
249 result.update(_makeCRS(ann))
250
251 # our targets are always binary; wrap them for json.dump
252 target = codecs.getwriter("utf-8")(target)
253 return json.dump(result, target)
254
255
256 # NOTE: while json could easily serialize full data elements,
257 # right now we're only writing single tables.
258 common.registerDataWriter("geojson",
259 writeTableAsGeoJSON, "application/geo+json", "GeoJSON", ".geojson")