feat(engine): execute inventory-bounded multi-plate jobs
This commit is contained in:
@@ -0,0 +1,182 @@
|
||||
using OpenNest.Geometry;
|
||||
|
||||
namespace OpenNest.Engine.Tests.Jobs;
|
||||
|
||||
public class FiniteStockJobTests
|
||||
{
|
||||
internal static NestJob Job(int? stock = 3, NestJobOptions? options = null) => new(
|
||||
new[] { new NestJobPart("p", PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle()), 3) },
|
||||
new[] { new NestPlateStock("s", new Size(100, 200), stock) }, options);
|
||||
|
||||
internal sealed class Nester(Func<PlatePlacementRequest, PlateCandidate> place) : IPlateNester
|
||||
{
|
||||
public int Calls { get; private set; }
|
||||
public PlateCandidate Place(PlatePlacementRequest request, IProgress<NestJobProgress>? progress = null,
|
||||
CancellationToken token = default) { Calls++; return place(request); }
|
||||
}
|
||||
|
||||
internal static PlateCandidate One(PlatePlacementRequest request) => new(new[]
|
||||
{ new NestJobPlacement(request.Parts[0].Id, 99, 1, 2, 0) });
|
||||
|
||||
[Theory]
|
||||
[InlineData(3, 3, 0, NestJobStatus.Complete, NestJobStopReason.Completed)]
|
||||
[InlineData(2, 2, 1, NestJobStatus.Incomplete, NestJobStopReason.StockExhausted)]
|
||||
[InlineData(0, 0, 3, NestJobStatus.Incomplete, NestJobStopReason.StockExhausted)]
|
||||
public void DemandAndPhysicalStockAreAccountedFromPlacements(int stock, int placed, int left,
|
||||
NestJobStatus status, NestJobStopReason reason)
|
||||
{
|
||||
var requests = new List<int>();
|
||||
var nester = new Nester(r => { requests.Add(r.Parts[0].Quantity); return One(r); });
|
||||
var job = Job(stock);
|
||||
var result = new NestJobRunner(_ => nester).Solve(job);
|
||||
Assert.Equal(status, result.Status);
|
||||
Assert.Equal(reason, result.StopReason);
|
||||
Assert.Equal(placed, result.Plates.Count);
|
||||
Assert.All(result.Plates, p => Assert.Single(p.Placements));
|
||||
Assert.Equal(Enumerable.Range(0, placed), result.Plates.SelectMany(p => p.Placements).Select(p => p.InstanceIndex));
|
||||
Assert.Equal(Enumerable.Range(0, placed).Select(i => 3 - i), requests);
|
||||
Assert.Equal(new PartFulfillment("p", 3, placed, left), Assert.Single(result.Fulfillment));
|
||||
Assert.Equal(new StockUsage("s", placed, stock - placed), Assert.Single(result.StockUsage));
|
||||
Assert.Equal(3, job.Parts[0].Quantity);
|
||||
Assert.Equal(stock, job.Plates[0].Quantity);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData(3)]
|
||||
public void NoPlacementStopsWithoutConsumingStock(int? stock)
|
||||
{
|
||||
var nester = new Nester(_ => new PlateCandidate(Array.Empty<NestJobPlacement>()));
|
||||
var result = new NestJobRunner(_ => nester).Solve(Job(stock));
|
||||
Assert.Equal(1, nester.Calls);
|
||||
Assert.Empty(result.Plates);
|
||||
Assert.Equal(NestJobStatus.Incomplete, result.Status);
|
||||
Assert.Equal(NestJobStopReason.NoPlacementFound, result.StopReason);
|
||||
Assert.Equal(new StockUsage("s", 0, stock), Assert.Single(result.StockUsage));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PlateLimitStopsUnlimitedStock()
|
||||
{
|
||||
var result = new NestJobRunner(_ => new Nester(One)).Solve(Job(null, new NestJobOptions(maxPlates: 2)));
|
||||
Assert.Equal(2, result.Plates.Count);
|
||||
Assert.Equal(NestJobStopReason.PlateLimitReached, result.StopReason);
|
||||
Assert.Equal(new StockUsage("s", 2, null), Assert.Single(result.StockUsage));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CancellationImmediatelyAfterEngineReturnThrowsWithoutCommit()
|
||||
{
|
||||
using var cts = new CancellationTokenSource();
|
||||
var commits = new List<NestJobProgress>();
|
||||
var nester = new Nester(r => { cts.Cancel(); return One(r); });
|
||||
Assert.Throws<OperationCanceledException>(() => new NestJobRunner(_ => nester)
|
||||
.Solve(Job(), new InlineProgress(commits.Add), cts.Token));
|
||||
Assert.DoesNotContain(commits, p => p.Stage == NestJobStage.PlateCommitted);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InitialCancellationSkipsEngine()
|
||||
{
|
||||
using var cts = new CancellationTokenSource();
|
||||
cts.Cancel();
|
||||
Assert.Throws<OperationCanceledException>(() => new NestJobRunner(_ => throw new Exception("called"))
|
||||
.Solve(Job(), token: cts.Token));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("unknown", 0, 0, 0, 1)]
|
||||
[InlineData("p", double.NaN, 0, 0, 1)]
|
||||
[InlineData("p", 0, double.PositiveInfinity, 0, 1)]
|
||||
[InlineData("p", 0, 0, double.NaN, 1)]
|
||||
[InlineData("p", 0, 0, 0, 4)]
|
||||
public void InvalidCandidateThrows(string id, double x, double y, double rotation, int count)
|
||||
{
|
||||
var nester = new Nester(_ => new PlateCandidate(Enumerable.Range(0, count)
|
||||
.Select(i => new NestJobPlacement(id, i, x, y, rotation))));
|
||||
Assert.Throws<InvalidOperationException>(() => new NestJobRunner(_ => nester).Solve(Job()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NullCandidateAndUnknownStrategyAreExplicitErrors()
|
||||
{
|
||||
Assert.Throws<InvalidOperationException>(() => new NestJobRunner(_ => new Nester(_ => null!)).Solve(Job()));
|
||||
Assert.Throws<NotSupportedException>(() => new NestJobRunner(_ => null!).Solve(Job(options: new NestJobOptions("missing"))));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MixedStockIsNotSilentlyIgnored()
|
||||
{
|
||||
var job = Job();
|
||||
var mixed = new NestJob(job.Parts, job.Plates.Concat(new[] { new NestPlateStock("other", new Size(10, 20), 2) }));
|
||||
Assert.Throws<NotSupportedException>(() => new NestJobRunner(_ => new Nester(One)).Solve(mixed));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(0, 20, 0, 1)]
|
||||
[InlineData(10, double.NaN, 0, 1)]
|
||||
[InlineData(10, 20, -1, 1)]
|
||||
[InlineData(10, 20, double.PositiveInfinity, 1)]
|
||||
[InlineData(10, 20, 0, 5)]
|
||||
public void InvalidStockSettingsRejected(double width, double length, double spacing, int quadrant)
|
||||
{
|
||||
var job = new NestJob(Job().Parts, new[] { new NestPlateStock("s", new Size(width, length), 1, spacing, quadrant: quadrant) });
|
||||
Assert.Throws<ArgumentException>(() => new NestJobRunner(_ => new Nester(One)).Solve(job));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidEdgesAndGeometryRejected()
|
||||
{
|
||||
var runner = new NestJobRunner(_ => new Nester(One));
|
||||
foreach (var edges in new[] { new Spacing(-1, 0, 0, 0), new Spacing(0, double.NaN, 0, 0), new Spacing(1000, 1000, 1000, 1000) })
|
||||
Assert.Throws<ArgumentException>(() => runner.Solve(new NestJob(Job().Parts,
|
||||
new[] { new NestPlateStock("s", new Size(100, 200), edgeSpacing: edges) })));
|
||||
var program = TestDrawingFactory.Rectangle();
|
||||
program.LineTo(double.NaN, 0);
|
||||
Assert.Throws<ArgumentException>(() => runner.Solve(new NestJob(new[]
|
||||
{ new NestJobPart("p", PartGeometrySnapshot.FromProgram(program), 1) }, Job().Plates)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void InvalidContractInputsAreRejected()
|
||||
{
|
||||
var job = Job();
|
||||
Assert.Throws<ArgumentNullException>(() => new NestJobRunner(_ => new Nester(One)).Solve(null!));
|
||||
Assert.Throws<ArgumentException>(() => new NestJob(new NestJobPart[] { null! }, job.Plates));
|
||||
Assert.Throws<ArgumentException>(() => new NestJob(job.Parts.Concat(job.Parts), job.Plates));
|
||||
Assert.Throws<ArgumentException>(() => new NestJob(job.Parts, job.Plates.Concat(job.Plates)));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new NestJobPart("p", job.Parts[0].Geometry, 0));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new NestPlateStock("s", new Size(1, 1), -1));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new NestJobOptions(maxPlates: 0));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RunnerFactoriesAreInstanceScopedAndReceiveExactStrategyKeys()
|
||||
{
|
||||
var keys = new List<string>();
|
||||
var first = new NestJobRunner(key => { keys.Add(key); return new Nester(One); });
|
||||
var second = new NestJobRunner(key => { keys.Add(key); return new Nester(_ => new PlateCandidate(Array.Empty<NestJobPlacement>())); });
|
||||
Assert.Equal(NestJobStatus.Complete, first.Solve(Job(options: new NestJobOptions("custom-A"))).Status);
|
||||
Assert.Equal(NestJobStopReason.NoPlacementFound, second.Solve(Job(options: new NestJobOptions("custom-B"))).StopReason);
|
||||
Assert.Equal(NestJobStatus.Complete, first.Solve(Job(options: new NestJobOptions("custom-A"))).Status);
|
||||
Assert.Equal(new[] { "custom-A", "custom-B", "custom-A" }, keys);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CancellationAfterAnEarlierCommitStillThrowsRatherThanReturningPartialResult()
|
||||
{
|
||||
using var cts = new CancellationTokenSource();
|
||||
var calls = 0;
|
||||
var commits = new List<NestJobProgress>();
|
||||
var nester = new Nester(r => { if (++calls == 2) cts.Cancel(); return One(r); });
|
||||
Assert.Throws<OperationCanceledException>(() => new NestJobRunner(_ => nester)
|
||||
.Solve(Job(), new InlineProgress(commits.Add), cts.Token));
|
||||
Assert.Equal(1, Assert.Single(commits.Where(p => p.Stage == NestJobStage.PlateCommitted)).CommittedParts);
|
||||
Assert.Equal(2, calls);
|
||||
}
|
||||
|
||||
private sealed class InlineProgress(Action<NestJobProgress> report) : IProgress<NestJobProgress>
|
||||
{
|
||||
public void Report(NestJobProgress value) => report(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
using OpenNest.CNC;
|
||||
using OpenNest.Geometry;
|
||||
|
||||
namespace OpenNest.Engine.Tests.Jobs;
|
||||
|
||||
public class JobAdapterTests
|
||||
{
|
||||
[Fact]
|
||||
public void LegacyMutationsCannotDoubleSubtractOrReachCallerObjects()
|
||||
{
|
||||
var drawing = new Drawing("same name", TestDrawingFactory.Rectangle());
|
||||
drawing.Quantity.Required = 9;
|
||||
var item = new NestItem { Drawing = drawing, Quantity = 3, Priority = 7, StepAngle = 0 };
|
||||
var sourcePlate = new Plate(100, 200) { Quantity = 3, PartSpacing = 2 };
|
||||
var job = new NestJob(new[] { DrawingJobMapper.FromItem("requirement", item) },
|
||||
new[] { DrawingJobMapper.FromPlate("stock", sourcePlate, 3) });
|
||||
var quantities = new List<int>();
|
||||
var adapter = new LegacyPlateNesterAdapter(p => new MutatingEngine(p, items =>
|
||||
{
|
||||
var privateItem = Assert.Single(items);
|
||||
quantities.Add(privateItem.Quantity);
|
||||
Assert.NotSame(drawing, privateItem.Drawing);
|
||||
Assert.Equal(0, privateItem.StepAngle);
|
||||
Assert.Equal(7, privateItem.Priority);
|
||||
var part = new Part(privateItem.Drawing);
|
||||
privateItem.Quantity = 0;
|
||||
privateItem.Drawing.Quantity.Required = 0;
|
||||
return new List<Part> { part };
|
||||
}));
|
||||
var result = new NestJobRunner(_ => adapter).Solve(job);
|
||||
var materialized = NestResultMaterializer.Materialize(job, result);
|
||||
Assert.Equal(new[] { 3, 2, 1 }, quantities);
|
||||
Assert.Equal(NestJobStatus.Complete, result.Status);
|
||||
Assert.Equal(3, materialized.Nest.Plates.Count);
|
||||
Assert.All(materialized.Nest.Plates, p => { Assert.Equal(1, p.Quantity); Assert.Single(p.Parts); });
|
||||
var outputDrawing = materialized.DrawingsByPartId["requirement"];
|
||||
Assert.Equal(3, outputDrawing.Quantity.Required);
|
||||
Assert.Equal(3, outputDrawing.Quantity.Nested);
|
||||
Assert.All(materialized.Nest.Plates, p => Assert.Same(outputDrawing, p.Parts[0].BaseDrawing));
|
||||
Assert.NotSame(drawing, outputDrawing);
|
||||
Assert.Equal(9, drawing.Quantity.Required);
|
||||
Assert.Equal(0, drawing.Quantity.Nested);
|
||||
Assert.Equal(3, item.Quantity);
|
||||
Assert.Equal(3, sourcePlate.Quantity);
|
||||
Assert.Empty(sourcePlate.Parts);
|
||||
Assert.Equal(2, sourcePlate.PartSpacing);
|
||||
Assert.Equal(PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle()).Motions,
|
||||
PartGeometrySnapshot.FromProgram(drawing.Program).Motions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReferenceIdentityNotNamesControlsLegacyPlacements()
|
||||
{
|
||||
var drawing = new Drawing("duplicate", TestDrawingFactory.Rectangle());
|
||||
var job = new NestJob(new[] { DrawingJobMapper.FromDrawing("a", drawing, 1),
|
||||
DrawingJobMapper.FromDrawing("b", drawing, 1) }, FiniteStockJobTests.Job(1).Plates);
|
||||
var adapter = new LegacyPlateNesterAdapter(p => new MutatingEngine(p, items =>
|
||||
{
|
||||
Assert.NotSame(items[0].Drawing, items[1].Drawing);
|
||||
foreach (var item in items) item.Drawing.Name = "identical";
|
||||
return items.Select(i => new Part(i.Drawing)).ToList();
|
||||
}));
|
||||
var result = new NestJobRunner(_ => adapter).Solve(job);
|
||||
Assert.Equal(new[] { "a", "b" }, result.Plates[0].Placements.Select(p => p.PartId));
|
||||
var output = NestResultMaterializer.Materialize(job, result);
|
||||
Assert.NotSame(output.DrawingsByPartId["a"], output.DrawingsByPartId["b"]);
|
||||
Assert.All(output.DrawingsByPartId.Values, d => Assert.Equal(1, d.Quantity.Nested));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnknownPrivateDrawingIsRejectedEvenWithMatchingName()
|
||||
{
|
||||
var adapter = new LegacyPlateNesterAdapter(p => new MutatingEngine(p, items => new List<Part>
|
||||
{ new(new Drawing(items[0].Drawing.Name, TestDrawingFactory.Rectangle())) }));
|
||||
Assert.Throws<InvalidOperationException>(() => new NestJobRunner(_ => adapter).Solve(FiniteStockJobTests.Job()));
|
||||
Assert.Throws<NotSupportedException>(() => LegacyPlateNesterAdapter.Create("not registered"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ExactGeometryRoundTripsIncludingOriginArcHoleAndMode()
|
||||
{
|
||||
var program = TestDrawingFactory.Rectangle();
|
||||
program.Offset(-17.123456789, 5.25);
|
||||
program.MoveTo(-14, 9);
|
||||
program.ArcTo(-14, 9, -13, 9, RotationType.CW);
|
||||
((ArcMove)program.Codes[^1]).Layer = LayerType.Cut;
|
||||
var drawing = new Drawing("shape", program);
|
||||
var part = DrawingJobMapper.FromDrawing("p", drawing, 1);
|
||||
var snapshot = part.Geometry.Motions.ToArray();
|
||||
((Motion)program.Codes[1]).EndPoint = new Vector(999, 888);
|
||||
Assert.Equal(snapshot, part.Geometry.Motions);
|
||||
var roundTrip = DrawingJobMapper.ToProgram(part.Geometry);
|
||||
Assert.Equal(snapshot, PartGeometrySnapshot.FromProgram(roundTrip).Motions);
|
||||
Assert.Equal(program.Mode, roundTrip.Mode);
|
||||
roundTrip.Codes.Clear();
|
||||
Assert.Equal(snapshot, part.Geometry.Motions);
|
||||
var incremental = new Program(Mode.Incremental);
|
||||
incremental.MoveTo(5, -3);
|
||||
incremental.LineTo(7, 4);
|
||||
var incrementalSnapshot = PartGeometrySnapshot.FromProgram(incremental);
|
||||
Assert.Equal(Mode.Incremental, DrawingJobMapper.ToProgram(incrementalSnapshot).Mode);
|
||||
Assert.Equal(incrementalSnapshot.Motions,
|
||||
PartGeometrySnapshot.FromProgram(DrawingJobMapper.ToProgram(incrementalSnapshot)).Motions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RealDefaultEngineRunsFromDrawingThroughMaterialization()
|
||||
{
|
||||
var drawing = new Drawing("generated asymmetric rectangle", TestDrawingFactory.Rectangle(13, 7));
|
||||
drawing.Quantity.Required = 1;
|
||||
var job = new NestJob(new[] { DrawingJobMapper.FromDrawing("rectangle", drawing, 1) },
|
||||
new[] { new NestPlateStock("sheet", new Size(40, 60), 1, 1, new Spacing(2, 2, 2, 2)) });
|
||||
var result = new NestJobRunner(LegacyPlateNesterAdapter.Create).Solve(job);
|
||||
Assert.Equal(NestJobStatus.Complete, result.Status);
|
||||
Assert.Equal(new StockUsage("sheet", 1, 0), Assert.Single(result.StockUsage));
|
||||
var pose = Assert.Single(Assert.Single(result.Plates).Placements);
|
||||
var output = NestResultMaterializer.Materialize(job, result);
|
||||
var physicalPlate = Assert.Single(output.Nest.Plates);
|
||||
var placed = Assert.Single(physicalPlate.Parts);
|
||||
Assert.Equal(1, physicalPlate.Quantity);
|
||||
Assert.Same(output.DrawingsByPartId["rectangle"], placed.BaseDrawing);
|
||||
Assert.Equal(pose.X, placed.Location.X);
|
||||
Assert.Equal(pose.Y, placed.Location.Y);
|
||||
Assert.Equal(pose.Rotation, placed.Rotation, 10);
|
||||
Assert.Equal(1, placed.BaseDrawing.Quantity.Nested);
|
||||
Assert.Equal(0, drawing.Quantity.Nested);
|
||||
Assert.Equal(1, drawing.Quantity.Required);
|
||||
var bounds = placed.BoundingBox;
|
||||
var work = physicalPlate.WorkArea();
|
||||
Assert.True(bounds.Left >= work.Left - 1e-6 && bounds.Bottom >= work.Bottom - 1e-6);
|
||||
Assert.True(bounds.Right <= work.Right + 1e-6 && bounds.Top <= work.Top + 1e-6);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MaterializationRotatesAboutSnapshotOriginThenTranslates()
|
||||
{
|
||||
var program = TestDrawingFactory.Rectangle();
|
||||
program.Offset(-5, 3);
|
||||
var job = new NestJob(new[] { new NestJobPart("p", PartGeometrySnapshot.FromProgram(program), 1) },
|
||||
FiniteStockJobTests.Job(1).Plates);
|
||||
var result = new NestJobRunner(_ => new FiniteStockJobTests.Nester(_ => new PlateCandidate(new[]
|
||||
{ new NestJobPlacement("p", 0, 23, 31, 0.7) }))).Solve(job);
|
||||
var output = NestResultMaterializer.Materialize(job, result);
|
||||
var part = output.Nest.Plates[0].Parts[0];
|
||||
var expected = new Vector(-5, 3).Rotate(0.7);
|
||||
Assert.Equal(expected.X, ((Motion)part.Program.Codes[0]).EndPoint.X, 10);
|
||||
Assert.Equal(expected.Y, ((Motion)part.Program.Codes[0]).EndPoint.Y, 10);
|
||||
Assert.Equal(new Vector(23, 31), part.Location);
|
||||
}
|
||||
|
||||
private sealed class MutatingEngine(Plate plate, Func<List<NestItem>, List<Part>> nest) : NestEngineBase(plate)
|
||||
{
|
||||
public override string Name => "test";
|
||||
public override string Description => "mutates private demand";
|
||||
public override List<Part> Nest(List<NestItem> items, IProgress<NestProgress> progress, CancellationToken token)
|
||||
=> nest(items);
|
||||
}
|
||||
}
|
||||
@@ -41,12 +41,15 @@ public class NestJobRunnerTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NonemptyJobIsExplicitlyUnsupportedInContractSlice()
|
||||
public void EmptyStockReturnsIncomplete()
|
||||
{
|
||||
var part = new NestJobPart("part", PartGeometrySnapshot.FromProgram(TestDrawingFactory.Rectangle()), 1);
|
||||
var job = new NestJob(new[] { part }, Array.Empty<NestPlateStock>());
|
||||
var runner = new NestJobRunner(_ => new FakePlateNester());
|
||||
Assert.Throws<NotSupportedException>(() => runner.Solve(job));
|
||||
var result = runner.Solve(job);
|
||||
Assert.Equal(NestJobStatus.Incomplete, result.Status);
|
||||
Assert.Equal(NestJobStopReason.StockExhausted, result.StopReason);
|
||||
Assert.Equal(1, Assert.Single(result.Fulfillment).Unplaced);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
Reference in New Issue
Block a user