blob: 771ad2452f5e8a16d08ba0288d766cda6129259b [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 Fullera4e73272020-04-30 18:25:44 +010031 .option('downloads_dir', {
32 description: 'Set the download location',
33 default: './downloads',
34 type: 'string'
35 })
36 .option('dist_dir', {
37 description: 'Set the dist location',
38 default: './dist',
39 type: 'string'
40 })
Neil Fullerc4ae49b2020-04-30 18:08:43 +010041 .option('no_validation', {
42 description: 'Skip validation',
43 type: 'boolean'
44 })
45 .help()
46 .strict()
47 .alias('help', 'h')
48 .argv
49
Evan Siroky081648a2017-07-04 09:53:36 -070050// allow building of only a specified zones
Neil Fullerc4ae49b2020-04-30 18:08:43 +010051let includedZones = []
Neil Fuller2b4b80a2020-04-30 18:20:56 +010052let excludedZones = []
53if (argv.included_zones || argv.excluded_zones) {
54 if (argv.included_zones) {
55 let newZoneCfg = {}
56 includedZones = argv.included_zones
57 includedZones.forEach((zoneName) => {
58 newZoneCfg[zoneName] = zoneCfg[zoneName]
59 })
60 zoneCfg = newZoneCfg
61 }
62 if (argv.excluded_zones) {
63 let newZoneCfg = {}
64 excludedZones = argv.excluded_zones
65 Object.keys(zoneCfg).forEach((zoneName) => {
66 if (!excludedZones.includes(zoneName)) {
67 newZoneCfg[zoneName] = zoneCfg[zoneName]
68 }
69 })
70 zoneCfg = newZoneCfg
71 }
Evan Siroky081648a2017-07-04 09:53:36 -070072
73 // filter out unneccessary downloads
74 var newOsmBoundarySources = {}
75 Object.keys(zoneCfg).forEach((zoneName) => {
76 zoneCfg[zoneName].forEach((op) => {
77 if (op.source === 'overpass') {
78 newOsmBoundarySources[op.id] = osmBoundarySources[op.id]
79 }
80 })
81 })
82
83 osmBoundarySources = newOsmBoundarySources
84}
85
Evan Siroky7891a6e2016-11-05 11:50:50 -070086var geoJsonReader = new jsts.io.GeoJSONReader()
87var geoJsonWriter = new jsts.io.GeoJSONWriter()
Evan Siroky477ece62017-08-01 07:08:51 -070088var precisionModel = new jsts.geom.PrecisionModel(1000000)
89var precisionReducer = new jsts.precision.GeometryPrecisionReducer(precisionModel)
Evan Siroky7891a6e2016-11-05 11:50:50 -070090var distZones = {}
Evan Sirokyb57a5b92016-11-07 10:22:34 -080091var minRequestGap = 4
92var curRequestGap = 4
evansirokyd401c892016-06-16 00:05:14 -070093
Evan Siroky7891a6e2016-11-05 11:50:50 -070094var safeMkdir = function (dirname, callback) {
95 fs.mkdir(dirname, function (err) {
96 if (err && err.code === 'EEXIST') {
evansiroky4be1c7a2016-06-16 18:23:34 -070097 callback()
98 } else {
99 callback(err)
100 }
101 })
102}
103
Evan Sirokyb173fd42017-03-08 15:16:27 -0800104var debugGeo = function (op, a, b, reducePrecision) {
evansirokybecb56e2016-07-06 12:42:35 -0700105 var result
106
Evan Sirokyb173fd42017-03-08 15:16:27 -0800107 if (reducePrecision) {
Evan Sirokyb173fd42017-03-08 15:16:27 -0800108 a = precisionReducer.reduce(a)
109 b = precisionReducer.reduce(b)
110 }
111
evansiroky6f9d8f72016-06-21 16:27:54 -0700112 try {
Evan Siroky7891a6e2016-11-05 11:50:50 -0700113 switch (op) {
evansiroky6f9d8f72016-06-21 16:27:54 -0700114 case 'union':
evansirokybecb56e2016-07-06 12:42:35 -0700115 result = a.union(b)
evansiroky6f9d8f72016-06-21 16:27:54 -0700116 break
117 case 'intersection':
evansirokybecb56e2016-07-06 12:42:35 -0700118 result = a.intersection(b)
evansiroky6f9d8f72016-06-21 16:27:54 -0700119 break
Evan Siroky070bbb92017-03-07 23:48:29 -0800120 case 'intersects':
121 result = a.intersects(b)
122 break
evansiroky6f9d8f72016-06-21 16:27:54 -0700123 case 'diff':
Evan Sirokyb173fd42017-03-08 15:16:27 -0800124 result = a.difference(b)
evansiroky6f9d8f72016-06-21 16:27:54 -0700125 break
126 default:
127 var err = new Error('invalid op: ' + op)
128 throw err
129 }
Evan Siroky7891a6e2016-11-05 11:50:50 -0700130 } catch (e) {
Evan Sirokyb173fd42017-03-08 15:16:27 -0800131 if (e.name === 'TopologyException') {
132 console.log('Encountered TopologyException, retry with GeometryPrecisionReducer')
133 return debugGeo(op, a, b, true)
134 }
evansiroky6f9d8f72016-06-21 16:27:54 -0700135 console.log('op err')
evansirokybecb56e2016-07-06 12:42:35 -0700136 console.log(e)
137 console.log(e.stack)
138 fs.writeFileSync('debug_' + op + '_a.json', JSON.stringify(geoJsonWriter.write(a)))
139 fs.writeFileSync('debug_' + op + '_b.json', JSON.stringify(geoJsonWriter.write(b)))
evansiroky6f9d8f72016-06-21 16:27:54 -0700140 throw e
141 }
evansiroky6f9d8f72016-06-21 16:27:54 -0700142
evansirokybecb56e2016-07-06 12:42:35 -0700143 return result
evansiroky4be1c7a2016-06-16 18:23:34 -0700144}
145
Evan Siroky070bbb92017-03-07 23:48:29 -0800146var fetchIfNeeded = function (file, superCallback, downloadCallback, fetchFn) {
147 // check for file that got downloaded
Evan Siroky7891a6e2016-11-05 11:50:50 -0700148 fs.stat(file, function (err) {
Evan Siroky070bbb92017-03-07 23:48:29 -0800149 if (!err) {
150 // file found, skip download steps
151 return superCallback()
152 }
153 // check for manual file that got fixed and needs validation
154 var fixedFile = file.replace('.json', '_fixed.json')
155 fs.stat(fixedFile, function (err) {
156 if (!err) {
157 // file found, return fixed file
158 return downloadCallback(null, require(fixedFile))
159 }
160 // no manual fixed file found, download from overpass
161 fetchFn()
162 })
evansiroky50216c62016-06-16 17:41:47 -0700163 })
164}
165
Evan Siroky7891a6e2016-11-05 11:50:50 -0700166var geoJsonToGeom = function (geoJson) {
Evan Siroky8326cf02017-03-02 08:27:55 -0800167 try {
168 return geoJsonReader.read(JSON.stringify(geoJson))
169 } catch (e) {
170 console.error('error converting geojson to geometry')
171 fs.writeFileSync('debug_geojson_read_error.json', JSON.stringify(geoJson))
172 throw e
173 }
Evan Siroky5669adc2016-07-07 17:25:31 -0700174}
175
Evan Siroky8b47abe2016-10-02 12:28:52 -0700176var geomToGeoJson = function (geom) {
177 return geoJsonWriter.write(geom)
178}
179
Evan Siroky7891a6e2016-11-05 11:50:50 -0700180var geomToGeoJsonString = function (geom) {
Evan Siroky5669adc2016-07-07 17:25:31 -0700181 return JSON.stringify(geoJsonWriter.write(geom))
182}
183
evansiroky5348a6f2019-01-05 15:39:28 -0800184const downloadProgress = new ProgressStats(
185 'Downloading',
186 Object.keys(osmBoundarySources).length
187)
188
Evan Siroky7891a6e2016-11-05 11:50:50 -0700189var downloadOsmBoundary = function (boundaryId, boundaryCallback) {
190 var cfg = osmBoundarySources[boundaryId]
Evan Siroky1bcd4772017-10-14 23:47:21 -0700191 var query = '[out:json][timeout:60];('
192 if (cfg.way) {
193 query += 'way'
194 } else {
195 query += 'relation'
196 }
Neil Fullera4e73272020-04-30 18:25:44 +0100197 var boundaryFilename = argv.downloads_dir + '/' + boundaryId + '.json'
Evan Siroky7891a6e2016-11-05 11:50:50 -0700198 var debug = 'getting data for ' + boundaryId
199 var queryKeys = Object.keys(cfg)
evansiroky63d35e12016-06-16 10:08:15 -0700200
Evan Siroky5669adc2016-07-07 17:25:31 -0700201 for (var i = queryKeys.length - 1; i >= 0; i--) {
Evan Siroky7891a6e2016-11-05 11:50:50 -0700202 var k = queryKeys[i]
Evan Siroky1bcd4772017-10-14 23:47:21 -0700203 if (k === 'way') continue
Evan Siroky7891a6e2016-11-05 11:50:50 -0700204 var v = cfg[k]
Evan Siroky5669adc2016-07-07 17:25:31 -0700205
206 query += '["' + k + '"="' + v + '"]'
evansiroky63d35e12016-06-16 10:08:15 -0700207 }
208
evansiroky283ebbc2018-07-16 15:13:07 -0700209 query += ';);out body;>;out meta qt;'
evansiroky4be1c7a2016-06-16 18:23:34 -0700210
evansiroky5348a6f2019-01-05 15:39:28 -0800211 downloadProgress.beginTask(debug, true)
evansiroky63d35e12016-06-16 10:08:15 -0700212
Evan Siroky7891a6e2016-11-05 11:50:50 -0700213 asynclib.auto({
214 downloadFromOverpass: function (cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800215 console.log('downloading from overpass')
Evan Siroky070bbb92017-03-07 23:48:29 -0800216 fetchIfNeeded(boundaryFilename, boundaryCallback, cb, function () {
Evan Sirokyb57a5b92016-11-07 10:22:34 -0800217 var overpassResponseHandler = function (err, data) {
218 if (err) {
219 console.log(err)
220 console.log('Increasing overpass request gap')
221 curRequestGap *= 2
222 makeQuery()
223 } else {
224 console.log('Success, decreasing overpass request gap')
225 curRequestGap = Math.max(minRequestGap, curRequestGap / 2)
226 cb(null, data)
227 }
228 }
229 var makeQuery = function () {
230 console.log('waiting ' + curRequestGap + ' seconds')
231 setTimeout(function () {
232 overpass(query, overpassResponseHandler, { flatProperties: true })
233 }, curRequestGap * 1000)
234 }
235 makeQuery()
evansiroky63d35e12016-06-16 10:08:15 -0700236 })
237 },
Evan Siroky7891a6e2016-11-05 11:50:50 -0700238 validateOverpassResult: ['downloadFromOverpass', function (results, cb) {
evansiroky63d35e12016-06-16 10:08:15 -0700239 var data = results.downloadFromOverpass
evansiroky70b35fe2018-04-01 21:06:36 -0700240 if (!data.features) {
Evan Siroky7891a6e2016-11-05 11:50:50 -0700241 var err = new Error('Invalid geojson for boundary: ' + boundaryId)
evansiroky63d35e12016-06-16 10:08:15 -0700242 return cb(err)
243 }
evansiroky70b35fe2018-04-01 21:06:36 -0700244 if (data.features.length === 0) {
245 console.error('No data for the following query:')
246 console.error(query)
247 console.error('To read more about this error, please visit https://git.io/vxKQL')
evansiroky0ea1d1e2018-10-30 22:30:51 -0700248 return cb(new Error('No data found for from overpass query'))
evansiroky70b35fe2018-04-01 21:06:36 -0700249 }
evansiroky63d35e12016-06-16 10:08:15 -0700250 cb()
251 }],
Evan Siroky7891a6e2016-11-05 11:50:50 -0700252 saveSingleMultiPolygon: ['validateOverpassResult', function (results, cb) {
253 var data = results.downloadFromOverpass
254 var combined
evansiroky63d35e12016-06-16 10:08:15 -0700255
256 // union all multi-polygons / polygons into one
257 for (var i = data.features.length - 1; i >= 0; i--) {
Evan Siroky5669adc2016-07-07 17:25:31 -0700258 var curOsmGeom = data.features[i].geometry
evansiroky92c15c42018-11-15 20:58:18 -0800259 const curOsmProps = data.features[i].properties
260 if (
261 (curOsmGeom.type === 'Polygon' || curOsmGeom.type === 'MultiPolygon') &&
262 curOsmProps.type === 'boundary' // need to make sure enclaves aren't unioned
263 ) {
evansiroky63d35e12016-06-16 10:08:15 -0700264 console.log('combining border')
evansiroky70b35fe2018-04-01 21:06:36 -0700265 let errors = geojsonhint.hint(curOsmGeom)
266 if (errors && errors.length > 0) {
267 const stringifiedGeojson = JSON.stringify(curOsmGeom, null, 2)
268 errors = geojsonhint.hint(stringifiedGeojson)
269 console.error('Invalid geojson received in Overpass Result')
270 console.error('Overpass query: ' + query)
271 const problemFilename = boundaryId + '_convert_to_geom_error.json'
272 fs.writeFileSync(problemFilename, stringifiedGeojson)
273 console.error('saved problem file to ' + problemFilename)
274 console.error('To read more about this error, please visit https://git.io/vxKQq')
275 return cb(errors)
276 }
Evan Siroky070bbb92017-03-07 23:48:29 -0800277 try {
278 var curGeom = geoJsonToGeom(curOsmGeom)
279 } catch (e) {
280 console.error('error converting overpass result to geojson')
Evan Siroky477ece62017-08-01 07:08:51 -0700281 console.error(e)
evansiroky70b35fe2018-04-01 21:06:36 -0700282
Evan Siroky1bcd4772017-10-14 23:47:21 -0700283 fs.writeFileSync(boundaryId + '_convert_to_geom_error-all-features.json', JSON.stringify(data))
evansiroky70b35fe2018-04-01 21:06:36 -0700284 return cb(e)
Evan Siroky070bbb92017-03-07 23:48:29 -0800285 }
Evan Siroky7891a6e2016-11-05 11:50:50 -0700286 if (!combined) {
evansiroky63d35e12016-06-16 10:08:15 -0700287 combined = curGeom
288 } else {
Evan Siroky5669adc2016-07-07 17:25:31 -0700289 combined = debugGeo('union', curGeom, combined)
evansiroky63d35e12016-06-16 10:08:15 -0700290 }
291 }
292 }
Evan Siroky081c8e42017-05-29 14:53:52 -0700293 try {
294 fs.writeFile(boundaryFilename, geomToGeoJsonString(combined), cb)
295 } catch (e) {
296 console.error('error writing combined border to geojson')
297 fs.writeFileSync(boundaryId + '_combined_border_convert_to_geom_error.json', JSON.stringify(data))
evansiroky70b35fe2018-04-01 21:06:36 -0700298 return cb(e)
Evan Siroky081c8e42017-05-29 14:53:52 -0700299 }
evansiroky63d35e12016-06-16 10:08:15 -0700300 }]
301 }, boundaryCallback)
302}
evansirokyd401c892016-06-16 00:05:14 -0700303
Evan Siroky4fc596c2016-09-25 19:52:30 -0700304var getTzDistFilename = function (tzid) {
Neil Fullera4e73272020-04-30 18:25:44 +0100305 return argv.dist_dir + '/' + tzid.replace(/\//g, '__') + '.json'
Evan Siroky4fc596c2016-09-25 19:52:30 -0700306}
307
308/**
309 * Get the geometry of the requested source data
310 *
311 * @return {Object} geom The geometry of the source
312 * @param {Object} source An object representing the data source
313 * must have `source` key and then either:
314 * - `id` if from a file
315 * - `id` if from a file
316 */
Evan Siroky7891a6e2016-11-05 11:50:50 -0700317var getDataSource = function (source) {
evansirokybecb56e2016-07-06 12:42:35 -0700318 var geoJson
Evan Siroky7891a6e2016-11-05 11:50:50 -0700319 if (source.source === 'overpass') {
Neil Fullera4e73272020-04-30 18:25:44 +0100320 geoJson = require(argv.downloads_dir + '/' + source.id + '.json')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700321 } else if (source.source === 'manual-polygon') {
evansirokybecb56e2016-07-06 12:42:35 -0700322 geoJson = polygon(source.data).geometry
Evan Siroky7891a6e2016-11-05 11:50:50 -0700323 } else if (source.source === 'manual-multipolygon') {
Evan Siroky8e30a2e2016-08-06 19:55:35 -0700324 geoJson = multiPolygon(source.data).geometry
Evan Siroky7891a6e2016-11-05 11:50:50 -0700325 } else if (source.source === 'dist') {
Evan Siroky4fc596c2016-09-25 19:52:30 -0700326 geoJson = require(getTzDistFilename(source.id))
evansiroky4be1c7a2016-06-16 18:23:34 -0700327 } else {
328 var err = new Error('unknown source: ' + source.source)
329 throw err
330 }
Evan Siroky5669adc2016-07-07 17:25:31 -0700331 return geoJsonToGeom(geoJson)
evansiroky4be1c7a2016-06-16 18:23:34 -0700332}
333
Evan Siroky477ece62017-08-01 07:08:51 -0700334/**
335 * Post process created timezone boundary.
336 * - remove small holes and exclaves
337 * - reduce geometry precision
338 *
339 * @param {Geometry} geom The jsts geometry of the timezone
evansiroky26325842018-04-03 14:10:42 -0700340 * @param {boolean} returnAsObject if true, return as object, otherwise return stringified
341 * @return {Object|String} geojson as object or stringified
Evan Siroky477ece62017-08-01 07:08:51 -0700342 */
evansiroky26325842018-04-03 14:10:42 -0700343var postProcessZone = function (geom, returnAsObject) {
Evan Siroky477ece62017-08-01 07:08:51 -0700344 // reduce precision of geometry
345 const geojson = geomToGeoJson(precisionReducer.reduce(geom))
346
347 // iterate through all polygons
348 const filteredPolygons = []
349 let allPolygons = geojson.coordinates
350 if (geojson.type === 'Polygon') {
351 allPolygons = [geojson.coordinates]
352 }
353
354 allPolygons.forEach((curPolygon, idx) => {
355 // remove any polygon with very small area
356 const polygonFeature = polygon(curPolygon)
357 const polygonArea = area.geometry(polygonFeature.geometry)
358
359 if (polygonArea < 1) return
360
361 // find all holes
362 const filteredLinearRings = []
363
364 curPolygon.forEach((curLinearRing, lrIdx) => {
365 if (lrIdx === 0) {
366 // always keep first linearRing
367 filteredLinearRings.push(curLinearRing)
368 } else {
369 const polygonFromLinearRing = polygon([curLinearRing])
370 const linearRingArea = area.geometry(polygonFromLinearRing.geometry)
371
372 // only include holes with relevant area
373 if (linearRingArea > 1) {
374 filteredLinearRings.push(curLinearRing)
375 }
376 }
377 })
378
379 filteredPolygons.push(filteredLinearRings)
380 })
381
382 // recompile to geojson string
383 const newGeojson = {
384 type: geojson.type
385 }
386
387 if (geojson.type === 'Polygon') {
388 newGeojson.coordinates = filteredPolygons[0]
389 } else {
390 newGeojson.coordinates = filteredPolygons
391 }
392
evansiroky26325842018-04-03 14:10:42 -0700393 return returnAsObject ? newGeojson : JSON.stringify(newGeojson)
Evan Siroky477ece62017-08-01 07:08:51 -0700394}
395
evansiroky5348a6f2019-01-05 15:39:28 -0800396const buildingProgress = new ProgressStats(
397 'Building',
398 Object.keys(zoneCfg).length
399)
400
Evan Siroky7891a6e2016-11-05 11:50:50 -0700401var makeTimezoneBoundary = function (tzid, callback) {
evansiroky3046a3d2019-01-05 21:19:14 -0800402 buildingProgress.beginTask(`makeTimezoneBoundary for ${tzid}`, true)
evansiroky35f64342016-06-16 22:17:04 -0700403
Evan Siroky7891a6e2016-11-05 11:50:50 -0700404 var ops = zoneCfg[tzid]
405 var geom
evansiroky4be1c7a2016-06-16 18:23:34 -0700406
Evan Siroky7891a6e2016-11-05 11:50:50 -0700407 asynclib.eachSeries(ops, function (task, cb) {
evansiroky4be1c7a2016-06-16 18:23:34 -0700408 var taskData = getDataSource(task)
evansiroky6f9d8f72016-06-21 16:27:54 -0700409 console.log('-', task.op, task.id)
Evan Siroky7891a6e2016-11-05 11:50:50 -0700410 if (task.op === 'init') {
evansiroky4be1c7a2016-06-16 18:23:34 -0700411 geom = taskData
Evan Siroky7891a6e2016-11-05 11:50:50 -0700412 } else if (task.op === 'intersect') {
evansiroky6f9d8f72016-06-21 16:27:54 -0700413 geom = debugGeo('intersection', geom, taskData)
Evan Siroky7891a6e2016-11-05 11:50:50 -0700414 } else if (task.op === 'difference') {
evansiroky6f9d8f72016-06-21 16:27:54 -0700415 geom = debugGeo('diff', geom, taskData)
Evan Siroky7891a6e2016-11-05 11:50:50 -0700416 } else if (task.op === 'difference-reverse-order') {
Evan Siroky8ccaf0b2016-09-03 11:36:13 -0700417 geom = debugGeo('diff', taskData, geom)
Evan Siroky7891a6e2016-11-05 11:50:50 -0700418 } else if (task.op === 'union') {
evansiroky6f9d8f72016-06-21 16:27:54 -0700419 geom = debugGeo('union', geom, taskData)
Evan Siroky8ccaf0b2016-09-03 11:36:13 -0700420 } else {
421 var err = new Error('unknown op: ' + task.op)
422 return cb(err)
evansiroky4be1c7a2016-06-16 18:23:34 -0700423 }
evansiroky35f64342016-06-16 22:17:04 -0700424 cb()
Evan Siroky4fc596c2016-09-25 19:52:30 -0700425 },
Evan Siroky7891a6e2016-11-05 11:50:50 -0700426 function (err) {
427 if (err) { return callback(err) }
Evan Siroky4fc596c2016-09-25 19:52:30 -0700428 fs.writeFile(getTzDistFilename(tzid),
Evan Siroky477ece62017-08-01 07:08:51 -0700429 postProcessZone(geom),
evansirokybecb56e2016-07-06 12:42:35 -0700430 callback)
evansiroky4be1c7a2016-06-16 18:23:34 -0700431 })
432}
433
Evan Siroky4fc596c2016-09-25 19:52:30 -0700434var loadDistZonesIntoMemory = function () {
435 console.log('load zones into memory')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700436 var zones = Object.keys(zoneCfg)
437 var tzid
Evan Siroky4fc596c2016-09-25 19:52:30 -0700438
439 for (var i = 0; i < zones.length; i++) {
440 tzid = zones[i]
441 distZones[tzid] = getDataSource({ source: 'dist', id: tzid })
442 }
443}
444
445var getDistZoneGeom = function (tzid) {
446 return distZones[tzid]
447}
448
evansiroky92c15c42018-11-15 20:58:18 -0800449var roundDownToTenth = function (n) {
450 return Math.floor(n * 10) / 10
451}
452
453var roundUpToTenth = function (n) {
454 return Math.ceil(n * 10) / 10
455}
456
457var formatBounds = function (bounds) {
458 let boundsStr = '['
459 boundsStr += roundDownToTenth(bounds[0]) + ', '
460 boundsStr += roundDownToTenth(bounds[1]) + ', '
461 boundsStr += roundUpToTenth(bounds[2]) + ', '
462 boundsStr += roundUpToTenth(bounds[3]) + ']'
463 return boundsStr
464}
465
Evan Siroky4fc596c2016-09-25 19:52:30 -0700466var validateTimezoneBoundaries = function () {
evansiroky5348a6f2019-01-05 15:39:28 -0800467 const numZones = Object.keys(zoneCfg).length
468 const validationProgress = new ProgressStats(
469 'Validation',
470 numZones * (numZones + 1) / 2
471 )
472
evansiroky26325842018-04-03 14:10:42 -0700473 console.log('do validation... this may take a few minutes')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700474 var allZonesOk = true
475 var zones = Object.keys(zoneCfg)
evansiroky3046a3d2019-01-05 21:19:14 -0800476 var lastPct = 0
Evan Siroky7891a6e2016-11-05 11:50:50 -0700477 var compareTzid, tzid, zoneGeom
Evan Siroky4fc596c2016-09-25 19:52:30 -0700478
479 for (var i = 0; i < zones.length; i++) {
480 tzid = zones[i]
481 zoneGeom = getDistZoneGeom(tzid)
482
483 for (var j = i + 1; j < zones.length; j++) {
evansiroky3046a3d2019-01-05 21:19:14 -0800484 const curPct = Math.floor(validationProgress.getPercentage())
485 if (curPct % 10 === 0 && curPct !== lastPct) {
evansiroky5348a6f2019-01-05 15:39:28 -0800486 validationProgress.printStats('Validating zones', true)
evansiroky3046a3d2019-01-05 21:19:14 -0800487 lastPct = curPct
evansiroky5348a6f2019-01-05 15:39:28 -0800488 }
Evan Siroky4fc596c2016-09-25 19:52:30 -0700489 compareTzid = zones[j]
490
491 var compareZoneGeom = getDistZoneGeom(compareTzid)
Evan Siroky070bbb92017-03-07 23:48:29 -0800492
493 var intersects = false
494 try {
495 intersects = debugGeo('intersects', zoneGeom, compareZoneGeom)
496 } catch (e) {
497 console.warn('warning, encountered intersection error with zone ' + tzid + ' and ' + compareTzid)
498 }
499 if (intersects) {
Evan Siroky7891a6e2016-11-05 11:50:50 -0700500 var intersectedGeom = debugGeo('intersection', zoneGeom, compareZoneGeom)
501 var intersectedArea = intersectedGeom.getArea()
Evan Siroky4fc596c2016-09-25 19:52:30 -0700502
Evan Siroky7891a6e2016-11-05 11:50:50 -0700503 if (intersectedArea > 0.0001) {
evansiroky0ea1d1e2018-10-30 22:30:51 -0700504 // check if the intersected area(s) are one of the expected areas of overlap
505 const allowedOverlapBounds = expectedZoneOverlaps[`${tzid}-${compareTzid}`] || expectedZoneOverlaps[`${compareTzid}-${tzid}`]
506 const overlapsGeoJson = geoJsonWriter.write(intersectedGeom)
507
508 // these zones are allowed to overlap in certain places, make sure the
509 // found overlap(s) all fit within the expected areas of overlap
510 if (allowedOverlapBounds) {
511 // if the overlaps are a multipolygon, make sure each individual
512 // polygon of overlap fits within at least one of the expected
513 // overlaps
514 let overlapsPolygons
515 switch (overlapsGeoJson.type) {
evansiroky92c15c42018-11-15 20:58:18 -0800516 case 'MultiPolygon':
517 overlapsPolygons = overlapsGeoJson.coordinates.map(
518 polygonCoords => ({
519 coordinates: polygonCoords,
520 type: 'Polygon'
521 })
522 )
523 break
evansiroky0ea1d1e2018-10-30 22:30:51 -0700524 case 'Polygon':
525 overlapsPolygons = [overlapsGeoJson]
526 break
evansiroky92c15c42018-11-15 20:58:18 -0800527 case 'GeometryCollection':
528 overlapsPolygons = []
529 overlapsGeoJson.geometries.forEach(geom => {
530 if (geom.type === 'Polygon') {
531 overlapsPolygons.push(geom)
532 } else if (geom.type === 'MultiPolygon') {
533 geom.coordinates.forEach(polygonCoords => {
534 overlapsPolygons.push({
535 coordinates: polygonCoords,
536 type: 'Polygon'
537 })
538 })
539 }
540 })
541 break
evansiroky0ea1d1e2018-10-30 22:30:51 -0700542 default:
evansiroky92c15c42018-11-15 20:58:18 -0800543 console.error('unexpected geojson overlap type')
544 console.log(overlapsGeoJson)
evansiroky0ea1d1e2018-10-30 22:30:51 -0700545 break
546 }
547
548 let allOverlapsOk = true
549 overlapsPolygons.forEach((polygon, idx) => {
550 const bounds = bbox(polygon)
evansiroky92c15c42018-11-15 20:58:18 -0800551 const polygonArea = area.geometry(polygon)
evansiroky0ea1d1e2018-10-30 22:30:51 -0700552 if (
evansiroky92c15c42018-11-15 20:58:18 -0800553 polygonArea > 10 && // ignore small polygons
evansiroky0ea1d1e2018-10-30 22:30:51 -0700554 !allowedOverlapBounds.some(allowedBounds =>
evansiroky92c15c42018-11-15 20:58:18 -0800555 allowedBounds.bounds[0] <= bounds[0] && // minX
556 allowedBounds.bounds[1] <= bounds[1] && // minY
557 allowedBounds.bounds[2] >= bounds[2] && // maxX
558 allowedBounds.bounds[3] >= bounds[3] // maxY
evansiroky0ea1d1e2018-10-30 22:30:51 -0700559 )
560 ) {
evansiroky92c15c42018-11-15 20:58:18 -0800561 console.error(`Unexpected intersection (${polygonArea} area) with bounds: ${formatBounds(bounds)}`)
evansiroky0ea1d1e2018-10-30 22:30:51 -0700562 allOverlapsOk = false
563 }
564 })
565
566 if (allOverlapsOk) continue
567 }
568
evansiroky92c15c42018-11-15 20:58:18 -0800569 // at least one unexpected overlap found, output an error and write debug file
evansiroky70b35fe2018-04-01 21:06:36 -0700570 console.error('Validation error: ' + tzid + ' intersects ' + compareTzid + ' area: ' + intersectedArea)
evansiroky92c15c42018-11-15 20:58:18 -0800571 const debugFilename = tzid.replace(/\//g, '-') + '-' + compareTzid.replace(/\//g, '-') + '-overlap.json'
evansiroky70b35fe2018-04-01 21:06:36 -0700572 fs.writeFileSync(
573 debugFilename,
evansiroky0ea1d1e2018-10-30 22:30:51 -0700574 JSON.stringify(overlapsGeoJson)
evansiroky70b35fe2018-04-01 21:06:36 -0700575 )
576 console.error('wrote overlap area as file ' + debugFilename)
577 console.error('To read more about this error, please visit https://git.io/vx6nx')
Evan Siroky4fc596c2016-09-25 19:52:30 -0700578 allZonesOk = false
579 }
580 }
evansiroky5348a6f2019-01-05 15:39:28 -0800581 validationProgress.logNext()
Evan Siroky4fc596c2016-09-25 19:52:30 -0700582 }
583 }
584
585 return allZonesOk ? null : 'Zone validation unsuccessful'
Evan Siroky4fc596c2016-09-25 19:52:30 -0700586}
587
evansiroky26325842018-04-03 14:10:42 -0700588let oceanZoneBoundaries
evansiroky9fd50512019-07-07 12:06:28 -0700589let oceanZones = [
590 { tzid: 'Etc/GMT-12', left: 172.5, right: 180 },
591 { tzid: 'Etc/GMT-11', left: 157.5, right: 172.5 },
592 { tzid: 'Etc/GMT-10', left: 142.5, right: 157.5 },
593 { tzid: 'Etc/GMT-9', left: 127.5, right: 142.5 },
594 { tzid: 'Etc/GMT-8', left: 112.5, right: 127.5 },
595 { tzid: 'Etc/GMT-7', left: 97.5, right: 112.5 },
596 { tzid: 'Etc/GMT-6', left: 82.5, right: 97.5 },
597 { tzid: 'Etc/GMT-5', left: 67.5, right: 82.5 },
598 { tzid: 'Etc/GMT-4', left: 52.5, right: 67.5 },
599 { tzid: 'Etc/GMT-3', left: 37.5, right: 52.5 },
600 { tzid: 'Etc/GMT-2', left: 22.5, right: 37.5 },
601 { tzid: 'Etc/GMT-1', left: 7.5, right: 22.5 },
602 { tzid: 'Etc/GMT', left: -7.5, right: 7.5 },
603 { tzid: 'Etc/GMT+1', left: -22.5, right: -7.5 },
604 { tzid: 'Etc/GMT+2', left: -37.5, right: -22.5 },
605 { tzid: 'Etc/GMT+3', left: -52.5, right: -37.5 },
606 { tzid: 'Etc/GMT+4', left: -67.5, right: -52.5 },
607 { tzid: 'Etc/GMT+5', left: -82.5, right: -67.5 },
608 { tzid: 'Etc/GMT+6', left: -97.5, right: -82.5 },
609 { tzid: 'Etc/GMT+7', left: -112.5, right: -97.5 },
610 { tzid: 'Etc/GMT+8', left: -127.5, right: -112.5 },
611 { tzid: 'Etc/GMT+9', left: -142.5, right: -127.5 },
612 { tzid: 'Etc/GMT+10', left: -157.5, right: -142.5 },
613 { tzid: 'Etc/GMT+11', left: -172.5, right: -157.5 },
614 { tzid: 'Etc/GMT+12', left: -180, right: -172.5 }
615]
616
Neil Fullerc4ae49b2020-04-30 18:08:43 +0100617if (includedZones.length > 0) {
618 oceanZones = oceanZones.filter(oceanZone => includedZones.indexOf(oceanZone) > -1)
evansiroky9fd50512019-07-07 12:06:28 -0700619}
Neil Fuller2b4b80a2020-04-30 18:20:56 +0100620if (excludedZones.length > 0) {
621 oceanZones = oceanZones.filter(oceanZone => excludedZones.indexOf(oceanZone) === -1)
622}
evansiroky26325842018-04-03 14:10:42 -0700623
624var addOceans = function (callback) {
625 console.log('adding ocean boundaries')
evansiroky26325842018-04-03 14:10:42 -0700626 const zones = Object.keys(zoneCfg)
627
evansiroky3046a3d2019-01-05 21:19:14 -0800628 const oceanProgress = new ProgressStats(
629 'Oceans',
630 oceanZones.length
631 )
632
evansiroky26325842018-04-03 14:10:42 -0700633 oceanZoneBoundaries = oceanZones.map(zone => {
evansiroky3046a3d2019-01-05 21:19:14 -0800634 oceanProgress.beginTask(zone.tzid, true)
evansiroky26325842018-04-03 14:10:42 -0700635 const geoJson = polygon([[
636 [zone.left, 90],
evansiroky0ea1d1e2018-10-30 22:30:51 -0700637 [zone.left, -90],
638 [zone.right, -90],
639 [zone.right, 90],
evansiroky26325842018-04-03 14:10:42 -0700640 [zone.left, 90]
641 ]]).geometry
642
643 let geom = geoJsonToGeom(geoJson)
644
645 // diff against every zone
646 zones.forEach(distZone => {
647 geom = debugGeo('diff', geom, getDistZoneGeom(distZone))
648 })
649
650 return {
651 geom: postProcessZone(geom, true),
652 tzid: zone.tzid
653 }
654 })
655
656 callback()
657}
658
Evan Siroky7891a6e2016-11-05 11:50:50 -0700659var combineAndWriteZones = function (callback) {
Neil Fullera4e73272020-04-30 18:25:44 +0100660 var stream = fs.createWriteStream(argv.dist_dir + '/combined.json')
661 var streamWithOceans = fs.createWriteStream(argv.dist_dir + '/combined-with-oceans.json')
Evan Siroky8b47abe2016-10-02 12:28:52 -0700662 var zones = Object.keys(zoneCfg)
663
664 stream.write('{"type":"FeatureCollection","features":[')
evansiroky26325842018-04-03 14:10:42 -0700665 streamWithOceans.write('{"type":"FeatureCollection","features":[')
Evan Siroky8b47abe2016-10-02 12:28:52 -0700666
667 for (var i = 0; i < zones.length; i++) {
Evan Siroky7891a6e2016-11-05 11:50:50 -0700668 if (i > 0) {
Evan Siroky8b47abe2016-10-02 12:28:52 -0700669 stream.write(',')
evansiroky26325842018-04-03 14:10:42 -0700670 streamWithOceans.write(',')
Evan Siroky8b47abe2016-10-02 12:28:52 -0700671 }
672 var feature = {
673 type: 'Feature',
674 properties: { tzid: zones[i] },
675 geometry: geomToGeoJson(getDistZoneGeom(zones[i]))
676 }
evansiroky26325842018-04-03 14:10:42 -0700677 const stringified = JSON.stringify(feature)
678 stream.write(stringified)
679 streamWithOceans.write(stringified)
Evan Siroky8b47abe2016-10-02 12:28:52 -0700680 }
evansiroky26325842018-04-03 14:10:42 -0700681 oceanZoneBoundaries.forEach(boundary => {
682 streamWithOceans.write(',')
683 var feature = {
684 type: 'Feature',
685 properties: { tzid: boundary.tzid },
686 geometry: boundary.geom
687 }
688 streamWithOceans.write(JSON.stringify(feature))
689 })
690 asynclib.parallel([
691 cb => {
692 stream.end(']}', cb)
693 },
694 cb => {
695 streamWithOceans.end(']}', cb)
696 }
697 ], callback)
Evan Siroky8b47abe2016-10-02 12:28:52 -0700698}
699
evansiroky5348a6f2019-01-05 15:39:28 -0800700const autoScript = {
Evan Siroky7891a6e2016-11-05 11:50:50 -0700701 makeDownloadsDir: function (cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800702 overallProgress.beginTask('Creating downloads dir')
Neil Fullera4e73272020-04-30 18:25:44 +0100703 safeMkdir(argv.downloads_dir, cb)
evansiroky4be1c7a2016-06-16 18:23:34 -0700704 },
Evan Siroky7891a6e2016-11-05 11:50:50 -0700705 makeDistDir: function (cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800706 overallProgress.beginTask('Creating dist dir')
Neil Fullera4e73272020-04-30 18:25:44 +0100707 safeMkdir(argv.dist_dir, cb)
evansirokyd401c892016-06-16 00:05:14 -0700708 },
Evan Siroky7891a6e2016-11-05 11:50:50 -0700709 getOsmBoundaries: ['makeDownloadsDir', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800710 overallProgress.beginTask('Downloading osm boundaries')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700711 asynclib.eachSeries(Object.keys(osmBoundarySources), downloadOsmBoundary, cb)
evansiroky63d35e12016-06-16 10:08:15 -0700712 }],
evansirokya48b3922020-04-27 15:29:06 -0700713 zipInputData: ['makeDistDir', 'getOsmBoundaries', function (results, cb) {
714 overallProgress.beginTask('Zipping up input data')
715 exec('zip dist/input-data.zip downloads/* timezones.json osmBoundarySources.json expectedZoneOverlaps.json', cb)
716 }],
Evan Siroky7891a6e2016-11-05 11:50:50 -0700717 createZones: ['makeDistDir', 'getOsmBoundaries', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800718 overallProgress.beginTask('Creating timezone boundaries')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700719 asynclib.each(Object.keys(zoneCfg), makeTimezoneBoundary, cb)
evansiroky50216c62016-06-16 17:41:47 -0700720 }],
Evan Siroky7891a6e2016-11-05 11:50:50 -0700721 validateZones: ['createZones', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800722 overallProgress.beginTask('Validating timezone boundaries')
Evan Siroky4fc596c2016-09-25 19:52:30 -0700723 loadDistZonesIntoMemory()
Neil Fullerc4ae49b2020-04-30 18:08:43 +0100724 if (argv.no_validation) {
Evan Siroky081648a2017-07-04 09:53:36 -0700725 console.warn('WARNING: Skipping validation!')
726 cb()
727 } else {
728 cb(validateTimezoneBoundaries())
729 }
Evan Siroky4fc596c2016-09-25 19:52:30 -0700730 }],
evansiroky26325842018-04-03 14:10:42 -0700731 addOceans: ['validateZones', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800732 overallProgress.beginTask('Adding oceans')
evansiroky26325842018-04-03 14:10:42 -0700733 addOceans(cb)
734 }],
735 mergeZones: ['addOceans', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800736 overallProgress.beginTask('Merging zones')
Evan Siroky8b47abe2016-10-02 12:28:52 -0700737 combineAndWriteZones(cb)
738 }],
739 zipGeoJson: ['mergeZones', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800740 overallProgress.beginTask('Zipping geojson')
Neil Fullera4e73272020-04-30 18:25:44 +0100741 let zipFile = argv.dist_dir + '/timezones.geojson.zip'
742 let jsonFile = argv.dist_dir + '/combined.json'
743 exec('zip ' + zipFile + ' ' + jsonFile, cb)
Evan Siroky8b47abe2016-10-02 12:28:52 -0700744 }],
evansiroky26325842018-04-03 14:10:42 -0700745 zipGeoJsonWithOceans: ['mergeZones', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800746 overallProgress.beginTask('Zipping geojson with oceans')
Neil Fullera4e73272020-04-30 18:25:44 +0100747 let zipFile = argv.dist_dir + '/timezones-with-oceans.geojson.zip'
748 let jsonFile = argv.dist_dir + '/combined-with-oceans.json'
749 exec('zip ' + zipFile + ' ' + jsonFile, cb)
evansiroky26325842018-04-03 14:10:42 -0700750 }],
Evan Siroky8b47abe2016-10-02 12:28:52 -0700751 makeShapefile: ['mergeZones', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800752 overallProgress.beginTask('Converting from geojson to shapefile')
Neil Fullera4e73272020-04-30 18:25:44 +0100753 let shapeFileGlob = argv.dist_dir + '/combined-shapefile.*'
754 rimraf.sync(shapeFileGlob)
755 let shapeFile = argv.dist_dir + '/combined-shapefile.shp'
756 let jsonFile = argv.dist_dir + '/combined.json'
evansiroky26325842018-04-03 14:10:42 -0700757 exec(
Neil Fullera4e73272020-04-30 18:25:44 +0100758 'ogr2ogr -f "ESRI Shapefile" ' + shapeFile + ' ' + jsonFile,
evansiroky26325842018-04-03 14:10:42 -0700759 function (err, stdout, stderr) {
760 if (err) { return cb(err) }
Neil Fullera4e73272020-04-30 18:25:44 +0100761 let shapeFileZip = argv.dist_dir + '/timezones.shapefile.zip'
762 exec('zip ' + shapeFileZip + ' ' + shapeFileGlob, cb)
evansiroky26325842018-04-03 14:10:42 -0700763 }
764 )
765 }],
766 makeShapefileWithOceans: ['mergeZones', function (results, cb) {
evansiroky5348a6f2019-01-05 15:39:28 -0800767 overallProgress.beginTask('Converting from geojson with oceans to shapefile')
Neil Fullera4e73272020-04-30 18:25:44 +0100768 let shapeFileGlob = argv.dist_dir + '/combined-shapefile-with-oceans.*'
769 rimraf.sync(shapeFileGlob)
770 let shapeFile = argv.dist_dir + '/combined-shapefile-with-oceans.shp'
771 let jsonFile = argv.dist_dir + '/combined-with-oceans.json'
evansiroky26325842018-04-03 14:10:42 -0700772 exec(
Neil Fullera4e73272020-04-30 18:25:44 +0100773 'ogr2ogr -f "ESRI Shapefile" ' + shapeFile + ' ' + jsonFile,
evansiroky26325842018-04-03 14:10:42 -0700774 function (err, stdout, stderr) {
775 if (err) { return cb(err) }
Neil Fullera4e73272020-04-30 18:25:44 +0100776 let shapeFileZip = argv.dist_dir + '/timezones-with-oceans.shapefile.zip'
777 exec('zip ' + shapeFileZip + ' ' + shapeFileGlob, cb)
evansiroky26325842018-04-03 14:10:42 -0700778 }
779 )
evansiroky9fd50512019-07-07 12:06:28 -0700780 }],
781 makeListOfTimeZoneNames: function (cb) {
782 overallProgress.beginTask('Writing timezone names to file')
783 let zoneNames = Object.keys(zoneCfg)
784 oceanZones.forEach(oceanZone => {
785 zoneNames.push(oceanZone.tzid)
786 })
Neil Fullerc4ae49b2020-04-30 18:08:43 +0100787 if (includedZones.length > 0) {
788 zoneNames = zoneNames.filter(zoneName => includedZones.indexOf(zoneName) > -1)
evansiroky9fd50512019-07-07 12:06:28 -0700789 }
Neil Fuller2b4b80a2020-04-30 18:20:56 +0100790 if (excludedZones.length > 0) {
791 zoneNames = zoneNames.filter(zoneName => excludedZones.indexOf(zoneName) === -1)
792 }
evansiroky9fd50512019-07-07 12:06:28 -0700793 fs.writeFile(
Neil Fullera4e73272020-04-30 18:25:44 +0100794 argv.dist_dir + '/timezone-names.json',
evansiroky9fd50512019-07-07 12:06:28 -0700795 JSON.stringify(zoneNames),
796 cb
797 )
798 }
evansiroky5348a6f2019-01-05 15:39:28 -0800799}
800
801const overallProgress = new ProgressStats('Overall', Object.keys(autoScript).length)
802
803asynclib.auto(autoScript, function (err, results) {
evansirokyd401c892016-06-16 00:05:14 -0700804 console.log('done')
Evan Siroky7891a6e2016-11-05 11:50:50 -0700805 if (err) {
evansirokyd401c892016-06-16 00:05:14 -0700806 console.log('error!', err)
evansirokyd401c892016-06-16 00:05:14 -0700807 }
Evan Siroky4fc596c2016-09-25 19:52:30 -0700808})