Skip to main content

U-Nesting

A high-performance 2D/3D spatial optimization engine for nesting and bin packing problems.

PyPI version License: MIT

Features

  • 2D Nesting: Optimal placement of irregular polygons on sheets
  • 3D Bin Packing: Efficient box placement in containers
  • Multiple Algorithms: BLF, NFP-guided, Genetic Algorithm, BRKGA, Simulated Annealing
  • High Performance: Written in Rust with Python bindings
  • Type Hints: Full type annotation support

Installation

pip install u-nesting

Quick Start

2D Nesting

import u_nesting

# Define polygons to nest
geometries = [
    {
        "id": "part1",
        "polygon": [[0, 0], [100, 0], [100, 50], [0, 50]],
        "quantity": 5,
        "rotations": [0, 90, 180, 270]
    },
    {
        "id": "triangle",
        "polygon": [[0, 0], [80, 0], [40, 60]],
        "quantity": 3
    }
]

# Define sheet boundary
boundary = {"width": 500, "height": 300}

# Configure solver
config = {
    "strategy": "nfp",      # Options: blf, nfp, ga, brkga, sa, gdrr, alns
    "spacing": 2.0,         # Gap between parts
    "time_limit_ms": 30000  # 30 second timeout
}

# Solve
result = u_nesting.solve_2d(geometries, boundary, config)

print(f"Utilization: {result['utilization']:.1%}")
print(f"Placed: {len(result['placements'])} items")
for p in result['placements']:
    print(f"  {p['id']}[{p['instance']}]: ({p['x']:.1f}, {p['y']:.1f})")

3D Bin Packing

import u_nesting

# Define boxes to pack
geometries = [
    {
        "id": "small",
        "dimensions": [20, 20, 20],
        "quantity": 10
    },
    {
        "id": "large",
        "dimensions": [40, 30, 25],
        "quantity": 5,
        "mass": 2.5  # Optional weight
    }
]

# Define container
boundary = {
    "dimensions": [200, 150, 100],
    "max_mass": 50.0,    # Optional mass limit
    "gravity": True,     # Stack from bottom
    "stability": True    # Require stable placement
}

# Configure solver
config = {
    "strategy": "ep",       # Extreme Point heuristic
    "time_limit_ms": 10000
}

# Solve
result = u_nesting.solve_3d(geometries, boundary, config)

print(f"Utilization: {result['utilization']:.1%}")
print(f"Containers used: {result['bins_used']}")

API Reference

solve_2d(geometries, boundary, config=None) -> dict

Solve a 2D nesting problem.

Parameters:

Nothing a request asks for is raised as an exception: every refusal comes back in the result dict, with success False, a stable code and the values behind it in details -- the same codes and paths the C and WebAssembly bindings give. Branch on code, not on the error text.

  • Keys are read strictly: an unrecognized key in geometries, boundary or config, or a value of the wrong type -- a count given as a fraction (2.5) included -- is malformed_input with details parameter the path of the field (config.stratgy, geometries[0].quantity). A typo can never silently fall back to a default.
  • A number that is not finite (float("nan"), math.inf) is value_not_finite: parameter is the path of the value (config.spacing), or of the list it is in with its position as index (geometries[0].polygon[2], index 1 for the y coordinate), and id names the geometry. A value JSON cannot hold (a set, a non-string key) is malformed_input.
  • A value outside its range (a negative one included) is parameter_out_of_range: a geometry's quantity below 1 has parameter geometries[i].quantity and the geometry's id; a config setting (population_size below 2, seed below 0, ...) has parameter config.population_size; a boundary side, dimension or max_mass of 0 or below names it (boundary.width, boundary.dimensions[i], boundary.max_mass, with exclusive_min 0).
  • An empty geometries list is empty_input (parameter geometries); a strategy the dimension does not offer is invalid_option (parameter config.strategy); a boundary given as both a rectangle and a polygon, or half of a rectangle, is invalid_boundary.
  • geometries: List of geometry definitions
    • id (str): Unique identifier
    • polygon (list): Vertices as [[x, y], ...]
    • quantity (int): Number of copies (default: 1)
    • rotations (list): Allowed rotation angles in degrees — at least one; omit it for a fixed orientation (an empty list is refused)
    • allow_flip (bool): Allow horizontal flip
    • allow_part_in_part (bool): Let other pieces be placed in this piece's holes (default: false). Read by nfp, ga, brkga, sa, gdrr and alns; any other strategy refuses a request that sets it
    • holes (list): Interior holes as list of polygons
  • boundary: Sheet definition
    • width, height (float): Rectangle dimensions, OR
    • polygon (list): Custom boundary shape
  • config: Solver configuration (optional)
    • strategy (str): "blf", "nfp", "ga", "brkga", "sa", "gdrr", "alns"
    • spacing (float): Gap between geometries
    • margin (float): Gap from boundary
    • time_limit_ms (int): Timeout in milliseconds, at least 0 (0 = no limit; default 30000)
    • target_utilization (float): ga, brkga, sa stop once every part is placed at this utilization or more, in [0, 1]
    • population_size (int): GA/BRKGA population, at least 2, run as given. Omitted, each search uses the size it is tuned for: 30 in 2D
    • max_generations (int): GA/BRKGA generation budget, at least 0, run as given. Omitted, 50 in 2D
    • max_iterations (int): SA/GDRR/ALNS iteration budget, at least 1; a seeded run that ends on it rather than on the time limit is reproduced exactly
    • A setting only some strategies read (target_utilization, population_size, max_generations, max_iterations, crossover_rate, mutation_rate, seed) is refused as invalid_option under a strategy that does not read it, not ignored
    • crossover_rate / mutation_rate (float): GA crossover and mutation probabilities, in [0, 1] (default 0.85 / 0.05)
    • seed (int): RNG seed of ga, brkga, sa, gdrr, alns and hybridexact. The same problem with the same seed returns the same layout when the run ends on its own budget rather than on the clock (with time_limit_ms 0 a search runs to its own budget, max_generations / max_iterations)
    • multi_sheet (bool): Distribute overflow across multiple sheets (default: False). When True, parts that do not fit on one sheet spill onto extra sheets instead of becoming unplaced; sheets_used reports the sheet count and each placement's sheet_index selects its sheet with sheet-local coordinates.

Returns: The 2D response the C ABI and the WebAssembly binding answer, as a dictionary:

  • version (str): The response contract's version
  • success (bool): Whether solve succeeded
  • placements (list): Placement results (instance-level), each {"id", "instance", "x", "y", "rotation", "sheet_index", "flipped"} -- rotation in degrees
  • utilization (float): Placed area over the area of the sheets taken (sheets_used × the boundary's area), in every mode
  • sheets_used (int): Number of sheets used (>1 only when multi_sheet=True)
  • total_requested (int): Σ of every geometry's quantity (instance-level total). Unplaced instance count = total_requested - len(placements)
  • unplaced (list): Deduplicated IDs of items that couldn't be placed (not per-instance, so len(unplaced) under-reports the failed-instance count)
  • unplaced_reasons (list): Why each entry of unplaced is unplaced, in the same order: {"id": ..., "reason": "exceeds_boundary" | "no_room"} -- exceeds_boundary: no allowed rotation of the part fits the sheet less the margin, so more sheets will not help; no_room: it fits, the layout was full
  • unplaced_count (int): Instance-level count of unplaced instances
  • all_placed (bool): Whether every requested instance was placed -- prefer it to success, which only says the solve was not refused
  • used_bounding_box (list or None): [width, height] of the placed parts' footprint; None where there is none (multi-sheet, nothing placed, 3D, a refusal) -- never [0, 0]
  • used_utilization (float or None): Part area over used_bounding_box; None exactly where it is
  • stop_reason (str): Why the run stopped — completed (the method ran to its own end), optimal (an exact method proved it), target_reached (every part placed at target_utilization or more), iteration_limit, no_improvement (the search stalled), time_limit (time_limit_ms ran out; the layout is the best found by then) or cancelled (reachable only through the C ABI's progress callback -- a Python call takes no cancel argument, so bound a run with time_limit_ms). None on a refusal
  • elapsed_ms (int): Solve time
  • error (str | None): Readable text when the request was refused
  • code (str | None): Stable reason for that refusal (invalid_geometry, duplicate_id, parameter_out_of_range, ...)
  • details (dict | None): The values behind code (id, first, index, parameter, got, ...). A range gives each bounded side as min / max when the bound itself is accepted, or exclusive_min / exclusive_max when it is not

solve_3d(geometries, boundary, config=None) -> dict

Solve a 3D bin packing problem.

Parameters:

  • geometries: List of box definitions
    • id (str): Unique identifier
    • dimensions (list): [width, depth, height]
    • quantity (int): Number of copies
    • mass (float): Weight, at least 0 (optional)
    • orientation (str): "any", "upright" or "fixed" (optional)
  • boundary: Container definition
    • dimensions (list): [width, depth, height], each above 0
    • max_mass (float): Weight limit, above 0 (optional)
    • gravity (bool): Enable gravity constraint
    • stability (bool): Enable stability constraint
  • config: Same as solve_2d but multi_sheet, which is refused (invalid_option, config.multi_sheet: one container, no sheets), and:
    • strategy: "blf", "ep", "ga", "brkga", "sa"
    • population_size / max_generations omitted: 100 / 500 for ga, 50 / 100 for brkga

Returns: The 3D response the C ABI and the WebAssembly binding answer: the keys of solve_2d with bins_used for sheets_used, no footprint fields (used_bounding_box, used_utilization), and placements {"id", "instance", "bin_index", "x", "y", "z", "orientation"} -- orientation an axis permutation such as "xyz".

check_2d(geometries, boundary, solve_result, config=None) -> dict

Check a 2D layout against the problem it answers -- by the rules the nester places under, by code that shares no placement code with it. geometries, boundary and config are the problem, exactly as solve_2d takes them; solve_result is a successful solve_2d result for it (edited or from elsewhere, any layout of that shape can be checked).

Returns: {"version", "success", "error", "code", "details", "feasible", "violations"}. Each violation is {"code": ..., ...} with the values behind it; codes()["violations"] lists them. A layout that breaks its problem is a result (feasible False), not a refusal; a problem solve_2d refuses, or a solve_result that is itself a refusal, comes back with success False and error, code, details. Nothing is raised.

import u_nesting

problem = dict(
    geometries=[{"id": "p", "polygon": [[0, 0], [40, 0], [40, 20], [0, 20]], "quantity": 3}],
    boundary={"width": 100, "height": 100},
)
solved = u_nesting.solve_2d(**problem)
assert u_nesting.check_2d(solve_result=solved, **problem)["feasible"]

# Put two pieces on one spot: the check names the rule.
solved["placements"][1].update(x=solved["placements"][0]["x"], y=solved["placements"][0]["y"])
answer = u_nesting.check_2d(solve_result=solved, **problem)
assert not answer["feasible"] and answer["violations"]

optimize_cutting_path(geometries, solve_result, cutting_config=None) -> dict

Optimize the cutting path of a 2D layout for a laser, plasma or knife cutter: the order of the contours (holes before the parts around them), where each is pierced, and the rapid travel between them. geometries are the problem's geometries as solve_2d takes them; solve_result is a successful solve_2d result for it.

cutting_config (optional): kerf_width, pierce_weight, max_2opt_iterations, time_limit_ms (the budget of the improvement phase, default 5000, 0 = unlimited), rapid_speed, cut_speed (units/s, for the time estimate), exterior_direction / interior_direction ("ccw", "cw" or "auto"), home_position ([x, y]), pierce_candidates, tolerance.

Returns: {"version", "success", "error", "code", "details", "sequence", "total_cut_distance", "total_rapid_distance", "total_pierces", "estimated_time_seconds", "efficiency", "computation_time_ms", "skipped_contours"} -- the response the C ABI and the WebAssembly binding answer. skipped_contours lists the contours of placed parts the plan cannot cut and why. Every refusal comes back with success False; nothing is raised.

import u_nesting

geometries = [{"id": "p", "polygon": [[0, 0], [40, 0], [40, 20], [0, 20]], "quantity": 3}]
# A kerf is cut out of the gap between parts: nest with a spacing at least as wide.
solved = u_nesting.solve_2d(geometries, {"width": 100, "height": 100}, {"spacing": 1.0})
cut = u_nesting.optimize_cutting_path(geometries, solved, {"kerf_width": 0.2})
assert cut["success"], cut["error"]
print(len(cut["sequence"]), cut["total_pierces"], cut["estimated_time_seconds"])

check_3d(geometries, boundary, solve_result, config=None) -> dict

Check a 3D packing against the problem it answers, as check_2d does: every box inside the container and its margin, no overlap or spacing breach, allowed orientations, one container, copy counts, max_mass, and support under gravity / stability. solve_result is a successful solve_3d result.

available_strategies() -> dict

The strategies each dimension offers and the settings each reads: {"2d": [{"name": "blf", "reads": ["spacing", ...]}, ...], "3d": [...]}. A setting the chosen strategy does not read is refused (invalid_option), not ignored; this is the table that refusal is made from, so a caller can offer only the settings that change the run:

import u_nesting

catalog = u_nesting.available_strategies()
reads = {s["name"]: set(s["reads"]) for s in catalog["2d"]}
assert "target_utilization" in reads["ga"]
assert "target_utilization" not in reads["nfp"]

codes() -> dict

Every refusal code the functions answer with (with the details fields that can come with it) and every violation code the checkers report: {"refusals": [{"code", "fields"}], "violations": [{"code", "fields", "checkers"}]}. It is read off the engine's own refusal and violation types, so a caller that translates codes can check its list against the package's:

import u_nesting

known = {r["code"] for r in u_nesting.codes()["refusals"]}
assert "parameter_out_of_range" in known

Strategy Selection Guide

Strategy Speed Quality Best For
blf Fast Good Large instances, quick results
nfp Medium Better 2D with complex shapes
ep Fast Good 3D bin packing
ga Slow Best Small instances, max quality
brkga Slow Best Complex constraints
sa Medium Better Balanced speed/quality
gdrr Medium Better 2D, ruin-and-recreate on dense layouts
alns Medium Better 2D, adaptive neighborhood search

Requirements

  • Python 3.9+
  • No additional dependencies

License

MIT License - see LICENSE for details.

Metadata

Release files for u-nesting 0.30.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distributions (wheels)

Table of built distributions (wheels) for u-nesting 0.30.0
File Actions
u_nesting-0.30.0-cp39-abi3-win_amd64.whl CPython 3.9 abi3 Windows x86-64 Details for u_nesting-0.30.0-cp39-abi3-win_amd64.whl
u_nesting-0.30.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl CPython 3.9 abi3 Linux glibc 2.17+ x86-64 Details for u_nesting-0.30.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
u_nesting-0.30.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl CPython 3.9 abi3 Linux glibc 2.17+ ARM64 Details for u_nesting-0.30.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
u_nesting-0.30.0-cp39-abi3-macosx_11_0_arm64.whl CPython 3.9 abi3 macOS 11.0+ ARM64 Details for u_nesting-0.30.0-cp39-abi3-macosx_11_0_arm64.whl
u_nesting-0.30.0-cp39-abi3-macosx_10_12_x86_64.whl CPython 3.9 abi3 macOS 10.12+ x86-64 Details for u_nesting-0.30.0-cp39-abi3-macosx_10_12_x86_64.whl

Total release size: 5.4 MB

Release files / u_nesting-0.30.0-cp39-abi3-win_amd64.whl

Download URL u_nesting-0.30.0-cp39-abi3-win_amd64.whl
Size 1.1 MB
Tags CPython 3.9 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
80755f46311d8ccc88f97d56195e72bd63d48072672b8ef961329f7a4a873d51
BLAKE2b-256 checksum
How to use checksums
636e6cd848641f58bdfc204731964525245a6bf0b8481a0a623c1464e8f3b5f1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Release files / u_nesting-0.30.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl

Download URL u_nesting-0.30.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 1.1 MB
Tags CPython 3.9 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
3d03fe202ef72c982aee147cdaf9a66ee09765f28e649d31b958f5979efbab72
BLAKE2b-256 checksum
How to use checksums
78b8cf9a85fdc2f3dc6ecf4e3012148e44405c383cd2e162da8d01a97cb51976
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Release files / u_nesting-0.30.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl

Download URL u_nesting-0.30.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
Size 1.0 MB
Tags CPython 3.9 Linux glibc 2.17+ ARM64 abi3
SHA-256 checksum
How to use checksums
cefea1ff3394e91ae13e475663ca2965cfeb17c68817b35d7ab383a103f65f84
BLAKE2b-256 checksum
How to use checksums
b3b8d7741463f89ba36f6757ac348c4c03abf17c6c5ff65a5e26eaed76c71902
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Release files / u_nesting-0.30.0-cp39-abi3-macosx_11_0_arm64.whl

Download URL u_nesting-0.30.0-cp39-abi3-macosx_11_0_arm64.whl
Size 1.0 MB
Tags CPython 3.9 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
5eb8b3bf4694de802140e511e4afddb43f78eeda6935bb7cc535ff8e3b995fef
BLAKE2b-256 checksum
How to use checksums
e65bb06b3a19b80115b07474b52533e26d616a71f4946d2de2ffd4860e3275ab
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Release files / u_nesting-0.30.0-cp39-abi3-macosx_10_12_x86_64.whl

Download URL u_nesting-0.30.0-cp39-abi3-macosx_10_12_x86_64.whl
Size 1.1 MB
Tags CPython 3.9 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
637851a5bfae6caff6a49a913289ac26414753b18436c1b7dfe5d08822f45f5d
BLAKE2b-256 checksum
How to use checksums
02ee57846c82cfe7d765f7901dbfcbe6d819c8776229acab8800ee4333669e19
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

Security for u-nesting 0.30.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 5 files in this release have been uploaded with provenance metadata.

Select from 5 files

Attestation for u_nesting-0.30.0-cp39-abi3-win_amd64.whl

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 13, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.30.0 This release

5 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page