Skip to content

Add TSP route ordering (Fields2Cover genRoute / OR-Tools) - #117

Merged
SteveMacenski merged 17 commits into
open-navigation:mainfrom
u33549:Feature/umutc/f2c-enhancements-main/3-tsp-route
Jul 8, 2026
Merged

SteveMacenski merged 17 commits into
open-navigation:mainfrom
u33549:Feature/umutc/f2c-enhancements-main/3-tsp-route

Conversation

@u33549

@u33549 u33549 commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Summary

Third PR in the series splitting the Fields2Cover (F2C) v2 enhancement branch.
Adds a TSP-based route orderer — ordering the unordered swaths via F2C's
genRoute (OR-Tools) — as a new TSP route mode, alongside the existing
BOUSTROPHEDON / SNAKE / SPIRAL / CUSTOM orderers. Builds on #112 and #113.

Changes

TSP route planning (core)

  • RouteType::TSP and RouteGenerator::generateRouteTSP (+ resolveType),
    wrapping the Fields2Cover genRoute route planner with its OR-Tools knobs.
  • Wired into coverage_server: when route_mode = TSP, swaths are ordered by
    the TSP planner and the connecting path is planned over that route.
  • BT node ports exposing the TSP knobs.
  • Per-cell TSP + route stitching for multi-cell input: a single genRoute call
    builds an all-pairs path matrix that blows up memory, so the route is planned
    per cell and stitched.

Interface changes (additive)

  • types.hpp: RouteType enum + TSP.
  • RouteMode.msg: mode now also accepts TSP; new TSP knobs
    tsp_redirect_swaths (bool), tsp_time_limit (s), tsp_search_for_optimum (bool).

Testing

  • test_route: TSP route generation, route-type resolution, and the TSP knobs.

Note

This PR adds standalone TSP ordering for a single (non-decomposed) field or cell.
A follow-up PR will route decomposed (multi-cell) fields with the TSP planner,
connecting cells through their shared headland rather than a direct shortcut.
Further PRs beyond that will continue splitting out the remaining enhancements.

u33549 added 7 commits July 6, 2026 21:04
- types.hpp: RouteType::TSP = 5
- swath_generator: additive generateSwathsByCells() returning F2CSwathsByCells
  (does not flatten; existing generateSwaths paths unchanged)
- route_generator: generateRouteTSP(cells, sbc, settings) via RoutePlannerBase/OR-Tools;
  resolveType() public wrapper for server branching; toType/toString TSP arm;
  default_tsp_redirect_swaths/time_limit/search_for_optimum/d_tol params + setters
- path_generator: resolveCurve() private helper shared by both overloads;
  generatePath(F2CRoute, PathMode) overload calling planPath(robot, route, curve)
- RouteMode.msg: tsp_redirect_swaths/tsp_time_limit/tsp_search_for_optimum/tsp_d_tol fields
- Tests: B1-T1..T6, T11 (TSP non-empty, coverage preserved, connections, single-cell,
  generateSwathsByCells equivalence, F2CRoute path, toType/toString/createGenerator)
- coverage_server: fork generate_route branch on resolveType()==TSP;
  TSP path: re-wraps field into F2CCells, calls generateSwathsByCells(),
  generateRouteTSP(), generatePath(F2CRoute) (K4 bridge), then toCoveragePathMsg/toNavPathMsg
- K5: TSP + generate_path=false throws CoverageException (no fallback)
- Dynamic params: default_tsp_redirect_swaths (bool), default_tsp_time_limit (int),
  default_tsp_search_for_optimum (bool), default_tsp_d_tol (double)
- Non-TSP existing path preserved exactly (mevcut kod birebir korunur)
- Tests: B1-T13 (default_tsp_* dynamic params round-trip)
- compute_complete_coverage_path: route_mode_type (string) input port wired to
  goal_.route_mode.mode; tsp_redirect_swaths/tsp_time_limit/tsp_search_for_optimum/
  tsp_d_tol ports wired to goal_.route_mode.tsp_* fields (B.3 decomp-port pattern)
- Tests: B1-T14 (XML tsp_* attributes flow through to goal fields)
- Add #include <utility> for pair<> (cpplint build/include_what_you_use)
- Wrap long RCLCPP_DEBUG lines to <= 100 chars (whitespace/line_length)
Race condition fix: server thread sometimes needed more than 1s to spin up,
causing flaky test failures unrelated to coverage logic.
F2C v2.0.0's RoutePlannerBase::genRoute materializes the all-pairs
shortest-path matrix with explicit point paths (N^2 vectors, N ~ 4x total
swaths). On decomposed multi-cell input (11 cells, 917 swaths, N ~ 3700)
this allocates ~2.4GB and dies with std::bad_alloc.

Solve each cell alone (small N) in RouteGenerator::generateRouteTSP and
stitch the per-cell routes with straight-line bridges in decomposition
order. Cells are disconnected after per-cell headland shrink anyway
(inter-cell costs are INF), so no global optimality is lost, and
tsp_time_limit now applies per cell.

Also raise test_server ctest TIMEOUT to 300s: the binary runs 7 tests in
one process and the decomp+TSP tests exceed the 60s default, which killed
the process mid-test with no result file.
Drop internal planning jargon (K-step / decomposition-plan references) and
trim the verbose per-cell-TSP and single-cell-set explanations down to the
essential rationale.
Copilot AI review requested due to automatic review settings July 6, 2026 18:23

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@SteveMacenski

SteveMacenski commented Jul 6, 2026 •

Copy link
Copy Markdown
Member

What does this new ordering actually do?

This also seems to add more duplication than the other feature additions

@u33549

u33549 commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

The existing route modes (BOUSTROPHEDON/SNAKE/SPIRAL/CUSTOM) all order swaths by a fixed sweep pattern — they assume a single-cell field and decide visit order from that pattern alone, without looking at actual connection distances between swaths.

TSP instead wraps Fields2Cover's genRoute (RoutePlannerBase, OR-Tools-based): it treats visiting all swaths as a traveling-salesman problem — computing the real connection cost between every pair of swath endpoints and solving for the order (and direction) that minimizes total travel/connection distance, rather than assuming a serpentine pattern holds.

Where this actually matters: on decomposed / multi-region fields, a fixed pattern order doesn't know about cell boundaries and can produce long backtracking connections between regions. TSP evaluates the real geometry and picks a shorter route instead of assuming pattern adjacency.

Knobs exposed on RouteMode:

tsp_redirect_swaths — allow the solver to reverse a swath's direction if that gives a shorter connection
tsp_time_limit — OR-Tools solver time budget (seconds)
tsp_search_for_optimum — enable guided local search for a better (but slower) solve
This PR adds TSP ordering for a single field/cell. Routing decomposed multi-cell fields with it is a follow-up (uses the same generateRouteTSP, per-cell, then stitches the routes together — the per-cell/stitching rationale is in route_generator.cpp).

@SteveMacenski

Copy link
Copy Markdown
Member

Should we find an architectural way to have this work as a RouteGeneratorPtr rather than embedding in RouteGenerator directly? This breaks the design pattern using the route generator ptr & I think causes this breakout of if/else in the server itself as well causing so much duplication.

@u33549

u33549 commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

The blocker is at the F2C level: RouteGeneratorPtr is a SingleCellSwathsOrderBase (genSortedSwaths(F2CSwaths) -> F2CSwaths), whereas the TSP planner is RoutePlannerBase — a separate, unrelated base class with different inputs (F2CCells + F2CSwathsByCells) and a different output (F2CRoute). So it can't slot into the existing factory as-is, which is what forced the is_tsp branch into the server.

The fix I'd propose is to add a thin abstraction on our side that both implement and that returns a unified F2CRoute:

class RouteMethod {
 public:
  virtual F2CRoute plan(const F2CCells & travel_cells,
                        const F2CSwathsByCells & swaths_by_cells,
                        const RouteMode & settings) = 0;
};
using RouteGeneratorPtr = std::shared_ptr<RouteMethod>;

SwathOrderMethod wraps the existing SingleCellSwathsOrderBase orderers (flattens swaths, calls genSortedSwaths, wraps the result in a single-group F2CRoute).
TspRouteMethod wraps RoutePlannerBase::genRoute.
createGenerator() returns the right one, so the server just calls route_gen_->plan(...) with no is_tsp branching.
Normalizing both paths to F2CRoute also removes the duplication that branch created — the second swath generation and the repeated result-filling collapse into one path.

Sound good?

@SteveMacenski

Copy link
Copy Markdown
Member

Sounds good to me

u33549 added 3 commits July 7, 2026 01:03
F2C exposes swath ordering (SingleCellSwathsOrderBase) and TSP planning
(RoutePlannerBase) as two unrelated base classes with different inputs and
outputs. Add a RouteMethod interface that adapts both behind one plan()
call returning F2CRoute: SwathOrderMethod wraps the orderers, TspRouteMethod
wraps the per-cell TSP planner. Not yet wired in.
RouteGeneratorPtr now points at RouteMethod. RouteGenerator exposes a single
generateRoute(cells, swaths_by_cells, settings) -> F2CRoute that dispatches
polymorphically, so the coverage server no longer branches on the route mode.
The server computes cells and per-cell swaths once and fills the result once,
removing the is_tsp branch, the duplicate decompose and swath generation, and
the duplicated result-filling. TSP without a path now returns ordered swaths
instead of erroring.
Adapt existing tests to generateRoute(cells, swaths_by_cells) and to TSP now
being a valid RouteMethod. Add coverage for the single-group route wrap, path
generation from a wrapped orderer route, and TSP-without-path succeeding.
@u33549
u33549 force-pushed the Feature/umutc/f2c-enhancements-main/3-tsp-route branch from 3289d43 to 6c5063e Compare July 6, 2026 22:25
@u33549

u33549 commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

i think this version is better

u33549 added 2 commits July 8, 2026 01:08
generatePath(Swaths) and the flat generateSwaths(Field/Cells) had no callers
left; only the F2CRoute / SwathsByCells APIs remain.
…load

Both servers duplicated the same F2CRoute flatten loop; it now lives in utils.
@SteveMacenski

Copy link
Copy Markdown
Member

LMK when I should look again

@u33549

u33549 commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

@SteveMacenski, can you check the last commits?

Comment thread opennav_coverage/src/path_generator.cpp Resolved
It was shared by the two generatePath overloads; with the Swaths one removed
it had a single caller, so the body now matches main with only the input type
changed.
Comment thread opennav_coverage/test/CMakeLists.txt Resolved
@u33549

u33549 commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

A question unrelated to the topic how are you able to review things so carefully? Do you have a strategy?

@SteveMacenski

Copy link
Copy Markdown
Member

Otherwise LGTM

A question unrelated to the topic how are you able to review things so carefully? Do you have a strategy?

Years of practice and I'm sure I still miss some.

@u33549

u33549 commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

I fixed the comment issues.

Years of practice and I'm sure I still miss some.

That's really impressive. I spent nearly four years writing code in a different area, and my coding and code review skills had really improved, but since I started working on robotics and with the advancements in AI, I've become really rusty. I didn't really notice it in my own projects, but working with you really brought it home to me. I think I need to go back to the old-school way of developing.

@SteveMacenski

SteveMacenski commented Jul 8, 2026 •

Copy link
Copy Markdown
Member

I feel like we're playing wack-a-mole with comments. These are important ordered clarifications of the workload of the code. Keep all of my comments as they exist aligned with their new locations they exist at.

Remove:

// Cells + per-cell swaths, generated once and reused by the route planner.

@u33549

u33549 commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

I'm really sorry for any misunderstandings. I'm asking about the changes I made here to make sure I understood correctly before pushing them.

     Field field_no_headland = field;
-    // Cells + per-cell swaths, generated once and reused by the route planner.
     F2CCells cells;
     if (do_decomp) {
       F2CCells raw_cells;
       raw_cells.addGeometry(field);
       F2CCells decomposed = decomp_gen_->decompose(raw_cells, goal->decomp_mode);
+
+      // Apply a separate headland to each sub-cell
       cells = goal->generate_headland ?
         headland_gen_->generateHeadlands(decomposed, goal->headland_mode) : decomposed;
     } else {
+      // (1) Optional: Remove headland from polygon field
       if (goal->generate_headland) {
         field_no_headland = headland_gen_->generateHeadlands(field, goal->headland_mode);
       }
       cells.addGeometry(field_no_headland);
     }
+
+    // (2) Generate swaths to cover polygon field, including internal voids
     F2CSwathsByCells swaths_by_cells = swath_gen_->generateSwathsByCells(cells, goal->swath_mode);
     Swaths swaths = swaths_by_cells.flatten();
 
-    // (2) Optional: Generate an ordered route through the unordered swaths
+    // (3) Optional: Generate an ordered route through the unordered swaths
     ...
-      // (3) Optional: Generate connection turns between ordered swaths
+      // (4) Optional: Generate connection turns between ordered swaths
       // Converts UTM back to GPS, if necessary, for action returns

Is this what you meant?

@SteveMacenski

SteveMacenski commented Jul 8, 2026 •

Copy link
Copy Markdown
Member

Yes :-) As long as the comments are now colocated with the changed location of the key API calls to do each step

Edit: whoops, wrong button

@u33549

u33549 commented Jul 8, 2026

Copy link
Copy Markdown
Contributor Author

I hope I understood it correctly and made the right corrections.

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.

3 participants