aboutsummaryrefslogtreecommitdiff
path: root/bin/candidates.js
blob: af87f5a96dde5d3b73dfd2be08bc109ba5b2009c (plain) (blame)
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
#!/usr/bin/env node

/**
 * Prepare import candidates by conflation category and suburb as OSM XML
 */

const fs = require('fs')
const path = require('path')
const { Transform, pipeline } = require('stream')
const ndjson = require('ndjson')
const PolygonLookup = require('polygon-lookup')
const geojsontoosm = require('geojsontoosm')

const argv = require('yargs/yargs')(process.argv.slice(2))
  .option('verbose', {
    type: 'boolean',
    description: 'Verbose logging'
  })
  .argv

if (argv._.length < 3) {
  console.error("Usage: ./conflate.js data/victoria-admin-level10.osm.geojson dist/conflate dist/candidates")
  process.exit(1)
}

const suburbsFile = argv._[0]
const conflatePath = argv._[1]
const outputPath = argv._[2]

if (!fs.existsSync(suburbsFile)) {
  console.error(`${suburbsFile} not found`)
  process.exit(1)
}

if (!fs.existsSync(conflatePath)) {
  console.error(`${conflatePath} not found`)
  process.exit(1)
}

// output GeoJSON Features by layer by suburb ID
const outputFeatures = {
  'newAddressesInBlocksWithoutAnyExisting': {}
}

for (const layer of Object.keys(outputFeatures)) {
  const layerPath = path.join(outputPath, layer)
  if (!fs.existsSync(layerPath)) {
    fs.mkdirSync(layerPath)
  }
}

// suburb GeoJSON Features
const suburbs = []

// suburb ID to name
const suburbName = {
  0: 'VIC'
}

// suburb point in polygon index
let lookupSuburbs

const outsideVicSuburb = {
  type: 'Feature',
  id: 0,
  properties: {
    name: 'VIC'
  },
  geometry: null
}

// index suburbs
let suburbCount = 0
const readSuburbs = new Transform({
  readableObjectMode: true,
  writableObjectMode: true,
  transform(suburb, encoding, callback) {
    suburbCount++

    if (process.stdout.isTTY && suburbCount % 1000 === 0) {
      process.stdout.write(` ${suburbCount.toLocaleString()}\r`)
    }

    if (!('id' in suburb)) {
      console.log('Suburb missing id', suburb)
      process.exit(1)
    }

    for (const layer of Object.keys(outputFeatures)) {
      outputFeatures[layer][suburb.id] = []
    }

    suburbName[suburb.id] = suburb.properties.name

    suburbs.push(suburb)

    callback()
  }
})

function findSuburb(feature) {
  // find which suburb this address is in
  const results = lookupSuburbs.search(...feature.geometry.coordinates.slice(0, 2), 1)
  const suburb = results ? (results.type === 'FeatureCollection' ? (results.features ? results.features[0] : outsideVicSuburb) : results[0]) : outsideVicSuburb

  return suburb
}


// produce import candidates
let sourceCount = 0
const candidatesNewAddressesInBlocksWithoutAnyExisting = new Transform({
  readableObjectMode: true,
  writableObjectMode: true,
  transform(feature, encoding, callback) {
    sourceCount++

    if (process.stdout.isTTY && sourceCount % 1000 === 0) {
      process.stdout.write(` ${sourceCount.toLocaleString()}\r`)
    }

    // remove tracing properties
    delete feature.properties._pfi

    const suburb = findSuburb(feature)

    outputFeatures['newAddressesInBlocksWithoutAnyExisting'][suburb.id].push(feature)

    callback()
  }
})

/**
 * Save our candidate address data as .osm files by layer by suburb
 */
function outputCandidates() {
  let i = 0
  for (const layer of Object.keys(outputFeatures)) {
    i++
    let j = 0
    for (const suburbId of Object.keys(outputFeatures[layer])) {
      j++
      if (process.stdout.isTTY && i % 10 === 0) {
        process.stdout.write(` ${j.toLocaleString()}/${Object.keys(outputFeatures).length.toLocaleString()} - ${layer} - ${i.toLocaleString()}/${suburbs.length.toLocaleString()}\r`)
      }

      const suburbFeatures = outputFeatures[layer][suburbId]
      if (suburbFeatures && suburbFeatures.length) {
        const xml = geojsontoosm(suburbFeatures)
        fs.writeFileSync(path.join(outputPath, layer, `${suburbId}_${suburbName[suburbId]}.osm`), xml)
      } // else no data for this suburb
    }
  }
}

// first pass to index by geometry
console.log('Step 1/4: Reading suburbs')
pipeline(
  fs.createReadStream(suburbsFile),
  ndjson.parse(),
  readSuburbs,
  err => {
    if (err) {
      console.log(err)
      process.exit(1)
    } else {
      console.log('Step 2/4: Creating index of Suburbs')
      lookupSuburbs = new PolygonLookup({
        type: 'FeatureCollection',
        features: suburbs
      })

      console.log('Step 3/4: noOSMAddressWithinBlock')
      pipeline(
        fs.createReadStream(path.join(conflatePath, 'noOSMAddressWithinBlock.geojson')),
        ndjson.parse(),
        candidatesNewAddressesInBlocksWithoutAnyExisting,
        err => {
          if (err) {
            console.log(err)
            process.exit(1)
          } else {

            /*
            console.log('Step 4/4: noExactMatch')
            pipeline(
              fs.createReadStream(path.join(conflatePath, 'noExactMatch.geojson')),
              ndjson.parse(),
              candidates,
              err => {
                if (err) {
                  console.log(err)
                  process.exit(1)
                } else {
                  */
                  console.log('Output candidate .osm files')
                  outputCandidates()
                  process.exit(0)
                  /*
                }
              }
            )
            */
          }
        }
      )

    }
  }
)