Skip to content

Feat/tikz galleries - #98

Open
lrleon wants to merge 13 commits into
masterfrom
feat/tikz-galleries
Open

Feat/tikz galleries#98
lrleon wants to merge 13 commits into
masterfrom
feat/tikz-galleries

Conversation

@lrleon

@lrleon lrleon commented Jul 21, 2026

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • Nuevas funcionalidades
    • Nueva galería “standalone” exportable a TikZ/LaTeX con 20 paneles de geometría computacional.
    • Ejemplo ampliado con visualizaciones de QuadTree y consultas en R-Tree / R*-Tree.
    • API de depuración pública debug_snapshot() en R-Tree y R*-Tree para inspeccionar la estructura.
  • Mejoras
    • Modernizado el backend de generación de planos TikZ (colecciones y leyendas) para un render más sólido.
  • Tests
    • Nuevas pruebas de invariantes estructurales de snapshots y validación de renderizado TikZ (incluye ausencia de valores inválidos).

lrleon added 4 commits July 20, 2026 17:00
…ithms

Se añade soporte para visualizar la estructura jerárquica de árboles R y R*
(con sus MBR y cajas de entrada) en un plano TikZ, incluyendo consultas
de intersección con rectángulos. Se implementan las funciones
put_rtree_result, visualize_rtree y visualize_rtree_query, y se extiende
la clase RTree (tpl_r_tree.H) con DebugNode, DebugSnapshot y el método
debug_snapshot(). Se agregan pruebas unitarias y ejemplos completos de
galería que incluyen quadtree y árboles R/R*.
…ithms

Se añade soporte para visualizar la estructura jerárquica de árboles R y R*
(con sus MBR y cajas de entrada) en un plano TikZ, incluyendo consultas
de intersección con rectángulos. Se implementan las funciones
put_rtree_result, visualize_rtree y visualize_rtree_query, y se extiende
la clase RTree (tpl_r_tree.H) con DebugNode, DebugSnapshot y el método
debug_snapshot(). Se agregan pruebas unitarias y ejemplos completos de
galería que incluyen quadtree y árboles R/R*.
…ithms

Se añade soporte para visualizar la estructura jerárquica de árboles R y R*
(con sus MBR y cajas de entrada) en un plano TikZ, incluyendo consultas
de intersección con rectángulos. Se implementan las funciones
put_rtree_result, visualize_rtree y visualize_rtree_query, y se extiende
la clase RTree (tpl_r_tree.H) con DebugNode, DebugSnapshot y el método
debug_snapshot(). Se agregan pruebas unitarias y ejemplos completos de
galería que incluyen quadtree y árboles R/R*.
…ithms

Se añade soporte para visualizar la estructura jerárquica de árboles R y R*
(con sus MBR y cajas de entrada) en un plano TikZ, incluyendo consultas
de intersección con rectángulos. Se implementan las funciones
put_rtree_result, visualize_rtree y visualize_rtree_query, y se extiende
la clase RTree (tpl_r_tree.H) con DebugNode, DebugSnapshot y el método
debug_snapshot(). Se agregan pruebas unitarias y ejemplos completos de
galería que incluyen quadtree y árboles R/R*.
Copilot AI review requested due to automatic review settings July 21, 2026 20:13
@coderabbitai

coderabbitai Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Se añade una galería TikZ de 20 algoritmos geométricos, se amplía el ejemplo de estructuras espaciales con QuadTree, RTree y RStarTree, se incorpora RTree::debug_snapshot() con pruebas estructurales y se migra parte del backend TikZ a Array.

Changes

Visualización espacial y soporte de depuración

Layer / File(s) Summary
API de snapshots e invariantes de R-tree
tpl_r_tree.H, Tests/r_tree_debug_snapshot_test_helpers.H, Tests/r_tree_test.cc, Tests/r_star_tree_test.cc
RTree expone snapshots DFS con cajas, profundidad, hojas, entradas e hijos; los helpers y tests validan árboles vacíos, raíces hoja y estructuras multinivel.
Contenedores y ordenación del backend TikZ
tikzgeom.H
Las geometrías, objetos y leyendas usan Array; el renderizado ordena objetos por capa y orden de inserción mediante quicksort_op.
Visualización de estructuras espaciales
Examples/tikz_tree_structures_example.cc, Tests/tikzgeom_algorithms_test.cc
El ejemplo dibuja QuadTree, RTree y RStarTree con consultas y métricas; los tests cubren sus visualizaciones TikZ.
Galería de geometría computacional
Examples/tikz_computational_geometry_gallery_example.cc
Se añade un ejecutable que genera un documento LaTeX standalone con 20 paneles, captions y métricas de algoritmos geométricos.
Modernización de cabeceras y utilidades
ah-comb.H, ah-ranges.H, tpl_array.H, tpl_dynArray.H, array_it.H, point.H, tpl_avl.H, tpl_avlRk.H, tpl_binNodeUtils.H
Se normalizan formatos, include guards, detección de ranges y uso de contenedores sin cambios funcionales observables, salvo la activación de ah-errors.H.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant RTree
  participant DebugSnapshot
  participant TikzPlane
  RTree->>DebugSnapshot: Genera snapshot estructural
  DebugSnapshot->>TikzPlane: Entrega nodos, cajas y aciertos
  TikzPlane->>TikzPlane: Emite comandos TikZ
Loading

Possibly related PRs

  • lrleon/Aleph-w#93: Añade la base de RTree/RStarTree ampliada aquí con debug_snapshot().
  • lrleon/Aleph-w#97: Comparte la integración de snapshots y las pruebas de visualización TikZ para RTree y RStarTree.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed El título refleja el cambio principal: se añaden galerías y ejemplos TikZ nuevos relacionados con la geometría computacional.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Header Docstring Coverage ✅ Passed Las APIs públicas nuevas o tocadas en headers in-scope (p.ej., point.H, ah-ranges.H, array_it.H, tpl_r_tree.H) llevan Doxygen; no vi huecos.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/tikz-galleries

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds visualization/debugging support for spatial trees (notably R-tree/R*-tree) and expands TikZ-based “gallery” examples to showcase computational-geometry algorithms and data structures.

Changes:

  • Added RTree::debug_snapshot() plus snapshot structs to expose full R-tree structure (payload-independent) for visualization/debugging.
  • Refactored TikZ geometry rendering to use Aleph Array (and Aleph sorting utilities) instead of std::vector in core TikZ code paths.
  • Extended tikzgeom_algorithms.H with helpers to render additional algorithm outputs (including R-tree rendering), plus new tests and example galleries.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
tpl_r_tree.H Adds debug snapshot structs and debug_snapshot() API for R-tree visualization.
tikzgeom.H Replaces std::vector usage with Array and switches ordering to Aleph sort utils.
tikzgeom_algorithms.H Adds visualization helpers (incl. R-tree) and refactors formatting/structure.
Tests/tikzgeom_algorithms_test.cc Adds visualization tests for R-tree and R*-tree query rendering.
Tests/r_tree_test.cc Adds invariant tests validating RTree::DebugSnapshot structure/bboxes.
Tests/r_star_tree_test.cc Adds invariant tests validating RStarTree::DebugSnapshot structure/bboxes.
Examples/tikz_tree_structures_example.cc Extends tree-structure gallery (quadtree + R-tree/R*-tree visuals).
Examples/tikz_computational_geometry_gallery_example.cc Adds a new multi-panel computational geometry TikZ gallery example.

Comment thread Examples/tikz_tree_structures_example.cc Outdated
Comment thread Examples/tikz_computational_geometry_gallery_example.cc
Comment thread tpl_r_tree.H

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
Tests/r_tree_test.cc (1)

207-259: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extraer union_of/check_snapshot_node a un helper de test compartido. Ambos archivos definen exactamente la misma lógica de verificación de invariantes de DebugSnapshot en un namespace anónimo local, duplicando el código.

  • Tests/r_tree_test.cc#L207-L259: mover union_of y check_snapshot_node<Snapshot> a un header de utilidades de test compartido (p. ej. Tests/r_tree_test_utils.H) e incluirlo aquí.
  • Tests/r_star_tree_test.cc#L208-L259: eliminar la copia duplicada e incluir el mismo header de utilidades compartido.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@Tests/r_tree_test.cc` around lines 207 - 259, Extrae union_of y
check_snapshot_node<Snapshot> a un header compartido de utilidades de tests,
preservando exactamente la lógica de verificación de DebugSnapshot; en
Tests/r_tree_test.cc, líneas 207-259, mueve ambas funciones al helper e incluye
dicho header, y en Tests/r_star_tree_test.cc, líneas 208-259, elimina la copia
local e incluye el mismo helper.
tpl_r_tree.H (1)

1103-1147: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Documentar la profundidad de pila para la recursión en debug_snapshot().

El comentario Doxygen documenta la complejidad temporal (O(n)) pero no la profundidad de la pila de llamadas del DFS recursivo (self(self, ...)), que es O(height_). Esto es requerido explícitamente por las guías de codificación para algoritmos recursivos.

📝 Sugerencia de documentación
   /** `@brief` Capture the full tree structure for visualization/debugging.
    *  `@return` A `@ref` DebugSnapshot with every node in preorder; empty
    *          (`nodes` empty, `root` unset) when the tree `is_empty()`.
    *  `@par` Complexity O(n).
+   *  `@note` Recursive DFS; call-stack depth is O(height_), bounded by the
+   *        tree's height.
    *  `@throws` std::bad_alloc if node allocation fails.
    */

Como indican las guías de codificación, "Document space complexity for recursive algorithms (call stack depth) in Doxygen".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tpl_r_tree.H` around lines 1103 - 1147, Update the Doxygen comment for
debug_snapshot() to document the recursive DFS call-stack depth as O(height_),
alongside the existing O(n) time complexity. Do not change the implementation or
other complexity descriptions.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@Examples/tikz_computational_geometry_gallery_example.cc`:
- Around line 434-436: Replace the panels container in the relevant example code
with Aleph’s Array<Tikz_Plane>, preserving the reserve capacity of 20. Update
all panels operations, including emplace_back, back, and operator[], to use the
corresponding Array APIs while leaving the existing geometry behavior unchanged.
- Around line 696-710: Update the output-generation flow around the stream used
by the panel draw loop to explicitly close it and validate its final state after
writing the document footer. Only print the “Generated” success message and
compile hint when closing and stream validation succeed; otherwise report the
write/close failure and avoid claiming successful generation.

---

Nitpick comments:
In `@Tests/r_tree_test.cc`:
- Around line 207-259: Extrae union_of y check_snapshot_node<Snapshot> a un
header compartido de utilidades de tests, preservando exactamente la lógica de
verificación de DebugSnapshot; en Tests/r_tree_test.cc, líneas 207-259, mueve
ambas funciones al helper e incluye dicho header, y en
Tests/r_star_tree_test.cc, líneas 208-259, elimina la copia local e incluye el
mismo helper.

In `@tpl_r_tree.H`:
- Around line 1103-1147: Update the Doxygen comment for debug_snapshot() to
document the recursive DFS call-stack depth as O(height_), alongside the
existing O(n) time complexity. Do not change the implementation or other
complexity descriptions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9fd7b5cc-f468-4926-b694-21def1e843cd

📥 Commits

Reviewing files that changed from the base of the PR and between 32c2e20 and 23abd95.

📒 Files selected for processing (8)
  • Examples/tikz_computational_geometry_gallery_example.cc
  • Examples/tikz_tree_structures_example.cc
  • Tests/r_star_tree_test.cc
  • Tests/r_tree_test.cc
  • Tests/tikzgeom_algorithms_test.cc
  • tikzgeom.H
  • tikzgeom_algorithms.H
  • tpl_r_tree.H

Comment thread Examples/tikz_computational_geometry_gallery_example.cc
Comment thread Examples/tikz_computational_geometry_gallery_example.cc
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 22, 2026
…los y tests

- En tikz_computational_geometry_gallery_example.cc: cerrar el archivo de salida y verificar errores de escritura para evitar fallos silenciosos.
- En tpl_r_tree.H: corregir error tipográfico en documentación ("movable-only usable" → "move-only") y mejorar la descripción de complejidad de debug_snapshot.
- En tikz_tree_structures_example.cc: cambiar iteración no-const a const para corrección constante.
- En Tests/r_tree_test.cc y Tests/r_star_tree_test.cc: extraer funciones auxiliares duplicadas a un nuevo archivo cabecera r_tree_debug_snapshot_test_helpers.H y unificar su uso, eliminando código repetido.
Copilot AI review requested due to automatic review settings July 22, 2026 19:45
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 22, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated no new comments.

…los y tests

- En tikz_computational_geometry_gallery_example.cc: cerrar el archivo de salida y verificar errores de escritura para evitar fallos silenciosos.
- En tpl_r_tree.H: corregir error tipográfico en documentación ("movable-only usable" → "move-only") y mejorar la descripción de complejidad de debug_snapshot.
- En tikz_tree_structures_example.cc: cambiar iteración no-const a const para corrección constante.
- En Tests/r_tree_test.cc y Tests/r_star_tree_test.cc: extraer funciones auxiliares duplicadas a un nuevo archivo cabecera r_tree_debug_snapshot_test_helpers.H y unificar su uso, eliminando código repetido.
Copilot AI review requested due to automatic review settings July 22, 2026 20:00
…los y tests

- En tikz_computational_geometry_gallery_example.cc: cerrar el archivo de salida y verificar errores de escritura para evitar fallos silenciosos.
- En tpl_r_tree.H: corregir error tipográfico en documentación ("movable-only usable" → "move-only") y mejorar la descripción de complejidad de debug_snapshot.
- En tikz_tree_structures_example.cc: cambiar iteración no-const a const para corrección constante.
- En Tests/r_tree_test.cc y Tests/r_star_tree_test.cc: extraer funciones auxiliares duplicadas a un nuevo archivo cabecera r_tree_debug_snapshot_test_helpers.H y unificar su uso, eliminando código repetido.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 9 out of 9 changed files in this pull request and generated 1 comment.

Comment thread Tests/r_star_tree_test.cc Outdated
Copilot AI review requested due to automatic review settings July 22, 2026 20:04

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 9 out of 9 changed files in this pull request and generated no new comments.

Comments suppressed due to low confidence (1)

Tests/r_star_tree_test.cc:1

  • The file header comment was accidentally changed from a block comment opener (/*) to a line comment (//*). This leaves the following license header lines as raw tokens and also makes the later */ a stray token, which will break compilation.
//*

…los y tests

- En tikz_computational_geometry_gallery_example.cc: cerrar el archivo de salida y verificar errores de escritura para evitar fallos silenciosos.
- En tpl_r_tree.H: corregir error tipográfico en documentación ("movable-only usable" → "move-only") y mejorar la descripción de complejidad de debug_snapshot.
- En tikz_tree_structures_example.cc: cambiar iteración no-const a const para corrección constante.
- En Tests/r_tree_test.cc y Tests/r_star_tree_test.cc: extraer funciones auxiliares duplicadas a un nuevo archivo cabecera r_tree_debug_snapshot_test_helpers.H y unificar su uso, eliminando código repetido.
Copilot AI review requested due to automatic review settings July 22, 2026 20:10

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 9 out of 9 changed files in this pull request and generated no new comments.

@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@Tests/r_tree_debug_snapshot_test_helpers.H`:
- Around line 43-56: Añade documentación Doxygen completa a los helpers union_of
y check_snapshot_node, incluyendo `@brief`, `@param`, `@return`, precondiciones,
garantías de excepción, complejidad temporal y espacial, y garantías de
thread-safety; mantén intacto el comportamiento actual de ambas funciones.
- Around line 80-86: Actualiza check_snapshot_node para recibir y reutilizar un
conjunto compartido de índices visitados durante toda la recursión; marca cada
nodo antes de descender y, si un índice ya aparece, registra una expectativa
fallida y retorna de forma controlada. Mantén la validación de límites existente
y evita contabilizar o procesar nodos repetidos.
- Around line 56-59: Valida idx en check_snapshot_node antes de llamar a
snap.nodes(idx), incluyendo el caso de snapshot vacío y cualquier índice fuera
de rango. Registra una aserción de prueba y retorna inmediatamente con un valor
apropiado cuando el índice no sea válido, preservando el acceso y las
comprobaciones existentes para índices válidos.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a7d4e39f-027d-49ea-b4ca-1ea06c3bbcd3

📥 Commits

Reviewing files that changed from the base of the PR and between 51b17f6 and 02f246e.

📒 Files selected for processing (1)
  • Tests/r_tree_debug_snapshot_test_helpers.H

Comment thread Tests/r_tree_debug_snapshot_test_helpers.H
Comment thread Tests/r_tree_debug_snapshot_test_helpers.H Outdated
Comment thread Tests/r_tree_debug_snapshot_test_helpers.H Outdated
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 25, 2026
…los y tests

- En tikz_computational_geometry_gallery_example.cc: cerrar el archivo de salida y verificar errores de escritura para evitar fallos silenciosos.
- En tpl_r_tree.H: corregir error tipográfico en documentación ("movable-only usable" → "move-only") y mejorar la descripción de complejidad de debug_snapshot.
- En tikz_tree_structures_example.cc: cambiar iteración no-const a const para corrección constante.
- En Tests/r_tree_test.cc y Tests/r_star_tree_test.cc: extraer funciones auxiliares duplicadas a un nuevo archivo cabecera r_tree_debug_snapshot_test_helpers.H y unificar su uso, eliminando código repetido.
Copilot AI review requested due to automatic review settings July 25, 2026 16:25
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 25, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 9 out of 9 changed files in this pull request and generated 1 comment.

Comments suppressed due to low confidence (1)

Examples/tikz_computational_geometry_gallery_example.cc:436

  • This example uses std::vector<Tikz_Plane> even though the codebase policy is to prefer Aleph containers when an equivalent exists. Here the number of panels is known a priori (20), so Array<Tikz_Plane> (with reserve(20) and append(...)) would satisfy the policy and keep container usage consistent across the repository.
  std::vector<Tikz_Plane> panels;
  panels.reserve(20);
  auto & p = panels;  // shorthand

Comment thread Tests/r_tree_debug_snapshot_test_helpers.H
Include tpl_array.H in r_tree_debug_snapshot_test_helpers.H to ensure proper compilation for Array<bool>.
Copilot AI review requested due to automatic review settings July 25, 2026 16:33

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 9 out of 9 changed files in this pull request and generated 1 comment.

Comment thread tikzgeom_algorithms.H Outdated
coderabbitai[bot]
coderabbitai Bot previously approved these changes Jul 25, 2026
Include tpl_array.H in r_tree_debug_snapshot_test_helpers.H to ensure proper compilation for Array<bool>.
Copilot AI review requested due to automatic review settings July 25, 2026 16:53

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 10 out of 10 changed files in this pull request and generated no new comments.

Comments suppressed due to low confidence (1)

Examples/tikz_computational_geometry_gallery_example.cc:440

  • This new example uses std::vector<Tikz_Plane> for the panel collection, but the project container policy requires using Aleph containers when an equivalent exists. Here Array<Tikz_Plane> can be used, replacing emplace_back()/back() with append(Tikz_Plane(...)) and get_last() (or indexing with operator()).
  std::vector<Tikz_Plane> panels;
  panels.reserve(20);
  auto & p = panels;  // shorthand

  // 1. Primitives & polygons showcase.
  p.emplace_back(190, 120, 6, 6);
  {

Include tpl_array.H in r_tree_debug_snapshot_test_helpers.H to ensure proper compilation for Array<bool>.
Copilot AI review requested due to automatic review settings July 26, 2026 16:34

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 19 out of 19 changed files in this pull request and generated 1 comment.

Comments suppressed due to low confidence (1)

tpl_r_tree.H:1138

  • Same readability issue as the leaf case: Array<size_t> child_indices(node.children.size()) sets capacity, not logical size. Switching to a default-constructed Array + reserve() makes it clear this is a push/append build-up, which helps prevent future maintenance mistakes with Aleph::Array’s non-std::vector sizing semantics.
            Array<size_t> child_indices(node.children.size());
            for (size_t i = 0; i < node.children.size(); ++i)
              child_indices.append(self(self, *node.children(i).child, depth + 1));
            snap.nodes(out_idx).children = std::move(child_indices);

Comment thread tpl_r_tree.H Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
ah-ranges.H (1)

571-581: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Inconsistencia de std::move entre las dos implementaciones de ranges_fold_left.

Aquí el fallback hace init = op(init, elem), mientras que la variante de la sección !ALEPH_HAS_RANGES (líneas 913-918) hace init = op(std::move(init), elem). Para tipos costosos de copiar o con sobrecargas que distinguen lvalue/rvalue el resultado y el rendimiento difieren según la configuración del compilador.

♻️ Unificar el fallback
   // Fallback for C++20 - use explicit variable to avoid rvalue issues
   for (auto &&elem : r)
-    init = op(init, elem);
+    init = op(std::move(init), elem);
   return init;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ah-ranges.H` around lines 571 - 581, Unifica el comportamiento de ambos
fallbacks de ranges_fold_left usando std::move(init) al invocar BinaryOp.
Actualiza el bucle de ranges_fold_left para pasar init como rvalue, manteniendo
intactas la ruta std::ranges::fold_left y el resto de la lógica.
🧹 Nitpick comments (10)
Tests/r_tree_test.cc (1)

69-69: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Usar std::ranges::sort para ordenar Array en los tests.

En C++20 esta guía prioriza algoritmos de rangos, y Array expone iteradores STL adecuados (SortArray utiliza std::ranges::sort). Cambiar estos 7 llamados a std::sort(...) por std::ranges::sort mantendrá el comportamiento y alineará el test con el estilo del proyecto.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@Tests/r_tree_test.cc` at line 69, Replace all seven std::sort calls with
std::ranges::sort while preserving their existing ranges and behavior:
Tests/r_tree_test.cc lines 69, 77, and 88, and Tests/r_star_tree_test.cc lines
66, 77, 88, and 96. Use the existing Array iterators and project C++20 ranges
style.

Source: Coding guidelines

tpl_dynArray.H (2)

59-60: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

#include <ah-errors.H> duplicado.

♻️ Limpieza
 `#include` <ah-dry.H>
 `#include` <ah-errors.H>
-#include <ah-errors.H>
 `#include` <tpl_array.H>
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tpl_dynArray.H` around lines 59 - 60, Remove the duplicate `#include`
<ah-errors.H> directive, keeping a single inclusion in the header.

1382-1385: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Comparación con signo/sin signo en has_curr().

curr_idx es long y array_ptr->size() es size_t; la comparación promueve curr_idx a size_t. La guarda curr_idx >= 0 previa evita el fallo lógico, pero el compilador emitirá -Wsign-compare. Un static_cast<size_t>(curr_idx) < array_ptr->size() deja la intención explícita.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tpl_dynArray.H` around lines 1382 - 1385, Update has_curr() to avoid the
signed/unsigned comparison warning by preserving the curr_idx >= 0 guard and
explicitly converting curr_idx to size_t for the comparison with
array_ptr->size(). Keep the existing null-pointer and bounds behavior unchanged.
array_it.H (2)

216-217: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Constructor de conversión implícita.

Array_Iterator(const Array_Container<T> &) no es explicit, por lo que cualquier Array_Container<T> se convierte silenciosamente en iterador en llamadas sobrecargadas. Considerar marcarlo explicit salvo que la conversión implícita sea intencional para la API funcional de Aleph.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@array_it.H` around lines 216 - 217, Mark the Array_Iterator constructor
accepting const Array_Container<T>& as explicit to prevent unintended implicit
conversions during overload resolution, unless the library intentionally
requires this conversion for its functional API.

410-411: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

const size_t n elimina implícitamente la asignación de copia/movimiento.

Al ser un miembro no estático const, Array_Container<T> deja de ser asignable (operator= implícito suprimido), lo que impide reasignar la vista o almacenarla en contenedores que requieran asignación. Para una vista no propietaria conviene un miembro no const y exponer la inmutabilidad solo mediante la interfaz pública (size()/capacity() ya son const).

♻️ Refactor propuesto
   T *base = nullptr;
-  const size_t n = 0;
+  size_t n = 0;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@array_it.H` around lines 410 - 411, El miembro no estático const size_t n
suprime la asignación implícita de Array_Container<T>. Declara n como miembro no
const, manteniendo la inmutabilidad mediante la interfaz pública existente como
size() y capacity(), y conserva sin cambios la semántica de la vista no
propietaria.
tpl_array.H (1)

473-498: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Sobrecargas ambiguas de traverse.

Coexisten traverse(Operation&), traverse(Operation&) const, traverse(Operation&&) const y traverse(Operation&&). Con un lvalue no-const, Operation& y Operation&& (por deducción de referencia reenviada) compiten y la resolución depende de detalles sutiles; además los overloads && con argumento por defecto Operation() no son invocables sin argumentos explícitos de plantilla. Vale la pena consolidar en un único template <class Op> bool traverse(Op &&op) const.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tpl_array.H` around lines 473 - 498, Consolida las cuatro sobrecargas de
traverse en una única plantilla `traverse(Op&& op) const`, eliminando las
variantes con `Operation&`, la versión no const y los argumentos
predeterminados. Conserva el reenvío perfecto hacia `array.traverse` y la firma
const del contenedor.
tpl_avlRk.H (2)

939-950: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Truncamiento potencial al calcular DIFF desde alturas.

static_cast<signed char>(h2) - static_cast<signed char>(h1) convierte cada altura a signed char antes de restar; con alturas > 127 el resultado es incorrecto. Aunque un AVL con size_t de nodos difícilmente supere ~90 de altura, es más robusto restar como enteros y castear el resultado.

🛡️ Ajuste sugerido
-        DIFF(pivot) = static_cast<signed char>(h2) - static_cast<signed char>(h1);
+        DIFF(pivot) =
+          static_cast<signed char>(static_cast<long>(h2) - static_cast<long>(h1));

Aplica igualmente en las líneas 987, 1000, 1035 y 1047.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tpl_avlRk.H` around lines 939 - 950, Actualiza los cálculos de DIFF en
join_with_pivot y en las ubicaciones equivalentes indicadas para restar h1 y h2
como enteros de mayor rango, y solo después convertir el resultado al tipo de
DIFF. Evita convertir cada altura a signed char antes de la resta, preservando
el valor correcto para alturas superiores a 127.

780-1214: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Elimina o conecta las rutinas AVLRk sin llamadores.

join_exclusive_rec, join_with_pivot, join_right, join_left, split_key_rec, split_key_dup_rec, split_pos_rec, extract_min y extract_max no intervienen en la API pública actual: sus versiones públicas usan recorridos iterativos y reinserción con coste O(n)/O(m log(n+m)). Para evitar mantener dos algoritmos divergentes y no documentados, conecta estas rutinas O(log n) a la API pública o elimina las auxiliares sin uso.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tpl_avlRk.H` around lines 780 - 1214, Elimina las rutinas auxiliares sin
llamadores visibles —extract_min, extract_max, join_exclusive_rec,
join_with_pivot, join_right, join_left, split_key_rec, split_key_dup_rec y
split_pos_rec— o intégralas en las implementaciones públicas actuales de
join/split. Si las conectas, sustituye los recorridos iterativos y la
reinserción por estas rutas O(log n), manteniendo la semántica pública
existente; no dejes dos algoritmos divergentes.
tpl_binNodeUtils.H (2)

55-57: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

inline static en plantillas de ámbito de espacio de nombres es contradictorio.

static fuerza enlace interno (una copia por unidad de traducción) y anula el propósito de inline; en plantillas ni siquiera es necesario, porque ya admiten definiciones múltiples. Mismo patrón en las líneas 100-102, 144-146, 799-801, 946-947, 1038, 1322 y 1776.

♻️ Ajuste sugerido
 template <class Node>
-inline static void inorder_rec_helper(Node *node, const int &level, int &position,
-                                      void (*visitFct)(Node *, int, int))
+inline void inorder_rec_helper(Node *node, const int &level, int &position,
+                               void (*visitFct)(Node *, int, int))
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tpl_binNodeUtils.H` around lines 55 - 57, Elimina el calificador static de
inorder_rec_helper y conserva inline para evitar enlace interno innecesario en
la plantilla. Aplica el mismo cambio a todas las funciones de plantilla con el
patrón inline static indicadas en las líneas 100-102, 144-146, 799-801, 946-947,
1038, 1322 y 1776.

2647-2659: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

reset_last() es O(n) por el recuento de nodos.

size(root) recorre todo el árbol solo para fijar pos, de modo que reposicionar el iterador al último elemento cuesta O(n) en lugar de O(log n). Conviene documentar la complejidad en el Doxygen del método o calcular la posición de forma perezosa (solo cuando se consulte get_pos()).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tpl_binNodeUtils.H` around lines 2647 - 2659, El método reset_last() recorre
todo el árbol mediante size(root) para establecer pos. Elimina ese recuento
eager, deja la posición marcada como pendiente al reposicionar en
advance_to_max(root) y haz que get_pos() calcule el índice solo cuando sea
necesario, manteniendo el resultado correcto para el último elemento.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tpl_array.H`:
- Around line 456-459: Corrige Array::rev() para que devuelva el Array temporal
por valor, evitando retornar una referencia colgante tras reverse(). Elimina el
overload duplicado indicado y conserva un único overload const con el tipo de
retorno por valor.

In `@tpl_avl.H`:
- Around line 60-62: Remove the global using namespace Aleph directive before
namespace Aleph in tpl_avl.H at lines 60-62 and tpl_avlRk.H at line 62, leaving
only the namespace Aleph declaration in both headers.

In `@tpl_dynArray.H`:
- Around line 1387-1390: Actualiza los métodos is_last(), reset_last() y end()
para comprobar si array_ptr es nulo antes de acceder a él. Define el
comportamiento seguro para iteradores singulares de forma coherente con
has_curr(), evitando cualquier desreferencia nula y preservando el
comportamiento actual cuando array_ptr es válido.
- Around line 1302-1309: Update DynArray::reverse() to return immediately when
current_dim is zero, before initializing j with current_dim - 1. Preserve the
existing two-pointer swap behavior for non-empty arrays.

---

Outside diff comments:
In `@ah-ranges.H`:
- Around line 571-581: Unifica el comportamiento de ambos fallbacks de
ranges_fold_left usando std::move(init) al invocar BinaryOp. Actualiza el bucle
de ranges_fold_left para pasar init como rvalue, manteniendo intactas la ruta
std::ranges::fold_left y el resto de la lógica.

---

Nitpick comments:
In `@array_it.H`:
- Around line 216-217: Mark the Array_Iterator constructor accepting const
Array_Container<T>& as explicit to prevent unintended implicit conversions
during overload resolution, unless the library intentionally requires this
conversion for its functional API.
- Around line 410-411: El miembro no estático const size_t n suprime la
asignación implícita de Array_Container<T>. Declara n como miembro no const,
manteniendo la inmutabilidad mediante la interfaz pública existente como size()
y capacity(), y conserva sin cambios la semántica de la vista no propietaria.

In `@Tests/r_tree_test.cc`:
- Line 69: Replace all seven std::sort calls with std::ranges::sort while
preserving their existing ranges and behavior: Tests/r_tree_test.cc lines 69,
77, and 88, and Tests/r_star_tree_test.cc lines 66, 77, 88, and 96. Use the
existing Array iterators and project C++20 ranges style.

In `@tpl_array.H`:
- Around line 473-498: Consolida las cuatro sobrecargas de traverse en una única
plantilla `traverse(Op&& op) const`, eliminando las variantes con `Operation&`,
la versión no const y los argumentos predeterminados. Conserva el reenvío
perfecto hacia `array.traverse` y la firma const del contenedor.

In `@tpl_avlRk.H`:
- Around line 939-950: Actualiza los cálculos de DIFF en join_with_pivot y en
las ubicaciones equivalentes indicadas para restar h1 y h2 como enteros de mayor
rango, y solo después convertir el resultado al tipo de DIFF. Evita convertir
cada altura a signed char antes de la resta, preservando el valor correcto para
alturas superiores a 127.
- Around line 780-1214: Elimina las rutinas auxiliares sin llamadores visibles
—extract_min, extract_max, join_exclusive_rec, join_with_pivot, join_right,
join_left, split_key_rec, split_key_dup_rec y split_pos_rec— o intégralas en las
implementaciones públicas actuales de join/split. Si las conectas, sustituye los
recorridos iterativos y la reinserción por estas rutas O(log n), manteniendo la
semántica pública existente; no dejes dos algoritmos divergentes.

In `@tpl_binNodeUtils.H`:
- Around line 55-57: Elimina el calificador static de inorder_rec_helper y
conserva inline para evitar enlace interno innecesario en la plantilla. Aplica
el mismo cambio a todas las funciones de plantilla con el patrón inline static
indicadas en las líneas 100-102, 144-146, 799-801, 946-947, 1038, 1322 y 1776.
- Around line 2647-2659: El método reset_last() recorre todo el árbol mediante
size(root) para establecer pos. Elimina ese recuento eager, deja la posición
marcada como pendiente al reposicionar en advance_to_max(root) y haz que
get_pos() calcule el índice solo cuando sea necesario, manteniendo el resultado
correcto para el último elemento.

In `@tpl_dynArray.H`:
- Around line 59-60: Remove the duplicate `#include` <ah-errors.H> directive,
keeping a single inclusion in the header.
- Around line 1382-1385: Update has_curr() to avoid the signed/unsigned
comparison warning by preserving the curr_idx >= 0 guard and explicitly
converting curr_idx to size_t for the comparison with array_ptr->size(). Keep
the existing null-pointer and bounds behavior unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: bb508895-0975-40b2-8242-e6f7cf146b2e

📥 Commits

Reviewing files that changed from the base of the PR and between 794ab34 and cc68689.

📒 Files selected for processing (14)
  • Tests/prefix_tree_test.cc
  • Tests/r_star_tree_test.cc
  • Tests/r_tree_debug_snapshot_test_helpers.H
  • Tests/r_tree_test.cc
  • ah-comb.H
  • ah-ranges.H
  • array_it.H
  • point.H
  • tikzgeom_algorithms.H
  • tpl_array.H
  • tpl_avl.H
  • tpl_avlRk.H
  • tpl_binNodeUtils.H
  • tpl_dynArray.H
🚧 Files skipped from review as they are similar to previous changes (1)
  • Tests/r_tree_debug_snapshot_test_helpers.H

Comment thread tpl_array.H
Comment thread tpl_avl.H Outdated
Comment thread tpl_dynArray.H
Comment thread tpl_dynArray.H
Include tpl_array.H in r_tree_debug_snapshot_test_helpers.H to ensure proper compilation for Array<bool>.
Copilot AI review requested due to automatic review settings July 26, 2026 17:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 19 out of 19 changed files in this pull request and generated 2 comments.

Comments suppressed due to low confidence (1)

Examples/tikz_computational_geometry_gallery_example.cc:436

  • This new example introduces std::vector<Tikz_Plane> for panel aggregation. The project’s container policy strongly prefers Aleph containers when equivalents exist (here Array<Tikz_Plane> works), and other parts of this PR are already migrating from std::vector to Array. Consider switching panels to Array<Tikz_Plane> and adjusting the emplace_back/back call sites accordingly to keep examples consistent with the library’s container ecosystem.
  std::vector<Tikz_Plane> panels;
  panels.reserve(20);
  auto & p = panels;  // shorthand

Comment thread tpl_array.H
Comment thread tpl_r_tree.H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants