-
Notifications
You must be signed in to change notification settings - Fork 1
/
cityaq.go
executable file
·356 lines (326 loc) · 9.49 KB
/
cityaq.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package cityaq
import (
"context"
"encoding/json"
"fmt"
"math"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"sync"
rpc "github.com/ctessum/cityaq/cityaqrpc"
"github.com/ctessum/geom"
"github.com/ctessum/geom/encoding/geojson"
"github.com/ctessum/geom/index/rtree"
"github.com/ctessum/requestcache/v4"
"github.com/spatialmodel/inmap/cloud"
"github.com/spatialmodel/inmap/emissions/aep/aeputil"
)
// CityAQ estimates the air quality impacts of activities in cities.
type CityAQ struct {
// CityGeomDir is the location of the directory that holds the
// GeoJSON geometries of cities.
CityGeomDir string
aeputil.SpatialConfig
// Location where temporary results should be stored.
CacheLoc string
inmapClient *cloud.Client
// InMAPCityMarginalConfigFile specifies the path to the file with InMAP
// configuration information for city marginal simulations.
InMAPCityMarginalConfigFile string
// InMAPCityTotalConfigFile specifies the path to the file with InMAP
// configuration information for a city-specific total-concentration simulation.
InMAPCityTotalConfigFile string
// InMAPTotalConfigFile specifies the path to the file with InMAP
// configuration information for a total-concentration simulation.
InMAPTotalConfigFile string
// Version specifies the version of the InMAP Docker image that should be
// used for running simulations, for example "latest" or "v1.7.2".
Version string
// cityPaths holds the locations of the files containing the
// boundaries of each city.
cityPaths map[string]string
loadCityPathsOnce sync.Once
countries *rtree.Rtree
loadCountriesOnce sync.Once
cloudSetupOnce sync.Once
cacheSetupOnce sync.Once
cache *requestcache.Cache
}
// Cities returns the files in the CityGeomDir directory field of the receiver.
func (c *CityAQ) Cities(ctx context.Context, _ *rpc.CitiesRequest) (*rpc.CitiesResponse, error) {
c.cityPaths = make(map[string]string)
r := new(rpc.CitiesResponse)
err := filepath.Walk(os.ExpandEnv(c.CityGeomDir), func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() || filepath.Ext(path) != ".geojson" {
return nil
}
name, err := c.geojsonName(path, "en")
if err != nil {
return err
}
r.Names = append(r.Names, name)
c.cityPaths[name] = path
return nil
})
sort.Strings(r.Names)
return r, err
}
func (c *CityAQ) loadCityPaths() {
c.loadCityPathsOnce.Do(func() {
if c.cityPaths == nil {
_, err := c.Cities(context.Background(), nil)
if err != nil {
panic(err)
}
}
})
}
func (c *CityAQ) setupCache() {
c.cacheSetupOnce.Do(func() {
d := requestcache.Deduplicate()
m := requestcache.Memory(20)
if c.CacheLoc == "" {
c.cache = requestcache.NewCache(d, m)
} else if strings.HasPrefix(c.CacheLoc, "gs://") {
loc, err := url.Parse(c.CacheLoc)
if err != nil {
panic(err)
}
cf, err := requestcache.GoogleCloudStorage(context.TODO(), loc.Host,
strings.TrimLeft(loc.Path, "/"))
if err != nil {
panic(err)
}
c.cache = requestcache.NewCache(d, m, cf)
} else {
c.cache = requestcache.NewCache(d, m,
requestcache.Disk(strings.TrimPrefix(c.CacheLoc, "file://")))
}
})
}
// CityGeometry returns the geometry of the requested city.
func (c *CityAQ) CityGeometry(ctx context.Context, req *rpc.CityGeometryRequest) (*rpc.CityGeometryResponse, error) {
polys, err := c.geojsonGeometry(req.CityName)
if err != nil {
return nil, err
}
o := &rpc.CityGeometryResponse{
Polygons: polygonsToRPC([]geom.Polygon{polys}),
}
return o, err
}
func polygonalsToRPC(polys []geom.Polygonal) []*rpc.Polygon {
o := make([]*rpc.Polygon, len(polys))
for i, poly := range polys {
o[i] = new(rpc.Polygon)
o[i].Paths = make([]*rpc.Path, len(poly.(geom.Polygon)))
for j, path := range poly.(geom.Polygon) {
o[i].Paths[j] = new(rpc.Path)
o[i].Paths[j].Points = make([]*rpc.Point, len(path))
for k, pt := range path {
o[i].Paths[j].Points[k] = &rpc.Point{X: pt.X, Y: pt.Y}
}
}
}
return o
}
func polygonsToRPC(polys []geom.Polygon) []*rpc.Polygon {
o := make([]*rpc.Polygon, len(polys))
for i, poly := range polys {
o[i] = new(rpc.Polygon)
o[i].Paths = make([]*rpc.Path, len(poly))
for j, path := range poly {
o[i].Paths[j] = new(rpc.Path)
o[i].Paths[j].Points = make([]*rpc.Point, len(path))
for k, pt := range path {
o[i].Paths[j].Points[k] = &rpc.Point{X: pt.X, Y: pt.Y}
}
}
}
return o
}
// geojsonGeometry returns the geometry of the requested geojson file.
func (c *CityAQ) geojsonGeometry(cityName string) (geom.Polygon, error) {
type gj struct {
Type string `json:"type"`
Features []struct {
Type string `json:"type"`
Geometry geojson.Geometry `json:"geometry"`
} `json:"features"`
}
c.loadCityPaths()
path, ok := c.cityPaths[cityName]
if !ok {
return nil, fmt.Errorf("invalid city name %s", cityName)
}
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("opening city geojson file: %v", err)
}
dec := json.NewDecoder(f)
var data gj
if err := dec.Decode(&data); err != nil {
return nil, err
}
var polys geom.Polygon
for _, ft := range data.Features {
g, err := geojson.FromGeoJSON(&ft.Geometry)
if err != nil {
return nil, err
}
switch g.(type) {
case geom.Polygon:
polys = append(polys, g.(geom.Polygon)...)
case geom.MultiPolygon:
for _, poly := range g.(geom.MultiPolygon) {
polys = append(polys, poly...)
}
}
}
return polys, nil
}
// geojsonName returns a city name (in the requested language)
// from a GeoJSON file. (Language doesn't currently do anything)
func (c *CityAQ) geojsonName(path, _ string) (string, error) {
type gj interface{}
f, err := os.Open(path)
if err != nil {
return "", err
}
dec := json.NewDecoder(f)
var data gj
if err := dec.Decode(&data); err != nil {
return "", fmt.Errorf("file %s: %v", path, err)
}
features := data.(map[string]interface{})["features"].([]interface{})
for _, feat := range features {
featmap, ok := feat.(map[string]interface{})
if !ok {
continue
}
props, ok := featmap["properties"]
if !ok {
continue
}
propmap, ok := props.(map[string]interface{})
if !ok {
continue
}
name, ok := propmap["c40_city_name"]
if !ok {
name, ok = propmap["name"]
if !ok {
return "", fmt.Errorf("file %s, missing name", path)
}
}
return name.(string), nil
}
return "", fmt.Errorf("couldn't find name in %v", data)
}
// emissionsGrid returns the grid to be used for mapping gridded information about the requested city.
// dx is grid cell edge length in degrees.
func (c *CityAQ) emissionsGrid(cityName, sourceType string, dx float64) ([]geom.Polygonal, error) {
if dx <= 0 {
return nil, fmt.Errorf("cityaq: emissions grid dx must be >0 but is %g", dx)
}
polygon, err := c.geojsonGeometry(cityName)
if err != nil {
return nil, err
}
if egugridEmissions(sourceType) {
// Use EGU grid geometry instead of city.
country, err := c.countryOrGridBuffer(cityName)
if err != nil {
return nil, err
}
polygon = country.Polygon
}
b := polygon.Bounds()
if b.Min.X >= b.Max.X || b.Min.Y >= b.Max.Y {
return nil, fmt.Errorf("invalid emissionsGrid bounding box (%+v) for %s %s", b, cityName, sourceType)
}
var o []geom.Polygonal
const bufferFrac = 0.1
buffer := math.Sqrt((b.Max.X-b.Min.X)*(b.Max.Y-b.Min.Y)) * bufferFrac
b.Min.X -= buffer
b.Min.Y -= buffer
b.Max.X += buffer
b.Max.Y += buffer
b.Min.X = roundUnit(b.Min.X, dx)
b.Min.Y = roundUnit(b.Min.Y, dx)
b.Max.X = roundUnit(b.Max.X+dx/2, dx) // Round the max values up.
b.Max.Y = roundUnit(b.Max.Y+dx/2, dx) // Round the max values up.
for y := b.Min.Y; y < b.Max.Y+dx; y += dx {
for x := b.Min.X; x < b.Max.X+dx; x += dx {
o = append(o, geom.Polygon{
{
{X: x, Y: y}, {X: x + dx, Y: y}, {X: x + dx, Y: y + dx}, {X: x, Y: y + dx},
},
})
}
}
return o, nil
}
// EmissionsGridBounds returns the bounds of the grid to be used for
// mapping gridded information about the requested city.
func (c *CityAQ) EmissionsGridBounds(ctx context.Context, req *rpc.EmissionsGridBoundsRequest) (*rpc.EmissionsGridBoundsResponse, error) {
o, err := c.emissionsGrid(req.CityName, req.SourceType, mapResolution(req.SourceType, req.CityName))
if err != nil {
return nil, err
}
b := geom.NewBounds()
for _, g := range o {
b.Extend(g.Bounds())
}
return &rpc.EmissionsGridBoundsResponse{
Min: &rpc.Point{X: b.Min.X, Y: b.Min.Y},
Max: &rpc.Point{X: b.Max.X, Y: b.Max.Y},
}, nil
}
// MapScale returns statistics about map data.
func (c *CityAQ) MapScale(ctx context.Context, req *rpc.MapScaleRequest) (*rpc.MapScaleResponse, error) {
var data []float64
switch req.ImpactType {
case rpc.ImpactType_Emissions:
response, err := c.GriddedEmissions(ctx, &rpc.GriddedEmissionsRequest{
CityName: req.CityName,
Emission: req.Emission,
SourceType: req.SourceType,
})
if err != nil {
return nil, err
}
data = response.Emissions
case rpc.ImpactType_Concentrations:
response, err := c.GriddedConcentrations(ctx, &rpc.GriddedConcentrationsRequest{
CityName: req.CityName,
Emission: req.Emission,
SourceType: req.SourceType,
SimulationType: req.SimulationType,
})
if err != nil {
return nil, err
}
data = response.Concentrations
default:
return nil, fmt.Errorf("invalid impact type %s", req.ImpactType.String())
}
min, max := math.Inf(1), math.Inf(-1)
for _, e := range data {
if e < min {
min = e
}
if e > max {
max = e
}
}
max += max * 0.0001
min -= min * 0.0001
return &rpc.MapScaleResponse{Min: min, Max: max}, nil
}