blob: 6db6bd7351bee6860289675c00016f870c3eb93d [file] [log] [blame]
Evan Siroky7891a6e2016-11-05 11:50:50 -07001var exec = require('child_process').exec
2var fs = require('fs')
evansirokyd401c892016-06-16 00:05:14 -07003
Evan Siroky477ece62017-08-01 07:08:51 -07004var area = require('@mapbox/geojson-area')
evansiroky70b35fe2018-04-01 21:06:36 -07005var geojsonhint = require('@mapbox/geojsonhint')
evansiroky0ea1d1e2018-10-30 22:30:51 -07006var bbox = require('@turf/bbox').default
Evan Siroky8326cf02017-03-02 08:27:55 -08007var helpers = require('@turf/helpers')
Evan Siroky070bbb92017-03-07 23:48:29 -08008var multiPolygon = helpers.multiPolygon
Evan Siroky8326cf02017-03-02 08:27:55 -08009var polygon = helpers.polygon
Evan Siroky7891a6e2016-11-05 11:50:50 -070010var asynclib = require('async')
11var jsts = require('jsts')
Evan Sirokyb57a5b92016-11-07 10:22:34 -080012var rimraf = require('rimraf')
Evan Siroky7891a6e2016-11-05 11:50:50 -070013var overpass = require('query-overpass')
Neil Fullerc4ae49b2020-04-30 18:08:43 +010014var yargs = require('yargs')
evansirokyd401c892016-06-16 00:05:14 -070015
evansiroky5348a6f2019-01-05 15:39:28 -080016const ProgressStats = require('./progressStats')
17
Evan Siroky7891a6e2016-11-05 11:50:50 -070018var osmBoundarySources = require('./osmBoundarySources.json')
19var zoneCfg = require('./timezones.json')
evansiroky0ea1d1e2018-10-30 22:30:51 -070020var expectedZoneOverlaps = require('./expectedZoneOverlaps.json')
Evan Siroky081648a2017-07-04 09:53:36 -070021
Neil Fullerc4ae49b2020-04-30 18:08:43 +010022const argv = yargs
23 .option('included_zones', {
24 description: 'Include specified zones',
25 type: 'array'
26 })
Neil Fuller2b4b80a2020-04-30 18:20:56 +010027 .option('excluded_zones', {
28 description: 'Exclude specified zones',
29 type: 'array'
30 })
Neil Fullerc4ae49b2020-04-30 18:08:43 +010031 .option('no_validation', {
32 description: 'Skip validation',
33 type: 'boolean'
34 })
35 .help()
36 .strict()
37 .alias('help', 'h')
38 .argv
39
Evan Siroky081648a2017-07-04 09:53:36 -070040// allow building of only a specified zones
Neil Fullerc4ae49b2020-04-30 18:08:43 +010041let includedZones = []
Neil Fuller2b4b80a2020-04-30 18:20:56 +010042let excludedZones = []
43if (argv.included_zones || argv.excluded_zones) {
44 if (argv.included_zones) {
45 let newZoneCfg = {}
46 includedZones = argv.included_zones
47 includedZones.forEach((zoneName) => {
48 newZoneCfg[zoneName] = zoneCfg[zoneName]
49 })
50 zoneCfg = newZoneCfg
51 }
52 if (argv.excluded_zones) {
53 let newZoneCfg = {}
54 excludedZones = argv.excluded_zones
55 Object.keys(zoneCfg).forEach((zoneName) => {
56 if (!excludedZones.includes(zoneName)) {
57 newZoneCfg[zoneName] = zoneCfg[zoneName]
58 }
59 })
60 zoneCfg = newZoneCfg
61 }
Evan Siroky081648a2017-07-04 09:53:36 -070062
63 // filter out unneccessary downloads
64 var newOsmBoundarySources = {}
65 Object.keys(zoneCfg).forEach((zoneName) => {
66 zoneCfg[zoneName].forEach((op) => {
67 if (op.source === 'overpass') {
68 newOsmBoundarySources[op.id] = osmBoundarySources[op.id]
69 }
70 })
71 })
72
73 osmBoundarySources = newOsmBoundarySources
74}
75
Evan Siroky7891a6e2016-11-05 11:50:50 -070076var geoJsonReader = new jsts.io.GeoJSONReader()
77var geoJsonWriter = new jsts.io.GeoJSONWriter()
Evan Siroky477ece62017-08-01 07:08:51 -070078var precisionModel = new jsts.geom.PrecisionModel(1000000)
79var precisionReducer = new jsts.precision.GeometryPrecisionReducer(precisionModel)
Evan Siroky7891a6e2016-11-05 11:50:50 -070080var distZones = {}
Evan Sirokyb57a5b92016-11-07 10:22:34 -080081var minRequestGap = 4
82var curRequestGap = 4
evansirokyd401c892016-06-16 00:05:14 -070083
Evan Siroky7891a6e2016-11-05 11:50:50 -070084var safeMkdir = function (dirname, callback) {
85 fs.mkdir(dirname, function (err) {
86 if (err && err.code === 'EEXIST') {
evansiroky4be1c7a2016-06-16 18:23:34 -070087 callback()
88 } else {
89 callback(err)
90 }
91 })
92}
93
Evan Sirokyb173fd42017-03-08 15:16:27 -080094var debugGeo = function (op, a, b, reducePrecision) {
evansirokybecb56e2016-07-06 12:42:35 -070095 var result
96
Evan Sirokyb173fd42017-03-08 15:16:27 -080097 if (reducePrecision) {
Evan Sirokyb173fd42017-03-08 15:16:27 -080098 a = precisionReducer.reduce(a)
99 b = precisionReducer.reduce(b)
100 }
101
evansiroky6f9d8f72016-06-21 16:27:54 -0700102 try {
Evan Siroky7891a6e2016-11-05 11:50:50 -0700103 switch (op) {
evansiroky6f9d8f72016-06-21 16:27:54 -0700104 case 'union':
evansirokybecb56e2016-07-06 12:42:35 -0700105 result = a.union(b)
evansiroky6f9d8f72016-06-21 16:27:54 -0700106 break
107 case 'intersection':
evansirokybecb56e2016-07-06 12:42:35 -0700108 result = a.intersection(b)
evansiroky6f9d8f72016-06-21 16:27:54 -0700109 break
Evan Siroky070bbb92017-03-07 23:48:29 -0800110 case 'intersects':
111 result = a.intersects(b)
112 break
evansiroky6f9d8f72016-06-21 16:27:54 -0700113 case 'diff':
Evan Sirokyb173fd42017-03-08 15:16:27 -0800114 result = a.difference(b)
evansiroky6f9d8f72016-06-21 16:27:54 -0700115 break
116 default:
117 var err = new Error('invalid op: ' + op)
118 throw err
119 }
Evan Siroky7891a6e2016-11-05 11:50:50 -0700120 } catch (e) {
Evan Sirokyb173fd42017-03-08 15:16:27 -0800121 if (e.name === 'TopologyException') {
122 console.log('Encountered TopologyException, retry with GeometryPrecisionReducer')
123 return debugGeo(op, a, b, true)
124 }
evansiroky6f9d8f72016-06-21 16:27:54 -0700125 console.log('op err')
evansirokybecb56e2016-07-06 12:42:35 -0700126 console.log(e)
127 console.log(e.stack)
128 fs.writeFileSync('debug_' + op + '_a.json', JSON.stringify(geoJsonWriter.write(a)))
129 fs.writeFileSync('debug_' + op + '_b.json', JSON.stringify(geoJsonWriter.write(b)))
evansiroky6f9d8f72016-06-21 16:27:54 -0700130 throw e
131 }
evansiroky6f9d8f72016-06-21 16:27:54 -0700132
evansirokybecb56e2016-07-06 12:42:35 -0700133 return result
evansiroky4be1c7a2016-06-16 18:23:34 -0700134}
135
Evan Siroky070bbb92017-03-07 23:48:29 -0800136var fetchIfNeeded = function (file, superCallback, downloadCallback, fetchFn) {
137 // check for file that got downloaded
Evan Siroky7891a6e2016-11-05 11:50:50 -0700138 fs.stat(file, function (err) {
Evan Siroky070bbb92017-03-07 23:48:29 -0800139 if (!err) {
140 // file found, skip download steps
141 return superCallback()
142 }
143 // check for manual file that got fixed and needs validation
144 var fixedFile = file.replace('.json', '_fixed.json')
145 fs.stat(fixedFile, function (err) {
146 if (!err) {
147 // file found, return fixed file
148 return downloadCallback(null, require(fixedFile))
149 }
150 // no manual fixed file found, download from overpass
151 fetchFn()
152 })
evansiroky50216c62016-06-16 17:41:47 -0700153 })
154}
155
Evan Siroky7891a6e2016-11-05 11:50:50 -0700156var geoJsonToGeom = function (geoJson) {
Evan Siroky8326cf02017-03-02 08:27:55 -0800157 try {
158 return geoJsonReader.read(JSON.stringify(geoJson))
159 } catch (e) {
160 console.error('error converting geojson to geometry')
161 fs.writeFileSync('debug_geojson_read_error.json', JSON.stringify(geoJson))
162 throw e
163 }
Evan Siroky5669adc2016-07-07 17:25:31 -0700164}
165
Evan Siroky8b47abe2016-10-02 12:28:52 -0700166var geomToGeoJson = function (geom) {
167 return geoJsonWriter.write(geom)
168}
169
Evan Siroky7891a6e2016-11-05 11:50:50 -0700170var geomToGeoJsonString = function (geom) {
Evan Siroky5669adc2016-07-07 17:25:31 -0700171 return JSON.stringify(geoJsonWriter.write(geom))
172}
173
evansiroky5348a6f2019-01-05 15:39:28 -0800174const downloadProgress = new ProgressStats(
175 'Downloading',
176 Object.keys(osmBoundarySources).length
177)
178
Evan Siroky7891a6e2016-11-05 11:50:50 -0700179var downloadOsmBoundary = function (boundaryId, boundaryCallback) {
180 var cfg = osmBoundarySources[boundaryId]
Evan Siroky1bcd4772017-10-14 23:47:21 -0700181 var query = '[out:json][timeout:60];('
182 if (cfg.way) {
183 query += 'way'
184 } else {
185 query += 'relation'
186 }
Evan Siroky7891a6e2016-11-05 11:50:50 -0700187 var boundaryFilename = './downloads/' + boundaryId + '.json'
188 var debug = 'getting data for ' + boundaryId
189 var queryKeys = Object.keys(cfg)
evansiroky63d35e12016-06-16 10:08:15 -0700190
Evan Siroky5669adc2016-07-07 17:25:31 -0700191 for (var i = queryKeys.length - 1; i >= 0; i--) {
Evan Siroky7891a6e2016-11-05 11:50:50 -0700192 var k = queryKeys[i]
Evan Siroky1bcd4772017-10-14 23:47:21 -0700193 if (k === 'way') continue
Evan Siroky7891a6e2016-11-05 11:50:50 -0700194 var v = cfg[k]
Evan Siroky5669adc2016-07-07 17:25:31 -0700195
196 query += '["' + k + '"="' + v + '"]'
evansiroky63d35e12016-06-16 10:08:15 -0700197 }
198
evansiroky283ebbc2018-07-16 15:13:07 -0700199 query += ';);out body;>;out meta qt;'
evansiroky4be1c7a2016-06-16 18:23:34 -0700200
evansiroky5348a6f2019-01-05 15:39:28 -0800201 downloadProgress.beginTask(debug, true)
evansiroky63d35e12016-06-16 10:08:15 -0700202
Evan Siroky7891a6e2016-11-05 11:50:50 -0700203 asynclib.auto({
204 downloadFromOverpass: function (cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800205 console.log('downloading from overpass')
Evan Siroky070bbb92017-03-07 23:48:29 -0800206 fetchIfNeeded(boundaryFilename, boundaryCallback, cb, function () {
Evan Sirokyb57a5b92016-11-07 10:22:34 -0800207 var overpassResponseHandler = function (err, data) {
208 if (err) {
209 console.log(err)
210 console.log('Increasing overpass request gap')
211 curRequestGap *= 2
212 makeQuery()
213 } else {
214 console.log('Success, decreasing overpass request gap')
215 curRequestGap = Math.max(minRequestGap, curRequestGap / 2)
216 cb(null, data)
217 }
218 }
219 var makeQuery = function () {
220 console.log('waiting ' + curRequestGap + ' seconds')
221 setTimeout(function () {
222 overpass(query, overpassResponseHandler, { flatProperties: true })
223 }, curRequestGap * 1000)
224 }
225 makeQuery()
evansiroky63d35e12016-06-16 10:08:15 -0700226 })
227 },
Evan Siroky7891a6e2016-11-05 11:50:50 -0700228 validateOverpassResult: ['downloadFromOverpass', function (results, cb) {
evansiroky63d35e12016-06-16 10:08:15 -0700229 var data = results.downloadFromOverpass
evansiroky70b35fe2018-04-01 21:06:36 -0700230 if (!data.features) {
Evan Siroky7891a6e2016-11-05 11:50:50 -0700231 var err = new Error('Invalid geojson for boundary: ' + boundaryId)
evansiroky63d35e12016-06-16 10:08:15 -0700232 return cb(err)
233 }
evansiroky70b35fe2018-04-01 21:06:36 -0700234 if (data.features.length === 0) {
235 console.error('No data for the following query:')
236 console.error(query)
237 console.error('To read more about this error, please visit https://git.io/vxKQL')
evansiroky0ea1d1e2018-10-30 22:30:51 -0700238 return cb(new Error('No data found for from overpass query'))
evansiroky70b35fe2018-04-01 21:06:36 -0700239 }
evansiroky63d35e12016-06-16 10:08:15 -0700240 cb()
241 }],
Evan Siroky7891a6e2016-11-05 11:50:50 -0700242 saveSingleMultiPolygon: ['validateOverpassResult', function (results, cb) {
243 var data = results.downloadFromOverpass
244 var combined
evansiroky63d35e12016-06-16 10:08:15 -0700245
246 // union all multi-polygons / polygons into one
247 for (var i = data.features.length - 1; i >= 0; i--) {
Evan Siroky5669adc2016-07-07 17:25:31 -0700248 var curOsmGeom = data.features[i].geometry
evansiroky92c15c42018-11-15 20:58:18 -0800249 const curOsmProps = data.features[i].properties
250 if (
251 (curOsmGeom.type === 'Polygon' || curOsmGeom.type === 'MultiPolygon') &&
252 curOsmProps.type === 'boundary' // need to make sure enclaves aren't unioned
253 ) {
evansiroky63d35e12016-06-16 10:08:15 -0700254 console.log('combining border')
evansiroky70b35fe2018-04-01 21:06:36 -0700255 let errors = geojsonhint.hint(curOsmGeom)
256 if (errors && errors.length > 0) {
257 const stringifiedGeojson = JSON.stringify(curOsmGeom, null, 2)
258 errors = geojsonhint.hint(stringifiedGeojson)
259 console.error('Invalid geojson received in Overpass Result')
260 console.error('Overpass query: ' + query)
261 const problemFilename = boundaryId + '_convert_to_geom_error.json'
262 fs.writeFileSync(problemFilename, stringifiedGeojson)
263 console.error('saved problem file to ' + problemFilename)
264 console.error('To read more about this error, please visit https://git.io/vxKQq')
265 return cb(errors)
266 }
Evan Siroky070bbb92017-03-07 23:48:29 -0800267 try {
268 var curGeom = geoJsonToGeom(curOsmGeom)
269 } catch (e) {
270 console.error('error converting overpass result to geojson')
Evan Siroky477ece62017-08-01 07:08:51 -0700271 console.error(e)
evansiroky70b35fe2018-04-01 21:06:36 -0700272
Evan Siroky1bcd4772017-10-14 23:47:21 -0700273 fs.writeFileSync(boundaryId + '_convert_to_geom_error-all-features.json', JSON.stringify(data))
evansiroky70b35fe2018-04-01 21:06:36 -0700274 return cb(e)
Evan Siroky070bbb92017-03-07 23:48:29 -0800275 }
Evan Siroky7891a6e2016-11-05 11:50:50 -0700276 if (!combined) {
evansiroky63d35e12016-06-16 10:08:15 -0700277 combined = curGeom
278 } else {
Evan Siroky5669adc2016-07-07 17:25:31 -0700279 combined = debugGeo('union', curGeom, combined)
evansiroky63d35e12016-06-16 10:08:15 -0700280 }
281 }
282 }
Evan Siroky081c8e42017-05-29 14:53:52 -0700283 try {
284 fs.writeFile(boundaryFilename, geomToGeoJsonString(combined), cb)
285 } catch (e) {
286 console.error('error writing combined border to geojson')
287 fs.writeFileSync(boundaryId + '_combined_border_convert_to_geom_error.json', JSON.stringify(data))
evansiroky70b35fe2018-04-01 21:06:36 -0700288 return cb(e)
Evan Siroky081c8e42017-05-29 14:53:52 -0700289 }
evansiroky63d35e12016-06-16 10:08:15 -0700290 }]
291 }, boundaryCallback)
292}
evansirokyd401c892016-06-16 00:05:14 -0700293
Evan Siroky4fc596c2016-09-25 19:52:30 -0700294var getTzDistFilename = function (tzid) {
295 return './dist/' + tzid.replace(/\//g, '__') + '.json'
296}
297
298/**
299 * Get the geometry of the requested source data
300 *
301 * @return {Object} geom The geometry of the source
302 * @param {Object} source An object representing the data source
303 * must have `source` key and then either:
304 * - `id` if from a file
305 * - `id` if from a file
306 */
Evan Siroky7891a6e2016-11-05 11:50:50 -0700307var getDataSource = function (source) {
evansirokybecb56e2016-07-06 12:42:35 -0700308 var geoJson
Evan Siroky7891a6e2016-11-05 11:50:50 -0700309 if (source.source === 'overpass') {
evansirokybecb56e2016-07-06 12:42:35 -0700310 geoJson = require('./downloads/' + source.id + '.json')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700311 } else if (source.source === 'manual-polygon') {
evansirokybecb56e2016-07-06 12:42:35 -0700312 geoJson = polygon(source.data).geometry
Evan Siroky7891a6e2016-11-05 11:50:50 -0700313 } else if (source.source === 'manual-multipolygon') {
Evan Siroky8e30a2e2016-08-06 19:55:35 -0700314 geoJson = multiPolygon(source.data).geometry
Evan Siroky7891a6e2016-11-05 11:50:50 -0700315 } else if (source.source === 'dist') {
Evan Siroky4fc596c2016-09-25 19:52:30 -0700316 geoJson = require(getTzDistFilename(source.id))
evansiroky4be1c7a2016-06-16 18:23:34 -0700317 } else {
318 var err = new Error('unknown source: ' + source.source)
319 throw err
320 }
Evan Siroky5669adc2016-07-07 17:25:31 -0700321 return geoJsonToGeom(geoJson)
evansiroky4be1c7a2016-06-16 18:23:34 -0700322}
323
Evan Siroky477ece62017-08-01 07:08:51 -0700324/**
325 * Post process created timezone boundary.
326 * - remove small holes and exclaves
327 * - reduce geometry precision
328 *
329 * @param {Geometry} geom The jsts geometry of the timezone
evansiroky26325842018-04-03 14:10:42 -0700330 * @param {boolean} returnAsObject if true, return as object, otherwise return stringified
331 * @return {Object|String} geojson as object or stringified
Evan Siroky477ece62017-08-01 07:08:51 -0700332 */
evansiroky26325842018-04-03 14:10:42 -0700333var postProcessZone = function (geom, returnAsObject) {
Evan Siroky477ece62017-08-01 07:08:51 -0700334 // reduce precision of geometry
335 const geojson = geomToGeoJson(precisionReducer.reduce(geom))
336
337 // iterate through all polygons
338 const filteredPolygons = []
339 let allPolygons = geojson.coordinates
340 if (geojson.type === 'Polygon') {
341 allPolygons = [geojson.coordinates]
342 }
343
344 allPolygons.forEach((curPolygon, idx) => {
345 // remove any polygon with very small area
346 const polygonFeature = polygon(curPolygon)
347 const polygonArea = area.geometry(polygonFeature.geometry)
348
349 if (polygonArea < 1) return
350
351 // find all holes
352 const filteredLinearRings = []
353
354 curPolygon.forEach((curLinearRing, lrIdx) => {
355 if (lrIdx === 0) {
356 // always keep first linearRing
357 filteredLinearRings.push(curLinearRing)
358 } else {
359 const polygonFromLinearRing = polygon([curLinearRing])
360 const linearRingArea = area.geometry(polygonFromLinearRing.geometry)
361
362 // only include holes with relevant area
363 if (linearRingArea > 1) {
364 filteredLinearRings.push(curLinearRing)
365 }
366 }
367 })
368
369 filteredPolygons.push(filteredLinearRings)
370 })
371
372 // recompile to geojson string
373 const newGeojson = {
374 type: geojson.type
375 }
376
377 if (geojson.type === 'Polygon') {
378 newGeojson.coordinates = filteredPolygons[0]
379 } else {
380 newGeojson.coordinates = filteredPolygons
381 }
382
evansiroky26325842018-04-03 14:10:42 -0700383 return returnAsObject ? newGeojson : JSON.stringify(newGeojson)
Evan Siroky477ece62017-08-01 07:08:51 -0700384}
385
evansiroky5348a6f2019-01-05 15:39:28 -0800386const buildingProgress = new ProgressStats(
387 'Building',
388 Object.keys(zoneCfg).length
389)
390
Evan Siroky7891a6e2016-11-05 11:50:50 -0700391var makeTimezoneBoundary = function (tzid, callback) {
evansiroky3046a3d2019-01-05 21:19:14 -0800392 buildingProgress.beginTask(`makeTimezoneBoundary for ${tzid}`, true)
evansiroky35f64342016-06-16 22:17:04 -0700393
Evan Siroky7891a6e2016-11-05 11:50:50 -0700394 var ops = zoneCfg[tzid]
395 var geom
evansiroky4be1c7a2016-06-16 18:23:34 -0700396
Evan Siroky7891a6e2016-11-05 11:50:50 -0700397 asynclib.eachSeries(ops, function (task, cb) {
evansiroky4be1c7a2016-06-16 18:23:34 -0700398 var taskData = getDataSource(task)
evansiroky6f9d8f72016-06-21 16:27:54 -0700399 console.log('-', task.op, task.id)
Evan Siroky7891a6e2016-11-05 11:50:50 -0700400 if (task.op === 'init') {
evansiroky4be1c7a2016-06-16 18:23:34 -0700401 geom = taskData
Evan Siroky7891a6e2016-11-05 11:50:50 -0700402 } else if (task.op === 'intersect') {
evansiroky6f9d8f72016-06-21 16:27:54 -0700403 geom = debugGeo('intersection', geom, taskData)
Evan Siroky7891a6e2016-11-05 11:50:50 -0700404 } else if (task.op === 'difference') {
evansiroky6f9d8f72016-06-21 16:27:54 -0700405 geom = debugGeo('diff', geom, taskData)
Evan Siroky7891a6e2016-11-05 11:50:50 -0700406 } else if (task.op === 'difference-reverse-order') {
Evan Siroky8ccaf0b2016-09-03 11:36:13 -0700407 geom = debugGeo('diff', taskData, geom)
Evan Siroky7891a6e2016-11-05 11:50:50 -0700408 } else if (task.op === 'union') {
evansiroky6f9d8f72016-06-21 16:27:54 -0700409 geom = debugGeo('union', geom, taskData)
Evan Siroky8ccaf0b2016-09-03 11:36:13 -0700410 } else {
411 var err = new Error('unknown op: ' + task.op)
412 return cb(err)
evansiroky4be1c7a2016-06-16 18:23:34 -0700413 }
evansiroky35f64342016-06-16 22:17:04 -0700414 cb()
Evan Siroky4fc596c2016-09-25 19:52:30 -0700415 },
Evan Siroky7891a6e2016-11-05 11:50:50 -0700416 function (err) {
417 if (err) { return callback(err) }
Evan Siroky4fc596c2016-09-25 19:52:30 -0700418 fs.writeFile(getTzDistFilename(tzid),
Evan Siroky477ece62017-08-01 07:08:51 -0700419 postProcessZone(geom),
evansirokybecb56e2016-07-06 12:42:35 -0700420 callback)
evansiroky4be1c7a2016-06-16 18:23:34 -0700421 })
422}
423
Evan Siroky4fc596c2016-09-25 19:52:30 -0700424var loadDistZonesIntoMemory = function () {
425 console.log('load zones into memory')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700426 var zones = Object.keys(zoneCfg)
427 var tzid
Evan Siroky4fc596c2016-09-25 19:52:30 -0700428
429 for (var i = 0; i < zones.length; i++) {
430 tzid = zones[i]
431 distZones[tzid] = getDataSource({ source: 'dist', id: tzid })
432 }
433}
434
435var getDistZoneGeom = function (tzid) {
436 return distZones[tzid]
437}
438
evansiroky92c15c42018-11-15 20:58:18 -0800439var roundDownToTenth = function (n) {
440 return Math.floor(n * 10) / 10
441}
442
443var roundUpToTenth = function (n) {
444 return Math.ceil(n * 10) / 10
445}
446
447var formatBounds = function (bounds) {
448 let boundsStr = '['
449 boundsStr += roundDownToTenth(bounds[0]) + ', '
450 boundsStr += roundDownToTenth(bounds[1]) + ', '
451 boundsStr += roundUpToTenth(bounds[2]) + ', '
452 boundsStr += roundUpToTenth(bounds[3]) + ']'
453 return boundsStr
454}
455
Evan Siroky4fc596c2016-09-25 19:52:30 -0700456var validateTimezoneBoundaries = function () {
evansiroky5348a6f2019-01-05 15:39:28 -0800457 const numZones = Object.keys(zoneCfg).length
458 const validationProgress = new ProgressStats(
459 'Validation',
460 numZones * (numZones + 1) / 2
461 )
462
evansiroky26325842018-04-03 14:10:42 -0700463 console.log('do validation... this may take a few minutes')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700464 var allZonesOk = true
465 var zones = Object.keys(zoneCfg)
evansiroky3046a3d2019-01-05 21:19:14 -0800466 var lastPct = 0
Evan Siroky7891a6e2016-11-05 11:50:50 -0700467 var compareTzid, tzid, zoneGeom
Evan Siroky4fc596c2016-09-25 19:52:30 -0700468
469 for (var i = 0; i < zones.length; i++) {
470 tzid = zones[i]
471 zoneGeom = getDistZoneGeom(tzid)
472
473 for (var j = i + 1; j < zones.length; j++) {
evansiroky3046a3d2019-01-05 21:19:14 -0800474 const curPct = Math.floor(validationProgress.getPercentage())
475 if (curPct % 10 === 0 && curPct !== lastPct) {
evansiroky5348a6f2019-01-05 15:39:28 -0800476 validationProgress.printStats('Validating zones', true)
evansiroky3046a3d2019-01-05 21:19:14 -0800477 lastPct = curPct
evansiroky5348a6f2019-01-05 15:39:28 -0800478 }
Evan Siroky4fc596c2016-09-25 19:52:30 -0700479 compareTzid = zones[j]
480
481 var compareZoneGeom = getDistZoneGeom(compareTzid)
Evan Siroky070bbb92017-03-07 23:48:29 -0800482
483 var intersects = false
484 try {
485 intersects = debugGeo('intersects', zoneGeom, compareZoneGeom)
486 } catch (e) {
487 console.warn('warning, encountered intersection error with zone ' + tzid + ' and ' + compareTzid)
488 }
489 if (intersects) {
Evan Siroky7891a6e2016-11-05 11:50:50 -0700490 var intersectedGeom = debugGeo('intersection', zoneGeom, compareZoneGeom)
491 var intersectedArea = intersectedGeom.getArea()
Evan Siroky4fc596c2016-09-25 19:52:30 -0700492
Evan Siroky7891a6e2016-11-05 11:50:50 -0700493 if (intersectedArea > 0.0001) {
evansiroky0ea1d1e2018-10-30 22:30:51 -0700494 // check if the intersected area(s) are one of the expected areas of overlap
495 const allowedOverlapBounds = expectedZoneOverlaps[`${tzid}-${compareTzid}`] || expectedZoneOverlaps[`${compareTzid}-${tzid}`]
496 const overlapsGeoJson = geoJsonWriter.write(intersectedGeom)
497
498 // these zones are allowed to overlap in certain places, make sure the
499 // found overlap(s) all fit within the expected areas of overlap
500 if (allowedOverlapBounds) {
501 // if the overlaps are a multipolygon, make sure each individual
502 // polygon of overlap fits within at least one of the expected
503 // overlaps
504 let overlapsPolygons
505 switch (overlapsGeoJson.type) {
evansiroky92c15c42018-11-15 20:58:18 -0800506 case 'MultiPolygon':
507 overlapsPolygons = overlapsGeoJson.coordinates.map(
508 polygonCoords => ({
509 coordinates: polygonCoords,
510 type: 'Polygon'
511 })
512 )
513 break
evansiroky0ea1d1e2018-10-30 22:30:51 -0700514 case 'Polygon':
515 overlapsPolygons = [overlapsGeoJson]
516 break
evansiroky92c15c42018-11-15 20:58:18 -0800517 case 'GeometryCollection':
518 overlapsPolygons = []
519 overlapsGeoJson.geometries.forEach(geom => {
520 if (geom.type === 'Polygon') {
521 overlapsPolygons.push(geom)
522 } else if (geom.type === 'MultiPolygon') {
523 geom.coordinates.forEach(polygonCoords => {
524 overlapsPolygons.push({
525 coordinates: polygonCoords,
526 type: 'Polygon'
527 })
528 })
529 }
530 })
531 break
evansiroky0ea1d1e2018-10-30 22:30:51 -0700532 default:
evansiroky92c15c42018-11-15 20:58:18 -0800533 console.error('unexpected geojson overlap type')
534 console.log(overlapsGeoJson)
evansiroky0ea1d1e2018-10-30 22:30:51 -0700535 break
536 }
537
538 let allOverlapsOk = true
539 overlapsPolygons.forEach((polygon, idx) => {
540 const bounds = bbox(polygon)
evansiroky92c15c42018-11-15 20:58:18 -0800541 const polygonArea = area.geometry(polygon)
evansiroky0ea1d1e2018-10-30 22:30:51 -0700542 if (
evansiroky92c15c42018-11-15 20:58:18 -0800543 polygonArea > 10 && // ignore small polygons
evansiroky0ea1d1e2018-10-30 22:30:51 -0700544 !allowedOverlapBounds.some(allowedBounds =>
evansiroky92c15c42018-11-15 20:58:18 -0800545 allowedBounds.bounds[0] <= bounds[0] && // minX
546 allowedBounds.bounds[1] <= bounds[1] && // minY
547 allowedBounds.bounds[2] >= bounds[2] && // maxX
548 allowedBounds.bounds[3] >= bounds[3] // maxY
evansiroky0ea1d1e2018-10-30 22:30:51 -0700549 )
550 ) {
evansiroky92c15c42018-11-15 20:58:18 -0800551 console.error(`Unexpected intersection (${polygonArea} area) with bounds: ${formatBounds(bounds)}`)
evansiroky0ea1d1e2018-10-30 22:30:51 -0700552 allOverlapsOk = false
553 }
554 })
555
556 if (allOverlapsOk) continue
557 }
558
evansiroky92c15c42018-11-15 20:58:18 -0800559 // at least one unexpected overlap found, output an error and write debug file
evansiroky70b35fe2018-04-01 21:06:36 -0700560 console.error('Validation error: ' + tzid + ' intersects ' + compareTzid + ' area: ' + intersectedArea)
evansiroky92c15c42018-11-15 20:58:18 -0800561 const debugFilename = tzid.replace(/\//g, '-') + '-' + compareTzid.replace(/\//g, '-') + '-overlap.json'
evansiroky70b35fe2018-04-01 21:06:36 -0700562 fs.writeFileSync(
563 debugFilename,
evansiroky0ea1d1e2018-10-30 22:30:51 -0700564 JSON.stringify(overlapsGeoJson)
evansiroky70b35fe2018-04-01 21:06:36 -0700565 )
566 console.error('wrote overlap area as file ' + debugFilename)
567 console.error('To read more about this error, please visit https://git.io/vx6nx')
Evan Siroky4fc596c2016-09-25 19:52:30 -0700568 allZonesOk = false
569 }
570 }
evansiroky5348a6f2019-01-05 15:39:28 -0800571 validationProgress.logNext()
Evan Siroky4fc596c2016-09-25 19:52:30 -0700572 }
573 }
574
575 return allZonesOk ? null : 'Zone validation unsuccessful'
Evan Siroky4fc596c2016-09-25 19:52:30 -0700576}
577
evansiroky26325842018-04-03 14:10:42 -0700578let oceanZoneBoundaries
evansiroky9fd50512019-07-07 12:06:28 -0700579let oceanZones = [
580 { tzid: 'Etc/GMT-12', left: 172.5, right: 180 },
581 { tzid: 'Etc/GMT-11', left: 157.5, right: 172.5 },
582 { tzid: 'Etc/GMT-10', left: 142.5, right: 157.5 },
583 { tzid: 'Etc/GMT-9', left: 127.5, right: 142.5 },
584 { tzid: 'Etc/GMT-8', left: 112.5, right: 127.5 },
585 { tzid: 'Etc/GMT-7', left: 97.5, right: 112.5 },
586 { tzid: 'Etc/GMT-6', left: 82.5, right: 97.5 },
587 { tzid: 'Etc/GMT-5', left: 67.5, right: 82.5 },
588 { tzid: 'Etc/GMT-4', left: 52.5, right: 67.5 },
589 { tzid: 'Etc/GMT-3', left: 37.5, right: 52.5 },
590 { tzid: 'Etc/GMT-2', left: 22.5, right: 37.5 },
591 { tzid: 'Etc/GMT-1', left: 7.5, right: 22.5 },
592 { tzid: 'Etc/GMT', left: -7.5, right: 7.5 },
593 { tzid: 'Etc/GMT+1', left: -22.5, right: -7.5 },
594 { tzid: 'Etc/GMT+2', left: -37.5, right: -22.5 },
595 { tzid: 'Etc/GMT+3', left: -52.5, right: -37.5 },
596 { tzid: 'Etc/GMT+4', left: -67.5, right: -52.5 },
597 { tzid: 'Etc/GMT+5', left: -82.5, right: -67.5 },
598 { tzid: 'Etc/GMT+6', left: -97.5, right: -82.5 },
599 { tzid: 'Etc/GMT+7', left: -112.5, right: -97.5 },
600 { tzid: 'Etc/GMT+8', left: -127.5, right: -112.5 },
601 { tzid: 'Etc/GMT+9', left: -142.5, right: -127.5 },
602 { tzid: 'Etc/GMT+10', left: -157.5, right: -142.5 },
603 { tzid: 'Etc/GMT+11', left: -172.5, right: -157.5 },
604 { tzid: 'Etc/GMT+12', left: -180, right: -172.5 }
605]
606
Neil Fullerc4ae49b2020-04-30 18:08:43 +0100607if (includedZones.length > 0) {
608 oceanZones = oceanZones.filter(oceanZone => includedZones.indexOf(oceanZone) > -1)
evansiroky9fd50512019-07-07 12:06:28 -0700609}
Neil Fuller2b4b80a2020-04-30 18:20:56 +0100610if (excludedZones.length > 0) {
611 oceanZones = oceanZones.filter(oceanZone => excludedZones.indexOf(oceanZone) === -1)
612}
evansiroky26325842018-04-03 14:10:42 -0700613
614var addOceans = function (callback) {
615 console.log('adding ocean boundaries')
evansiroky26325842018-04-03 14:10:42 -0700616 const zones = Object.keys(zoneCfg)
617
evansiroky3046a3d2019-01-05 21:19:14 -0800618 const oceanProgress = new ProgressStats(
619 'Oceans',
620 oceanZones.length
621 )
622
evansiroky26325842018-04-03 14:10:42 -0700623 oceanZoneBoundaries = oceanZones.map(zone => {
evansiroky3046a3d2019-01-05 21:19:14 -0800624 oceanProgress.beginTask(zone.tzid, true)
evansiroky26325842018-04-03 14:10:42 -0700625 const geoJson = polygon([[
626 [zone.left, 90],
evansiroky0ea1d1e2018-10-30 22:30:51 -0700627 [zone.left, -90],
628 [zone.right, -90],
629 [zone.right, 90],
evansiroky26325842018-04-03 14:10:42 -0700630 [zone.left, 90]
631 ]]).geometry
632
633 let geom = geoJsonToGeom(geoJson)
634
635 // diff against every zone
636 zones.forEach(distZone => {
637 geom = debugGeo('diff', geom, getDistZoneGeom(distZone))
638 })
639
640 return {
641 geom: postProcessZone(geom, true),
642 tzid: zone.tzid
643 }
644 })
645
646 callback()
647}
648
Evan Siroky7891a6e2016-11-05 11:50:50 -0700649var combineAndWriteZones = function (callback) {
Evan Siroky8b47abe2016-10-02 12:28:52 -0700650 var stream = fs.createWriteStream('./dist/combined.json')
evansiroky26325842018-04-03 14:10:42 -0700651 var streamWithOceans = fs.createWriteStream('./dist/combined-with-oceans.json')
Evan Siroky8b47abe2016-10-02 12:28:52 -0700652 var zones = Object.keys(zoneCfg)
653
654 stream.write('{"type":"FeatureCollection","features":[')
evansiroky26325842018-04-03 14:10:42 -0700655 streamWithOceans.write('{"type":"FeatureCollection","features":[')
Evan Siroky8b47abe2016-10-02 12:28:52 -0700656
657 for (var i = 0; i < zones.length; i++) {
Evan Siroky7891a6e2016-11-05 11:50:50 -0700658 if (i > 0) {
Evan Siroky8b47abe2016-10-02 12:28:52 -0700659 stream.write(',')
evansiroky26325842018-04-03 14:10:42 -0700660 streamWithOceans.write(',')
Evan Siroky8b47abe2016-10-02 12:28:52 -0700661 }
662 var feature = {
663 type: 'Feature',
664 properties: { tzid: zones[i] },
665 geometry: geomToGeoJson(getDistZoneGeom(zones[i]))
666 }
evansiroky26325842018-04-03 14:10:42 -0700667 const stringified = JSON.stringify(feature)
668 stream.write(stringified)
669 streamWithOceans.write(stringified)
Evan Siroky8b47abe2016-10-02 12:28:52 -0700670 }
evansiroky26325842018-04-03 14:10:42 -0700671 oceanZoneBoundaries.forEach(boundary => {
672 streamWithOceans.write(',')
673 var feature = {
674 type: 'Feature',
675 properties: { tzid: boundary.tzid },
676 geometry: boundary.geom
677 }
678 streamWithOceans.write(JSON.stringify(feature))
679 })
680 asynclib.parallel([
681 cb => {
682 stream.end(']}', cb)
683 },
684 cb => {
685 streamWithOceans.end(']}', cb)
686 }
687 ], callback)
Evan Siroky8b47abe2016-10-02 12:28:52 -0700688}
689
evansiroky5348a6f2019-01-05 15:39:28 -0800690const autoScript = {
Evan Siroky7891a6e2016-11-05 11:50:50 -0700691 makeDownloadsDir: function (cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800692 overallProgress.beginTask('Creating downloads dir')
evansiroky4be1c7a2016-06-16 18:23:34 -0700693 safeMkdir('./downloads', cb)
694 },
Evan Siroky7891a6e2016-11-05 11:50:50 -0700695 makeDistDir: function (cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800696 overallProgress.beginTask('Creating dist dir')
evansiroky4be1c7a2016-06-16 18:23:34 -0700697 safeMkdir('./dist', cb)
evansirokyd401c892016-06-16 00:05:14 -0700698 },
Evan Siroky7891a6e2016-11-05 11:50:50 -0700699 getOsmBoundaries: ['makeDownloadsDir', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800700 overallProgress.beginTask('Downloading osm boundaries')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700701 asynclib.eachSeries(Object.keys(osmBoundarySources), downloadOsmBoundary, cb)
evansiroky63d35e12016-06-16 10:08:15 -0700702 }],
evansirokya48b3922020-04-27 15:29:06 -0700703 zipInputData: ['makeDistDir', 'getOsmBoundaries', function (results, cb) {
704 overallProgress.beginTask('Zipping up input data')
705 exec('zip dist/input-data.zip downloads/* timezones.json osmBoundarySources.json expectedZoneOverlaps.json', cb)
706 }],
Evan Siroky7891a6e2016-11-05 11:50:50 -0700707 createZones: ['makeDistDir', 'getOsmBoundaries', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800708 overallProgress.beginTask('Creating timezone boundaries')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700709 asynclib.each(Object.keys(zoneCfg), makeTimezoneBoundary, cb)
evansiroky50216c62016-06-16 17:41:47 -0700710 }],
Evan Siroky7891a6e2016-11-05 11:50:50 -0700711 validateZones: ['createZones', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800712 overallProgress.beginTask('Validating timezone boundaries')
Evan Siroky4fc596c2016-09-25 19:52:30 -0700713 loadDistZonesIntoMemory()
Neil Fullerc4ae49b2020-04-30 18:08:43 +0100714 if (argv.no_validation) {
Evan Siroky081648a2017-07-04 09:53:36 -0700715 console.warn('WARNING: Skipping validation!')
716 cb()
717 } else {
718 cb(validateTimezoneBoundaries())
719 }
Evan Siroky4fc596c2016-09-25 19:52:30 -0700720 }],
evansiroky26325842018-04-03 14:10:42 -0700721 addOceans: ['validateZones', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800722 overallProgress.beginTask('Adding oceans')
evansiroky26325842018-04-03 14:10:42 -0700723 addOceans(cb)
724 }],
725 mergeZones: ['addOceans', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800726 overallProgress.beginTask('Merging zones')
Evan Siroky8b47abe2016-10-02 12:28:52 -0700727 combineAndWriteZones(cb)
728 }],
729 zipGeoJson: ['mergeZones', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800730 overallProgress.beginTask('Zipping geojson')
Evan Siroky8b47abe2016-10-02 12:28:52 -0700731 exec('zip dist/timezones.geojson.zip dist/combined.json', cb)
732 }],
evansiroky26325842018-04-03 14:10:42 -0700733 zipGeoJsonWithOceans: ['mergeZones', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800734 overallProgress.beginTask('Zipping geojson with oceans')
evansiroky26325842018-04-03 14:10:42 -0700735 exec('zip dist/timezones-with-oceans.geojson.zip dist/combined-with-oceans.json', cb)
736 }],
Evan Siroky8b47abe2016-10-02 12:28:52 -0700737 makeShapefile: ['mergeZones', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800738 overallProgress.beginTask('Converting from geojson to shapefile')
evansiroky26325842018-04-03 14:10:42 -0700739 rimraf.sync('dist/combined-shapefile.*')
740 exec(
evansirokye3360f72018-11-16 09:24:26 -0800741 'ogr2ogr -f "ESRI Shapefile" dist/combined-shapefile.shp dist/combined.json',
evansiroky26325842018-04-03 14:10:42 -0700742 function (err, stdout, stderr) {
743 if (err) { return cb(err) }
744 exec('zip dist/timezones.shapefile.zip dist/combined-shapefile.*', cb)
745 }
746 )
747 }],
748 makeShapefileWithOceans: ['mergeZones', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800749 overallProgress.beginTask('Converting from geojson with oceans to shapefile')
evansiroky26325842018-04-03 14:10:42 -0700750 rimraf.sync('dist/combined-shapefile-with-oceans.*')
751 exec(
evansirokye3360f72018-11-16 09:24:26 -0800752 'ogr2ogr -f "ESRI Shapefile" dist/combined-shapefile-with-oceans.shp dist/combined-with-oceans.json',
evansiroky26325842018-04-03 14:10:42 -0700753 function (err, stdout, stderr) {
754 if (err) { return cb(err) }
755 exec('zip dist/timezones-with-oceans.shapefile.zip dist/combined-shapefile-with-oceans.*', cb)
756 }
757 )
evansiroky9fd50512019-07-07 12:06:28 -0700758 }],
759 makeListOfTimeZoneNames: function (cb) {
760 overallProgress.beginTask('Writing timezone names to file')
761 let zoneNames = Object.keys(zoneCfg)
762 oceanZones.forEach(oceanZone => {
763 zoneNames.push(oceanZone.tzid)
764 })
Neil Fullerc4ae49b2020-04-30 18:08:43 +0100765 if (includedZones.length > 0) {
766 zoneNames = zoneNames.filter(zoneName => includedZones.indexOf(zoneName) > -1)
evansiroky9fd50512019-07-07 12:06:28 -0700767 }
Neil Fuller2b4b80a2020-04-30 18:20:56 +0100768 if (excludedZones.length > 0) {
769 zoneNames = zoneNames.filter(zoneName => excludedZones.indexOf(zoneName) === -1)
770 }
evansiroky9fd50512019-07-07 12:06:28 -0700771 fs.writeFile(
772 'dist/timezone-names.json',
773 JSON.stringify(zoneNames),
774 cb
775 )
776 }
evansiroky5348a6f2019-01-05 15:39:28 -0800777}
778
779const overallProgress = new ProgressStats('Overall', Object.keys(autoScript).length)
780
781asynclib.auto(autoScript, function (err, results) {
evansirokyd401c892016-06-16 00:05:14 -0700782 console.log('done')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700783 if (err) {
evansirokyd401c892016-06-16 00:05:14 -0700784 console.log('error!', err)
evansirokyd401c892016-06-16 00:05:14 -0700785 }
Evan Siroky4fc596c2016-09-25 19:52:30 -0700786})