forked from OpenTreeMap/otm-ecoservice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
454 lines (371 loc) · 9.9 KB
/
main.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//
// Todo
//
// * http://10.0.0.10:8080/eco.json?otmcode=ULAM&diameter=11®ion=LoMidWXXX
// negative natural gas?
// * support itree override table
//
package main
import (
"code.google.com/p/gcfg"
"errors"
"flag"
"fmt"
"github.com/azavea/ecobenefits/eco"
"github.com/ungerik/go-rest"
"log"
"net/url"
"os"
"runtime/pprof"
"strconv"
"time"
)
var (
cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
configpath = flag.String("configpath", "./", "path to the configuration")
)
type config struct {
Database eco.DBInfo
Data struct {
Path string
}
Server struct {
Host string
Port string
}
}
// We can't marshall maps directly with
// go-rest so we just wrap it here
type BenefitsWrapper struct {
Benefits map[string]float64
}
type SummaryPostData struct {
Region string
Query string
Instance_id string
}
type ScenarioTree struct {
Otmcode string
Species_id int
Region string
Diameters []float64
}
type ScenarioPostData struct {
Region string
Instance_id string
Years int
Scenario_trees []ScenarioTree
}
type Scenario struct {
Total map[string]float64
Years []map[string]float64
}
// Given a values list return the single value
// associated with a given key or an error
func getSingleValue(in url.Values, key string) (string, error) {
if keys, ok := in[key]; ok {
if len(keys) == 1 {
return keys[0], nil
}
}
return "", errors.New(
fmt.Sprintf("Missing or invalid %v parameter", key))
}
func getSingleIntValue(in url.Values, key string) (int, error) {
str, err := getSingleValue(in, key)
if err != nil {
return 0, err
}
intv, err := strconv.Atoi(str)
if err != nil {
return 0, err
}
return intv, nil
}
func main() {
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
var cfg config
err := gcfg.ReadFileInto(&cfg, *configpath)
if err != nil {
panic(err)
}
regiondata := eco.LoadFiles(cfg.Data.Path)
speciesdata, err := eco.LoadSpeciesMap(cfg.Data.Path + "/species.json")
if err != nil {
panic(err)
}
dbraw, err := eco.OpenDatabaseConnection(&cfg.Database)
if err != nil {
panic(err)
}
defer dbraw.Close()
db := (*eco.DBContext)(dbraw)
overrides, err := db.GetOverrideMap()
if err != nil {
panic(err)
}
eco.InitGeos()
regiongeometry, err := db.GetRegionGeoms()
if err != nil {
panic(err)
}
// This is implemented as an anonymous function so it can
// close over the variables set at the start of the main
// function, which can be expensive to load and only need to
// be loaded once.
getItreeCode := func(otmcode string, speciesId int, region string, instanceId int) (string, error) {
speciesDataForRegion, found := speciesdata[region]
if !found {
return "", errors.New(fmt.Sprintf("Species data not found for the %v region",
region))
}
itreeCode, foundItree := speciesDataForRegion[otmcode]
notFoundMessage := fmt.Sprintf("iTree code not found for otmcode %v in region %v",
otmcode, region)
overidesForInstance, found := overrides[instanceId]
if found {
overridesForRegion, found := overidesForInstance[region]
if found {
overrideCode, found := overridesForRegion[speciesId]
if found {
itreeCode = overrideCode
foundItree = true
} else {
notFoundMessage = fmt.Sprintf("There are overrides "+
"defined for instance %v in the %v region "+
"but not for species ID %v", instanceId, region, speciesId)
}
} else {
notFoundMessage = fmt.Sprintf("There are overrides defined for "+
"the instance, but not for the %v region", region)
}
}
// It is normal for an instance to not have any
// overrides defined, so there is no else block to set
// an error message in the not-found case.
if !foundItree {
return "", errors.New(notFoundMessage)
} else {
return itreeCode, nil
}
}
rest.HandleGET("/eco.json", func(in url.Values) (*BenefitsWrapper, error) {
instanceid, err := getSingleIntValue(in, "instanceid")
if err != nil {
return nil, err
}
speciesid, err := getSingleIntValue(in, "speciesid")
if err != nil {
return nil, err
}
otmcode, err := getSingleValue(in, "otmcode")
if err != nil {
return nil, err
}
diameterstr, err := getSingleValue(in, "diameter")
if err != nil {
return nil, err
}
diameter, err := strconv.ParseFloat(diameterstr, 64)
if err != nil {
return nil, err
}
diameter = diameter * eco.CentimetersPerInch
region, err := getSingleValue(in, "region")
if err != nil {
return nil, err
}
factorDataForRegion, found := regiondata[region]
if !found {
return nil, errors.New("invalid region")
}
itreecode, err := getItreeCode(otmcode, speciesid, region, instanceid)
if err != nil {
return nil, err
}
factorsum := make([]float64, len(eco.Factors))
eco.CalcOneTree(
factorDataForRegion,
itreecode,
diameter,
factorsum)
return &BenefitsWrapper{Benefits: eco.FactorArrayToMap(factorsum)}, nil
})
rest.HandlePOST("/eco_summary.json", func(data *SummaryPostData) (*BenefitsWrapper, error) {
query := data.Query
region := data.Region
instanceid, err := strconv.Atoi(data.Instance_id)
if err != nil {
return nil, err
}
now := time.Now()
// Using a fixed region lets us avoid costly
// hash lookups. While we don't yet cache this value, we should
// consider it since instance geometries change so rarely
var regions []eco.Region
if len(region) == 0 {
regions, err = db.GetRegionsForInstance(
regiongeometry, instanceid)
if err != nil {
return nil, err
}
if len(regions) == 1 {
region = regions[0].Code
}
}
// Contains the running total of the various factors
instanceOverrides := overrides[instanceid]
rows, err := db.ExecSql(query)
s := time.Since(now)
fmt.Println(int64(s/time.Millisecond), "ms (query)")
if err != nil {
return nil, err
}
factorsums, err :=
eco.CalcBenefitsWithData(
regions, rows, region,
speciesdata, regiondata, instanceOverrides)
s = time.Since(now)
fmt.Println(int64(s/time.Millisecond), "ms (total)")
if err != nil {
return nil, err
}
return &BenefitsWrapper{Benefits: factorsums}, nil
})
// Take an array of prospective trees where each tree contains
// an array of diamaters, one for each year the tree is alive,
// and return an array of eco calulations, one for each year
//
// Trees will die of as part of the scenario, so the
// `diameters` arrays for the trees may have different
// lengths. Trees that die may be replaced with other trees,
// so there will be trees that appear in the scenario at t >
// 0, so the `diameters` array may have initial elements set
// to 0.
//
// Specifying a "region" for an individual tree will override the
// scenario-level "region" value.
//
// The "years" parameter must be >= the length of the longest
// "diameters" array under "scenario_trees".
//
// Request (with bogus example parameters):
//
// POST /eco_scenario.json
//
// {
// "region": "NoEastXXX",
// "instance_id": 1,
// "years": 3
// "scenario_trees": [
// {
// "otmcode": "CACO",
// "species_id": 1,
// "region": "NoEastXXX",
// "diameters": [1, 1.3, 1.7]
// }
// ]
// }
//
// Response (with bogus example values):
//
// {
// "Years": [
// {
// "aq_nox_avoided": 0.01548490,
// "aq_nox_dep": 0.00771784,
// "aq_pm10_avoided": 0.00546863
// },
// {
// "aq_nox_avoided": 0.02548420,
// "aq_nox_dep": 0.01973722,
// "aq_pm10_avoided": 0.00676823
// },
// {
// "aq_nox_avoided": 0.05484902,
// "aq_nox_dep": 0.04774471,
// "aq_pm10_avoided": 0.00946822
// }
// ],
// "Total": {
// "aq_nox_avoided": ... ,
// "aq_nox_dep": ... ,
// "aq_pm10_avoided": ...
// }
// }
rest.HandlePOST("/eco_scenario.json", func(data *ScenarioPostData) (*Scenario, error) {
t := time.Now()
scenarioTrees := data.Scenario_trees
scenarioRegion := data.Region
instanceId, err := strconv.Atoi(data.Instance_id)
if err != nil {
return nil, err
}
if len(scenarioRegion) == 0 {
var regions []eco.Region
regions, err = db.GetRegionsForInstance(
regiongeometry, instanceId)
if err != nil {
return nil, err
}
if len(regions) == 1 {
scenarioRegion = regions[0].Code
}
}
yearTotals := make([][]float64, data.Years)
grandTotals := make([]float64, len(eco.Factors))
for i := range yearTotals {
yearTotals[i] = make([]float64, len(eco.Factors))
}
for _, tree := range scenarioTrees {
effectiveRegion := scenarioRegion
if len(tree.Region) != 0 {
effectiveRegion = tree.Region
}
factorDataForRegion, found := regiondata[effectiveRegion]
if !found {
return nil, errors.New("No data is available for the iTree region with code " + effectiveRegion)
}
itreecode, err := getItreeCode(tree.Otmcode,
tree.Species_id, effectiveRegion, instanceId)
if err != nil {
return nil, err
}
for i, diameter := range tree.Diameters {
factorSum := make([]float64, len(eco.Factors))
eco.CalcOneTree(
factorDataForRegion,
itreecode,
diameter,
factorSum)
for j, value := range factorSum {
yearTotals[i][j] = value
grandTotals[j] += value
}
}
}
// The requests are written to stdout like this:
// 2014/07/15 14:06:10 POST /eco_scenario.json
// Indenting the timing report aligns it with the http
// verb on the previous line.
fmt.Println(" ",
int64(time.Since(t)/time.Millisecond), "ms (total)")
years := make([]map[string]float64, data.Years)
for i, a := range yearTotals {
years[i] = eco.FactorArrayToMap(a)
}
return &Scenario{
Total: eco.FactorArrayToMap(grandTotals),
Years: years}, nil
})
rest.RunServer(
fmt.Sprintf("%v:%v", cfg.Server.Host, cfg.Server.Port), nil)
}