-
-
Notifications
You must be signed in to change notification settings - Fork 83
/
index.js
1762 lines (1624 loc) · 58.2 KB
/
index.js
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const exec = require('child_process').exec
const fs = require('fs')
const path = require('path')
const stream = require('stream')
const { promisify } = require('util')
const area = require('@mapbox/geojson-area')
const geojsonhint = require('@mapbox/geojsonhint')
const time = require('@tubular/time')
const bbox = require('@turf/bbox').default
const helpers = require('@turf/helpers')
const multiPolygon = helpers.multiPolygon
const polygon = helpers.polygon
const asynclib = require('async')
const got = require('got')
const hasha = require('hasha')
const jsts = require('jsts')
const cloneDeep = require('lodash.clonedeep')
const memoize = require('lodash.memoize')
const hash = require('object-hash')
const rimraf = require('rimraf')
const overpass = require('query-overpass')
const yargs = require('yargs')
const FeatureWriterStream = require('./util/featureWriterStream')
const ProgressStats = require('./util/progressStats')
const { FileCache, FileLookupCache } = require('./util/cache')
let osmBoundarySources = require('./osmBoundarySources.json')
let zoneCfg = require('./timezones.json')
let zoneCfg1970 = {}
let zoneCfgNow = {}
const expectedZoneOverlaps = require('./expectedZoneOverlaps.json')
const argv = yargs
.option('cache_dir', {
description: 'Set the cache location, for caching results',
default: './cache',
type: 'string'
})
.option('dist_dir', {
description: 'Set the dist location, for the generated release files',
default: './dist',
type: 'string'
})
.option('downloads_dir', {
description: 'Set the download location for features from OpenStreetMap',
default: './downloads',
type: 'string'
})
.option('excluded_zones', {
description: 'Exclude specified zones',
type: 'array'
})
.option('included_zones', {
description: 'Include specified zones',
type: 'array'
})
.option('skip_1970_zones', {
description: 'Skip creation of zones that are the same since 1970',
type: 'boolean'
})
.option('skip_now_zones', {
description: 'Skip creation of zones that are the same since now',
type: 'boolean'
})
.option('skip_analyze_diffs', {
description: 'Skip analysis of diffs between versions',
type: 'boolean'
})
.option('skip_analyze_osm_tz_diffs', {
description: 'Skip analysis of diffs between timezone-boundary-builder output and raw OSM timezone relations',
type: 'boolean'
})
.option('skip_shapefile', {
description: 'Skip shapefile creation',
type: 'boolean'
})
.option('skip_validation', {
description: 'Skip validation',
type: 'boolean'
})
.option('skip_zip', {
description: 'Skip zip creation',
type: 'boolean'
})
.option('working_dir', {
description: 'Set the working files location for temporary / intermediate files',
default: './working',
type: 'string'
})
.help()
.strict()
.alias('help', 'h')
.argv
// Resolve the arguments with paths so relative paths become absolute.
const cacheDir = path.resolve(argv.cache_dir)
const downloadsDir = path.resolve(argv.downloads_dir)
const distDir = path.resolve(argv.dist_dir)
const workingDir = path.resolve(argv.working_dir)
const osmDownloadDir = path.join(workingDir, 'osm-downloads')
function hashMd5 (obj) {
if (!obj) return 'non-object'
return hash(obj, { algorithm: 'md5' })
}
function loadJsonCacheSync (filename) {
try {
return JSON.parse(
fs.readFileSync(filename, { encoding: 'utf-8' })
)
} catch (err) {
// cache not found, return empty obj
return {}
}
}
function writeJsonSync (filename, json) {
fs.writeFileSync(filename, JSON.stringify(json))
}
function getTimezonePopulation (zone) {
// return 0 if the timezone is an alias so it doesn't conflict with larger zones
const zoneData = time.Timezone.from(zone)
return zoneData.aliasFor ? 0 : zoneData.population
}
let tzdbInitialized = false
function getZoneCfgSinceTime (cutoffTime, cacheFilename) {
// load cache and return immediately if it exists
const cachedConfig = loadJsonCacheSync(cacheFilename)
if (Object.keys(cachedConfig).length > 0) {
return cachedConfig
}
if (!tzdbInitialized) {
// initialize the tubular time to make sure it has all the latest zones
time.initTimezoneLarge()
tzdbInitialized = true
}
const newZoneCfg = {}
// Iterate through all zones to determine which share same timekeeping method since cutoff time
const timekeepingPatternZones = {}
Object.keys(zoneCfg).forEach(zone => {
// calculate which offset pattern this zone follows and add it to list
const timezoneInstance = time.Timezone.from(zone)
const currentZoneOffset = timezoneInstance.getOffsetForWallTime(timezoneInstance)
let timekeepingKey = `${currentZoneOffset}`
const transitions = timezoneInstance.getAllTransitions()
if (transitions) {
// timezone with transitions between daylight savings and standard time since cutoff time
const futureTransitionsHash = hashMd5(transitions.filter(t => t.transitionTime > cutoffTime))
timekeepingKey = `${currentZoneOffset}-${futureTransitionsHash}`
}
if (!timekeepingPatternZones[timekeepingKey]) {
timekeepingPatternZones[timekeepingKey] = []
}
timekeepingPatternZones[timekeepingKey].push(zone)
})
// iterate through each set of zones with the same future timekeeping method to determine
// which has the largest population
Object.keys(timekeepingPatternZones).forEach(k => {
timekeepingPatternZones[k].sort((a, b) => getTimezonePopulation(b) - getTimezonePopulation(a))
newZoneCfg[timekeepingPatternZones[k][0]] = timekeepingPatternZones[k]
})
writeJsonSync(cacheFilename, newZoneCfg)
return newZoneCfg
}
if (!argv.skip_now_zones) {
console.log('Generating zone config for zones with the same timekeeping method since now')
zoneCfgNow = getZoneCfgSinceTime(
(new Date()).getTime(),
path.join(cacheDir, 'zone-config-now.json')
)
}
if (!argv.skip_1970_zones) {
console.log('Generating zone config for zones with the same timekeeping method since 1970')
zoneCfg1970 = getZoneCfgSinceTime(
0,
path.join(cacheDir, 'zone-config-1970.json')
)
}
// allow building of only a specified zones
let includedZones = []
let excludedZones = []
if (argv.included_zones || argv.excluded_zones) {
if (argv.included_zones) {
const newZoneCfg = {}
const newZoneCfg1970 = {}
const newZoneCfgNow = {}
includedZones = argv.included_zones
includedZones.forEach((zoneName) => {
if (
!zoneCfg[zoneName] ||
(!argv.skip_1970_zones && !zoneCfg1970[zoneName]) ||
(!argv.skip_now_zones && !zoneCfgNow[zoneName])
) {
console.error(`${zoneName} is not a valid timezone identifier!`)
process.exit(1)
}
newZoneCfg[zoneName] = zoneCfg[zoneName]
newZoneCfg1970[zoneName] = zoneCfg1970[zoneName]
newZoneCfgNow[zoneName] = zoneCfgNow[zoneName]
})
zoneCfg = newZoneCfg
zoneCfg1970 = newZoneCfg1970
zoneCfgNow = newZoneCfgNow
}
if (argv.excluded_zones) {
const newZoneCfg = {}
const newZoneCfg1970 = {}
const newZoneCfgNow = {}
excludedZones = argv.excluded_zones
Object.keys(zoneCfg).forEach((zoneName) => {
if (
!zoneCfg[zoneName] ||
(!argv.skip_1970_zones && !zoneCfg1970[zoneName]) ||
(!argv.skip_now_zones && !zoneCfgNow[zoneName])
) {
console.error(`${zoneName} is not a valid timezone identifier!`)
process.exit(1)
}
if (!excludedZones.includes(zoneName)) {
newZoneCfg[zoneName] = zoneCfg[zoneName]
newZoneCfg1970[zoneName] = zoneCfg1970[zoneName]
newZoneCfgNow[zoneName] = zoneCfgNow[zoneName]
}
})
zoneCfg = newZoneCfg
zoneCfg1970 = newZoneCfg1970
zoneCfgNow = newZoneCfgNow
}
// filter out unneccessary downloads
const newOsmBoundarySources = {}
Object.keys(zoneCfg).forEach((zoneName) => {
zoneCfg[zoneName].forEach((op) => {
if (op.source === 'overpass') {
newOsmBoundarySources[op.id] = osmBoundarySources[op.id]
}
})
})
osmBoundarySources = newOsmBoundarySources
}
const geoJsonReader = new jsts.io.GeoJSONReader()
const geoJsonWriter = new jsts.io.GeoJSONWriter()
const precisionModel = new jsts.geom.PrecisionModel(1000000)
const precisionReducer = new jsts.precision.GeometryPrecisionReducer(precisionModel)
const finalZones = {}
const final1970Zones = {}
const finalNowZones = {}
let lastReleaseName
let lastReleaseJSONfile
const minRequestGap = 8
let curRequestGap = 8
const bufferDistance = 0.01
function safeMkdir (dirname, callback) {
fs.mkdir(dirname, function (err) {
if (err && err.code === 'EEXIST') {
callback()
} else {
callback(err)
}
})
}
function debugGeo (
op,
a,
b,
reducePrecision,
bufferAfterPrecisionReduction
) {
let result
if (reducePrecision) {
a = precisionReducer.reduce(a)
b = precisionReducer.reduce(b)
}
try {
switch (op) {
case 'union':
result = a.union(b)
break
case 'intersection':
result = a.intersection(b)
break
case 'intersects':
result = a.intersects(b)
break
case 'diff':
result = a.difference(b)
break
default:
throw new Error('invalid op: ' + op)
}
} catch (e) {
if (e.name === 'TopologyException') {
if (reducePrecision) {
if (bufferAfterPrecisionReduction) {
console.log('Encountered TopologyException, retry with buffer increase')
return debugGeo(
op,
a.buffer(bufferDistance),
b.buffer(bufferDistance),
true,
bufferAfterPrecisionReduction
)
} else {
throw new Error('Encountered TopologyException after reducing precision')
}
} else {
console.log('Encountered TopologyException, retry with GeometryPrecisionReducer')
return debugGeo(op, a, b, true, bufferAfterPrecisionReduction)
}
}
console.log('op err')
console.log(e)
console.log(e.stack)
fs.writeFileSync('debug_' + op + '_a.json', JSON.stringify(geoJsonWriter.write(a)))
fs.writeFileSync('debug_' + op + '_b.json', JSON.stringify(geoJsonWriter.write(b)))
throw e
}
return result
}
function fetchIfNeeded (file, superCallback, downloadCallback, fetchFn) {
// check for file that got downloaded
fs.stat(file, function (err) {
if (!err) {
// file found, skip download steps
return superCallback()
}
// check for manual file that got fixed and needs validation
const fixedFile = file.replace('.json', '_fixed.json')
fs.stat(fixedFile, function (err) {
if (!err) {
// file found, return fixed file
return downloadCallback(null, require(fixedFile))
}
// no manual fixed file found, download from overpass
fetchFn()
})
})
}
function geoJsonToGeom (geoJson) {
try {
return geoJsonReader.read(JSON.stringify(geoJson))
} catch (e) {
console.error('error converting geojson to geometry')
fs.writeFileSync('debug_geojson_read_error.json', JSON.stringify(geoJson))
throw e
}
}
function geomToGeoJson (geom) {
return geoJsonWriter.write(geom)
}
function geomToGeoJsonString (geom) {
return JSON.stringify(geoJsonWriter.write(geom))
}
const downloadProgress = new ProgressStats(
'Downloading',
Object.keys(osmBoundarySources).length
)
const downloadOSMZoneProgress = new ProgressStats(
'Downloading OSM Zone',
Object.keys(zoneCfg).length
)
/**
* Download something from overpass and convert it into GeoJSON.
*
* @param {string} queryName Name of the query (for debugging purposes)
* @param {object} overpassConfig Config used to build overpass query
* @param {string} filename Filename to save result to
* @param {function} overpassDownloadCallback The callback to call when done
*/
function downloadFromOverpass (
queryName,
overpassConfig,
filename,
overpassDownloadCallback
) {
let query = '[out:json][timeout:60];('
if (overpassConfig.way) {
query += 'way'
} else {
query += 'relation'
}
const queryKeys = Object.keys(overpassConfig)
for (let i = queryKeys.length - 1; i >= 0; i--) {
const k = queryKeys[i]
if (k === 'way') continue
const v = overpassConfig[k]
query += '["' + k + '"="' + v + '"]'
}
query += ';);out body;>;out meta qt;'
// query-overpass sometimes makes duplicate callbacks, so keep track of the callbacks and
// only do a next action once.
let curOverpassQueryAttempt = 0
const overpassAttempts = {}
asynclib.auto({
fetchFromOverpassIfNeeded: function (cb) {
console.log('downloading from overpass')
fetchIfNeeded(filename, overpassDownloadCallback, cb, function () {
const overpassResponseHandler = function (err, data, overpassAttempt) {
if (overpassAttempts[overpassAttempt]) {
// Skip duplicate callback
return
}
overpassAttempts[overpassAttempt] = true
if (err) {
console.log(err)
console.log('Increasing overpass request gap')
curRequestGap *= 2
makeQuery()
} else {
console.log('Success, decreasing overpass request gap')
curRequestGap = Math.max(minRequestGap, curRequestGap / 2)
cb(null, data)
}
}
const makeQuery = function () {
console.log('waiting ' + curRequestGap + ' seconds')
setTimeout(function () {
curOverpassQueryAttempt++
overpass(
query,
(err, data) => overpassResponseHandler(err, data, curOverpassQueryAttempt),
{ flatProperties: true }
)
}, curRequestGap * 1000)
}
makeQuery()
})
},
validateOverpassResult: ['fetchFromOverpassIfNeeded', function (results, cb) {
const data = results.fetchFromOverpassIfNeeded
if (!data.features) {
const err = new Error(`Invalid geojson from overpass for query: ${queryName}`)
return cb(err)
}
if (data.features.length === 0) {
console.error('No data for the following query:')
console.error(query)
console.error('To read more about this error, please visit https://git.io/vxKQL')
return cb(new Error('No data found for from overpass query'))
}
cb()
}],
saveSingleMultiPolygon: ['validateOverpassResult', function (results, cb) {
const data = results.fetchFromOverpassIfNeeded
let combined
// union all multi-polygons / polygons into one
for (let i = data.features.length - 1; i >= 0; i--) {
const curOsmGeom = data.features[i].geometry
const curOsmProps = data.features[i].properties
if (
(curOsmGeom.type === 'Polygon' || curOsmGeom.type === 'MultiPolygon') &&
curOsmProps.type === 'boundary' // need to make sure enclaves aren't unioned
) {
console.log('combining border')
let errors = geojsonhint.hint(curOsmGeom)
if (errors && errors.length > 0) {
const stringifiedGeojson = JSON.stringify(curOsmGeom, null, 2)
errors = geojsonhint.hint(stringifiedGeojson)
console.error('Invalid geojson received in Overpass Result')
console.error('Overpass query: ' + query)
const problemFilename = `${queryName}_convert_to_geom_error.json`
fs.writeFileSync(problemFilename, stringifiedGeojson)
console.error('saved problem file to ' + problemFilename)
console.error('To read more about this error, please visit https://git.io/vxKQq')
return cb(errors)
}
let curGeom
try {
curGeom = geoJsonToGeom(curOsmGeom)
} catch (e) {
console.error('error converting overpass result to geojson')
console.error(e)
fs.writeFileSync(
`${queryName}_convert_to_geom_error-all-features.json`,
JSON.stringify(data)
)
return cb(e)
}
if (!combined) {
combined = curGeom
} else {
combined = debugGeo('union', curGeom, combined)
}
}
}
try {
fs.writeFile(filename, geomToGeoJsonString(combined), cb)
} catch (e) {
console.error('error writing combined border to geojson')
fs.writeFileSync(
queryName + '_combined_border_convert_to_geom_error.json',
JSON.stringify(data)
)
return cb(e)
}
}]
}, overpassDownloadCallback)
}
function downloadOsmBoundary (boundaryId, boundaryCallback) {
const boundaryFilename = downloadsDir + '/' + boundaryId + '.json'
downloadProgress.beginTask(`getting data for ${boundaryId}`, true)
downloadFromOverpass(
boundaryId,
osmBoundarySources[boundaryId],
boundaryFilename,
boundaryCallback
)
}
function downloadOsmTimezoneBoundary (tzId, boundaryCallback) {
const tzBoundayName = `${tzId.replace(/\//g, '-')}-tz`
const boundaryFilename = path.join(downloadsDir, `${tzBoundayName}.json`)
const workingBoundaryFilename = path.join(osmDownloadDir, `${tzBoundayName}.json`)
downloadOSMZoneProgress.beginTask(`getting data for ${tzBoundayName}`, true)
// the downloads directory is cleared of all timezone boundaries not downloaded from OSM (there
// are still a few in here with manual definitions). Therefore, keep a copy of all OSM downloads
// so they aren't redownloaded during multiple reruns of the script
function copyToOsmDownloadFolder (err) {
if (err) return boundaryCallback(err)
fs.copyFile(boundaryFilename, workingBoundaryFilename, boundaryCallback)
}
// Before downloading from Overpass, check if there's a copy in the working folder. Since osm
// downloads are always after production zones, it is safe to copy an osm boundary because a
// production one would've already been downloaded in the event it were deleted in order to force
// the retrieval of a new zone.
fs.stat(
boundaryFilename,
(err, stats) => {
if (!err) {
// file found, initiate eventual callback
return copyToOsmDownloadFolder()
}
// check for file in working dir
fs.stat(
workingBoundaryFilename,
(err, stats) => {
if (!err) {
// file exists, copy over
return fs.copyFile(workingBoundaryFilename, boundaryFilename, boundaryCallback)
}
// file doesn't exist, download from overpass
downloadFromOverpass(
tzBoundayName,
{ timezone: tzId },
boundaryFilename,
err => {
if (err) {
// assume no data or unparseable data, write a null island
fs.writeFile(
boundaryFilename,
JSON.stringify(
{
type: 'Polygon',
coordinates: [
[[-0.1, -0.1], [0.1, -0.1], [0.1, 0.1], [-0.1, 0.1], [-0.1, -0.1]]
]
}
),
copyToOsmDownloadFolder
)
} else {
copyToOsmDownloadFolder()
}
}
)
}
)
}
)
}
function safeTzFilename (tzid) {
return tzid.replace(/\//g, '__')
}
function getFinalTzOutputFilename (tzid) {
return path.join(workingDir, `${safeTzFilename(tzid)}.json`)
}
function getFinal1970TzOutputFilename (tzid) {
return path.join(workingDir, `${safeTzFilename(tzid)}-1970.json`)
}
function getFinalNowTzOutputFilename (tzid) {
return path.join(workingDir, `${safeTzFilename(tzid)}-now.json`)
}
function getSourceDownloadName (id) {
return downloadsDir + '/' + id + '.json'
}
/**
* Get the geometry of the requested source data
*
* @return {Object} geom The geometry of the source
* @param {Object} source An object representing the data source
* must have `source` key and then either:
* - `id` if from a file
* - `id` if from a file
*/
function getDataSource (source) {
let geoJson
if (source.source === 'overpass') {
geoJson = require(getSourceDownloadName(source.id))
} else if (source.source === 'manual-polygon') {
geoJson = polygon(source.data).geometry
} else if (source.source === 'manual-multipolygon') {
geoJson = multiPolygon(source.data).geometry
} else if (source.source === 'final') {
geoJson = require(getFinalTzOutputFilename(source.id))
} else if (source.source === 'final1970') {
geoJson = require(getFinal1970TzOutputFilename(source.id))
} else if (source.source === 'finalNow') {
geoJson = require(getFinalNowTzOutputFilename(source.id))
} else {
const err = new Error('unknown source: ' + source.source)
throw err
}
return geoJsonToGeom(geoJson)
}
/**
* Post process created timezone boundary.
* - remove small holes and exclaves
* - reduce geometry precision
*
* @param {Geometry} geom The jsts geometry of the timezone
* @param {boolean} returnAsObject if true, return as object, otherwise return stringified
* @return {Object|String} geojson as object or stringified
*/
function postProcessZone (geom, returnAsObject) {
// reduce precision of geometry
const geojson = geomToGeoJson(precisionReducer.reduce(geom))
// iterate through all polygons
const filteredPolygons = []
let allPolygons = geojson.coordinates
if (geojson.type === 'Polygon') {
allPolygons = [geojson.coordinates]
}
allPolygons.forEach((curPolygon, idx) => {
// remove any polygon with very small area
const polygonFeature = polygon(curPolygon)
const polygonArea = area.geometry(polygonFeature.geometry)
if (polygonArea < 1) return
// find all holes
const filteredLinearRings = []
curPolygon.forEach((curLinearRing, lrIdx) => {
if (lrIdx === 0) {
// always keep first linearRing
filteredLinearRings.push(curLinearRing)
} else {
const polygonFromLinearRing = polygon([curLinearRing])
const linearRingArea = area.geometry(polygonFromLinearRing.geometry)
// only include holes with relevant area
if (linearRingArea > 1) {
filteredLinearRings.push(curLinearRing)
}
}
})
filteredPolygons.push(filteredLinearRings)
})
// recompile to geojson string
const newGeojson = {
type: geojson.type
}
if (geojson.type === 'Polygon') {
newGeojson.coordinates = filteredPolygons[0]
} else {
newGeojson.coordinates = filteredPolygons
}
return returnAsObject ? newGeojson : JSON.stringify(newGeojson)
}
const buildingProgress = new ProgressStats(
'Building',
Object.keys(zoneCfg).length
)
function makeTimezoneBoundaries (callback) {
// load cache if available
const tzBoundaryCache = new FileLookupCache({
filename: path.join(cacheDir, 'boundary-creation-cache.json')
})
tzBoundaryCache.init(() => {
asynclib.each(
Object.keys(zoneCfg),
(tzid, cb) => {
buildingProgress.beginTask(`makeTimezoneBoundary for ${tzid}`, true)
const tzFilename = getFinalTzOutputFilename(tzid)
const ops = zoneCfg[tzid]
let geom
asynclib.map(
ops,
(op, opCb) => {
const newOp = cloneDeep(op)
if (op.source === 'overpass') {
hasha.fromFile(getSourceDownloadName(op.id))
.then(val => {
newOp.source = val
opCb(null, newOp)
})
.catch(opCb)
} else {
opCb(null, newOp)
}
},
(err, hashableOps) => {
if (err) return cb(err)
tzBoundaryCache.calculate({
cacheKey: hashMd5(hashableOps),
outputFilename: tzFilename,
calculateFn: calculateCb => {
console.log(`makeTimezoneBoundary for ${tzid}`)
asynclib.eachSeries(
ops,
(task, taskCb) => {
const taskData = getDataSource(task)
console.log('-', task.op, task.id)
if (task.op === 'init') {
geom = taskData
} else if (task.op === 'intersect') {
geom = debugGeo('intersection', geom, taskData)
} else if (task.op === 'difference') {
geom = debugGeo('diff', geom, taskData)
} else if (task.op === 'difference-reverse-order') {
geom = debugGeo('diff', taskData, geom)
} else if (task.op === 'union') {
geom = debugGeo('union', geom, taskData)
} else {
const err = new Error('unknown op: ' + task.op)
return taskCb(err)
}
taskCb()
},
opsErr => {
if (opsErr) return calculateCb(err)
calculateCb(null, postProcessZone(geom))
}
)
},
callback: cb
})
}
)
},
err => {
if (err) return callback(err)
tzBoundaryCache.end(callback)
}
)
})
}
function makeDerivedTimezoneBoundaries (strategy, callback) {
const cfg = (
strategy === '1970'
? {
cacheFilename: path.join(cacheDir, 'derived-1970-cache.json'),
derivedZoneConfig: zoneCfg1970,
getFinalTzFilenameFn: getFinal1970TzOutputFilename,
loadZonesInMemoryFn: loadFinal1970ZonesIntoMemory,
progressStatsName: 'Building 1970 zones',
progressStatsUpdatePrefix: 'make1970TimezoneBoundary for'
}
: {
cacheFilename: path.join(cacheDir, 'derived-now-cache.json'),
derivedZoneConfig: zoneCfgNow,
getFinalTzFilenameFn: getFinalNowTzOutputFilename,
loadZonesInMemoryFn: loadFinalNowZonesIntoMemory,
progressStatsName: 'Building Now zones',
progressStatsUpdatePrefix: 'makeNowTimezoneBoundary for'
}
)
const buildingProgress = new ProgressStats(
cfg.progressStatsName,
Object.keys(cfg.derivedZoneConfig).length
)
// load cache if available
const tzBoundaryCache = new FileLookupCache({
filename: cfg.cacheFilename
})
tzBoundaryCache.init(() => {
asynclib.each(
Object.keys(cfg.derivedZoneConfig),
(tzid, cb) => {
const message = `${cfg.progressStatsUpdatePrefix} ${tzid}`
buildingProgress.beginTask(message, true)
tzBoundaryCache.calculate({
cacheKey: hashMd5(cfg.derivedZoneConfig[tzid].map(getZoneGeomHash)),
outputFilename: cfg.getFinalTzFilenameFn(tzid),
calculateFn: calculateCb => {
console.log(message)
let geom = getDataSource({ source: 'final', id: tzid })
cfg.derivedZoneConfig[tzid].forEach(zone => {
console.log('-', zone)
if (zone === tzid) return
const zoneData = getDataSource({ source: 'final', id: zone })
geom = debugGeo('union', geom, zoneData)
})
calculateCb(null, postProcessZone(geom))
},
callback: cb
})
},
err => {
if (err) return callback(err)
cfg.loadZonesInMemoryFn()
tzBoundaryCache.end(callback)
}
)
})
}
function loadFinalZonesIntoMemory () {
console.log('load zones into memory')
Object.keys(zoneCfg).forEach(tzid => {
finalZones[tzid] = getDataSource({ source: 'final', id: tzid })
})
}
function loadFinal1970ZonesIntoMemory () {
console.log('load 1970 zones into memory')
Object.keys(zoneCfg1970).forEach(tzid => {
final1970Zones[tzid] = getDataSource({ source: 'final1970', id: tzid })
})
}
function loadFinalNowZonesIntoMemory () {
console.log('load Now zones into memory')
Object.keys(zoneCfgNow).forEach(tzid => {
finalNowZones[tzid] = getDataSource({ source: 'finalNow', id: tzid })
})
}
function roundDownToTenth (n) {
return Math.floor(n * 10) / 10
}
function roundUpToTenth (n) {
return Math.ceil(n * 10) / 10
}
function formatBounds (bounds) {
let boundsStr = '['
boundsStr += roundDownToTenth(bounds[0]) + ', '
boundsStr += roundDownToTenth(bounds[1]) + ', '
boundsStr += roundUpToTenth(bounds[2]) + ', '
boundsStr += roundUpToTenth(bounds[3]) + ']'
return boundsStr
}
const getZoneGeomHash = memoize((tzid) => {
const zoneFilename = getFinalTzOutputFilename(tzid)
try {
fs.statSync(zoneFilename)
} catch (err) {
return `${tzid}-filenotfound`
}
return `${tzid}-${hasha.fromFileSync(zoneFilename, { algorithm: 'md5' })}`
})
function validateTimezoneBoundaries (callback) {
console.log('do validation... this may take a few minutes with fresh data')
// load cache if available
const validationCache = new FileCache({
filename: path.join(cacheDir, 'validation-cache.json')
})
validationCache.init(() => {
let allZonesOk = true
const zones = Object.keys(zoneCfg)
const numZones = Object.keys(zoneCfg).length
const validationProgress = new ProgressStats(
'Validation',
numZones * (numZones + 1) / 2
)
let lastPct = 0
const validationCalcs = []
for (let i = 0; i < zones.length; i++) {
for (let j = i + 1; j < zones.length; j++) {
validationCalcs.push({ tzid: zones[i], compareTzid: zones[j] })
}
}
asynclib.each(
validationCalcs,
({ tzid, compareTzid }, validationCb) => {
const allowedOverlapBounds = expectedZoneOverlaps[`${tzid}-${compareTzid}`] || expectedZoneOverlaps[`${compareTzid}-${tzid}`]
validationCache.calculate({
cacheKey: `${getZoneGeomHash(tzid)}-${getZoneGeomHash(compareTzid)}-${hashMd5(allowedOverlapBounds)}`,
calculateFn: calculateCb => {
const zoneGeom = finalZones[tzid]
const compareZoneGeom = finalZones[compareTzid]
let intersects = false
try {
intersects = debugGeo('intersects', zoneGeom, compareZoneGeom)
} catch (e) {
console.warn('warning, encountered intersection error with zone ' + tzid + ' and ' + compareTzid)
}
if (intersects) {
const intersectedGeom = debugGeo('intersection', zoneGeom, compareZoneGeom)
const intersectedArea = intersectedGeom.getArea()
if (intersectedArea > 0.0001) {
// check if the intersected area(s) are one of the expected areas of overlap
const overlapsGeoJson = geoJsonWriter.write(intersectedGeom)
// these zones are allowed to overlap in certain places, make sure the
// found overlap(s) all fit within the expected areas of overlap
if (allowedOverlapBounds) {
// if the overlaps are a multipolygon, make sure each individual
// polygon of overlap fits within at least one of the expected
// overlaps
let overlapsPolygons
switch (overlapsGeoJson.type) {
case 'MultiPolygon':
overlapsPolygons = overlapsGeoJson.coordinates.map(
polygonCoords => ({
coordinates: polygonCoords,
type: 'Polygon'
})
)
break
case 'Polygon':
overlapsPolygons = [overlapsGeoJson]
break
case 'GeometryCollection':
overlapsPolygons = []
overlapsGeoJson.geometries.forEach(geom => {
if (geom.type === 'Polygon') {
overlapsPolygons.push(geom)