Packing and cutting from Python, solved by PackingSolver: nest any shapes on sheets (Shapely polygons welcome), pack rectangles, cut plates with guillotine cuts, cut bars, pack boxes and load trucks. Describe the job, solve() it, read back where each of your things went. Each solve runs in a crash-proof child process.
pip install pyckingsolverIt brings upstream's own solver module, packingsolver (wheels for Windows x64 and x86, Linux x86_64 and
aarch64 with glibc 2.28 or newer, macOS arm64 and x86_64), pinned to one upstream commit. Python 3.13+.
import pyckingsolver as pk
from shapely.geometry import Point, box
plate = box(0, 0, 150, 100).difference(Point(75, 50).buffer(30)) # any Shapely polygon, holes kept
job = pk.Nesting(pk.Objective.BinPacking, spacing=2)
job.add_sheet(500, 300, count=None) # as many sheets as needed
job.add_part(plate, count=6, key="plate", rotations=[0, 90])
job.add_part(pk.shapes.circle(12), count=40, key="disc") # an exact circle
result = job.solve(time_limit=10, idle_limit=2) # stop 2 s after the last improvement
for sheet in result.sheets:
for part in sheet.parts:
print(part.key, part.x, part.y, part.angle, part.polygon) # the polygon as it lies on the sheetkey is anything you like (a name, a database row, an object); it comes back on every placement. Give
keys=[...] instead to tell the copies apart. A part that did not fit is in result.unplaced.
One vocabulary everywhere. 2D sizes are width (along x) and height (along y); 3D sizes are length
(x), width (y) and height (z); positions are x, y, z. Stock and the things placed take count
(None: unlimited stock), min_count, cost / value and key; every add_* returns an index. Every
choice is an enum member named as upstream names it (pk.Objective.Knapsack,
pk.Nesting.LeftoverMode.BottomLeft, pk.GuillotineCutting.CutType.Exact): no strings to misspell.
| Job | Stock | Placed | Result |
|---|---|---|---|
pk.Nesting |
add_sheet(width, height) or add_sheet(polygon) |
add_part(polygon) |
result.sheets[i].parts: key, x, y, angle, mirrored, pinned, polygon |
pk.RectanglePacking |
add_sheet(width, height) |
add_part(width, height) |
result.sheets[i].parts: key, x, y, width, height, rotated |
pk.GuillotineCutting |
add_plate(width, height, left_trim=...) |
add_part(width, height) |
result.plates[i].parts, and .cuts: the cut tree |
pk.BarCutting |
add_bar(length) |
add_piece(length) |
result.bars[i].pieces: key, x, length |
pk.BoxPacking |
add_container(length, width, height) |
add_box(length, width, height) |
result.containers[i].boxes: key, x, y, z, length, width, height, rotation |
pk.BoxStacking |
add_truck(length, width, height, axles=...) |
add_box(...) |
result.trucks[i].stacks[j].boxes, or .boxes |
Each entry of result.sheets (or plates, bars, ...) is one physical piece of stock, with .stock
holding its key.
# Pieces from bars
job = pk.BarCutting()
job.add_bar(6000, count=None, key="6 m")
job.add_piece(1500, count=7, key="post")
job.add_piece(2900, count=2, key="rail")
for bar in job.solve(time_limit=10).bars:
print(bar.stock, [(p.key, p.x, p.length) for p in bar.pieces])
# Guillotine cuts: 3 stages, a 4 mm kerf, a hard 10 mm trim on the left
job = pk.GuillotineCutting(stages=3, kerf=4)
job.add_plate(6000, 3210, count=10, left_trim=10, left_trim_type=pk.GuillotineCutting.TrimType.Hard)
job.add_part(1200, 800, count=20, key="shelf")
plate = job.solve(time_limit=10).plates[0]
print([(p.key, p.x, p.y, p.rotated) for p in plate.parts])
print([(c.kind, c.depth, c.x, c.y, c.width, c.height) for c in plate.cuts]) # plate, intermediate, part, waste
# Boxes in containers, turned about the vertical when it helps
job = pk.BoxPacking()
job.add_container(1200, 800, 1000, count=None)
job.add_box(400, 300, 250, count=20, key="carton", rotations=pk.BoxPacking.UPRIGHT) # list(pk.BoxPacking.Rotation): any way
for c in job.solve(time_limit=30).containers:
print([(b.key, b.x, b.y, b.z, b.rotation) for b in c.boxes])
# A truck in stacks
job = pk.BoxStacking()
job.add_truck(13600, 2450, 2700, count=3)
job.add_box(1200, 800, 1000, count=30, key="pallet", stack_group=0, max_stack=2)
for truck in job.solve(time_limit=30).trucks:
print([(s.x, s.y, [b.key for b in s.boxes]) for s in truck.stacks])A job's first argument is a pk.Objective member, upstream's names (job.objectives lists the ones it solves):
pk.Objective. |
|
|---|---|
BinPacking (the default) |
place everything on the fewest sheets, plates, bars, containers or trucks |
BinPackingWithLeftovers |
the same, the last one's leftover kept in one piece (leftover=Job.LeftoverMode.BottomLeft, ...) |
VariableSizedBinPacking |
place everything on the cheapest mix of stock sizes (cost defaults to the size) |
VariableSizedBinPackingWithLeftovers |
the same, less a refund for each leftover |
Knapsack |
fill the stock you have with the most value (defaults to the size); some parts may stay out |
OpenDimensionX, OpenDimensionY |
one side of the stock is open: use as little of it as possible (OpenDimensionZ for BoxPacking) |
OpenDimensionXY |
Nesting: both sides open, the smallest rectangle |
Feasibility |
only answer: does everything fit? |
BinPackingCuttingCost |
GuillotineCutting: the fewest plates, then the cheapest cuts (cut_cost(stage, fixed=, per_length=)) |
result = job.solve(
time_limit=60, # seconds
idle_limit=5, # stop 5 s after the last improvement
first_solution_limit=10, # give up if nothing is found by then
on_progress=show, # called with each better Result
cancel=stop_event, # anything with .is_set(): raises pk.Cancelled
pause=pause_event, # while set the solve is frozen, then goes on where it stopped
use_tree_search=True, # any upstream tuning option, by its upstream name: see Job.Options
)result is false when nothing was found. It carries cost, value, waste_percentage, unplaced,
proven_optimal, time, metrics (every upstream number: the bounds, and under "Solution" the
waste, leftover values, ...), and save(path) writes upstream's certificate. An instance upstream
rejects, or a solver crash, raises RuntimeError with upstream's message.
A pause counts in no limit and can last up to a day in all; a threading.Event, set and cleared from
another thread, does it (solve() blocks). Upstream's tuning options are listed on each job's
Options (pk.Nesting.Options, ...); you rarely need them.
| Defects | Nesting.add_defect(sheet, polygon, gap=10); add_defect(stock, x, y, width, height) on rectangles, plates and truck floors. A hole in a Nesting sheet polygon becomes a defect. |
| Pins | Nesting.pin(sheet, polygon, at=(x, y), angle=0): fixed before the search, back with pinned=True (upstream takes pins only with Knapsack on a sheet of count=1) |
| Edge gap | Nesting.add_sheet(..., edge_gap=5) |
| Rotations | Nesting: rotations=[0, 90], [(0, 360)] for any angle, mirror=True; rectangles: rotate=False; BoxPacking: rotations=[BoxPacking.Rotation.XYZ, ...]; BoxStacking: rotate=True |
| Leftovers | leftover=Job.LeftoverMode.X (each job has its own), leftover_value=pk.LeftoverValueType.Depth, leftover_on_every_<stock>=True |
| Limits | job.add_limit(stock, capacity, use={part_index: amount}): e.g. machine minutes per sheet |
| Stop early | stop_at_value=, give_up_below_value= (Knapsack); BarCutting(stop_at_bins=, stop_at_cost=) |
| Kinds | add_part(..., kind=1) with add_sheet(..., accepts=[1, 2]) (rectangles, bars) |
| Order | BarCutting.use_up_first(first, then) (solved by upstream's MILP); guillotine stack=; unloading=Job.UnloadingConstraint.IncreasingX with group= |
| Weights | weight=, max_weight=, max_weight_above=, weight_tolerance=, check_weight(group); BoxPacking(stable=True) |
| Stacks | BoxStacking.add_box(stack_group=, max_stack=, nesting_height=), add_truck(axles={...}) |
| Guillotine | GuillotineCutting(roadef2018=, preset="3NHO", stages= (math.inf: no limit), cut_type=CutType.X, first_cut=CutOrientation.X, kerf=, min_waste=, *_distance_*_cuts=, max_number_*_cuts=), crop_plate |
| Files | Job.load(path): upstream's instance JSON; load_csv(items=, bins=, parameters=) (all but Nesting; defects= too on rectangles, plates and trucks) |
Box and bar sizes are integers (upstream's type): scale to a finer unit. Nesting takes any float.
examples/example.py runs every Nesting scenario below and writes these images:
uv run python examples/example.py [scenario ...].
1.0 replaces the upstream-style builders with the six jobs.
| 0.x | 1.0 |
|---|---|
ps.InstanceBuilder() + set_objective(ps.Objective.BinPacking) |
pk.Nesting(pk.Objective.BinPacking) |
ps.LeftoverMode.BottomLeft, ps.box.Rotation.XYZ, ... |
pk.Nesting.LeftoverMode.BottomLeft, pk.BoxPacking.Rotation.XYZ, ... (each job carries its enums) |
ps.box / ps.onedimensional / ps.rectangle / ps.rectangleguillotine / ps.boxstacks |
pk.BoxPacking / pk.BarCutting / pk.RectanglePacking / pk.GuillotineCutting / pk.BoxStacking |
add_bin_type(shape, copies=-1) |
add_sheet(shape, count=None) (add_plate, add_bar, add_container, add_truck) |
add_item_type(shape, copies=, profit=, allowed_rotations=[(0, 0, False)]) |
add_part(shape, count=, value=, rotations=[0], key=) (add_piece, add_box) |
set_item_item_minimum_spacing(s) |
Nesting(spacing=s) |
add_defect + set_item_defect_minimum_spacing |
add_defect(sheet, shape, gap=) |
add_fixed_item(bin, item_type, xy) |
pin(sheet, shape, at=xy) |
add_bin_type_resource + add_resource_consumption |
add_limit(stock, capacity, use=) |
set_knapsack_goal / set_knapsack_cutoff |
stop_at_value= / give_up_below_value= |
ps.optimize(ib.build(), time_limit=, stall_timeout=, first_solution_timeout=, new_solution_callback=) |
job.solve(time_limit=, idle_limit=, first_solution_limit=, on_progress=) |
output.solution.bin(i).items, item_type_id, bl_corner |
result.sheets[i].parts, key, x / y |
solution.shape_scaled(b, i) + to_shapely |
part.polygon |
number_of_different_bins() == 0 |
not result |
ps.OptimizeCancelled |
pk.Cancelled |
ps.build_rectangle, build_circle, build_shape, ... |
pk.shapes.rectangle, circle, polygon, ... |
Measured on the solver:
- A pinned part's holes can stay empty: the shape simplification shrinks them below every candidate part, and the first beam search then stops (details in AGENTS.md).
Knapsackcan settle on a wasteful arrangement: tree search packs along a skyline, so a gap closed by two later parts is never refilled.BinPackingdoes not tidy the last sheet: every layout with the same number of sheets scores the same, so the leftovers can end up spread over two sheets.BinPackingWithLeftoversfills the others first and gathers the rest in one corner. More time does not change the count: 30 parts needing 1.76 sheets of area gave 3 sheets after 2 s and after 60 s alike.- A limit on one part type leaves free space unused: in the
knapsackscenario, capping the discs at 4 withadd_limitgives value 48;count=4instead gives 64. A limit every part uses behaves. - Holes inside parts: the auto-selected search for
Knapsackleft every bolt hole of thelaser_sheetscenario empty;use_tree_search=Trueput 25 to 28 discs in them (two runs). - Not reachable: irregular quality rules (upstream has neither a Python binding nor a JSON key) and one-dimensional fixed items (no upstream builder method). Upstream's automatic box profits are left out: at the pinned commit they come out 0.
The solver is the packingsolver pin in pyproject.toml: upstream
publishes each master commit as 0.1.<commits on master>. extern/packingsolver is upstream's checkout,
for reading its sources. Checks: uv run python test/test_pyckingsolver.py. History in
CHANGELOG.md.
AGPL-3.0-or-later, see LICENSE.
Built on PackingSolver by Florian Fontan (MIT), installed as
its own packingsolver package. Its Python module is built without Clp (EPL-2.0): HiGHS, Boost,
nlohmann/json and every fontanf dependency are MIT or BSL-1.0.









