Repository navigation
Order swaths per cell, and let the orderers produce a connected route - #251
Gonzalo-Mier merged 6 commits into
Conversation
There was a problem hiding this comment.
🟡 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&)andgenRoute(const F2CCells&, const F2CSwathsByCells&)toSingleCellSwathsOrderBaseso 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 stricterCustomOrdervalidation.
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 wrappedRobotmethod issetMinTurningRadius(...). 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.
|
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? |
|
Hi @Gonzalo-Mier, On the second question, I'd lean towards a separate repo (something like |
|
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." |
|
I'll take a look at this. |
|
@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.
Full chain, real path:
|
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) 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. |
7cd5e92 to
1d7c724
Compare
|
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.
1d7c724 to
9d1c1dd
Compare
|
No changes were made; I accidentally did a force push while editing my fork. |
|
Hi @u33549, thank you again for another awesome PR. This has been requested for quite a while, so thank you for implementing it.
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. |




BOUSTROPHEDON,SNAKE,SPIRALandCUSTOMreturn a bareF2CSwaths. 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:
and ordering relies on it:
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.genSortedSwathsstarts withsort(), so equal ids end up adjacent and the cells interleave:A0 B0 A1 B1 A2 B2. Nothing throws — the result is a perfectly validF2CSwathsthat 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::genRouteon the same field: 2784 m).Three changes
1.
flatten()numbers the copy from 0. One place, fixes every caller.2.
genSortedSwathsoverload takingF2CSwathsByCells. 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.3.
genRoute, so the order comes with its connections.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&)andRoutePlannerBase::createShortestGraphalready exist and are what the TSP planner uses:The signature matches the one on
SingleCellSwathsOrderBaseinv3.0, so code written against it moves over unchanged.genSortedSwaths(const F2CSwaths&)is untouched.v3.0builds the graph throughGraph2D::addEdges/addEdgesSwathExtremes/reconnectEdges, which do not exist here, so this version goes throughcreateShortestGraphinstead. If you would rather the orderers did not reach intoRoutePlannerBase, the graph can move into a shared helper both call.Reading the figures
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.genRouteCustomOrderchecked the order too lateOne
check(swaths)mixed three questions, two of which need the swaths and one of which does not, and all three ran deep insidegenSortedSwaths: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 insortSwaths, where the swath count is actually known. Same rule and same call sites asv3.0.Three existing tests move with it:
bad_orderandout_of_rangenow expect the constructor to throw, andincomplete_orderuses a valid but short order so it still exercises the length check.v3.0made 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:
nl_field_300075lt_field_169ee_field_214The 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.Tutorial
tutorials/8_complete_flow.cpptaught the pattern this PR is about:swaths = snake_sorter.genSortedSwaths(swaths); F2CPath path = path_planner.planPath(robot, swaths, dubins); // no connectionsIt now goes through
genRouteandplanPath(robot, route, dubins).tutorials/5_route_planning.cppis left alone, but worth noting: its ordering section takesno_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
createShortestGraphadds 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.
genRouteproduces them, so the places it cannot are now visible — the magenta segments below are transitions with no connection, not a path.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:
planPathfalls 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.0Three things in
v3.0that this work ran into, none of which affect this PR:CustomOrder::sortSwathsdivides bycustom_order.size(), which is 0 for a default-constructedCustomOrder. Isolating the arithmetic and running it givesSIGFPE. That is whyemptyOrderThrowsInsteadOfCrashingis in this PR — so the bulk arithmetic is not imported later without noticing.SingleCellSwathsOrderBase::genRoutethere still callsswaths.flatten(), so the id collision above applies tov3.0as well.MultiLineString::connectMultiLineStringsiterateslines[i]in its inner loop wherejis the loop variable, so it only ever connects a group to itself. Read, not run.