-
Notifications
You must be signed in to change notification settings - Fork 0
/
reduceOverlap.js
executable file
·310 lines (274 loc) · 11 KB
/
reduceOverlap.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
#!/usr/bin/env node
/**
* Reduce overlapping features which can be combined together into a single feature.
*/
const fs = require('fs')
const { Readable, Transform, pipeline } = require('stream')
const ndjson = require('ndjson')
const cloneDeep = require('clone-deep')
const unitsToRanges = require('../lib/unitsToRanges.js')
const valueLimits = require('../lib/valueLimits.js')
const argv = require('yargs/yargs')(process.argv.slice(2))
.option('debug', {
type: 'boolean',
description: 'Dumps full debug logs'
})
.option('verbose', {
type: 'boolean',
description: 'Verbose logging'
})
.argv
if (argv._.length < 2) {
console.error("Usage: ./reduceOverlap.js input.geojson output.geojson")
process.exit(1)
}
const inputFile = argv._[0]
const outputFile = argv._[1]
if (!fs.existsSync(inputFile)) {
console.error(`${inputFile} not found`)
process.exit(1)
}
let sourceCount = 0
const features = {}
/**
* Index features by geometry. Used as a first pass, so a second pass can easily compare
* features with the same geometry.
*/
const index = new Transform({
readableObjectMode: true,
writableObjectMode: true,
transform(feature, encoding, callback) {
sourceCount++
if (!argv.quiet) {
if (process.stdout.isTTY && sourceCount % 10000 === 0) {
process.stdout.write(` ${sourceCount.toLocaleString()}\r`)
}
}
const geometryKey = feature.geometry.coordinates.join(',')
if (!(geometryKey in features)) {
features[geometryKey] = []
}
features[geometryKey].push(feature)
callback()
}
})
/**
* Reduces features with the same geometry.
*/
let reduceIndex = 0
const reduce = new Transform({
readableObjectMode: true,
writableObjectMode: true,
transform(key, encoding, callback) {
reduceIndex++
if (!argv.quiet) {
if (process.stdout.isTTY && reduceIndex % 10000 === 0) {
process.stdout.write(` ${reduceIndex.toLocaleString()} / ${sourceCount.toLocaleString()} (${Math.round(reduceIndex / sourceCount * 100)}%)\r`)
}
}
var overlappingFeatures = features[key]
if (overlappingFeatures.length === 1) {
// only one feature with this geometry, nothing to reduce, output as is
this.push(overlappingFeatures[0])
} else {
// multiple features with the same geometry
// group by housenumber, street, suburb, state, postcode to reduce units into addr:flats
// overlappingFeatures is all the features at the same point
const featuresGroupByNonUnit = {}
overlappingFeatures.forEach(feature => {
const key = [
feature.properties['addr:housenumber'],
feature.properties['addr:street'],
feature.properties['addr:suburb'],
feature.properties['addr:state'],
feature.properties['addr:postcode']
].join(';')
if (!(key in featuresGroupByNonUnit)) {
featuresGroupByNonUnit[key] = []
}
featuresGroupByNonUnit[key].push(feature)
})
const noUnits = !overlappingFeatures.filter(f => 'addr:unit' in f.properties).length
const sameNonHousenumber = overlappingFeatures.map(feature => [
feature.properties['addr:street'],
feature.properties['addr:suburb'],
feature.properties['addr:state'],
feature.properties['addr:postcode']
].join('|'))
.every( (val, i, arr) => val === arr[0] ) // check if all values are the same
const firstNumber = noUnits && sameNonHousenumber ? overlappingFeatures.map(f => f.properties['addr:housenumber']).reduce((acc, cur) => {
if (cur && cur.split('-').length === 2) {
cur = cur.split('-')[0]
}
if (acc && acc.split('-').length === 2) {
acc = acc.split('-')[0]
}
return (cur < acc) ? cur : acc
}) : null
const lastNumber = noUnits && sameNonHousenumber ? overlappingFeatures.map(f => f.properties['addr:housenumber']).reduce((acc, cur) => {
if (cur && cur.split('-').length === 2) {
cur = cur.split('-')[1]
}
if (acc && acc.split('-').length === 2) {
acc = acc.split('-')[1]
}
return (cur > acc) ? cur : acc
}) : null
if (noUnits && sameNonHousenumber && firstNumber && lastNumber && (firstNumber !== lastNumber)) {
const featureAsRange = overlappingFeatures[0]
featureAsRange.properties['addr:housenumber'] = `${firstNumber}-${lastNumber}`
if (featureAsRange.properties._pfi) {
featureAsRange.properties._pfi = overlappingFeatures.map(f => f.properties._pfi).join(',')
}
this.push(featureAsRange)
} else {
Object.values(featuresGroupByNonUnit).forEach(featureGroup => {
if (featureGroup.length > 1) {
const hasNonUnit = featureGroup.map(f => 'addr:unit' in f.properties).includes(false)
if (hasNonUnit) {
// all have same housenumber, street, suburb, state, postcode and there is a non-unit feature
const nonUnitFeatures = featureGroup.filter(f => (!('addr:unit' in f.properties)))
if (nonUnitFeatures.length > 1) {
// multiple non-unit features shouldn't actually occur
console.log("Multiple non-unit features, this shouldn't occur, because reduceDuplicates should have address this already.", nonUnitFeatures)
process.exit(1)
} else {
// a single non-unit feature exists
const nonUnitFeature = cloneDeep(nonUnitFeatures[0])
// place all the other addr:unit into addr:flats on the non-unit feature
const allOtherUnits = featureGroup.filter(f => 'addr:unit' in f.properties).map(f => f.properties['addr:unit'])
// if allOtherUnits.length is one then that means we have one address without a unit and one with a unit at the same point
// in this case we just drop the non-unit address and keep the addr:unit one
if (allOtherUnits.length === 1) {
if (argv.debug) {
featureGroup.forEach(feature => {
debugStreams.oneUnitOneNonUnit.write(feature)
})
}
const retainedFeature = featureGroup.filter(f => 'addr:unit' in f.properties)[0]
if (retainedFeature.properties._pfi) {
retainedFeature.properties._pfi = featureGroup.map(f => f.properties._pfi).join(',')
}
this.push(retainedFeature)
} else {
const flats = unitsToRanges(allOtherUnits, argv.verbose && featureGroup)
// because OSM carto will render addr:flats regardless of length for the time being if there would be too many flat ranges then don't include addr:flats at all
if (flats.split(';').length <= 2) {
nonUnitFeature.properties['addr:flats'] = flats
}
if (nonUnitFeature.properties._pfi) {
nonUnitFeature.properties._pfi = featureGroup.map(f => f.properties._pfi).join(',')
}
this.push(nonUnitFeature)
}
}
} else {
// all have same housenumber, street, suburb, state, postcode but no non-unit, ie. all with different unit values
// combine all the addr:unit into addr:flats and then drop addr:unit
const units = featureGroup.filter(f => 'addr:unit' in f.properties).map(f => f.properties['addr:unit'])
if (units.length <= 1) {
console.log(`all have same housenumber, street, suburb, state, postcode with no non-unit, but only found ${units.length} units`, units)
process.exit(1)
}
const feature = cloneDeep(featureGroup[0])
delete feature.properties['addr:unit']
const flats = unitsToRanges(units, argv.verbose && featureGroup)
feature.properties['addr:flats'] = flats
if (feature.properties._pfi) {
feature.properties._pfi = featureGroup.map(f => f.properties._pfi).join(',')
}
this.push(feature)
}
} else if (featureGroup.length === 1) {
// while other features share the same geometry, this one is unique in it's housenumber,street,suburb,state,postcode
// so output this feature, and we deal with the overlap at another stage
const feature = featureGroup[0]
this.push(feature)
if (argv.debug) {
debugStreams.sameGeometry.write(feature)
}
}
})
}
}
callback()
}
})
/**
* Per https://wiki.openstreetmap.org/wiki/API_v0.6#Maximum_string_lengths
* tag values are limited to 255 characters. Because some addr:flats values can
* exceed this, they are split into addr:flatsN tags.
*/
let limitValuesIndex = 0
const limitValues = new Transform({
readableObjectMode: true,
writableObjectMode: true,
transform(feature, encoding, callback) {
limitValuesIndex++
if (!argv.quiet) {
if (limitValuesIndex % 10000 === 0) {
process.stdout.write(` ${limitValuesIndex.toLocaleString()} / ${sourceCount.toLocaleString()} (${Math.round(limitValuesIndex / sourceCount * 100)}%)\r`)
}
}
this.push(valueLimits(feature))
callback()
}
})
const debugKeys = ['oneUnitOneNonUnit', 'sameGeometry']
const debugStreams = {}
const debugStreamOutputs = {}
if (argv.debug) {
debugKeys.forEach(key => {
debugStreams[key] = ndjson.stringify()
debugStreamOutputs[key] = debugStreams[key].pipe(fs.createWriteStream(`debug/reduceOverlap/${key}.geojson`))
})
}
// first pass to index by geometry
console.log('Pass 1/2: index by geometry')
pipeline(
fs.createReadStream(inputFile),
ndjson.parse(),
index,
err => {
if (err) {
console.log(err)
process.exit(1)
} else {
console.log(` of ${sourceCount.toLocaleString()} features found ${Object.keys(features).length.toLocaleString()} unique geometries`)
// second pass to reduce overlapping features
console.log('Pass 2/2: reduce overlapping features')
pipeline(
Readable.from(Object.keys(features)),
reduce,
limitValues,
ndjson.stringify(),
fs.createWriteStream(outputFile),
err => {
if (err) {
console.log(err)
process.exit(1)
} else {
if (argv.debug) {
debugKeys.forEach(key => {
debugStreams[key].end()
})
Promise.all(debugKeys.map(key => {
return new Promise(resolve => {
debugStreamOutputs[key].on('finish', () => {
console.log(`saved debug/reduceOverlap/${key}.geojson`)
resolve()
})
})
}))
.then(() => {
process.exit(0)
})
} else {
process.exit(0)
}
}
}
)
}
}
)