Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions python-package/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,43 @@

## [Unreleased]

### Corrigido

- `geocode()`: a coluna interna usada na busca probabilística
(`temp_lograd_determ`) passa a começar nula, como no pacote R, e não como
texto vazio. Antes, se a base do CNEFE tivesse um logradouro vazio, endereços
sem candidato na busca por similaridade poderiam ser dados como encontrados
nesse logradouro (`pn01`). O release atual do CNEFE não tem logradouro vazio,
então o resultado com os dados atuais não muda.

### Modificado

- `geocode()`: a cada etapa do matching, a remoção dos endereços já encontrados
passou a considerar só os resultados da etapa corrente, em vez de varrer
todos os resultados acumulados, e deixou de fazer duas contagens extras por
etapa. Espelha a otimização já presente no pacote R. O resultado não muda.
- `geocode()`: menor uso de memória. As tabelas de referência do CNEFE passam a
ser apagadas assim que nenhuma etapa seguinte do matching precisa delas, assim
como as tabelas intermediárias depois do laço e da resolução de empates; e as
colunas do CNEFE que o pacote não usa (`code_muni`, `n_setor` e, sem
`resultado_completo`, `cod_setor`) deixam de ser carregadas. Pico de memória
~12% menor com 20 mil endereços e ~33% menor com 1 milhão. Espelha o pacote
R. O resultado não muda.
- `geocode()`: busca probabilística mais rápida. O cálculo de similaridade de
logradouros passou a ser feito uma vez por combinação distinta de chave e
logradouro (em vez de uma vez por endereço), sem candidatos repetidos, e as
etapas sem número deixam de recalcular endereços com número, já testados na
etapa anterior. Mesma query do pacote R. O resultado não muda.
- `geocode()`: interpolação por número (resultados `da01`–`da04` e
`pa01`–`pa03`) mais rápida. O endereço encontrado passou a ser montado uma
vez por grupo de candidatos, e não uma vez por candidato, e o agrupamento
usa colunas curtas em vez do texto do endereço. Mesma query do pacote R. O
resultado não muda.
- `geocode()`: as tabelas de logradouros usadas na busca probabilística passam
a ser filtradas também pelos estados do input, e não só pelos municípios,
deixando de carregar municípios homônimos de outros estados. Espelha o
pacote R. O resultado não muda.

## [0.1.1] - 2026-09-23

### Modificado
Expand Down
24 changes: 21 additions & 3 deletions python-package/geocodebr/geocode.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
select_match_function,
trata_empates_geocode_duckdb,
)
from .tables import drop_obsolete_tables
from .messages import (
message_looking_for_matches,
message_preparing_output,
Expand Down Expand Up @@ -244,9 +245,12 @@ def geocode(
df_input = df_input.with_row_index("tempidgeocodebr")
original_columns = [col for col in input_columns] + ["tempidgeocodebr"]
df_padrao = df_padrao.with_columns(df_input["tempidgeocodebr"])
# Create temp `logradouro` columns to be used in probabilistic match
# Create temp `logradouro` columns to be used in probabilistic match.
# temp_lograd_determ starts as NULL (like R's NA_character_): the
# "temp_lograd_determ IS NOT NULL" filter in the probabilistic joins
# must exclude rows without a Jaro candidate
df_padrao = df_padrao.with_columns(
pl.lit("").alias("temp_lograd_determ"),
pl.lit(None, dtype=pl.Utf8).alias("temp_lograd_determ"),
pl.lit(None, dtype=pl.Float64).alias("similaridade_logradouro"),
)

Expand All @@ -270,7 +274,7 @@ def geocode(
unit="end",
bar_format="{l_bar}{bar}| {n_fmt}/{total_fmt} [{postfix}]",
) as pbar:
for match_type in ALL_POSSIBLE_MATCH_TYPES:
for i, match_type in enumerate(ALL_POSSIBLE_MATCH_TYPES):
key_cols = get_key_cols(match_type)
if all(col in input_padrao_columns for col in key_cols) and not any(
col in campos_nao_declarados for col in key_cols
Expand All @@ -284,14 +288,28 @@ def geocode(
)
matched_rows += affected
pbar.update(affected)
# free the tables that the remaining steps no longer use
drop_obsolete_tables(
con, ALL_POSSIBLE_MATCH_TYPES[i + 1:], campos_nao_declarados
)
if matched_rows == n_rows:
break

# nothing after the loop reads input_padrao_db or the reference tables
drop_obsolete_tables(con, [], campos_nao_declarados)
con.execute("DROP TABLE IF EXISTS input_padrao_db")

message_preparing_output(verboso)
empates_resolvidos = trata_empates_geocode_duckdb(
con, resultado_completo, resolver_empates, verboso
)
output_table_to_use = "output_db" if empates_resolvidos == 0 else "output_db2"
# tie-breaking work tables; output_db is only dropped if the result
# is in output_db2 (IF EXISTS covers the branch that renames it)
con.execute("DROP TABLE IF EXISTS ids_empatados")
con.execute("DROP TABLE IF EXISTS empates_classif")
if output_table_to_use == "output_db2":
con.execute("DROP TABLE IF EXISTS output_db")
## message_add_precision(verboso)
add_precision_col(con, output_table_to_use)
## message_merge_input(verboso)
Expand Down
31 changes: 31 additions & 0 deletions python-package/geocodebr/match_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,5 +136,36 @@ def tabelas_necessarias(campos_nao_declarados: list[str]) -> list[str]:
return list(dict.fromkeys(get_reference_table(mt) for mt in ativos))


def tables_still_needed(
remaining_match_types: list[str], campos_nao_declarados: list[str]
) -> set[str]:
"""Temporary tables that the remaining steps of the loop will still use.

Mirrors ``tabelas_ainda_necessarias()`` in ``r-package/R/utils.R``: the
reference tables of the remaining active steps, plus the two
``unique_logr_*`` tables from ``register_unique_logradouros_table()``
(their base depends only on whether the match_type is ``*03`` or not).
"""
active = [
mt
for mt in remaining_match_types
if not any(col in campos_nao_declarados for col in get_key_cols(mt))
]
tables = {get_reference_table(mt) for mt in active}

probabilistic = [
mt
for mt in active
if mt in PROBABILISTIC_EXACT_TYPES
| PROBABILISTIC_INTERPOLATION_TYPES
| PROBABILISTIC_TYPES_NO_NUMBER
]
if any(mt in {"pn03", "pa03", "pl03"} for mt in probabilistic):
tables.add("unique_logr_municipio_logradouro_localidade")
if any(mt not in {"pn03", "pa03", "pl03"} for mt in probabilistic):
tables.add("unique_logr_municipio_logradouro_cep_localidade")
return tables


def get_prob_match_cutoff(match_type: str) -> float:
return 0.85 if match_type in {"pn01", "pa01", "pl01"} else 0.9
70 changes: 47 additions & 23 deletions python-package/geocodebr/matching.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from .string_dist import calculate_string_dist
from .tables import register_cnefe_table, register_unique_logradouros_table
from .messages import inform
from .utils import quote_ident
from .utils import quote_ident, sql_string


def create_output_db(con: duckdb.DuckDBPyConnection, resultado_completo: bool) -> None:
Expand Down Expand Up @@ -60,7 +60,7 @@ def match_cases(
) -> int:
y = get_reference_table(match_type)
key_cols = get_key_cols(match_type)
register_cnefe_table(con, match_type, pasta_dados)
register_cnefe_table(con, match_type, pasta_dados, resultado_completo=resultado_completo)

join_condition = " AND ".join(f"{y}.{col} = {x}.{col}" for col in key_cols)
cols_not_null = " AND ".join(f"{x}.{col} IS NOT NULL" for col in key_cols)
Expand All @@ -86,7 +86,7 @@ def match_cases(
WHERE {cols_not_null}
"""
)
return update_input_db(con, update_tb=x, reference_tb=output_tb)
return update_input_db(con, update_tb=x, reference_tb=output_tb, match_type=match_type)


def match_weighted_cases(
Expand All @@ -100,12 +100,13 @@ def match_weighted_cases(
) -> int:
y = get_reference_table(match_type)
original_key_cols = get_key_cols(match_type)
register_cnefe_table(con, match_type, pasta_dados)
register_cnefe_table(con, match_type, pasta_dados, resultado_completo=resultado_completo)

cols_not_null = " AND ".join(f"{x}.{col} IS NOT NULL" for col in original_key_cols)
key_cols = [col for col in original_key_cols if col != "numero"]
join_condition = " AND ".join(f"{y}.{col} = {x}.{col}" for col in key_cols)
ordem_first = "ORDER BY ABS(numero - numero_cnefe), numero_cnefe, lat, lon"
sel_free, grp_free = _free_cols(y, key_cols)
colunas_encontradas, additional_first, additional_second = _complete_weighted_columns(
y, key_cols, resultado_completo, ordem_first
)
Expand All @@ -116,9 +117,8 @@ def match_weighted_cases(
SELECT {x}.tempidgeocodebr,
{x}.numero,
{y}.numero AS numero_cnefe,
ABS({x}.numero - {y}.numero) AS distancia_numero,
{y}.lat, {y}.lon,
REGEXP_REPLACE({y}.endereco_completo, ', \\d+ -', CONCAT(', ', {x}.numero, ' (aprox) -')) AS endereco_encontrado,
{y}.endereco_completo{sel_free},
{y}.desvio_metros,
{x}.log_causa_confusao,
{y}.n_casos AS contagem_cnefe {additional_first}
Expand All @@ -134,16 +134,16 @@ def match_weighted_cases(
SELECT tempidgeocodebr,
SUM((1 / ABS(numero - numero_cnefe) * lat)) / SUM(1 / ABS(numero - numero_cnefe)) AS lat,
SUM((1 / ABS(numero - numero_cnefe) * lon)) / SUM(1 / ABS(numero - numero_cnefe)) AS lon,
FIRST(endereco_encontrado {ordem_first}) AS endereco_encontrado,
REGEXP_REPLACE(FIRST(endereco_completo {ordem_first}), ', \\d+ -', CONCAT(', ', numero, ' (aprox) -')) AS endereco_encontrado,
'{match_type}' AS tipo_resultado,
AVG(desvio_metros) AS desvio_metros,
FIRST(log_causa_confusao {ordem_first}) AS log_causa_confusao,
FIRST(contagem_cnefe {ordem_first}) AS contagem_cnefe {additional_second}
FROM temp_db
GROUP BY tempidgeocodebr, endereco_encontrado
GROUP BY tempidgeocodebr, numero {grp_free}
"""
)
return update_input_db(con, update_tb=x, reference_tb=output_tb)
return update_input_db(con, update_tb=x, reference_tb=output_tb, match_type=match_type)


def match_cases_probabilistic(
Expand All @@ -157,7 +157,7 @@ def match_cases_probabilistic(
) -> int:
y = get_reference_table(match_type)
key_cols = get_key_cols(match_type)
register_cnefe_table(con, match_type, pasta_dados)
register_cnefe_table(con, match_type, pasta_dados, resultado_completo=resultado_completo)
unique_logradouros_tbl = register_unique_logradouros_table(con, match_type, pasta_dados)
calculate_string_dist(con, match_type, unique_logradouros_tbl)

Expand Down Expand Up @@ -196,7 +196,7 @@ def match_cases_probabilistic(
WHERE {cols_not_null}
"""
)
return update_input_db(con, update_tb=x, reference_tb=output_tb)
return update_input_db(con, update_tb=x, reference_tb=output_tb, match_type=match_type)


def match_weighted_cases_probabilistic(
Expand All @@ -210,7 +210,7 @@ def match_weighted_cases_probabilistic(
) -> int:
y = get_reference_table(match_type)
original_key_cols = get_key_cols(match_type)
register_cnefe_table(con, match_type, pasta_dados)
register_cnefe_table(con, match_type, pasta_dados, resultado_completo=resultado_completo)
if match_type not in MATCH_TYPES_JARO_REDUNDANTE:
unique_logradouros_tbl = register_unique_logradouros_table(con, match_type, pasta_dados)
calculate_string_dist(con, match_type, unique_logradouros_tbl)
Expand All @@ -221,6 +221,7 @@ def match_weighted_cases_probabilistic(
join_condition = join_condition.replace("input_padrao_db.logradouro", "input_padrao_db.temp_lograd_determ")
cols_not_null_match = cols_not_null.replace(".logradouro", ".temp_lograd_determ")
ordem_first = "ORDER BY ABS(numero - numero_cnefe), numero_cnefe, lat, lon"
sel_free, grp_free = _free_cols(y, key_cols)
colunas_prefix = ""
additional_prefix_first = ""
additional_prefix_second = ""
Expand All @@ -243,9 +244,8 @@ def match_weighted_cases_probabilistic(
SELECT {x}.tempidgeocodebr,
{x}.numero,
{y}.numero AS numero_cnefe,
ABS({x}.numero - {y}.numero) AS distancia_numero,
{y}.lat, {y}.lon,
REGEXP_REPLACE({y}.endereco_completo, ', \\d+ -', CONCAT(', ', {x}.numero, ' (aprox) -')) AS endereco_encontrado,
{y}.endereco_completo{sel_free},
{y}.desvio_metros,
{x}.log_causa_confusao,
{y}.n_casos AS contagem_cnefe {additional_first}
Expand All @@ -261,16 +261,16 @@ def match_weighted_cases_probabilistic(
SELECT tempidgeocodebr,
SUM((1 / ABS(numero - numero_cnefe) * lat)) / SUM(1 / ABS(numero - numero_cnefe)) AS lat,
SUM((1 / ABS(numero - numero_cnefe) * lon)) / SUM(1 / ABS(numero - numero_cnefe)) AS lon,
FIRST(endereco_encontrado {ordem_first}) AS endereco_encontrado,
REGEXP_REPLACE(FIRST(endereco_completo {ordem_first}), ', \\d+ -', CONCAT(', ', numero, ' (aprox) -')) AS endereco_encontrado,
'{match_type}' AS tipo_resultado,
AVG(desvio_metros) AS desvio_metros,
FIRST(log_causa_confusao {ordem_first}) AS log_causa_confusao,
FIRST(contagem_cnefe {ordem_first}) AS contagem_cnefe {additional_second}
FROM temp_db
GROUP BY tempidgeocodebr, endereco_encontrado
GROUP BY tempidgeocodebr, numero {grp_free}
"""
)
return update_input_db(con, update_tb=x, reference_tb=output_tb)
return update_input_db(con, update_tb=x, reference_tb=output_tb, match_type=match_type)


def select_match_function(match_type: str):
Expand All @@ -289,18 +289,22 @@ def update_input_db(
con: duckdb.DuckDBPyConnection,
update_tb: str = "input_padrao_db",
reference_tb: str = "output_db",
match_type: str | None = None,
) -> int:
before = con.execute(f"SELECT COUNT(*) FROM {quote_ident(update_tb)}").fetchone()[0]
con.execute(
# only the ids inserted in THIS step are still in update_tb (previous
# steps already deleted theirs); filtering by tipo_resultado avoids
# scanning the whole output_db -- which grows at every step -- 25 times.
# The DELETE already returns the number of deleted rows. Mirrors
# update_input_db() in R
step_filter = f"WHERE tipo_resultado = {sql_string(match_type)}" if match_type else ""
return con.execute(
f"""
DELETE FROM {quote_ident(update_tb)}
WHERE tempidgeocodebr IN (
SELECT tempidgeocodebr FROM {quote_ident(reference_tb)}
SELECT tempidgeocodebr FROM {quote_ident(reference_tb)} {step_filter}
)
"""
)
after = con.execute(f"SELECT COUNT(*) FROM {quote_ident(update_tb)}").fetchone()[0]
return before - after
).fetchone()[0]


def add_precision_col(con: duckdb.DuckDBPyConnection, update_tb: str) -> None:
Expand Down Expand Up @@ -383,6 +387,9 @@ def merge_results_to_input(
expr = f"{quote_ident(y)}.{quote_ident(col)}"
y_exprs.append(f"{expr} AS {quote_ident(col)}")
select_y = ", ".join(y_exprs)
# TABLE, not VIEW: with a VIEW the JOIN + ORDER BY run during the fetch to
# Arrow, and on large inputs the process keeps ~10 GB retained after
# returning (43.9 M rows, Windows), without reducing the peak
con.execute(
f"""
CREATE OR REPLACE TEMP TABLE geocodebr_result AS
Expand Down Expand Up @@ -801,6 +808,23 @@ def _build_found_columns(
return colunas_encontradas, additional_cols


def _free_cols(y: str, key_cols: list[str]) -> tuple[str, str]:
"""Columns of ``y`` that make up ``endereco_completo`` and are not fixed by the join.

They are what splits the candidates of a same ``tempidgeocodebr`` into
distinct addresses. Mirrors ``cols_livres`` in
``r-package/R/match_weighted_cases.R``: partitioning by
``(tempidgeocodebr, numero, free_cols)`` is the same as by
``endereco_encontrado`` (the string is constant within each CNEFE group
and distinct cep/localidade produce distinct strings), but with a short
key and the regex running once per group rather than once per candidate.
"""
free_cols = [c for c in ("cep", "localidade") if c in y.split("_") and c not in key_cols]
sel = "".join(f", {y}.{c} AS {c}_cnefe" for c in free_cols)
grp = "".join(f", {c}_cnefe" for c in free_cols)
return sel, grp


def _complete_weighted_columns(
y: str,
key_cols: list[str],
Expand Down
Loading
Loading