Repository navigation
Expand file tree
/
Copy pathdne-geo-join.js
More file actions
1530 lines (1447 loc) · 56.1 KB
/
Copy pathdne-geo-join.js
File metadata and controls
1530 lines (1447 loc) · 56.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
/**
* Junta o DNE (LOG_*.TXT, latin1) com o extract OSM (OSM_*.TXT ou shards, utf8)
* e emite DNE_GEO_LOGRADOURO_{UF}.TXT com geometria por logradouro.
*
* OSM aceita arquivo flat `OSM_LOGRADOURO_{UF}.TXT` **ou** pasta de shards
* `OSM_LOGRADOURO_{UF}/{N}-linhas/000001.txt` (+ MANIFEST.json). Prefere shards
* se a pasta existir. Idem para `OSM_ADDR_POINT_{UF}`.
*
* Especificação: docs/geo/dne-geo-join.md
*
* CLI:
* node dne-geo-join.js --dne=DIR --osm=DIR --out=DIR --uf=SP
* --cluster-cell=0.02 célula da clusterização (graus)
* --footprint-cell=0.01 célula do footprint municipal (graus)
* --max-extent-km=15 acima disso, com mais de um candidato, vira `ambiguo`
* --footprint-dilate=1 células de halo na pegada municipal
* --ancora-raio-km=60 descarta âncora fora da massa do município (0 desliga)
* --envelope-tol-km=1 recupera fora_do_footprint com 1 candidato a ≤N km da mancha
* --sem-envelope desliga a recuperação por envelope
* --vizinho-cep5-tol-km=1 recupera fora_do_footprint e pós-conflito por CEP-5 (km)
* --vizinho-cep5-min=3 mínimo de vias ok no mesmo CEP-5 (ou bairro)
* --sem-vizinho-cep5 desliga a recuperação por vizinhança CEP-5 (5e e 5f)
* --max-dist-vizinho-km=5 `ok` longe demais das vizinhas CEP/bairro vira ambiguo
* --sem-max-dist-vizinho desliga essa guarda (fase 5g)
* --sem-fuzzy desliga o degrau fuzzy (Levenshtein dist=1, len≥10)
* --sem-exclusao-cluster desliga a exclusividade de cluster entre municípios
* --sem-validacao-poligono desliga a verificação pós-join por polígono municipal
* --mun-poly=ARQ malha municipal alternativa (padrão: ./mun-poly.json)
* --validacao-exemplos=30 quantas das piores vão para o relatório
* --quiet
*/
var fs = require('fs');
var path = require('path');
var readline = require('readline');
var nameNorm = require('./name-norm').nameNorm;
var keys = require('./name-keys');
var geo = require('./geo-cluster');
var txtAt = require('./txt-at-writer');
var munPoly = require('./mun-poly');
var REGRAS = [
'exato', 'area', 'name_alt', 'addr', 'nucleo', 'fonetico',
'titulo', 'titulo_fonetico', 'conectores', 'fuzzy', 'vizinho_cep5'
];
// A "âncora local" antiga (centroide + raio = max dist) foi medida e removida:
// rendia ~36 linhas e o raio explodia com outliers. As fases 5e/5f (vizinho CEP-5)
// usam distância ao **vizinho mais próximo** já ok no mesmo CEP-5 (fallback: bairro),
// candidato único: 5e no resíduo `fora_do_footprint`; 5f após exclusão multi-município
// no resíduo `conflito_municipio` (cluster alternativo livre perto do CEP-5/bairro).
// Ver docs/geo/amostras-ambiguo-sp.md e docs/geo/dne-geo-join.md §Fase 5e/5f.
function digitsCep5(cep) {
var d = String(cep || '').replace(/\D/g, '');
return d.length >= 5 ? d.slice(0, 5) : '';
}
/** Distância ao ponto mais próximo (km). Infinity se lista vazia. */
function nearestDistKm(lat, lng, pts) {
var best = Infinity;
for (var i = 0; i < pts.length; i++) {
var d = geo.distKm(lat, lng, pts[i].lat, pts[i].lng);
if (d < best) best = d;
}
return best;
}
/** Índice de vias já `ok` por `loc_nu|CEP-5` e por `bai_nu` (âncoras de vizinhança). */
function indexVizinhoAnchors(rows) {
var byCep5Loc = new Map();
var byBaiNu = new Map();
for (var i = 0; i < rows.length; i++) {
var r = rows[i];
if (r.status !== 'ok' || !r.cluster) continue;
var pt = {
lat: r.cluster.agg.lat,
lng: r.cluster.agg.lng,
log_nu: r.log_nu,
log_no: r.log_no
};
var c5 = digitsCep5(r.cep);
if (c5) {
var ck = r.loc_nu + '|' + c5;
var ca = byCep5Loc.get(ck);
if (ca) ca.push(pt); else byCep5Loc.set(ck, [pt]);
}
if (r.bai_ini) {
var ba = byBaiNu.get(r.bai_ini);
if (ba) ba.push(pt); else byBaiNu.set(r.bai_ini, [pt]);
}
}
return { byCep5Loc: byCep5Loc, byBaiNu: byBaiNu };
}
/**
* Âncoras de vizinhança para uma linha: CEP-5 no mesmo município, senão bairro.
* Exige ≥ min pontos. Devolve null se insuficiente.
*/
function anchorsForRow(row, idxAnch, min) {
var fonte = 'cep5';
var anchors = null;
var c5 = digitsCep5(row.cep);
if (c5) anchors = idxAnch.byCep5Loc.get(row.loc_nu + '|' + c5) || null;
if (!anchors || anchors.length < min) {
anchors = row.bai_ini ? (idxAnch.byBaiNu.get(row.bai_ini) || null) : null;
fonte = 'bairro';
}
if (!anchors || anchors.length < min) return null;
return { anchors: anchors, fonte: fonte, cep5: c5 };
}
/**
* Entre candidatos de nome, fica quem está a ≤ tolKm do vizinho mais próximo
* e com extensão ok. Se `ownerOf` for passado, ignora cluster cujo dono é outro
* `loc_nu`. Aceita só se sobrar exatamente 1.
* Devolve { clusterIdx, dist, nCandConsiderados } ou null.
*/
function pickVizinhoUnico(candIdxs, clusters, anchors, tolKm, maxExtentKm, rowLocNu, ownerOf) {
var perto = [];
for (var i = 0; i < candIdxs.length; i++) {
var ci = candIdxs[i];
if (ownerOf) {
var own = ownerOf.get(ci);
if (own !== undefined && own !== rowLocNu) continue;
}
var ag = clusters[ci].agg;
var d = nearestDistKm(ag.lat, ag.lng, anchors);
if (d > tolKm) continue;
var ext = Math.max(
(ag.latMax - ag.latMin) * 111,
(ag.lngMax - ag.lngMin) * 102
);
if (ext > maxExtentKm) continue;
perto.push({ idx: ci, dist: d });
}
if (perto.length !== 1) return null;
return {
clusterIdx: perto[0].idx,
dist: perto[0].dist,
nCandConsiderados: candIdxs.length
};
}
/**
* Desempate entre clusters dentro do footprint.
* Ordem: CEP-5 (vizinhas já `ok` no mesmo município) → centroide do bairro →
* tamanho (só 2ª volta). Na 1ª volta, homônimo com vários clusters espera;
* tamanho na 1ª faz a via famosa "roubar" a periférica (Rua dos Pinheiros).
* Via física partida em vários CEP/bairros continua ok: cada trecho cai no
* cluster mais perto das vizinhas do próprio CEP, ou no único cluster se
* o footprint já filtrou os outros.
*/
function pickDesempate(dentro, clusters, row, volta, porBairro, idxAnch) {
if (dentro.length === 1) return { idx: dentro[0], via: 'unico' };
if (idxAnch) {
var c5 = digitsCep5(row.cep);
var anc = c5 ? idxAnch.byCep5Loc.get(row.loc_nu + '|' + c5) : null;
if (anc && anc.length) {
var pts = [];
for (var a = 0; a < anc.length; a++) {
if (anc[a].log_nu !== row.log_nu) pts.push(anc[a]);
}
if (pts.length) {
var bestI = null, bestD = Infinity, second = Infinity;
for (var i = 0; i < dentro.length; i++) {
var agC = clusters[dentro[i]].agg;
var dC = nearestDistKm(agC.lat, agC.lng, pts);
if (dC < bestD) { second = bestD; bestD = dC; bestI = dentro[i]; }
else if (dC < second) second = dC;
}
if (bestI != null && bestD < second) {
return { idx: bestI, via: 'cep5' };
}
}
}
}
var b = porBairro.get(row.bai_ini);
if (b && b.n > 0) {
var bLat = b.sLat / b.n, bLng = b.sLng / b.n;
var melhor = Infinity, escolhidoB = null, empateB = false;
for (var d = 0; d < dentro.length; d++) {
var a2 = clusters[dentro[d]].agg;
var dist = geo.distKm(bLat, bLng, a2.lat, a2.lng);
if (dist < melhor - 1e-9) {
melhor = dist;
escolhidoB = dentro[d];
empateB = false;
} else if (Math.abs(dist - melhor) < 1e-9) {
empateB = true;
}
}
if (escolhidoB != null && !empateB) return { idx: escolhidoB, via: 'bairro' };
}
if (volta === 1) return { idx: null, via: 'espera_cep_bairro' };
var maiorPeso = -1, escolhidoT = dentro[0], empate = false;
for (var e = 0; e < dentro.length; e++) {
var w = clusters[dentro[e]].agg.weight;
if (w > maiorPeso) { maiorPeso = w; escolhidoT = dentro[e]; empate = false; }
else if (w === maiorPeso) empate = true;
}
if (empate) return { idx: null, via: 'empate_de_tamanho' };
return { idx: escolhidoT, via: 'tamanho' };
}
/**
* Âncoras de CEP-5 (mesmo município) ou bairro, sem a própria linha e sem
* homônimo de mesmo log_no (dois "dos Pinheiros" roubados não se validam).
*/
function vizinhoAnchorsForGuard(row, idxAnch) {
if (!idxAnch) return null;
var c5 = digitsCep5(row.cep);
var fonte = 'cep5';
var raw = c5 ? idxAnch.byCep5Loc.get(row.loc_nu + '|' + c5) : null;
var pts = [];
function take(arr) {
if (!arr) return;
for (var i = 0; i < arr.length; i++) {
var p = arr[i];
if (p.log_nu === row.log_nu) continue;
if (p.log_no && row.log_no && p.log_no === row.log_no) continue;
pts.push(p);
}
}
take(raw);
if (!pts.length) {
fonte = 'bairro';
take(row.bai_ini ? idxAnch.byBaiNu.get(row.bai_ini) : null);
}
if (!pts.length) return null;
return { anchors: pts, fonte: fonte };
}
/** Distância mínima cluster-vizinhas (qualquer feat, não só o centróide). */
function clusterMinDistKm(cluster, pts) {
var best = Infinity;
var feats = cluster && cluster.feats ? cluster.feats : [];
for (var i = 0; i < feats.length; i++) {
var f = feats[i];
if (f.lat == null || f.lng == null) continue;
var d = nearestDistKm(f.lat, f.lng, pts);
if (d < best) best = d;
}
if (best === Infinity && cluster && cluster.agg) {
best = nearestDistKm(cluster.agg.lat, cluster.agg.lng, pts);
}
return best;
}
function distToVizinhoGuard(row, cluster, idxAnch) {
var v = vizinhoAnchorsForGuard(row, idxAnch);
if (!v) return null;
return { dist: clusterMinDistKm(cluster, v.anchors), fonte: v.fonte, n: v.anchors.length };
}
/** Top-N vizinhas mais próximas de (lat,lng) para auditoria. */
function topVizinhos(lat, lng, anchors, n) {
var sorted = anchors.slice().sort(function (a, b) {
return geo.distKm(lat, lng, a.lat, a.lng) - geo.distKm(lat, lng, b.lat, b.lng);
});
var out = [];
for (var i = 0; i < sorted.length && i < n; i++) {
out.push({
log_nu: sorted[i].log_nu,
log_no: sorted[i].log_no,
dist_km: Math.round(geo.distKm(lat, lng, sorted[i].lat, sorted[i].lng) * 1000) / 1000
});
}
return out;
}
function readLines(file, encoding, onLine) {
return new Promise(function (resolve, reject) {
var rl = readline.createInterface({
input: fs.createReadStream(file, encoding ? { encoding: encoding } : undefined),
crlfDelay: Infinity
});
rl.on('line', function (l) { if (l) onLine(l); });
rl.on('close', resolve);
rl.on('error', reject);
});
}
/** Lê um ou mais arquivos em ordem (flat ou shards). */
async function readLinesMany(files, encoding, onLine) {
for (var i = 0; i < files.length; i++) {
await readLines(files[i], encoding, onLine);
}
}
function num(v) {
if (v === undefined || v === '') return null;
var f = Number(v);
return isFinite(f) ? f : null;
}
// ---------------------------------------------------------------- DNE (latin1)
async function loadLocalidades(dneDir) {
var byId = new Map();
await readLines(path.join(dneDir, 'LOG_LOCALIDADE.TXT'), 'latin1', function (l) {
var p = l.split('@');
byId.set(p[0], {
loc_nu: p[0], uf: p[1], nome: p[2], sit: p[4], tipo: p[5],
sub: p[6] || '', mun: p[8] || ''
});
});
// distrito herda o IBGE do município de subordinação
byId.forEach(function (l) {
if (!l.mun && l.sub) {
var pai = byId.get(l.sub);
if (pai && pai.mun) l.mun = pai.mun;
}
});
return byId;
}
async function loadBairros(dneDir, uf) {
var byId = new Map();
await readLines(path.join(dneDir, 'LOG_BAIRRO.TXT'), 'latin1', function (l) {
var p = l.split('@');
if (p[1] !== uf) return;
byId.set(p[0], { bai_nu: p[0], uf: p[1], loc_nu: p[2], nome: p[3] });
});
return byId;
}
async function loadLogradouros(dneDir, uf) {
var rows = [];
await readLines(path.join(dneDir, 'LOG_LOGRADOURO_' + uf + '.TXT'), 'latin1', function (l) {
var p = l.split('@');
var tlo = p[8] || '';
var semTipo = nameNorm(p[5]);
// LOG_STA_TLO = 'N' → o tipo não faz parte do nome usado no endereço
var comTipo = p[9] === 'N' ? semTipo : nameNorm(tlo + ' ' + p[5]);
rows.push({
log_nu: p[0], uf: p[1], loc_nu: p[2], bai_ini: p[3], bai_fim: p[4] || '',
log_no: p[5], compl: p[6] || '', cep: p[7], tlo: tlo, sta: p[9] || '',
abrev: p[10] || '',
comTipo: comTipo, semTipo: semTipo,
tloNorm: nameNorm(tlo),
ehArea: keys.isAreaTlo(nameNorm(tlo)),
cluster: null, regra: '', status: 'sem_nome_osm', nCand: 0
});
});
return rows;
}
// ---------------------------------------------------------------- OSM (utf8)
/**
* Resolve paths de OSM_LOGRADOURO_{UF} (shard ou flat).
* @returns {{ mode: string, paths: string[], label: string }}
*/
function resolveOsmLogradouro(osmDir, uf) {
var resolved = txtAt.resolveDatasetPaths(osmDir, 'OSM_LOGRADOURO_' + uf);
var label =
resolved.mode === 'shard'
? 'OSM_LOGRADOURO_' + uf + '/ (' + resolved.paths.length + ' shards)'
: resolved.mode === 'flat'
? path.basename(resolved.paths[0])
: 'OSM_LOGRADOURO_' + uf + '.TXT';
return { mode: resolved.mode, paths: resolved.paths, label: label, resolved: resolved };
}
/** Lê OSM_LOGRADOURO_{UF} (flat ou shards) agrupando por name_norm (e name_alt_norm). */
async function loadOsmStreets(osmDir, uf, quiet) {
var byName = new Map(); // name_norm -> [feat]
var altOf = new Map(); // name_alt_norm -> Set(name_norm)
var lines = 0, semGeom = 0;
var res = resolveOsmLogradouro(osmDir, uf);
if (!res.paths.length) {
return { byName: byName, altOf: altOf, lines: 0, semGeom: 0, mode: 'missing', files: 0 };
}
if (!quiet && res.mode === 'shard') {
process.stderr.write(' lendo ' + res.label + '\n');
}
await readLinesMany(res.paths, null, function (l) {
var p = l.split('@');
lines++;
var lat = num(p[10]), lng = num(p[11]);
if (lat === null || lng === null) { semGeom++; return; }
var nn = p[2];
if (!nn) return;
var feat = {
// `id` = osm_id da way. Não participa de cluster nem de casamento —
// existe só para o cluster VENCEDOR poder dizer, na saída, de quais
// ways ele é feito. É o que deixa o consumidor buscar o traçado por
// id exato, em vez de recasar nome na hora de desenhar.
id: p[0] || '',
lat: lat, lng: lng,
latMin: num(p[12]) === null ? lat : num(p[12]),
latMax: num(p[13]) === null ? lat : num(p[13]),
lngMin: num(p[14]) === null ? lng : num(p[14]),
lngMax: num(p[15]) === null ? lng : num(p[15]),
n: num(p[16]) || 1,
kind: p[3] || ''
};
var arr = byName.get(nn);
if (arr) arr.push(feat);
else byName.set(nn, [feat]);
var alt = p[18];
if (alt) {
var parts = alt.split(';');
for (var i = 0; i < parts.length; i++) {
var a = parts[i];
if (!a || a === nn) continue;
var s = altOf.get(a);
if (s) s.add(nn);
else altOf.set(a, new Set([nn]));
}
}
if (!quiet && lines % 200000 === 0) {
process.stderr.write('\r osm ' + lines + ' linhas, ' + byName.size + ' nomes');
}
});
if (!quiet) process.stderr.write('\r osm ' + lines + ' linhas, ' + byName.size + ' nomes\n');
return {
byName: byName, altOf: altOf, lines: lines, semGeom: semGeom,
mode: res.mode, files: res.paths.length
};
}
/** Pontos addr:street (flat ou shards) — peso 1, só se não houver way com o mesmo name_norm. */
async function loadAddrPoints(osmDir, uf, byName) {
var resolved = txtAt.resolveDatasetPaths(osmDir, 'OSM_ADDR_POINT_' + uf);
if (!resolved.paths.length) return 0;
var add = 0;
await readLinesMany(resolved.paths, null, function (l) {
var p = l.split('@');
var lat = num(p[1]), lng = num(p[2]);
var nn = p[4];
if (lat === null || lng === null || !nn) return;
if (byName.has(nn)) return; // way nomeada ganha do ponto de numeração
var feat = {
lat: lat, lng: lng, latMin: lat, latMax: lat, lngMin: lng, lngMax: lng,
n: 1, kind: 'addr'
};
var arr = byName.get(nn);
if (arr) arr.push(feat);
else byName.set(nn, [feat]);
add++;
});
return add;
}
// ---------------------------------------------------------------- clusters
function buildClusters(byName, clusterCell) {
var clusters = []; // {name, feats, agg, hasVia, hasArea}
var byNameIdx = new Map(); // name_norm -> [idx]
byName.forEach(function (feats, nn) {
var groups = geo.clusterFeatures(feats, clusterCell);
var idxs = [];
for (var i = 0; i < groups.length; i++) {
var agg = geo.aggregate(groups[i]);
var hasArea = false, hasVia = false;
for (var k = 0; k < agg.kinds.length; k++) {
if (keys.isAreaKind(agg.kinds[k])) hasArea = true;
else hasVia = true;
}
idxs.push(clusters.length);
clusters.push({
name: nn, feats: groups[i], agg: agg,
hasVia: hasVia, hasArea: hasArea
});
}
byNameIdx.set(nn, idxs);
});
return { clusters: clusters, byName: byNameIdx };
}
/**
* Índices derivados sobre os nomes de cluster:
* núcleo sem tipo, fonético, núcleo sem título, fonético sem título,
* núcleo sem conectores no meio, e índice SymSpell K=1 para fuzzy.
*/
function buildDerivedIndexes(byNameIdx) {
var byCore = new Map();
var byPhon = new Map();
var byTitle = new Map();
var byTitlePhon = new Map();
var byMid = new Map();
function push(map, key, idxs) {
if (!key) return;
var a = map.get(key);
if (a) { for (var i = 0; i < idxs.length; i++) a.push(idxs[i]); }
else map.set(key, idxs.slice());
}
byNameIdx.forEach(function (idxs, nn) {
var c = keys.coreName(nn);
if (!c) return;
push(byCore, c, idxs);
push(byPhon, keys.phoneticKey(c), idxs);
var bare = keys.stripTitulos(c).bare;
push(byTitle, bare, idxs);
push(byTitlePhon, keys.phoneticKey(bare), idxs);
push(byMid, keys.stripMidLiga(bare), idxs);
});
return {
byCore: byCore, byPhon: byPhon,
byTitle: byTitle, byTitlePhon: byTitlePhon,
byMid: byMid,
fuzzyDel: buildFuzzyDelIndex(byMid)
};
}
/** deleteKey → [midBare, …] para lookup SymSpell K=1. */
function buildFuzzyDelIndex(byMid) {
var delIndex = new Map();
byMid.forEach(function (_idxs, mid) {
if (!mid || mid.length < 4) return;
var dels = keys.deletes1(mid);
for (var i = 0; i < dels.length; i++) {
var d = dels[i];
var a = delIndex.get(d);
if (a) a.push(mid);
else delIndex.set(d, [mid]);
}
});
return delIndex;
}
/**
* Mid-bares OSM a distância de Levenshtein exatamente 1 do `mid` DNE.
* Só considera nomes com fuzzyMaxDist(len) ≥ 1 (≥len ≥ 10).
*/
function fuzzyMidKeys(mid, delIndex) {
var md = keys.fuzzyMaxDist(mid.length);
if (md < 1 || !delIndex) return [];
var seen = Object.create(null);
var out = [];
var probes = keys.deletes1(mid);
for (var i = 0; i < probes.length; i++) {
var arr = delIndex.get(probes[i]);
if (!arr) continue;
for (var j = 0; j < arr.length; j++) {
var osmMid = arr[j];
if (osmMid === mid || seen[osmMid]) continue;
if (keys.levenshtein(mid, osmMid, md) !== 1) continue;
seen[osmMid] = 1;
out.push(osmMid);
}
}
return out;
}
// ---------------------------------------------------------------- cascata
/**
* Candidatos de um degrau da cascata, já filtrados pela guarda kind-aware.
* Área (`square`/`park`) só serve para TLO_TX de área.
*/
function candidatesFor(row, idxs, clusters) {
if (!idxs || !idxs.length) return [];
var out = [];
for (var i = 0; i < idxs.length; i++) {
var c = clusters[idxs[i]];
if (!row.ehArea && !c.hasVia) continue; // Rua não casa com praça/parque puro
out.push(idxs[i]);
}
return out;
}
function cascadeCandidates(row, idx, clusters) {
var core = keys.coreName(row.comTipo);
var bare = keys.stripTitulos(core).bare;
var mid = keys.stripMidLiga(bare);
var tries = [
['exato', idx.byName.get(row.comTipo)],
['exato', idx.byName.get(row.semTipo)],
['name_alt', idx.altIdx.get(row.comTipo)],
['name_alt', idx.altIdx.get(row.semTipo)],
['nucleo', idx.byCore.get(core)],
['fonetico', idx.byPhon.get(keys.phoneticKey(core))],
// DNE sem título ↔ OSM com Doutor/Prof/… (ou o inverso)
['titulo', idx.byTitle.get(bare)],
['titulo_fonetico', idx.byTitlePhon.get(keys.phoneticKey(bare))],
// DNE/OSM divergem em de/da/do no meio ("Moraes Costa" ↔ "Moraes da Costa")
['conectores', idx.byMid.get(mid)]
];
for (var i = 0; i < tries.length; i++) {
var cand = candidatesFor(row, tries[i][1], clusters);
if (cand.length) return { regra: tries[i][0], cand: cand };
}
// Fuzzy dist=1 (len≥10): último recurso de nome; footprint/desempate filtram depois.
if (!idx.semFuzzy && idx.fuzzyDel) {
var fKeys = fuzzyMidKeys(mid, idx.fuzzyDel);
if (fKeys.length) {
var fIdxs = [];
for (var f = 0; f < fKeys.length; f++) {
var fi = idx.byMid.get(fKeys[f]);
if (fi) {
for (var k = 0; k < fi.length; k++) fIdxs.push(fi[k]);
}
}
var fCand = candidatesFor(row, fIdxs, clusters);
if (fCand.length) return { regra: 'fuzzy', cand: fCand };
}
}
return { regra: '', cand: [] };
}
function main(opts) {
return run(opts);
}
async function run(opts) {
var uf = String(opts.uf || '').toUpperCase();
var quiet = !!opts.quiet;
var log = quiet ? function () {} : function (m) { process.stderr.write(m + '\n'); };
var clusterCell = opts.clusterCell || geo.CELL_CLUSTER;
var footprintCell = opts.footprintCell || geo.CELL_FOOTPRINT;
var maxExtentKm = opts.maxExtentKm || 15;
var dilate = opts.footprintDilate == null ? 1 : opts.footprintDilate;
// 60 km: cabe o maior município de MG (raio ~56 km) e o espalhamento normal
// de um distrito; não cabe a âncora de outra cidade, que erra por centenas.
var ancoraRaioKm = opts.ancoraRaioKm == null ? 60 : opts.ancoraRaioKm;
var envelopeTolKm = opts.envelopeTolKm == null ? 1 : opts.envelopeTolKm;
var useEnvelope = opts.semEnvelope ? false : true;
var useExclusao = opts.semExclusaoCluster ? false : true;
var useVizinhoCep5 = opts.semVizinhoCep5 ? false : true;
var vizinhoCep5TolKm = opts.vizinhoCep5TolKm == null ? 1 : opts.vizinhoCep5TolKm;
var vizinhoCep5Min = opts.vizinhoCep5Min == null ? 3 : opts.vizinhoCep5Min;
var useMaxDistVizinho = opts.semMaxDistVizinho ? false : true;
var maxDistVizinhoKm = opts.maxDistVizinhoKm == null ? 5 : opts.maxDistVizinhoKm;
var useFuzzy = opts.semFuzzy ? false : true;
log('DNE : ' + opts.dneDir);
log('OSM : ' + opts.osmDir);
log('UF : ' + uf);
var osmRes = resolveOsmLogradouro(opts.osmDir, uf);
var semExtract = osmRes.mode === 'missing';
log('[1/6] DNE…');
var localidades = await loadLocalidades(opts.dneDir);
var bairros = await loadBairros(opts.dneDir, uf);
var rows = await loadLogradouros(opts.dneDir, uf);
log(' localidades=' + localidades.size + ' bairros=' + bairros.size + ' logradouros=' + rows.length);
var osm = { byName: new Map(), altOf: new Map(), lines: 0, semGeom: 0, mode: 'missing', files: 0 };
var addrAdded = 0;
if (!semExtract) {
log('[2/6] OSM…');
osm = await loadOsmStreets(opts.osmDir, uf, quiet);
addrAdded = await loadAddrPoints(opts.osmDir, uf, osm.byName);
log(' modo=' + osm.mode + ' arquivos=' + osm.files +
' addr:street sem way homônima: ' + addrAdded);
} else {
log('[2/6] OSM ausente (' + osmRes.label + ') — tudo sai sem_extract');
}
log('[3/6] clusters…');
var built = buildClusters(osm.byName, clusterCell);
var clusters = built.clusters;
for (var ci = 0; ci < clusters.length; ci++) clusters[ci].id = ci;
var derived = buildDerivedIndexes(built.byName);
// name_alt → índices dos clusters do nome principal
var altIdx = new Map();
osm.altOf.forEach(function (nomes, alt) {
var acc = [];
nomes.forEach(function (nn) {
var ix = built.byName.get(nn);
if (ix) for (var i = 0; i < ix.length; i++) acc.push(ix[i]);
});
if (acc.length) altIdx.set(alt, acc);
});
var idx = {
byName: built.byName, altIdx: altIdx,
byCore: derived.byCore, byPhon: derived.byPhon,
byTitle: derived.byTitle, byTitlePhon: derived.byTitlePhon,
byMid: derived.byMid,
fuzzyDel: useFuzzy ? derived.fuzzyDel : null,
semFuzzy: !useFuzzy
};
log(' clusters=' + clusters.length + ' nomes=' + built.byName.size +
' nucleos=' + derived.byCore.size + ' foneticos=' + derived.byPhon.size +
' titulos=' + derived.byTitle.size + ' mids=' + derived.byMid.size +
(useFuzzy ? '' : ' fuzzy=off'));
// ---- Fase 2: âncoras (nome com 1 loc_nu no DNE e 1 cluster no OSM)
log('[4/6] âncoras e footprint…');
var locsDoNome = new Map();
for (var i = 0; i < rows.length; i++) {
var r = rows[i];
var s = locsDoNome.get(r.comTipo);
if (s) s.add(r.loc_nu);
else locsDoNome.set(r.comTipo, new Set([r.loc_nu]));
}
var pontosPorLoc = new Map();
var ancoras = 0;
locsDoNome.forEach(function (locs, nome) {
if (locs.size !== 1) return;
var ix = built.byName.get(nome);
if (!ix || ix.length !== 1) return;
ancoras++;
var loc = locs.values().next().value;
var arr = pontosPorLoc.get(loc);
if (!arr) pontosPorLoc.set(loc, arr = []);
var feats = clusters[ix[0]].feats;
for (var j = 0; j < feats.length; j++) arr.push(feats[j]);
});
var footprints = new Map();
var centroLoc = new Map(); // diagnóstico: centro e raio das âncoras do município
// Âncora de outra cidade alarga a pegada e faz o município aceitar candidato
// de lá — ver geo.trimOutliers. Poda antes de construir pegada E centro:
// os dois são usados como "onde este município fica".
var ancorasPodadas = 0;
var locsPodadas = 0;
pontosPorLoc.forEach(function (pts, loc) {
var poda = geo.trimOutliers(pts, ancoraRaioKm);
if (poda.dropped) { ancorasPodadas += poda.dropped; locsPodadas++; }
pts = poda.points;
pontosPorLoc.set(loc, pts);
footprints.set(loc, geo.buildFootprint(pts, footprintCell, dilate));
var sLat = 0, sLng = 0;
for (var i = 0; i < pts.length; i++) { sLat += pts[i].lat; sLng += pts[i].lng; }
var cLat = sLat / pts.length, cLng = sLng / pts.length;
var raio = 0;
for (var j = 0; j < pts.length; j++) {
var d = geo.distKm(cLat, cLng, pts[j].lat, pts[j].lng);
if (d > raio) raio = d;
}
centroLoc.set(loc, { lat: cLat, lng: cLng, raio: raio });
});
// distrito sem âncora própria usa a pegada do município de subordinação
var herdados = 0;
localidades.forEach(function (l) {
if (footprints.has(l.loc_nu) || !l.sub) return;
var pai = footprints.get(l.sub);
if (pai) { footprints.set(l.loc_nu, pai); herdados++; }
});
log(' ancoras=' + ancoras + ' footprints=' + footprints.size + ' (herdados=' + herdados + ')'
+ (ancoraRaioKm > 0
? ' | podadas=' + ancorasPodadas + ' pontos em ' + locsPodadas +
' localidades (raio=' + ancoraRaioKm + ' km)'
: ' | poda de âncora desligada'));
// ---- Fase 4/5: cascata + desempate, em duas voltas
log('[5/6] casando…');
var stats = { rodadas: [] };
var porBairro = new Map(); // bai_nu -> {sLat,sLng,n}
function resolver(volta) {
var ok = 0, amb = 0, sem = 0;
// 2ª volta: vias únicas da 1ª viram âncoras CEP-5/bairro para o desempate.
var idxAnch = volta > 1 ? indexVizinhoAnchors(rows) : null;
for (var i = 0; i < rows.length; i++) {
var r = rows[i];
if (r.status === 'ok') continue;
if (semExtract) { r.status = 'sem_extract'; continue; }
var got = cascadeCandidates(r, idx, clusters);
if (!got.cand.length) { r.status = 'sem_nome_osm'; r.motivo = ''; sem++; continue; }
var fp = footprints.get(r.loc_nu);
var dentro = [];
for (var c = 0; c < got.cand.length; c++) {
if (geo.footprintOverlap(fp, clusters[got.cand[c]].feats) >= 0.5) dentro.push(got.cand[c]);
}
// sem footprint (município ralo): candidato único ainda vale
if (!dentro.length && !fp && got.cand.length === 1) dentro = got.cand;
if (!dentro.length) {
r.status = 'ambiguo';
r.motivo = fp ? 'fora_do_footprint' : 'sem_footprint';
r.nCand = got.cand.length;
// Quão longe o melhor candidato está da mancha do município? Perto =
// buraco na pegada (recuperável); longe = rua de outra cidade.
var cen = centroLoc.get(r.loc_nu);
if (cen) {
var perto = Infinity;
for (var cc = 0; cc < got.cand.length; cc++) {
var ag2 = clusters[got.cand[cc]].agg;
var dd = geo.distKm(cen.lat, cen.lng, ag2.lat, ag2.lng) - cen.raio;
if (dd < perto) perto = dd;
}
r.distKm = Math.max(0, perto);
}
amb++;
continue;
}
r.nCand = dentro.length;
var pick = pickDesempate(dentro, clusters, r, volta, porBairro, idxAnch);
if (pick.idx == null) {
r.status = 'ambiguo';
r.motivo = pick.via;
amb++;
continue;
}
var escolhido = pick.idx;
var alvo = clusters[escolhido];
// Encadeamento do single-link: nome genérico ("Rua Dois") espalhado pela
// cidade forma uma corrente de células que liga pontas a dezenas de km.
// Medido em Guarulhos: 29 ways, 25 km, 19 clusters concorrentes.
// Via longa legítima (rodovia) aparece como cluster ÚNICO — daí a 2ª condição.
var ag = alvo.agg;
var extKm = Math.max(
(ag.latMax - ag.latMin) * 111,
(ag.lngMax - ag.lngMin) * 102
);
if (extKm > maxExtentKm && dentro.length > 1) {
r.status = 'ambiguo';
r.motivo = 'extensao_' + Math.round(extKm) + 'km';
amb++;
continue;
}
if (useMaxDistVizinho && maxDistVizinhoKm > 0 && idxAnch) {
var dv = distToVizinhoGuard(r, alvo, idxAnch);
if (dv && dv.dist > maxDistVizinhoKm) {
r.status = 'ambiguo';
r.motivo = 'longe_do_' + dv.fonte;
r.distKm = dv.dist;
amb++;
continue;
}
}
r.cluster = alvo;
r.motivo = '';
var soAddr = ag.kinds.length === 1 && ag.kinds[0] === 'addr';
r.regra = soAddr
? 'addr'
: (got.regra === 'exato' && r.ehArea && !alvo.hasVia ? 'area' : got.regra);
r.status = 'ok';
ok++;
// Tamanho é último recurso: não envenena o centroide do bairro.
if (dentro.length === 1 || pick.via === 'cep5' || pick.via === 'bairro' || pick.via === 'unico') {
var bb = porBairro.get(r.bai_ini);
if (!bb) porBairro.set(r.bai_ini, bb = { sLat: 0, sLng: 0, n: 0 });
bb.sLat += r.cluster.agg.lat;
bb.sLng += r.cluster.agg.lng;
bb.n++;
}
}
stats.rodadas.push({ volta: volta, ok: ok, ambiguo: amb, sem_nome_osm: sem });
return ok;
}
resolver(1);
// 2ª volta: footprint cresceu com o que casou, e agora há centroide de bairro
if (!semExtract) {
var extra = new Map();
for (var q = 0; q < rows.length; q++) {
var rr = rows[q];
if (rr.status !== 'ok' || !rr.cluster) continue;
var arr2 = extra.get(rr.loc_nu);
if (!arr2) extra.set(rr.loc_nu, arr2 = []);
for (var z = 0; z < rr.cluster.feats.length; z++) arr2.push(rr.cluster.feats[z]);
}
extra.forEach(function (pts, loc) {
var base = pontosPorLoc.get(loc) || [];
// Poda também aqui: o que a 1ª volta casou entra na pegada da 2ª, e um
// acerto duvidoso longe da cidade se tornaria licença para os próximos.
var podados = geo.trimOutliers(base.concat(pts), ancoraRaioKm).points;
footprints.set(loc, geo.buildFootprint(podados, footprintCell, dilate));
});
for (var w2 = 0; w2 < rows.length; w2++) {
if (rows[w2].status !== 'ok') rows[w2].status = 'pendente';
}
resolver(2);
for (var w3 = 0; w3 < rows.length; w3++) {
if (rows[w3].status === 'pendente') rows[w3].status = 'sem_nome_osm';
}
// ---- Fase 5c: buraco na pegada — candidato único perto da mancha
// Não dilata o footprint (halo metropolitano mistura cidades vizinhas).
// Entre os candidatos de nome, conta quantos caem a ≤ tol km da mancha
// (centro−raio das âncoras). Se sobra exatamente 1 e a extensão é ok → aceita.
var envelopeOk = 0;
if (useEnvelope && envelopeTolKm > 0) {
for (var e5 = 0; e5 < rows.length; e5++) {
var re = rows[e5];
if (re.status !== 'ambiguo' || re.motivo !== 'fora_do_footprint') continue;
var cenE = centroLoc.get(re.loc_nu);
if (!cenE) continue;
var gotE = cascadeCandidates(re, idx, clusters);
if (!gotE.cand.length) continue;
var pertoE = [];
for (var pe = 0; pe < gotE.cand.length; pe++) {
var agP = clusters[gotE.cand[pe]].agg;
var dP = Math.max(0, geo.distKm(cenE.lat, cenE.lng, agP.lat, agP.lng) - cenE.raio);
if (dP <= envelopeTolKm) pertoE.push(gotE.cand[pe]);
}
if (pertoE.length !== 1) continue;
var alvoE = clusters[pertoE[0]];
var agE = alvoE.agg;
var extE = Math.max(
(agE.latMax - agE.latMin) * 111,
(agE.lngMax - agE.lngMin) * 102
);
if (extE > maxExtentKm) continue;
re.cluster = alvoE;
re.motivo = '';
re.regra = gotE.regra === 'exato' && re.ehArea && !alvoE.hasVia
? 'area' : (gotE.regra || 'exato');
re.status = 'ok';
re.nCand = 1;
re.via_envelope = true;
envelopeOk++;
var bbE = porBairro.get(re.bai_ini);
if (!bbE) porBairro.set(re.bai_ini, bbE = { sLat: 0, sLng: 0, n: 0 });
bbE.sLat += agE.lat;
bbE.sLng += agE.lng;
bbE.n++;
}
if (envelopeOk) log(' envelope: recuperou ' + envelopeOk + ' (tol=' + envelopeTolKm + ' km)');
}
stats.envelope_recuperados = envelopeOk;
// ---- Fase 5e: vizinhança CEP-5 (ou bairro) no resíduo fora_do_footprint
// Distância ao vizinho mais próximo já ok — nunca raio de centroide.
// Aceita só se sobrar exatamente 1 candidato de nome a ≤ tol km de ≥min âncoras.
var vizinhoOk = 0;
var exemplosVizinho = [];
if (useVizinhoCep5 && vizinhoCep5TolKm > 0 && vizinhoCep5Min > 0) {
var idxV5 = indexVizinhoAnchors(rows);
for (var v5 = 0; v5 < rows.length; v5++) {
var rV = rows[v5];
if (rV.status !== 'ambiguo' || rV.motivo !== 'fora_do_footprint') continue;
var gotV = cascadeCandidates(rV, idx, clusters);
if (!gotV.cand.length) continue;
var ancV = anchorsForRow(rV, idxV5, vizinhoCep5Min);
if (!ancV) continue;
var pickV = pickVizinhoUnico(
gotV.cand, clusters, ancV.anchors, vizinhoCep5TolKm, maxExtentKm,
rV.loc_nu, null
);
if (!pickV) continue;
var alvoV = clusters[pickV.clusterIdx];
var agVV = alvoV.agg;
rV.cluster = alvoV;
rV.motivo = '';
rV.regra = 'vizinho_cep5';
rV.status = 'ok';
rV.nCand = gotV.cand.length;
rV.via_vizinho_cep5 = true;
rV.nome_regra = gotV.regra;
rV.vizinho_fonte = ancV.fonte;
rV.vizinho_n = ancV.anchors.length;
rV.vizinho_dist = pickV.dist;
vizinhoOk++;
if (exemplosVizinho.length < 30) {
exemplosVizinho.push({
log_nu: rV.log_nu,
dne_nome: (rV.tlo + ' ' + rV.log_no).trim(),
cep: rV.cep,
cep5: ancV.cep5,
localidade: (localidades.get(rV.loc_nu) || {}).nome || '',
geo_regra: 'vizinho_cep5',
nome_regra: gotV.regra,
fonte: ancV.fonte,
fase: 'fora_do_footprint',
n_vizinhos: ancV.anchors.length,
dist_vizinho_km: Math.round(pickV.dist * 1000) / 1000,
n_cand_nome: gotV.cand.length,
vizinhos: topVizinhos(agVV.lat, agVV.lng, ancV.anchors, 3)
});
}
var bbV = porBairro.get(rV.bai_ini);
if (!bbV) porBairro.set(rV.bai_ini, bbV = { sLat: 0, sLng: 0, n: 0 });
bbV.sLat += agVV.lat;
bbV.sLng += agVV.lng;
bbV.n++;
}
if (vizinhoOk) {
log(' vizinho_cep5: recuperou ' + vizinhoOk +
' (tol=' + vizinhoCep5TolKm + ' km, min=' + vizinhoCep5Min + ')');
}
}
stats.vizinho_cep5_recuperados = vizinhoOk;
stats.vizinho_cep5_exemplos = exemplosVizinho;
// ---- Fase 5d: cluster usado por 2+ municípios → dono único
// Uma via física é de uma cidade só. Preferência: loc_nu com mais linhas ok;
// empate → âncora municipal mais próxima do centroide do cluster.
var multiAntes = 0, revogados = 0, clustersMulti = 0;
if (useExclusao) {
var claim = new Map(); // clusterId -> Map(loc_nu -> count)
for (var x = 0; x < rows.length; x++) {
var rx = rows[x];
if (rx.status !== 'ok' || !rx.cluster) continue;
var cid = rx.cluster.id;
var m = claim.get(cid);
if (!m) claim.set(cid, m = new Map());
m.set(rx.loc_nu, (m.get(rx.loc_nu) || 0) + 1);