From e84542e5f6ec2f8724414a70588a212e979a3f22 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Fri, 20 Nov 2026 07:48:22 -0500 Subject: [PATCH] feat(engine): squeeze the last sheet in Irregular The frontier rule lets the sheet state pick the next part and sends small parts first, so a part as long as the layout can end up behind them and set the sheet's length. On N26-2CJ (two 55" plates, rings, sectors, an arc and strips on 48 x 96) Auto Nest ended at 75.2" where the hand layout, both plates stacked along one edge, ends at 63.5". After the search, pack the last sheet's parts again in a given order, largest first, each at the lowest point across a strip that ends short of where they reach now, and search the order (single-part moves, then seeded swaps) for one that fits them all. Each strip that takes them is followed by a shorter one. Parts that may turn freely are also offered every 30 degrees. Work is counted, the seed is fixed, and the squeezed sheet replaces the plan's only when the plan then ranks better. N26-2CJ now ends at 62.1", leaving 33.4 x 47.5 against 20.3 x 47.5. A search over few parts runs out of new orders, and decodes it has already made cost no work, so it also ends after a run of rounds that place nothing new, and its per-strip budget shrinks with the part count. CurvedPartsClearEveryInflatedClampInEveryQuadrant asked for a disc on the sheet edge between the clamps. The squeezed sheet is 0.1" shorter with that disc wedged on a clamp's corner, so the test now asks for a disc below the clamps' tops. Co-Authored-By: Claude Fable 5.2 --- .../NestingEngines/IrregularClampZoneTests.cs | 4 +- .../NestingEngines/IrregularSqueezeTests.cs | 253 +++++++++++++ .../Irregular/IrregularNestingEngine.cs | 91 +++++ .../Irregular/OrderedSqueeze.cs | 343 ++++++++++++++++++ docs/nesting-engines.md | 35 +- 5 files changed, 724 insertions(+), 2 deletions(-) create mode 100644 OpenNest.Engine.Tests/NestingEngines/IrregularSqueezeTests.cs create mode 100644 OpenNest.Engine/NestingEngines/Irregular/OrderedSqueeze.cs diff --git a/OpenNest.Engine.Tests/NestingEngines/IrregularClampZoneTests.cs b/OpenNest.Engine.Tests/NestingEngines/IrregularClampZoneTests.cs index 77bf1804..418735f5 100644 --- a/OpenNest.Engine.Tests/NestingEngines/IrregularClampZoneTests.cs +++ b/OpenNest.Engine.Tests/NestingEngines/IrregularClampZoneTests.cs @@ -34,7 +34,9 @@ public class IrregularClampZoneTests Assert.Equal(9, Assert.Single(result.Plates).Placements.Count); AssertDiscsClearClamps(result, 1); LayoutAssert.Valid(job, result); - Assert.Contains(result.Plates[0].Placements, p => p.Y - 1 < stock.WorkArea.Bottom + 0.05); + // A disc drops between the clamps, below their tops: only the clamps are blocked, not + // the band they sit in. The squeezed sheet wedges it on a clamp's corner, short of the edge. + Assert.Contains(result.Plates[0].Placements, p => p.Y - 1 < 0.625); } [Theory] diff --git a/OpenNest.Engine.Tests/NestingEngines/IrregularSqueezeTests.cs b/OpenNest.Engine.Tests/NestingEngines/IrregularSqueezeTests.cs new file mode 100644 index 00000000..9139b1be --- /dev/null +++ b/OpenNest.Engine.Tests/NestingEngines/IrregularSqueezeTests.cs @@ -0,0 +1,253 @@ +using System.Threading; +using OpenNest.Clamps; +using OpenNest.CutOffs; +using OpenNest.Engine.Jobs; +using OpenNest.Engine.NestingEngines.Irregular; +using OpenNest.Geometry; +using static OpenNest.Engine.Tests.NestingEngines.JobBuilder; +using static OpenNest.Engine.Tests.NestingEngines.Shapes; + +namespace OpenNest.Engine.Tests.NestingEngines; + +public class IrregularSqueezeTests +{ + private static OrderedSqueeze Squeeze(IReadOnlyList types, NestPlateStock stock, WorkCounter? counter = null) => + new(types, new NoFitCache(stock.PartSpacing), stock, + stock.ClampZones.Count == 0 ? null : new ClampObstacles(stock), counter ?? new WorkCounter(), + type => type.Orientations); + + /// One copy of each type, side by side along X in type order: a layout to shorten. + private static List InARow(IReadOnlyList types, NestPlateStock stock, params int[] order) + { + var placed = new List(); + var x = stock.WorkArea.Left; + foreach (var index in order) + { + var pose = types[index].Orientations[0]; + placed.Add(new Placed(pose, x - pose.MinX, stock.WorkArea.Bottom - pose.MinY)); + x += pose.Width + stock.PartSpacing; + } + return placed; + } + + private static NestJobResult Result(NestJob job, IReadOnlyList types, SheetFill fill) + { + var builder = new NestJobResultBuilder(job); + builder.AddSheet(fill.Stock, fill.Parts.Select(p => (types[p.Orientation.TypeIndex].Part.Id, p.X, p.Y, p.Orientation.Rotation))); + return builder.Build(NestJobStopReason.Completed); + } + + [Fact] + public void PartsBehindALongOneStackOnIt() + { + // Two squares in front of a bar reach 59; the squares fit above the bar, which is 40 long. + var stock = Stock("sheet", 20, 60, spacing: 0.25, edge: new Spacing(0.25, 0.25)); + var job = Job(new[] + { + Part("bar", Rectangle(40, 8), 1, RotationPolicy.Fixed(0)), + Part("a", Rectangle(9, 9), 1, RotationPolicy.Fixed(0)), + Part("b", Rectangle(9, 9), 1, RotationPolicy.Fixed(0)), + }, new[] { stock }); + var types = PartCatalog.Build(job); + var current = InARow(types, stock, 1, 2, 0); + Assert.True(current.Max(p => p.Right) > 58); + + var fill = Squeeze(types, stock).Fill(current, PackAxis.X, CancellationToken.None); + + Assert.NotNull(fill); + Assert.Equal(3, fill!.Parts.Count); + Assert.True(fill.Parts.Max(p => p.Right) < 41, $"reaches {fill.Parts.Max(p => p.Right)}"); + LayoutAssert.Valid(job, Result(job, types, fill)); + } + + [Fact] + public void SqueezesAcrossTheSheetToo() + { + var stock = Stock("sheet", 60, 20, spacing: 0.25, edge: new Spacing(0.25, 0.25)); + var job = Job(new[] + { + Part("bar", Rectangle(8, 40), 1, RotationPolicy.Fixed(0)), + Part("a", Rectangle(9, 9), 1, RotationPolicy.Fixed(0)), + Part("b", Rectangle(9, 9), 1, RotationPolicy.Fixed(0)), + }, new[] { stock }); + var types = PartCatalog.Build(job); + var bar = types[0].Orientations[0]; + var square = types[1].Orientations[0]; + var other = types[2].Orientations[0]; + var work = stock.WorkArea; + // The squares below the bar, stacked along Y. + var current = new List + { + new(square, work.Left - square.MinX, work.Bottom - square.MinY), + new(other, work.Left - other.MinX, work.Bottom + 9.25 - other.MinY), + new(bar, work.Left - bar.MinX, work.Bottom + 18.5 - bar.MinY), + }; + + var fill = Squeeze(types, stock).Fill(current, PackAxis.Y, CancellationToken.None); + + Assert.NotNull(fill); + Assert.True(fill!.Parts.Max(p => p.Top) < 41, $"reaches {fill.Parts.Max(p => p.Top)}"); + LayoutAssert.Valid(job, Result(job, types, fill)); + } + + [Fact] + public void ASheetThatCannotBeShorterIsKept() + { + var stock = Stock("sheet", 20, 60, spacing: 0.25, edge: new Spacing(0.25, 0.25)); + var job = Job(new[] + { + Part("a", Rectangle(50, 9), 1, RotationPolicy.Fixed(0)), + Part("b", Rectangle(50, 9), 1, RotationPolicy.Fixed(0)), + }, new[] { stock }); + var types = PartCatalog.Build(job); + var a = types[0].Orientations[0]; + var b = types[1].Orientations[0]; + var work = stock.WorkArea; + var current = new List + { + new(a, work.Left - a.MinX, work.Bottom - a.MinY), + new(b, work.Left - b.MinX, work.Bottom + 9.25 - b.MinY), + }; + + Assert.Null(Squeeze(types, stock).Fill(current, PackAxis.X, CancellationToken.None)); + } + + [Fact] + public void OnePartOrTooManyAreLeftAlone() + { + var stock = Stock("sheet", 20, 60, spacing: 0.25); + var job = Job(new[] { Part("box", Rectangle(1, 1), OrderedSqueeze.MaxParts + 1, RotationPolicy.Fixed(0)) }, new[] { stock }); + var types = PartCatalog.Build(job); + var pose = types[0].Orientations[0]; + var one = new List { new(pose, 30, 5) }; + var many = Enumerable.Range(0, OrderedSqueeze.MaxParts + 1).Select(i => new Placed(pose, i * 1.5, 5)).ToList(); + + Assert.Null(Squeeze(types, stock).Fill(one, PackAxis.X, CancellationToken.None)); + Assert.Null(Squeeze(types, stock).Fill(many, PackAxis.X, CancellationToken.None)); + } + + [Fact] + public void PartsKeepClearOfClamps() + { + var clamp = new ClampZone("clamp", new Box(20, 0, 2, 1)); + var stock = Stock("sheet", 20, 60, spacing: 0.25, edge: new Spacing(0.25, 0.25), clampZones: new[] { clamp }); + var job = Job(new[] + { + Part("bar", Rectangle(40, 8), 1, RotationPolicy.Fixed(0)), + Part("a", Rectangle(9, 9), 1, RotationPolicy.Fixed(0)), + Part("b", Rectangle(9, 9), 1, RotationPolicy.Fixed(0)), + }, new[] { stock }); + var types = PartCatalog.Build(job); + // Clear of the clamp: the row starts above it. + var current = InARow(types, stock, 1, 2, 0).Select(p => p with { Y = p.Y + 2 }).ToList(); + + var fill = Squeeze(types, stock).Fill(current, PackAxis.X, CancellationToken.None); + + Assert.NotNull(fill); + LayoutAssert.Valid(job, Result(job, types, fill!)); + } + + [Fact] + public void WorkIsCountedAndBounded() + { + var stock = Stock("sheet", 20, 60, spacing: 0.25, edge: new Spacing(0.25, 0.25)); + var job = Job(new[] + { + Part("bar", Rectangle(40, 8), 1, RotationPolicy.Fixed(0)), + Part("a", Rectangle(9, 9), 1, RotationPolicy.Fixed(0)), + Part("b", Rectangle(9, 9), 1, RotationPolicy.Fixed(0)), + }, new[] { stock }); + var types = PartCatalog.Build(job); + var counter = new WorkCounter(); + + Squeeze(types, stock, counter).Fill(InARow(types, stock, 1, 2, 0), PackAxis.X, CancellationToken.None); + + Assert.InRange(counter.Value, 1, OrderedSqueeze.MaxWork + OrderedSqueeze.TryWork); + } + + [Fact] + public void FewerPartsGetLessWorkPerStrip() + { + Assert.Equal(OrderedSqueeze.TryWork, OrderedSqueeze.TryBudget(11)); + Assert.Equal(OrderedSqueeze.TryWork, OrderedSqueeze.TryBudget(OrderedSqueeze.MaxParts)); + Assert.InRange(OrderedSqueeze.TryBudget(8), OrderedSqueeze.TryBudget(5) + 1, OrderedSqueeze.TryWork - 1); + Assert.True(OrderedSqueeze.TryBudget(2) >= 1); + } + + [Fact] + public void TheSameSheetSqueezesTheSameWay() + { + var stock = Stock("sheet", 30, 80, spacing: 0.25, edge: new Spacing(0.25, 0.25)); + NestJobResult Solve() + { + var job = Job(new[] + { + Part("bar", Rectangle(45, 9), 2, RotationPolicy.Automatic), + Part("disc", Disc(6), 2, RotationPolicy.Automatic), + Part("ell", LShape(12, 10, 4), 2, RotationPolicy.Automatic), + Part("tri", Triangle(10, 7), 2, RotationPolicy.Automatic), + }, new[] { stock }); + var result = new IrregularNestingEngine().Solve(job); + LayoutAssert.Valid(job, result); + return result; + } + + var first = Solve(); + var second = Solve(); + + Assert.Equal(first.Plates.Single().Placements, second.Plates.Single().Placements); + } + + [Fact] + public void TheEngineEndsNoLongerThanWithoutTheSqueeze() + { + var stock = Stock("sheet", 30, 80, spacing: 0.25, edge: new Spacing(0.25, 0.25)); + var job = Job(new[] + { + Part("bar", Rectangle(45, 9), 2, RotationPolicy.Automatic), + Part("disc", Disc(6), 2, RotationPolicy.Automatic), + Part("ell", LShape(12, 10, 4), 2, RotationPolicy.Automatic), + Part("tri", Triangle(10, 7), 2, RotationPolicy.Automatic), + }, new[] { stock }); + + var plain = new IrregularNestingEngine { SqueezeLastSheet = false }.Solve(job); + var squeezed = new IrregularNestingEngine().Solve(job); + + LayoutAssert.Valid(job, squeezed); + Assert.Equal(NestJobStatus.Complete, squeezed.Status); + Assert.Single(squeezed.Plates); + Assert.True(NestJobCost.CompactnessOffcut(job, squeezed) > NestJobCost.CompactnessOffcut(job, plain), + $"{NestJobCost.CompactnessOffcut(job, squeezed)} against {NestJobCost.CompactnessOffcut(job, plain)}"); + } + + [Fact] + public void LockedPartsAreNotTurned() + { + var stock = Stock("sheet", 30, 80, spacing: 0.25, edge: new Spacing(0.25, 0.25)); + var job = Job(new[] + { + Part("bar", Rectangle(45, 9), 2, RotationPolicy.Fixed(0)), + Part("ell", LShape(12, 10, 4), 2, RotationPolicy.Fixed(0)), + Part("tri", Triangle(10, 7), 3, RotationPolicy.Fixed(0)), + }, new[] { stock }); + + var result = new IrregularNestingEngine().Solve(job); + + LayoutAssert.Valid(job, result); + Assert.All(result.Plates.SelectMany(p => p.Placements), p => Assert.Equal(0, p.Rotation)); + } + + [Theory] + [InlineData(null, 48.0, 96.0, "X")] + [InlineData(null, 96.0, 48.0, "X,Y")] + [InlineData(CutOffAxis.Vertical, 96.0, 48.0, "X")] + [InlineData(CutOffAxis.Horizontal, 48.0, 96.0, "Y")] + public void TheSqueezeFollowsTheOffcutTheJobCounts(CutOffAxis? cut, double width, double length, string axes) + { + var stock = Stock("sheet", width, length); + var job = Job(new[] { Part("box", Rectangle(1, 1), 1) }, new[] { stock }, + new NestJobOptions("Lattice", offcutCut: cut)); + + Assert.Equal(axes, string.Join(",", IrregularNestingEngine.SqueezeAxes(job, stock))); + } +} diff --git a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs index 0eaa02f7..995f3645 100644 --- a/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs +++ b/OpenNest.Engine/NestingEngines/Irregular/IrregularNestingEngine.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; +using OpenNest.CutOffs; using OpenNest.Engine.Jobs; using OpenNest.Engine.Jobs.Adapters; @@ -69,6 +70,28 @@ public sealed class IrregularNestingEngine : INestingEngine /// Most parts a plan may hold for the sheet-reduction pass to try it. internal const int MaxReduceParts = 40; + /// Whether the last sheet is squeezed; off only in tests of the search before it. + internal bool SqueezeLastSheet { get; init; } = true; + + /// + /// Step, in radians (30 degrees), of the extra orientations the squeeze offers a part that + /// may turn freely, beside the catalog's. + /// + internal const double SqueezeAngleStep = System.Math.PI / 6; + + /// + /// Axes the last sheet is squeezed along: the one the job's offcut must come off, else along + /// the length of the stock, and across it too when the stock is taller than it is long. + /// + internal static IEnumerable SqueezeAxes(NestJob job, NestPlateStock stock) + { + if (job.Options.OffcutCut != CutOffAxis.Horizontal) + yield return PackAxis.X; + if (job.Options.OffcutCut == CutOffAxis.Horizontal + || (job.Options.OffcutCut == null && stock.WorkArea.Width > stock.WorkArea.Length)) + yield return PackAxis.Y; + } + /// /// Deterministic work budget, in free-region subtractions, after which no further variant /// starts. Keeps big jobs well inside benchmark timeouts without consulting a clock. @@ -221,6 +244,17 @@ public sealed class IrregularNestingEngine : INestingEngine ReportPlan(job, types, improved, progress, token); } } + // Last, shorten the last sheet: its parts packed again in a given order, largest first, + // inside ever shorter strips. Replaces the result only by beating it. + if (SqueezeLastSheet) + { + var squeezed = solver.Squeeze(improved); + if (!ReferenceEquals(squeezed, improved)) + { + improved = squeezed; + ReportPlan(job, types, improved, progress, token); + } + } if (searchOn) SearchUntilCancelled(job, types, solver, demand, improved, groups, progress, token); return BuildResult(job, types, improved, progress, token); @@ -631,6 +665,63 @@ public sealed class IrregularNestingEngine : INestingEngine yield return snake; } + /// + /// Packs the last sheet of a complete plan again inside ever shorter strips + /// (), along each of ; a shorter + /// sheet replaces it when the plan then beats the one given. + /// + public Plan Squeeze(Plan plan) + { + if (plan.Unplaced != 0 || plan.Sheets.Count == 0) + return plan; + var last = plan.Sheets[^1]; + var stock = last.Stock; + if (stock.Outline != null || last.Parts.Count < 2 || last.Parts.Count > OrderedSqueeze.MaxParts) + return plan; + var best = plan; + foreach (var axis in SqueezeAxes(job, stock)) + { + token.ThrowIfCancellationRequested(); + var fill = new OrderedSqueeze(types, CacheFor(stock), stock, ClampsFor(stock), Work, SqueezeOrientations) + .Fill(last.Parts, axis, token); + if (fill == null) + continue; + var sheets = plan.Sheets.Take(plan.Sheets.Count - 1).Append(fill).ToList(); + var candidate = plan with + { + Sheets = sheets, + Cost = NestJobCost.RequireFinite(plan.Cost - NetCost(job.Options, last) + NetCost(job.Options, fill)), + }; + if (candidate.IsBetterThan(best)) + best = candidate; + } + return best; + } + + private readonly Dictionary> squeezeOrientations = new(); + + /// + /// The orientations the squeeze offers : the catalog's, and for a + /// part that may turn freely also every that gives another + /// outline. Built once per type per solve, as each owns no-fit polygons. + /// + private IReadOnlyList SqueezeOrientations(PartType type) + { + if (squeezeOrientations.TryGetValue(type.Index, out var found)) + return found; + var all = type.Orientations.ToList(); + if (type.Perimeter != null && all.Count > 0 && type.Part.Rotation.Kind == RotationPolicyKind.Automatic) + { + var angles = all.Select(o => o.Rotation).ToList(); + for (var turn = 0; turn * SqueezeAngleStep < 2 * System.Math.PI - 1e-9; turn++) + angles.Add(turn * SqueezeAngleStep); + foreach (var angle in RotationCandidates.DistinctOutlines(type.Perimeter, angles).Skip(all.Count)) + if (Orient(type, angle) is { } extra) + all.Add(extra); + } + return squeezeOrientations[type.Index] = all; + } + /// Next private orientation index: far above the catalog's, pair and block poses. private int solvedOrientations = 1_000_000; diff --git a/OpenNest.Engine/NestingEngines/Irregular/OrderedSqueeze.cs b/OpenNest.Engine/NestingEngines/Irregular/OrderedSqueeze.cs new file mode 100644 index 00000000..3ac0e6df --- /dev/null +++ b/OpenNest.Engine/NestingEngines/Irregular/OrderedSqueeze.cs @@ -0,0 +1,343 @@ +#nullable enable +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Clipper2Lib; +using OpenNest.Engine.Jobs; +using OpenNest.Geometry; + +namespace OpenNest.Engine.NestingEngines.Irregular; + +/// +/// Shortens one sheet: packs its parts again inside a strip that ends short of where they reach +/// now, and keeps shortening the strip while they still all fit. +/// +/// The frontier packer lets the sheet state pick the next part, and its rule (least front advance +/// per area) sends small parts first, so a part as long as the layout can end up behind them and +/// set the sheet's length. Here the parts go in a given order instead, largest first to begin +/// with, each at the lowest point any of its orientations reaches across the strip (then nearest +/// the strip's start), the way a sheet is laid out by hand: the big parts along one edge, the +/// rest stacked on them, the small ones in the gaps. A part that does not fit is left out, and a +/// local search over the order (move one part to another position, best move first; then a few +/// seeded swaps from the best order so far) looks for an order that leaves none out. Each strip +/// that takes them all is followed by a shorter one, starting from the order that worked. +/// +/// Every position is a vertex of an exact free region (inner-fit rectangle less the no-fit +/// polygons of clamps and placed parts), as in . Decodes sharing the +/// first parts of an order share those placements. Work is counted, not timed, so the result is +/// deterministic; the swaps come from a fixed seed. +/// +internal sealed class OrderedSqueeze( + IReadOnlyList types, + NoFitCache nfps, + NestPlateStock stock, + ClampObstacles? clamps, + WorkCounter counter, + Func> orientations) +{ + /// Most parts a sheet may hold to be squeezed: a decode costs about their square. + internal const int MaxParts = 30; + + /// How much shorter each strip ends, as a share of the work area along the strip. + internal const double Step = 0.005; + + /// Work one strip length may spend looking for an order that fits. + internal const long TryWork = 600_000; + + /// Fewest parts whose search gets all of . + private const int FullSearchParts = 11; + + /// Work a whole squeeze may spend. + internal const long MaxWork = 3_000_000; + + /// Seeded swaps applied to the best order so far when a local search stalls. + private const int Kicks = 3; + + /// Rounds in a row, per part, that place nothing new before a search gives up. + private const int IdleRounds = 2; + + /// Same slack as the frontier packer's inner-fit rectangle. + private const double FitSlack = 2e-4; + + private const double Tie = 1e-6; + + /// + /// The parts of packed into the shortest strip along + /// found, or null when no strip shorter than they reach now takes them all. + /// + public SheetFill? Fill(IReadOnlyList current, PackAxis axis, CancellationToken token) + { + if (current.Count < 2 || current.Count > MaxParts || stock.Outline != null) + return null; + var work = stock.WorkArea; + var start = axis == PackAxis.X ? work.Left : work.Bottom; + var across = axis == PackAxis.X ? work.Width : work.Length; + var step = Step * (axis == PackAxis.X ? work.Length : work.Width); + if (!(step > 0)) + return null; + + var order = current.Select(p => p.Orientation.TypeIndex) + .OrderByDescending(t => types[t].Area).ThenBy(t => t).ToList(); + var area = order.Sum(t => types[t].Area); + var random = new Random(1); + var limit = counter.Value + MaxWork; + var tryWork = TryBudget(current.Count); + var reach = Extent(current, axis) - step; + List? best = null; + // A strip with less room than the parts' area holds no order of them. + while (counter.Value < limit && (reach - start) * across >= area) + { + token.ThrowIfCancellationRequested(); + var strip = axis == PackAxis.X + ? new Box(work.Left, work.Bottom, reach - work.Left, work.Width) + : new Box(work.Left, work.Bottom, work.Length, reach - work.Bottom); + var found = Search(order, strip, axis, area, random, System.Math.Min(limit, counter.Value + tryWork), token); + if (found is not var (parts, fitted)) + break; + best = parts; + order = fitted; + reach = Extent(parts, axis) - step; + } + return best == null ? null : new SheetFill(stock, best, area); + } + + /// + /// Work one strip length may spend on parts. A round of single-part + /// moves decodes about n^2 orders of n parts, each placed against up to n others, so the same + /// number of rounds costs fewer parts a fourth power less. + /// + internal static long TryBudget(int parts) + { + var share = System.Math.Min(1.0, (double)parts / FullSearchParts); + return System.Math.Max(1, (long)(TryWork * share * share * share * share)); + } + + private static double Extent(IReadOnlyList parts, PackAxis axis) => + axis == PackAxis.X ? parts.Max(p => p.Right) : parts.Max(p => p.Top); + + /// An order's decode, ranked by the part area left out, then by how low the placed + /// parts sit across the strip (their area-weighted center). + private readonly record struct Score(double Unplaced, double Moment) + { + public bool Beats(Score other, double scale) => + Unplaced < other.Unplaced - 1e-9 * scale + || (Unplaced <= other.Unplaced + 1e-9 * scale && Moment < other.Moment - 1e-9 * System.Math.Max(1, System.Math.Abs(other.Moment))); + } + + /// + /// Looks for an order that fits every part in : from + /// , the best single-part move while one improves the decode, then the + /// best order so far with a few seeded swaps, until work is spent. + /// + private (List Parts, List Order)? Search(List seed, Box strip, PackAxis axis, double area, + Random random, long limit, CancellationToken token) + { + var decoder = new Decoder(types, (type, placed) => Place(type, placed, strip, axis, token), axis); + bool Fits(Score score) => score.Unplaced <= 1e-9 * area; + var order = seed.ToList(); + var bestOrder = order; + Score? bestScore = null; + var idle = 0; + while (true) + { + token.ThrowIfCancellationRequested(); + var known = decoder.Placements; + var score = decoder.Decode(order, area, out var placed); + while (!Fits(score) && counter.Value < limit) + { + var move = score; + List? moved = null; + List? movedParts = null; + for (var from = 0; from < order.Count && !Fits(move) && counter.Value < limit; from++) + for (var to = 0; to < order.Count && counter.Value < limit; to++) + { + // One step back is the same order as moving the neighbor one step forward. + if (to == from || to == from - 1) + continue; + token.ThrowIfCancellationRequested(); + var next = order.ToList(); + next.RemoveAt(from); + next.Insert(to, order[from]); + // Copies of one part trade places without changing the order. + if (next.SequenceEqual(order)) + continue; + var result = decoder.Decode(next, area, out var parts); + if (!result.Beats(move, area)) + continue; + move = result; + moved = next; + movedParts = parts; + if (Fits(move)) + break; + } + if (moved == null) + break; + order = moved; + score = move; + placed = movedParts!; + } + if (Fits(score)) + return (placed, order); + if (counter.Value >= limit) + return null; + // Orders already decoded cost no work, so the budget alone never ends a search that + // has run out of new ones: a few parts have only a few orders. Stop once the swaps + // keep coming back to placements already made. + idle = decoder.Placements == known ? idle + 1 : 0; + if (idle >= IdleRounds * order.Count) + return null; + if (bestScore is not { } incumbent || score.Beats(incumbent, area)) + { + bestScore = score; + bestOrder = order; + } + order = bestOrder.ToList(); + for (var kick = 0; kick < Kicks; kick++) + { + var a = random.Next(order.Count); + var b = random.Next(order.Count); + (order[a], order[b]) = (order[b], order[a]); + } + } + } + + /// + /// Places an order's parts one after another in a strip. A placement depends only on the + /// parts before it, so the decodes of one strip share a tree of order prefixes. + /// + private sealed class Decoder(IReadOnlyList types, Func, Placed?> place, PackAxis axis) + { + private sealed class Node + { + /// Null when the part fits nowhere after its prefix. + public Placed? Pose; + public Dictionary? Next; + } + + private readonly Node root = new(); + + /// Placements worked out so far; a decode that adds none met only known prefixes. + public int Placements { get; private set; } + + public Score Decode(IReadOnlyList order, double area, out List placed) + { + placed = new List(order.Count); + var node = root; + double placedArea = 0, moment = 0; + foreach (var type in order) + { + node.Next ??= new Dictionary(); + if (!node.Next.TryGetValue(type, out var next)) + { + node.Next[type] = next = new Node { Pose = place(types[type], placed) }; + Placements++; + } + node = next; + if (next.Pose is not { } pose) + continue; + placed.Add(pose); + var weight = types[type].Area; + placedArea += weight; + moment += weight * (axis == PackAxis.X ? (pose.Bottom + pose.Top) / 2 : (pose.Left + pose.Right) / 2); + } + return new Score(area - placedArea, moment); + } + } + + /// + /// The pose of that ends lowest across the strip, over all its + /// orientations: then nearest the strip's start, then starting lowest. Null when none fits. + /// + private Placed? Place(PartType type, IReadOnlyList placed, Box strip, PackAxis axis, CancellationToken token) + { + var poses = orientations(type).Where(o => o.Width <= strip.Length + 1e-9 && o.Height <= strip.Width + 1e-9).ToList(); + var clampCount = clamps?.Count ?? 0; + // A part too long for the strip still costs its lookup, so every new placement is counted. + counter.Add((long)System.Math.Max(1, poses.Count) * System.Math.Max(1, placed.Count + clampCount)); + if (poses.Count == 0) + return null; + var results = new (Placed? Pose, double Top, double Side, double Foot)[poses.Count]; + // Orientations are independent; combining them in catalog order keeps the choice deterministic. + Parallel.For(0, poses.Count, new ParallelOptions { CancellationToken = token }, index => + { + var o = poses[index]; + var minX = strip.Left - o.MinX; + var maxX = System.Math.Max(minX, strip.Right - o.MaxX); + var minY = strip.Bottom - o.MinY; + var maxY = System.Math.Max(minY, strip.Top - o.MaxY); + var free = new PathsD + { + new PathD + { + new(minX - FitSlack, minY - FitSlack), + new(maxX + FitSlack, minY - FitSlack), + new(maxX + FitSlack, maxY + FitSlack), + new(minX - FitSlack, maxY + FitSlack), + }, + }; + // One difference against every blocker at once: the same region as subtracting them + // in turn, at a fraction of the cost. + var blocked = new PathsD(); + void Block(Nfp nfp, double dx, double dy) + { + if (nfp.Bounds.right + dx < minX - FitSlack || nfp.Bounds.left + dx > maxX + FitSlack + || nfp.Bounds.bottom + dy < minY - FitSlack || nfp.Bounds.top + dy > maxY + FitSlack) + return; + blocked.AddRange(dx == 0 && dy == 0 ? nfp.Region : Clipper.TranslatePaths(nfp.Region, dx, dy)); + } + for (var i = 0; i < clampCount; i++) + Block(clamps!.Get(i, o), 0, 0); + foreach (var part in placed) + Block(nfps.Get(part.Orientation, o), part.X, part.Y); + if (blocked.Count > 0) + free = Clipper.Difference(free, blocked, FillRule.NonZero, NoFitCache.Precision); + + Placed? best = null; + double bestTop = double.PositiveInfinity, bestSide = double.PositiveInfinity, bestFoot = double.PositiveInfinity; + foreach (var path in free) + { + // A sliver thinner than the precision grid is no real room. + if (path.Count < 3) + continue; + foreach (var raw in path) + { + var x = System.Math.Clamp(raw.x, minX, maxX); + var y = System.Math.Clamp(raw.y, minY, maxY); + double top, side, foot; + if (axis == PackAxis.X) + { + top = y + o.MaxY; + side = x + o.MinX; + foot = y + o.MinY; + } + else + { + top = x + o.MaxX; + side = y + o.MinY; + foot = x + o.MinX; + } + if (best != null && !Lower(top, side, foot, bestTop, bestSide, bestFoot)) + continue; + best = new Placed(o, x, y); + bestTop = top; + bestSide = side; + bestFoot = foot; + } + } + results[index] = (best, bestTop, bestSide, bestFoot); + }); + + (Placed? Pose, double Top, double Side, double Foot) chosen = default; + foreach (var result in results) + if (result.Pose != null + && (chosen.Pose == null || Lower(result.Top, result.Side, result.Foot, chosen.Top, chosen.Side, chosen.Foot))) + chosen = result; + return chosen.Pose; + } + + private static bool Lower(double top, double side, double foot, double bestTop, double bestSide, double bestFoot) => + top < bestTop - Tie + || (top <= bestTop + Tie && (side < bestSide - Tie || (side <= bestSide + Tie && foot < bestFoot - Tie))); +} diff --git a/docs/nesting-engines.md b/docs/nesting-engines.md index d81afe36..0fe19909 100644 --- a/docs/nesting-engines.md +++ b/docs/nesting-engines.md @@ -14,7 +14,7 @@ in `OpenNest.Engine/NestingEngines//`, its tests in `OpenNest.Engine.Tests | Default | Any job; used when no engine is named | Runs Irregular, Rectangles and Circles, checks each layout with the layout check and keeps the best: valid first, then fewest unplaced parts, then lowest salvage-credited cost, then the largest compactness offcut; remaining ties keep the engine listed first here | | Rectangles | Plain and near-rectangular plates | Each part packed as the box of its material at its minimum-area rotation, using a maximal-rectangles free list; the sheet that finishes the job is also squeezed into a shorter or narrower bin; stock chosen sheet by sheet by salvage-credited look-ahead cost | | Circles | Round parts: blanks, washers, flanges, gears by their tip circle | Each part packed as its minimum enclosing circle at centers tangent to two of walls, placed discs and clamp keep-outs, with hexagonal and square lattice seeds; bids only when every part is round; stock chosen as Rectangles does, plus whole-job runs preferring each stock and a tail re-plan | -| Irregular | Irregular profiles | No-fit-polygon frontier packing with gap filling and best-fit pairs, six whole-job strategy variants (each also keeping a stock that finished the job when the per-sheet estimate passed it over for a plan that ended up dearer) and a tail re-plan, then grouped variants that pack like parts together, then a banded variant that packs each sheet in full-height strips, each group as its Lattice band or each strip from the largest parts down, then a sheet-reduction pass that packs edge parts first and turns a key part by its contacts; under a time limit it first reports a quick plan without Lattice blocks, and after its search keeps trying seeded variants until the limit | +| Irregular | Irregular profiles | No-fit-polygon frontier packing with gap filling and best-fit pairs, six whole-job strategy variants (each also keeping a stock that finished the job when the per-sheet estimate passed it over for a plan that ended up dearer) and a tail re-plan, then grouped variants that pack like parts together, then a banded variant that packs each sheet in full-height strips, each group as its Lattice band or each strip from the largest parts down, then a sheet-reduction pass that packs edge parts first and turns a key part by its contacts, then a squeeze that packs the last sheet again, largest part first, in ever shorter strips; under a time limit it first reports a quick plan without Lattice blocks, and after its search keeps trying seeded variants until the limit | | FlatBar | Flat bar: parts about as wide as the bar | Each stock read as a bar and cut in one row: the CutList cut-list packer and a best-fill search on part lengths less their self-nesting gain, then a slide-left pass that nests shaped ends and refills freed length; stock chosen bar by bar by whole-plan cost | | Lattice, Strip, Vertical Remnant, Horizontal Remnant | Many copies of a few parts | The fixed placement strategies behind interactive fill; Lattice is the multi-phase lattice fill (linear, pairs, rectangle best-fit, remainder; the pairs phase fills the strip its grid leaves with rows of pairs when they hold more than single parts, and also tiles herringbone pairs: the part turned so a hull edge lies along a sheet axis, nested into its own row, with every other row reversed), and the remnant strategies run it ranked to keep the largest drop. In whole jobs, all four place a plate with any fixed or bounded part rotation by the rotation-aware ordered placer instead | @@ -406,6 +406,39 @@ On a job of ten one-off brackets (four 112-inch tapered bars, four gussets, two 60 x 120 with a clamp rail, the bars stacked three to a sheet and the plan took three sheets; the pass packs two bars, two gussets and a plate per sheet, the middle bar turned 4.4 degrees, on two. +### Last-sheet squeeze + +Last of all, Irregular shortens the last sheet of a complete plan (`OrderedSqueeze`), when that +sheet is rectangular and holds 2 to 30 parts. The frontier rule lets the sheet state pick the next +part and sends small parts first, so a part as long as the layout can end up behind them and set +the sheet's length. A person lays the big parts along one edge, stacks the rest on them and drops +the small ones into the gaps. + +- The sheet's parts are packed again inside a strip ending 0.5% of the work area short of where + they reach now. They go in a given order, largest first to begin with, each at the lowest point + any of its orientations reaches across the strip, then nearest the strip's start. A part that + does not fit is left out. +- A local search over the order looks for one that leaves none out: the best move of one part to + another position, while a move improves the decode (less part area left out, then parts sitting + lower), then the best order so far with three swaps from a fixed seed. Decodes that share the + first parts of an order share those placements. +- A strip that takes every part is followed by a shorter one, starting from the order that + worked, until a strip's search spends its work (600,000 counted blockers for 11 parts or more, + less by the fourth power of the count below that) or the squeeze its total (3,000,000), or the + strip has less room than the parts' area. Orders already decoded cost no work, so a search also + ends after two rounds per part in a row that place nothing new: a few parts have few orders. +- A part that may turn freely is also offered every 30 degrees beside its catalog orientations; + a part with a rotation policy keeps the catalog's. Positions are vertices of exact free regions + (no-fit polygons, clamps, unchanged spacing), as everywhere in this engine. +- The strip runs along the stock's length, and across it too when the stock is taller than it is + long; a job's `OffcutCut` picks the one axis its offcut counts on. The squeezed sheet replaces + the plan's only when the plan then ranks better, so a result is never worse for it. + +On a job of eleven one-off parts (two 55-inch plates, two rings, four sectors, an arc and two +strips on 48 x 96 with a clamp rail) the search ended the layout at 75.2 with a 55-inch plate +behind the sectors; the squeeze stacks both plates along the bottom with everything else above +and beside them, ends at 62.1, and leaves a 33.4 x 47.5 drop rather than 20.3 x 47.5. + ## Flat bar FlatBar treats each stock's long work-area axis as the bar's length and lays parts in a single