Skip to content

Order swaths per cell, and let the orderers produce a connected route - #251

Merged
Gonzalo-Mier merged 6 commits into
Fields2Cover:developfrom
u33549:dev/umutc/v2.1.0-devel/orderer-routes
Sep 22, 2026
Merged

Gonzalo-Mier merged 6 commits into
Fields2Cover:developfrom
u33549:dev/umutc/v2.1.0-devel/orderer-routes

Conversation

@u33549

@u33549 u33549 commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

BOUSTROPHEDON, SNAKE, SPIRAL and CUSTOM return a bare F2CSwaths. That turns out to hide two separate problems, and both come from the same place: swath ids.

The id contract

Everything that builds swaths numbers them by position:

// Swaths.cpp
void Swaths::append(const LineString& line, double width, SwathType type) {
  this->emplace_back(line, width, this->size(), type);   // id == index
}

and ordering relies on it:

// Swath.cpp
bool Swath::operator<(const Swath& s) const { return this->getId() < s.getId(); }
// Swaths.cpp
void Swaths::sort() { ... std::sort(data_.begin(), data_.end()); }

The id is a position, not an identity. SwathsByCells::flatten() was the one place that broke it: swaths are generated cell by cell (SwathGeneratorBase::generateSwaths), so every cell numbers from 0, and flatten kept those ids. Six swaths from two cells came out with three distinct ids.

genSortedSwaths starts with sort(), so equal ids end up adjacent and the cells interleave: A0 B0 A1 B1 A2 B2. Nothing throws — the result is a perfectly valid F2CSwaths that drives the machine back and forth across the field.

On tutorial 7's own field, decomposed into two cells: 29 cell crossings instead of 1, and the route grows from 2960 m to 6597 m (RoutePlannerBase::genRoute on the same field: 2784 m).

Three changes

1. flatten() numbers the copy from 0. One place, fixes every caller.

Swath renumbered = s;
renumbered.setId(static_cast<int>(swaths.size()));

2. genSortedSwaths overload taking F2CSwathsByCells. Unique ids keep the cells contiguous, but a pattern applied to the flattened set is still wrong — a spiral over 34 swaths from two cells is a spiral spanning both. Ordering each cell on its own keeps the pattern inside the cell it belongs to.

virtual F2CSwathsByCells genSortedSwaths(
    const F2CSwathsByCells& swaths, uint32_t variant = 0) const;

3. genRoute, so the order comes with its connections.

F2CRoute genRoute(const F2CCells& cells, const F2CSwathsByCells& swaths,
    double d_tol = 1e-4) const;

A bare order ignores the boundary. Consumers join consecutive swaths with a straight hop, and on a field that is not convex that hop leaves the field or crosses covered ground. The body is ten lines and adds no geometry — Route::addSwath(const Swath&, Graph2D&) and RoutePlannerBase::createShortestGraph already exist and are what the TSP planner uses:

F2CSwathsByCells sorted = this->genSortedSwaths(swaths);
F2CGraph2D graph = RoutePlannerBase().createShortestGraph(cells, sorted, d_tol);
F2CRoute route;
for (auto&& cell_swaths : sorted) {
  for (auto&& s : cell_swaths) { route.addSwath(s, graph); }
}

The signature matches the one on SingleCellSwathsOrderBase in v3.0, so code written against it moves over unchanged. genSortedSwaths(const F2CSwaths&) is untouched.

v3.0 builds the graph through Graph2D::addEdges/addEdgesSwathExtremes/reconnectEdges, which do not exist here, so this version goes through createShortestGraph instead. If you would rather the orderers did not reach into RoutePlannerBase, the graph can move into a shared helper both call.

Reading the figures

grey field boundary
light blue cells after decomposition
green → black swaths, shaded by their position in the route: green is driven first, black last
red connections — the route's own path between swaths
magenta a transition with no connection (see the last section)

Before and after are the same field, the same decomposition and the same orderer. Only the ordering and the connections differ.

An L-shaped field, two cells. Left: the straight hops the bare order leaves to the consumer run right across the notch, 392.8 m of them outside the field. Right: genRoute, every connection along the boundary, 0 m outside.

today genRoute

CustomOrder checked the order too late

One check(swaths) mixed three questions, two of which need the swaths and one of which does not, and all three ran deep inside genSortedSwaths:

f2c::rp::CustomOrder order({5, 5, 1});   // accepted
// ... decompose, generate swaths ...     ~13 ms of geometry
order.genSortedSwaths(swaths);           // only here does it complain

Split by what each part depends on. The order is now checked when it is set — it must be a permutation of 0..n-1, which covers both uniqueness and range without needing the swaths. The length comparison stays in sortSwaths, where the swath count is actually known. Same rule and same call sites as v3.0.

Three existing tests move with it: bad_order and out_of_range now expect the constructor to throw, and incomplete_order uses a valid but short order so it still exercises the length check. v3.0 made the same two changes.

What it does on real fields

Run over Fields2Benchmark, decomposed and ordered: 349 of the 350 fields hit at least one of the two problems. Three of them, plus three synthetic fields that isolate each mechanism:

field cells swaths cell crossings connection length outside the field
nl_field_300075 5 60 51 → 4 (ideal 4) 7696 → 2074 m 0 → 0
lt_field_169 6 60 56 → 5 (ideal 5) 5600 → 1665 m 0 → 0
ee_field_214 4 27 20 → 3 (ideal 3) 1944 → 712 m 62.6 → 0 m
two adjacent rectangles 2 12 11 → 1 284 → 84 m 0 → 0
L-shaped notch 2 8 7 → 1 596 → 436 m 392.8 → 0 m
square, two obstacles 7 26 23 → 6 1239 → 329 m 125.7 → 0 m

The two convex-ish real fields never leave the field either way; there the win is only the route length. The concave and holed ones do leave it today, and stop.

nl_field_300075, five cells. The red web on the left is 7696 m of connections crossing the field to reach the next swath id; on the right the red is only the turn at each swath end, 2074 m in total, and the green-to-black shading now runs cell by cell instead of alternating.

today this PR

Tutorial

tutorials/8_complete_flow.cpp taught the pattern this PR is about:

swaths = snake_sorter.genSortedSwaths(swaths);
F2CPath path = path_planner.planPath(robot, swaths, dubins);   // no connections

It now goes through genRoute and planPath(robot, route, dubins). tutorials/5_route_planning.cpp is left alone, but worth noting: its ordering section takes no_hl.getGeometry(0), one cell out of the field, which is how it avoids the multi-cell case.

A limit this PR makes visible but does not fix

createShortestGraph adds border edges ring by ring and never connects the rings to each other, so on a field with obstacles each interior ring is its own connected component. On the square with two obstacles above: 74 nodes, 3 components, and 6 of 25 transitions get no connection (125.5 m in total).

Nobody noticed before because the TSP never picks a pair whose cost is INF, and the orderers produced no connections at all. genRoute produces them, so the places it cannot are now visible — the magenta segments below are transitions with no connection, not a path.

today this PR

Left, the bare order hops straight over both obstacles. Right, the route follows the boundary everywhere it can, and the two magenta diagonals are the transitions it could not connect.

Measured, the effect is milder than it sounds: planPath falls back to a plain turn there, and on both fields I tried the resulting path stayed inside the field and off the obstacles (0 m over either obstacle). What is wrong is the route as a data structure — a consumer that follows the connection polyline finds nothing. I could not construct a field where it drives through an obstacle, so I am reporting it rather than claiming it. It belongs in its own issue, with these measurements.

While reading v3.0

Three things in v3.0 that this work ran into, none of which affect this PR:

  • CustomOrder::sortSwaths divides by custom_order.size(), which is 0 for a default-constructed CustomOrder. Isolating the arithmetic and running it gives SIGFPE. That is why emptyOrderThrowsInsteadOfCrashing is in this PR — so the bulk arithmetic is not imported later without noticing.
  • SingleCellSwathsOrderBase::genRoute there still calls swaths.flatten(), so the id collision above applies to v3.0 as well.
  • MultiLineString::connectMultiLineStrings iterates lines[i] in its inner loop where j is the loop variable, so it only ever connects a group to itself. Read, not run.

Copilot AI lite review requested due to automatic review settings September 2, 2026 18:33

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.

🟡 Changes recommended

The updated tutorial docs use a non-existent setMinRadius(...) API (C++ and Python snippets), which will not compile/run as written.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

This PR fixes multi-cell swath ordering/path issues caused by per-cell swath id collisions, and introduces APIs to (a) order swaths per-cell and (b) generate routes that include headland-based connections between swaths.

Changes:

  • Renumber swath ids in F2CSwathsByCells::flatten() to maintain the “id == position” contract across cells.
  • Add genSortedSwaths(const F2CSwathsByCells&) and genRoute(const F2CCells&, const F2CSwathsByCells&) to SingleCellSwathsOrderBase so orderers can produce per-cell ordering and connected routes.
  • Update tutorials/docs and add C++/Python tests covering multi-cell ordering, unique flatten ids, genRoute, and stricter CustomOrder validation.
File summaries
File Description
tutorials/python/8_complete_flow.py Switch tutorial to multi-cell swaths and use genRoute + route-based planPath.
tutorials/8_complete_flow.cpp Same as Python tutorial: generate SwathsByCells, then genRoute, then plan from route.
tests/python/route_planning/snake_order_test.py Add Python coverage for per-cell ordering, genRoute, and unique ids from flatten().
tests/cpp/types/SwathsByCells_test.cpp Add C++ tests ensuring flatten() produces unique ids and doesn’t mutate sources.
tests/cpp/route_planning/snake_order_test.cpp Add C++ tests asserting genRoute adds (and keeps) intra-cell connections.
tests/cpp/route_planning/custom_order_test.cpp Update/expand tests for earlier CustomOrder validation and per-cell application.
tests/cpp/route_planning/boustrophedon_order_test.cpp Add multi-cell ordering tests and demonstrate why per-cell ordering matters.
src/fields2cover/types/SwathsByCells.cpp Implement flatten() renumbering to avoid cross-cell id collisions.
src/fields2cover/route_planning/single_cell_swaths_order_base.cpp Implement per-cell genSortedSwaths and new genRoute using shortest-path graph.
src/fields2cover/route_planning/custom_order.cpp Validate custom order at set-time; move size check into sortSwaths.
include/fields2cover/route_planning/single_cell_swaths_order_base.h Declare new per-cell genSortedSwaths and genRoute API.
include/fields2cover/route_planning/custom_order.h Update CustomOrder validation helper signature/docs.
docs/source/tutorials/complete_flow.rst Update tutorial narrative/snippets to use genRoute and multi-cell swaths.
CHANGELOG.md Document the new APIs and bugfixes.
Review details

Suppressed comments (1)

docs/source/tutorials/complete_flow.rst:91

  • The Python snippet uses robot.setMinRadius(2), but the wrapped Robot method is setMinTurningRadius(...). This example will raise an AttributeError in Python as written.
    robot = f2c.Robot(2.0, 6.0);
    robot.setMinRadius(2);
    const_hl = f2c.HG_Const_gen()
    mid_hl = const_hl.generateHeadlands(field.getField(), 1.5 * robot.getWidth())
  • Files reviewed: 14/16 changed files
  • Comments generated: 2
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread docs/source/tutorials/complete_flow.rst Resolved
Comment thread CHANGELOG.md Resolved
@Gonzalo-Mier

Copy link
Copy Markdown
Member

Hi @u33549, I like the idea of this PR.

Be aware that there is an unwanted behaviour added in this PR, which is crossing the inner field. The previous behaviour was, in part, intended, to alert the user that headlands are needed to make turns for tractors. In this cases, the algorithm uses the borders of the inner field, instead of the headland lines. Do you have any idea how to solve this? Maybe adding some corridor logic here?

On the other hand, I see the impact of this algorithm for aerial drones. Do you have any idea how we can provide some option for the user to use the library for UGV or UAV and for them to be aware of the implications, like in this case crossing the inner field?

@u33549

u33549 commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @Gonzalo-Mier,
A idea about the first question: opennav_coverage#141 introduced full headland coverage, where scan lines ('swaths') don't need to extend all the way to the end of the headland — the vehicle can join and leave a line from any desired point. Not a full corridor solution, but might be a useful building block when we get to that.

On the second question, I'd lean towards a separate repo (something like f2c-air) rather than a flag/option inside Fields2Cover itself. UGV and UAV users are fairly different audiences, and UAV systems shouldn't have to carry the extra code weight of UGV-specific logic they'll never use.

@u33549

u33549 commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Could you point to a specific example this happens? I want to make sure I'm looking at the same case you mean by "crossing the inner field."

@Gonzalo-Mier

Copy link
Copy Markdown
Member
645180290-f8889b24-d3ba-4413-8f92-870917f34acd

This for example, has several intances of crossing the field without headlands.

I prefer to have everything in the same repo, as the problem is essentially the same.

@u33549

u33549 commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

I'll take a look at this.

@u33549

u33549 commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

@Gonzalo-Mier i found it:

Reproduced your example. The gap turned out to be in our own setup, not the library: our decomposed cells had zero gap between them, so their borders overlapped and confused the routing graph.

corridor_A1_dec_travel

Full chain, real path:

full_chain_highlighted full_chain_corridor_zoom

@u33549

u33549 commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor Author

I prefer to have everything in the same repo, as the problem is essentially the same.

What do you think of a solution like this, with three CMake targets in the same one:

fields2cover_core — geometry, swath generation, decomposition, objectives (both need this)
fields2cover_ugv — route planning with headland/corridor/turning-radius awareness (ground-specific)
fields2cover_uav — route planning without those constraints (aerial-specific)
Aerial users link the core and uav targets; they never include the UGV routing weight. Same repository, same version, same pull request workflow—a dependency split, not a fork.

With this method, we automate the release of three PIP versions—f2c-ground, f2c-air, and f2c-all—during the PIP installation process, allowing users to install whichever one they prefer.

If you'd like, let's open a separate issue for the headland routes and this architectural planning—we're discussing multiple issues here, and it might get confusing.

@u33549
u33549 force-pushed the dev/umutc/v2.1.0-devel/orderer-routes branch from 7cd5e92 to 1d7c724 Compare September 3, 2026 19:54
@u33549

u33549 commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Also, I don't really keep up with the tutorials, so if there's anything I forgot to update or misrepresented there, please let me know and I can correct it.

Each cell numbers its swaths from 0, so flatten() repeated them and
Swaths::sort(), which orders on the id alone, interleaved the cells.
Every cell numbers its swaths from 0, so ordering a flattened multi-cell
set interleaved the cells. A bare order also ignores the boundary, so a
snake or spiral skip cut over covered ground; genRoute connects the
swaths through the headland graph the route planner already builds.
Robot only has setMinTurningRadius, so both snippets have been wrong for
a while. Pre-existing, in the block this PR already rewrites.
@u33549
u33549 changed the base branch from main to develop September 4, 2026 17:19
@pascalzauberzeug pascalzauberzeug added this to the 2.2.0 milestone Sep 8, 2026
@u33549
u33549 force-pushed the dev/umutc/v2.1.0-devel/orderer-routes branch from 1d7c724 to 9d1c1dd Compare September 18, 2026 17:38
@u33549

u33549 commented Sep 18, 2026

Copy link
Copy Markdown
Contributor Author

No changes were made; I accidentally did a force push while editing my fork.

@Gonzalo-Mier

Copy link
Copy Markdown
Member

Hi @u33549, thank you again for another awesome PR. This has been requested for quite a while, so thank you for implementing it.

What do you think of a solution like this, with three CMake targets in the same one:

fields2cover_core — geometry, swath generation, decomposition, objectives (both need this) fields2cover_ugv — route planning with headland/corridor/turning-radius awareness (ground-specific) fields2cover_uav — route planning without those constraints (aerial-specific) Aerial users link the core and uav targets; they never include the UGV routing weight. Same repository, same version, same pull request workflow—a dependency split, not a fork.

I still prefer to keep just one single repo and cmake for everything. It is confusing to have more than one and also harder to maintain. If you prefer it, we could create tutorials specific for certain use-cases. As you mention, we can discuss that in another issue.

@Gonzalo-Mier
Gonzalo-Mier merged commit c7f63bf into Fields2Cover:develop Sep 22, 2026
69 of 70 checks passed
@u33549
u33549 deleted the dev/umutc/v2.1.0-devel/orderer-routes branch September 22, 2026 13:21
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.

4 participants